videojs-http-streaming-sync-workers.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160
  1. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('video.js'), require('@xmldom/xmldom')) :
  4. typeof define === 'function' && define.amd ? define(['exports', 'video.js', '@xmldom/xmldom'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.httpStreaming = {}, global.videojs, global.window));
  6. })(this, (function (exports, videojs, xmldom) { 'use strict';
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
  9. var urlToolkit = {exports: {}};
  10. (function (module, exports) {
  11. // see https://tools.ietf.org/html/rfc1808
  12. (function (root) {
  13. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
  14. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
  15. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  16. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  17. var URLToolkit = {
  18. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  19. // E.g
  20. // With opts.alwaysNormalize = false (default, spec compliant)
  21. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  22. // With opts.alwaysNormalize = true (not spec compliant)
  23. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  24. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  25. opts = opts || {}; // remove any remaining space and CRLF
  26. baseURL = baseURL.trim();
  27. relativeURL = relativeURL.trim();
  28. if (!relativeURL) {
  29. // 2a) If the embedded URL is entirely empty, it inherits the
  30. // entire base URL (i.e., is set equal to the base URL)
  31. // and we are done.
  32. if (!opts.alwaysNormalize) {
  33. return baseURL;
  34. }
  35. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  36. if (!basePartsForNormalise) {
  37. throw new Error('Error trying to parse base URL.');
  38. }
  39. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  40. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  41. }
  42. var relativeParts = URLToolkit.parseURL(relativeURL);
  43. if (!relativeParts) {
  44. throw new Error('Error trying to parse relative URL.');
  45. }
  46. if (relativeParts.scheme) {
  47. // 2b) If the embedded URL starts with a scheme name, it is
  48. // interpreted as an absolute URL and we are done.
  49. if (!opts.alwaysNormalize) {
  50. return relativeURL;
  51. }
  52. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  53. return URLToolkit.buildURLFromParts(relativeParts);
  54. }
  55. var baseParts = URLToolkit.parseURL(baseURL);
  56. if (!baseParts) {
  57. throw new Error('Error trying to parse base URL.');
  58. }
  59. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  60. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  61. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  62. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  63. baseParts.netLoc = pathParts[1];
  64. baseParts.path = pathParts[2];
  65. }
  66. if (baseParts.netLoc && !baseParts.path) {
  67. baseParts.path = '/';
  68. }
  69. var builtParts = {
  70. // 2c) Otherwise, the embedded URL inherits the scheme of
  71. // the base URL.
  72. scheme: baseParts.scheme,
  73. netLoc: relativeParts.netLoc,
  74. path: null,
  75. params: relativeParts.params,
  76. query: relativeParts.query,
  77. fragment: relativeParts.fragment
  78. };
  79. if (!relativeParts.netLoc) {
  80. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  81. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  82. // (if any) of the base URL.
  83. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
  84. // path is not relative and we skip to Step 7.
  85. if (relativeParts.path[0] !== '/') {
  86. if (!relativeParts.path) {
  87. // 5) If the embedded URL path is empty (and not preceded by a
  88. // slash), then the embedded URL inherits the base URL path
  89. builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to
  90. // step 7; otherwise, it inherits the <params> of the base
  91. // URL (if any) and
  92. if (!relativeParts.params) {
  93. builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to
  94. // step 7; otherwise, it inherits the <query> of the base
  95. // URL (if any) and we skip to step 7.
  96. if (!relativeParts.query) {
  97. builtParts.query = baseParts.query;
  98. }
  99. }
  100. } else {
  101. // 6) The last segment of the base URL's path (anything
  102. // following the rightmost slash "/", or the entire path if no
  103. // slash is present) is removed and the embedded URL's path is
  104. // appended in its place.
  105. var baseURLPath = baseParts.path;
  106. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  107. builtParts.path = URLToolkit.normalizePath(newPath);
  108. }
  109. }
  110. }
  111. if (builtParts.path === null) {
  112. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  113. }
  114. return URLToolkit.buildURLFromParts(builtParts);
  115. },
  116. parseURL: function (url) {
  117. var parts = URL_REGEX.exec(url);
  118. if (!parts) {
  119. return null;
  120. }
  121. return {
  122. scheme: parts[1] || '',
  123. netLoc: parts[2] || '',
  124. path: parts[3] || '',
  125. params: parts[4] || '',
  126. query: parts[5] || '',
  127. fragment: parts[6] || ''
  128. };
  129. },
  130. normalizePath: function (path) {
  131. // The following operations are
  132. // then applied, in order, to the new path:
  133. // 6a) All occurrences of "./", where "." is a complete path
  134. // segment, are removed.
  135. // 6b) If the path ends with "." as a complete path segment,
  136. // that "." is removed.
  137. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a
  138. // complete path segment not equal to "..", are removed.
  139. // Removal of these path segments is performed iteratively,
  140. // removing the leftmost matching pattern on each iteration,
  141. // until no matching pattern remains.
  142. // 6d) If the path ends with "<segment>/..", where <segment> is a
  143. // complete path segment not equal to "..", that
  144. // "<segment>/.." is removed.
  145. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  146. return path.split('').reverse().join('');
  147. },
  148. buildURLFromParts: function (parts) {
  149. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  150. }
  151. };
  152. module.exports = URLToolkit;
  153. })();
  154. })(urlToolkit);
  155. var URLToolkit = urlToolkit.exports;
  156. var DEFAULT_LOCATION = 'http://example.com';
  157. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  158. // return early if we don't need to resolve
  159. if (/^[a-z]+:/i.test(relativeUrl)) {
  160. return relativeUrl;
  161. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  162. if (/^data:/.test(baseUrl)) {
  163. baseUrl = window.location && window.location.href || '';
  164. } // IE11 supports URL but not the URL constructor
  165. // feature detect the behavior we want
  166. var nativeURL = typeof window.URL === 'function';
  167. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  168. // and if baseUrl isn't an absolute url
  169. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  170. if (nativeURL) {
  171. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  172. } else if (!/\/\//i.test(baseUrl)) {
  173. baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  174. }
  175. if (nativeURL) {
  176. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  177. // and if we're location-less, remove the location
  178. // otherwise, return the url unmodified
  179. if (removeLocation) {
  180. return newUrl.href.slice(DEFAULT_LOCATION.length);
  181. } else if (protocolLess) {
  182. return newUrl.href.slice(newUrl.protocol.length);
  183. }
  184. return newUrl.href;
  185. }
  186. return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  187. };
  188. /**
  189. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  190. */
  191. const resolveUrl = resolveUrl$1;
  192. /**
  193. * If the xhr request was redirected, return the responseURL, otherwise,
  194. * return the original url.
  195. *
  196. * @api private
  197. *
  198. * @param {string} url - an url being requested
  199. * @param {XMLHttpRequest} req - xhr request result
  200. *
  201. * @return {string}
  202. */
  203. const resolveManifestRedirect = (url, req) => {
  204. // To understand how the responseURL below is set and generated:
  205. // - https://fetch.spec.whatwg.org/#concept-response-url
  206. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  207. if (req && req.responseURL && url !== req.responseURL) {
  208. return req.responseURL;
  209. }
  210. return url;
  211. };
  212. const logger = source => {
  213. if (videojs__default["default"].log.debug) {
  214. return videojs__default["default"].log.debug.bind(videojs__default["default"], 'VHS:', `${source} >`);
  215. }
  216. return function () {};
  217. };
  218. function _extends() {
  219. _extends = Object.assign || function (target) {
  220. for (var i = 1; i < arguments.length; i++) {
  221. var source = arguments[i];
  222. for (var key in source) {
  223. if (Object.prototype.hasOwnProperty.call(source, key)) {
  224. target[key] = source[key];
  225. }
  226. }
  227. }
  228. return target;
  229. };
  230. return _extends.apply(this, arguments);
  231. }
  232. /**
  233. * @file stream.js
  234. */
  235. /**
  236. * A lightweight readable stream implemention that handles event dispatching.
  237. *
  238. * @class Stream
  239. */
  240. var Stream = /*#__PURE__*/function () {
  241. function Stream() {
  242. this.listeners = {};
  243. }
  244. /**
  245. * Add a listener for a specified event type.
  246. *
  247. * @param {string} type the event name
  248. * @param {Function} listener the callback to be invoked when an event of
  249. * the specified type occurs
  250. */
  251. var _proto = Stream.prototype;
  252. _proto.on = function on(type, listener) {
  253. if (!this.listeners[type]) {
  254. this.listeners[type] = [];
  255. }
  256. this.listeners[type].push(listener);
  257. }
  258. /**
  259. * Remove a listener for a specified event type.
  260. *
  261. * @param {string} type the event name
  262. * @param {Function} listener a function previously registered for this
  263. * type of event through `on`
  264. * @return {boolean} if we could turn it off or not
  265. */
  266. ;
  267. _proto.off = function off(type, listener) {
  268. if (!this.listeners[type]) {
  269. return false;
  270. }
  271. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  272. // In Video.js we slice listener functions
  273. // on trigger so that it does not mess up the order
  274. // while we loop through.
  275. //
  276. // Here we slice on off so that the loop in trigger
  277. // can continue using it's old reference to loop without
  278. // messing up the order.
  279. this.listeners[type] = this.listeners[type].slice(0);
  280. this.listeners[type].splice(index, 1);
  281. return index > -1;
  282. }
  283. /**
  284. * Trigger an event of the specified type on this stream. Any additional
  285. * arguments to this function are passed as parameters to event listeners.
  286. *
  287. * @param {string} type the event name
  288. */
  289. ;
  290. _proto.trigger = function trigger(type) {
  291. var callbacks = this.listeners[type];
  292. if (!callbacks) {
  293. return;
  294. } // Slicing the arguments on every invocation of this method
  295. // can add a significant amount of overhead. Avoid the
  296. // intermediate object creation for the common case of a
  297. // single callback argument
  298. if (arguments.length === 2) {
  299. var length = callbacks.length;
  300. for (var i = 0; i < length; ++i) {
  301. callbacks[i].call(this, arguments[1]);
  302. }
  303. } else {
  304. var args = Array.prototype.slice.call(arguments, 1);
  305. var _length = callbacks.length;
  306. for (var _i = 0; _i < _length; ++_i) {
  307. callbacks[_i].apply(this, args);
  308. }
  309. }
  310. }
  311. /**
  312. * Destroys the stream and cleans up.
  313. */
  314. ;
  315. _proto.dispose = function dispose() {
  316. this.listeners = {};
  317. }
  318. /**
  319. * Forwards all `data` events on this stream to the destination stream. The
  320. * destination stream should provide a method `push` to receive the data
  321. * events as they arrive.
  322. *
  323. * @param {Stream} destination the stream that will receive all `data` events
  324. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  325. */
  326. ;
  327. _proto.pipe = function pipe(destination) {
  328. this.on('data', function (data) {
  329. destination.push(data);
  330. });
  331. };
  332. return Stream;
  333. }();
  334. var atob = function atob(s) {
  335. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  336. };
  337. function decodeB64ToUint8Array(b64Text) {
  338. var decodedString = atob(b64Text);
  339. var array = new Uint8Array(decodedString.length);
  340. for (var i = 0; i < decodedString.length; i++) {
  341. array[i] = decodedString.charCodeAt(i);
  342. }
  343. return array;
  344. }
  345. /*! @name m3u8-parser @version 6.0.0 @license Apache-2.0 */
  346. /**
  347. * @file m3u8/line-stream.js
  348. */
  349. /**
  350. * A stream that buffers string input and generates a `data` event for each
  351. * line.
  352. *
  353. * @class LineStream
  354. * @extends Stream
  355. */
  356. class LineStream extends Stream {
  357. constructor() {
  358. super();
  359. this.buffer = '';
  360. }
  361. /**
  362. * Add new data to be parsed.
  363. *
  364. * @param {string} data the text to process
  365. */
  366. push(data) {
  367. let nextNewline;
  368. this.buffer += data;
  369. nextNewline = this.buffer.indexOf('\n');
  370. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  371. this.trigger('data', this.buffer.substring(0, nextNewline));
  372. this.buffer = this.buffer.substring(nextNewline + 1);
  373. }
  374. }
  375. }
  376. const TAB = String.fromCharCode(0x09);
  377. const parseByterange = function (byterangeString) {
  378. // optionally match and capture 0+ digits before `@`
  379. // optionally match and capture 0+ digits after `@`
  380. const match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  381. const result = {};
  382. if (match[1]) {
  383. result.length = parseInt(match[1], 10);
  384. }
  385. if (match[2]) {
  386. result.offset = parseInt(match[2], 10);
  387. }
  388. return result;
  389. };
  390. /**
  391. * "forgiving" attribute list psuedo-grammar:
  392. * attributes -> keyvalue (',' keyvalue)*
  393. * keyvalue -> key '=' value
  394. * key -> [^=]*
  395. * value -> '"' [^"]* '"' | [^,]*
  396. */
  397. const attributeSeparator = function () {
  398. const key = '[^=]*';
  399. const value = '"[^"]*"|[^,]*';
  400. const keyvalue = '(?:' + key + ')=(?:' + value + ')';
  401. return new RegExp('(?:^|,)(' + keyvalue + ')');
  402. };
  403. /**
  404. * Parse attributes from a line given the separator
  405. *
  406. * @param {string} attributes the attribute line to parse
  407. */
  408. const parseAttributes$1 = function (attributes) {
  409. const result = {};
  410. if (!attributes) {
  411. return result;
  412. } // split the string using attributes as the separator
  413. const attrs = attributes.split(attributeSeparator());
  414. let i = attrs.length;
  415. let attr;
  416. while (i--) {
  417. // filter out unmatched portions of the string
  418. if (attrs[i] === '') {
  419. continue;
  420. } // split the key and value
  421. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  422. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  423. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  424. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  425. result[attr[0]] = attr[1];
  426. }
  427. return result;
  428. };
  429. /**
  430. * A line-level M3U8 parser event stream. It expects to receive input one
  431. * line at a time and performs a context-free parse of its contents. A stream
  432. * interpretation of a manifest can be useful if the manifest is expected to
  433. * be too large to fit comfortably into memory or the entirety of the input
  434. * is not immediately available. Otherwise, it's probably much easier to work
  435. * with a regular `Parser` object.
  436. *
  437. * Produces `data` events with an object that captures the parser's
  438. * interpretation of the input. That object has a property `tag` that is one
  439. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  440. * property, `line`, which captures the entirety of the input without
  441. * interpretation. Comments similarly have a single additional property
  442. * `text` which is the input without the leading `#`.
  443. *
  444. * Tags always have a property `tagType` which is the lower-cased version of
  445. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  446. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  447. * tags are given the tag type `unknown` and a single additional property
  448. * `data` with the remainder of the input.
  449. *
  450. * @class ParseStream
  451. * @extends Stream
  452. */
  453. class ParseStream extends Stream {
  454. constructor() {
  455. super();
  456. this.customParsers = [];
  457. this.tagMappers = [];
  458. }
  459. /**
  460. * Parses an additional line of input.
  461. *
  462. * @param {string} line a single line of an M3U8 file to parse
  463. */
  464. push(line) {
  465. let match;
  466. let event; // strip whitespace
  467. line = line.trim();
  468. if (line.length === 0) {
  469. // ignore empty lines
  470. return;
  471. } // URIs
  472. if (line[0] !== '#') {
  473. this.trigger('data', {
  474. type: 'uri',
  475. uri: line
  476. });
  477. return;
  478. } // map tags
  479. const newLines = this.tagMappers.reduce((acc, mapper) => {
  480. const mappedLine = mapper(line); // skip if unchanged
  481. if (mappedLine === line) {
  482. return acc;
  483. }
  484. return acc.concat([mappedLine]);
  485. }, [line]);
  486. newLines.forEach(newLine => {
  487. for (let i = 0; i < this.customParsers.length; i++) {
  488. if (this.customParsers[i].call(this, newLine)) {
  489. return;
  490. }
  491. } // Comments
  492. if (newLine.indexOf('#EXT') !== 0) {
  493. this.trigger('data', {
  494. type: 'comment',
  495. text: newLine.slice(1)
  496. });
  497. return;
  498. } // strip off any carriage returns here so the regex matching
  499. // doesn't have to account for them.
  500. newLine = newLine.replace('\r', ''); // Tags
  501. match = /^#EXTM3U/.exec(newLine);
  502. if (match) {
  503. this.trigger('data', {
  504. type: 'tag',
  505. tagType: 'm3u'
  506. });
  507. return;
  508. }
  509. match = /^#EXTINF:([0-9\.]*)?,?(.*)?$/.exec(newLine);
  510. if (match) {
  511. event = {
  512. type: 'tag',
  513. tagType: 'inf'
  514. };
  515. if (match[1]) {
  516. event.duration = parseFloat(match[1]);
  517. }
  518. if (match[2]) {
  519. event.title = match[2];
  520. }
  521. this.trigger('data', event);
  522. return;
  523. }
  524. match = /^#EXT-X-TARGETDURATION:([0-9.]*)?/.exec(newLine);
  525. if (match) {
  526. event = {
  527. type: 'tag',
  528. tagType: 'targetduration'
  529. };
  530. if (match[1]) {
  531. event.duration = parseInt(match[1], 10);
  532. }
  533. this.trigger('data', event);
  534. return;
  535. }
  536. match = /^#EXT-X-VERSION:([0-9.]*)?/.exec(newLine);
  537. if (match) {
  538. event = {
  539. type: 'tag',
  540. tagType: 'version'
  541. };
  542. if (match[1]) {
  543. event.version = parseInt(match[1], 10);
  544. }
  545. this.trigger('data', event);
  546. return;
  547. }
  548. match = /^#EXT-X-MEDIA-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  549. if (match) {
  550. event = {
  551. type: 'tag',
  552. tagType: 'media-sequence'
  553. };
  554. if (match[1]) {
  555. event.number = parseInt(match[1], 10);
  556. }
  557. this.trigger('data', event);
  558. return;
  559. }
  560. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:(\-?[0-9.]*)?/.exec(newLine);
  561. if (match) {
  562. event = {
  563. type: 'tag',
  564. tagType: 'discontinuity-sequence'
  565. };
  566. if (match[1]) {
  567. event.number = parseInt(match[1], 10);
  568. }
  569. this.trigger('data', event);
  570. return;
  571. }
  572. match = /^#EXT-X-PLAYLIST-TYPE:(.*)?$/.exec(newLine);
  573. if (match) {
  574. event = {
  575. type: 'tag',
  576. tagType: 'playlist-type'
  577. };
  578. if (match[1]) {
  579. event.playlistType = match[1];
  580. }
  581. this.trigger('data', event);
  582. return;
  583. }
  584. match = /^#EXT-X-BYTERANGE:(.*)?$/.exec(newLine);
  585. if (match) {
  586. event = _extends(parseByterange(match[1]), {
  587. type: 'tag',
  588. tagType: 'byterange'
  589. });
  590. this.trigger('data', event);
  591. return;
  592. }
  593. match = /^#EXT-X-ALLOW-CACHE:(YES|NO)?/.exec(newLine);
  594. if (match) {
  595. event = {
  596. type: 'tag',
  597. tagType: 'allow-cache'
  598. };
  599. if (match[1]) {
  600. event.allowed = !/NO/.test(match[1]);
  601. }
  602. this.trigger('data', event);
  603. return;
  604. }
  605. match = /^#EXT-X-MAP:(.*)$/.exec(newLine);
  606. if (match) {
  607. event = {
  608. type: 'tag',
  609. tagType: 'map'
  610. };
  611. if (match[1]) {
  612. const attributes = parseAttributes$1(match[1]);
  613. if (attributes.URI) {
  614. event.uri = attributes.URI;
  615. }
  616. if (attributes.BYTERANGE) {
  617. event.byterange = parseByterange(attributes.BYTERANGE);
  618. }
  619. }
  620. this.trigger('data', event);
  621. return;
  622. }
  623. match = /^#EXT-X-STREAM-INF:(.*)$/.exec(newLine);
  624. if (match) {
  625. event = {
  626. type: 'tag',
  627. tagType: 'stream-inf'
  628. };
  629. if (match[1]) {
  630. event.attributes = parseAttributes$1(match[1]);
  631. if (event.attributes.RESOLUTION) {
  632. const split = event.attributes.RESOLUTION.split('x');
  633. const resolution = {};
  634. if (split[0]) {
  635. resolution.width = parseInt(split[0], 10);
  636. }
  637. if (split[1]) {
  638. resolution.height = parseInt(split[1], 10);
  639. }
  640. event.attributes.RESOLUTION = resolution;
  641. }
  642. if (event.attributes.BANDWIDTH) {
  643. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  644. }
  645. if (event.attributes['FRAME-RATE']) {
  646. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  647. }
  648. if (event.attributes['PROGRAM-ID']) {
  649. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  650. }
  651. }
  652. this.trigger('data', event);
  653. return;
  654. }
  655. match = /^#EXT-X-MEDIA:(.*)$/.exec(newLine);
  656. if (match) {
  657. event = {
  658. type: 'tag',
  659. tagType: 'media'
  660. };
  661. if (match[1]) {
  662. event.attributes = parseAttributes$1(match[1]);
  663. }
  664. this.trigger('data', event);
  665. return;
  666. }
  667. match = /^#EXT-X-ENDLIST/.exec(newLine);
  668. if (match) {
  669. this.trigger('data', {
  670. type: 'tag',
  671. tagType: 'endlist'
  672. });
  673. return;
  674. }
  675. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  676. if (match) {
  677. this.trigger('data', {
  678. type: 'tag',
  679. tagType: 'discontinuity'
  680. });
  681. return;
  682. }
  683. match = /^#EXT-X-PROGRAM-DATE-TIME:(.*)$/.exec(newLine);
  684. if (match) {
  685. event = {
  686. type: 'tag',
  687. tagType: 'program-date-time'
  688. };
  689. if (match[1]) {
  690. event.dateTimeString = match[1];
  691. event.dateTimeObject = new Date(match[1]);
  692. }
  693. this.trigger('data', event);
  694. return;
  695. }
  696. match = /^#EXT-X-KEY:(.*)$/.exec(newLine);
  697. if (match) {
  698. event = {
  699. type: 'tag',
  700. tagType: 'key'
  701. };
  702. if (match[1]) {
  703. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  704. if (event.attributes.IV) {
  705. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  706. event.attributes.IV = event.attributes.IV.substring(2);
  707. }
  708. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  709. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  710. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  711. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  712. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  713. event.attributes.IV = new Uint32Array(event.attributes.IV);
  714. }
  715. }
  716. this.trigger('data', event);
  717. return;
  718. }
  719. match = /^#EXT-X-START:(.*)$/.exec(newLine);
  720. if (match) {
  721. event = {
  722. type: 'tag',
  723. tagType: 'start'
  724. };
  725. if (match[1]) {
  726. event.attributes = parseAttributes$1(match[1]);
  727. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  728. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  729. }
  730. this.trigger('data', event);
  731. return;
  732. }
  733. match = /^#EXT-X-CUE-OUT-CONT:(.*)?$/.exec(newLine);
  734. if (match) {
  735. event = {
  736. type: 'tag',
  737. tagType: 'cue-out-cont'
  738. };
  739. if (match[1]) {
  740. event.data = match[1];
  741. } else {
  742. event.data = '';
  743. }
  744. this.trigger('data', event);
  745. return;
  746. }
  747. match = /^#EXT-X-CUE-OUT:(.*)?$/.exec(newLine);
  748. if (match) {
  749. event = {
  750. type: 'tag',
  751. tagType: 'cue-out'
  752. };
  753. if (match[1]) {
  754. event.data = match[1];
  755. } else {
  756. event.data = '';
  757. }
  758. this.trigger('data', event);
  759. return;
  760. }
  761. match = /^#EXT-X-CUE-IN:(.*)?$/.exec(newLine);
  762. if (match) {
  763. event = {
  764. type: 'tag',
  765. tagType: 'cue-in'
  766. };
  767. if (match[1]) {
  768. event.data = match[1];
  769. } else {
  770. event.data = '';
  771. }
  772. this.trigger('data', event);
  773. return;
  774. }
  775. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  776. if (match && match[1]) {
  777. event = {
  778. type: 'tag',
  779. tagType: 'skip'
  780. };
  781. event.attributes = parseAttributes$1(match[1]);
  782. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  783. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  784. }
  785. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  786. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  787. }
  788. this.trigger('data', event);
  789. return;
  790. }
  791. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  792. if (match && match[1]) {
  793. event = {
  794. type: 'tag',
  795. tagType: 'part'
  796. };
  797. event.attributes = parseAttributes$1(match[1]);
  798. ['DURATION'].forEach(function (key) {
  799. if (event.attributes.hasOwnProperty(key)) {
  800. event.attributes[key] = parseFloat(event.attributes[key]);
  801. }
  802. });
  803. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  804. if (event.attributes.hasOwnProperty(key)) {
  805. event.attributes[key] = /YES/.test(event.attributes[key]);
  806. }
  807. });
  808. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  809. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  810. }
  811. this.trigger('data', event);
  812. return;
  813. }
  814. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  815. if (match && match[1]) {
  816. event = {
  817. type: 'tag',
  818. tagType: 'server-control'
  819. };
  820. event.attributes = parseAttributes$1(match[1]);
  821. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  822. if (event.attributes.hasOwnProperty(key)) {
  823. event.attributes[key] = parseFloat(event.attributes[key]);
  824. }
  825. });
  826. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  827. if (event.attributes.hasOwnProperty(key)) {
  828. event.attributes[key] = /YES/.test(event.attributes[key]);
  829. }
  830. });
  831. this.trigger('data', event);
  832. return;
  833. }
  834. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  835. if (match && match[1]) {
  836. event = {
  837. type: 'tag',
  838. tagType: 'part-inf'
  839. };
  840. event.attributes = parseAttributes$1(match[1]);
  841. ['PART-TARGET'].forEach(function (key) {
  842. if (event.attributes.hasOwnProperty(key)) {
  843. event.attributes[key] = parseFloat(event.attributes[key]);
  844. }
  845. });
  846. this.trigger('data', event);
  847. return;
  848. }
  849. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  850. if (match && match[1]) {
  851. event = {
  852. type: 'tag',
  853. tagType: 'preload-hint'
  854. };
  855. event.attributes = parseAttributes$1(match[1]);
  856. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  857. if (event.attributes.hasOwnProperty(key)) {
  858. event.attributes[key] = parseInt(event.attributes[key], 10);
  859. const subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  860. event.attributes.byterange = event.attributes.byterange || {};
  861. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  862. delete event.attributes[key];
  863. }
  864. });
  865. this.trigger('data', event);
  866. return;
  867. }
  868. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  869. if (match && match[1]) {
  870. event = {
  871. type: 'tag',
  872. tagType: 'rendition-report'
  873. };
  874. event.attributes = parseAttributes$1(match[1]);
  875. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  876. if (event.attributes.hasOwnProperty(key)) {
  877. event.attributes[key] = parseInt(event.attributes[key], 10);
  878. }
  879. });
  880. this.trigger('data', event);
  881. return;
  882. } // unknown tag type
  883. this.trigger('data', {
  884. type: 'tag',
  885. data: newLine.slice(4)
  886. });
  887. });
  888. }
  889. /**
  890. * Add a parser for custom headers
  891. *
  892. * @param {Object} options a map of options for the added parser
  893. * @param {RegExp} options.expression a regular expression to match the custom header
  894. * @param {string} options.customType the custom type to register to the output
  895. * @param {Function} [options.dataParser] function to parse the line into an object
  896. * @param {boolean} [options.segment] should tag data be attached to the segment object
  897. */
  898. addParser({
  899. expression,
  900. customType,
  901. dataParser,
  902. segment
  903. }) {
  904. if (typeof dataParser !== 'function') {
  905. dataParser = line => line;
  906. }
  907. this.customParsers.push(line => {
  908. const match = expression.exec(line);
  909. if (match) {
  910. this.trigger('data', {
  911. type: 'custom',
  912. data: dataParser(line),
  913. customType,
  914. segment
  915. });
  916. return true;
  917. }
  918. });
  919. }
  920. /**
  921. * Add a custom header mapper
  922. *
  923. * @param {Object} options
  924. * @param {RegExp} options.expression a regular expression to match the custom header
  925. * @param {Function} options.map function to translate tag into a different tag
  926. */
  927. addTagMapper({
  928. expression,
  929. map
  930. }) {
  931. const mapFn = line => {
  932. if (expression.test(line)) {
  933. return map(line);
  934. }
  935. return line;
  936. };
  937. this.tagMappers.push(mapFn);
  938. }
  939. }
  940. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  941. const camelCaseKeys = function (attributes) {
  942. const result = {};
  943. Object.keys(attributes).forEach(function (key) {
  944. result[camelCase(key)] = attributes[key];
  945. });
  946. return result;
  947. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  948. // we need this helper because defaults are based upon targetDuration and
  949. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  950. // target durations are set.
  951. const setHoldBack = function (manifest) {
  952. const {
  953. serverControl,
  954. targetDuration,
  955. partTargetDuration
  956. } = manifest;
  957. if (!serverControl) {
  958. return;
  959. }
  960. const tag = '#EXT-X-SERVER-CONTROL';
  961. const hb = 'holdBack';
  962. const phb = 'partHoldBack';
  963. const minTargetDuration = targetDuration && targetDuration * 3;
  964. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  965. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  966. serverControl[hb] = minTargetDuration;
  967. this.trigger('info', {
  968. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  969. });
  970. }
  971. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  972. this.trigger('warn', {
  973. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  974. });
  975. serverControl[hb] = minTargetDuration;
  976. } // default no part hold back to part target duration * 3
  977. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  978. serverControl[phb] = partTargetDuration * 3;
  979. this.trigger('info', {
  980. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  981. });
  982. } // if part hold back is too small default it to part target duration * 2
  983. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  984. this.trigger('warn', {
  985. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  986. });
  987. serverControl[phb] = minPartDuration;
  988. }
  989. };
  990. /**
  991. * A parser for M3U8 files. The current interpretation of the input is
  992. * exposed as a property `manifest` on parser objects. It's just two lines to
  993. * create and parse a manifest once you have the contents available as a string:
  994. *
  995. * ```js
  996. * var parser = new m3u8.Parser();
  997. * parser.push(xhr.responseText);
  998. * ```
  999. *
  1000. * New input can later be applied to update the manifest object by calling
  1001. * `push` again.
  1002. *
  1003. * The parser attempts to create a usable manifest object even if the
  1004. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  1005. * events during the parse if it encounters input that seems invalid or
  1006. * requires some property of the manifest object to be defaulted.
  1007. *
  1008. * @class Parser
  1009. * @extends Stream
  1010. */
  1011. class Parser extends Stream {
  1012. constructor() {
  1013. super();
  1014. this.lineStream = new LineStream();
  1015. this.parseStream = new ParseStream();
  1016. this.lineStream.pipe(this.parseStream);
  1017. /* eslint-disable consistent-this */
  1018. const self = this;
  1019. /* eslint-enable consistent-this */
  1020. const uris = [];
  1021. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  1022. let currentMap; // if specified, the active decryption key
  1023. let key;
  1024. let hasParts = false;
  1025. const noop = function () {};
  1026. const defaultMediaGroups = {
  1027. 'AUDIO': {},
  1028. 'VIDEO': {},
  1029. 'CLOSED-CAPTIONS': {},
  1030. 'SUBTITLES': {}
  1031. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  1032. // used in MPDs with Widevine encrypted streams.
  1033. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  1034. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  1035. this.manifest = {
  1036. allowCache: true,
  1037. discontinuityStarts: [],
  1038. segments: []
  1039. }; // keep track of the last seen segment's byte range end, as segments are not required
  1040. // to provide the offset, in which case it defaults to the next byte after the
  1041. // previous segment
  1042. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  1043. let lastPartByterangeEnd = 0;
  1044. this.on('end', () => {
  1045. // only add preloadSegment if we don't yet have a uri for it.
  1046. // and we actually have parts/preloadHints
  1047. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  1048. return;
  1049. }
  1050. if (!currentUri.map && currentMap) {
  1051. currentUri.map = currentMap;
  1052. }
  1053. if (!currentUri.key && key) {
  1054. currentUri.key = key;
  1055. }
  1056. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  1057. currentUri.timeline = currentTimeline;
  1058. }
  1059. this.manifest.preloadSegment = currentUri;
  1060. }); // update the manifest with the m3u8 entry from the parse stream
  1061. this.parseStream.on('data', function (entry) {
  1062. let mediaGroup;
  1063. let rendition;
  1064. ({
  1065. tag() {
  1066. // switch based on the tag type
  1067. (({
  1068. version() {
  1069. if (entry.version) {
  1070. this.manifest.version = entry.version;
  1071. }
  1072. },
  1073. 'allow-cache'() {
  1074. this.manifest.allowCache = entry.allowed;
  1075. if (!('allowed' in entry)) {
  1076. this.trigger('info', {
  1077. message: 'defaulting allowCache to YES'
  1078. });
  1079. this.manifest.allowCache = true;
  1080. }
  1081. },
  1082. byterange() {
  1083. const byterange = {};
  1084. if ('length' in entry) {
  1085. currentUri.byterange = byterange;
  1086. byterange.length = entry.length;
  1087. if (!('offset' in entry)) {
  1088. /*
  1089. * From the latest spec (as of this writing):
  1090. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  1091. *
  1092. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  1093. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  1094. *
  1095. * "If o [offset] is not present, the sub-range begins at the next byte
  1096. * following the sub-range of the previous media segment."
  1097. */
  1098. entry.offset = lastByterangeEnd;
  1099. }
  1100. }
  1101. if ('offset' in entry) {
  1102. currentUri.byterange = byterange;
  1103. byterange.offset = entry.offset;
  1104. }
  1105. lastByterangeEnd = byterange.offset + byterange.length;
  1106. },
  1107. endlist() {
  1108. this.manifest.endList = true;
  1109. },
  1110. inf() {
  1111. if (!('mediaSequence' in this.manifest)) {
  1112. this.manifest.mediaSequence = 0;
  1113. this.trigger('info', {
  1114. message: 'defaulting media sequence to zero'
  1115. });
  1116. }
  1117. if (!('discontinuitySequence' in this.manifest)) {
  1118. this.manifest.discontinuitySequence = 0;
  1119. this.trigger('info', {
  1120. message: 'defaulting discontinuity sequence to zero'
  1121. });
  1122. }
  1123. if (entry.duration > 0) {
  1124. currentUri.duration = entry.duration;
  1125. }
  1126. if (entry.duration === 0) {
  1127. currentUri.duration = 0.01;
  1128. this.trigger('info', {
  1129. message: 'updating zero segment duration to a small value'
  1130. });
  1131. }
  1132. this.manifest.segments = uris;
  1133. },
  1134. key() {
  1135. if (!entry.attributes) {
  1136. this.trigger('warn', {
  1137. message: 'ignoring key declaration without attribute list'
  1138. });
  1139. return;
  1140. } // clear the active encryption key
  1141. if (entry.attributes.METHOD === 'NONE') {
  1142. key = null;
  1143. return;
  1144. }
  1145. if (!entry.attributes.URI) {
  1146. this.trigger('warn', {
  1147. message: 'ignoring key declaration without URI'
  1148. });
  1149. return;
  1150. }
  1151. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  1152. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1153. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  1154. attributes: entry.attributes
  1155. };
  1156. return;
  1157. }
  1158. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  1159. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1160. this.manifest.contentProtection['com.microsoft.playready'] = {
  1161. uri: entry.attributes.URI
  1162. };
  1163. return;
  1164. } // check if the content is encrypted for Widevine
  1165. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  1166. if (entry.attributes.KEYFORMAT === widevineUuid) {
  1167. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  1168. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  1169. this.trigger('warn', {
  1170. message: 'invalid key method provided for Widevine'
  1171. });
  1172. return;
  1173. }
  1174. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  1175. this.trigger('warn', {
  1176. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  1177. });
  1178. }
  1179. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  1180. this.trigger('warn', {
  1181. message: 'invalid key URI provided for Widevine'
  1182. });
  1183. return;
  1184. }
  1185. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  1186. this.trigger('warn', {
  1187. message: 'invalid key ID provided for Widevine'
  1188. });
  1189. return;
  1190. } // if Widevine key attributes are valid, store them as `contentProtection`
  1191. // on the manifest to emulate Widevine tag structure in a DASH mpd
  1192. this.manifest.contentProtection = this.manifest.contentProtection || {};
  1193. this.manifest.contentProtection['com.widevine.alpha'] = {
  1194. attributes: {
  1195. schemeIdUri: entry.attributes.KEYFORMAT,
  1196. // remove '0x' from the key id string
  1197. keyId: entry.attributes.KEYID.substring(2)
  1198. },
  1199. // decode the base64-encoded PSSH box
  1200. pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
  1201. };
  1202. return;
  1203. }
  1204. if (!entry.attributes.METHOD) {
  1205. this.trigger('warn', {
  1206. message: 'defaulting key method to AES-128'
  1207. });
  1208. } // setup an encryption key for upcoming segments
  1209. key = {
  1210. method: entry.attributes.METHOD || 'AES-128',
  1211. uri: entry.attributes.URI
  1212. };
  1213. if (typeof entry.attributes.IV !== 'undefined') {
  1214. key.iv = entry.attributes.IV;
  1215. }
  1216. },
  1217. 'media-sequence'() {
  1218. if (!isFinite(entry.number)) {
  1219. this.trigger('warn', {
  1220. message: 'ignoring invalid media sequence: ' + entry.number
  1221. });
  1222. return;
  1223. }
  1224. this.manifest.mediaSequence = entry.number;
  1225. },
  1226. 'discontinuity-sequence'() {
  1227. if (!isFinite(entry.number)) {
  1228. this.trigger('warn', {
  1229. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  1230. });
  1231. return;
  1232. }
  1233. this.manifest.discontinuitySequence = entry.number;
  1234. currentTimeline = entry.number;
  1235. },
  1236. 'playlist-type'() {
  1237. if (!/VOD|EVENT/.test(entry.playlistType)) {
  1238. this.trigger('warn', {
  1239. message: 'ignoring unknown playlist type: ' + entry.playlist
  1240. });
  1241. return;
  1242. }
  1243. this.manifest.playlistType = entry.playlistType;
  1244. },
  1245. map() {
  1246. currentMap = {};
  1247. if (entry.uri) {
  1248. currentMap.uri = entry.uri;
  1249. }
  1250. if (entry.byterange) {
  1251. currentMap.byterange = entry.byterange;
  1252. }
  1253. if (key) {
  1254. currentMap.key = key;
  1255. }
  1256. },
  1257. 'stream-inf'() {
  1258. this.manifest.playlists = uris;
  1259. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1260. if (!entry.attributes) {
  1261. this.trigger('warn', {
  1262. message: 'ignoring empty stream-inf attributes'
  1263. });
  1264. return;
  1265. }
  1266. if (!currentUri.attributes) {
  1267. currentUri.attributes = {};
  1268. }
  1269. _extends(currentUri.attributes, entry.attributes);
  1270. },
  1271. media() {
  1272. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1273. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1274. this.trigger('warn', {
  1275. message: 'ignoring incomplete or missing media group'
  1276. });
  1277. return;
  1278. } // find the media group, creating defaults as necessary
  1279. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1280. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1281. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  1282. rendition = {
  1283. default: /yes/i.test(entry.attributes.DEFAULT)
  1284. };
  1285. if (rendition.default) {
  1286. rendition.autoselect = true;
  1287. } else {
  1288. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1289. }
  1290. if (entry.attributes.LANGUAGE) {
  1291. rendition.language = entry.attributes.LANGUAGE;
  1292. }
  1293. if (entry.attributes.URI) {
  1294. rendition.uri = entry.attributes.URI;
  1295. }
  1296. if (entry.attributes['INSTREAM-ID']) {
  1297. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  1298. }
  1299. if (entry.attributes.CHARACTERISTICS) {
  1300. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  1301. }
  1302. if (entry.attributes.FORCED) {
  1303. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  1304. } // insert the new rendition
  1305. mediaGroup[entry.attributes.NAME] = rendition;
  1306. },
  1307. discontinuity() {
  1308. currentTimeline += 1;
  1309. currentUri.discontinuity = true;
  1310. this.manifest.discontinuityStarts.push(uris.length);
  1311. },
  1312. 'program-date-time'() {
  1313. if (typeof this.manifest.dateTimeString === 'undefined') {
  1314. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  1315. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  1316. // to the manifest object
  1317. // TODO: Consider removing this in future major version
  1318. this.manifest.dateTimeString = entry.dateTimeString;
  1319. this.manifest.dateTimeObject = entry.dateTimeObject;
  1320. }
  1321. currentUri.dateTimeString = entry.dateTimeString;
  1322. currentUri.dateTimeObject = entry.dateTimeObject;
  1323. },
  1324. targetduration() {
  1325. if (!isFinite(entry.duration) || entry.duration < 0) {
  1326. this.trigger('warn', {
  1327. message: 'ignoring invalid target duration: ' + entry.duration
  1328. });
  1329. return;
  1330. }
  1331. this.manifest.targetDuration = entry.duration;
  1332. setHoldBack.call(this, this.manifest);
  1333. },
  1334. start() {
  1335. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  1336. this.trigger('warn', {
  1337. message: 'ignoring start declaration without appropriate attribute list'
  1338. });
  1339. return;
  1340. }
  1341. this.manifest.start = {
  1342. timeOffset: entry.attributes['TIME-OFFSET'],
  1343. precise: entry.attributes.PRECISE
  1344. };
  1345. },
  1346. 'cue-out'() {
  1347. currentUri.cueOut = entry.data;
  1348. },
  1349. 'cue-out-cont'() {
  1350. currentUri.cueOutCont = entry.data;
  1351. },
  1352. 'cue-in'() {
  1353. currentUri.cueIn = entry.data;
  1354. },
  1355. 'skip'() {
  1356. this.manifest.skip = camelCaseKeys(entry.attributes);
  1357. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  1358. },
  1359. 'part'() {
  1360. hasParts = true; // parts are always specifed before a segment
  1361. const segmentIndex = this.manifest.segments.length;
  1362. const part = camelCaseKeys(entry.attributes);
  1363. currentUri.parts = currentUri.parts || [];
  1364. currentUri.parts.push(part);
  1365. if (part.byterange) {
  1366. if (!part.byterange.hasOwnProperty('offset')) {
  1367. part.byterange.offset = lastPartByterangeEnd;
  1368. }
  1369. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  1370. }
  1371. const partIndex = currentUri.parts.length - 1;
  1372. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  1373. if (this.manifest.renditionReports) {
  1374. this.manifest.renditionReports.forEach((r, i) => {
  1375. if (!r.hasOwnProperty('lastPart')) {
  1376. this.trigger('warn', {
  1377. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  1378. });
  1379. }
  1380. });
  1381. }
  1382. },
  1383. 'server-control'() {
  1384. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  1385. if (!attrs.hasOwnProperty('canBlockReload')) {
  1386. attrs.canBlockReload = false;
  1387. this.trigger('info', {
  1388. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  1389. });
  1390. }
  1391. setHoldBack.call(this, this.manifest);
  1392. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  1393. this.trigger('warn', {
  1394. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  1395. });
  1396. }
  1397. },
  1398. 'preload-hint'() {
  1399. // parts are always specifed before a segment
  1400. const segmentIndex = this.manifest.segments.length;
  1401. const hint = camelCaseKeys(entry.attributes);
  1402. const isPart = hint.type && hint.type === 'PART';
  1403. currentUri.preloadHints = currentUri.preloadHints || [];
  1404. currentUri.preloadHints.push(hint);
  1405. if (hint.byterange) {
  1406. if (!hint.byterange.hasOwnProperty('offset')) {
  1407. // use last part byterange end or zero if not a part.
  1408. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  1409. if (isPart) {
  1410. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  1411. }
  1412. }
  1413. }
  1414. const index = currentUri.preloadHints.length - 1;
  1415. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  1416. if (!hint.type) {
  1417. return;
  1418. } // search through all preload hints except for the current one for
  1419. // a duplicate type.
  1420. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  1421. const otherHint = currentUri.preloadHints[i];
  1422. if (!otherHint.type) {
  1423. continue;
  1424. }
  1425. if (otherHint.type === hint.type) {
  1426. this.trigger('warn', {
  1427. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  1428. });
  1429. }
  1430. }
  1431. },
  1432. 'rendition-report'() {
  1433. const report = camelCaseKeys(entry.attributes);
  1434. this.manifest.renditionReports = this.manifest.renditionReports || [];
  1435. this.manifest.renditionReports.push(report);
  1436. const index = this.manifest.renditionReports.length - 1;
  1437. const required = ['LAST-MSN', 'URI'];
  1438. if (hasParts) {
  1439. required.push('LAST-PART');
  1440. }
  1441. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  1442. },
  1443. 'part-inf'() {
  1444. this.manifest.partInf = camelCaseKeys(entry.attributes);
  1445. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  1446. if (this.manifest.partInf.partTarget) {
  1447. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  1448. }
  1449. setHoldBack.call(this, this.manifest);
  1450. }
  1451. })[entry.tagType] || noop).call(self);
  1452. },
  1453. uri() {
  1454. currentUri.uri = entry.uri;
  1455. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  1456. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1457. this.trigger('warn', {
  1458. message: 'defaulting segment duration to the target duration'
  1459. });
  1460. currentUri.duration = this.manifest.targetDuration;
  1461. } // annotate with encryption information, if necessary
  1462. if (key) {
  1463. currentUri.key = key;
  1464. }
  1465. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  1466. if (currentMap) {
  1467. currentUri.map = currentMap;
  1468. } // reset the last byterange end as it needs to be 0 between parts
  1469. lastPartByterangeEnd = 0; // prepare for the next URI
  1470. currentUri = {};
  1471. },
  1472. comment() {// comments are not important for playback
  1473. },
  1474. custom() {
  1475. // if this is segment-level data attach the output to the segment
  1476. if (entry.segment) {
  1477. currentUri.custom = currentUri.custom || {};
  1478. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  1479. } else {
  1480. this.manifest.custom = this.manifest.custom || {};
  1481. this.manifest.custom[entry.customType] = entry.data;
  1482. }
  1483. }
  1484. })[entry.type].call(self);
  1485. });
  1486. }
  1487. warnOnMissingAttributes_(identifier, attributes, required) {
  1488. const missing = [];
  1489. required.forEach(function (key) {
  1490. if (!attributes.hasOwnProperty(key)) {
  1491. missing.push(key);
  1492. }
  1493. });
  1494. if (missing.length) {
  1495. this.trigger('warn', {
  1496. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  1497. });
  1498. }
  1499. }
  1500. /**
  1501. * Parse the input string and update the manifest object.
  1502. *
  1503. * @param {string} chunk a potentially incomplete portion of the manifest
  1504. */
  1505. push(chunk) {
  1506. this.lineStream.push(chunk);
  1507. }
  1508. /**
  1509. * Flush any remaining input. This can be handy if the last line of an M3U8
  1510. * manifest did not contain a trailing newline but the file has been
  1511. * completely received.
  1512. */
  1513. end() {
  1514. // flush any buffered input
  1515. this.lineStream.push('\n');
  1516. this.trigger('end');
  1517. }
  1518. /**
  1519. * Add an additional parser for non-standard tags
  1520. *
  1521. * @param {Object} options a map of options for the added parser
  1522. * @param {RegExp} options.expression a regular expression to match the custom header
  1523. * @param {string} options.type the type to register to the output
  1524. * @param {Function} [options.dataParser] function to parse the line into an object
  1525. * @param {boolean} [options.segment] should tag data be attached to the segment object
  1526. */
  1527. addParser(options) {
  1528. this.parseStream.addParser(options);
  1529. }
  1530. /**
  1531. * Add a custom header mapper
  1532. *
  1533. * @param {Object} options
  1534. * @param {RegExp} options.expression a regular expression to match the custom header
  1535. * @param {Function} options.map function to translate tag into a different tag
  1536. */
  1537. addTagMapper(options) {
  1538. this.parseStream.addTagMapper(options);
  1539. }
  1540. }
  1541. var regexs = {
  1542. // to determine mime types
  1543. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  1544. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  1545. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  1546. // to determine if a codec is audio or video
  1547. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  1548. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  1549. text: /^(stpp.ttml.im1t)/,
  1550. // mux.js support regex
  1551. muxerVideo: /^(avc0?1)/,
  1552. muxerAudio: /^(mp4a)/,
  1553. // match nothing as muxer does not support text right now.
  1554. // there cannot never be a character before the start of a string
  1555. // so this matches nothing.
  1556. muxerText: /a^/
  1557. };
  1558. var mediaTypes = ['video', 'audio', 'text'];
  1559. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  1560. /**
  1561. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  1562. * `avc1.<hhhhhh>`
  1563. *
  1564. * @param {string} codec
  1565. * Codec string to translate
  1566. * @return {string}
  1567. * The translated codec string
  1568. */
  1569. var translateLegacyCodec = function translateLegacyCodec(codec) {
  1570. if (!codec) {
  1571. return codec;
  1572. }
  1573. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  1574. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  1575. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  1576. return 'avc1.' + profileHex + '00' + avcLevelHex;
  1577. });
  1578. };
  1579. /**
  1580. * @typedef {Object} ParsedCodecInfo
  1581. * @property {number} codecCount
  1582. * Number of codecs parsed
  1583. * @property {string} [videoCodec]
  1584. * Parsed video codec (if found)
  1585. * @property {string} [videoObjectTypeIndicator]
  1586. * Video object type indicator (if found)
  1587. * @property {string|null} audioProfile
  1588. * Audio profile
  1589. */
  1590. /**
  1591. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  1592. * object type indicator, and the audio profile.
  1593. *
  1594. * @param {string} [codecString]
  1595. * The codec string to parse
  1596. * @return {ParsedCodecInfo}
  1597. * Parsed codec info
  1598. */
  1599. var parseCodecs = function parseCodecs(codecString) {
  1600. if (codecString === void 0) {
  1601. codecString = '';
  1602. }
  1603. var codecs = codecString.split(',');
  1604. var result = [];
  1605. codecs.forEach(function (codec) {
  1606. codec = codec.trim();
  1607. var codecType;
  1608. mediaTypes.forEach(function (name) {
  1609. var match = regexs[name].exec(codec.toLowerCase());
  1610. if (!match || match.length <= 1) {
  1611. return;
  1612. }
  1613. codecType = name; // maintain codec case
  1614. var type = codec.substring(0, match[1].length);
  1615. var details = codec.replace(type, '');
  1616. result.push({
  1617. type: type,
  1618. details: details,
  1619. mediaType: name
  1620. });
  1621. });
  1622. if (!codecType) {
  1623. result.push({
  1624. type: codec,
  1625. details: '',
  1626. mediaType: 'unknown'
  1627. });
  1628. }
  1629. });
  1630. return result;
  1631. };
  1632. /**
  1633. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  1634. * a default alternate audio playlist for the provided audio group.
  1635. *
  1636. * @param {Object} master
  1637. * The master playlist
  1638. * @param {string} audioGroupId
  1639. * ID of the audio group for which to find the default codec info
  1640. * @return {ParsedCodecInfo}
  1641. * Parsed codec info
  1642. */
  1643. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  1644. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  1645. return null;
  1646. }
  1647. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  1648. if (!audioGroup) {
  1649. return null;
  1650. }
  1651. for (var name in audioGroup) {
  1652. var audioType = audioGroup[name];
  1653. if (audioType.default && audioType.playlists) {
  1654. // codec should be the same for all playlists within the audio type
  1655. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  1656. }
  1657. }
  1658. return null;
  1659. };
  1660. var isAudioCodec = function isAudioCodec(codec) {
  1661. if (codec === void 0) {
  1662. codec = '';
  1663. }
  1664. return regexs.audio.test(codec.trim().toLowerCase());
  1665. };
  1666. var isTextCodec = function isTextCodec(codec) {
  1667. if (codec === void 0) {
  1668. codec = '';
  1669. }
  1670. return regexs.text.test(codec.trim().toLowerCase());
  1671. };
  1672. var getMimeForCodec = function getMimeForCodec(codecString) {
  1673. if (!codecString || typeof codecString !== 'string') {
  1674. return;
  1675. }
  1676. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  1677. return translateLegacyCodec(c.trim());
  1678. }); // default to video type
  1679. var type = 'video'; // only change to audio type if the only codec we have is
  1680. // audio
  1681. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  1682. type = 'audio';
  1683. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  1684. // text uses application/<container> for now
  1685. type = 'application';
  1686. } // default the container to mp4
  1687. var container = 'mp4'; // every codec must be able to go into the container
  1688. // for that container to be the correct one
  1689. if (codecs.every(function (c) {
  1690. return regexs.mp4.test(c);
  1691. })) {
  1692. container = 'mp4';
  1693. } else if (codecs.every(function (c) {
  1694. return regexs.webm.test(c);
  1695. })) {
  1696. container = 'webm';
  1697. } else if (codecs.every(function (c) {
  1698. return regexs.ogg.test(c);
  1699. })) {
  1700. container = 'ogg';
  1701. }
  1702. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  1703. };
  1704. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  1705. if (codecString === void 0) {
  1706. codecString = '';
  1707. }
  1708. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  1709. };
  1710. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  1711. if (codecString === void 0) {
  1712. codecString = '';
  1713. }
  1714. return codecString.toLowerCase().split(',').every(function (codec) {
  1715. codec = codec.trim(); // any match is supported.
  1716. for (var i = 0; i < upperMediaTypes.length; i++) {
  1717. var type = upperMediaTypes[i];
  1718. if (regexs["muxer" + type].test(codec)) {
  1719. return true;
  1720. }
  1721. }
  1722. return false;
  1723. });
  1724. };
  1725. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  1726. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  1727. /**
  1728. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  1729. */
  1730. /**
  1731. * Delegates to videojs.obj.merge (Video.js 8) or
  1732. * videojs.mergeOptions (Video.js 7).
  1733. */
  1734. function merge$1(...args) {
  1735. const context = videojs__default["default"].obj || videojs__default["default"];
  1736. const fn = context.merge || context.mergeOptions;
  1737. return fn.apply(context, args);
  1738. }
  1739. /**
  1740. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  1741. * videojs.createTimeRanges (Video.js 7).
  1742. */
  1743. function createTimeRanges(...args) {
  1744. const context = videojs__default["default"].time || videojs__default["default"];
  1745. const fn = context.createTimeRanges || context.createTimeRanges;
  1746. return fn.apply(context, args);
  1747. }
  1748. /**
  1749. * ranges
  1750. *
  1751. * Utilities for working with TimeRanges.
  1752. *
  1753. */
  1754. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  1755. // can be misleading because of precision differences or when the current media has poorly
  1756. // aligned audio and video, which can cause values to be slightly off from what you would
  1757. // expect. This value is what we consider to be safe to use in such comparisons to account
  1758. // for these scenarios.
  1759. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  1760. const filterRanges = function (timeRanges, predicate) {
  1761. const results = [];
  1762. let i;
  1763. if (timeRanges && timeRanges.length) {
  1764. // Search for ranges that match the predicate
  1765. for (i = 0; i < timeRanges.length; i++) {
  1766. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  1767. results.push([timeRanges.start(i), timeRanges.end(i)]);
  1768. }
  1769. }
  1770. }
  1771. return createTimeRanges(results);
  1772. };
  1773. /**
  1774. * Attempts to find the buffered TimeRange that contains the specified
  1775. * time.
  1776. *
  1777. * @param {TimeRanges} buffered - the TimeRanges object to query
  1778. * @param {number} time - the time to filter on.
  1779. * @return {TimeRanges} a new TimeRanges object
  1780. */
  1781. const findRange = function (buffered, time) {
  1782. return filterRanges(buffered, function (start, end) {
  1783. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  1784. });
  1785. };
  1786. /**
  1787. * Returns the TimeRanges that begin later than the specified time.
  1788. *
  1789. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  1790. * @param {number} time - the time to filter on.
  1791. * @return {TimeRanges} a new TimeRanges object.
  1792. */
  1793. const findNextRange = function (timeRanges, time) {
  1794. return filterRanges(timeRanges, function (start) {
  1795. return start - TIME_FUDGE_FACTOR >= time;
  1796. });
  1797. };
  1798. /**
  1799. * Returns gaps within a list of TimeRanges
  1800. *
  1801. * @param {TimeRanges} buffered - the TimeRanges object
  1802. * @return {TimeRanges} a TimeRanges object of gaps
  1803. */
  1804. const findGaps = function (buffered) {
  1805. if (buffered.length < 2) {
  1806. return createTimeRanges();
  1807. }
  1808. const ranges = [];
  1809. for (let i = 1; i < buffered.length; i++) {
  1810. const start = buffered.end(i - 1);
  1811. const end = buffered.start(i);
  1812. ranges.push([start, end]);
  1813. }
  1814. return createTimeRanges(ranges);
  1815. };
  1816. /**
  1817. * Calculate the intersection of two TimeRanges
  1818. *
  1819. * @param {TimeRanges} bufferA
  1820. * @param {TimeRanges} bufferB
  1821. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  1822. */
  1823. const bufferIntersection = function (bufferA, bufferB) {
  1824. let start = null;
  1825. let end = null;
  1826. let arity = 0;
  1827. const extents = [];
  1828. const ranges = [];
  1829. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  1830. return createTimeRanges();
  1831. } // Handle the case where we have both buffers and create an
  1832. // intersection of the two
  1833. let count = bufferA.length; // A) Gather up all start and end times
  1834. while (count--) {
  1835. extents.push({
  1836. time: bufferA.start(count),
  1837. type: 'start'
  1838. });
  1839. extents.push({
  1840. time: bufferA.end(count),
  1841. type: 'end'
  1842. });
  1843. }
  1844. count = bufferB.length;
  1845. while (count--) {
  1846. extents.push({
  1847. time: bufferB.start(count),
  1848. type: 'start'
  1849. });
  1850. extents.push({
  1851. time: bufferB.end(count),
  1852. type: 'end'
  1853. });
  1854. } // B) Sort them by time
  1855. extents.sort(function (a, b) {
  1856. return a.time - b.time;
  1857. }); // C) Go along one by one incrementing arity for start and decrementing
  1858. // arity for ends
  1859. for (count = 0; count < extents.length; count++) {
  1860. if (extents[count].type === 'start') {
  1861. arity++; // D) If arity is ever incremented to 2 we are entering an
  1862. // overlapping range
  1863. if (arity === 2) {
  1864. start = extents[count].time;
  1865. }
  1866. } else if (extents[count].type === 'end') {
  1867. arity--; // E) If arity is ever decremented to 1 we leaving an
  1868. // overlapping range
  1869. if (arity === 1) {
  1870. end = extents[count].time;
  1871. }
  1872. } // F) Record overlapping ranges
  1873. if (start !== null && end !== null) {
  1874. ranges.push([start, end]);
  1875. start = null;
  1876. end = null;
  1877. }
  1878. }
  1879. return createTimeRanges(ranges);
  1880. };
  1881. /**
  1882. * Gets a human readable string for a TimeRange
  1883. *
  1884. * @param {TimeRange} range
  1885. * @return {string} a human readable string
  1886. */
  1887. const printableRange = range => {
  1888. const strArr = [];
  1889. if (!range || !range.length) {
  1890. return '';
  1891. }
  1892. for (let i = 0; i < range.length; i++) {
  1893. strArr.push(range.start(i) + ' => ' + range.end(i));
  1894. }
  1895. return strArr.join(', ');
  1896. };
  1897. /**
  1898. * Calculates the amount of time left in seconds until the player hits the end of the
  1899. * buffer and causes a rebuffer
  1900. *
  1901. * @param {TimeRange} buffered
  1902. * The state of the buffer
  1903. * @param {Numnber} currentTime
  1904. * The current time of the player
  1905. * @param {number} playbackRate
  1906. * The current playback rate of the player. Defaults to 1.
  1907. * @return {number}
  1908. * Time until the player has to start rebuffering in seconds.
  1909. * @function timeUntilRebuffer
  1910. */
  1911. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  1912. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  1913. return (bufferedEnd - currentTime) / playbackRate;
  1914. };
  1915. /**
  1916. * Converts a TimeRanges object into an array representation
  1917. *
  1918. * @param {TimeRanges} timeRanges
  1919. * @return {Array}
  1920. */
  1921. const timeRangesToArray = timeRanges => {
  1922. const timeRangesList = [];
  1923. for (let i = 0; i < timeRanges.length; i++) {
  1924. timeRangesList.push({
  1925. start: timeRanges.start(i),
  1926. end: timeRanges.end(i)
  1927. });
  1928. }
  1929. return timeRangesList;
  1930. };
  1931. /**
  1932. * Determines if two time range objects are different.
  1933. *
  1934. * @param {TimeRange} a
  1935. * the first time range object to check
  1936. *
  1937. * @param {TimeRange} b
  1938. * the second time range object to check
  1939. *
  1940. * @return {Boolean}
  1941. * Whether the time range objects differ
  1942. */
  1943. const isRangeDifferent = function (a, b) {
  1944. // same object
  1945. if (a === b) {
  1946. return false;
  1947. } // one or the other is undefined
  1948. if (!a && b || !b && a) {
  1949. return true;
  1950. } // length is different
  1951. if (a.length !== b.length) {
  1952. return true;
  1953. } // see if any start/end pair is different
  1954. for (let i = 0; i < a.length; i++) {
  1955. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  1956. return true;
  1957. }
  1958. } // if the length and every pair is the same
  1959. // this is the same time range
  1960. return false;
  1961. };
  1962. const lastBufferedEnd = function (a) {
  1963. if (!a || !a.length || !a.end) {
  1964. return;
  1965. }
  1966. return a.end(a.length - 1);
  1967. };
  1968. /**
  1969. * A utility function to add up the amount of time in a timeRange
  1970. * after a specified startTime.
  1971. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  1972. * would return 40 as there are 40s seconds after 0 in the timeRange
  1973. *
  1974. * @param {TimeRange} range
  1975. * The range to check against
  1976. * @param {number} startTime
  1977. * The time in the time range that you should start counting from
  1978. *
  1979. * @return {number}
  1980. * The number of seconds in the buffer passed the specified time.
  1981. */
  1982. const timeAheadOf = function (range, startTime) {
  1983. let time = 0;
  1984. if (!range || !range.length) {
  1985. return time;
  1986. }
  1987. for (let i = 0; i < range.length; i++) {
  1988. const start = range.start(i);
  1989. const end = range.end(i); // startTime is after this range entirely
  1990. if (startTime > end) {
  1991. continue;
  1992. } // startTime is within this range
  1993. if (startTime > start && startTime <= end) {
  1994. time += end - startTime;
  1995. continue;
  1996. } // startTime is before this range.
  1997. time += end - start;
  1998. }
  1999. return time;
  2000. };
  2001. /**
  2002. * @file playlist.js
  2003. *
  2004. * Playlist related utilities.
  2005. */
  2006. /**
  2007. * Get the duration of a segment, with special cases for
  2008. * llhls segments that do not have a duration yet.
  2009. *
  2010. * @param {Object} playlist
  2011. * the playlist that the segment belongs to.
  2012. * @param {Object} segment
  2013. * the segment to get a duration for.
  2014. *
  2015. * @return {number}
  2016. * the segment duration
  2017. */
  2018. const segmentDurationWithParts = (playlist, segment) => {
  2019. // if this isn't a preload segment
  2020. // then we will have a segment duration that is accurate.
  2021. if (!segment.preload) {
  2022. return segment.duration;
  2023. } // otherwise we have to add up parts and preload hints
  2024. // to get an up to date duration.
  2025. let result = 0;
  2026. (segment.parts || []).forEach(function (p) {
  2027. result += p.duration;
  2028. }); // for preload hints we have to use partTargetDuration
  2029. // as they won't even have a duration yet.
  2030. (segment.preloadHints || []).forEach(function (p) {
  2031. if (p.type === 'PART') {
  2032. result += playlist.partTargetDuration;
  2033. }
  2034. });
  2035. return result;
  2036. };
  2037. /**
  2038. * A function to get a combined list of parts and segments with durations
  2039. * and indexes.
  2040. *
  2041. * @param {Playlist} playlist the playlist to get the list for.
  2042. *
  2043. * @return {Array} The part/segment list.
  2044. */
  2045. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  2046. if (segment.parts) {
  2047. segment.parts.forEach(function (part, pi) {
  2048. acc.push({
  2049. duration: part.duration,
  2050. segmentIndex: si,
  2051. partIndex: pi,
  2052. part,
  2053. segment
  2054. });
  2055. });
  2056. } else {
  2057. acc.push({
  2058. duration: segment.duration,
  2059. segmentIndex: si,
  2060. partIndex: null,
  2061. segment,
  2062. part: null
  2063. });
  2064. }
  2065. return acc;
  2066. }, []);
  2067. const getLastParts = media => {
  2068. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  2069. return lastSegment && lastSegment.parts || [];
  2070. };
  2071. const getKnownPartCount = ({
  2072. preloadSegment
  2073. }) => {
  2074. if (!preloadSegment) {
  2075. return;
  2076. }
  2077. const {
  2078. parts,
  2079. preloadHints
  2080. } = preloadSegment;
  2081. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  2082. partCount += parts && parts.length ? parts.length : 0;
  2083. return partCount;
  2084. };
  2085. /**
  2086. * Get the number of seconds to delay from the end of a
  2087. * live playlist.
  2088. *
  2089. * @param {Playlist} main the main playlist
  2090. * @param {Playlist} media the media playlist
  2091. * @return {number} the hold back in seconds.
  2092. */
  2093. const liveEdgeDelay = (main, media) => {
  2094. if (media.endList) {
  2095. return 0;
  2096. } // dash suggestedPresentationDelay trumps everything
  2097. if (main && main.suggestedPresentationDelay) {
  2098. return main.suggestedPresentationDelay;
  2099. }
  2100. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  2101. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  2102. return media.serverControl.partHoldBack;
  2103. } else if (hasParts && media.partTargetDuration) {
  2104. return media.partTargetDuration * 3; // finally look for full segment delays
  2105. } else if (media.serverControl && media.serverControl.holdBack) {
  2106. return media.serverControl.holdBack;
  2107. } else if (media.targetDuration) {
  2108. return media.targetDuration * 3;
  2109. }
  2110. return 0;
  2111. };
  2112. /**
  2113. * walk backward until we find a duration we can use
  2114. * or return a failure
  2115. *
  2116. * @param {Playlist} playlist the playlist to walk through
  2117. * @param {Number} endSequence the mediaSequence to stop walking on
  2118. */
  2119. const backwardDuration = function (playlist, endSequence) {
  2120. let result = 0;
  2121. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  2122. // the interval, use it
  2123. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  2124. // information that is earlier than endSequence
  2125. if (segment) {
  2126. if (typeof segment.start !== 'undefined') {
  2127. return {
  2128. result: segment.start,
  2129. precise: true
  2130. };
  2131. }
  2132. if (typeof segment.end !== 'undefined') {
  2133. return {
  2134. result: segment.end - segment.duration,
  2135. precise: true
  2136. };
  2137. }
  2138. }
  2139. while (i--) {
  2140. segment = playlist.segments[i];
  2141. if (typeof segment.end !== 'undefined') {
  2142. return {
  2143. result: result + segment.end,
  2144. precise: true
  2145. };
  2146. }
  2147. result += segmentDurationWithParts(playlist, segment);
  2148. if (typeof segment.start !== 'undefined') {
  2149. return {
  2150. result: result + segment.start,
  2151. precise: true
  2152. };
  2153. }
  2154. }
  2155. return {
  2156. result,
  2157. precise: false
  2158. };
  2159. };
  2160. /**
  2161. * walk forward until we find a duration we can use
  2162. * or return a failure
  2163. *
  2164. * @param {Playlist} playlist the playlist to walk through
  2165. * @param {number} endSequence the mediaSequence to stop walking on
  2166. */
  2167. const forwardDuration = function (playlist, endSequence) {
  2168. let result = 0;
  2169. let segment;
  2170. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  2171. // information
  2172. for (; i < playlist.segments.length; i++) {
  2173. segment = playlist.segments[i];
  2174. if (typeof segment.start !== 'undefined') {
  2175. return {
  2176. result: segment.start - result,
  2177. precise: true
  2178. };
  2179. }
  2180. result += segmentDurationWithParts(playlist, segment);
  2181. if (typeof segment.end !== 'undefined') {
  2182. return {
  2183. result: segment.end - result,
  2184. precise: true
  2185. };
  2186. }
  2187. } // indicate we didn't find a useful duration estimate
  2188. return {
  2189. result: -1,
  2190. precise: false
  2191. };
  2192. };
  2193. /**
  2194. * Calculate the media duration from the segments associated with a
  2195. * playlist. The duration of a subinterval of the available segments
  2196. * may be calculated by specifying an end index.
  2197. *
  2198. * @param {Object} playlist a media playlist object
  2199. * @param {number=} endSequence an exclusive upper boundary
  2200. * for the playlist. Defaults to playlist length.
  2201. * @param {number} expired the amount of time that has dropped
  2202. * off the front of the playlist in a live scenario
  2203. * @return {number} the duration between the first available segment
  2204. * and end index.
  2205. */
  2206. const intervalDuration = function (playlist, endSequence, expired) {
  2207. if (typeof endSequence === 'undefined') {
  2208. endSequence = playlist.mediaSequence + playlist.segments.length;
  2209. }
  2210. if (endSequence < playlist.mediaSequence) {
  2211. return 0;
  2212. } // do a backward walk to estimate the duration
  2213. const backward = backwardDuration(playlist, endSequence);
  2214. if (backward.precise) {
  2215. // if we were able to base our duration estimate on timing
  2216. // information provided directly from the Media Source, return
  2217. // it
  2218. return backward.result;
  2219. } // walk forward to see if a precise duration estimate can be made
  2220. // that way
  2221. const forward = forwardDuration(playlist, endSequence);
  2222. if (forward.precise) {
  2223. // we found a segment that has been buffered and so it's
  2224. // position is known precisely
  2225. return forward.result;
  2226. } // return the less-precise, playlist-based duration estimate
  2227. return backward.result + expired;
  2228. };
  2229. /**
  2230. * Calculates the duration of a playlist. If a start and end index
  2231. * are specified, the duration will be for the subset of the media
  2232. * timeline between those two indices. The total duration for live
  2233. * playlists is always Infinity.
  2234. *
  2235. * @param {Object} playlist a media playlist object
  2236. * @param {number=} endSequence an exclusive upper
  2237. * boundary for the playlist. Defaults to the playlist media
  2238. * sequence number plus its length.
  2239. * @param {number=} expired the amount of time that has
  2240. * dropped off the front of the playlist in a live scenario
  2241. * @return {number} the duration between the start index and end
  2242. * index.
  2243. */
  2244. const duration = function (playlist, endSequence, expired) {
  2245. if (!playlist) {
  2246. return 0;
  2247. }
  2248. if (typeof expired !== 'number') {
  2249. expired = 0;
  2250. } // if a slice of the total duration is not requested, use
  2251. // playlist-level duration indicators when they're present
  2252. if (typeof endSequence === 'undefined') {
  2253. // if present, use the duration specified in the playlist
  2254. if (playlist.totalDuration) {
  2255. return playlist.totalDuration;
  2256. } // duration should be Infinity for live playlists
  2257. if (!playlist.endList) {
  2258. return window.Infinity;
  2259. }
  2260. } // calculate the total duration based on the segment durations
  2261. return intervalDuration(playlist, endSequence, expired);
  2262. };
  2263. /**
  2264. * Calculate the time between two indexes in the current playlist
  2265. * neight the start- nor the end-index need to be within the current
  2266. * playlist in which case, the targetDuration of the playlist is used
  2267. * to approximate the durations of the segments
  2268. *
  2269. * @param {Array} options.durationList list to iterate over for durations.
  2270. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  2271. * @param {number} options.startIndex partsAndSegments index to start
  2272. * @param {number} options.endIndex partsAndSegments index to end.
  2273. * @return {number} the number of seconds between startIndex and endIndex
  2274. */
  2275. const sumDurations = function ({
  2276. defaultDuration,
  2277. durationList,
  2278. startIndex,
  2279. endIndex
  2280. }) {
  2281. let durations = 0;
  2282. if (startIndex > endIndex) {
  2283. [startIndex, endIndex] = [endIndex, startIndex];
  2284. }
  2285. if (startIndex < 0) {
  2286. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  2287. durations += defaultDuration;
  2288. }
  2289. startIndex = 0;
  2290. }
  2291. for (let i = startIndex; i < endIndex; i++) {
  2292. durations += durationList[i].duration;
  2293. }
  2294. return durations;
  2295. };
  2296. /**
  2297. * Calculates the playlist end time
  2298. *
  2299. * @param {Object} playlist a media playlist object
  2300. * @param {number=} expired the amount of time that has
  2301. * dropped off the front of the playlist in a live scenario
  2302. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  2303. * playlist end calculation should consider the safe live end
  2304. * (truncate the playlist end by three segments). This is normally
  2305. * used for calculating the end of the playlist's seekable range.
  2306. * This takes into account the value of liveEdgePadding.
  2307. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  2308. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  2309. * If this is provided, it is used in the safe live end calculation.
  2310. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  2311. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2312. * @return {number} the end time of playlist
  2313. * @function playlistEnd
  2314. */
  2315. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  2316. if (!playlist || !playlist.segments) {
  2317. return null;
  2318. }
  2319. if (playlist.endList) {
  2320. return duration(playlist);
  2321. }
  2322. if (expired === null) {
  2323. return null;
  2324. }
  2325. expired = expired || 0;
  2326. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  2327. if (useSafeLiveEnd) {
  2328. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  2329. lastSegmentEndTime -= liveEdgePadding;
  2330. } // don't return a time less than zero
  2331. return Math.max(0, lastSegmentEndTime);
  2332. };
  2333. /**
  2334. * Calculates the interval of time that is currently seekable in a
  2335. * playlist. The returned time ranges are relative to the earliest
  2336. * moment in the specified playlist that is still available. A full
  2337. * seekable implementation for live streams would need to offset
  2338. * these values by the duration of content that has expired from the
  2339. * stream.
  2340. *
  2341. * @param {Object} playlist a media playlist object
  2342. * dropped off the front of the playlist in a live scenario
  2343. * @param {number=} expired the amount of time that has
  2344. * dropped off the front of the playlist in a live scenario
  2345. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  2346. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2347. * @return {TimeRanges} the periods of time that are valid targets
  2348. * for seeking
  2349. */
  2350. const seekable = function (playlist, expired, liveEdgePadding) {
  2351. const useSafeLiveEnd = true;
  2352. const seekableStart = expired || 0;
  2353. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  2354. if (seekableEnd === null) {
  2355. return createTimeRanges();
  2356. }
  2357. return createTimeRanges(seekableStart, seekableEnd);
  2358. };
  2359. /**
  2360. * Determine the index and estimated starting time of the segment that
  2361. * contains a specified playback position in a media playlist.
  2362. *
  2363. * @param {Object} options.playlist the media playlist to query
  2364. * @param {number} options.currentTime The number of seconds since the earliest
  2365. * possible position to determine the containing segment for
  2366. * @param {number} options.startTime the time when the segment/part starts
  2367. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  2368. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  2369. *
  2370. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  2371. */
  2372. const getMediaInfoForTime = function ({
  2373. playlist,
  2374. currentTime,
  2375. startingSegmentIndex,
  2376. startingPartIndex,
  2377. startTime,
  2378. exactManifestTimings
  2379. }) {
  2380. let time = currentTime - startTime;
  2381. const partsAndSegments = getPartsAndSegments(playlist);
  2382. let startIndex = 0;
  2383. for (let i = 0; i < partsAndSegments.length; i++) {
  2384. const partAndSegment = partsAndSegments[i];
  2385. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  2386. continue;
  2387. } // skip this if part index does not match.
  2388. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  2389. continue;
  2390. }
  2391. startIndex = i;
  2392. break;
  2393. }
  2394. if (time < 0) {
  2395. // Walk backward from startIndex in the playlist, adding durations
  2396. // until we find a segment that contains `time` and return it
  2397. if (startIndex > 0) {
  2398. for (let i = startIndex - 1; i >= 0; i--) {
  2399. const partAndSegment = partsAndSegments[i];
  2400. time += partAndSegment.duration;
  2401. if (exactManifestTimings) {
  2402. if (time < 0) {
  2403. continue;
  2404. }
  2405. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  2406. continue;
  2407. }
  2408. return {
  2409. partIndex: partAndSegment.partIndex,
  2410. segmentIndex: partAndSegment.segmentIndex,
  2411. startTime: startTime - sumDurations({
  2412. defaultDuration: playlist.targetDuration,
  2413. durationList: partsAndSegments,
  2414. startIndex,
  2415. endIndex: i
  2416. })
  2417. };
  2418. }
  2419. } // We were unable to find a good segment within the playlist
  2420. // so select the first segment
  2421. return {
  2422. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2423. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2424. startTime: currentTime
  2425. };
  2426. } // When startIndex is negative, we first walk forward to first segment
  2427. // adding target durations. If we "run out of time" before getting to
  2428. // the first segment, return the first segment
  2429. if (startIndex < 0) {
  2430. for (let i = startIndex; i < 0; i++) {
  2431. time -= playlist.targetDuration;
  2432. if (time < 0) {
  2433. return {
  2434. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2435. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2436. startTime: currentTime
  2437. };
  2438. }
  2439. }
  2440. startIndex = 0;
  2441. } // Walk forward from startIndex in the playlist, subtracting durations
  2442. // until we find a segment that contains `time` and return it
  2443. for (let i = startIndex; i < partsAndSegments.length; i++) {
  2444. const partAndSegment = partsAndSegments[i];
  2445. time -= partAndSegment.duration;
  2446. if (exactManifestTimings) {
  2447. if (time > 0) {
  2448. continue;
  2449. }
  2450. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  2451. continue;
  2452. }
  2453. return {
  2454. partIndex: partAndSegment.partIndex,
  2455. segmentIndex: partAndSegment.segmentIndex,
  2456. startTime: startTime + sumDurations({
  2457. defaultDuration: playlist.targetDuration,
  2458. durationList: partsAndSegments,
  2459. startIndex,
  2460. endIndex: i
  2461. })
  2462. };
  2463. } // We are out of possible candidates so load the last one...
  2464. return {
  2465. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  2466. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  2467. startTime: currentTime
  2468. };
  2469. };
  2470. /**
  2471. * Check whether the playlist is excluded or not.
  2472. *
  2473. * @param {Object} playlist the media playlist object
  2474. * @return {boolean} whether the playlist is excluded or not
  2475. * @function isExcluded
  2476. */
  2477. const isExcluded = function (playlist) {
  2478. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  2479. };
  2480. /**
  2481. * Check whether the playlist is compatible with current playback configuration or has
  2482. * been excluded permanently for being incompatible.
  2483. *
  2484. * @param {Object} playlist the media playlist object
  2485. * @return {boolean} whether the playlist is incompatible or not
  2486. * @function isIncompatible
  2487. */
  2488. const isIncompatible = function (playlist) {
  2489. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  2490. };
  2491. /**
  2492. * Check whether the playlist is enabled or not.
  2493. *
  2494. * @param {Object} playlist the media playlist object
  2495. * @return {boolean} whether the playlist is enabled or not
  2496. * @function isEnabled
  2497. */
  2498. const isEnabled = function (playlist) {
  2499. const excluded = isExcluded(playlist);
  2500. return !playlist.disabled && !excluded;
  2501. };
  2502. /**
  2503. * Check whether the playlist has been manually disabled through the representations api.
  2504. *
  2505. * @param {Object} playlist the media playlist object
  2506. * @return {boolean} whether the playlist is disabled manually or not
  2507. * @function isDisabled
  2508. */
  2509. const isDisabled = function (playlist) {
  2510. return playlist.disabled;
  2511. };
  2512. /**
  2513. * Returns whether the current playlist is an AES encrypted HLS stream
  2514. *
  2515. * @return {boolean} true if it's an AES encrypted HLS stream
  2516. */
  2517. const isAes = function (media) {
  2518. for (let i = 0; i < media.segments.length; i++) {
  2519. if (media.segments[i].key) {
  2520. return true;
  2521. }
  2522. }
  2523. return false;
  2524. };
  2525. /**
  2526. * Checks if the playlist has a value for the specified attribute
  2527. *
  2528. * @param {string} attr
  2529. * Attribute to check for
  2530. * @param {Object} playlist
  2531. * The media playlist object
  2532. * @return {boolean}
  2533. * Whether the playlist contains a value for the attribute or not
  2534. * @function hasAttribute
  2535. */
  2536. const hasAttribute = function (attr, playlist) {
  2537. return playlist.attributes && playlist.attributes[attr];
  2538. };
  2539. /**
  2540. * Estimates the time required to complete a segment download from the specified playlist
  2541. *
  2542. * @param {number} segmentDuration
  2543. * Duration of requested segment
  2544. * @param {number} bandwidth
  2545. * Current measured bandwidth of the player
  2546. * @param {Object} playlist
  2547. * The media playlist object
  2548. * @param {number=} bytesReceived
  2549. * Number of bytes already received for the request. Defaults to 0
  2550. * @return {number|NaN}
  2551. * The estimated time to request the segment. NaN if bandwidth information for
  2552. * the given playlist is unavailable
  2553. * @function estimateSegmentRequestTime
  2554. */
  2555. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  2556. if (!hasAttribute('BANDWIDTH', playlist)) {
  2557. return NaN;
  2558. }
  2559. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  2560. return (size - bytesReceived * 8) / bandwidth;
  2561. };
  2562. /*
  2563. * Returns whether the current playlist is the lowest rendition
  2564. *
  2565. * @return {Boolean} true if on lowest rendition
  2566. */
  2567. const isLowestEnabledRendition = (main, media) => {
  2568. if (main.playlists.length === 1) {
  2569. return true;
  2570. }
  2571. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  2572. return main.playlists.filter(playlist => {
  2573. if (!isEnabled(playlist)) {
  2574. return false;
  2575. }
  2576. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  2577. }).length === 0;
  2578. };
  2579. const playlistMatch = (a, b) => {
  2580. // both playlits are null
  2581. // or only one playlist is non-null
  2582. // no match
  2583. if (!a && !b || !a && b || a && !b) {
  2584. return false;
  2585. } // playlist objects are the same, match
  2586. if (a === b) {
  2587. return true;
  2588. } // first try to use id as it should be the most
  2589. // accurate
  2590. if (a.id && b.id && a.id === b.id) {
  2591. return true;
  2592. } // next try to use reslovedUri as it should be the
  2593. // second most accurate.
  2594. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  2595. return true;
  2596. } // finally try to use uri as it should be accurate
  2597. // but might miss a few cases for relative uris
  2598. if (a.uri && b.uri && a.uri === b.uri) {
  2599. return true;
  2600. }
  2601. return false;
  2602. };
  2603. const someAudioVariant = function (main, callback) {
  2604. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  2605. let found = false;
  2606. for (const groupName in AUDIO) {
  2607. for (const label in AUDIO[groupName]) {
  2608. found = callback(AUDIO[groupName][label]);
  2609. if (found) {
  2610. break;
  2611. }
  2612. }
  2613. if (found) {
  2614. break;
  2615. }
  2616. }
  2617. return !!found;
  2618. };
  2619. const isAudioOnly = main => {
  2620. // we are audio only if we have no main playlists but do
  2621. // have media group playlists.
  2622. if (!main || !main.playlists || !main.playlists.length) {
  2623. // without audio variants or playlists this
  2624. // is not an audio only main.
  2625. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  2626. return found;
  2627. } // if every playlist has only an audio codec it is audio only
  2628. for (let i = 0; i < main.playlists.length; i++) {
  2629. const playlist = main.playlists[i];
  2630. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  2631. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  2632. continue;
  2633. } // playlist is in an audio group it is audio only
  2634. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  2635. if (found) {
  2636. continue;
  2637. } // if we make it here this playlist isn't audio and we
  2638. // are not audio only
  2639. return false;
  2640. } // if we make it past every playlist without returning, then
  2641. // this is an audio only playlist.
  2642. return true;
  2643. }; // exports
  2644. var Playlist = {
  2645. liveEdgeDelay,
  2646. duration,
  2647. seekable,
  2648. getMediaInfoForTime,
  2649. isEnabled,
  2650. isDisabled,
  2651. isExcluded,
  2652. isIncompatible,
  2653. playlistEnd,
  2654. isAes,
  2655. hasAttribute,
  2656. estimateSegmentRequestTime,
  2657. isLowestEnabledRendition,
  2658. isAudioOnly,
  2659. playlistMatch,
  2660. segmentDurationWithParts
  2661. };
  2662. const {
  2663. log
  2664. } = videojs__default["default"];
  2665. const createPlaylistID = (index, uri) => {
  2666. return `${index}-${uri}`;
  2667. }; // default function for creating a group id
  2668. const groupID = (type, group, label) => {
  2669. return `placeholder-uri-${type}-${group}-${label}`;
  2670. };
  2671. /**
  2672. * Parses a given m3u8 playlist
  2673. *
  2674. * @param {Function} [onwarn]
  2675. * a function to call when the parser triggers a warning event.
  2676. * @param {Function} [oninfo]
  2677. * a function to call when the parser triggers an info event.
  2678. * @param {string} manifestString
  2679. * The downloaded manifest string
  2680. * @param {Object[]} [customTagParsers]
  2681. * An array of custom tag parsers for the m3u8-parser instance
  2682. * @param {Object[]} [customTagMappers]
  2683. * An array of custom tag mappers for the m3u8-parser instance
  2684. * @param {boolean} [llhls]
  2685. * Whether to keep ll-hls features in the manifest after parsing.
  2686. * @return {Object}
  2687. * The manifest object
  2688. */
  2689. const parseManifest = ({
  2690. onwarn,
  2691. oninfo,
  2692. manifestString,
  2693. customTagParsers = [],
  2694. customTagMappers = [],
  2695. llhls
  2696. }) => {
  2697. const parser = new Parser();
  2698. if (onwarn) {
  2699. parser.on('warn', onwarn);
  2700. }
  2701. if (oninfo) {
  2702. parser.on('info', oninfo);
  2703. }
  2704. customTagParsers.forEach(customParser => parser.addParser(customParser));
  2705. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  2706. parser.push(manifestString);
  2707. parser.end();
  2708. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  2709. // if we don't want llhls support.
  2710. if (!llhls) {
  2711. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  2712. if (manifest.hasOwnProperty(k)) {
  2713. delete manifest[k];
  2714. }
  2715. });
  2716. if (manifest.segments) {
  2717. manifest.segments.forEach(function (segment) {
  2718. ['parts', 'preloadHints'].forEach(function (k) {
  2719. if (segment.hasOwnProperty(k)) {
  2720. delete segment[k];
  2721. }
  2722. });
  2723. });
  2724. }
  2725. }
  2726. if (!manifest.targetDuration) {
  2727. let targetDuration = 10;
  2728. if (manifest.segments && manifest.segments.length) {
  2729. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  2730. }
  2731. if (onwarn) {
  2732. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  2733. }
  2734. manifest.targetDuration = targetDuration;
  2735. }
  2736. const parts = getLastParts(manifest);
  2737. if (parts.length && !manifest.partTargetDuration) {
  2738. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  2739. if (onwarn) {
  2740. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  2741. 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.');
  2742. }
  2743. manifest.partTargetDuration = partTargetDuration;
  2744. }
  2745. return manifest;
  2746. };
  2747. /**
  2748. * Loops through all supported media groups in main and calls the provided
  2749. * callback for each group
  2750. *
  2751. * @param {Object} main
  2752. * The parsed main manifest object
  2753. * @param {Function} callback
  2754. * Callback to call for each media group
  2755. */
  2756. const forEachMediaGroup$1 = (main, callback) => {
  2757. if (!main.mediaGroups) {
  2758. return;
  2759. }
  2760. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  2761. if (!main.mediaGroups[mediaType]) {
  2762. return;
  2763. }
  2764. for (const groupKey in main.mediaGroups[mediaType]) {
  2765. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  2766. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  2767. callback(mediaProperties, mediaType, groupKey, labelKey);
  2768. }
  2769. }
  2770. });
  2771. };
  2772. /**
  2773. * Adds properties and attributes to the playlist to keep consistent functionality for
  2774. * playlists throughout VHS.
  2775. *
  2776. * @param {Object} config
  2777. * Arguments object
  2778. * @param {Object} config.playlist
  2779. * The media playlist
  2780. * @param {string} [config.uri]
  2781. * The uri to the media playlist (if media playlist is not from within a main
  2782. * playlist)
  2783. * @param {string} id
  2784. * ID to use for the playlist
  2785. */
  2786. const setupMediaPlaylist = ({
  2787. playlist,
  2788. uri,
  2789. id
  2790. }) => {
  2791. playlist.id = id;
  2792. playlist.playlistErrors_ = 0;
  2793. if (uri) {
  2794. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  2795. // playlists do not contain their own source URI, but one is needed for consistency in
  2796. // VHS.
  2797. playlist.uri = uri;
  2798. } // For HLS main playlists, even though certain attributes MUST be defined, the
  2799. // stream may still be played without them.
  2800. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  2801. // manifest.
  2802. //
  2803. // To avoid undefined reference errors through the project, and make the code easier
  2804. // to write/read, add an empty attributes object for these cases.
  2805. playlist.attributes = playlist.attributes || {};
  2806. };
  2807. /**
  2808. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  2809. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  2810. * playlist references to the playlists array.
  2811. *
  2812. * @param {Object} main
  2813. * The main playlist
  2814. */
  2815. const setupMediaPlaylists = main => {
  2816. let i = main.playlists.length;
  2817. while (i--) {
  2818. const playlist = main.playlists[i];
  2819. setupMediaPlaylist({
  2820. playlist,
  2821. id: createPlaylistID(i, playlist.uri)
  2822. });
  2823. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  2824. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  2825. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  2826. // the stream can be played without it. Although an attributes property may have been
  2827. // added to the playlist to prevent undefined references, issue a warning to fix the
  2828. // manifest.
  2829. if (!playlist.attributes.BANDWIDTH) {
  2830. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  2831. }
  2832. }
  2833. };
  2834. /**
  2835. * Adds resolvedUri properties to each media group.
  2836. *
  2837. * @param {Object} main
  2838. * The main playlist
  2839. */
  2840. const resolveMediaGroupUris = main => {
  2841. forEachMediaGroup$1(main, properties => {
  2842. if (properties.uri) {
  2843. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  2844. }
  2845. });
  2846. };
  2847. /**
  2848. * Creates a main playlist wrapper to insert a sole media playlist into.
  2849. *
  2850. * @param {Object} media
  2851. * Media playlist
  2852. * @param {string} uri
  2853. * The media URI
  2854. *
  2855. * @return {Object}
  2856. * main playlist
  2857. */
  2858. const mainForMedia = (media, uri) => {
  2859. const id = createPlaylistID(0, uri);
  2860. const main = {
  2861. mediaGroups: {
  2862. 'AUDIO': {},
  2863. 'VIDEO': {},
  2864. 'CLOSED-CAPTIONS': {},
  2865. 'SUBTITLES': {}
  2866. },
  2867. uri: window.location.href,
  2868. resolvedUri: window.location.href,
  2869. playlists: [{
  2870. uri,
  2871. id,
  2872. resolvedUri: uri,
  2873. // m3u8-parser does not attach an attributes property to media playlists so make
  2874. // sure that the property is attached to avoid undefined reference errors
  2875. attributes: {}
  2876. }]
  2877. }; // set up ID reference
  2878. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  2879. main.playlists[uri] = main.playlists[0];
  2880. return main;
  2881. };
  2882. /**
  2883. * Does an in-place update of the main manifest to add updated playlist URI references
  2884. * as well as other properties needed by VHS that aren't included by the parser.
  2885. *
  2886. * @param {Object} main
  2887. * main manifest object
  2888. * @param {string} uri
  2889. * The source URI
  2890. * @param {function} createGroupID
  2891. * A function to determine how to create the groupID for mediaGroups
  2892. */
  2893. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  2894. main.uri = uri;
  2895. for (let i = 0; i < main.playlists.length; i++) {
  2896. if (!main.playlists[i].uri) {
  2897. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  2898. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  2899. // TODO: consider adding dummy URIs in mpd-parser
  2900. const phonyUri = `placeholder-uri-${i}`;
  2901. main.playlists[i].uri = phonyUri;
  2902. }
  2903. }
  2904. const audioOnlyMain = isAudioOnly(main);
  2905. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  2906. // add a playlist array under properties
  2907. if (!properties.playlists || !properties.playlists.length) {
  2908. // If the manifest is audio only and this media group does not have a uri, check
  2909. // if the media group is located in the main list of playlists. If it is, don't add
  2910. // placeholder properties as it shouldn't be considered an alternate audio track.
  2911. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  2912. for (let i = 0; i < main.playlists.length; i++) {
  2913. const p = main.playlists[i];
  2914. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  2915. return;
  2916. }
  2917. }
  2918. }
  2919. properties.playlists = [_extends({}, properties)];
  2920. }
  2921. properties.playlists.forEach(function (p, i) {
  2922. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  2923. const id = createPlaylistID(i, groupId);
  2924. if (p.uri) {
  2925. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  2926. } else {
  2927. // DEPRECATED, this has been added to prevent a breaking change.
  2928. // previously we only ever had a single media group playlist, so
  2929. // we mark the first playlist uri without prepending the index as we used to
  2930. // ideally we would do all of the playlists the same way.
  2931. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  2932. // the placeholder again
  2933. p.resolvedUri = p.uri;
  2934. }
  2935. p.id = p.id || id; // add an empty attributes object, all playlists are
  2936. // expected to have this.
  2937. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  2938. main.playlists[p.id] = p;
  2939. main.playlists[p.uri] = p;
  2940. });
  2941. });
  2942. setupMediaPlaylists(main);
  2943. resolveMediaGroupUris(main);
  2944. };
  2945. /**
  2946. * @file playlist-loader.js
  2947. *
  2948. * A state machine that manages the loading, caching, and updating of
  2949. * M3U8 playlists.
  2950. *
  2951. */
  2952. const {
  2953. EventTarget: EventTarget$1
  2954. } = videojs__default["default"];
  2955. const addLLHLSQueryDirectives = (uri, media) => {
  2956. if (media.endList || !media.serverControl) {
  2957. return uri;
  2958. }
  2959. const parameters = {};
  2960. if (media.serverControl.canBlockReload) {
  2961. const {
  2962. preloadSegment
  2963. } = media; // next msn is a zero based value, length is not.
  2964. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  2965. // that we are going to request a part of that preload segment.
  2966. // the logic below is used to determine that.
  2967. if (preloadSegment) {
  2968. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  2969. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  2970. // length of parts, then we know we had part preload hints
  2971. // and we need to add the _HLS_part= query
  2972. if (nextPart > -1 && nextPart !== parts.length - 1) {
  2973. // add existing parts to our preload hints
  2974. // eslint-disable-next-line
  2975. parameters._HLS_part = nextPart;
  2976. } // this if statement makes sure that we request the msn
  2977. // of the preload segment if:
  2978. // 1. the preload segment had parts (and was not yet a full segment)
  2979. // but was added to our segments array
  2980. // 2. the preload segment had preload hints for parts that are not in
  2981. // the manifest yet.
  2982. // in all other cases we want the segment after the preload segment
  2983. // which will be given by using media.segments.length because it is 1 based
  2984. // rather than 0 based.
  2985. if (nextPart > -1 || parts.length) {
  2986. nextMSN--;
  2987. }
  2988. } // add _HLS_msn= in front of any _HLS_part query
  2989. // eslint-disable-next-line
  2990. parameters._HLS_msn = nextMSN;
  2991. }
  2992. if (media.serverControl && media.serverControl.canSkipUntil) {
  2993. // add _HLS_skip= infront of all other queries.
  2994. // eslint-disable-next-line
  2995. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  2996. }
  2997. if (Object.keys(parameters).length) {
  2998. const parsedUri = new window.URL(uri);
  2999. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  3000. if (!parameters.hasOwnProperty(name)) {
  3001. return;
  3002. }
  3003. parsedUri.searchParams.set(name, parameters[name]);
  3004. });
  3005. uri = parsedUri.toString();
  3006. }
  3007. return uri;
  3008. };
  3009. /**
  3010. * Returns a new segment object with properties and
  3011. * the parts array merged.
  3012. *
  3013. * @param {Object} a the old segment
  3014. * @param {Object} b the new segment
  3015. *
  3016. * @return {Object} the merged segment
  3017. */
  3018. const updateSegment = (a, b) => {
  3019. if (!a) {
  3020. return b;
  3021. }
  3022. const result = merge$1(a, b); // if only the old segment has preload hints
  3023. // and the new one does not, remove preload hints.
  3024. if (a.preloadHints && !b.preloadHints) {
  3025. delete result.preloadHints;
  3026. } // if only the old segment has parts
  3027. // then the parts are no longer valid
  3028. if (a.parts && !b.parts) {
  3029. delete result.parts; // if both segments have parts
  3030. // copy part propeties from the old segment
  3031. // to the new one.
  3032. } else if (a.parts && b.parts) {
  3033. for (let i = 0; i < b.parts.length; i++) {
  3034. if (a.parts && a.parts[i]) {
  3035. result.parts[i] = merge$1(a.parts[i], b.parts[i]);
  3036. }
  3037. }
  3038. } // set skipped to false for segments that have
  3039. // have had information merged from the old segment.
  3040. if (!a.skipped && b.skipped) {
  3041. result.skipped = false;
  3042. } // set preload to false for segments that have
  3043. // had information added in the new segment.
  3044. if (a.preload && !b.preload) {
  3045. result.preload = false;
  3046. }
  3047. return result;
  3048. };
  3049. /**
  3050. * Returns a new array of segments that is the result of merging
  3051. * properties from an older list of segments onto an updated
  3052. * list. No properties on the updated playlist will be ovewritten.
  3053. *
  3054. * @param {Array} original the outdated list of segments
  3055. * @param {Array} update the updated list of segments
  3056. * @param {number=} offset the index of the first update
  3057. * segment in the original segment list. For non-live playlists,
  3058. * this should always be zero and does not need to be
  3059. * specified. For live playlists, it should be the difference
  3060. * between the media sequence numbers in the original and updated
  3061. * playlists.
  3062. * @return {Array} a list of merged segment objects
  3063. */
  3064. const updateSegments = (original, update, offset) => {
  3065. const oldSegments = original.slice();
  3066. const newSegments = update.slice();
  3067. offset = offset || 0;
  3068. const result = [];
  3069. let currentMap;
  3070. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  3071. const oldSegment = oldSegments[newIndex + offset];
  3072. const newSegment = newSegments[newIndex];
  3073. if (oldSegment) {
  3074. currentMap = oldSegment.map || currentMap;
  3075. result.push(updateSegment(oldSegment, newSegment));
  3076. } else {
  3077. // carry over map to new segment if it is missing
  3078. if (currentMap && !newSegment.map) {
  3079. newSegment.map = currentMap;
  3080. }
  3081. result.push(newSegment);
  3082. }
  3083. }
  3084. return result;
  3085. };
  3086. const resolveSegmentUris = (segment, baseUri) => {
  3087. // preloadSegment will not have a uri at all
  3088. // as the segment isn't actually in the manifest yet, only parts
  3089. if (!segment.resolvedUri && segment.uri) {
  3090. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  3091. }
  3092. if (segment.key && !segment.key.resolvedUri) {
  3093. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  3094. }
  3095. if (segment.map && !segment.map.resolvedUri) {
  3096. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  3097. }
  3098. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  3099. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  3100. }
  3101. if (segment.parts && segment.parts.length) {
  3102. segment.parts.forEach(p => {
  3103. if (p.resolvedUri) {
  3104. return;
  3105. }
  3106. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3107. });
  3108. }
  3109. if (segment.preloadHints && segment.preloadHints.length) {
  3110. segment.preloadHints.forEach(p => {
  3111. if (p.resolvedUri) {
  3112. return;
  3113. }
  3114. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3115. });
  3116. }
  3117. };
  3118. const getAllSegments = function (media) {
  3119. const segments = media.segments || [];
  3120. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  3121. // a usable segment, only include a preloadSegment that has
  3122. // parts.
  3123. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  3124. // if preloadHints has a MAP that means that the
  3125. // init segment is going to change. We cannot use any of the parts
  3126. // from this preload segment.
  3127. if (preloadSegment.preloadHints) {
  3128. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  3129. if (preloadSegment.preloadHints[i].type === 'MAP') {
  3130. return segments;
  3131. }
  3132. }
  3133. } // set the duration for our preload segment to target duration.
  3134. preloadSegment.duration = media.targetDuration;
  3135. preloadSegment.preload = true;
  3136. segments.push(preloadSegment);
  3137. }
  3138. return segments;
  3139. }; // consider the playlist unchanged if the playlist object is the same or
  3140. // the number of segments is equal, the media sequence number is unchanged,
  3141. // and this playlist hasn't become the end of the playlist
  3142. 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;
  3143. /**
  3144. * Returns a new main playlist that is the result of merging an
  3145. * updated media playlist into the original version. If the
  3146. * updated media playlist does not match any of the playlist
  3147. * entries in the original main playlist, null is returned.
  3148. *
  3149. * @param {Object} main a parsed main M3U8 object
  3150. * @param {Object} media a parsed media M3U8 object
  3151. * @return {Object} a new object that represents the original
  3152. * main playlist with the updated media playlist merged in, or
  3153. * null if the merge produced no change.
  3154. */
  3155. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  3156. const result = merge$1(main, {});
  3157. const oldMedia = result.playlists[newMedia.id];
  3158. if (!oldMedia) {
  3159. return null;
  3160. }
  3161. if (unchangedCheck(oldMedia, newMedia)) {
  3162. return null;
  3163. }
  3164. newMedia.segments = getAllSegments(newMedia);
  3165. const mergedPlaylist = merge$1(oldMedia, newMedia); // always use the new media's preload segment
  3166. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  3167. delete mergedPlaylist.preloadSegment;
  3168. } // if the update could overlap existing segment information, merge the two segment lists
  3169. if (oldMedia.segments) {
  3170. if (newMedia.skip) {
  3171. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  3172. // old properties into the new segments
  3173. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  3174. newMedia.segments.unshift({
  3175. skipped: true
  3176. });
  3177. }
  3178. }
  3179. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  3180. } // resolve any segment URIs to prevent us from having to do it later
  3181. mergedPlaylist.segments.forEach(segment => {
  3182. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  3183. }); // TODO Right now in the playlists array there are two references to each playlist, one
  3184. // that is referenced by index, and one by URI. The index reference may no longer be
  3185. // necessary.
  3186. for (let i = 0; i < result.playlists.length; i++) {
  3187. if (result.playlists[i].id === newMedia.id) {
  3188. result.playlists[i] = mergedPlaylist;
  3189. }
  3190. }
  3191. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  3192. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  3193. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  3194. if (!properties.playlists) {
  3195. return;
  3196. }
  3197. for (let i = 0; i < properties.playlists.length; i++) {
  3198. if (newMedia.id === properties.playlists[i].id) {
  3199. properties.playlists[i] = mergedPlaylist;
  3200. }
  3201. }
  3202. });
  3203. return result;
  3204. };
  3205. /**
  3206. * Calculates the time to wait before refreshing a live playlist
  3207. *
  3208. * @param {Object} media
  3209. * The current media
  3210. * @param {boolean} update
  3211. * True if there were any updates from the last refresh, false otherwise
  3212. * @return {number}
  3213. * The time in ms to wait before refreshing the live playlist
  3214. */
  3215. const refreshDelay = (media, update) => {
  3216. const segments = media.segments || [];
  3217. const lastSegment = segments[segments.length - 1];
  3218. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  3219. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  3220. if (update && lastDuration) {
  3221. return lastDuration * 1000;
  3222. } // if the playlist is unchanged since the last reload or last segment duration
  3223. // cannot be determined, try again after half the target duration
  3224. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  3225. };
  3226. /**
  3227. * Load a playlist from a remote location
  3228. *
  3229. * @class PlaylistLoader
  3230. * @extends Stream
  3231. * @param {string|Object} src url or object of manifest
  3232. * @param {boolean} withCredentials the withCredentials xhr option
  3233. * @class
  3234. */
  3235. class PlaylistLoader extends EventTarget$1 {
  3236. constructor(src, vhs, options = {}) {
  3237. super();
  3238. if (!src) {
  3239. throw new Error('A non-empty playlist URL or object is required');
  3240. }
  3241. this.logger_ = logger('PlaylistLoader');
  3242. const {
  3243. withCredentials = false
  3244. } = options;
  3245. this.src = src;
  3246. this.vhs_ = vhs;
  3247. this.withCredentials = withCredentials;
  3248. const vhsOptions = vhs.options_;
  3249. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  3250. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  3251. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  3252. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  3253. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  3254. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  3255. }
  3256. handleMediaupdatetimeout_() {
  3257. if (this.state !== 'HAVE_METADATA') {
  3258. // only refresh the media playlist if no other activity is going on
  3259. return;
  3260. }
  3261. const media = this.media();
  3262. let uri = resolveUrl(this.main.uri, media.uri);
  3263. if (this.llhls) {
  3264. uri = addLLHLSQueryDirectives(uri, media);
  3265. }
  3266. this.state = 'HAVE_CURRENT_METADATA';
  3267. this.request = this.vhs_.xhr({
  3268. uri,
  3269. withCredentials: this.withCredentials
  3270. }, (error, req) => {
  3271. // disposed
  3272. if (!this.request) {
  3273. return;
  3274. }
  3275. if (error) {
  3276. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  3277. }
  3278. this.haveMetadata({
  3279. playlistString: this.request.responseText,
  3280. url: this.media().uri,
  3281. id: this.media().id
  3282. });
  3283. });
  3284. }
  3285. playlistRequestError(xhr, playlist, startingState) {
  3286. const {
  3287. uri,
  3288. id
  3289. } = playlist; // any in-flight request is now finished
  3290. this.request = null;
  3291. if (startingState) {
  3292. this.state = startingState;
  3293. }
  3294. this.error = {
  3295. playlist: this.main.playlists[id],
  3296. status: xhr.status,
  3297. message: `HLS playlist request error at URL: ${uri}.`,
  3298. responseText: xhr.responseText,
  3299. code: xhr.status >= 500 ? 4 : 2
  3300. };
  3301. this.trigger('error');
  3302. }
  3303. parseManifest_({
  3304. url,
  3305. manifestString
  3306. }) {
  3307. return parseManifest({
  3308. onwarn: ({
  3309. message
  3310. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  3311. oninfo: ({
  3312. message
  3313. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  3314. manifestString,
  3315. customTagParsers: this.customTagParsers,
  3316. customTagMappers: this.customTagMappers,
  3317. llhls: this.llhls
  3318. });
  3319. }
  3320. /**
  3321. * Update the playlist loader's state in response to a new or updated playlist.
  3322. *
  3323. * @param {string} [playlistString]
  3324. * Playlist string (if playlistObject is not provided)
  3325. * @param {Object} [playlistObject]
  3326. * Playlist object (if playlistString is not provided)
  3327. * @param {string} url
  3328. * URL of playlist
  3329. * @param {string} id
  3330. * ID to use for playlist
  3331. */
  3332. haveMetadata({
  3333. playlistString,
  3334. playlistObject,
  3335. url,
  3336. id
  3337. }) {
  3338. // any in-flight request is now finished
  3339. this.request = null;
  3340. this.state = 'HAVE_METADATA';
  3341. const playlist = playlistObject || this.parseManifest_({
  3342. url,
  3343. manifestString: playlistString
  3344. });
  3345. playlist.lastRequest = Date.now();
  3346. setupMediaPlaylist({
  3347. playlist,
  3348. uri: url,
  3349. id
  3350. }); // merge this playlist into the main manifest
  3351. const update = updateMain$1(this.main, playlist);
  3352. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  3353. this.pendingMedia_ = null;
  3354. if (update) {
  3355. this.main = update;
  3356. this.media_ = this.main.playlists[id];
  3357. } else {
  3358. this.trigger('playlistunchanged');
  3359. }
  3360. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  3361. this.trigger('loadedplaylist');
  3362. }
  3363. /**
  3364. * Abort any outstanding work and clean up.
  3365. */
  3366. dispose() {
  3367. this.trigger('dispose');
  3368. this.stopRequest();
  3369. window.clearTimeout(this.mediaUpdateTimeout);
  3370. window.clearTimeout(this.finalRenditionTimeout);
  3371. this.off();
  3372. }
  3373. stopRequest() {
  3374. if (this.request) {
  3375. const oldRequest = this.request;
  3376. this.request = null;
  3377. oldRequest.onreadystatechange = null;
  3378. oldRequest.abort();
  3379. }
  3380. }
  3381. /**
  3382. * When called without any arguments, returns the currently
  3383. * active media playlist. When called with a single argument,
  3384. * triggers the playlist loader to asynchronously switch to the
  3385. * specified media playlist. Calling this method while the
  3386. * loader is in the HAVE_NOTHING causes an error to be emitted
  3387. * but otherwise has no effect.
  3388. *
  3389. * @param {Object=} playlist the parsed media playlist
  3390. * object to switch to
  3391. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  3392. *
  3393. * @return {Playlist} the current loaded media
  3394. */
  3395. media(playlist, shouldDelay) {
  3396. // getter
  3397. if (!playlist) {
  3398. return this.media_;
  3399. } // setter
  3400. if (this.state === 'HAVE_NOTHING') {
  3401. throw new Error('Cannot switch media playlist from ' + this.state);
  3402. } // find the playlist object if the target playlist has been
  3403. // specified by URI
  3404. if (typeof playlist === 'string') {
  3405. if (!this.main.playlists[playlist]) {
  3406. throw new Error('Unknown playlist URI: ' + playlist);
  3407. }
  3408. playlist = this.main.playlists[playlist];
  3409. }
  3410. window.clearTimeout(this.finalRenditionTimeout);
  3411. if (shouldDelay) {
  3412. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  3413. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  3414. return;
  3415. }
  3416. const startingState = this.state;
  3417. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  3418. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  3419. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  3420. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  3421. playlist.endList && playlist.segments.length) {
  3422. // abort outstanding playlist requests
  3423. if (this.request) {
  3424. this.request.onreadystatechange = null;
  3425. this.request.abort();
  3426. this.request = null;
  3427. }
  3428. this.state = 'HAVE_METADATA';
  3429. this.media_ = playlist; // trigger media change if the active media has been updated
  3430. if (mediaChange) {
  3431. this.trigger('mediachanging');
  3432. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3433. // The initial playlist was a main manifest, and the first media selected was
  3434. // also provided (in the form of a resolved playlist object) as part of the
  3435. // source object (rather than just a URL). Therefore, since the media playlist
  3436. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  3437. // normal flow, and needs an explicit trigger here.
  3438. this.trigger('loadedmetadata');
  3439. } else {
  3440. this.trigger('mediachange');
  3441. }
  3442. }
  3443. return;
  3444. } // We update/set the timeout here so that live playlists
  3445. // that are not a media change will "start" the loader as expected.
  3446. // We expect that this function will start the media update timeout
  3447. // cycle again. This also prevents a playlist switch failure from
  3448. // causing us to stall during live.
  3449. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  3450. if (!mediaChange) {
  3451. return;
  3452. }
  3453. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  3454. if (this.request) {
  3455. if (playlist.resolvedUri === this.request.url) {
  3456. // requesting to switch to the same playlist multiple times
  3457. // has no effect after the first
  3458. return;
  3459. }
  3460. this.request.onreadystatechange = null;
  3461. this.request.abort();
  3462. this.request = null;
  3463. } // request the new playlist
  3464. if (this.media_) {
  3465. this.trigger('mediachanging');
  3466. }
  3467. this.pendingMedia_ = playlist;
  3468. this.request = this.vhs_.xhr({
  3469. uri: playlist.resolvedUri,
  3470. withCredentials: this.withCredentials
  3471. }, (error, req) => {
  3472. // disposed
  3473. if (!this.request) {
  3474. return;
  3475. }
  3476. playlist.lastRequest = Date.now();
  3477. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  3478. if (error) {
  3479. return this.playlistRequestError(this.request, playlist, startingState);
  3480. }
  3481. this.haveMetadata({
  3482. playlistString: req.responseText,
  3483. url: playlist.uri,
  3484. id: playlist.id
  3485. }); // fire loadedmetadata the first time a media playlist is loaded
  3486. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3487. this.trigger('loadedmetadata');
  3488. } else {
  3489. this.trigger('mediachange');
  3490. }
  3491. });
  3492. }
  3493. /**
  3494. * pause loading of the playlist
  3495. */
  3496. pause() {
  3497. if (this.mediaUpdateTimeout) {
  3498. window.clearTimeout(this.mediaUpdateTimeout);
  3499. this.mediaUpdateTimeout = null;
  3500. }
  3501. this.stopRequest();
  3502. if (this.state === 'HAVE_NOTHING') {
  3503. // If we pause the loader before any data has been retrieved, its as if we never
  3504. // started, so reset to an unstarted state.
  3505. this.started = false;
  3506. } // Need to restore state now that no activity is happening
  3507. if (this.state === 'SWITCHING_MEDIA') {
  3508. // if the loader was in the process of switching media, it should either return to
  3509. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  3510. // playlist yet. This is determined by the existence of loader.media_
  3511. if (this.media_) {
  3512. this.state = 'HAVE_METADATA';
  3513. } else {
  3514. this.state = 'HAVE_MAIN_MANIFEST';
  3515. }
  3516. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  3517. this.state = 'HAVE_METADATA';
  3518. }
  3519. }
  3520. /**
  3521. * start loading of the playlist
  3522. */
  3523. load(shouldDelay) {
  3524. if (this.mediaUpdateTimeout) {
  3525. window.clearTimeout(this.mediaUpdateTimeout);
  3526. this.mediaUpdateTimeout = null;
  3527. }
  3528. const media = this.media();
  3529. if (shouldDelay) {
  3530. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  3531. this.mediaUpdateTimeout = window.setTimeout(() => {
  3532. this.mediaUpdateTimeout = null;
  3533. this.load();
  3534. }, delay);
  3535. return;
  3536. }
  3537. if (!this.started) {
  3538. this.start();
  3539. return;
  3540. }
  3541. if (media && !media.endList) {
  3542. this.trigger('mediaupdatetimeout');
  3543. } else {
  3544. this.trigger('loadedplaylist');
  3545. }
  3546. }
  3547. updateMediaUpdateTimeout_(delay) {
  3548. if (this.mediaUpdateTimeout) {
  3549. window.clearTimeout(this.mediaUpdateTimeout);
  3550. this.mediaUpdateTimeout = null;
  3551. } // we only have use mediaupdatetimeout for live playlists.
  3552. if (!this.media() || this.media().endList) {
  3553. return;
  3554. }
  3555. this.mediaUpdateTimeout = window.setTimeout(() => {
  3556. this.mediaUpdateTimeout = null;
  3557. this.trigger('mediaupdatetimeout');
  3558. this.updateMediaUpdateTimeout_(delay);
  3559. }, delay);
  3560. }
  3561. /**
  3562. * start loading of the playlist
  3563. */
  3564. start() {
  3565. this.started = true;
  3566. if (typeof this.src === 'object') {
  3567. // in the case of an entirely constructed manifest object (meaning there's no actual
  3568. // manifest on a server), default the uri to the page's href
  3569. if (!this.src.uri) {
  3570. this.src.uri = window.location.href;
  3571. } // resolvedUri is added on internally after the initial request. Since there's no
  3572. // request for pre-resolved manifests, add on resolvedUri here.
  3573. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  3574. // request can be skipped (since the top level of the manifest, at a minimum, is
  3575. // already available as a parsed manifest object). However, if the manifest object
  3576. // represents a main playlist, some media playlists may need to be resolved before
  3577. // the starting segment list is available. Therefore, go directly to setup of the
  3578. // initial playlist, and let the normal flow continue from there.
  3579. //
  3580. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  3581. // that the first request is asynchronous.
  3582. setTimeout(() => {
  3583. this.setupInitialPlaylist(this.src);
  3584. }, 0);
  3585. return;
  3586. } // request the specified URL
  3587. this.request = this.vhs_.xhr({
  3588. uri: this.src,
  3589. withCredentials: this.withCredentials
  3590. }, (error, req) => {
  3591. // disposed
  3592. if (!this.request) {
  3593. return;
  3594. } // clear the loader's request reference
  3595. this.request = null;
  3596. if (error) {
  3597. this.error = {
  3598. status: req.status,
  3599. message: `HLS playlist request error at URL: ${this.src}.`,
  3600. responseText: req.responseText,
  3601. // MEDIA_ERR_NETWORK
  3602. code: 2
  3603. };
  3604. if (this.state === 'HAVE_NOTHING') {
  3605. this.started = false;
  3606. }
  3607. return this.trigger('error');
  3608. }
  3609. this.src = resolveManifestRedirect(this.src, req);
  3610. const manifest = this.parseManifest_({
  3611. manifestString: req.responseText,
  3612. url: this.src
  3613. });
  3614. this.setupInitialPlaylist(manifest);
  3615. });
  3616. }
  3617. srcUri() {
  3618. return typeof this.src === 'string' ? this.src : this.src.uri;
  3619. }
  3620. /**
  3621. * Given a manifest object that's either a main or media playlist, trigger the proper
  3622. * events and set the state of the playlist loader.
  3623. *
  3624. * If the manifest object represents a main playlist, `loadedplaylist` will be
  3625. * triggered to allow listeners to select a playlist. If none is selected, the loader
  3626. * will default to the first one in the playlists array.
  3627. *
  3628. * If the manifest object represents a media playlist, `loadedplaylist` will be
  3629. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  3630. *
  3631. * In the case of a media playlist, a main playlist object wrapper with one playlist
  3632. * will be created so that all logic can handle playlists in the same fashion (as an
  3633. * assumed manifest object schema).
  3634. *
  3635. * @param {Object} manifest
  3636. * The parsed manifest object
  3637. */
  3638. setupInitialPlaylist(manifest) {
  3639. this.state = 'HAVE_MAIN_MANIFEST';
  3640. if (manifest.playlists) {
  3641. this.main = manifest;
  3642. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  3643. // then resolve URIs in advance, as they are usually done after a playlist request,
  3644. // which may not happen if the playlist is resolved.
  3645. manifest.playlists.forEach(playlist => {
  3646. playlist.segments = getAllSegments(playlist);
  3647. playlist.segments.forEach(segment => {
  3648. resolveSegmentUris(segment, playlist.resolvedUri);
  3649. });
  3650. });
  3651. this.trigger('loadedplaylist');
  3652. if (!this.request) {
  3653. // no media playlist was specifically selected so start
  3654. // from the first listed one
  3655. this.media(this.main.playlists[0]);
  3656. }
  3657. return;
  3658. } // In order to support media playlists passed in as vhs-json, the case where the uri
  3659. // is not provided as part of the manifest should be considered, and an appropriate
  3660. // default used.
  3661. const uri = this.srcUri() || window.location.href;
  3662. this.main = mainForMedia(manifest, uri);
  3663. this.haveMetadata({
  3664. playlistObject: manifest,
  3665. url: uri,
  3666. id: this.main.playlists[0].id
  3667. });
  3668. this.trigger('loadedmetadata');
  3669. }
  3670. }
  3671. /**
  3672. * @file xhr.js
  3673. */
  3674. const {
  3675. xhr: videojsXHR
  3676. } = videojs__default["default"];
  3677. const callbackWrapper = function (request, error, response, callback) {
  3678. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  3679. if (!error && reqResponse) {
  3680. request.responseTime = Date.now();
  3681. request.roundTripTime = request.responseTime - request.requestTime;
  3682. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  3683. if (!request.bandwidth) {
  3684. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  3685. }
  3686. }
  3687. if (response.headers) {
  3688. request.responseHeaders = response.headers;
  3689. } // videojs.xhr now uses a specific code on the error
  3690. // object to signal that a request has timed out instead
  3691. // of setting a boolean on the request object
  3692. if (error && error.code === 'ETIMEDOUT') {
  3693. request.timedout = true;
  3694. } // videojs.xhr no longer considers status codes outside of 200 and 0
  3695. // (for file uris) to be errors, but the old XHR did, so emulate that
  3696. // behavior. Status 206 may be used in response to byterange requests.
  3697. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  3698. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  3699. }
  3700. callback(error, request);
  3701. };
  3702. const xhrFactory = function () {
  3703. const xhr = function XhrFunction(options, callback) {
  3704. // Add a default timeout
  3705. options = merge$1({
  3706. timeout: 45e3
  3707. }, options); // Allow an optional user-specified function to modify the option
  3708. // object before we construct the xhr request
  3709. const beforeRequest = XhrFunction.beforeRequest || videojs__default["default"].Vhs.xhr.beforeRequest;
  3710. if (beforeRequest && typeof beforeRequest === 'function') {
  3711. const newOptions = beforeRequest(options);
  3712. if (newOptions) {
  3713. options = newOptions;
  3714. }
  3715. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  3716. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  3717. const xhrMethod = videojs__default["default"].Vhs.xhr.original === true ? videojsXHR : videojs__default["default"].Vhs.xhr;
  3718. const request = xhrMethod(options, function (error, response) {
  3719. return callbackWrapper(request, error, response, callback);
  3720. });
  3721. const originalAbort = request.abort;
  3722. request.abort = function () {
  3723. request.aborted = true;
  3724. return originalAbort.apply(request, arguments);
  3725. };
  3726. request.uri = options.uri;
  3727. request.requestTime = Date.now();
  3728. return request;
  3729. };
  3730. xhr.original = true;
  3731. return xhr;
  3732. };
  3733. /**
  3734. * Turns segment byterange into a string suitable for use in
  3735. * HTTP Range requests
  3736. *
  3737. * @param {Object} byterange - an object with two values defining the start and end
  3738. * of a byte-range
  3739. */
  3740. const byterangeStr = function (byterange) {
  3741. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  3742. // header uses inclusive ranges
  3743. let byterangeEnd;
  3744. const byterangeStart = byterange.offset;
  3745. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  3746. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  3747. } else {
  3748. byterangeEnd = byterange.offset + byterange.length - 1;
  3749. }
  3750. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  3751. };
  3752. /**
  3753. * Defines headers for use in the xhr request for a particular segment.
  3754. *
  3755. * @param {Object} segment - a simplified copy of the segmentInfo object
  3756. * from SegmentLoader
  3757. */
  3758. const segmentXhrHeaders = function (segment) {
  3759. const headers = {};
  3760. if (segment.byterange) {
  3761. headers.Range = byterangeStr(segment.byterange);
  3762. }
  3763. return headers;
  3764. };
  3765. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  3766. var DASH_REGEX = /^application\/dash\+xml/i;
  3767. /**
  3768. * Returns a string that describes the type of source based on a video source object's
  3769. * media type.
  3770. *
  3771. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  3772. *
  3773. * @param {string} type
  3774. * Video source object media type
  3775. * @return {('hls'|'dash'|'vhs-json'|null)}
  3776. * VHS source type string
  3777. */
  3778. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  3779. if (MPEGURL_REGEX.test(type)) {
  3780. return 'hls';
  3781. }
  3782. if (DASH_REGEX.test(type)) {
  3783. return 'dash';
  3784. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  3785. // source URL.
  3786. //
  3787. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  3788. //
  3789. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  3790. // project, and the +json suffix identifies the structure of the media type.
  3791. if (type === 'application/vnd.videojs.vhs+json') {
  3792. return 'vhs-json';
  3793. }
  3794. return null;
  3795. };
  3796. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  3797. // we used to do this with log2 but BigInt does not support builtin math
  3798. // Math.ceil(log2(x));
  3799. var countBits = function countBits(x) {
  3800. return x.toString(2).length;
  3801. }; // count the number of whole bytes it would take to represent a number
  3802. var countBytes = function countBytes(x) {
  3803. return Math.ceil(countBits(x) / 8);
  3804. };
  3805. var isArrayBufferView = function isArrayBufferView(obj) {
  3806. if (ArrayBuffer.isView === 'function') {
  3807. return ArrayBuffer.isView(obj);
  3808. }
  3809. return obj && obj.buffer instanceof ArrayBuffer;
  3810. };
  3811. var isTypedArray = function isTypedArray(obj) {
  3812. return isArrayBufferView(obj);
  3813. };
  3814. var toUint8 = function toUint8(bytes) {
  3815. if (bytes instanceof Uint8Array) {
  3816. return bytes;
  3817. }
  3818. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  3819. // any non-number or NaN leads to empty uint8array
  3820. // eslint-disable-next-line
  3821. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  3822. bytes = 0;
  3823. } else {
  3824. bytes = [bytes];
  3825. }
  3826. }
  3827. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  3828. };
  3829. var BigInt = window.BigInt || Number;
  3830. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  3831. (function () {
  3832. var a = new Uint16Array([0xFFCC]);
  3833. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  3834. if (b[0] === 0xFF) {
  3835. return 'big';
  3836. }
  3837. if (b[0] === 0xCC) {
  3838. return 'little';
  3839. }
  3840. return 'unknown';
  3841. })();
  3842. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  3843. var _ref = _temp === void 0 ? {} : _temp,
  3844. _ref$signed = _ref.signed,
  3845. signed = _ref$signed === void 0 ? false : _ref$signed,
  3846. _ref$le = _ref.le,
  3847. le = _ref$le === void 0 ? false : _ref$le;
  3848. bytes = toUint8(bytes);
  3849. var fn = le ? 'reduce' : 'reduceRight';
  3850. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  3851. var number = obj.call(bytes, function (total, byte, i) {
  3852. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  3853. return total + BigInt(byte) * BYTE_TABLE[exponent];
  3854. }, BigInt(0));
  3855. if (signed) {
  3856. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  3857. number = BigInt(number);
  3858. if (number > max) {
  3859. number -= max;
  3860. number -= max;
  3861. number -= BigInt(2);
  3862. }
  3863. }
  3864. return Number(number);
  3865. };
  3866. var numberToBytes = function numberToBytes(number, _temp2) {
  3867. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  3868. _ref2$le = _ref2.le,
  3869. le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
  3870. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  3871. number = 0;
  3872. }
  3873. number = BigInt(number);
  3874. var byteCount = countBytes(number);
  3875. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  3876. for (var i = 0; i < byteCount; i++) {
  3877. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  3878. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  3879. if (number < 0) {
  3880. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  3881. bytes[byteIndex] -= i === 0 ? 1 : 2;
  3882. }
  3883. }
  3884. return bytes;
  3885. };
  3886. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  3887. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  3888. string = string.toString();
  3889. }
  3890. if (typeof string !== 'string') {
  3891. return new Uint8Array();
  3892. } // If the string already is bytes, we don't have to do this
  3893. // otherwise we do this so that we split multi length characters
  3894. // into individual bytes
  3895. if (!stringIsBytes) {
  3896. string = unescape(encodeURIComponent(string));
  3897. }
  3898. var view = new Uint8Array(string.length);
  3899. for (var i = 0; i < string.length; i++) {
  3900. view[i] = string.charCodeAt(i);
  3901. }
  3902. return view;
  3903. };
  3904. var concatTypedArrays = function concatTypedArrays() {
  3905. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  3906. buffers[_key] = arguments[_key];
  3907. }
  3908. buffers = buffers.filter(function (b) {
  3909. return b && (b.byteLength || b.length) && typeof b !== 'string';
  3910. });
  3911. if (buffers.length <= 1) {
  3912. // for 0 length we will return empty uint8
  3913. // for 1 length we return the first uint8
  3914. return toUint8(buffers[0]);
  3915. }
  3916. var totalLen = buffers.reduce(function (total, buf, i) {
  3917. return total + (buf.byteLength || buf.length);
  3918. }, 0);
  3919. var tempBuffer = new Uint8Array(totalLen);
  3920. var offset = 0;
  3921. buffers.forEach(function (buf) {
  3922. buf = toUint8(buf);
  3923. tempBuffer.set(buf, offset);
  3924. offset += buf.byteLength;
  3925. });
  3926. return tempBuffer;
  3927. };
  3928. /**
  3929. * Check if the bytes "b" are contained within bytes "a".
  3930. *
  3931. * @param {Uint8Array|Array} a
  3932. * Bytes to check in
  3933. *
  3934. * @param {Uint8Array|Array} b
  3935. * Bytes to check for
  3936. *
  3937. * @param {Object} options
  3938. * options
  3939. *
  3940. * @param {Array|Uint8Array} [offset=0]
  3941. * offset to use when looking at bytes in a
  3942. *
  3943. * @param {Array|Uint8Array} [mask=[]]
  3944. * mask to use on bytes before comparison.
  3945. *
  3946. * @return {boolean}
  3947. * If all bytes in b are inside of a, taking into account
  3948. * bit masks.
  3949. */
  3950. var bytesMatch = function bytesMatch(a, b, _temp3) {
  3951. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  3952. _ref3$offset = _ref3.offset,
  3953. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  3954. _ref3$mask = _ref3.mask,
  3955. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  3956. a = toUint8(a);
  3957. b = toUint8(b); // ie 11 does not support uint8 every
  3958. var fn = b.every ? b.every : Array.prototype.every;
  3959. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  3960. fn.call(b, function (bByte, i) {
  3961. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  3962. return bByte === aByte;
  3963. });
  3964. };
  3965. /**
  3966. * @file bin-utils.js
  3967. */
  3968. /**
  3969. * convert a TimeRange to text
  3970. *
  3971. * @param {TimeRange} range the timerange to use for conversion
  3972. * @param {number} i the iterator on the range to convert
  3973. * @return {string} the range in string format
  3974. */
  3975. const textRange = function (range, i) {
  3976. return range.start(i) + '-' + range.end(i);
  3977. };
  3978. /**
  3979. * format a number as hex string
  3980. *
  3981. * @param {number} e The number
  3982. * @param {number} i the iterator
  3983. * @return {string} the hex formatted number as a string
  3984. */
  3985. const formatHexString = function (e, i) {
  3986. const value = e.toString(16);
  3987. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  3988. };
  3989. const formatAsciiString = function (e) {
  3990. if (e >= 0x20 && e < 0x7e) {
  3991. return String.fromCharCode(e);
  3992. }
  3993. return '.';
  3994. };
  3995. /**
  3996. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  3997. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  3998. *
  3999. * @param {Object} message
  4000. * Object of properties and values to send to the web worker
  4001. * @return {Object}
  4002. * Modified message with TypedArray values expanded
  4003. * @function createTransferableMessage
  4004. */
  4005. const createTransferableMessage = function (message) {
  4006. const transferable = {};
  4007. Object.keys(message).forEach(key => {
  4008. const value = message[key];
  4009. if (isArrayBufferView(value)) {
  4010. transferable[key] = {
  4011. bytes: value.buffer,
  4012. byteOffset: value.byteOffset,
  4013. byteLength: value.byteLength
  4014. };
  4015. } else {
  4016. transferable[key] = value;
  4017. }
  4018. });
  4019. return transferable;
  4020. };
  4021. /**
  4022. * Returns a unique string identifier for a media initialization
  4023. * segment.
  4024. *
  4025. * @param {Object} initSegment
  4026. * the init segment object.
  4027. *
  4028. * @return {string} the generated init segment id
  4029. */
  4030. const initSegmentId = function (initSegment) {
  4031. const byterange = initSegment.byterange || {
  4032. length: Infinity,
  4033. offset: 0
  4034. };
  4035. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  4036. };
  4037. /**
  4038. * Returns a unique string identifier for a media segment key.
  4039. *
  4040. * @param {Object} key the encryption key
  4041. * @return {string} the unique id for the media segment key.
  4042. */
  4043. const segmentKeyId = function (key) {
  4044. return key.resolvedUri;
  4045. };
  4046. /**
  4047. * utils to help dump binary data to the console
  4048. *
  4049. * @param {Array|TypedArray} data
  4050. * data to dump to a string
  4051. *
  4052. * @return {string} the data as a hex string.
  4053. */
  4054. const hexDump = data => {
  4055. const bytes = Array.prototype.slice.call(data);
  4056. const step = 16;
  4057. let result = '';
  4058. let hex;
  4059. let ascii;
  4060. for (let j = 0; j < bytes.length / step; j++) {
  4061. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  4062. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  4063. result += hex + ' ' + ascii + '\n';
  4064. }
  4065. return result;
  4066. };
  4067. const tagDump = ({
  4068. bytes
  4069. }) => hexDump(bytes);
  4070. const textRanges = ranges => {
  4071. let result = '';
  4072. let i;
  4073. for (i = 0; i < ranges.length; i++) {
  4074. result += textRange(ranges, i) + ' ';
  4075. }
  4076. return result;
  4077. };
  4078. var utils = /*#__PURE__*/Object.freeze({
  4079. __proto__: null,
  4080. createTransferableMessage: createTransferableMessage,
  4081. initSegmentId: initSegmentId,
  4082. segmentKeyId: segmentKeyId,
  4083. hexDump: hexDump,
  4084. tagDump: tagDump,
  4085. textRanges: textRanges
  4086. });
  4087. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  4088. // 25% was arbitrarily chosen, and may need to be refined over time.
  4089. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  4090. /**
  4091. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  4092. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  4093. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  4094. *
  4095. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  4096. * point" (a point where we have a mapping from program time to player time, with player
  4097. * time being the post transmux start of the segment).
  4098. *
  4099. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  4100. *
  4101. * @param {number} playerTime the player time
  4102. * @param {Object} segment the segment which contains the player time
  4103. * @return {Date} program time
  4104. */
  4105. const playerTimeToProgramTime = (playerTime, segment) => {
  4106. if (!segment.dateTimeObject) {
  4107. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  4108. // be used to map the start of a segment with a real world time).
  4109. return null;
  4110. }
  4111. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  4112. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  4113. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  4114. const offsetFromSegmentStart = playerTime - startOfSegment;
  4115. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  4116. };
  4117. const originalSegmentVideoDuration = videoTimingInfo => {
  4118. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  4119. };
  4120. /**
  4121. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  4122. * returned segment might be an estimate or an accurate match.
  4123. *
  4124. * @param {string} programTime The ISO-8601 programTime to find a match for
  4125. * @param {Object} playlist A playlist object to search within
  4126. */
  4127. const findSegmentForProgramTime = (programTime, playlist) => {
  4128. // Assumptions:
  4129. // - verifyProgramDateTimeTags has already been run
  4130. // - live streams have been started
  4131. let dateTimeObject;
  4132. try {
  4133. dateTimeObject = new Date(programTime);
  4134. } catch (e) {
  4135. return null;
  4136. }
  4137. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4138. return null;
  4139. }
  4140. let segment = playlist.segments[0];
  4141. if (dateTimeObject < segment.dateTimeObject) {
  4142. // Requested time is before stream start.
  4143. return null;
  4144. }
  4145. for (let i = 0; i < playlist.segments.length - 1; i++) {
  4146. segment = playlist.segments[i];
  4147. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  4148. if (dateTimeObject < nextSegmentStart) {
  4149. break;
  4150. }
  4151. }
  4152. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4153. const lastSegmentStart = lastSegment.dateTimeObject;
  4154. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  4155. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  4156. if (dateTimeObject > lastSegmentEnd) {
  4157. // Beyond the end of the stream, or our best guess of the end of the stream.
  4158. return null;
  4159. }
  4160. if (dateTimeObject > lastSegmentStart) {
  4161. segment = lastSegment;
  4162. }
  4163. return {
  4164. segment,
  4165. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  4166. // Although, given that all segments have accurate date time objects, the segment
  4167. // selected should be accurate, unless the video has been transmuxed at some point
  4168. // (determined by the presence of the videoTimingInfo object), the segment's "player
  4169. // time" (the start time in the player) can't be considered accurate.
  4170. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4171. };
  4172. };
  4173. /**
  4174. * Finds a segment that contains the given player time(in seconds).
  4175. *
  4176. * @param {number} time The player time to find a match for
  4177. * @param {Object} playlist A playlist object to search within
  4178. */
  4179. const findSegmentForPlayerTime = (time, playlist) => {
  4180. // Assumptions:
  4181. // - there will always be a segment.duration
  4182. // - we can start from zero
  4183. // - segments are in time order
  4184. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4185. return null;
  4186. }
  4187. let segmentEnd = 0;
  4188. let segment;
  4189. for (let i = 0; i < playlist.segments.length; i++) {
  4190. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  4191. // should contain the most accurate values we have for the segment's player times.
  4192. //
  4193. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  4194. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  4195. // calculate an end value.
  4196. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  4197. if (time <= segmentEnd) {
  4198. break;
  4199. }
  4200. }
  4201. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4202. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  4203. // The time requested is beyond the stream end.
  4204. return null;
  4205. }
  4206. if (time > segmentEnd) {
  4207. // The time is within or beyond the last segment.
  4208. //
  4209. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  4210. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  4211. // Technically, because the duration value is only an estimate, the time may still
  4212. // exist in the last segment, however, there isn't enough information to make even
  4213. // a reasonable estimate.
  4214. return null;
  4215. }
  4216. segment = lastSegment;
  4217. }
  4218. return {
  4219. segment,
  4220. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  4221. // Because videoTimingInfo is only set after transmux, it is the only way to get
  4222. // accurate timing values.
  4223. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4224. };
  4225. };
  4226. /**
  4227. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  4228. * If the offset returned is positive, the programTime occurs after the
  4229. * comparisonTimestamp.
  4230. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  4231. *
  4232. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  4233. * @param {string} programTime The programTime as an ISO-8601 string
  4234. * @return {number} offset
  4235. */
  4236. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  4237. let segmentDateTime;
  4238. let programDateTime;
  4239. try {
  4240. segmentDateTime = new Date(comparisonTimeStamp);
  4241. programDateTime = new Date(programTime);
  4242. } catch (e) {// TODO handle error
  4243. }
  4244. const segmentTimeEpoch = segmentDateTime.getTime();
  4245. const programTimeEpoch = programDateTime.getTime();
  4246. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  4247. };
  4248. /**
  4249. * Checks that all segments in this playlist have programDateTime tags.
  4250. *
  4251. * @param {Object} playlist A playlist object
  4252. */
  4253. const verifyProgramDateTimeTags = playlist => {
  4254. if (!playlist.segments || playlist.segments.length === 0) {
  4255. return false;
  4256. }
  4257. for (let i = 0; i < playlist.segments.length; i++) {
  4258. const segment = playlist.segments[i];
  4259. if (!segment.dateTimeObject) {
  4260. return false;
  4261. }
  4262. }
  4263. return true;
  4264. };
  4265. /**
  4266. * Returns the programTime of the media given a playlist and a playerTime.
  4267. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  4268. * If the segments containing the time requested have not been buffered yet, an estimate
  4269. * may be returned to the callback.
  4270. *
  4271. * @param {Object} args
  4272. * @param {Object} args.playlist A playlist object to search within
  4273. * @param {number} time A playerTime in seconds
  4274. * @param {Function} callback(err, programTime)
  4275. * @return {string} err.message A detailed error message
  4276. * @return {Object} programTime
  4277. * @return {number} programTime.mediaSeconds The streamTime in seconds
  4278. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  4279. */
  4280. const getProgramTime = ({
  4281. playlist,
  4282. time = undefined,
  4283. callback
  4284. }) => {
  4285. if (!callback) {
  4286. throw new Error('getProgramTime: callback must be provided');
  4287. }
  4288. if (!playlist || time === undefined) {
  4289. return callback({
  4290. message: 'getProgramTime: playlist and time must be provided'
  4291. });
  4292. }
  4293. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  4294. if (!matchedSegment) {
  4295. return callback({
  4296. message: 'valid programTime was not found'
  4297. });
  4298. }
  4299. if (matchedSegment.type === 'estimate') {
  4300. return callback({
  4301. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  4302. seekTime: matchedSegment.estimatedStart
  4303. });
  4304. }
  4305. const programTimeObject = {
  4306. mediaSeconds: time
  4307. };
  4308. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  4309. if (programTime) {
  4310. programTimeObject.programDateTime = programTime.toISOString();
  4311. }
  4312. return callback(null, programTimeObject);
  4313. };
  4314. /**
  4315. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  4316. *
  4317. * @param {Object} args
  4318. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  4319. * @param {Object} args.playlist A playlist to look within
  4320. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  4321. * @param {Function} args.seekTo A method to perform a seek
  4322. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  4323. * @param {Object} args.tech The tech to seek on
  4324. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  4325. * @return {string} err.message A detailed error message
  4326. * @return {number} newTime The exact time that was seeked to in seconds
  4327. */
  4328. const seekToProgramTime = ({
  4329. programTime,
  4330. playlist,
  4331. retryCount = 2,
  4332. seekTo,
  4333. pauseAfterSeek = true,
  4334. tech,
  4335. callback
  4336. }) => {
  4337. if (!callback) {
  4338. throw new Error('seekToProgramTime: callback must be provided');
  4339. }
  4340. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  4341. return callback({
  4342. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  4343. });
  4344. }
  4345. if (!playlist.endList && !tech.hasStarted_) {
  4346. return callback({
  4347. message: 'player must be playing a live stream to start buffering'
  4348. });
  4349. }
  4350. if (!verifyProgramDateTimeTags(playlist)) {
  4351. return callback({
  4352. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  4353. });
  4354. }
  4355. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  4356. if (!matchedSegment) {
  4357. return callback({
  4358. message: `${programTime} was not found in the stream`
  4359. });
  4360. }
  4361. const segment = matchedSegment.segment;
  4362. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  4363. if (matchedSegment.type === 'estimate') {
  4364. // we've run out of retries
  4365. if (retryCount === 0) {
  4366. return callback({
  4367. message: `${programTime} is not buffered yet. Try again`
  4368. });
  4369. }
  4370. seekTo(matchedSegment.estimatedStart + mediaOffset);
  4371. tech.one('seeked', () => {
  4372. seekToProgramTime({
  4373. programTime,
  4374. playlist,
  4375. retryCount: retryCount - 1,
  4376. seekTo,
  4377. pauseAfterSeek,
  4378. tech,
  4379. callback
  4380. });
  4381. });
  4382. return;
  4383. } // Since the segment.start value is determined from the buffered end or ending time
  4384. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  4385. // modifications.
  4386. const seekToTime = segment.start + mediaOffset;
  4387. const seekedCallback = () => {
  4388. return callback(null, tech.currentTime());
  4389. }; // listen for seeked event
  4390. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  4391. if (pauseAfterSeek) {
  4392. tech.pause();
  4393. }
  4394. seekTo(seekToTime);
  4395. };
  4396. /**
  4397. * Loops through all supported media groups in master and calls the provided
  4398. * callback for each group
  4399. *
  4400. * @param {Object} master
  4401. * The parsed master manifest object
  4402. * @param {string[]} groups
  4403. * The media groups to call the callback for
  4404. * @param {Function} callback
  4405. * Callback to call for each media group
  4406. */
  4407. var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
  4408. groups.forEach(function (mediaType) {
  4409. for (var groupKey in master.mediaGroups[mediaType]) {
  4410. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  4411. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  4412. callback(mediaProperties, mediaType, groupKey, labelKey);
  4413. }
  4414. }
  4415. });
  4416. };
  4417. /*! @name mpd-parser @version 1.0.1 @license Apache-2.0 */
  4418. const isObject = obj => {
  4419. return !!obj && typeof obj === 'object';
  4420. };
  4421. const merge = (...objects) => {
  4422. return objects.reduce((result, source) => {
  4423. if (typeof source !== 'object') {
  4424. return result;
  4425. }
  4426. Object.keys(source).forEach(key => {
  4427. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  4428. result[key] = result[key].concat(source[key]);
  4429. } else if (isObject(result[key]) && isObject(source[key])) {
  4430. result[key] = merge(result[key], source[key]);
  4431. } else {
  4432. result[key] = source[key];
  4433. }
  4434. });
  4435. return result;
  4436. }, {});
  4437. };
  4438. const values = o => Object.keys(o).map(k => o[k]);
  4439. const range = (start, end) => {
  4440. const result = [];
  4441. for (let i = start; i < end; i++) {
  4442. result.push(i);
  4443. }
  4444. return result;
  4445. };
  4446. const flatten = lists => lists.reduce((x, y) => x.concat(y), []);
  4447. const from = list => {
  4448. if (!list.length) {
  4449. return [];
  4450. }
  4451. const result = [];
  4452. for (let i = 0; i < list.length; i++) {
  4453. result.push(list[i]);
  4454. }
  4455. return result;
  4456. };
  4457. const findIndexes = (l, key) => l.reduce((a, e, i) => {
  4458. if (e[key]) {
  4459. a.push(i);
  4460. }
  4461. return a;
  4462. }, []);
  4463. /**
  4464. * Returns a union of the included lists provided each element can be identified by a key.
  4465. *
  4466. * @param {Array} list - list of lists to get the union of
  4467. * @param {Function} keyFunction - the function to use as a key for each element
  4468. *
  4469. * @return {Array} the union of the arrays
  4470. */
  4471. const union = (lists, keyFunction) => {
  4472. return values(lists.reduce((acc, list) => {
  4473. list.forEach(el => {
  4474. acc[keyFunction(el)] = el;
  4475. });
  4476. return acc;
  4477. }, {}));
  4478. };
  4479. var errors = {
  4480. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  4481. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  4482. DASH_INVALID_XML: 'DASH_INVALID_XML',
  4483. NO_BASE_URL: 'NO_BASE_URL',
  4484. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  4485. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  4486. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  4487. };
  4488. /**
  4489. * @typedef {Object} SingleUri
  4490. * @property {string} uri - relative location of segment
  4491. * @property {string} resolvedUri - resolved location of segment
  4492. * @property {Object} byterange - Object containing information on how to make byte range
  4493. * requests following byte-range-spec per RFC2616.
  4494. * @property {String} byterange.length - length of range request
  4495. * @property {String} byterange.offset - byte offset of range request
  4496. *
  4497. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  4498. */
  4499. /**
  4500. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  4501. * that conforms to how m3u8-parser is structured
  4502. *
  4503. * @see https://github.com/videojs/m3u8-parser
  4504. *
  4505. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  4506. * @param {string} source - source url for segment
  4507. * @param {string} range - optional range used for range calls,
  4508. * follows RFC 2616, Clause 14.35.1
  4509. * @return {SingleUri} full segment information transformed into a format similar
  4510. * to m3u8-parser
  4511. */
  4512. const urlTypeToSegment = ({
  4513. baseUrl = '',
  4514. source = '',
  4515. range = '',
  4516. indexRange = ''
  4517. }) => {
  4518. const segment = {
  4519. uri: source,
  4520. resolvedUri: resolveUrl$1(baseUrl || '', source)
  4521. };
  4522. if (range || indexRange) {
  4523. const rangeStr = range ? range : indexRange;
  4524. const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  4525. let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  4526. let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  4527. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  4528. startRange = Number(startRange);
  4529. }
  4530. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  4531. endRange = Number(endRange);
  4532. }
  4533. let length;
  4534. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  4535. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  4536. } else {
  4537. length = endRange - startRange + 1;
  4538. }
  4539. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  4540. length = Number(length);
  4541. } // byterange should be inclusive according to
  4542. // RFC 2616, Clause 14.35.1
  4543. segment.byterange = {
  4544. length,
  4545. offset: startRange
  4546. };
  4547. }
  4548. return segment;
  4549. };
  4550. const byteRangeToString = byterange => {
  4551. // `endRange` is one less than `offset + length` because the HTTP range
  4552. // header uses inclusive ranges
  4553. let endRange;
  4554. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  4555. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  4556. } else {
  4557. endRange = byterange.offset + byterange.length - 1;
  4558. }
  4559. return `${byterange.offset}-${endRange}`;
  4560. };
  4561. /**
  4562. * parse the end number attribue that can be a string
  4563. * number, or undefined.
  4564. *
  4565. * @param {string|number|undefined} endNumber
  4566. * The end number attribute.
  4567. *
  4568. * @return {number|null}
  4569. * The result of parsing the end number.
  4570. */
  4571. const parseEndNumber = endNumber => {
  4572. if (endNumber && typeof endNumber !== 'number') {
  4573. endNumber = parseInt(endNumber, 10);
  4574. }
  4575. if (isNaN(endNumber)) {
  4576. return null;
  4577. }
  4578. return endNumber;
  4579. };
  4580. /**
  4581. * Functions for calculating the range of available segments in static and dynamic
  4582. * manifests.
  4583. */
  4584. const segmentRange = {
  4585. /**
  4586. * Returns the entire range of available segments for a static MPD
  4587. *
  4588. * @param {Object} attributes
  4589. * Inheritied MPD attributes
  4590. * @return {{ start: number, end: number }}
  4591. * The start and end numbers for available segments
  4592. */
  4593. static(attributes) {
  4594. const {
  4595. duration,
  4596. timescale = 1,
  4597. sourceDuration,
  4598. periodDuration
  4599. } = attributes;
  4600. const endNumber = parseEndNumber(attributes.endNumber);
  4601. const segmentDuration = duration / timescale;
  4602. if (typeof endNumber === 'number') {
  4603. return {
  4604. start: 0,
  4605. end: endNumber
  4606. };
  4607. }
  4608. if (typeof periodDuration === 'number') {
  4609. return {
  4610. start: 0,
  4611. end: periodDuration / segmentDuration
  4612. };
  4613. }
  4614. return {
  4615. start: 0,
  4616. end: sourceDuration / segmentDuration
  4617. };
  4618. },
  4619. /**
  4620. * Returns the current live window range of available segments for a dynamic MPD
  4621. *
  4622. * @param {Object} attributes
  4623. * Inheritied MPD attributes
  4624. * @return {{ start: number, end: number }}
  4625. * The start and end numbers for available segments
  4626. */
  4627. dynamic(attributes) {
  4628. const {
  4629. NOW,
  4630. clientOffset,
  4631. availabilityStartTime,
  4632. timescale = 1,
  4633. duration,
  4634. periodStart = 0,
  4635. minimumUpdatePeriod = 0,
  4636. timeShiftBufferDepth = Infinity
  4637. } = attributes;
  4638. const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  4639. // after retrieving UTC server time.
  4640. const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  4641. // Convert the period start time to EPOCH.
  4642. const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  4643. const periodEndWC = now + minimumUpdatePeriod;
  4644. const periodDuration = periodEndWC - periodStartWC;
  4645. const segmentCount = Math.ceil(periodDuration * timescale / duration);
  4646. const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  4647. const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  4648. return {
  4649. start: Math.max(0, availableStart),
  4650. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  4651. };
  4652. }
  4653. };
  4654. /**
  4655. * Maps a range of numbers to objects with information needed to build the corresponding
  4656. * segment list
  4657. *
  4658. * @name toSegmentsCallback
  4659. * @function
  4660. * @param {number} number
  4661. * Number of the segment
  4662. * @param {number} index
  4663. * Index of the number in the range list
  4664. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  4665. * Object with segment timing and duration info
  4666. */
  4667. /**
  4668. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  4669. * information needed to build the segment list.
  4670. *
  4671. * @param {Object} attributes
  4672. * Inherited MPD attributes
  4673. * @return {toSegmentsCallback}
  4674. * Callback map function
  4675. */
  4676. const toSegments = attributes => number => {
  4677. const {
  4678. duration,
  4679. timescale = 1,
  4680. periodStart,
  4681. startNumber = 1
  4682. } = attributes;
  4683. return {
  4684. number: startNumber + number,
  4685. duration: duration / timescale,
  4686. timeline: periodStart,
  4687. time: number * duration
  4688. };
  4689. };
  4690. /**
  4691. * Returns a list of objects containing segment timing and duration info used for
  4692. * building the list of segments. This uses the @duration attribute specified
  4693. * in the MPD manifest to derive the range of segments.
  4694. *
  4695. * @param {Object} attributes
  4696. * Inherited MPD attributes
  4697. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  4698. * List of Objects with segment timing and duration info
  4699. */
  4700. const parseByDuration = attributes => {
  4701. const {
  4702. type,
  4703. duration,
  4704. timescale = 1,
  4705. periodDuration,
  4706. sourceDuration
  4707. } = attributes;
  4708. const {
  4709. start,
  4710. end
  4711. } = segmentRange[type](attributes);
  4712. const segments = range(start, end).map(toSegments(attributes));
  4713. if (type === 'static') {
  4714. const index = segments.length - 1; // section is either a period or the full source
  4715. const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  4716. segments[index].duration = sectionDuration - duration / timescale * index;
  4717. }
  4718. return segments;
  4719. };
  4720. /**
  4721. * Translates SegmentBase into a set of segments.
  4722. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  4723. * node should be translated into segment.
  4724. *
  4725. * @param {Object} attributes
  4726. * Object containing all inherited attributes from parent elements with attribute
  4727. * names as keys
  4728. * @return {Object.<Array>} list of segments
  4729. */
  4730. const segmentsFromBase = attributes => {
  4731. const {
  4732. baseUrl,
  4733. initialization = {},
  4734. sourceDuration,
  4735. indexRange = '',
  4736. periodStart,
  4737. presentationTime,
  4738. number = 0,
  4739. duration
  4740. } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  4741. if (!baseUrl) {
  4742. throw new Error(errors.NO_BASE_URL);
  4743. }
  4744. const initSegment = urlTypeToSegment({
  4745. baseUrl,
  4746. source: initialization.sourceURL,
  4747. range: initialization.range
  4748. });
  4749. const segment = urlTypeToSegment({
  4750. baseUrl,
  4751. source: baseUrl,
  4752. indexRange
  4753. });
  4754. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  4755. // (since SegmentBase is only for one total segment)
  4756. if (duration) {
  4757. const segmentTimeInfo = parseByDuration(attributes);
  4758. if (segmentTimeInfo.length) {
  4759. segment.duration = segmentTimeInfo[0].duration;
  4760. segment.timeline = segmentTimeInfo[0].timeline;
  4761. }
  4762. } else if (sourceDuration) {
  4763. segment.duration = sourceDuration;
  4764. segment.timeline = periodStart;
  4765. } // If presentation time is provided, these segments are being generated by SIDX
  4766. // references, and should use the time provided. For the general case of SegmentBase,
  4767. // there should only be one segment in the period, so its presentation time is the same
  4768. // as its period start.
  4769. segment.presentationTime = presentationTime || periodStart;
  4770. segment.number = number;
  4771. return [segment];
  4772. };
  4773. /**
  4774. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  4775. * according to the sidx information given.
  4776. *
  4777. * playlist.sidx has metadadata about the sidx where-as the sidx param
  4778. * is the parsed sidx box itself.
  4779. *
  4780. * @param {Object} playlist the playlist to update the sidx information for
  4781. * @param {Object} sidx the parsed sidx box
  4782. * @return {Object} the playlist object with the updated sidx information
  4783. */
  4784. const addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {
  4785. // Retain init segment information
  4786. const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  4787. const sourceDuration = playlist.sidx.duration; // Retain source timeline
  4788. const timeline = playlist.timeline || 0;
  4789. const sidxByteRange = playlist.sidx.byterange;
  4790. const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  4791. const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  4792. const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);
  4793. const segments = [];
  4794. const type = playlist.endList ? 'static' : 'dynamic';
  4795. const periodStart = playlist.sidx.timeline;
  4796. let presentationTime = periodStart;
  4797. let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  4798. let startIndex; // eslint-disable-next-line
  4799. if (typeof sidx.firstOffset === 'bigint') {
  4800. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  4801. } else {
  4802. startIndex = sidxEnd + sidx.firstOffset;
  4803. }
  4804. for (let i = 0; i < mediaReferences.length; i++) {
  4805. const reference = sidx.references[i]; // size of the referenced (sub)segment
  4806. const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  4807. // this will be converted to seconds when generating segments
  4808. const duration = reference.subsegmentDuration; // should be an inclusive range
  4809. let endIndex; // eslint-disable-next-line
  4810. if (typeof startIndex === 'bigint') {
  4811. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  4812. } else {
  4813. endIndex = startIndex + size - 1;
  4814. }
  4815. const indexRange = `${startIndex}-${endIndex}`;
  4816. const attributes = {
  4817. baseUrl,
  4818. timescale,
  4819. timeline,
  4820. periodStart,
  4821. presentationTime,
  4822. number,
  4823. duration,
  4824. sourceDuration,
  4825. indexRange,
  4826. type
  4827. };
  4828. const segment = segmentsFromBase(attributes)[0];
  4829. if (initSegment) {
  4830. segment.map = initSegment;
  4831. }
  4832. segments.push(segment);
  4833. if (typeof startIndex === 'bigint') {
  4834. startIndex += window.BigInt(size);
  4835. } else {
  4836. startIndex += size;
  4837. }
  4838. presentationTime += duration / timescale;
  4839. number++;
  4840. }
  4841. playlist.segments = segments;
  4842. return playlist;
  4843. };
  4844. const SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  4845. const TIME_FUDGE = 1 / 60;
  4846. /**
  4847. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  4848. *
  4849. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  4850. *
  4851. * @return {TimelineStart[]} the combined and deduped timeline starts
  4852. */
  4853. const getUniqueTimelineStarts = timelineStarts => {
  4854. return union(timelineStarts, ({
  4855. timeline
  4856. }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);
  4857. };
  4858. /**
  4859. * Finds the playlist with the matching NAME attribute.
  4860. *
  4861. * @param {Array} playlists - playlists to search through
  4862. * @param {string} name - the NAME attribute to search for
  4863. *
  4864. * @return {Object|null} the matching playlist object, or null
  4865. */
  4866. const findPlaylistWithName = (playlists, name) => {
  4867. for (let i = 0; i < playlists.length; i++) {
  4868. if (playlists[i].attributes.NAME === name) {
  4869. return playlists[i];
  4870. }
  4871. }
  4872. return null;
  4873. };
  4874. /**
  4875. * Gets a flattened array of media group playlists.
  4876. *
  4877. * @param {Object} manifest - the main manifest object
  4878. *
  4879. * @return {Array} the media group playlists
  4880. */
  4881. const getMediaGroupPlaylists = manifest => {
  4882. let mediaGroupPlaylists = [];
  4883. forEachMediaGroup(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {
  4884. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  4885. });
  4886. return mediaGroupPlaylists;
  4887. };
  4888. /**
  4889. * Updates the playlist's media sequence numbers.
  4890. *
  4891. * @param {Object} config - options object
  4892. * @param {Object} config.playlist - the playlist to update
  4893. * @param {number} config.mediaSequence - the mediaSequence number to start with
  4894. */
  4895. const updateMediaSequenceForPlaylist = ({
  4896. playlist,
  4897. mediaSequence
  4898. }) => {
  4899. playlist.mediaSequence = mediaSequence;
  4900. playlist.segments.forEach((segment, index) => {
  4901. segment.number = playlist.mediaSequence + index;
  4902. });
  4903. };
  4904. /**
  4905. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  4906. * and a complete list of timeline starts.
  4907. *
  4908. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  4909. * will be updated.
  4910. *
  4911. * Since early available timelines are not supported, at least one segment must be present.
  4912. *
  4913. * @param {Object} config - options object
  4914. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  4915. * @param {Object[]} newPlaylists - the new playlists to update
  4916. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  4917. */
  4918. const updateSequenceNumbers = ({
  4919. oldPlaylists,
  4920. newPlaylists,
  4921. timelineStarts
  4922. }) => {
  4923. newPlaylists.forEach(playlist => {
  4924. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  4925. timeline
  4926. }) {
  4927. return timeline === playlist.timeline;
  4928. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  4929. // (see ISO_23009-1-2012 5.3.5.2).
  4930. //
  4931. // If the same Representation existed in a prior Period, it will retain the same NAME.
  4932. const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  4933. if (!oldPlaylist) {
  4934. // Since this is a new playlist, the media sequence values can start from 0 without
  4935. // consequence.
  4936. return;
  4937. } // TODO better support for live SIDX
  4938. //
  4939. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  4940. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  4941. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  4942. // not supported when the SIDX properties change on refreshes.
  4943. //
  4944. // In the future, if support needs to be added, the merging logic here can be called
  4945. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  4946. // thrown due to undefined references.
  4947. if (playlist.sidx) {
  4948. return;
  4949. } // Since we don't yet support early available timelines, we don't need to support
  4950. // playlists with no segments.
  4951. const firstNewSegment = playlist.segments[0];
  4952. const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {
  4953. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  4954. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  4955. // In this case the media sequence should account for this update, and the new segments
  4956. // should be marked as discontinuous from the prior content, since the last prior
  4957. // timeline was removed.
  4958. if (oldMatchingSegmentIndex === -1) {
  4959. updateMediaSequenceForPlaylist({
  4960. playlist,
  4961. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  4962. });
  4963. playlist.segments[0].discontinuity = true;
  4964. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  4965. //
  4966. // If the new playlist's timeline is the same as the last seen segment's timeline,
  4967. // then a discontinuity can be added to identify that there's potentially missing
  4968. // content. If there's no missing content, the discontinuity should still be rather
  4969. // harmless. It's possible that if segment durations are accurate enough, that the
  4970. // existence of a gap can be determined using the presentation times and durations,
  4971. // but if the segment timing info is off, it may introduce more problems than simply
  4972. // adding the discontinuity.
  4973. //
  4974. // If the new playlist's timeline is different from the last seen segment's timeline,
  4975. // then a discontinuity can be added to identify that this is the first seen segment
  4976. // of a new timeline. However, the logic at the start of this function that
  4977. // determined the disconinuity sequence by timeline index is now off by one (the
  4978. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  4979. // we added it), so the disconinuity sequence must be decremented.
  4980. //
  4981. // A period may also have a duration of zero, so the case of no segments is handled
  4982. // here even though we don't yet support early available periods.
  4983. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  4984. playlist.discontinuitySequence--;
  4985. }
  4986. return;
  4987. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  4988. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  4989. // timeline's matching one, but instead should be the one prior, and the first segment
  4990. // of the new manifest should be marked with a discontinuity.
  4991. //
  4992. // The reason for this special case is that discontinuity sequence shows how many
  4993. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  4994. // the first segment of a new "timeline." Because of this, while DASH will retain that
  4995. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  4996. // sequence, and that first segment is an indicator, but can be removed before that
  4997. // timeline is gone.
  4998. const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  4999. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  5000. firstNewSegment.discontinuity = true;
  5001. playlist.discontinuityStarts.unshift(0);
  5002. playlist.discontinuitySequence--;
  5003. }
  5004. updateMediaSequenceForPlaylist({
  5005. playlist,
  5006. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  5007. });
  5008. });
  5009. };
  5010. /**
  5011. * Given an old parsed manifest object and a new parsed manifest object, updates the
  5012. * sequence and timing values within the new manifest to ensure that it lines up with the
  5013. * old.
  5014. *
  5015. * @param {Array} oldManifest - the old main manifest object
  5016. * @param {Array} newManifest - the new main manifest object
  5017. *
  5018. * @return {Object} the updated new manifest object
  5019. */
  5020. const positionManifestOnTimeline = ({
  5021. oldManifest,
  5022. newManifest
  5023. }) => {
  5024. // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  5025. //
  5026. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  5027. //
  5028. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  5029. //
  5030. // Because of this change, and the difficulty of supporting periods with changing start
  5031. // times, periods with changing start times are not supported. This makes the logic much
  5032. // simpler, since periods with the same start time can be considerred the same period
  5033. // across refreshes.
  5034. //
  5035. // To give an example as to the difficulty of handling periods where the start time may
  5036. // change, if a single period manifest is refreshed with another manifest with a single
  5037. // period, and both the start and end times are increased, then the only way to determine
  5038. // if it's a new period or an old one that has changed is to look through the segments of
  5039. // each playlist and determine the presentation time bounds to find a match. In addition,
  5040. // if the period start changed to exceed the old period end, then there would be no
  5041. // match, and it would not be possible to determine whether the refreshed period is a new
  5042. // one or the old one.
  5043. const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  5044. const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  5045. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  5046. // of properties are saved for each seen Period. Even long running live streams won't
  5047. // generate too many Periods, unless the stream is watched for decades. In the future,
  5048. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  5049. // but it may not become an issue, and the additional info can be useful for debugging.
  5050. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  5051. updateSequenceNumbers({
  5052. oldPlaylists,
  5053. newPlaylists,
  5054. timelineStarts: newManifest.timelineStarts
  5055. });
  5056. return newManifest;
  5057. };
  5058. const generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  5059. const mergeDiscontiguousPlaylists = playlists => {
  5060. const mergedPlaylists = values(playlists.reduce((acc, playlist) => {
  5061. // assuming playlist IDs are the same across periods
  5062. // TODO: handle multiperiod where representation sets are not the same
  5063. // across periods
  5064. const name = playlist.attributes.id + (playlist.attributes.lang || '');
  5065. if (!acc[name]) {
  5066. // First Period
  5067. acc[name] = playlist;
  5068. acc[name].attributes.timelineStarts = [];
  5069. } else {
  5070. // Subsequent Periods
  5071. if (playlist.segments) {
  5072. // first segment of subsequent periods signal a discontinuity
  5073. if (playlist.segments[0]) {
  5074. playlist.segments[0].discontinuity = true;
  5075. }
  5076. acc[name].segments.push(...playlist.segments);
  5077. } // bubble up contentProtection, this assumes all DRM content
  5078. // has the same contentProtection
  5079. if (playlist.attributes.contentProtection) {
  5080. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  5081. }
  5082. }
  5083. acc[name].attributes.timelineStarts.push({
  5084. // Although they represent the same number, it's important to have both to make it
  5085. // compatible with HLS potentially having a similar attribute.
  5086. start: playlist.attributes.periodStart,
  5087. timeline: playlist.attributes.periodStart
  5088. });
  5089. return acc;
  5090. }, {}));
  5091. return mergedPlaylists.map(playlist => {
  5092. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  5093. return playlist;
  5094. });
  5095. };
  5096. const addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {
  5097. const sidxKey = generateSidxKey(playlist.sidx);
  5098. const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  5099. if (sidxMatch) {
  5100. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  5101. }
  5102. return playlist;
  5103. };
  5104. const addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {
  5105. if (!Object.keys(sidxMapping).length) {
  5106. return playlists;
  5107. }
  5108. for (const i in playlists) {
  5109. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  5110. }
  5111. return playlists;
  5112. };
  5113. const formatAudioPlaylist = ({
  5114. attributes,
  5115. segments,
  5116. sidx,
  5117. mediaSequence,
  5118. discontinuitySequence,
  5119. discontinuityStarts
  5120. }, isAudioOnly) => {
  5121. const playlist = {
  5122. attributes: {
  5123. NAME: attributes.id,
  5124. BANDWIDTH: attributes.bandwidth,
  5125. CODECS: attributes.codecs,
  5126. ['PROGRAM-ID']: 1
  5127. },
  5128. uri: '',
  5129. endList: attributes.type === 'static',
  5130. timeline: attributes.periodStart,
  5131. resolvedUri: '',
  5132. targetDuration: attributes.duration,
  5133. discontinuitySequence,
  5134. discontinuityStarts,
  5135. timelineStarts: attributes.timelineStarts,
  5136. mediaSequence,
  5137. segments
  5138. };
  5139. if (attributes.contentProtection) {
  5140. playlist.contentProtection = attributes.contentProtection;
  5141. }
  5142. if (sidx) {
  5143. playlist.sidx = sidx;
  5144. }
  5145. if (isAudioOnly) {
  5146. playlist.attributes.AUDIO = 'audio';
  5147. playlist.attributes.SUBTITLES = 'subs';
  5148. }
  5149. return playlist;
  5150. };
  5151. const formatVttPlaylist = ({
  5152. attributes,
  5153. segments,
  5154. mediaSequence,
  5155. discontinuityStarts,
  5156. discontinuitySequence
  5157. }) => {
  5158. if (typeof segments === 'undefined') {
  5159. // vtt tracks may use single file in BaseURL
  5160. segments = [{
  5161. uri: attributes.baseUrl,
  5162. timeline: attributes.periodStart,
  5163. resolvedUri: attributes.baseUrl || '',
  5164. duration: attributes.sourceDuration,
  5165. number: 0
  5166. }]; // targetDuration should be the same duration as the only segment
  5167. attributes.duration = attributes.sourceDuration;
  5168. }
  5169. const m3u8Attributes = {
  5170. NAME: attributes.id,
  5171. BANDWIDTH: attributes.bandwidth,
  5172. ['PROGRAM-ID']: 1
  5173. };
  5174. if (attributes.codecs) {
  5175. m3u8Attributes.CODECS = attributes.codecs;
  5176. }
  5177. return {
  5178. attributes: m3u8Attributes,
  5179. uri: '',
  5180. endList: attributes.type === 'static',
  5181. timeline: attributes.periodStart,
  5182. resolvedUri: attributes.baseUrl || '',
  5183. targetDuration: attributes.duration,
  5184. timelineStarts: attributes.timelineStarts,
  5185. discontinuityStarts,
  5186. discontinuitySequence,
  5187. mediaSequence,
  5188. segments
  5189. };
  5190. };
  5191. const organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {
  5192. let mainPlaylist;
  5193. const formattedPlaylists = playlists.reduce((a, playlist) => {
  5194. const role = playlist.attributes.role && playlist.attributes.role.value || '';
  5195. const language = playlist.attributes.lang || '';
  5196. let label = playlist.attributes.label || 'main';
  5197. if (language && !playlist.attributes.label) {
  5198. const roleLabel = role ? ` (${role})` : '';
  5199. label = `${playlist.attributes.lang}${roleLabel}`;
  5200. }
  5201. if (!a[label]) {
  5202. a[label] = {
  5203. language,
  5204. autoselect: true,
  5205. default: role === 'main',
  5206. playlists: [],
  5207. uri: ''
  5208. };
  5209. }
  5210. const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  5211. a[label].playlists.push(formatted);
  5212. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  5213. mainPlaylist = playlist;
  5214. mainPlaylist.default = true;
  5215. }
  5216. return a;
  5217. }, {}); // if no playlists have role "main", mark the first as main
  5218. if (!mainPlaylist) {
  5219. const firstLabel = Object.keys(formattedPlaylists)[0];
  5220. formattedPlaylists[firstLabel].default = true;
  5221. }
  5222. return formattedPlaylists;
  5223. };
  5224. const organizeVttPlaylists = (playlists, sidxMapping = {}) => {
  5225. return playlists.reduce((a, playlist) => {
  5226. const label = playlist.attributes.lang || 'text';
  5227. if (!a[label]) {
  5228. a[label] = {
  5229. language: label,
  5230. default: false,
  5231. autoselect: false,
  5232. playlists: [],
  5233. uri: ''
  5234. };
  5235. }
  5236. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  5237. return a;
  5238. }, {});
  5239. };
  5240. const organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {
  5241. if (!svc) {
  5242. return svcObj;
  5243. }
  5244. svc.forEach(service => {
  5245. const {
  5246. channel,
  5247. language
  5248. } = service;
  5249. svcObj[language] = {
  5250. autoselect: false,
  5251. default: false,
  5252. instreamId: channel,
  5253. language
  5254. };
  5255. if (service.hasOwnProperty('aspectRatio')) {
  5256. svcObj[language].aspectRatio = service.aspectRatio;
  5257. }
  5258. if (service.hasOwnProperty('easyReader')) {
  5259. svcObj[language].easyReader = service.easyReader;
  5260. }
  5261. if (service.hasOwnProperty('3D')) {
  5262. svcObj[language]['3D'] = service['3D'];
  5263. }
  5264. });
  5265. return svcObj;
  5266. }, {});
  5267. const formatVideoPlaylist = ({
  5268. attributes,
  5269. segments,
  5270. sidx,
  5271. discontinuityStarts
  5272. }) => {
  5273. const playlist = {
  5274. attributes: {
  5275. NAME: attributes.id,
  5276. AUDIO: 'audio',
  5277. SUBTITLES: 'subs',
  5278. RESOLUTION: {
  5279. width: attributes.width,
  5280. height: attributes.height
  5281. },
  5282. CODECS: attributes.codecs,
  5283. BANDWIDTH: attributes.bandwidth,
  5284. ['PROGRAM-ID']: 1
  5285. },
  5286. uri: '',
  5287. endList: attributes.type === 'static',
  5288. timeline: attributes.periodStart,
  5289. resolvedUri: '',
  5290. targetDuration: attributes.duration,
  5291. discontinuityStarts,
  5292. timelineStarts: attributes.timelineStarts,
  5293. segments
  5294. };
  5295. if (attributes.frameRate) {
  5296. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  5297. }
  5298. if (attributes.contentProtection) {
  5299. playlist.contentProtection = attributes.contentProtection;
  5300. }
  5301. if (sidx) {
  5302. playlist.sidx = sidx;
  5303. }
  5304. return playlist;
  5305. };
  5306. const videoOnly = ({
  5307. attributes
  5308. }) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  5309. const audioOnly = ({
  5310. attributes
  5311. }) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  5312. const vttOnly = ({
  5313. attributes
  5314. }) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  5315. /**
  5316. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  5317. * be the same number.
  5318. *
  5319. * @typedef {Object} TimelineStart
  5320. * @property {number} start - the start time of the timeline
  5321. * @property {number} timeline - the timeline number
  5322. */
  5323. /**
  5324. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  5325. *
  5326. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  5327. * DASH specific attribute used in constructing segment URI's from templates. However, from
  5328. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  5329. * value, which should start at the original media sequence value (or 0) and increment by 1
  5330. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  5331. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  5332. * from a 0 mediaSequence value and increment from there.
  5333. *
  5334. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  5335. * debugging and making sense of the manifest.
  5336. *
  5337. * For live playlists, to account for values increasing in manifests when periods are
  5338. * removed on refreshes, merging logic should be used to update the numbers to their
  5339. * appropriate values (to ensure they're sequential and increasing).
  5340. *
  5341. * @param {Object[]} playlists - the playlists to update
  5342. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  5343. */
  5344. const addMediaSequenceValues = (playlists, timelineStarts) => {
  5345. // increment all segments sequentially
  5346. playlists.forEach(playlist => {
  5347. playlist.mediaSequence = 0;
  5348. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  5349. timeline
  5350. }) {
  5351. return timeline === playlist.timeline;
  5352. });
  5353. if (!playlist.segments) {
  5354. return;
  5355. }
  5356. playlist.segments.forEach((segment, index) => {
  5357. segment.number = index;
  5358. });
  5359. });
  5360. };
  5361. /**
  5362. * Given a media group object, flattens all playlists within the media group into a single
  5363. * array.
  5364. *
  5365. * @param {Object} mediaGroupObject - the media group object
  5366. *
  5367. * @return {Object[]}
  5368. * The media group playlists
  5369. */
  5370. const flattenMediaGroupPlaylists = mediaGroupObject => {
  5371. if (!mediaGroupObject) {
  5372. return [];
  5373. }
  5374. return Object.keys(mediaGroupObject).reduce((acc, label) => {
  5375. const labelContents = mediaGroupObject[label];
  5376. return acc.concat(labelContents.playlists);
  5377. }, []);
  5378. };
  5379. const toM3u8 = ({
  5380. dashPlaylists,
  5381. locations,
  5382. sidxMapping = {},
  5383. previousManifest
  5384. }) => {
  5385. if (!dashPlaylists.length) {
  5386. return {};
  5387. } // grab all main manifest attributes
  5388. const {
  5389. sourceDuration: duration,
  5390. type,
  5391. suggestedPresentationDelay,
  5392. minimumUpdatePeriod
  5393. } = dashPlaylists[0].attributes;
  5394. const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  5395. const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  5396. const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  5397. const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);
  5398. const manifest = {
  5399. allowCache: true,
  5400. discontinuityStarts: [],
  5401. segments: [],
  5402. endList: true,
  5403. mediaGroups: {
  5404. AUDIO: {},
  5405. VIDEO: {},
  5406. ['CLOSED-CAPTIONS']: {},
  5407. SUBTITLES: {}
  5408. },
  5409. uri: '',
  5410. duration,
  5411. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  5412. };
  5413. if (minimumUpdatePeriod >= 0) {
  5414. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  5415. }
  5416. if (locations) {
  5417. manifest.locations = locations;
  5418. }
  5419. if (type === 'dynamic') {
  5420. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  5421. }
  5422. const isAudioOnly = manifest.playlists.length === 0;
  5423. const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  5424. const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  5425. const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  5426. const playlistTimelineStarts = formattedPlaylists.map(({
  5427. timelineStarts
  5428. }) => timelineStarts);
  5429. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  5430. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  5431. if (organizedAudioGroup) {
  5432. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  5433. }
  5434. if (organizedVttGroup) {
  5435. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  5436. }
  5437. if (captions.length) {
  5438. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  5439. }
  5440. if (previousManifest) {
  5441. return positionManifestOnTimeline({
  5442. oldManifest: previousManifest,
  5443. newManifest: manifest
  5444. });
  5445. }
  5446. return manifest;
  5447. };
  5448. /**
  5449. * Calculates the R (repetition) value for a live stream (for the final segment
  5450. * in a manifest where the r value is negative 1)
  5451. *
  5452. * @param {Object} attributes
  5453. * Object containing all inherited attributes from parent elements with attribute
  5454. * names as keys
  5455. * @param {number} time
  5456. * current time (typically the total time up until the final segment)
  5457. * @param {number} duration
  5458. * duration property for the given <S />
  5459. *
  5460. * @return {number}
  5461. * R value to reach the end of the given period
  5462. */
  5463. const getLiveRValue = (attributes, time, duration) => {
  5464. const {
  5465. NOW,
  5466. clientOffset,
  5467. availabilityStartTime,
  5468. timescale = 1,
  5469. periodStart = 0,
  5470. minimumUpdatePeriod = 0
  5471. } = attributes;
  5472. const now = (NOW + clientOffset) / 1000;
  5473. const periodStartWC = availabilityStartTime + periodStart;
  5474. const periodEndWC = now + minimumUpdatePeriod;
  5475. const periodDuration = periodEndWC - periodStartWC;
  5476. return Math.ceil((periodDuration * timescale - time) / duration);
  5477. };
  5478. /**
  5479. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  5480. * timing and duration
  5481. *
  5482. * @param {Object} attributes
  5483. * Object containing all inherited attributes from parent elements with attribute
  5484. * names as keys
  5485. * @param {Object[]} segmentTimeline
  5486. * List of objects representing the attributes of each S element contained within
  5487. *
  5488. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  5489. * List of Objects with segment timing and duration info
  5490. */
  5491. const parseByTimeline = (attributes, segmentTimeline) => {
  5492. const {
  5493. type,
  5494. minimumUpdatePeriod = 0,
  5495. media = '',
  5496. sourceDuration,
  5497. timescale = 1,
  5498. startNumber = 1,
  5499. periodStart: timeline
  5500. } = attributes;
  5501. const segments = [];
  5502. let time = -1;
  5503. for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  5504. const S = segmentTimeline[sIndex];
  5505. const duration = S.d;
  5506. const repeat = S.r || 0;
  5507. const segmentTime = S.t || 0;
  5508. if (time < 0) {
  5509. // first segment
  5510. time = segmentTime;
  5511. }
  5512. if (segmentTime && segmentTime > time) {
  5513. // discontinuity
  5514. // TODO: How to handle this type of discontinuity
  5515. // timeline++ here would treat it like HLS discontuity and content would
  5516. // get appended without gap
  5517. // E.G.
  5518. // <S t="0" d="1" />
  5519. // <S d="1" />
  5520. // <S d="1" />
  5521. // <S t="5" d="1" />
  5522. // would have $Time$ values of [0, 1, 2, 5]
  5523. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  5524. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  5525. // does the value of sourceDuration consider this when calculating arbitrary
  5526. // negative @r repeat value?
  5527. // E.G. Same elements as above with this added at the end
  5528. // <S d="1" r="-1" />
  5529. // with a sourceDuration of 10
  5530. // Would the 2 gaps be included in the time duration calculations resulting in
  5531. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  5532. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  5533. time = segmentTime;
  5534. }
  5535. let count;
  5536. if (repeat < 0) {
  5537. const nextS = sIndex + 1;
  5538. if (nextS === segmentTimeline.length) {
  5539. // last segment
  5540. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  5541. count = getLiveRValue(attributes, time, duration);
  5542. } else {
  5543. // TODO: This may be incorrect depending on conclusion of TODO above
  5544. count = (sourceDuration * timescale - time) / duration;
  5545. }
  5546. } else {
  5547. count = (segmentTimeline[nextS].t - time) / duration;
  5548. }
  5549. } else {
  5550. count = repeat + 1;
  5551. }
  5552. const end = startNumber + segments.length + count;
  5553. let number = startNumber + segments.length;
  5554. while (number < end) {
  5555. segments.push({
  5556. number,
  5557. duration: duration / timescale,
  5558. time,
  5559. timeline
  5560. });
  5561. time += duration;
  5562. number++;
  5563. }
  5564. }
  5565. return segments;
  5566. };
  5567. const identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  5568. /**
  5569. * Replaces template identifiers with corresponding values. To be used as the callback
  5570. * for String.prototype.replace
  5571. *
  5572. * @name replaceCallback
  5573. * @function
  5574. * @param {string} match
  5575. * Entire match of identifier
  5576. * @param {string} identifier
  5577. * Name of matched identifier
  5578. * @param {string} format
  5579. * Format tag string. Its presence indicates that padding is expected
  5580. * @param {string} width
  5581. * Desired length of the replaced value. Values less than this width shall be left
  5582. * zero padded
  5583. * @return {string}
  5584. * Replacement for the matched identifier
  5585. */
  5586. /**
  5587. * Returns a function to be used as a callback for String.prototype.replace to replace
  5588. * template identifiers
  5589. *
  5590. * @param {Obect} values
  5591. * Object containing values that shall be used to replace known identifiers
  5592. * @param {number} values.RepresentationID
  5593. * Value of the Representation@id attribute
  5594. * @param {number} values.Number
  5595. * Number of the corresponding segment
  5596. * @param {number} values.Bandwidth
  5597. * Value of the Representation@bandwidth attribute.
  5598. * @param {number} values.Time
  5599. * Timestamp value of the corresponding segment
  5600. * @return {replaceCallback}
  5601. * Callback to be used with String.prototype.replace to replace identifiers
  5602. */
  5603. const identifierReplacement = values => (match, identifier, format, width) => {
  5604. if (match === '$$') {
  5605. // escape sequence
  5606. return '$';
  5607. }
  5608. if (typeof values[identifier] === 'undefined') {
  5609. return match;
  5610. }
  5611. const value = '' + values[identifier];
  5612. if (identifier === 'RepresentationID') {
  5613. // Format tag shall not be present with RepresentationID
  5614. return value;
  5615. }
  5616. if (!format) {
  5617. width = 1;
  5618. } else {
  5619. width = parseInt(width, 10);
  5620. }
  5621. if (value.length >= width) {
  5622. return value;
  5623. }
  5624. return `${new Array(width - value.length + 1).join('0')}${value}`;
  5625. };
  5626. /**
  5627. * Constructs a segment url from a template string
  5628. *
  5629. * @param {string} url
  5630. * Template string to construct url from
  5631. * @param {Obect} values
  5632. * Object containing values that shall be used to replace known identifiers
  5633. * @param {number} values.RepresentationID
  5634. * Value of the Representation@id attribute
  5635. * @param {number} values.Number
  5636. * Number of the corresponding segment
  5637. * @param {number} values.Bandwidth
  5638. * Value of the Representation@bandwidth attribute.
  5639. * @param {number} values.Time
  5640. * Timestamp value of the corresponding segment
  5641. * @return {string}
  5642. * Segment url with identifiers replaced
  5643. */
  5644. const constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));
  5645. /**
  5646. * Generates a list of objects containing timing and duration information about each
  5647. * segment needed to generate segment uris and the complete segment object
  5648. *
  5649. * @param {Object} attributes
  5650. * Object containing all inherited attributes from parent elements with attribute
  5651. * names as keys
  5652. * @param {Object[]|undefined} segmentTimeline
  5653. * List of objects representing the attributes of each S element contained within
  5654. * the SegmentTimeline element
  5655. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  5656. * List of Objects with segment timing and duration info
  5657. */
  5658. const parseTemplateInfo = (attributes, segmentTimeline) => {
  5659. if (!attributes.duration && !segmentTimeline) {
  5660. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  5661. // one media segment
  5662. return [{
  5663. number: attributes.startNumber || 1,
  5664. duration: attributes.sourceDuration,
  5665. time: 0,
  5666. timeline: attributes.periodStart
  5667. }];
  5668. }
  5669. if (attributes.duration) {
  5670. return parseByDuration(attributes);
  5671. }
  5672. return parseByTimeline(attributes, segmentTimeline);
  5673. };
  5674. /**
  5675. * Generates a list of segments using information provided by the SegmentTemplate element
  5676. *
  5677. * @param {Object} attributes
  5678. * Object containing all inherited attributes from parent elements with attribute
  5679. * names as keys
  5680. * @param {Object[]|undefined} segmentTimeline
  5681. * List of objects representing the attributes of each S element contained within
  5682. * the SegmentTimeline element
  5683. * @return {Object[]}
  5684. * List of segment objects
  5685. */
  5686. const segmentsFromTemplate = (attributes, segmentTimeline) => {
  5687. const templateValues = {
  5688. RepresentationID: attributes.id,
  5689. Bandwidth: attributes.bandwidth || 0
  5690. };
  5691. const {
  5692. initialization = {
  5693. sourceURL: '',
  5694. range: ''
  5695. }
  5696. } = attributes;
  5697. const mapSegment = urlTypeToSegment({
  5698. baseUrl: attributes.baseUrl,
  5699. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  5700. range: initialization.range
  5701. });
  5702. const segments = parseTemplateInfo(attributes, segmentTimeline);
  5703. return segments.map(segment => {
  5704. templateValues.Number = segment.number;
  5705. templateValues.Time = segment.time;
  5706. const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  5707. // - if timescale isn't present on any level, default to 1.
  5708. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  5709. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  5710. const presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is
  5711. // calculated in mpd-parser prior to this, so it's assumed to be available.
  5712. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  5713. const map = {
  5714. uri,
  5715. timeline: segment.timeline,
  5716. duration: segment.duration,
  5717. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  5718. map: mapSegment,
  5719. number: segment.number,
  5720. presentationTime
  5721. };
  5722. return map;
  5723. });
  5724. };
  5725. /**
  5726. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  5727. * to an object that matches the output of a segment in videojs/mpd-parser
  5728. *
  5729. * @param {Object} attributes
  5730. * Object containing all inherited attributes from parent elements with attribute
  5731. * names as keys
  5732. * @param {Object} segmentUrl
  5733. * <SegmentURL> node to translate into a segment object
  5734. * @return {Object} translated segment object
  5735. */
  5736. const SegmentURLToSegmentObject = (attributes, segmentUrl) => {
  5737. const {
  5738. baseUrl,
  5739. initialization = {}
  5740. } = attributes;
  5741. const initSegment = urlTypeToSegment({
  5742. baseUrl,
  5743. source: initialization.sourceURL,
  5744. range: initialization.range
  5745. });
  5746. const segment = urlTypeToSegment({
  5747. baseUrl,
  5748. source: segmentUrl.media,
  5749. range: segmentUrl.mediaRange
  5750. });
  5751. segment.map = initSegment;
  5752. return segment;
  5753. };
  5754. /**
  5755. * Generates a list of segments using information provided by the SegmentList element
  5756. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  5757. * node should be translated into segment.
  5758. *
  5759. * @param {Object} attributes
  5760. * Object containing all inherited attributes from parent elements with attribute
  5761. * names as keys
  5762. * @param {Object[]|undefined} segmentTimeline
  5763. * List of objects representing the attributes of each S element contained within
  5764. * the SegmentTimeline element
  5765. * @return {Object.<Array>} list of segments
  5766. */
  5767. const segmentsFromList = (attributes, segmentTimeline) => {
  5768. const {
  5769. duration,
  5770. segmentUrls = [],
  5771. periodStart
  5772. } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  5773. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  5774. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  5775. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  5776. }
  5777. const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));
  5778. let segmentTimeInfo;
  5779. if (duration) {
  5780. segmentTimeInfo = parseByDuration(attributes);
  5781. }
  5782. if (segmentTimeline) {
  5783. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  5784. }
  5785. const segments = segmentTimeInfo.map((segmentTime, index) => {
  5786. if (segmentUrlMap[index]) {
  5787. const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  5788. // - if timescale isn't present on any level, default to 1.
  5789. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  5790. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  5791. segment.timeline = segmentTime.timeline;
  5792. segment.duration = segmentTime.duration;
  5793. segment.number = segmentTime.number;
  5794. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  5795. return segment;
  5796. } // Since we're mapping we should get rid of any blank segments (in case
  5797. // the given SegmentTimeline is handling for more elements than we have
  5798. // SegmentURLs for).
  5799. }).filter(segment => segment);
  5800. return segments;
  5801. };
  5802. const generateSegments = ({
  5803. attributes,
  5804. segmentInfo
  5805. }) => {
  5806. let segmentAttributes;
  5807. let segmentsFn;
  5808. if (segmentInfo.template) {
  5809. segmentsFn = segmentsFromTemplate;
  5810. segmentAttributes = merge(attributes, segmentInfo.template);
  5811. } else if (segmentInfo.base) {
  5812. segmentsFn = segmentsFromBase;
  5813. segmentAttributes = merge(attributes, segmentInfo.base);
  5814. } else if (segmentInfo.list) {
  5815. segmentsFn = segmentsFromList;
  5816. segmentAttributes = merge(attributes, segmentInfo.list);
  5817. }
  5818. const segmentsInfo = {
  5819. attributes
  5820. };
  5821. if (!segmentsFn) {
  5822. return segmentsInfo;
  5823. }
  5824. const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  5825. // must be in seconds. Since we've generated the segment list, we no longer need
  5826. // @duration to be in @timescale units, so we can convert it here.
  5827. if (segmentAttributes.duration) {
  5828. const {
  5829. duration,
  5830. timescale = 1
  5831. } = segmentAttributes;
  5832. segmentAttributes.duration = duration / timescale;
  5833. } else if (segments.length) {
  5834. // if there is no @duration attribute, use the largest segment duration as
  5835. // as target duration
  5836. segmentAttributes.duration = segments.reduce((max, segment) => {
  5837. return Math.max(max, Math.ceil(segment.duration));
  5838. }, 0);
  5839. } else {
  5840. segmentAttributes.duration = 0;
  5841. }
  5842. segmentsInfo.attributes = segmentAttributes;
  5843. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  5844. if (segmentInfo.base && segmentAttributes.indexRange) {
  5845. segmentsInfo.sidx = segments[0];
  5846. segmentsInfo.segments = [];
  5847. }
  5848. return segmentsInfo;
  5849. };
  5850. const toPlaylists = representations => representations.map(generateSegments);
  5851. const findChildren = (element, name) => from(element.childNodes).filter(({
  5852. tagName
  5853. }) => tagName === name);
  5854. const getContent = element => element.textContent.trim();
  5855. /**
  5856. * Converts the provided string that may contain a division operation to a number.
  5857. *
  5858. * @param {string} value - the provided string value
  5859. *
  5860. * @return {number} the parsed string value
  5861. */
  5862. const parseDivisionValue = value => {
  5863. return parseFloat(value.split('/').reduce((prev, current) => prev / current));
  5864. };
  5865. const parseDuration = str => {
  5866. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  5867. const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  5868. const SECONDS_IN_DAY = 24 * 60 * 60;
  5869. const SECONDS_IN_HOUR = 60 * 60;
  5870. const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  5871. const durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  5872. const match = durationRegex.exec(str);
  5873. if (!match) {
  5874. return 0;
  5875. }
  5876. const [year, month, day, hour, minute, second] = match.slice(1);
  5877. 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);
  5878. };
  5879. const parseDate = str => {
  5880. // Date format without timezone according to ISO 8601
  5881. // YYY-MM-DDThh:mm:ss.ssssss
  5882. 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
  5883. // expressed by ending with 'Z'
  5884. if (dateRegex.test(str)) {
  5885. str += 'Z';
  5886. }
  5887. return Date.parse(str);
  5888. };
  5889. const parsers = {
  5890. /**
  5891. * Specifies the duration of the entire Media Presentation. Format is a duration string
  5892. * as specified in ISO 8601
  5893. *
  5894. * @param {string} value
  5895. * value of attribute as a string
  5896. * @return {number}
  5897. * The duration in seconds
  5898. */
  5899. mediaPresentationDuration(value) {
  5900. return parseDuration(value);
  5901. },
  5902. /**
  5903. * Specifies the Segment availability start time for all Segments referred to in this
  5904. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  5905. * time. Format is a date string as specified in ISO 8601
  5906. *
  5907. * @param {string} value
  5908. * value of attribute as a string
  5909. * @return {number}
  5910. * The date as seconds from unix epoch
  5911. */
  5912. availabilityStartTime(value) {
  5913. return parseDate(value) / 1000;
  5914. },
  5915. /**
  5916. * Specifies the smallest period between potential changes to the MPD. Format is a
  5917. * duration string as specified in ISO 8601
  5918. *
  5919. * @param {string} value
  5920. * value of attribute as a string
  5921. * @return {number}
  5922. * The duration in seconds
  5923. */
  5924. minimumUpdatePeriod(value) {
  5925. return parseDuration(value);
  5926. },
  5927. /**
  5928. * Specifies the suggested presentation delay. Format is a
  5929. * duration string as specified in ISO 8601
  5930. *
  5931. * @param {string} value
  5932. * value of attribute as a string
  5933. * @return {number}
  5934. * The duration in seconds
  5935. */
  5936. suggestedPresentationDelay(value) {
  5937. return parseDuration(value);
  5938. },
  5939. /**
  5940. * specifices the type of mpd. Can be either "static" or "dynamic"
  5941. *
  5942. * @param {string} value
  5943. * value of attribute as a string
  5944. *
  5945. * @return {string}
  5946. * The type as a string
  5947. */
  5948. type(value) {
  5949. return value;
  5950. },
  5951. /**
  5952. * Specifies the duration of the smallest time shifting buffer for any Representation
  5953. * in the MPD. Format is a duration string as specified in ISO 8601
  5954. *
  5955. * @param {string} value
  5956. * value of attribute as a string
  5957. * @return {number}
  5958. * The duration in seconds
  5959. */
  5960. timeShiftBufferDepth(value) {
  5961. return parseDuration(value);
  5962. },
  5963. /**
  5964. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  5965. * Format is a duration string as specified in ISO 8601
  5966. *
  5967. * @param {string} value
  5968. * value of attribute as a string
  5969. * @return {number}
  5970. * The duration in seconds
  5971. */
  5972. start(value) {
  5973. return parseDuration(value);
  5974. },
  5975. /**
  5976. * Specifies the width of the visual presentation
  5977. *
  5978. * @param {string} value
  5979. * value of attribute as a string
  5980. * @return {number}
  5981. * The parsed width
  5982. */
  5983. width(value) {
  5984. return parseInt(value, 10);
  5985. },
  5986. /**
  5987. * Specifies the height of the visual presentation
  5988. *
  5989. * @param {string} value
  5990. * value of attribute as a string
  5991. * @return {number}
  5992. * The parsed height
  5993. */
  5994. height(value) {
  5995. return parseInt(value, 10);
  5996. },
  5997. /**
  5998. * Specifies the bitrate of the representation
  5999. *
  6000. * @param {string} value
  6001. * value of attribute as a string
  6002. * @return {number}
  6003. * The parsed bandwidth
  6004. */
  6005. bandwidth(value) {
  6006. return parseInt(value, 10);
  6007. },
  6008. /**
  6009. * Specifies the frame rate of the representation
  6010. *
  6011. * @param {string} value
  6012. * value of attribute as a string
  6013. * @return {number}
  6014. * The parsed frame rate
  6015. */
  6016. frameRate(value) {
  6017. return parseDivisionValue(value);
  6018. },
  6019. /**
  6020. * Specifies the number of the first Media Segment in this Representation in the Period
  6021. *
  6022. * @param {string} value
  6023. * value of attribute as a string
  6024. * @return {number}
  6025. * The parsed number
  6026. */
  6027. startNumber(value) {
  6028. return parseInt(value, 10);
  6029. },
  6030. /**
  6031. * Specifies the timescale in units per seconds
  6032. *
  6033. * @param {string} value
  6034. * value of attribute as a string
  6035. * @return {number}
  6036. * The parsed timescale
  6037. */
  6038. timescale(value) {
  6039. return parseInt(value, 10);
  6040. },
  6041. /**
  6042. * Specifies the presentationTimeOffset.
  6043. *
  6044. * @param {string} value
  6045. * value of the attribute as a string
  6046. *
  6047. * @return {number}
  6048. * The parsed presentationTimeOffset
  6049. */
  6050. presentationTimeOffset(value) {
  6051. return parseInt(value, 10);
  6052. },
  6053. /**
  6054. * Specifies the constant approximate Segment duration
  6055. * NOTE: The <Period> element also contains an @duration attribute. This duration
  6056. * specifies the duration of the Period. This attribute is currently not
  6057. * supported by the rest of the parser, however we still check for it to prevent
  6058. * errors.
  6059. *
  6060. * @param {string} value
  6061. * value of attribute as a string
  6062. * @return {number}
  6063. * The parsed duration
  6064. */
  6065. duration(value) {
  6066. const parsedValue = parseInt(value, 10);
  6067. if (isNaN(parsedValue)) {
  6068. return parseDuration(value);
  6069. }
  6070. return parsedValue;
  6071. },
  6072. /**
  6073. * Specifies the Segment duration, in units of the value of the @timescale.
  6074. *
  6075. * @param {string} value
  6076. * value of attribute as a string
  6077. * @return {number}
  6078. * The parsed duration
  6079. */
  6080. d(value) {
  6081. return parseInt(value, 10);
  6082. },
  6083. /**
  6084. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  6085. * starts relative to the beginning of the Period
  6086. *
  6087. * @param {string} value
  6088. * value of attribute as a string
  6089. * @return {number}
  6090. * The parsed time
  6091. */
  6092. t(value) {
  6093. return parseInt(value, 10);
  6094. },
  6095. /**
  6096. * Specifies the repeat count of the number of following contiguous Segments with the
  6097. * same duration expressed by the value of @d
  6098. *
  6099. * @param {string} value
  6100. * value of attribute as a string
  6101. * @return {number}
  6102. * The parsed number
  6103. */
  6104. r(value) {
  6105. return parseInt(value, 10);
  6106. },
  6107. /**
  6108. * Default parser for all other attributes. Acts as a no-op and just returns the value
  6109. * as a string
  6110. *
  6111. * @param {string} value
  6112. * value of attribute as a string
  6113. * @return {string}
  6114. * Unparsed value
  6115. */
  6116. DEFAULT(value) {
  6117. return value;
  6118. }
  6119. };
  6120. /**
  6121. * Gets all the attributes and values of the provided node, parses attributes with known
  6122. * types, and returns an object with attribute names mapped to values.
  6123. *
  6124. * @param {Node} el
  6125. * The node to parse attributes from
  6126. * @return {Object}
  6127. * Object with all attributes of el parsed
  6128. */
  6129. const parseAttributes = el => {
  6130. if (!(el && el.attributes)) {
  6131. return {};
  6132. }
  6133. return from(el.attributes).reduce((a, e) => {
  6134. const parseFn = parsers[e.name] || parsers.DEFAULT;
  6135. a[e.name] = parseFn(e.value);
  6136. return a;
  6137. }, {});
  6138. };
  6139. const keySystemsMap = {
  6140. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  6141. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  6142. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  6143. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  6144. };
  6145. /**
  6146. * Builds a list of urls that is the product of the reference urls and BaseURL values
  6147. *
  6148. * @param {string[]} referenceUrls
  6149. * List of reference urls to resolve to
  6150. * @param {Node[]} baseUrlElements
  6151. * List of BaseURL nodes from the mpd
  6152. * @return {string[]}
  6153. * List of resolved urls
  6154. */
  6155. const buildBaseUrls = (referenceUrls, baseUrlElements) => {
  6156. if (!baseUrlElements.length) {
  6157. return referenceUrls;
  6158. }
  6159. return flatten(referenceUrls.map(function (reference) {
  6160. return baseUrlElements.map(function (baseUrlElement) {
  6161. return resolveUrl$1(reference, getContent(baseUrlElement));
  6162. });
  6163. }));
  6164. };
  6165. /**
  6166. * Contains all Segment information for its containing AdaptationSet
  6167. *
  6168. * @typedef {Object} SegmentInformation
  6169. * @property {Object|undefined} template
  6170. * Contains the attributes for the SegmentTemplate node
  6171. * @property {Object[]|undefined} segmentTimeline
  6172. * Contains a list of atrributes for each S node within the SegmentTimeline node
  6173. * @property {Object|undefined} list
  6174. * Contains the attributes for the SegmentList node
  6175. * @property {Object|undefined} base
  6176. * Contains the attributes for the SegmentBase node
  6177. */
  6178. /**
  6179. * Returns all available Segment information contained within the AdaptationSet node
  6180. *
  6181. * @param {Node} adaptationSet
  6182. * The AdaptationSet node to get Segment information from
  6183. * @return {SegmentInformation}
  6184. * The Segment information contained within the provided AdaptationSet
  6185. */
  6186. const getSegmentInformation = adaptationSet => {
  6187. const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  6188. const segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  6189. const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge({
  6190. tag: 'SegmentURL'
  6191. }, parseAttributes(s)));
  6192. const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  6193. const segmentTimelineParentNode = segmentList || segmentTemplate;
  6194. const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  6195. const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  6196. const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  6197. // @initialization and an <Initialization> node. @initialization can be templated,
  6198. // while the node can have a url and range specified. If the <SegmentTemplate> has
  6199. // both @initialization and an <Initialization> subelement we opt to override with
  6200. // the node, as this interaction is not defined in the spec.
  6201. const template = segmentTemplate && parseAttributes(segmentTemplate);
  6202. if (template && segmentInitialization) {
  6203. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  6204. } else if (template && template.initialization) {
  6205. // If it is @initialization we convert it to an object since this is the format that
  6206. // later functions will rely on for the initialization segment. This is only valid
  6207. // for <SegmentTemplate>
  6208. template.initialization = {
  6209. sourceURL: template.initialization
  6210. };
  6211. }
  6212. const segmentInfo = {
  6213. template,
  6214. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),
  6215. list: segmentList && merge(parseAttributes(segmentList), {
  6216. segmentUrls,
  6217. initialization: parseAttributes(segmentInitialization)
  6218. }),
  6219. base: segmentBase && merge(parseAttributes(segmentBase), {
  6220. initialization: parseAttributes(segmentInitialization)
  6221. })
  6222. };
  6223. Object.keys(segmentInfo).forEach(key => {
  6224. if (!segmentInfo[key]) {
  6225. delete segmentInfo[key];
  6226. }
  6227. });
  6228. return segmentInfo;
  6229. };
  6230. /**
  6231. * Contains Segment information and attributes needed to construct a Playlist object
  6232. * from a Representation
  6233. *
  6234. * @typedef {Object} RepresentationInformation
  6235. * @property {SegmentInformation} segmentInfo
  6236. * Segment information for this Representation
  6237. * @property {Object} attributes
  6238. * Inherited attributes for this Representation
  6239. */
  6240. /**
  6241. * Maps a Representation node to an object containing Segment information and attributes
  6242. *
  6243. * @name inheritBaseUrlsCallback
  6244. * @function
  6245. * @param {Node} representation
  6246. * Representation node from the mpd
  6247. * @return {RepresentationInformation}
  6248. * Representation information needed to construct a Playlist object
  6249. */
  6250. /**
  6251. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  6252. * Segment information and attributes using inherited BaseURL nodes.
  6253. *
  6254. * @param {Object} adaptationSetAttributes
  6255. * Contains attributes inherited by the AdaptationSet
  6256. * @param {string[]} adaptationSetBaseUrls
  6257. * Contains list of resolved base urls inherited by the AdaptationSet
  6258. * @param {SegmentInformation} adaptationSetSegmentInfo
  6259. * Contains Segment information for the AdaptationSet
  6260. * @return {inheritBaseUrlsCallback}
  6261. * Callback map function
  6262. */
  6263. const inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {
  6264. const repBaseUrlElements = findChildren(representation, 'BaseURL');
  6265. const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  6266. const attributes = merge(adaptationSetAttributes, parseAttributes(representation));
  6267. const representationSegmentInfo = getSegmentInformation(representation);
  6268. return repBaseUrls.map(baseUrl => {
  6269. return {
  6270. segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
  6271. attributes: merge(attributes, {
  6272. baseUrl
  6273. })
  6274. };
  6275. });
  6276. };
  6277. /**
  6278. * Tranforms a series of content protection nodes to
  6279. * an object containing pssh data by key system
  6280. *
  6281. * @param {Node[]} contentProtectionNodes
  6282. * Content protection nodes
  6283. * @return {Object}
  6284. * Object containing pssh data by key system
  6285. */
  6286. const generateKeySystemInformation = contentProtectionNodes => {
  6287. return contentProtectionNodes.reduce((acc, node) => {
  6288. 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
  6289. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  6290. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  6291. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  6292. if (attributes.schemeIdUri) {
  6293. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  6294. }
  6295. const keySystem = keySystemsMap[attributes.schemeIdUri];
  6296. if (keySystem) {
  6297. acc[keySystem] = {
  6298. attributes
  6299. };
  6300. const psshNode = findChildren(node, 'cenc:pssh')[0];
  6301. if (psshNode) {
  6302. const pssh = getContent(psshNode);
  6303. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  6304. }
  6305. }
  6306. return acc;
  6307. }, {});
  6308. }; // defined in ANSI_SCTE 214-1 2016
  6309. const parseCaptionServiceMetadata = service => {
  6310. // 608 captions
  6311. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  6312. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6313. return values.map(value => {
  6314. let channel;
  6315. let language; // default language to value
  6316. language = value;
  6317. if (/^CC\d=/.test(value)) {
  6318. [channel, language] = value.split('=');
  6319. } else if (/^CC\d$/.test(value)) {
  6320. channel = value;
  6321. }
  6322. return {
  6323. channel,
  6324. language
  6325. };
  6326. });
  6327. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  6328. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6329. return values.map(value => {
  6330. const flags = {
  6331. // service or channel number 1-63
  6332. 'channel': undefined,
  6333. // language is a 3ALPHA per ISO 639.2/B
  6334. // field is required
  6335. 'language': undefined,
  6336. // BIT 1/0 or ?
  6337. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  6338. 'aspectRatio': 1,
  6339. // BIT 1/0
  6340. // easy reader flag indicated the text is tailed to the needs of beginning readers
  6341. // default 0, or off
  6342. 'easyReader': 0,
  6343. // BIT 1/0
  6344. // If 3d metadata is present (CEA-708.1) then 1
  6345. // default 0
  6346. '3D': 0
  6347. };
  6348. if (/=/.test(value)) {
  6349. const [channel, opts = ''] = value.split('=');
  6350. flags.channel = channel;
  6351. flags.language = value;
  6352. opts.split(',').forEach(opt => {
  6353. const [name, val] = opt.split(':');
  6354. if (name === 'lang') {
  6355. flags.language = val; // er for easyReadery
  6356. } else if (name === 'er') {
  6357. flags.easyReader = Number(val); // war for wide aspect ratio
  6358. } else if (name === 'war') {
  6359. flags.aspectRatio = Number(val);
  6360. } else if (name === '3D') {
  6361. flags['3D'] = Number(val);
  6362. }
  6363. });
  6364. } else {
  6365. flags.language = value;
  6366. }
  6367. if (flags.channel) {
  6368. flags.channel = 'SERVICE' + flags.channel;
  6369. }
  6370. return flags;
  6371. });
  6372. }
  6373. };
  6374. /**
  6375. * Maps an AdaptationSet node to a list of Representation information objects
  6376. *
  6377. * @name toRepresentationsCallback
  6378. * @function
  6379. * @param {Node} adaptationSet
  6380. * AdaptationSet node from the mpd
  6381. * @return {RepresentationInformation[]}
  6382. * List of objects containing Representaion information
  6383. */
  6384. /**
  6385. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  6386. * Representation information objects
  6387. *
  6388. * @param {Object} periodAttributes
  6389. * Contains attributes inherited by the Period
  6390. * @param {string[]} periodBaseUrls
  6391. * Contains list of resolved base urls inherited by the Period
  6392. * @param {string[]} periodSegmentInfo
  6393. * Contains Segment Information at the period level
  6394. * @return {toRepresentationsCallback}
  6395. * Callback map function
  6396. */
  6397. const toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {
  6398. const adaptationSetAttributes = parseAttributes(adaptationSet);
  6399. const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  6400. const role = findChildren(adaptationSet, 'Role')[0];
  6401. const roleAttributes = {
  6402. role: parseAttributes(role)
  6403. };
  6404. let attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
  6405. const accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  6406. const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  6407. if (captionServices) {
  6408. attrs = merge(attrs, {
  6409. captionServices
  6410. });
  6411. }
  6412. const label = findChildren(adaptationSet, 'Label')[0];
  6413. if (label && label.childNodes.length) {
  6414. const labelVal = label.childNodes[0].nodeValue.trim();
  6415. attrs = merge(attrs, {
  6416. label: labelVal
  6417. });
  6418. }
  6419. const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  6420. if (Object.keys(contentProtection).length) {
  6421. attrs = merge(attrs, {
  6422. contentProtection
  6423. });
  6424. }
  6425. const segmentInfo = getSegmentInformation(adaptationSet);
  6426. const representations = findChildren(adaptationSet, 'Representation');
  6427. const adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
  6428. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  6429. };
  6430. /**
  6431. * Contains all period information for mapping nodes onto adaptation sets.
  6432. *
  6433. * @typedef {Object} PeriodInformation
  6434. * @property {Node} period.node
  6435. * Period node from the mpd
  6436. * @property {Object} period.attributes
  6437. * Parsed period attributes from node plus any added
  6438. */
  6439. /**
  6440. * Maps a PeriodInformation object to a list of Representation information objects for all
  6441. * AdaptationSet nodes contained within the Period.
  6442. *
  6443. * @name toAdaptationSetsCallback
  6444. * @function
  6445. * @param {PeriodInformation} period
  6446. * Period object containing necessary period information
  6447. * @param {number} periodStart
  6448. * Start time of the Period within the mpd
  6449. * @return {RepresentationInformation[]}
  6450. * List of objects containing Representaion information
  6451. */
  6452. /**
  6453. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  6454. * Representation information objects
  6455. *
  6456. * @param {Object} mpdAttributes
  6457. * Contains attributes inherited by the mpd
  6458. * @param {string[]} mpdBaseUrls
  6459. * Contains list of resolved base urls inherited by the mpd
  6460. * @return {toAdaptationSetsCallback}
  6461. * Callback map function
  6462. */
  6463. const toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {
  6464. const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  6465. const periodAttributes = merge(mpdAttributes, {
  6466. periodStart: period.attributes.start
  6467. });
  6468. if (typeof period.attributes.duration === 'number') {
  6469. periodAttributes.periodDuration = period.attributes.duration;
  6470. }
  6471. const adaptationSets = findChildren(period.node, 'AdaptationSet');
  6472. const periodSegmentInfo = getSegmentInformation(period.node);
  6473. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  6474. };
  6475. /**
  6476. * Gets Period@start property for a given period.
  6477. *
  6478. * @param {Object} options
  6479. * Options object
  6480. * @param {Object} options.attributes
  6481. * Period attributes
  6482. * @param {Object} [options.priorPeriodAttributes]
  6483. * Prior period attributes (if prior period is available)
  6484. * @param {string} options.mpdType
  6485. * The MPD@type these periods came from
  6486. * @return {number|null}
  6487. * The period start, or null if it's an early available period or error
  6488. */
  6489. const getPeriodStart = ({
  6490. attributes,
  6491. priorPeriodAttributes,
  6492. mpdType
  6493. }) => {
  6494. // Summary of period start time calculation from DASH spec section 5.3.2.1
  6495. //
  6496. // A period's start is the first period's start + time elapsed after playing all
  6497. // prior periods to this one. Periods continue one after the other in time (without
  6498. // gaps) until the end of the presentation.
  6499. //
  6500. // The value of Period@start should be:
  6501. // 1. if Period@start is present: value of Period@start
  6502. // 2. if previous period exists and it has @duration: previous Period@start +
  6503. // previous Period@duration
  6504. // 3. if this is first period and MPD@type is 'static': 0
  6505. // 4. in all other cases, consider the period an "early available period" (note: not
  6506. // currently supported)
  6507. // (1)
  6508. if (typeof attributes.start === 'number') {
  6509. return attributes.start;
  6510. } // (2)
  6511. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  6512. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  6513. } // (3)
  6514. if (!priorPeriodAttributes && mpdType === 'static') {
  6515. return 0;
  6516. } // (4)
  6517. // There is currently no logic for calculating the Period@start value if there is
  6518. // no Period@start or prior Period@start and Period@duration available. This is not made
  6519. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  6520. // nothing about any other resolution strategies, it's implied. Thus, this case should
  6521. // be considered an early available period, or error, and null should suffice for both
  6522. // of those cases.
  6523. return null;
  6524. };
  6525. /**
  6526. * Traverses the mpd xml tree to generate a list of Representation information objects
  6527. * that have inherited attributes from parent nodes
  6528. *
  6529. * @param {Node} mpd
  6530. * The root node of the mpd
  6531. * @param {Object} options
  6532. * Available options for inheritAttributes
  6533. * @param {string} options.manifestUri
  6534. * The uri source of the mpd
  6535. * @param {number} options.NOW
  6536. * Current time per DASH IOP. Default is current time in ms since epoch
  6537. * @param {number} options.clientOffset
  6538. * Client time difference from NOW (in milliseconds)
  6539. * @return {RepresentationInformation[]}
  6540. * List of objects containing Representation information
  6541. */
  6542. const inheritAttributes = (mpd, options = {}) => {
  6543. const {
  6544. manifestUri = '',
  6545. NOW = Date.now(),
  6546. clientOffset = 0
  6547. } = options;
  6548. const periodNodes = findChildren(mpd, 'Period');
  6549. if (!periodNodes.length) {
  6550. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  6551. }
  6552. const locations = findChildren(mpd, 'Location');
  6553. const mpdAttributes = parseAttributes(mpd);
  6554. const mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  6555. mpdAttributes.type = mpdAttributes.type || 'static';
  6556. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  6557. mpdAttributes.NOW = NOW;
  6558. mpdAttributes.clientOffset = clientOffset;
  6559. if (locations.length) {
  6560. mpdAttributes.locations = locations.map(getContent);
  6561. }
  6562. const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  6563. // adding properties that require looking at prior periods is to parse attributes and add
  6564. // missing ones before toAdaptationSets is called. If more such properties are added, it
  6565. // may be better to refactor toAdaptationSets.
  6566. periodNodes.forEach((node, index) => {
  6567. const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  6568. // for this period.
  6569. const priorPeriod = periods[index - 1];
  6570. attributes.start = getPeriodStart({
  6571. attributes,
  6572. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  6573. mpdType: mpdAttributes.type
  6574. });
  6575. periods.push({
  6576. node,
  6577. attributes
  6578. });
  6579. });
  6580. return {
  6581. locations: mpdAttributes.locations,
  6582. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  6583. };
  6584. };
  6585. const stringToMpdXml = manifestString => {
  6586. if (manifestString === '') {
  6587. throw new Error(errors.DASH_EMPTY_MANIFEST);
  6588. }
  6589. const parser = new xmldom.DOMParser();
  6590. let xml;
  6591. let mpd;
  6592. try {
  6593. xml = parser.parseFromString(manifestString, 'application/xml');
  6594. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  6595. } catch (e) {// ie 11 throwsw on invalid xml
  6596. }
  6597. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  6598. throw new Error(errors.DASH_INVALID_XML);
  6599. }
  6600. return mpd;
  6601. };
  6602. /**
  6603. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  6604. *
  6605. * @param {string} mpd
  6606. * XML string of the MPD manifest
  6607. * @return {Object|null}
  6608. * Attributes of UTCTiming node specified in the manifest. Null if none found
  6609. */
  6610. const parseUTCTimingScheme = mpd => {
  6611. const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  6612. if (!UTCTimingNode) {
  6613. return null;
  6614. }
  6615. const attributes = parseAttributes(UTCTimingNode);
  6616. switch (attributes.schemeIdUri) {
  6617. case 'urn:mpeg:dash:utc:http-head:2014':
  6618. case 'urn:mpeg:dash:utc:http-head:2012':
  6619. attributes.method = 'HEAD';
  6620. break;
  6621. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  6622. case 'urn:mpeg:dash:utc:http-iso:2014':
  6623. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  6624. case 'urn:mpeg:dash:utc:http-iso:2012':
  6625. attributes.method = 'GET';
  6626. break;
  6627. case 'urn:mpeg:dash:utc:direct:2014':
  6628. case 'urn:mpeg:dash:utc:direct:2012':
  6629. attributes.method = 'DIRECT';
  6630. attributes.value = Date.parse(attributes.value);
  6631. break;
  6632. case 'urn:mpeg:dash:utc:http-ntp:2014':
  6633. case 'urn:mpeg:dash:utc:ntp:2014':
  6634. case 'urn:mpeg:dash:utc:sntp:2014':
  6635. default:
  6636. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  6637. }
  6638. return attributes;
  6639. };
  6640. /*
  6641. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  6642. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  6643. *
  6644. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  6645. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  6646. * updated to reflect its position relative to the prior manifest.
  6647. *
  6648. * @param {string} manifestString - the DASH manifest as a string
  6649. * @param {options} [options] - any options
  6650. *
  6651. * @return {Object} the manifest object
  6652. */
  6653. const parse = (manifestString, options = {}) => {
  6654. const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  6655. const playlists = toPlaylists(parsedManifestInfo.representationInfo);
  6656. return toM3u8({
  6657. dashPlaylists: playlists,
  6658. locations: parsedManifestInfo.locations,
  6659. sidxMapping: options.sidxMapping,
  6660. previousManifest: options.previousManifest
  6661. });
  6662. };
  6663. /**
  6664. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  6665. *
  6666. * @param {string} manifestString
  6667. * XML string of the MPD manifest
  6668. * @return {Object|null}
  6669. * Attributes of UTCTiming node specified in the manifest. Null if none found
  6670. */
  6671. const parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));
  6672. var MAX_UINT32 = Math.pow(2, 32);
  6673. var getUint64$1 = function (uint8) {
  6674. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  6675. var value;
  6676. if (dv.getBigUint64) {
  6677. value = dv.getBigUint64(0);
  6678. if (value < Number.MAX_SAFE_INTEGER) {
  6679. return Number(value);
  6680. }
  6681. return value;
  6682. }
  6683. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  6684. };
  6685. var numbers = {
  6686. getUint64: getUint64$1,
  6687. MAX_UINT32: MAX_UINT32
  6688. };
  6689. var getUint64 = numbers.getUint64;
  6690. var parseSidx = function (data) {
  6691. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  6692. result = {
  6693. version: data[0],
  6694. flags: new Uint8Array(data.subarray(1, 4)),
  6695. references: [],
  6696. referenceId: view.getUint32(4),
  6697. timescale: view.getUint32(8)
  6698. },
  6699. i = 12;
  6700. if (result.version === 0) {
  6701. result.earliestPresentationTime = view.getUint32(i);
  6702. result.firstOffset = view.getUint32(i + 4);
  6703. i += 8;
  6704. } else {
  6705. // read 64 bits
  6706. result.earliestPresentationTime = getUint64(data.subarray(i));
  6707. result.firstOffset = getUint64(data.subarray(i + 8));
  6708. i += 16;
  6709. }
  6710. i += 2; // reserved
  6711. var referenceCount = view.getUint16(i);
  6712. i += 2; // start of references
  6713. for (; referenceCount > 0; i += 12, referenceCount--) {
  6714. result.references.push({
  6715. referenceType: (data[i] & 0x80) >>> 7,
  6716. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  6717. subsegmentDuration: view.getUint32(i + 4),
  6718. startsWithSap: !!(data[i + 8] & 0x80),
  6719. sapType: (data[i + 8] & 0x70) >>> 4,
  6720. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  6721. });
  6722. }
  6723. return result;
  6724. };
  6725. var parseSidx_1 = parseSidx;
  6726. var ID3 = toUint8([0x49, 0x44, 0x33]);
  6727. var getId3Size = function getId3Size(bytes, offset) {
  6728. if (offset === void 0) {
  6729. offset = 0;
  6730. }
  6731. bytes = toUint8(bytes);
  6732. var flags = bytes[offset + 5];
  6733. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  6734. var footerPresent = (flags & 16) >> 4;
  6735. if (footerPresent) {
  6736. return returnSize + 20;
  6737. }
  6738. return returnSize + 10;
  6739. };
  6740. var getId3Offset = function getId3Offset(bytes, offset) {
  6741. if (offset === void 0) {
  6742. offset = 0;
  6743. }
  6744. bytes = toUint8(bytes);
  6745. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  6746. offset: offset
  6747. })) {
  6748. return offset;
  6749. }
  6750. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  6751. // have multiple ID3 tag sections even though
  6752. // they should not.
  6753. return getId3Offset(bytes, offset);
  6754. };
  6755. var normalizePath$1 = function normalizePath(path) {
  6756. if (typeof path === 'string') {
  6757. return stringToBytes(path);
  6758. }
  6759. if (typeof path === 'number') {
  6760. return path;
  6761. }
  6762. return path;
  6763. };
  6764. var normalizePaths$1 = function normalizePaths(paths) {
  6765. if (!Array.isArray(paths)) {
  6766. return [normalizePath$1(paths)];
  6767. }
  6768. return paths.map(function (p) {
  6769. return normalizePath$1(p);
  6770. });
  6771. };
  6772. /**
  6773. * find any number of boxes by name given a path to it in an iso bmff
  6774. * such as mp4.
  6775. *
  6776. * @param {TypedArray} bytes
  6777. * bytes for the iso bmff to search for boxes in
  6778. *
  6779. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  6780. * An array of paths or a single path representing the name
  6781. * of boxes to search through in bytes. Paths may be
  6782. * uint8 (character codes) or strings.
  6783. *
  6784. * @param {boolean} [complete=false]
  6785. * Should we search only for complete boxes on the final path.
  6786. * This is very useful when you do not want to get back partial boxes
  6787. * in the case of streaming files.
  6788. *
  6789. * @return {Uint8Array[]}
  6790. * An array of the end paths that we found.
  6791. */
  6792. var findBox = function findBox(bytes, paths, complete) {
  6793. if (complete === void 0) {
  6794. complete = false;
  6795. }
  6796. paths = normalizePaths$1(paths);
  6797. bytes = toUint8(bytes);
  6798. var results = [];
  6799. if (!paths.length) {
  6800. // short-circuit the search for empty paths
  6801. return results;
  6802. }
  6803. var i = 0;
  6804. while (i < bytes.length) {
  6805. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  6806. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  6807. if (size === 0) {
  6808. break;
  6809. }
  6810. var end = i + size;
  6811. if (end > bytes.length) {
  6812. // this box is bigger than the number of bytes we have
  6813. // and complete is set, we cannot find any more boxes.
  6814. if (complete) {
  6815. break;
  6816. }
  6817. end = bytes.length;
  6818. }
  6819. var data = bytes.subarray(i + 8, end);
  6820. if (bytesMatch(type, paths[0])) {
  6821. if (paths.length === 1) {
  6822. // this is the end of the path and we've found the box we were
  6823. // looking for
  6824. results.push(data);
  6825. } else {
  6826. // recursively search for the next box along the path
  6827. results.push.apply(results, findBox(data, paths.slice(1), complete));
  6828. }
  6829. }
  6830. i = end;
  6831. } // we've finished searching all of bytes
  6832. return results;
  6833. };
  6834. // https://matroska-org.github.io/libebml/specs.html
  6835. // https://www.matroska.org/technical/elements.html
  6836. // https://www.webmproject.org/docs/container/
  6837. var EBML_TAGS = {
  6838. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  6839. DocType: toUint8([0x42, 0x82]),
  6840. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  6841. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  6842. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  6843. Track: toUint8([0xAE]),
  6844. TrackNumber: toUint8([0xd7]),
  6845. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  6846. TrackEntry: toUint8([0xAE]),
  6847. TrackType: toUint8([0x83]),
  6848. FlagDefault: toUint8([0x88]),
  6849. CodecID: toUint8([0x86]),
  6850. CodecPrivate: toUint8([0x63, 0xA2]),
  6851. VideoTrack: toUint8([0xe0]),
  6852. AudioTrack: toUint8([0xe1]),
  6853. // Not used yet, but will be used for live webm/mkv
  6854. // see https://www.matroska.org/technical/basics.html#block-structure
  6855. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  6856. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  6857. Timestamp: toUint8([0xE7]),
  6858. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  6859. BlockGroup: toUint8([0xA0]),
  6860. BlockDuration: toUint8([0x9B]),
  6861. Block: toUint8([0xA1]),
  6862. SimpleBlock: toUint8([0xA3])
  6863. };
  6864. /**
  6865. * This is a simple table to determine the length
  6866. * of things in ebml. The length is one based (starts at 1,
  6867. * rather than zero) and for every zero bit before a one bit
  6868. * we add one to length. We also need this table because in some
  6869. * case we have to xor all the length bits from another value.
  6870. */
  6871. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  6872. var getLength = function getLength(byte) {
  6873. var len = 1;
  6874. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  6875. if (byte & LENGTH_TABLE[i]) {
  6876. break;
  6877. }
  6878. len++;
  6879. }
  6880. return len;
  6881. }; // length in ebml is stored in the first 4 to 8 bits
  6882. // of the first byte. 4 for the id length and 8 for the
  6883. // data size length. Length is measured by converting the number to binary
  6884. // then 1 + the number of zeros before a 1 is encountered starting
  6885. // from the left.
  6886. var getvint = function getvint(bytes, offset, removeLength, signed) {
  6887. if (removeLength === void 0) {
  6888. removeLength = true;
  6889. }
  6890. if (signed === void 0) {
  6891. signed = false;
  6892. }
  6893. var length = getLength(bytes[offset]);
  6894. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  6895. // as they will be modified below to remove the dataSizeLen bits and we do not
  6896. // want to modify the original data. normally we could just call slice on
  6897. // uint8array but ie 11 does not support that...
  6898. if (removeLength) {
  6899. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  6900. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  6901. }
  6902. return {
  6903. length: length,
  6904. value: bytesToNumber(valueBytes, {
  6905. signed: signed
  6906. }),
  6907. bytes: valueBytes
  6908. };
  6909. };
  6910. var normalizePath = function normalizePath(path) {
  6911. if (typeof path === 'string') {
  6912. return path.match(/.{1,2}/g).map(function (p) {
  6913. return normalizePath(p);
  6914. });
  6915. }
  6916. if (typeof path === 'number') {
  6917. return numberToBytes(path);
  6918. }
  6919. return path;
  6920. };
  6921. var normalizePaths = function normalizePaths(paths) {
  6922. if (!Array.isArray(paths)) {
  6923. return [normalizePath(paths)];
  6924. }
  6925. return paths.map(function (p) {
  6926. return normalizePath(p);
  6927. });
  6928. };
  6929. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  6930. if (offset >= bytes.length) {
  6931. return bytes.length;
  6932. }
  6933. var innerid = getvint(bytes, offset, false);
  6934. if (bytesMatch(id.bytes, innerid.bytes)) {
  6935. return offset;
  6936. }
  6937. var dataHeader = getvint(bytes, offset + innerid.length);
  6938. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  6939. };
  6940. /**
  6941. * Notes on the EBLM format.
  6942. *
  6943. * EBLM uses "vints" tags. Every vint tag contains
  6944. * two parts
  6945. *
  6946. * 1. The length from the first byte. You get this by
  6947. * converting the byte to binary and counting the zeros
  6948. * before a 1. Then you add 1 to that. Examples
  6949. * 00011111 = length 4 because there are 3 zeros before a 1.
  6950. * 00100000 = length 3 because there are 2 zeros before a 1.
  6951. * 00000011 = length 7 because there are 6 zeros before a 1.
  6952. *
  6953. * 2. The bits used for length are removed from the first byte
  6954. * Then all the bytes are merged into a value. NOTE: this
  6955. * is not the case for id ebml tags as there id includes
  6956. * length bits.
  6957. *
  6958. */
  6959. var findEbml = function findEbml(bytes, paths) {
  6960. paths = normalizePaths(paths);
  6961. bytes = toUint8(bytes);
  6962. var results = [];
  6963. if (!paths.length) {
  6964. return results;
  6965. }
  6966. var i = 0;
  6967. while (i < bytes.length) {
  6968. var id = getvint(bytes, i, false);
  6969. var dataHeader = getvint(bytes, i + id.length);
  6970. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  6971. if (dataHeader.value === 0x7f) {
  6972. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  6973. if (dataHeader.value !== bytes.length) {
  6974. dataHeader.value -= dataStart;
  6975. }
  6976. }
  6977. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  6978. var data = bytes.subarray(dataStart, dataEnd);
  6979. if (bytesMatch(paths[0], id.bytes)) {
  6980. if (paths.length === 1) {
  6981. // this is the end of the paths and we've found the tag we were
  6982. // looking for
  6983. results.push(data);
  6984. } else {
  6985. // recursively search for the next tag inside of the data
  6986. // of this one
  6987. results = results.concat(findEbml(data, paths.slice(1)));
  6988. }
  6989. }
  6990. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  6991. i += totalLength;
  6992. }
  6993. return results;
  6994. }; // see https://www.matroska.org/technical/basics.html#block-structure
  6995. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  6996. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  6997. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  6998. /**
  6999. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  7000. * Sequence Payload"
  7001. *
  7002. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  7003. * unit
  7004. * @return {Uint8Array} the RBSP without any Emulation
  7005. * Prevention Bytes
  7006. */
  7007. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  7008. var positions = [];
  7009. var i = 1; // Find all `Emulation Prevention Bytes`
  7010. while (i < bytes.length - 2) {
  7011. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  7012. positions.push(i + 2);
  7013. i++;
  7014. }
  7015. i++;
  7016. } // If no Emulation Prevention Bytes were found just return the original
  7017. // array
  7018. if (positions.length === 0) {
  7019. return bytes;
  7020. } // Create a new array to hold the NAL unit data
  7021. var newLength = bytes.length - positions.length;
  7022. var newData = new Uint8Array(newLength);
  7023. var sourceIndex = 0;
  7024. for (i = 0; i < newLength; sourceIndex++, i++) {
  7025. if (sourceIndex === positions[0]) {
  7026. // Skip this byte
  7027. sourceIndex++; // Remove this position index
  7028. positions.shift();
  7029. }
  7030. newData[i] = bytes[sourceIndex];
  7031. }
  7032. return newData;
  7033. };
  7034. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  7035. if (nalLimit === void 0) {
  7036. nalLimit = Infinity;
  7037. }
  7038. bytes = toUint8(bytes);
  7039. types = [].concat(types);
  7040. var i = 0;
  7041. var nalStart;
  7042. var nalsFound = 0; // keep searching until:
  7043. // we reach the end of bytes
  7044. // we reach the maximum number of nals they want to seach
  7045. // NOTE: that we disregard nalLimit when we have found the start
  7046. // of the nal we want so that we can find the end of the nal we want.
  7047. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  7048. var nalOffset = void 0;
  7049. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  7050. nalOffset = 4;
  7051. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  7052. nalOffset = 3;
  7053. } // we are unsynced,
  7054. // find the next nal unit
  7055. if (!nalOffset) {
  7056. i++;
  7057. continue;
  7058. }
  7059. nalsFound++;
  7060. if (nalStart) {
  7061. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  7062. }
  7063. var nalType = void 0;
  7064. if (dataType === 'h264') {
  7065. nalType = bytes[i + nalOffset] & 0x1f;
  7066. } else if (dataType === 'h265') {
  7067. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  7068. }
  7069. if (types.indexOf(nalType) !== -1) {
  7070. nalStart = i + nalOffset;
  7071. } // nal header is 1 length for h264, and 2 for h265
  7072. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  7073. }
  7074. return bytes.subarray(0, 0);
  7075. };
  7076. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  7077. return findNal(bytes, 'h264', type, nalLimit);
  7078. };
  7079. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  7080. return findNal(bytes, 'h265', type, nalLimit);
  7081. };
  7082. var CONSTANTS = {
  7083. // "webm" string literal in hex
  7084. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  7085. // "matroska" string literal in hex
  7086. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  7087. // "fLaC" string literal in hex
  7088. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  7089. // "OggS" string literal in hex
  7090. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  7091. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  7092. // of ac-3
  7093. 'ac3': toUint8([0x0b, 0x77]),
  7094. // "RIFF" string literal in hex used for wav and avi
  7095. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  7096. // "AVI" string literal in hex
  7097. 'avi': toUint8([0x41, 0x56, 0x49]),
  7098. // "WAVE" string literal in hex
  7099. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  7100. // "ftyp3g" string literal in hex
  7101. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  7102. // "ftyp" string literal in hex
  7103. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  7104. // "styp" string literal in hex
  7105. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  7106. // "ftypqt" string literal in hex
  7107. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  7108. // moov string literal in hex
  7109. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  7110. // moof string literal in hex
  7111. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  7112. };
  7113. var _isLikely = {
  7114. aac: function aac(bytes) {
  7115. var offset = getId3Offset(bytes);
  7116. return bytesMatch(bytes, [0xFF, 0x10], {
  7117. offset: offset,
  7118. mask: [0xFF, 0x16]
  7119. });
  7120. },
  7121. mp3: function mp3(bytes) {
  7122. var offset = getId3Offset(bytes);
  7123. return bytesMatch(bytes, [0xFF, 0x02], {
  7124. offset: offset,
  7125. mask: [0xFF, 0x06]
  7126. });
  7127. },
  7128. webm: function webm(bytes) {
  7129. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  7130. return bytesMatch(docType, CONSTANTS.webm);
  7131. },
  7132. mkv: function mkv(bytes) {
  7133. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  7134. return bytesMatch(docType, CONSTANTS.matroska);
  7135. },
  7136. mp4: function mp4(bytes) {
  7137. // if this file is another base media file format, it is not mp4
  7138. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  7139. return false;
  7140. } // if this file starts with a ftyp or styp box its mp4
  7141. if (bytesMatch(bytes, CONSTANTS.mp4, {
  7142. offset: 4
  7143. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  7144. offset: 4
  7145. })) {
  7146. return true;
  7147. } // if this file starts with a moof/moov box its mp4
  7148. if (bytesMatch(bytes, CONSTANTS.moof, {
  7149. offset: 4
  7150. }) || bytesMatch(bytes, CONSTANTS.moov, {
  7151. offset: 4
  7152. })) {
  7153. return true;
  7154. }
  7155. },
  7156. mov: function mov(bytes) {
  7157. return bytesMatch(bytes, CONSTANTS.mov, {
  7158. offset: 4
  7159. });
  7160. },
  7161. '3gp': function gp(bytes) {
  7162. return bytesMatch(bytes, CONSTANTS['3gp'], {
  7163. offset: 4
  7164. });
  7165. },
  7166. ac3: function ac3(bytes) {
  7167. var offset = getId3Offset(bytes);
  7168. return bytesMatch(bytes, CONSTANTS.ac3, {
  7169. offset: offset
  7170. });
  7171. },
  7172. ts: function ts(bytes) {
  7173. if (bytes.length < 189 && bytes.length >= 1) {
  7174. return bytes[0] === 0x47;
  7175. }
  7176. var i = 0; // check the first 376 bytes for two matching sync bytes
  7177. while (i + 188 < bytes.length && i < 188) {
  7178. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  7179. return true;
  7180. }
  7181. i += 1;
  7182. }
  7183. return false;
  7184. },
  7185. flac: function flac(bytes) {
  7186. var offset = getId3Offset(bytes);
  7187. return bytesMatch(bytes, CONSTANTS.flac, {
  7188. offset: offset
  7189. });
  7190. },
  7191. ogg: function ogg(bytes) {
  7192. return bytesMatch(bytes, CONSTANTS.ogg);
  7193. },
  7194. avi: function avi(bytes) {
  7195. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  7196. offset: 8
  7197. });
  7198. },
  7199. wav: function wav(bytes) {
  7200. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  7201. offset: 8
  7202. });
  7203. },
  7204. 'h264': function h264(bytes) {
  7205. // find seq_parameter_set_rbsp
  7206. return findH264Nal(bytes, 7, 3).length;
  7207. },
  7208. 'h265': function h265(bytes) {
  7209. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  7210. return findH265Nal(bytes, [32, 33], 3).length;
  7211. }
  7212. }; // get all the isLikely functions
  7213. // but make sure 'ts' is above h264 and h265
  7214. // but below everything else as it is the least specific
  7215. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  7216. .filter(function (t) {
  7217. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  7218. }) // add it back to the bottom
  7219. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  7220. isLikelyTypes.forEach(function (type) {
  7221. var isLikelyFn = _isLikely[type];
  7222. _isLikely[type] = function (bytes) {
  7223. return isLikelyFn(toUint8(bytes));
  7224. };
  7225. }); // export after wrapping
  7226. var isLikely = _isLikely; // A useful list of file signatures can be found here
  7227. // https://en.wikipedia.org/wiki/List_of_file_signatures
  7228. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  7229. bytes = toUint8(bytes);
  7230. for (var i = 0; i < isLikelyTypes.length; i++) {
  7231. var type = isLikelyTypes[i];
  7232. if (isLikely[type](bytes)) {
  7233. return type;
  7234. }
  7235. }
  7236. return '';
  7237. }; // fmp4 is not a container
  7238. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  7239. return findBox(bytes, ['moof']).length > 0;
  7240. };
  7241. // which will only happen if the request is complete.
  7242. const callbackOnCompleted = (request, cb) => {
  7243. if (request.readyState === 4) {
  7244. return cb();
  7245. }
  7246. return;
  7247. };
  7248. const containerRequest = (uri, xhr, cb) => {
  7249. let bytes = [];
  7250. let id3Offset;
  7251. let finished = false;
  7252. const endRequestAndCallback = function (err, req, type, _bytes) {
  7253. req.abort();
  7254. finished = true;
  7255. return cb(err, req, type, _bytes);
  7256. };
  7257. const progressListener = function (error, request) {
  7258. if (finished) {
  7259. return;
  7260. }
  7261. if (error) {
  7262. return endRequestAndCallback(error, request, '', bytes);
  7263. } // grap the new part of content that was just downloaded
  7264. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  7265. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  7266. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  7267. // or we need at least two bytes after an id3Offset
  7268. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  7269. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7270. }
  7271. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  7272. // to see the second sync byte, wait until we have enough data
  7273. // before declaring it ts
  7274. if (type === 'ts' && bytes.length < 188) {
  7275. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7276. } // this may be an unsynced ts segment
  7277. // wait for 376 bytes before detecting no container
  7278. if (!type && bytes.length < 376) {
  7279. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7280. }
  7281. return endRequestAndCallback(null, request, type, bytes);
  7282. };
  7283. const options = {
  7284. uri,
  7285. beforeSend(request) {
  7286. // this forces the browser to pass the bytes to us unprocessed
  7287. request.overrideMimeType('text/plain; charset=x-user-defined');
  7288. request.addEventListener('progress', function ({
  7289. total,
  7290. loaded
  7291. }) {
  7292. return callbackWrapper(request, null, {
  7293. statusCode: request.status
  7294. }, progressListener);
  7295. });
  7296. }
  7297. };
  7298. const request = xhr(options, function (error, response) {
  7299. return callbackWrapper(request, error, response, progressListener);
  7300. });
  7301. return request;
  7302. };
  7303. const {
  7304. EventTarget
  7305. } = videojs__default["default"];
  7306. const dashPlaylistUnchanged = function (a, b) {
  7307. if (!isPlaylistUnchanged(a, b)) {
  7308. return false;
  7309. } // for dash the above check will often return true in scenarios where
  7310. // the playlist actually has changed because mediaSequence isn't a
  7311. // dash thing, and we often set it to 1. So if the playlists have the same amount
  7312. // of segments we return true.
  7313. // So for dash we need to make sure that the underlying segments are different.
  7314. // if sidx changed then the playlists are different.
  7315. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  7316. return false;
  7317. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  7318. return false;
  7319. } // one or the other does not have segments
  7320. // there was a change.
  7321. if (a.segments && !b.segments || !a.segments && b.segments) {
  7322. return false;
  7323. } // neither has segments nothing changed
  7324. if (!a.segments && !b.segments) {
  7325. return true;
  7326. } // check segments themselves
  7327. for (let i = 0; i < a.segments.length; i++) {
  7328. const aSegment = a.segments[i];
  7329. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  7330. if (aSegment.uri !== bSegment.uri) {
  7331. return false;
  7332. } // neither segment has a byterange, there will be no byterange change.
  7333. if (!aSegment.byterange && !bSegment.byterange) {
  7334. continue;
  7335. }
  7336. const aByterange = aSegment.byterange;
  7337. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  7338. if (aByterange && !bByterange || !aByterange && bByterange) {
  7339. return false;
  7340. } // if both segments have byterange with different offsets, there was a change.
  7341. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  7342. return false;
  7343. }
  7344. } // if everything was the same with segments, this is the same playlist.
  7345. return true;
  7346. };
  7347. /**
  7348. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  7349. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  7350. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  7351. * periods without continuous playback this function may need modification as well as the parser.
  7352. */
  7353. const dashGroupId = (type, group, label, playlist) => {
  7354. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  7355. const playlistId = playlist.attributes.NAME || label;
  7356. return `placeholder-uri-${type}-${group}-${playlistId}`;
  7357. };
  7358. /**
  7359. * Parses the main XML string and updates playlist URI references.
  7360. *
  7361. * @param {Object} config
  7362. * Object of arguments
  7363. * @param {string} config.mainXml
  7364. * The mpd XML
  7365. * @param {string} config.srcUrl
  7366. * The mpd URL
  7367. * @param {Date} config.clientOffset
  7368. * A time difference between server and client
  7369. * @param {Object} config.sidxMapping
  7370. * SIDX mappings for moof/mdat URIs and byte ranges
  7371. * @return {Object}
  7372. * The parsed mpd manifest object
  7373. */
  7374. const parseMainXml = ({
  7375. mainXml,
  7376. srcUrl,
  7377. clientOffset,
  7378. sidxMapping,
  7379. previousManifest
  7380. }) => {
  7381. const manifest = parse(mainXml, {
  7382. manifestUri: srcUrl,
  7383. clientOffset,
  7384. sidxMapping,
  7385. previousManifest
  7386. });
  7387. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  7388. return manifest;
  7389. };
  7390. /**
  7391. * Removes any mediaGroup labels that no longer exist in the newMain
  7392. *
  7393. * @param {Object} update
  7394. * The previous mpd object being updated
  7395. * @param {Object} newMain
  7396. * The new mpd object
  7397. */
  7398. const removeOldMediaGroupLabels = (update, newMain) => {
  7399. forEachMediaGroup$1(update, (properties, type, group, label) => {
  7400. if (!(label in newMain.mediaGroups[type][group])) {
  7401. delete update.mediaGroups[type][group][label];
  7402. }
  7403. });
  7404. };
  7405. /**
  7406. * Returns a new main manifest that is the result of merging an updated main manifest
  7407. * into the original version.
  7408. *
  7409. * @param {Object} oldMain
  7410. * The old parsed mpd object
  7411. * @param {Object} newMain
  7412. * The updated parsed mpd object
  7413. * @return {Object}
  7414. * A new object representing the original main manifest with the updated media
  7415. * playlists merged in
  7416. */
  7417. const updateMain = (oldMain, newMain, sidxMapping) => {
  7418. let noChanges = true;
  7419. let update = merge$1(oldMain, {
  7420. // These are top level properties that can be updated
  7421. duration: newMain.duration,
  7422. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  7423. timelineStarts: newMain.timelineStarts
  7424. }); // First update the playlists in playlist list
  7425. for (let i = 0; i < newMain.playlists.length; i++) {
  7426. const playlist = newMain.playlists[i];
  7427. if (playlist.sidx) {
  7428. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  7429. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  7430. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  7431. }
  7432. }
  7433. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  7434. if (playlistUpdate) {
  7435. update = playlistUpdate;
  7436. noChanges = false;
  7437. }
  7438. } // Then update media group playlists
  7439. forEachMediaGroup$1(newMain, (properties, type, group, label) => {
  7440. if (properties.playlists && properties.playlists.length) {
  7441. const id = properties.playlists[0].id;
  7442. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  7443. if (playlistUpdate) {
  7444. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  7445. if (!(label in update.mediaGroups[type][group])) {
  7446. update.mediaGroups[type][group][label] = properties;
  7447. } // update the playlist reference within media groups
  7448. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  7449. noChanges = false;
  7450. }
  7451. }
  7452. }); // remove mediaGroup labels and references that no longer exist in the newMain
  7453. removeOldMediaGroupLabels(update, newMain);
  7454. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  7455. noChanges = false;
  7456. }
  7457. if (noChanges) {
  7458. return null;
  7459. }
  7460. return update;
  7461. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  7462. // If the SIDXs have maps, the two maps should match,
  7463. // both `a` and `b` missing SIDXs is considered matching.
  7464. // If `a` or `b` but not both have a map, they aren't matching.
  7465. const equivalentSidx = (a, b) => {
  7466. const neitherMap = Boolean(!a.map && !b.map);
  7467. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  7468. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  7469. }; // exported for testing
  7470. const compareSidxEntry = (playlists, oldSidxMapping) => {
  7471. const newSidxMapping = {};
  7472. for (const id in playlists) {
  7473. const playlist = playlists[id];
  7474. const currentSidxInfo = playlist.sidx;
  7475. if (currentSidxInfo) {
  7476. const key = generateSidxKey(currentSidxInfo);
  7477. if (!oldSidxMapping[key]) {
  7478. break;
  7479. }
  7480. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  7481. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  7482. newSidxMapping[key] = oldSidxMapping[key];
  7483. }
  7484. }
  7485. }
  7486. return newSidxMapping;
  7487. };
  7488. /**
  7489. * A function that filters out changed items as they need to be requested separately.
  7490. *
  7491. * The method is exported for testing
  7492. *
  7493. * @param {Object} main the parsed mpd XML returned via mpd-parser
  7494. * @param {Object} oldSidxMapping the SIDX to compare against
  7495. */
  7496. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  7497. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  7498. let mediaGroupSidx = videoSidx;
  7499. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  7500. if (properties.playlists && properties.playlists.length) {
  7501. const playlists = properties.playlists;
  7502. mediaGroupSidx = merge$1(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  7503. }
  7504. });
  7505. return mediaGroupSidx;
  7506. };
  7507. class DashPlaylistLoader extends EventTarget {
  7508. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  7509. // playlist loader setups from media groups will expect to be able to pass a playlist
  7510. // (since there aren't external URLs to media playlists with DASH)
  7511. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  7512. super();
  7513. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  7514. if (!mainPlaylistLoader) {
  7515. this.isMain_ = true;
  7516. }
  7517. const {
  7518. withCredentials = false
  7519. } = options;
  7520. this.vhs_ = vhs;
  7521. this.withCredentials = withCredentials;
  7522. if (!srcUrlOrPlaylist) {
  7523. throw new Error('A non-empty playlist URL or object is required');
  7524. } // event naming?
  7525. this.on('minimumUpdatePeriod', () => {
  7526. this.refreshXml_();
  7527. }); // live playlist staleness timeout
  7528. this.on('mediaupdatetimeout', () => {
  7529. this.refreshMedia_(this.media().id);
  7530. });
  7531. this.state = 'HAVE_NOTHING';
  7532. this.loadedPlaylists_ = {};
  7533. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  7534. // The mainPlaylistLoader will be created with a string
  7535. if (this.isMain_) {
  7536. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  7537. // once multi-period is refactored
  7538. this.mainPlaylistLoader_.sidxMapping_ = {};
  7539. } else {
  7540. this.childPlaylist_ = srcUrlOrPlaylist;
  7541. }
  7542. }
  7543. requestErrored_(err, request, startingState) {
  7544. // disposed
  7545. if (!this.request) {
  7546. return true;
  7547. } // pending request is cleared
  7548. this.request = null;
  7549. if (err) {
  7550. // use the provided error object or create one
  7551. // based on the request/response
  7552. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  7553. status: request.status,
  7554. message: 'DASH request error at URL: ' + request.uri,
  7555. response: request.response,
  7556. // MEDIA_ERR_NETWORK
  7557. code: 2
  7558. };
  7559. if (startingState) {
  7560. this.state = startingState;
  7561. }
  7562. this.trigger('error');
  7563. return true;
  7564. }
  7565. }
  7566. /**
  7567. * Verify that the container of the sidx segment can be parsed
  7568. * and if it can, get and parse that segment.
  7569. */
  7570. addSidxSegments_(playlist, startingState, cb) {
  7571. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  7572. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  7573. // keep this function async
  7574. this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
  7575. return;
  7576. } // resolve the segment URL relative to the playlist
  7577. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  7578. const fin = (err, request) => {
  7579. if (this.requestErrored_(err, request, startingState)) {
  7580. return;
  7581. }
  7582. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  7583. let sidx;
  7584. try {
  7585. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  7586. } catch (e) {
  7587. // sidx parsing failed.
  7588. this.requestErrored_(e, request, startingState);
  7589. return;
  7590. }
  7591. sidxMapping[sidxKey] = {
  7592. sidxInfo: playlist.sidx,
  7593. sidx
  7594. };
  7595. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  7596. return cb(true);
  7597. };
  7598. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  7599. if (err) {
  7600. return fin(err, request);
  7601. }
  7602. if (!container || container !== 'mp4') {
  7603. return fin({
  7604. status: request.status,
  7605. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  7606. // response is just bytes in this case
  7607. // but we really don't want to return that.
  7608. response: '',
  7609. playlist,
  7610. internal: true,
  7611. playlistExclusionDuration: Infinity,
  7612. // MEDIA_ERR_NETWORK
  7613. code: 2
  7614. }, request);
  7615. } // if we already downloaded the sidx bytes in the container request, use them
  7616. const {
  7617. offset,
  7618. length
  7619. } = playlist.sidx.byterange;
  7620. if (bytes.length >= length + offset) {
  7621. return fin(err, {
  7622. response: bytes.subarray(offset, offset + length),
  7623. status: request.status,
  7624. uri: request.uri
  7625. });
  7626. } // otherwise request sidx bytes
  7627. this.request = this.vhs_.xhr({
  7628. uri,
  7629. responseType: 'arraybuffer',
  7630. headers: segmentXhrHeaders({
  7631. byterange: playlist.sidx.byterange
  7632. })
  7633. }, fin);
  7634. });
  7635. }
  7636. dispose() {
  7637. this.trigger('dispose');
  7638. this.stopRequest();
  7639. this.loadedPlaylists_ = {};
  7640. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  7641. window.clearTimeout(this.mediaRequest_);
  7642. window.clearTimeout(this.mediaUpdateTimeout);
  7643. this.mediaUpdateTimeout = null;
  7644. this.mediaRequest_ = null;
  7645. this.minimumUpdatePeriodTimeout_ = null;
  7646. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  7647. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  7648. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  7649. }
  7650. this.off();
  7651. }
  7652. hasPendingRequest() {
  7653. return this.request || this.mediaRequest_;
  7654. }
  7655. stopRequest() {
  7656. if (this.request) {
  7657. const oldRequest = this.request;
  7658. this.request = null;
  7659. oldRequest.onreadystatechange = null;
  7660. oldRequest.abort();
  7661. }
  7662. }
  7663. media(playlist) {
  7664. // getter
  7665. if (!playlist) {
  7666. return this.media_;
  7667. } // setter
  7668. if (this.state === 'HAVE_NOTHING') {
  7669. throw new Error('Cannot switch media playlist from ' + this.state);
  7670. }
  7671. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  7672. if (typeof playlist === 'string') {
  7673. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  7674. throw new Error('Unknown playlist URI: ' + playlist);
  7675. }
  7676. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  7677. }
  7678. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  7679. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  7680. this.state = 'HAVE_METADATA';
  7681. this.media_ = playlist; // trigger media change if the active media has been updated
  7682. if (mediaChange) {
  7683. this.trigger('mediachanging');
  7684. this.trigger('mediachange');
  7685. }
  7686. return;
  7687. } // switching to the active playlist is a no-op
  7688. if (!mediaChange) {
  7689. return;
  7690. } // switching from an already loaded playlist
  7691. if (this.media_) {
  7692. this.trigger('mediachanging');
  7693. }
  7694. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  7695. // everything is ready just continue to haveMetadata
  7696. this.haveMetadata({
  7697. startingState,
  7698. playlist
  7699. });
  7700. });
  7701. }
  7702. haveMetadata({
  7703. startingState,
  7704. playlist
  7705. }) {
  7706. this.state = 'HAVE_METADATA';
  7707. this.loadedPlaylists_[playlist.id] = playlist;
  7708. this.mediaRequest_ = null; // This will trigger loadedplaylist
  7709. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  7710. // to resolve setup of media groups
  7711. if (startingState === 'HAVE_MAIN_MANIFEST') {
  7712. this.trigger('loadedmetadata');
  7713. } else {
  7714. // trigger media change if the active media has been updated
  7715. this.trigger('mediachange');
  7716. }
  7717. }
  7718. pause() {
  7719. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  7720. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  7721. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  7722. }
  7723. this.stopRequest();
  7724. window.clearTimeout(this.mediaUpdateTimeout);
  7725. this.mediaUpdateTimeout = null;
  7726. if (this.isMain_) {
  7727. window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  7728. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  7729. }
  7730. if (this.state === 'HAVE_NOTHING') {
  7731. // If we pause the loader before any data has been retrieved, its as if we never
  7732. // started, so reset to an unstarted state.
  7733. this.started = false;
  7734. }
  7735. }
  7736. load(isFinalRendition) {
  7737. window.clearTimeout(this.mediaUpdateTimeout);
  7738. this.mediaUpdateTimeout = null;
  7739. const media = this.media();
  7740. if (isFinalRendition) {
  7741. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  7742. this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
  7743. return;
  7744. } // because the playlists are internal to the manifest, load should either load the
  7745. // main manifest, or do nothing but trigger an event
  7746. if (!this.started) {
  7747. this.start();
  7748. return;
  7749. }
  7750. if (media && !media.endList) {
  7751. // Check to see if this is the main loader and the MUP was cleared (this happens
  7752. // when the loader was paused). `media` should be set at this point since one is always
  7753. // set during `start()`.
  7754. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  7755. // Trigger minimumUpdatePeriod to refresh the main manifest
  7756. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  7757. this.updateMinimumUpdatePeriodTimeout_();
  7758. }
  7759. this.trigger('mediaupdatetimeout');
  7760. } else {
  7761. this.trigger('loadedplaylist');
  7762. }
  7763. }
  7764. start() {
  7765. this.started = true; // We don't need to request the main manifest again
  7766. // Call this asynchronously to match the xhr request behavior below
  7767. if (!this.isMain_) {
  7768. this.mediaRequest_ = window.setTimeout(() => this.haveMain_(), 0);
  7769. return;
  7770. }
  7771. this.requestMain_((req, mainChanged) => {
  7772. this.haveMain_();
  7773. if (!this.hasPendingRequest() && !this.media_) {
  7774. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  7775. }
  7776. });
  7777. }
  7778. requestMain_(cb) {
  7779. this.request = this.vhs_.xhr({
  7780. uri: this.mainPlaylistLoader_.srcUrl,
  7781. withCredentials: this.withCredentials
  7782. }, (error, req) => {
  7783. if (this.requestErrored_(error, req)) {
  7784. if (this.state === 'HAVE_NOTHING') {
  7785. this.started = false;
  7786. }
  7787. return;
  7788. }
  7789. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  7790. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  7791. if (req.responseHeaders && req.responseHeaders.date) {
  7792. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  7793. } else {
  7794. this.mainLoaded_ = Date.now();
  7795. }
  7796. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  7797. if (mainChanged) {
  7798. this.handleMain_();
  7799. this.syncClientServerClock_(() => {
  7800. return cb(req, mainChanged);
  7801. });
  7802. return;
  7803. }
  7804. return cb(req, mainChanged);
  7805. });
  7806. }
  7807. /**
  7808. * Parses the main xml for UTCTiming node to sync the client clock to the server
  7809. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  7810. *
  7811. * @param {Function} done
  7812. * Function to call when clock sync has completed
  7813. */
  7814. syncClientServerClock_(done) {
  7815. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  7816. // server clock
  7817. if (utcTiming === null) {
  7818. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  7819. return done();
  7820. }
  7821. if (utcTiming.method === 'DIRECT') {
  7822. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  7823. return done();
  7824. }
  7825. this.request = this.vhs_.xhr({
  7826. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  7827. method: utcTiming.method,
  7828. withCredentials: this.withCredentials
  7829. }, (error, req) => {
  7830. // disposed
  7831. if (!this.request) {
  7832. return;
  7833. }
  7834. if (error) {
  7835. // sync request failed, fall back to using date header from mpd
  7836. // TODO: log warning
  7837. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  7838. return done();
  7839. }
  7840. let serverTime;
  7841. if (utcTiming.method === 'HEAD') {
  7842. if (!req.responseHeaders || !req.responseHeaders.date) {
  7843. // expected date header not preset, fall back to using date header from mpd
  7844. // TODO: log warning
  7845. serverTime = this.mainLoaded_;
  7846. } else {
  7847. serverTime = Date.parse(req.responseHeaders.date);
  7848. }
  7849. } else {
  7850. serverTime = Date.parse(req.responseText);
  7851. }
  7852. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  7853. done();
  7854. });
  7855. }
  7856. haveMain_() {
  7857. this.state = 'HAVE_MAIN_MANIFEST';
  7858. if (this.isMain_) {
  7859. // We have the main playlist at this point, so
  7860. // trigger this to allow PlaylistController
  7861. // to make an initial playlist selection
  7862. this.trigger('loadedplaylist');
  7863. } else if (!this.media_) {
  7864. // no media playlist was specifically selected so select
  7865. // the one the child playlist loader was created with
  7866. this.media(this.childPlaylist_);
  7867. }
  7868. }
  7869. handleMain_() {
  7870. // clear media request
  7871. this.mediaRequest_ = null;
  7872. const oldMain = this.mainPlaylistLoader_.main;
  7873. let newMain = parseMainXml({
  7874. mainXml: this.mainPlaylistLoader_.mainXml_,
  7875. srcUrl: this.mainPlaylistLoader_.srcUrl,
  7876. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  7877. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  7878. previousManifest: oldMain
  7879. }); // if we have an old main to compare the new main against
  7880. if (oldMain) {
  7881. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  7882. } // only update main if we have a new main
  7883. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  7884. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  7885. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  7886. this.mainPlaylistLoader_.srcUrl = location;
  7887. }
  7888. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  7889. this.updateMinimumUpdatePeriodTimeout_();
  7890. }
  7891. return Boolean(newMain);
  7892. }
  7893. updateMinimumUpdatePeriodTimeout_() {
  7894. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  7895. // a new one will be added if needed.
  7896. if (mpl.createMupOnMedia_) {
  7897. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  7898. mpl.createMupOnMedia_ = null;
  7899. } // clear any pending timeouts
  7900. if (mpl.minimumUpdatePeriodTimeout_) {
  7901. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  7902. mpl.minimumUpdatePeriodTimeout_ = null;
  7903. }
  7904. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  7905. // MPD has no future validity, so a new one will need to be acquired when new
  7906. // media segments are to be made available. Thus, we use the target duration
  7907. // in this case
  7908. if (mup === 0) {
  7909. if (mpl.media()) {
  7910. mup = mpl.media().targetDuration * 1000;
  7911. } else {
  7912. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  7913. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  7914. }
  7915. } // if minimumUpdatePeriod is invalid or <= zero, which
  7916. // can happen when a live video becomes VOD. skip timeout
  7917. // creation.
  7918. if (typeof mup !== 'number' || mup <= 0) {
  7919. if (mup < 0) {
  7920. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  7921. }
  7922. return;
  7923. }
  7924. this.createMUPTimeout_(mup);
  7925. }
  7926. createMUPTimeout_(mup) {
  7927. const mpl = this.mainPlaylistLoader_;
  7928. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
  7929. mpl.minimumUpdatePeriodTimeout_ = null;
  7930. mpl.trigger('minimumUpdatePeriod');
  7931. mpl.createMUPTimeout_(mup);
  7932. }, mup);
  7933. }
  7934. /**
  7935. * Sends request to refresh the main xml and updates the parsed main manifest
  7936. */
  7937. refreshXml_() {
  7938. this.requestMain_((req, mainChanged) => {
  7939. if (!mainChanged) {
  7940. return;
  7941. }
  7942. if (this.media_) {
  7943. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  7944. } // This will filter out updated sidx info from the mapping
  7945. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  7946. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  7947. // TODO: do we need to reload the current playlist?
  7948. this.refreshMedia_(this.media().id);
  7949. });
  7950. });
  7951. }
  7952. /**
  7953. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  7954. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  7955. * from the main loader.
  7956. */
  7957. refreshMedia_(mediaID) {
  7958. if (!mediaID) {
  7959. throw new Error('refreshMedia_ must take a media id');
  7960. } // for main we have to reparse the main xml
  7961. // to re-create segments based on current timing values
  7962. // which may change media. We only skip updating the main manifest
  7963. // if this is the first time this.media_ is being set.
  7964. // as main was just parsed in that case.
  7965. if (this.media_ && this.isMain_) {
  7966. this.handleMain_();
  7967. }
  7968. const playlists = this.mainPlaylistLoader_.main.playlists;
  7969. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  7970. if (mediaChanged) {
  7971. this.media_ = playlists[mediaID];
  7972. } else {
  7973. this.trigger('playlistunchanged');
  7974. }
  7975. if (!this.mediaUpdateTimeout) {
  7976. const createMediaUpdateTimeout = () => {
  7977. if (this.media().endList) {
  7978. return;
  7979. }
  7980. this.mediaUpdateTimeout = window.setTimeout(() => {
  7981. this.trigger('mediaupdatetimeout');
  7982. createMediaUpdateTimeout();
  7983. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  7984. };
  7985. createMediaUpdateTimeout();
  7986. }
  7987. this.trigger('loadedplaylist');
  7988. }
  7989. }
  7990. var Config = {
  7991. GOAL_BUFFER_LENGTH: 30,
  7992. MAX_GOAL_BUFFER_LENGTH: 60,
  7993. BACK_BUFFER_LENGTH: 30,
  7994. GOAL_BUFFER_LENGTH_RATE: 1,
  7995. // 0.5 MB/s
  7996. INITIAL_BANDWIDTH: 4194304,
  7997. // A fudge factor to apply to advertised playlist bitrates to account for
  7998. // temporary flucations in client bandwidth
  7999. BANDWIDTH_VARIANCE: 1.2,
  8000. // How much of the buffer must be filled before we consider upswitching
  8001. BUFFER_LOW_WATER_LINE: 0,
  8002. MAX_BUFFER_LOW_WATER_LINE: 30,
  8003. // TODO: Remove this when experimentalBufferBasedABR is removed
  8004. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  8005. BUFFER_LOW_WATER_LINE_RATE: 1,
  8006. // If the buffer is greater than the high water line, we won't switch down
  8007. BUFFER_HIGH_WATER_LINE: 30
  8008. };
  8009. const stringToArrayBuffer = string => {
  8010. const view = new Uint8Array(new ArrayBuffer(string.length));
  8011. for (let i = 0; i < string.length; i++) {
  8012. view[i] = string.charCodeAt(i);
  8013. }
  8014. return view.buffer;
  8015. };
  8016. class MockWorker {
  8017. constructor() {
  8018. this.listeners_ = [];
  8019. this.onmessage = null;
  8020. this.remote_ = null;
  8021. }
  8022. addEventListener(type, fn) {
  8023. if (type !== 'message') {
  8024. return;
  8025. }
  8026. this.listeners_.push(fn);
  8027. }
  8028. removeEventListener(type, fn) {
  8029. if (type !== 'message') {
  8030. return;
  8031. }
  8032. const i = this.listeners_.indexOf(fn);
  8033. if (i === -1) {
  8034. return;
  8035. }
  8036. this.listeners_.splice(i, 1);
  8037. }
  8038. dispatchEvent(event) {
  8039. if (!event || event.type !== 'message') {
  8040. return;
  8041. }
  8042. if (this.onmessage) {
  8043. this.onmessage(event);
  8044. }
  8045. this.listeners_.forEach(function (fn) {
  8046. fn(event);
  8047. });
  8048. }
  8049. postMessage(data) {
  8050. if (this.remote_) {
  8051. this.remote_.recv_(data);
  8052. }
  8053. }
  8054. recv_(data) {
  8055. // the browser puts the actual message under
  8056. const message = {
  8057. data
  8058. };
  8059. if (this.onmessage) {
  8060. this.onmessage(message);
  8061. }
  8062. this.listeners_.forEach(function (fn) {
  8063. fn(message);
  8064. });
  8065. }
  8066. terminate() {
  8067. if (this.remote_) {
  8068. this.remote_.remote_ = null;
  8069. this.remote_.terminate();
  8070. this.remote_ = null;
  8071. }
  8072. this.onmessage = null;
  8073. this.listeners_.length = 0;
  8074. }
  8075. }
  8076. MockWorker.prototype.on = MockWorker.prototype.addEventListener;
  8077. MockWorker.prototype.off = MockWorker.prototype.removeEventListener;
  8078. const factory = function (fn) {
  8079. return function () {
  8080. const client = new MockWorker();
  8081. const worker = new MockWorker();
  8082. client.type_ = 'window api';
  8083. client.remote_ = worker;
  8084. worker.remote_ = client;
  8085. worker.type_ = 'web worker';
  8086. fn(worker);
  8087. return client;
  8088. };
  8089. };
  8090. const transform = function (fn) {
  8091. // eslint-disable-next-line
  8092. return fn;
  8093. };
  8094. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  8095. const workerCode$1 = transform(function (self) {
  8096. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  8097. /**
  8098. * mux.js
  8099. *
  8100. * Copyright (c) Brightcove
  8101. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8102. *
  8103. * A lightweight readable stream implemention that handles event dispatching.
  8104. * Objects that inherit from streams should call init in their constructors.
  8105. */
  8106. var Stream$8 = function () {
  8107. this.init = function () {
  8108. var listeners = {};
  8109. /**
  8110. * Add a listener for a specified event type.
  8111. * @param type {string} the event name
  8112. * @param listener {function} the callback to be invoked when an event of
  8113. * the specified type occurs
  8114. */
  8115. this.on = function (type, listener) {
  8116. if (!listeners[type]) {
  8117. listeners[type] = [];
  8118. }
  8119. listeners[type] = listeners[type].concat(listener);
  8120. };
  8121. /**
  8122. * Remove a listener for a specified event type.
  8123. * @param type {string} the event name
  8124. * @param listener {function} a function previously registered for this
  8125. * type of event through `on`
  8126. */
  8127. this.off = function (type, listener) {
  8128. var index;
  8129. if (!listeners[type]) {
  8130. return false;
  8131. }
  8132. index = listeners[type].indexOf(listener);
  8133. listeners[type] = listeners[type].slice();
  8134. listeners[type].splice(index, 1);
  8135. return index > -1;
  8136. };
  8137. /**
  8138. * Trigger an event of the specified type on this stream. Any additional
  8139. * arguments to this function are passed as parameters to event listeners.
  8140. * @param type {string} the event name
  8141. */
  8142. this.trigger = function (type) {
  8143. var callbacks, i, length, args;
  8144. callbacks = listeners[type];
  8145. if (!callbacks) {
  8146. return;
  8147. } // Slicing the arguments on every invocation of this method
  8148. // can add a significant amount of overhead. Avoid the
  8149. // intermediate object creation for the common case of a
  8150. // single callback argument
  8151. if (arguments.length === 2) {
  8152. length = callbacks.length;
  8153. for (i = 0; i < length; ++i) {
  8154. callbacks[i].call(this, arguments[1]);
  8155. }
  8156. } else {
  8157. args = [];
  8158. i = arguments.length;
  8159. for (i = 1; i < arguments.length; ++i) {
  8160. args.push(arguments[i]);
  8161. }
  8162. length = callbacks.length;
  8163. for (i = 0; i < length; ++i) {
  8164. callbacks[i].apply(this, args);
  8165. }
  8166. }
  8167. };
  8168. /**
  8169. * Destroys the stream and cleans up.
  8170. */
  8171. this.dispose = function () {
  8172. listeners = {};
  8173. };
  8174. };
  8175. };
  8176. /**
  8177. * Forwards all `data` events on this stream to the destination stream. The
  8178. * destination stream should provide a method `push` to receive the data
  8179. * events as they arrive.
  8180. * @param destination {stream} the stream that will receive all `data` events
  8181. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  8182. * when the current stream emits a 'done' event
  8183. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  8184. */
  8185. Stream$8.prototype.pipe = function (destination) {
  8186. this.on('data', function (data) {
  8187. destination.push(data);
  8188. });
  8189. this.on('done', function (flushSource) {
  8190. destination.flush(flushSource);
  8191. });
  8192. this.on('partialdone', function (flushSource) {
  8193. destination.partialFlush(flushSource);
  8194. });
  8195. this.on('endedtimeline', function (flushSource) {
  8196. destination.endTimeline(flushSource);
  8197. });
  8198. this.on('reset', function (flushSource) {
  8199. destination.reset(flushSource);
  8200. });
  8201. return destination;
  8202. }; // Default stream functions that are expected to be overridden to perform
  8203. // actual work. These are provided by the prototype as a sort of no-op
  8204. // implementation so that we don't have to check for their existence in the
  8205. // `pipe` function above.
  8206. Stream$8.prototype.push = function (data) {
  8207. this.trigger('data', data);
  8208. };
  8209. Stream$8.prototype.flush = function (flushSource) {
  8210. this.trigger('done', flushSource);
  8211. };
  8212. Stream$8.prototype.partialFlush = function (flushSource) {
  8213. this.trigger('partialdone', flushSource);
  8214. };
  8215. Stream$8.prototype.endTimeline = function (flushSource) {
  8216. this.trigger('endedtimeline', flushSource);
  8217. };
  8218. Stream$8.prototype.reset = function (flushSource) {
  8219. this.trigger('reset', flushSource);
  8220. };
  8221. var stream = Stream$8;
  8222. var MAX_UINT32$1 = Math.pow(2, 32);
  8223. var getUint64$3 = function (uint8) {
  8224. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  8225. var value;
  8226. if (dv.getBigUint64) {
  8227. value = dv.getBigUint64(0);
  8228. if (value < Number.MAX_SAFE_INTEGER) {
  8229. return Number(value);
  8230. }
  8231. return value;
  8232. }
  8233. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  8234. };
  8235. var numbers = {
  8236. getUint64: getUint64$3,
  8237. MAX_UINT32: MAX_UINT32$1
  8238. };
  8239. /**
  8240. * mux.js
  8241. *
  8242. * Copyright (c) Brightcove
  8243. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8244. *
  8245. * Functions that generate fragmented MP4s suitable for use with Media
  8246. * Source Extensions.
  8247. */
  8248. var MAX_UINT32 = numbers.MAX_UINT32;
  8249. 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
  8250. (function () {
  8251. var i;
  8252. types = {
  8253. avc1: [],
  8254. // codingname
  8255. avcC: [],
  8256. btrt: [],
  8257. dinf: [],
  8258. dref: [],
  8259. esds: [],
  8260. ftyp: [],
  8261. hdlr: [],
  8262. mdat: [],
  8263. mdhd: [],
  8264. mdia: [],
  8265. mfhd: [],
  8266. minf: [],
  8267. moof: [],
  8268. moov: [],
  8269. mp4a: [],
  8270. // codingname
  8271. mvex: [],
  8272. mvhd: [],
  8273. pasp: [],
  8274. sdtp: [],
  8275. smhd: [],
  8276. stbl: [],
  8277. stco: [],
  8278. stsc: [],
  8279. stsd: [],
  8280. stsz: [],
  8281. stts: [],
  8282. styp: [],
  8283. tfdt: [],
  8284. tfhd: [],
  8285. traf: [],
  8286. trak: [],
  8287. trun: [],
  8288. trex: [],
  8289. tkhd: [],
  8290. vmhd: []
  8291. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  8292. // don't throw an error
  8293. if (typeof Uint8Array === 'undefined') {
  8294. return;
  8295. }
  8296. for (i in types) {
  8297. if (types.hasOwnProperty(i)) {
  8298. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  8299. }
  8300. }
  8301. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  8302. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  8303. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  8304. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  8305. 0x00, 0x00, 0x00, // flags
  8306. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8307. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  8308. 0x00, 0x00, 0x00, 0x00, // reserved
  8309. 0x00, 0x00, 0x00, 0x00, // reserved
  8310. 0x00, 0x00, 0x00, 0x00, // reserved
  8311. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  8312. ]);
  8313. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  8314. 0x00, 0x00, 0x00, // flags
  8315. 0x00, 0x00, 0x00, 0x00, // pre_defined
  8316. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  8317. 0x00, 0x00, 0x00, 0x00, // reserved
  8318. 0x00, 0x00, 0x00, 0x00, // reserved
  8319. 0x00, 0x00, 0x00, 0x00, // reserved
  8320. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  8321. ]);
  8322. HDLR_TYPES = {
  8323. video: VIDEO_HDLR,
  8324. audio: AUDIO_HDLR
  8325. };
  8326. DREF = new Uint8Array([0x00, // version 0
  8327. 0x00, 0x00, 0x00, // flags
  8328. 0x00, 0x00, 0x00, 0x01, // entry_count
  8329. 0x00, 0x00, 0x00, 0x0c, // entry_size
  8330. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  8331. 0x00, // version 0
  8332. 0x00, 0x00, 0x01 // entry_flags
  8333. ]);
  8334. SMHD = new Uint8Array([0x00, // version
  8335. 0x00, 0x00, 0x00, // flags
  8336. 0x00, 0x00, // balance, 0 means centered
  8337. 0x00, 0x00 // reserved
  8338. ]);
  8339. STCO = new Uint8Array([0x00, // version
  8340. 0x00, 0x00, 0x00, // flags
  8341. 0x00, 0x00, 0x00, 0x00 // entry_count
  8342. ]);
  8343. STSC = STCO;
  8344. STSZ = new Uint8Array([0x00, // version
  8345. 0x00, 0x00, 0x00, // flags
  8346. 0x00, 0x00, 0x00, 0x00, // sample_size
  8347. 0x00, 0x00, 0x00, 0x00 // sample_count
  8348. ]);
  8349. STTS = STCO;
  8350. VMHD = new Uint8Array([0x00, // version
  8351. 0x00, 0x00, 0x01, // flags
  8352. 0x00, 0x00, // graphicsmode
  8353. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  8354. ]);
  8355. })();
  8356. box = function (type) {
  8357. var payload = [],
  8358. size = 0,
  8359. i,
  8360. result,
  8361. view;
  8362. for (i = 1; i < arguments.length; i++) {
  8363. payload.push(arguments[i]);
  8364. }
  8365. i = payload.length; // calculate the total size we need to allocate
  8366. while (i--) {
  8367. size += payload[i].byteLength;
  8368. }
  8369. result = new Uint8Array(size + 8);
  8370. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  8371. view.setUint32(0, result.byteLength);
  8372. result.set(type, 4); // copy the payload into the result
  8373. for (i = 0, size = 8; i < payload.length; i++) {
  8374. result.set(payload[i], size);
  8375. size += payload[i].byteLength;
  8376. }
  8377. return result;
  8378. };
  8379. dinf = function () {
  8380. return box(types.dinf, box(types.dref, DREF));
  8381. };
  8382. esds = function (track) {
  8383. return box(types.esds, new Uint8Array([0x00, // version
  8384. 0x00, 0x00, 0x00, // flags
  8385. // ES_Descriptor
  8386. 0x03, // tag, ES_DescrTag
  8387. 0x19, // length
  8388. 0x00, 0x00, // ES_ID
  8389. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  8390. // DecoderConfigDescriptor
  8391. 0x04, // tag, DecoderConfigDescrTag
  8392. 0x11, // length
  8393. 0x40, // object type
  8394. 0x15, // streamType
  8395. 0x00, 0x06, 0x00, // bufferSizeDB
  8396. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  8397. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  8398. // DecoderSpecificInfo
  8399. 0x05, // tag, DecoderSpecificInfoTag
  8400. 0x02, // length
  8401. // ISO/IEC 14496-3, AudioSpecificConfig
  8402. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  8403. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  8404. ]));
  8405. };
  8406. ftyp = function () {
  8407. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  8408. };
  8409. hdlr = function (type) {
  8410. return box(types.hdlr, HDLR_TYPES[type]);
  8411. };
  8412. mdat = function (data) {
  8413. return box(types.mdat, data);
  8414. };
  8415. mdhd = function (track) {
  8416. var result = new Uint8Array([0x00, // version 0
  8417. 0x00, 0x00, 0x00, // flags
  8418. 0x00, 0x00, 0x00, 0x02, // creation_time
  8419. 0x00, 0x00, 0x00, 0x03, // modification_time
  8420. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8421. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  8422. 0x55, 0xc4, // 'und' language (undetermined)
  8423. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  8424. // defined. The sample rate can be parsed out of an ADTS header, for
  8425. // instance.
  8426. if (track.samplerate) {
  8427. result[12] = track.samplerate >>> 24 & 0xFF;
  8428. result[13] = track.samplerate >>> 16 & 0xFF;
  8429. result[14] = track.samplerate >>> 8 & 0xFF;
  8430. result[15] = track.samplerate & 0xFF;
  8431. }
  8432. return box(types.mdhd, result);
  8433. };
  8434. mdia = function (track) {
  8435. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  8436. };
  8437. mfhd = function (sequenceNumber) {
  8438. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  8439. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  8440. ]));
  8441. };
  8442. minf = function (track) {
  8443. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  8444. };
  8445. moof = function (sequenceNumber, tracks) {
  8446. var trackFragments = [],
  8447. i = tracks.length; // build traf boxes for each track fragment
  8448. while (i--) {
  8449. trackFragments[i] = traf(tracks[i]);
  8450. }
  8451. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  8452. };
  8453. /**
  8454. * Returns a movie box.
  8455. * @param tracks {array} the tracks associated with this movie
  8456. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  8457. */
  8458. moov = function (tracks) {
  8459. var i = tracks.length,
  8460. boxes = [];
  8461. while (i--) {
  8462. boxes[i] = trak(tracks[i]);
  8463. }
  8464. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  8465. };
  8466. mvex = function (tracks) {
  8467. var i = tracks.length,
  8468. boxes = [];
  8469. while (i--) {
  8470. boxes[i] = trex(tracks[i]);
  8471. }
  8472. return box.apply(null, [types.mvex].concat(boxes));
  8473. };
  8474. mvhd = function (duration) {
  8475. var bytes = new Uint8Array([0x00, // version 0
  8476. 0x00, 0x00, 0x00, // flags
  8477. 0x00, 0x00, 0x00, 0x01, // creation_time
  8478. 0x00, 0x00, 0x00, 0x02, // modification_time
  8479. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  8480. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  8481. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  8482. 0x01, 0x00, // 1.0 volume
  8483. 0x00, 0x00, // reserved
  8484. 0x00, 0x00, 0x00, 0x00, // reserved
  8485. 0x00, 0x00, 0x00, 0x00, // reserved
  8486. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  8487. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  8488. 0xff, 0xff, 0xff, 0xff // next_track_ID
  8489. ]);
  8490. return box(types.mvhd, bytes);
  8491. };
  8492. sdtp = function (track) {
  8493. var samples = track.samples || [],
  8494. bytes = new Uint8Array(4 + samples.length),
  8495. flags,
  8496. i; // leave the full box header (4 bytes) all zero
  8497. // write the sample table
  8498. for (i = 0; i < samples.length; i++) {
  8499. flags = samples[i].flags;
  8500. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  8501. }
  8502. return box(types.sdtp, bytes);
  8503. };
  8504. stbl = function (track) {
  8505. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  8506. };
  8507. (function () {
  8508. var videoSample, audioSample;
  8509. stsd = function (track) {
  8510. return box(types.stsd, new Uint8Array([0x00, // version 0
  8511. 0x00, 0x00, 0x00, // flags
  8512. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  8513. };
  8514. videoSample = function (track) {
  8515. var sps = track.sps || [],
  8516. pps = track.pps || [],
  8517. sequenceParameterSets = [],
  8518. pictureParameterSets = [],
  8519. i,
  8520. avc1Box; // assemble the SPSs
  8521. for (i = 0; i < sps.length; i++) {
  8522. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  8523. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  8524. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  8525. } // assemble the PPSs
  8526. for (i = 0; i < pps.length; i++) {
  8527. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  8528. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  8529. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  8530. }
  8531. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8532. 0x00, 0x01, // data_reference_index
  8533. 0x00, 0x00, // pre_defined
  8534. 0x00, 0x00, // reserved
  8535. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  8536. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  8537. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  8538. 0x00, 0x48, 0x00, 0x00, // horizresolution
  8539. 0x00, 0x48, 0x00, 0x00, // vertresolution
  8540. 0x00, 0x00, 0x00, 0x00, // reserved
  8541. 0x00, 0x01, // frame_count
  8542. 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  8543. 0x00, 0x18, // depth = 24
  8544. 0x11, 0x11 // pre_defined = -1
  8545. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  8546. track.profileIdc, // AVCProfileIndication
  8547. track.profileCompatibility, // profile_compatibility
  8548. track.levelIdc, // AVCLevelIndication
  8549. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  8550. ].concat([sps.length], // numOfSequenceParameterSets
  8551. sequenceParameterSets, // "SPS"
  8552. [pps.length], // numOfPictureParameterSets
  8553. pictureParameterSets // "PPS"
  8554. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  8555. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  8556. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  8557. ]))];
  8558. if (track.sarRatio) {
  8559. var hSpacing = track.sarRatio[0],
  8560. vSpacing = track.sarRatio[1];
  8561. 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])));
  8562. }
  8563. return box.apply(null, avc1Box);
  8564. };
  8565. audioSample = function (track) {
  8566. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  8567. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8568. 0x00, 0x01, // data_reference_index
  8569. // AudioSampleEntry, ISO/IEC 14496-12
  8570. 0x00, 0x00, 0x00, 0x00, // reserved
  8571. 0x00, 0x00, 0x00, 0x00, // reserved
  8572. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  8573. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  8574. 0x00, 0x00, // pre_defined
  8575. 0x00, 0x00, // reserved
  8576. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  8577. // MP4AudioSampleEntry, ISO/IEC 14496-14
  8578. ]), esds(track));
  8579. };
  8580. })();
  8581. tkhd = function (track) {
  8582. var result = new Uint8Array([0x00, // version 0
  8583. 0x00, 0x00, 0x07, // flags
  8584. 0x00, 0x00, 0x00, 0x00, // creation_time
  8585. 0x00, 0x00, 0x00, 0x00, // modification_time
  8586. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8587. 0x00, 0x00, 0x00, 0x00, // reserved
  8588. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  8589. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  8590. 0x00, 0x00, // layer
  8591. 0x00, 0x00, // alternate_group
  8592. 0x01, 0x00, // non-audio track volume
  8593. 0x00, 0x00, // reserved
  8594. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  8595. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  8596. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  8597. ]);
  8598. return box(types.tkhd, result);
  8599. };
  8600. /**
  8601. * Generate a track fragment (traf) box. A traf box collects metadata
  8602. * about tracks in a movie fragment (moof) box.
  8603. */
  8604. traf = function (track) {
  8605. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  8606. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  8607. 0x00, 0x00, 0x3a, // flags
  8608. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8609. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  8610. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8611. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8612. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  8613. ]));
  8614. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  8615. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  8616. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  8617. 0x00, 0x00, 0x00, // flags
  8618. // baseMediaDecodeTime
  8619. 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
  8620. // the containing moof to the first payload byte of the associated
  8621. // mdat
  8622. dataOffset = 32 + // tfhd
  8623. 20 + // tfdt
  8624. 8 + // traf header
  8625. 16 + // mfhd
  8626. 8 + // moof header
  8627. 8; // mdat header
  8628. // audio tracks require less metadata
  8629. if (track.type === 'audio') {
  8630. trackFragmentRun = trun$1(track, dataOffset);
  8631. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  8632. } // video tracks should contain an independent and disposable samples
  8633. // box (sdtp)
  8634. // generate one and adjust offsets to match
  8635. sampleDependencyTable = sdtp(track);
  8636. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  8637. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  8638. };
  8639. /**
  8640. * Generate a track box.
  8641. * @param track {object} a track definition
  8642. * @return {Uint8Array} the track box
  8643. */
  8644. trak = function (track) {
  8645. track.duration = track.duration || 0xffffffff;
  8646. return box(types.trak, tkhd(track), mdia(track));
  8647. };
  8648. trex = function (track) {
  8649. var result = new Uint8Array([0x00, // version 0
  8650. 0x00, 0x00, 0x00, // flags
  8651. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  8652. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  8653. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  8654. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  8655. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  8656. ]); // the last two bytes of default_sample_flags is the sample
  8657. // degradation priority, a hint about the importance of this sample
  8658. // relative to others. Lower the degradation priority for all sample
  8659. // types other than video.
  8660. if (track.type !== 'video') {
  8661. result[result.length - 1] = 0x00;
  8662. }
  8663. return box(types.trex, result);
  8664. };
  8665. (function () {
  8666. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  8667. // duration is present for the first sample, it will be present for
  8668. // all subsequent samples.
  8669. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  8670. trunHeader = function (samples, offset) {
  8671. var durationPresent = 0,
  8672. sizePresent = 0,
  8673. flagsPresent = 0,
  8674. compositionTimeOffset = 0; // trun flag constants
  8675. if (samples.length) {
  8676. if (samples[0].duration !== undefined) {
  8677. durationPresent = 0x1;
  8678. }
  8679. if (samples[0].size !== undefined) {
  8680. sizePresent = 0x2;
  8681. }
  8682. if (samples[0].flags !== undefined) {
  8683. flagsPresent = 0x4;
  8684. }
  8685. if (samples[0].compositionTimeOffset !== undefined) {
  8686. compositionTimeOffset = 0x8;
  8687. }
  8688. }
  8689. return [0x00, // version 0
  8690. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  8691. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  8692. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  8693. ];
  8694. };
  8695. videoTrun = function (track, offset) {
  8696. var bytesOffest, bytes, header, samples, sample, i;
  8697. samples = track.samples || [];
  8698. offset += 8 + 12 + 16 * samples.length;
  8699. header = trunHeader(samples, offset);
  8700. bytes = new Uint8Array(header.length + samples.length * 16);
  8701. bytes.set(header);
  8702. bytesOffest = header.length;
  8703. for (i = 0; i < samples.length; i++) {
  8704. sample = samples[i];
  8705. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  8706. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  8707. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  8708. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  8709. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  8710. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  8711. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  8712. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  8713. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  8714. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  8715. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  8716. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  8717. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  8718. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  8719. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  8720. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  8721. }
  8722. return box(types.trun, bytes);
  8723. };
  8724. audioTrun = function (track, offset) {
  8725. var bytes, bytesOffest, header, samples, sample, i;
  8726. samples = track.samples || [];
  8727. offset += 8 + 12 + 8 * samples.length;
  8728. header = trunHeader(samples, offset);
  8729. bytes = new Uint8Array(header.length + samples.length * 8);
  8730. bytes.set(header);
  8731. bytesOffest = header.length;
  8732. for (i = 0; i < samples.length; i++) {
  8733. sample = samples[i];
  8734. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  8735. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  8736. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  8737. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  8738. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  8739. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  8740. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  8741. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  8742. }
  8743. return box(types.trun, bytes);
  8744. };
  8745. trun$1 = function (track, offset) {
  8746. if (track.type === 'audio') {
  8747. return audioTrun(track, offset);
  8748. }
  8749. return videoTrun(track, offset);
  8750. };
  8751. })();
  8752. var mp4Generator = {
  8753. ftyp: ftyp,
  8754. mdat: mdat,
  8755. moof: moof,
  8756. moov: moov,
  8757. initSegment: function (tracks) {
  8758. var fileType = ftyp(),
  8759. movie = moov(tracks),
  8760. result;
  8761. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  8762. result.set(fileType);
  8763. result.set(movie, fileType.byteLength);
  8764. return result;
  8765. }
  8766. };
  8767. /**
  8768. * mux.js
  8769. *
  8770. * Copyright (c) Brightcove
  8771. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8772. */
  8773. // composed of the nal units that make up that frame
  8774. // Also keep track of cummulative data about the frame from the nal units such
  8775. // as the frame duration, starting pts, etc.
  8776. var groupNalsIntoFrames = function (nalUnits) {
  8777. var i,
  8778. currentNal,
  8779. currentFrame = [],
  8780. frames = []; // TODO added for LHLS, make sure this is OK
  8781. frames.byteLength = 0;
  8782. frames.nalCount = 0;
  8783. frames.duration = 0;
  8784. currentFrame.byteLength = 0;
  8785. for (i = 0; i < nalUnits.length; i++) {
  8786. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  8787. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  8788. // Since the very first nal unit is expected to be an AUD
  8789. // only push to the frames array when currentFrame is not empty
  8790. if (currentFrame.length) {
  8791. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  8792. frames.byteLength += currentFrame.byteLength;
  8793. frames.nalCount += currentFrame.length;
  8794. frames.duration += currentFrame.duration;
  8795. frames.push(currentFrame);
  8796. }
  8797. currentFrame = [currentNal];
  8798. currentFrame.byteLength = currentNal.data.byteLength;
  8799. currentFrame.pts = currentNal.pts;
  8800. currentFrame.dts = currentNal.dts;
  8801. } else {
  8802. // Specifically flag key frames for ease of use later
  8803. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  8804. currentFrame.keyFrame = true;
  8805. }
  8806. currentFrame.duration = currentNal.dts - currentFrame.dts;
  8807. currentFrame.byteLength += currentNal.data.byteLength;
  8808. currentFrame.push(currentNal);
  8809. }
  8810. } // For the last frame, use the duration of the previous frame if we
  8811. // have nothing better to go on
  8812. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  8813. currentFrame.duration = frames[frames.length - 1].duration;
  8814. } // Push the final frame
  8815. // TODO added for LHLS, make sure this is OK
  8816. frames.byteLength += currentFrame.byteLength;
  8817. frames.nalCount += currentFrame.length;
  8818. frames.duration += currentFrame.duration;
  8819. frames.push(currentFrame);
  8820. return frames;
  8821. }; // Convert an array of frames into an array of Gop with each Gop being composed
  8822. // of the frames that make up that Gop
  8823. // Also keep track of cummulative data about the Gop from the frames such as the
  8824. // Gop duration, starting pts, etc.
  8825. var groupFramesIntoGops = function (frames) {
  8826. var i,
  8827. currentFrame,
  8828. currentGop = [],
  8829. gops = []; // We must pre-set some of the values on the Gop since we
  8830. // keep running totals of these values
  8831. currentGop.byteLength = 0;
  8832. currentGop.nalCount = 0;
  8833. currentGop.duration = 0;
  8834. currentGop.pts = frames[0].pts;
  8835. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  8836. gops.byteLength = 0;
  8837. gops.nalCount = 0;
  8838. gops.duration = 0;
  8839. gops.pts = frames[0].pts;
  8840. gops.dts = frames[0].dts;
  8841. for (i = 0; i < frames.length; i++) {
  8842. currentFrame = frames[i];
  8843. if (currentFrame.keyFrame) {
  8844. // Since the very first frame is expected to be an keyframe
  8845. // only push to the gops array when currentGop is not empty
  8846. if (currentGop.length) {
  8847. gops.push(currentGop);
  8848. gops.byteLength += currentGop.byteLength;
  8849. gops.nalCount += currentGop.nalCount;
  8850. gops.duration += currentGop.duration;
  8851. }
  8852. currentGop = [currentFrame];
  8853. currentGop.nalCount = currentFrame.length;
  8854. currentGop.byteLength = currentFrame.byteLength;
  8855. currentGop.pts = currentFrame.pts;
  8856. currentGop.dts = currentFrame.dts;
  8857. currentGop.duration = currentFrame.duration;
  8858. } else {
  8859. currentGop.duration += currentFrame.duration;
  8860. currentGop.nalCount += currentFrame.length;
  8861. currentGop.byteLength += currentFrame.byteLength;
  8862. currentGop.push(currentFrame);
  8863. }
  8864. }
  8865. if (gops.length && currentGop.duration <= 0) {
  8866. currentGop.duration = gops[gops.length - 1].duration;
  8867. }
  8868. gops.byteLength += currentGop.byteLength;
  8869. gops.nalCount += currentGop.nalCount;
  8870. gops.duration += currentGop.duration; // push the final Gop
  8871. gops.push(currentGop);
  8872. return gops;
  8873. };
  8874. /*
  8875. * Search for the first keyframe in the GOPs and throw away all frames
  8876. * until that keyframe. Then extend the duration of the pulled keyframe
  8877. * and pull the PTS and DTS of the keyframe so that it covers the time
  8878. * range of the frames that were disposed.
  8879. *
  8880. * @param {Array} gops video GOPs
  8881. * @returns {Array} modified video GOPs
  8882. */
  8883. var extendFirstKeyFrame = function (gops) {
  8884. var currentGop;
  8885. if (!gops[0][0].keyFrame && gops.length > 1) {
  8886. // Remove the first GOP
  8887. currentGop = gops.shift();
  8888. gops.byteLength -= currentGop.byteLength;
  8889. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  8890. // first gop to cover the time period of the
  8891. // frames we just removed
  8892. gops[0][0].dts = currentGop.dts;
  8893. gops[0][0].pts = currentGop.pts;
  8894. gops[0][0].duration += currentGop.duration;
  8895. }
  8896. return gops;
  8897. };
  8898. /**
  8899. * Default sample object
  8900. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  8901. */
  8902. var createDefaultSample = function () {
  8903. return {
  8904. size: 0,
  8905. flags: {
  8906. isLeading: 0,
  8907. dependsOn: 1,
  8908. isDependedOn: 0,
  8909. hasRedundancy: 0,
  8910. degradationPriority: 0,
  8911. isNonSyncSample: 1
  8912. }
  8913. };
  8914. };
  8915. /*
  8916. * Collates information from a video frame into an object for eventual
  8917. * entry into an MP4 sample table.
  8918. *
  8919. * @param {Object} frame the video frame
  8920. * @param {Number} dataOffset the byte offset to position the sample
  8921. * @return {Object} object containing sample table info for a frame
  8922. */
  8923. var sampleForFrame = function (frame, dataOffset) {
  8924. var sample = createDefaultSample();
  8925. sample.dataOffset = dataOffset;
  8926. sample.compositionTimeOffset = frame.pts - frame.dts;
  8927. sample.duration = frame.duration;
  8928. sample.size = 4 * frame.length; // Space for nal unit size
  8929. sample.size += frame.byteLength;
  8930. if (frame.keyFrame) {
  8931. sample.flags.dependsOn = 2;
  8932. sample.flags.isNonSyncSample = 0;
  8933. }
  8934. return sample;
  8935. }; // generate the track's sample table from an array of gops
  8936. var generateSampleTable$1 = function (gops, baseDataOffset) {
  8937. var h,
  8938. i,
  8939. sample,
  8940. currentGop,
  8941. currentFrame,
  8942. dataOffset = baseDataOffset || 0,
  8943. samples = [];
  8944. for (h = 0; h < gops.length; h++) {
  8945. currentGop = gops[h];
  8946. for (i = 0; i < currentGop.length; i++) {
  8947. currentFrame = currentGop[i];
  8948. sample = sampleForFrame(currentFrame, dataOffset);
  8949. dataOffset += sample.size;
  8950. samples.push(sample);
  8951. }
  8952. }
  8953. return samples;
  8954. }; // generate the track's raw mdat data from an array of gops
  8955. var concatenateNalData = function (gops) {
  8956. var h,
  8957. i,
  8958. j,
  8959. currentGop,
  8960. currentFrame,
  8961. currentNal,
  8962. dataOffset = 0,
  8963. nalsByteLength = gops.byteLength,
  8964. numberOfNals = gops.nalCount,
  8965. totalByteLength = nalsByteLength + 4 * numberOfNals,
  8966. data = new Uint8Array(totalByteLength),
  8967. view = new DataView(data.buffer); // For each Gop..
  8968. for (h = 0; h < gops.length; h++) {
  8969. currentGop = gops[h]; // For each Frame..
  8970. for (i = 0; i < currentGop.length; i++) {
  8971. currentFrame = currentGop[i]; // For each NAL..
  8972. for (j = 0; j < currentFrame.length; j++) {
  8973. currentNal = currentFrame[j];
  8974. view.setUint32(dataOffset, currentNal.data.byteLength);
  8975. dataOffset += 4;
  8976. data.set(currentNal.data, dataOffset);
  8977. dataOffset += currentNal.data.byteLength;
  8978. }
  8979. }
  8980. }
  8981. return data;
  8982. }; // generate the track's sample table from a frame
  8983. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  8984. var sample,
  8985. dataOffset = baseDataOffset || 0,
  8986. samples = [];
  8987. sample = sampleForFrame(frame, dataOffset);
  8988. samples.push(sample);
  8989. return samples;
  8990. }; // generate the track's raw mdat data from a frame
  8991. var concatenateNalDataForFrame = function (frame) {
  8992. var i,
  8993. currentNal,
  8994. dataOffset = 0,
  8995. nalsByteLength = frame.byteLength,
  8996. numberOfNals = frame.length,
  8997. totalByteLength = nalsByteLength + 4 * numberOfNals,
  8998. data = new Uint8Array(totalByteLength),
  8999. view = new DataView(data.buffer); // For each NAL..
  9000. for (i = 0; i < frame.length; i++) {
  9001. currentNal = frame[i];
  9002. view.setUint32(dataOffset, currentNal.data.byteLength);
  9003. dataOffset += 4;
  9004. data.set(currentNal.data, dataOffset);
  9005. dataOffset += currentNal.data.byteLength;
  9006. }
  9007. return data;
  9008. };
  9009. var frameUtils$1 = {
  9010. groupNalsIntoFrames: groupNalsIntoFrames,
  9011. groupFramesIntoGops: groupFramesIntoGops,
  9012. extendFirstKeyFrame: extendFirstKeyFrame,
  9013. generateSampleTable: generateSampleTable$1,
  9014. concatenateNalData: concatenateNalData,
  9015. generateSampleTableForFrame: generateSampleTableForFrame,
  9016. concatenateNalDataForFrame: concatenateNalDataForFrame
  9017. };
  9018. /**
  9019. * mux.js
  9020. *
  9021. * Copyright (c) Brightcove
  9022. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9023. */
  9024. var highPrefix = [33, 16, 5, 32, 164, 27];
  9025. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  9026. var zeroFill = function (count) {
  9027. var a = [];
  9028. while (count--) {
  9029. a.push(0);
  9030. }
  9031. return a;
  9032. };
  9033. var makeTable = function (metaTable) {
  9034. return Object.keys(metaTable).reduce(function (obj, key) {
  9035. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  9036. return arr.concat(part);
  9037. }, []));
  9038. return obj;
  9039. }, {});
  9040. };
  9041. var silence;
  9042. var silence_1 = function () {
  9043. if (!silence) {
  9044. // Frames-of-silence to use for filling in missing AAC frames
  9045. var coneOfSilence = {
  9046. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  9047. 88200: [highPrefix, [231], zeroFill(170), [56]],
  9048. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  9049. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  9050. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  9051. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  9052. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  9053. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  9054. 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]],
  9055. 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]],
  9056. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  9057. };
  9058. silence = makeTable(coneOfSilence);
  9059. }
  9060. return silence;
  9061. };
  9062. /**
  9063. * mux.js
  9064. *
  9065. * Copyright (c) Brightcove
  9066. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9067. */
  9068. var ONE_SECOND_IN_TS$4 = 90000,
  9069. // 90kHz clock
  9070. secondsToVideoTs,
  9071. secondsToAudioTs,
  9072. videoTsToSeconds,
  9073. audioTsToSeconds,
  9074. audioTsToVideoTs,
  9075. videoTsToAudioTs,
  9076. metadataTsToSeconds;
  9077. secondsToVideoTs = function (seconds) {
  9078. return seconds * ONE_SECOND_IN_TS$4;
  9079. };
  9080. secondsToAudioTs = function (seconds, sampleRate) {
  9081. return seconds * sampleRate;
  9082. };
  9083. videoTsToSeconds = function (timestamp) {
  9084. return timestamp / ONE_SECOND_IN_TS$4;
  9085. };
  9086. audioTsToSeconds = function (timestamp, sampleRate) {
  9087. return timestamp / sampleRate;
  9088. };
  9089. audioTsToVideoTs = function (timestamp, sampleRate) {
  9090. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  9091. };
  9092. videoTsToAudioTs = function (timestamp, sampleRate) {
  9093. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  9094. };
  9095. /**
  9096. * Adjust ID3 tag or caption timing information by the timeline pts values
  9097. * (if keepOriginalTimestamps is false) and convert to seconds
  9098. */
  9099. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  9100. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  9101. };
  9102. var clock$2 = {
  9103. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  9104. secondsToVideoTs: secondsToVideoTs,
  9105. secondsToAudioTs: secondsToAudioTs,
  9106. videoTsToSeconds: videoTsToSeconds,
  9107. audioTsToSeconds: audioTsToSeconds,
  9108. audioTsToVideoTs: audioTsToVideoTs,
  9109. videoTsToAudioTs: videoTsToAudioTs,
  9110. metadataTsToSeconds: metadataTsToSeconds
  9111. };
  9112. /**
  9113. * mux.js
  9114. *
  9115. * Copyright (c) Brightcove
  9116. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9117. */
  9118. var coneOfSilence = silence_1;
  9119. var clock$1 = clock$2;
  9120. /**
  9121. * Sum the `byteLength` properties of the data in each AAC frame
  9122. */
  9123. var sumFrameByteLengths = function (array) {
  9124. var i,
  9125. currentObj,
  9126. sum = 0; // sum the byteLength's all each nal unit in the frame
  9127. for (i = 0; i < array.length; i++) {
  9128. currentObj = array[i];
  9129. sum += currentObj.data.byteLength;
  9130. }
  9131. return sum;
  9132. }; // Possibly pad (prefix) the audio track with silence if appending this track
  9133. // would lead to the introduction of a gap in the audio buffer
  9134. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  9135. var baseMediaDecodeTimeTs,
  9136. frameDuration = 0,
  9137. audioGapDuration = 0,
  9138. audioFillFrameCount = 0,
  9139. audioFillDuration = 0,
  9140. silentFrame,
  9141. i,
  9142. firstFrame;
  9143. if (!frames.length) {
  9144. return;
  9145. }
  9146. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  9147. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  9148. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  9149. // insert the shortest possible amount (audio gap or audio to video gap)
  9150. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  9151. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  9152. audioFillDuration = audioFillFrameCount * frameDuration;
  9153. } // don't attempt to fill gaps smaller than a single frame or larger
  9154. // than a half second
  9155. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  9156. return;
  9157. }
  9158. silentFrame = coneOfSilence()[track.samplerate];
  9159. if (!silentFrame) {
  9160. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  9161. // from the content instead
  9162. silentFrame = frames[0].data;
  9163. }
  9164. for (i = 0; i < audioFillFrameCount; i++) {
  9165. firstFrame = frames[0];
  9166. frames.splice(0, 0, {
  9167. data: silentFrame,
  9168. dts: firstFrame.dts - frameDuration,
  9169. pts: firstFrame.pts - frameDuration
  9170. });
  9171. }
  9172. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  9173. return audioFillDuration;
  9174. }; // If the audio segment extends before the earliest allowed dts
  9175. // value, remove AAC frames until starts at or after the earliest
  9176. // allowed DTS so that we don't end up with a negative baseMedia-
  9177. // DecodeTime for the audio track
  9178. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  9179. if (track.minSegmentDts >= earliestAllowedDts) {
  9180. return adtsFrames;
  9181. } // We will need to recalculate the earliest segment Dts
  9182. track.minSegmentDts = Infinity;
  9183. return adtsFrames.filter(function (currentFrame) {
  9184. // If this is an allowed frame, keep it and record it's Dts
  9185. if (currentFrame.dts >= earliestAllowedDts) {
  9186. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  9187. track.minSegmentPts = track.minSegmentDts;
  9188. return true;
  9189. } // Otherwise, discard it
  9190. return false;
  9191. });
  9192. }; // generate the track's raw mdat data from an array of frames
  9193. var generateSampleTable = function (frames) {
  9194. var i,
  9195. currentFrame,
  9196. samples = [];
  9197. for (i = 0; i < frames.length; i++) {
  9198. currentFrame = frames[i];
  9199. samples.push({
  9200. size: currentFrame.data.byteLength,
  9201. duration: 1024 // For AAC audio, all samples contain 1024 samples
  9202. });
  9203. }
  9204. return samples;
  9205. }; // generate the track's sample table from an array of frames
  9206. var concatenateFrameData = function (frames) {
  9207. var i,
  9208. currentFrame,
  9209. dataOffset = 0,
  9210. data = new Uint8Array(sumFrameByteLengths(frames));
  9211. for (i = 0; i < frames.length; i++) {
  9212. currentFrame = frames[i];
  9213. data.set(currentFrame.data, dataOffset);
  9214. dataOffset += currentFrame.data.byteLength;
  9215. }
  9216. return data;
  9217. };
  9218. var audioFrameUtils$1 = {
  9219. prefixWithSilence: prefixWithSilence,
  9220. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  9221. generateSampleTable: generateSampleTable,
  9222. concatenateFrameData: concatenateFrameData
  9223. };
  9224. /**
  9225. * mux.js
  9226. *
  9227. * Copyright (c) Brightcove
  9228. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9229. */
  9230. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  9231. /**
  9232. * Store information about the start and end of the track and the
  9233. * duration for each frame/sample we process in order to calculate
  9234. * the baseMediaDecodeTime
  9235. */
  9236. var collectDtsInfo = function (track, data) {
  9237. if (typeof data.pts === 'number') {
  9238. if (track.timelineStartInfo.pts === undefined) {
  9239. track.timelineStartInfo.pts = data.pts;
  9240. }
  9241. if (track.minSegmentPts === undefined) {
  9242. track.minSegmentPts = data.pts;
  9243. } else {
  9244. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  9245. }
  9246. if (track.maxSegmentPts === undefined) {
  9247. track.maxSegmentPts = data.pts;
  9248. } else {
  9249. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  9250. }
  9251. }
  9252. if (typeof data.dts === 'number') {
  9253. if (track.timelineStartInfo.dts === undefined) {
  9254. track.timelineStartInfo.dts = data.dts;
  9255. }
  9256. if (track.minSegmentDts === undefined) {
  9257. track.minSegmentDts = data.dts;
  9258. } else {
  9259. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  9260. }
  9261. if (track.maxSegmentDts === undefined) {
  9262. track.maxSegmentDts = data.dts;
  9263. } else {
  9264. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  9265. }
  9266. }
  9267. };
  9268. /**
  9269. * Clear values used to calculate the baseMediaDecodeTime between
  9270. * tracks
  9271. */
  9272. var clearDtsInfo = function (track) {
  9273. delete track.minSegmentDts;
  9274. delete track.maxSegmentDts;
  9275. delete track.minSegmentPts;
  9276. delete track.maxSegmentPts;
  9277. };
  9278. /**
  9279. * Calculate the track's baseMediaDecodeTime based on the earliest
  9280. * DTS the transmuxer has ever seen and the minimum DTS for the
  9281. * current track
  9282. * @param track {object} track metadata configuration
  9283. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  9284. * in the source; false to adjust the first segment to start at 0.
  9285. */
  9286. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  9287. var baseMediaDecodeTime,
  9288. scale,
  9289. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  9290. if (!keepOriginalTimestamps) {
  9291. minSegmentDts -= track.timelineStartInfo.dts;
  9292. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  9293. // we want the start of the first segment to be placed
  9294. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  9295. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  9296. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  9297. if (track.type === 'audio') {
  9298. // Audio has a different clock equal to the sampling_rate so we need to
  9299. // scale the PTS values into the clock rate of the track
  9300. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  9301. baseMediaDecodeTime *= scale;
  9302. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  9303. }
  9304. return baseMediaDecodeTime;
  9305. };
  9306. var trackDecodeInfo$1 = {
  9307. clearDtsInfo: clearDtsInfo,
  9308. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  9309. collectDtsInfo: collectDtsInfo
  9310. };
  9311. /**
  9312. * mux.js
  9313. *
  9314. * Copyright (c) Brightcove
  9315. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9316. *
  9317. * Reads in-band caption information from a video elementary
  9318. * stream. Captions must follow the CEA-708 standard for injection
  9319. * into an MPEG-2 transport streams.
  9320. * @see https://en.wikipedia.org/wiki/CEA-708
  9321. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  9322. */
  9323. // payload type field to indicate how they are to be
  9324. // interpreted. CEAS-708 caption content is always transmitted with
  9325. // payload type 0x04.
  9326. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  9327. RBSP_TRAILING_BITS = 128;
  9328. /**
  9329. * Parse a supplemental enhancement information (SEI) NAL unit.
  9330. * Stops parsing once a message of type ITU T T35 has been found.
  9331. *
  9332. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  9333. * @return {object} the parsed SEI payload
  9334. * @see Rec. ITU-T H.264, 7.3.2.3.1
  9335. */
  9336. var parseSei = function (bytes) {
  9337. var i = 0,
  9338. result = {
  9339. payloadType: -1,
  9340. payloadSize: 0
  9341. },
  9342. payloadType = 0,
  9343. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  9344. while (i < bytes.byteLength) {
  9345. // stop once we have hit the end of the sei_rbsp
  9346. if (bytes[i] === RBSP_TRAILING_BITS) {
  9347. break;
  9348. } // Parse payload type
  9349. while (bytes[i] === 0xFF) {
  9350. payloadType += 255;
  9351. i++;
  9352. }
  9353. payloadType += bytes[i++]; // Parse payload size
  9354. while (bytes[i] === 0xFF) {
  9355. payloadSize += 255;
  9356. i++;
  9357. }
  9358. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  9359. // there can only ever be one caption message in a frame's sei
  9360. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  9361. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  9362. if (userIdentifier === 'GA94') {
  9363. result.payloadType = payloadType;
  9364. result.payloadSize = payloadSize;
  9365. result.payload = bytes.subarray(i, i + payloadSize);
  9366. break;
  9367. } else {
  9368. result.payload = void 0;
  9369. }
  9370. } // skip the payload and parse the next message
  9371. i += payloadSize;
  9372. payloadType = 0;
  9373. payloadSize = 0;
  9374. }
  9375. return result;
  9376. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  9377. var parseUserData = function (sei) {
  9378. // itu_t_t35_contry_code must be 181 (United States) for
  9379. // captions
  9380. if (sei.payload[0] !== 181) {
  9381. return null;
  9382. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  9383. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  9384. return null;
  9385. } // the user_identifier should be "GA94" to indicate ATSC1 data
  9386. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  9387. return null;
  9388. } // finally, user_data_type_code should be 0x03 for caption data
  9389. if (sei.payload[7] !== 0x03) {
  9390. return null;
  9391. } // return the user_data_type_structure and strip the trailing
  9392. // marker bits
  9393. return sei.payload.subarray(8, sei.payload.length - 1);
  9394. }; // see CEA-708-D, section 4.4
  9395. var parseCaptionPackets = function (pts, userData) {
  9396. var results = [],
  9397. i,
  9398. count,
  9399. offset,
  9400. data; // if this is just filler, return immediately
  9401. if (!(userData[0] & 0x40)) {
  9402. return results;
  9403. } // parse out the cc_data_1 and cc_data_2 fields
  9404. count = userData[0] & 0x1f;
  9405. for (i = 0; i < count; i++) {
  9406. offset = i * 3;
  9407. data = {
  9408. type: userData[offset + 2] & 0x03,
  9409. pts: pts
  9410. }; // capture cc data when cc_valid is 1
  9411. if (userData[offset + 2] & 0x04) {
  9412. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  9413. results.push(data);
  9414. }
  9415. }
  9416. return results;
  9417. };
  9418. var discardEmulationPreventionBytes$1 = function (data) {
  9419. var length = data.byteLength,
  9420. emulationPreventionBytesPositions = [],
  9421. i = 1,
  9422. newLength,
  9423. newData; // Find all `Emulation Prevention Bytes`
  9424. while (i < length - 2) {
  9425. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  9426. emulationPreventionBytesPositions.push(i + 2);
  9427. i += 2;
  9428. } else {
  9429. i++;
  9430. }
  9431. } // If no Emulation Prevention Bytes were found just return the original
  9432. // array
  9433. if (emulationPreventionBytesPositions.length === 0) {
  9434. return data;
  9435. } // Create a new array to hold the NAL unit data
  9436. newLength = length - emulationPreventionBytesPositions.length;
  9437. newData = new Uint8Array(newLength);
  9438. var sourceIndex = 0;
  9439. for (i = 0; i < newLength; sourceIndex++, i++) {
  9440. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  9441. // Skip this byte
  9442. sourceIndex++; // Remove this position index
  9443. emulationPreventionBytesPositions.shift();
  9444. }
  9445. newData[i] = data[sourceIndex];
  9446. }
  9447. return newData;
  9448. }; // exports
  9449. var captionPacketParser = {
  9450. parseSei: parseSei,
  9451. parseUserData: parseUserData,
  9452. parseCaptionPackets: parseCaptionPackets,
  9453. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  9454. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  9455. };
  9456. /**
  9457. * mux.js
  9458. *
  9459. * Copyright (c) Brightcove
  9460. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9461. *
  9462. * Reads in-band caption information from a video elementary
  9463. * stream. Captions must follow the CEA-708 standard for injection
  9464. * into an MPEG-2 transport streams.
  9465. * @see https://en.wikipedia.org/wiki/CEA-708
  9466. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  9467. */
  9468. // Link To Transport
  9469. // -----------------
  9470. var Stream$7 = stream;
  9471. var cea708Parser = captionPacketParser;
  9472. var CaptionStream$2 = function (options) {
  9473. options = options || {};
  9474. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  9475. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  9476. this.captionPackets_ = [];
  9477. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  9478. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  9479. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  9480. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  9481. ];
  9482. if (this.parse708captions_) {
  9483. this.cc708Stream_ = new Cea708Stream({
  9484. captionServices: options.captionServices
  9485. }); // eslint-disable-line no-use-before-define
  9486. }
  9487. this.reset(); // forward data and done events from CCs to this CaptionStream
  9488. this.ccStreams_.forEach(function (cc) {
  9489. cc.on('data', this.trigger.bind(this, 'data'));
  9490. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  9491. cc.on('done', this.trigger.bind(this, 'done'));
  9492. }, this);
  9493. if (this.parse708captions_) {
  9494. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  9495. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  9496. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  9497. }
  9498. };
  9499. CaptionStream$2.prototype = new Stream$7();
  9500. CaptionStream$2.prototype.push = function (event) {
  9501. var sei, userData, newCaptionPackets; // only examine SEI NALs
  9502. if (event.nalUnitType !== 'sei_rbsp') {
  9503. return;
  9504. } // parse the sei
  9505. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  9506. if (!sei.payload) {
  9507. return;
  9508. } // ignore everything but user_data_registered_itu_t_t35
  9509. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  9510. return;
  9511. } // parse out the user data payload
  9512. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  9513. if (!userData) {
  9514. return;
  9515. } // Sometimes, the same segment # will be downloaded twice. To stop the
  9516. // caption data from being processed twice, we track the latest dts we've
  9517. // received and ignore everything with a dts before that. However, since
  9518. // data for a specific dts can be split across packets on either side of
  9519. // a segment boundary, we need to make sure we *don't* ignore the packets
  9520. // from the *next* segment that have dts === this.latestDts_. By constantly
  9521. // tracking the number of packets received with dts === this.latestDts_, we
  9522. // know how many should be ignored once we start receiving duplicates.
  9523. if (event.dts < this.latestDts_) {
  9524. // We've started getting older data, so set the flag.
  9525. this.ignoreNextEqualDts_ = true;
  9526. return;
  9527. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  9528. this.numSameDts_--;
  9529. if (!this.numSameDts_) {
  9530. // We've received the last duplicate packet, time to start processing again
  9531. this.ignoreNextEqualDts_ = false;
  9532. }
  9533. return;
  9534. } // parse out CC data packets and save them for later
  9535. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  9536. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  9537. if (this.latestDts_ !== event.dts) {
  9538. this.numSameDts_ = 0;
  9539. }
  9540. this.numSameDts_++;
  9541. this.latestDts_ = event.dts;
  9542. };
  9543. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  9544. this.ccStreams_.forEach(function (cc) {
  9545. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  9546. }, this);
  9547. };
  9548. CaptionStream$2.prototype.flushStream = function (flushType) {
  9549. // make sure we actually parsed captions before proceeding
  9550. if (!this.captionPackets_.length) {
  9551. this.flushCCStreams(flushType);
  9552. return;
  9553. } // In Chrome, the Array#sort function is not stable so add a
  9554. // presortIndex that we can use to ensure we get a stable-sort
  9555. this.captionPackets_.forEach(function (elem, idx) {
  9556. elem.presortIndex = idx;
  9557. }); // sort caption byte-pairs based on their PTS values
  9558. this.captionPackets_.sort(function (a, b) {
  9559. if (a.pts === b.pts) {
  9560. return a.presortIndex - b.presortIndex;
  9561. }
  9562. return a.pts - b.pts;
  9563. });
  9564. this.captionPackets_.forEach(function (packet) {
  9565. if (packet.type < 2) {
  9566. // Dispatch packet to the right Cea608Stream
  9567. this.dispatchCea608Packet(packet);
  9568. } else {
  9569. // Dispatch packet to the Cea708Stream
  9570. this.dispatchCea708Packet(packet);
  9571. }
  9572. }, this);
  9573. this.captionPackets_.length = 0;
  9574. this.flushCCStreams(flushType);
  9575. };
  9576. CaptionStream$2.prototype.flush = function () {
  9577. return this.flushStream('flush');
  9578. }; // Only called if handling partial data
  9579. CaptionStream$2.prototype.partialFlush = function () {
  9580. return this.flushStream('partialFlush');
  9581. };
  9582. CaptionStream$2.prototype.reset = function () {
  9583. this.latestDts_ = null;
  9584. this.ignoreNextEqualDts_ = false;
  9585. this.numSameDts_ = 0;
  9586. this.activeCea608Channel_ = [null, null];
  9587. this.ccStreams_.forEach(function (ccStream) {
  9588. ccStream.reset();
  9589. });
  9590. }; // From the CEA-608 spec:
  9591. /*
  9592. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  9593. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  9594. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  9595. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  9596. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  9597. * to switch to captioning or Text.
  9598. */
  9599. // With that in mind, we ignore any data between an XDS control code and a
  9600. // subsequent closed-captioning control code.
  9601. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  9602. // NOTE: packet.type is the CEA608 field
  9603. if (this.setsTextOrXDSActive(packet)) {
  9604. this.activeCea608Channel_[packet.type] = null;
  9605. } else if (this.setsChannel1Active(packet)) {
  9606. this.activeCea608Channel_[packet.type] = 0;
  9607. } else if (this.setsChannel2Active(packet)) {
  9608. this.activeCea608Channel_[packet.type] = 1;
  9609. }
  9610. if (this.activeCea608Channel_[packet.type] === null) {
  9611. // If we haven't received anything to set the active channel, or the
  9612. // packets are Text/XDS data, discard the data; we don't want jumbled
  9613. // captions
  9614. return;
  9615. }
  9616. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  9617. };
  9618. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  9619. return (packet.ccData & 0x7800) === 0x1000;
  9620. };
  9621. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  9622. return (packet.ccData & 0x7800) === 0x1800;
  9623. };
  9624. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  9625. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  9626. };
  9627. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  9628. if (this.parse708captions_) {
  9629. this.cc708Stream_.push(packet);
  9630. }
  9631. }; // ----------------------
  9632. // Session to Application
  9633. // ----------------------
  9634. // This hash maps special and extended character codes to their
  9635. // proper Unicode equivalent. The first one-byte key is just a
  9636. // non-standard character code. The two-byte keys that follow are
  9637. // the extended CEA708 character codes, along with the preceding
  9638. // 0x10 extended character byte to distinguish these codes from
  9639. // non-extended character codes. Every CEA708 character code that
  9640. // is not in this object maps directly to a standard unicode
  9641. // character code.
  9642. // The transparent space and non-breaking transparent space are
  9643. // technically not fully supported since there is no code to
  9644. // make them transparent, so they have normal non-transparent
  9645. // stand-ins.
  9646. // The special closed caption (CC) character isn't a standard
  9647. // unicode character, so a fairly similar unicode character was
  9648. // chosen in it's place.
  9649. var CHARACTER_TRANSLATION_708 = {
  9650. 0x7f: 0x266a,
  9651. // ♪
  9652. 0x1020: 0x20,
  9653. // Transparent Space
  9654. 0x1021: 0xa0,
  9655. // Nob-breaking Transparent Space
  9656. 0x1025: 0x2026,
  9657. // …
  9658. 0x102a: 0x0160,
  9659. // Š
  9660. 0x102c: 0x0152,
  9661. // Œ
  9662. 0x1030: 0x2588,
  9663. // █
  9664. 0x1031: 0x2018,
  9665. // ‘
  9666. 0x1032: 0x2019,
  9667. // ’
  9668. 0x1033: 0x201c,
  9669. // “
  9670. 0x1034: 0x201d,
  9671. // ”
  9672. 0x1035: 0x2022,
  9673. // •
  9674. 0x1039: 0x2122,
  9675. // ™
  9676. 0x103a: 0x0161,
  9677. // š
  9678. 0x103c: 0x0153,
  9679. // œ
  9680. 0x103d: 0x2120,
  9681. // ℠
  9682. 0x103f: 0x0178,
  9683. // Ÿ
  9684. 0x1076: 0x215b,
  9685. // ⅛
  9686. 0x1077: 0x215c,
  9687. // ⅜
  9688. 0x1078: 0x215d,
  9689. // ⅝
  9690. 0x1079: 0x215e,
  9691. // ⅞
  9692. 0x107a: 0x23d0,
  9693. // ⏐
  9694. 0x107b: 0x23a4,
  9695. // ⎤
  9696. 0x107c: 0x23a3,
  9697. // ⎣
  9698. 0x107d: 0x23af,
  9699. // ⎯
  9700. 0x107e: 0x23a6,
  9701. // ⎦
  9702. 0x107f: 0x23a1,
  9703. // ⎡
  9704. 0x10a0: 0x3138 // ㄸ (CC char)
  9705. };
  9706. var get708CharFromCode = function (code) {
  9707. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  9708. if (code & 0x1000 && code === newCode) {
  9709. // Invalid extended code
  9710. return '';
  9711. }
  9712. return String.fromCharCode(newCode);
  9713. };
  9714. var within708TextBlock = function (b) {
  9715. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  9716. };
  9717. var Cea708Window = function (windowNum) {
  9718. this.windowNum = windowNum;
  9719. this.reset();
  9720. };
  9721. Cea708Window.prototype.reset = function () {
  9722. this.clearText();
  9723. this.pendingNewLine = false;
  9724. this.winAttr = {};
  9725. this.penAttr = {};
  9726. this.penLoc = {};
  9727. this.penColor = {}; // These default values are arbitrary,
  9728. // defineWindow will usually override them
  9729. this.visible = 0;
  9730. this.rowLock = 0;
  9731. this.columnLock = 0;
  9732. this.priority = 0;
  9733. this.relativePositioning = 0;
  9734. this.anchorVertical = 0;
  9735. this.anchorHorizontal = 0;
  9736. this.anchorPoint = 0;
  9737. this.rowCount = 1;
  9738. this.virtualRowCount = this.rowCount + 1;
  9739. this.columnCount = 41;
  9740. this.windowStyle = 0;
  9741. this.penStyle = 0;
  9742. };
  9743. Cea708Window.prototype.getText = function () {
  9744. return this.rows.join('\n');
  9745. };
  9746. Cea708Window.prototype.clearText = function () {
  9747. this.rows = [''];
  9748. this.rowIdx = 0;
  9749. };
  9750. Cea708Window.prototype.newLine = function (pts) {
  9751. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  9752. this.beforeRowOverflow(pts);
  9753. }
  9754. if (this.rows.length > 0) {
  9755. this.rows.push('');
  9756. this.rowIdx++;
  9757. } // Show all virtual rows since there's no visible scrolling
  9758. while (this.rows.length > this.virtualRowCount) {
  9759. this.rows.shift();
  9760. this.rowIdx--;
  9761. }
  9762. };
  9763. Cea708Window.prototype.isEmpty = function () {
  9764. if (this.rows.length === 0) {
  9765. return true;
  9766. } else if (this.rows.length === 1) {
  9767. return this.rows[0] === '';
  9768. }
  9769. return false;
  9770. };
  9771. Cea708Window.prototype.addText = function (text) {
  9772. this.rows[this.rowIdx] += text;
  9773. };
  9774. Cea708Window.prototype.backspace = function () {
  9775. if (!this.isEmpty()) {
  9776. var row = this.rows[this.rowIdx];
  9777. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  9778. }
  9779. };
  9780. var Cea708Service = function (serviceNum, encoding, stream) {
  9781. this.serviceNum = serviceNum;
  9782. this.text = '';
  9783. this.currentWindow = new Cea708Window(-1);
  9784. this.windows = [];
  9785. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  9786. if (typeof encoding === 'string') {
  9787. this.createTextDecoder(encoding);
  9788. }
  9789. };
  9790. /**
  9791. * Initialize service windows
  9792. * Must be run before service use
  9793. *
  9794. * @param {Integer} pts PTS value
  9795. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  9796. */
  9797. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  9798. this.startPts = pts;
  9799. for (var win = 0; win < 8; win++) {
  9800. this.windows[win] = new Cea708Window(win);
  9801. if (typeof beforeRowOverflow === 'function') {
  9802. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  9803. }
  9804. }
  9805. };
  9806. /**
  9807. * Set current window of service to be affected by commands
  9808. *
  9809. * @param {Integer} windowNum Window number
  9810. */
  9811. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  9812. this.currentWindow = this.windows[windowNum];
  9813. };
  9814. /**
  9815. * Try to create a TextDecoder if it is natively supported
  9816. */
  9817. Cea708Service.prototype.createTextDecoder = function (encoding) {
  9818. if (typeof TextDecoder === 'undefined') {
  9819. this.stream.trigger('log', {
  9820. level: 'warn',
  9821. message: 'The `encoding` option is unsupported without TextDecoder support'
  9822. });
  9823. } else {
  9824. try {
  9825. this.textDecoder_ = new TextDecoder(encoding);
  9826. } catch (error) {
  9827. this.stream.trigger('log', {
  9828. level: 'warn',
  9829. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  9830. });
  9831. }
  9832. }
  9833. };
  9834. var Cea708Stream = function (options) {
  9835. options = options || {};
  9836. Cea708Stream.prototype.init.call(this);
  9837. var self = this;
  9838. var captionServices = options.captionServices || {};
  9839. var captionServiceEncodings = {};
  9840. var serviceProps; // Get service encodings from captionServices option block
  9841. Object.keys(captionServices).forEach(serviceName => {
  9842. serviceProps = captionServices[serviceName];
  9843. if (/^SERVICE/.test(serviceName)) {
  9844. captionServiceEncodings[serviceName] = serviceProps.encoding;
  9845. }
  9846. });
  9847. this.serviceEncodings = captionServiceEncodings;
  9848. this.current708Packet = null;
  9849. this.services = {};
  9850. this.push = function (packet) {
  9851. if (packet.type === 3) {
  9852. // 708 packet start
  9853. self.new708Packet();
  9854. self.add708Bytes(packet);
  9855. } else {
  9856. if (self.current708Packet === null) {
  9857. // This should only happen at the start of a file if there's no packet start.
  9858. self.new708Packet();
  9859. }
  9860. self.add708Bytes(packet);
  9861. }
  9862. };
  9863. };
  9864. Cea708Stream.prototype = new Stream$7();
  9865. /**
  9866. * Push current 708 packet, create new 708 packet.
  9867. */
  9868. Cea708Stream.prototype.new708Packet = function () {
  9869. if (this.current708Packet !== null) {
  9870. this.push708Packet();
  9871. }
  9872. this.current708Packet = {
  9873. data: [],
  9874. ptsVals: []
  9875. };
  9876. };
  9877. /**
  9878. * Add pts and both bytes from packet into current 708 packet.
  9879. */
  9880. Cea708Stream.prototype.add708Bytes = function (packet) {
  9881. var data = packet.ccData;
  9882. var byte0 = data >>> 8;
  9883. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  9884. // that service blocks will always line up with byte pairs.
  9885. this.current708Packet.ptsVals.push(packet.pts);
  9886. this.current708Packet.data.push(byte0);
  9887. this.current708Packet.data.push(byte1);
  9888. };
  9889. /**
  9890. * Parse completed 708 packet into service blocks and push each service block.
  9891. */
  9892. Cea708Stream.prototype.push708Packet = function () {
  9893. var packet708 = this.current708Packet;
  9894. var packetData = packet708.data;
  9895. var serviceNum = null;
  9896. var blockSize = null;
  9897. var i = 0;
  9898. var b = packetData[i++];
  9899. packet708.seq = b >> 6;
  9900. packet708.sizeCode = b & 0x3f; // 0b00111111;
  9901. for (; i < packetData.length; i++) {
  9902. b = packetData[i++];
  9903. serviceNum = b >> 5;
  9904. blockSize = b & 0x1f; // 0b00011111
  9905. if (serviceNum === 7 && blockSize > 0) {
  9906. // Extended service num
  9907. b = packetData[i++];
  9908. serviceNum = b;
  9909. }
  9910. this.pushServiceBlock(serviceNum, i, blockSize);
  9911. if (blockSize > 0) {
  9912. i += blockSize - 1;
  9913. }
  9914. }
  9915. };
  9916. /**
  9917. * Parse service block, execute commands, read text.
  9918. *
  9919. * Note: While many of these commands serve important purposes,
  9920. * many others just parse out the parameters or attributes, but
  9921. * nothing is done with them because this is not a full and complete
  9922. * implementation of the entire 708 spec.
  9923. *
  9924. * @param {Integer} serviceNum Service number
  9925. * @param {Integer} start Start index of the 708 packet data
  9926. * @param {Integer} size Block size
  9927. */
  9928. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  9929. var b;
  9930. var i = start;
  9931. var packetData = this.current708Packet.data;
  9932. var service = this.services[serviceNum];
  9933. if (!service) {
  9934. service = this.initService(serviceNum, i);
  9935. }
  9936. for (; i < start + size && i < packetData.length; i++) {
  9937. b = packetData[i];
  9938. if (within708TextBlock(b)) {
  9939. i = this.handleText(i, service);
  9940. } else if (b === 0x18) {
  9941. i = this.multiByteCharacter(i, service);
  9942. } else if (b === 0x10) {
  9943. i = this.extendedCommands(i, service);
  9944. } else if (0x80 <= b && b <= 0x87) {
  9945. i = this.setCurrentWindow(i, service);
  9946. } else if (0x98 <= b && b <= 0x9f) {
  9947. i = this.defineWindow(i, service);
  9948. } else if (b === 0x88) {
  9949. i = this.clearWindows(i, service);
  9950. } else if (b === 0x8c) {
  9951. i = this.deleteWindows(i, service);
  9952. } else if (b === 0x89) {
  9953. i = this.displayWindows(i, service);
  9954. } else if (b === 0x8a) {
  9955. i = this.hideWindows(i, service);
  9956. } else if (b === 0x8b) {
  9957. i = this.toggleWindows(i, service);
  9958. } else if (b === 0x97) {
  9959. i = this.setWindowAttributes(i, service);
  9960. } else if (b === 0x90) {
  9961. i = this.setPenAttributes(i, service);
  9962. } else if (b === 0x91) {
  9963. i = this.setPenColor(i, service);
  9964. } else if (b === 0x92) {
  9965. i = this.setPenLocation(i, service);
  9966. } else if (b === 0x8f) {
  9967. service = this.reset(i, service);
  9968. } else if (b === 0x08) {
  9969. // BS: Backspace
  9970. service.currentWindow.backspace();
  9971. } else if (b === 0x0c) {
  9972. // FF: Form feed
  9973. service.currentWindow.clearText();
  9974. } else if (b === 0x0d) {
  9975. // CR: Carriage return
  9976. service.currentWindow.pendingNewLine = true;
  9977. } else if (b === 0x0e) {
  9978. // HCR: Horizontal carriage return
  9979. service.currentWindow.clearText();
  9980. } else if (b === 0x8d) {
  9981. // DLY: Delay, nothing to do
  9982. i++;
  9983. } else ;
  9984. }
  9985. };
  9986. /**
  9987. * Execute an extended command
  9988. *
  9989. * @param {Integer} i Current index in the 708 packet
  9990. * @param {Service} service The service object to be affected
  9991. * @return {Integer} New index after parsing
  9992. */
  9993. Cea708Stream.prototype.extendedCommands = function (i, service) {
  9994. var packetData = this.current708Packet.data;
  9995. var b = packetData[++i];
  9996. if (within708TextBlock(b)) {
  9997. i = this.handleText(i, service, {
  9998. isExtended: true
  9999. });
  10000. }
  10001. return i;
  10002. };
  10003. /**
  10004. * Get PTS value of a given byte index
  10005. *
  10006. * @param {Integer} byteIndex Index of the byte
  10007. * @return {Integer} PTS
  10008. */
  10009. Cea708Stream.prototype.getPts = function (byteIndex) {
  10010. // There's 1 pts value per 2 bytes
  10011. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  10012. };
  10013. /**
  10014. * Initializes a service
  10015. *
  10016. * @param {Integer} serviceNum Service number
  10017. * @return {Service} Initialized service object
  10018. */
  10019. Cea708Stream.prototype.initService = function (serviceNum, i) {
  10020. var serviceName = 'SERVICE' + serviceNum;
  10021. var self = this;
  10022. var serviceName;
  10023. var encoding;
  10024. if (serviceName in this.serviceEncodings) {
  10025. encoding = this.serviceEncodings[serviceName];
  10026. }
  10027. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  10028. this.services[serviceNum].init(this.getPts(i), function (pts) {
  10029. self.flushDisplayed(pts, self.services[serviceNum]);
  10030. });
  10031. return this.services[serviceNum];
  10032. };
  10033. /**
  10034. * Execute text writing to current window
  10035. *
  10036. * @param {Integer} i Current index in the 708 packet
  10037. * @param {Service} service The service object to be affected
  10038. * @return {Integer} New index after parsing
  10039. */
  10040. Cea708Stream.prototype.handleText = function (i, service, options) {
  10041. var isExtended = options && options.isExtended;
  10042. var isMultiByte = options && options.isMultiByte;
  10043. var packetData = this.current708Packet.data;
  10044. var extended = isExtended ? 0x1000 : 0x0000;
  10045. var currentByte = packetData[i];
  10046. var nextByte = packetData[i + 1];
  10047. var win = service.currentWindow;
  10048. var char;
  10049. var charCodeArray; // Use the TextDecoder if one was created for this service
  10050. if (service.textDecoder_ && !isExtended) {
  10051. if (isMultiByte) {
  10052. charCodeArray = [currentByte, nextByte];
  10053. i++;
  10054. } else {
  10055. charCodeArray = [currentByte];
  10056. }
  10057. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  10058. } else {
  10059. char = get708CharFromCode(extended | currentByte);
  10060. }
  10061. if (win.pendingNewLine && !win.isEmpty()) {
  10062. win.newLine(this.getPts(i));
  10063. }
  10064. win.pendingNewLine = false;
  10065. win.addText(char);
  10066. return i;
  10067. };
  10068. /**
  10069. * Handle decoding of multibyte character
  10070. *
  10071. * @param {Integer} i Current index in the 708 packet
  10072. * @param {Service} service The service object to be affected
  10073. * @return {Integer} New index after parsing
  10074. */
  10075. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  10076. var packetData = this.current708Packet.data;
  10077. var firstByte = packetData[i + 1];
  10078. var secondByte = packetData[i + 2];
  10079. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  10080. i = this.handleText(++i, service, {
  10081. isMultiByte: true
  10082. });
  10083. }
  10084. return i;
  10085. };
  10086. /**
  10087. * Parse and execute the CW# command.
  10088. *
  10089. * Set the current window.
  10090. *
  10091. * @param {Integer} i Current index in the 708 packet
  10092. * @param {Service} service The service object to be affected
  10093. * @return {Integer} New index after parsing
  10094. */
  10095. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  10096. var packetData = this.current708Packet.data;
  10097. var b = packetData[i];
  10098. var windowNum = b & 0x07;
  10099. service.setCurrentWindow(windowNum);
  10100. return i;
  10101. };
  10102. /**
  10103. * Parse and execute the DF# command.
  10104. *
  10105. * Define a window and set it as the current window.
  10106. *
  10107. * @param {Integer} i Current index in the 708 packet
  10108. * @param {Service} service The service object to be affected
  10109. * @return {Integer} New index after parsing
  10110. */
  10111. Cea708Stream.prototype.defineWindow = function (i, service) {
  10112. var packetData = this.current708Packet.data;
  10113. var b = packetData[i];
  10114. var windowNum = b & 0x07;
  10115. service.setCurrentWindow(windowNum);
  10116. var win = service.currentWindow;
  10117. b = packetData[++i];
  10118. win.visible = (b & 0x20) >> 5; // v
  10119. win.rowLock = (b & 0x10) >> 4; // rl
  10120. win.columnLock = (b & 0x08) >> 3; // cl
  10121. win.priority = b & 0x07; // p
  10122. b = packetData[++i];
  10123. win.relativePositioning = (b & 0x80) >> 7; // rp
  10124. win.anchorVertical = b & 0x7f; // av
  10125. b = packetData[++i];
  10126. win.anchorHorizontal = b; // ah
  10127. b = packetData[++i];
  10128. win.anchorPoint = (b & 0xf0) >> 4; // ap
  10129. win.rowCount = b & 0x0f; // rc
  10130. b = packetData[++i];
  10131. win.columnCount = b & 0x3f; // cc
  10132. b = packetData[++i];
  10133. win.windowStyle = (b & 0x38) >> 3; // ws
  10134. win.penStyle = b & 0x07; // ps
  10135. // The spec says there are (rowCount+1) "virtual rows"
  10136. win.virtualRowCount = win.rowCount + 1;
  10137. return i;
  10138. };
  10139. /**
  10140. * Parse and execute the SWA command.
  10141. *
  10142. * Set attributes of the current window.
  10143. *
  10144. * @param {Integer} i Current index in the 708 packet
  10145. * @param {Service} service The service object to be affected
  10146. * @return {Integer} New index after parsing
  10147. */
  10148. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  10149. var packetData = this.current708Packet.data;
  10150. var b = packetData[i];
  10151. var winAttr = service.currentWindow.winAttr;
  10152. b = packetData[++i];
  10153. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  10154. winAttr.fillRed = (b & 0x30) >> 4; // fr
  10155. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  10156. winAttr.fillBlue = b & 0x03; // fb
  10157. b = packetData[++i];
  10158. winAttr.borderType = (b & 0xc0) >> 6; // bt
  10159. winAttr.borderRed = (b & 0x30) >> 4; // br
  10160. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  10161. winAttr.borderBlue = b & 0x03; // bb
  10162. b = packetData[++i];
  10163. winAttr.borderType += (b & 0x80) >> 5; // bt
  10164. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  10165. winAttr.printDirection = (b & 0x30) >> 4; // pd
  10166. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  10167. winAttr.justify = b & 0x03; // j
  10168. b = packetData[++i];
  10169. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  10170. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  10171. winAttr.displayEffect = b & 0x03; // de
  10172. return i;
  10173. };
  10174. /**
  10175. * Gather text from all displayed windows and push a caption to output.
  10176. *
  10177. * @param {Integer} i Current index in the 708 packet
  10178. * @param {Service} service The service object to be affected
  10179. */
  10180. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  10181. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  10182. // display text in the correct order, but sample files so far have not shown any issue.
  10183. for (var winId = 0; winId < 8; winId++) {
  10184. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  10185. displayedText.push(service.windows[winId].getText());
  10186. }
  10187. }
  10188. service.endPts = pts;
  10189. service.text = displayedText.join('\n\n');
  10190. this.pushCaption(service);
  10191. service.startPts = pts;
  10192. };
  10193. /**
  10194. * Push a caption to output if the caption contains text.
  10195. *
  10196. * @param {Service} service The service object to be affected
  10197. */
  10198. Cea708Stream.prototype.pushCaption = function (service) {
  10199. if (service.text !== '') {
  10200. this.trigger('data', {
  10201. startPts: service.startPts,
  10202. endPts: service.endPts,
  10203. text: service.text,
  10204. stream: 'cc708_' + service.serviceNum
  10205. });
  10206. service.text = '';
  10207. service.startPts = service.endPts;
  10208. }
  10209. };
  10210. /**
  10211. * Parse and execute the DSW command.
  10212. *
  10213. * Set visible property of windows based on the parsed bitmask.
  10214. *
  10215. * @param {Integer} i Current index in the 708 packet
  10216. * @param {Service} service The service object to be affected
  10217. * @return {Integer} New index after parsing
  10218. */
  10219. Cea708Stream.prototype.displayWindows = function (i, service) {
  10220. var packetData = this.current708Packet.data;
  10221. var b = packetData[++i];
  10222. var pts = this.getPts(i);
  10223. this.flushDisplayed(pts, service);
  10224. for (var winId = 0; winId < 8; winId++) {
  10225. if (b & 0x01 << winId) {
  10226. service.windows[winId].visible = 1;
  10227. }
  10228. }
  10229. return i;
  10230. };
  10231. /**
  10232. * Parse and execute the HDW command.
  10233. *
  10234. * Set visible property of windows based on the parsed bitmask.
  10235. *
  10236. * @param {Integer} i Current index in the 708 packet
  10237. * @param {Service} service The service object to be affected
  10238. * @return {Integer} New index after parsing
  10239. */
  10240. Cea708Stream.prototype.hideWindows = function (i, service) {
  10241. var packetData = this.current708Packet.data;
  10242. var b = packetData[++i];
  10243. var pts = this.getPts(i);
  10244. this.flushDisplayed(pts, service);
  10245. for (var winId = 0; winId < 8; winId++) {
  10246. if (b & 0x01 << winId) {
  10247. service.windows[winId].visible = 0;
  10248. }
  10249. }
  10250. return i;
  10251. };
  10252. /**
  10253. * Parse and execute the TGW command.
  10254. *
  10255. * Set visible property of windows based on the parsed bitmask.
  10256. *
  10257. * @param {Integer} i Current index in the 708 packet
  10258. * @param {Service} service The service object to be affected
  10259. * @return {Integer} New index after parsing
  10260. */
  10261. Cea708Stream.prototype.toggleWindows = function (i, service) {
  10262. var packetData = this.current708Packet.data;
  10263. var b = packetData[++i];
  10264. var pts = this.getPts(i);
  10265. this.flushDisplayed(pts, service);
  10266. for (var winId = 0; winId < 8; winId++) {
  10267. if (b & 0x01 << winId) {
  10268. service.windows[winId].visible ^= 1;
  10269. }
  10270. }
  10271. return i;
  10272. };
  10273. /**
  10274. * Parse and execute the CLW command.
  10275. *
  10276. * Clear text of windows based on the parsed bitmask.
  10277. *
  10278. * @param {Integer} i Current index in the 708 packet
  10279. * @param {Service} service The service object to be affected
  10280. * @return {Integer} New index after parsing
  10281. */
  10282. Cea708Stream.prototype.clearWindows = function (i, service) {
  10283. var packetData = this.current708Packet.data;
  10284. var b = packetData[++i];
  10285. var pts = this.getPts(i);
  10286. this.flushDisplayed(pts, service);
  10287. for (var winId = 0; winId < 8; winId++) {
  10288. if (b & 0x01 << winId) {
  10289. service.windows[winId].clearText();
  10290. }
  10291. }
  10292. return i;
  10293. };
  10294. /**
  10295. * Parse and execute the DLW command.
  10296. *
  10297. * Re-initialize windows based on the parsed bitmask.
  10298. *
  10299. * @param {Integer} i Current index in the 708 packet
  10300. * @param {Service} service The service object to be affected
  10301. * @return {Integer} New index after parsing
  10302. */
  10303. Cea708Stream.prototype.deleteWindows = function (i, service) {
  10304. var packetData = this.current708Packet.data;
  10305. var b = packetData[++i];
  10306. var pts = this.getPts(i);
  10307. this.flushDisplayed(pts, service);
  10308. for (var winId = 0; winId < 8; winId++) {
  10309. if (b & 0x01 << winId) {
  10310. service.windows[winId].reset();
  10311. }
  10312. }
  10313. return i;
  10314. };
  10315. /**
  10316. * Parse and execute the SPA command.
  10317. *
  10318. * Set pen attributes of the current window.
  10319. *
  10320. * @param {Integer} i Current index in the 708 packet
  10321. * @param {Service} service The service object to be affected
  10322. * @return {Integer} New index after parsing
  10323. */
  10324. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  10325. var packetData = this.current708Packet.data;
  10326. var b = packetData[i];
  10327. var penAttr = service.currentWindow.penAttr;
  10328. b = packetData[++i];
  10329. penAttr.textTag = (b & 0xf0) >> 4; // tt
  10330. penAttr.offset = (b & 0x0c) >> 2; // o
  10331. penAttr.penSize = b & 0x03; // s
  10332. b = packetData[++i];
  10333. penAttr.italics = (b & 0x80) >> 7; // i
  10334. penAttr.underline = (b & 0x40) >> 6; // u
  10335. penAttr.edgeType = (b & 0x38) >> 3; // et
  10336. penAttr.fontStyle = b & 0x07; // fs
  10337. return i;
  10338. };
  10339. /**
  10340. * Parse and execute the SPC command.
  10341. *
  10342. * Set pen color of the current window.
  10343. *
  10344. * @param {Integer} i Current index in the 708 packet
  10345. * @param {Service} service The service object to be affected
  10346. * @return {Integer} New index after parsing
  10347. */
  10348. Cea708Stream.prototype.setPenColor = function (i, service) {
  10349. var packetData = this.current708Packet.data;
  10350. var b = packetData[i];
  10351. var penColor = service.currentWindow.penColor;
  10352. b = packetData[++i];
  10353. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  10354. penColor.fgRed = (b & 0x30) >> 4; // fr
  10355. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  10356. penColor.fgBlue = b & 0x03; // fb
  10357. b = packetData[++i];
  10358. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  10359. penColor.bgRed = (b & 0x30) >> 4; // br
  10360. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  10361. penColor.bgBlue = b & 0x03; // bb
  10362. b = packetData[++i];
  10363. penColor.edgeRed = (b & 0x30) >> 4; // er
  10364. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  10365. penColor.edgeBlue = b & 0x03; // eb
  10366. return i;
  10367. };
  10368. /**
  10369. * Parse and execute the SPL command.
  10370. *
  10371. * Set pen location of the current window.
  10372. *
  10373. * @param {Integer} i Current index in the 708 packet
  10374. * @param {Service} service The service object to be affected
  10375. * @return {Integer} New index after parsing
  10376. */
  10377. Cea708Stream.prototype.setPenLocation = function (i, service) {
  10378. var packetData = this.current708Packet.data;
  10379. var b = packetData[i];
  10380. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  10381. service.currentWindow.pendingNewLine = true;
  10382. b = packetData[++i];
  10383. penLoc.row = b & 0x0f; // r
  10384. b = packetData[++i];
  10385. penLoc.column = b & 0x3f; // c
  10386. return i;
  10387. };
  10388. /**
  10389. * Execute the RST command.
  10390. *
  10391. * Reset service to a clean slate. Re-initialize.
  10392. *
  10393. * @param {Integer} i Current index in the 708 packet
  10394. * @param {Service} service The service object to be affected
  10395. * @return {Service} Re-initialized service
  10396. */
  10397. Cea708Stream.prototype.reset = function (i, service) {
  10398. var pts = this.getPts(i);
  10399. this.flushDisplayed(pts, service);
  10400. return this.initService(service.serviceNum, i);
  10401. }; // This hash maps non-ASCII, special, and extended character codes to their
  10402. // proper Unicode equivalent. The first keys that are only a single byte
  10403. // are the non-standard ASCII characters, which simply map the CEA608 byte
  10404. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  10405. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  10406. // can be performed regardless of the field and data channel on which the
  10407. // character code was received.
  10408. var CHARACTER_TRANSLATION = {
  10409. 0x2a: 0xe1,
  10410. // á
  10411. 0x5c: 0xe9,
  10412. // é
  10413. 0x5e: 0xed,
  10414. // í
  10415. 0x5f: 0xf3,
  10416. // ó
  10417. 0x60: 0xfa,
  10418. // ú
  10419. 0x7b: 0xe7,
  10420. // ç
  10421. 0x7c: 0xf7,
  10422. // ÷
  10423. 0x7d: 0xd1,
  10424. // Ñ
  10425. 0x7e: 0xf1,
  10426. // ñ
  10427. 0x7f: 0x2588,
  10428. // █
  10429. 0x0130: 0xae,
  10430. // ®
  10431. 0x0131: 0xb0,
  10432. // °
  10433. 0x0132: 0xbd,
  10434. // ½
  10435. 0x0133: 0xbf,
  10436. // ¿
  10437. 0x0134: 0x2122,
  10438. // ™
  10439. 0x0135: 0xa2,
  10440. // ¢
  10441. 0x0136: 0xa3,
  10442. // £
  10443. 0x0137: 0x266a,
  10444. // ♪
  10445. 0x0138: 0xe0,
  10446. // à
  10447. 0x0139: 0xa0,
  10448. //
  10449. 0x013a: 0xe8,
  10450. // è
  10451. 0x013b: 0xe2,
  10452. // â
  10453. 0x013c: 0xea,
  10454. // ê
  10455. 0x013d: 0xee,
  10456. // î
  10457. 0x013e: 0xf4,
  10458. // ô
  10459. 0x013f: 0xfb,
  10460. // û
  10461. 0x0220: 0xc1,
  10462. // Á
  10463. 0x0221: 0xc9,
  10464. // É
  10465. 0x0222: 0xd3,
  10466. // Ó
  10467. 0x0223: 0xda,
  10468. // Ú
  10469. 0x0224: 0xdc,
  10470. // Ü
  10471. 0x0225: 0xfc,
  10472. // ü
  10473. 0x0226: 0x2018,
  10474. // ‘
  10475. 0x0227: 0xa1,
  10476. // ¡
  10477. 0x0228: 0x2a,
  10478. // *
  10479. 0x0229: 0x27,
  10480. // '
  10481. 0x022a: 0x2014,
  10482. // —
  10483. 0x022b: 0xa9,
  10484. // ©
  10485. 0x022c: 0x2120,
  10486. // ℠
  10487. 0x022d: 0x2022,
  10488. // •
  10489. 0x022e: 0x201c,
  10490. // “
  10491. 0x022f: 0x201d,
  10492. // ”
  10493. 0x0230: 0xc0,
  10494. // À
  10495. 0x0231: 0xc2,
  10496. // Â
  10497. 0x0232: 0xc7,
  10498. // Ç
  10499. 0x0233: 0xc8,
  10500. // È
  10501. 0x0234: 0xca,
  10502. // Ê
  10503. 0x0235: 0xcb,
  10504. // Ë
  10505. 0x0236: 0xeb,
  10506. // ë
  10507. 0x0237: 0xce,
  10508. // Î
  10509. 0x0238: 0xcf,
  10510. // Ï
  10511. 0x0239: 0xef,
  10512. // ï
  10513. 0x023a: 0xd4,
  10514. // Ô
  10515. 0x023b: 0xd9,
  10516. // Ù
  10517. 0x023c: 0xf9,
  10518. // ù
  10519. 0x023d: 0xdb,
  10520. // Û
  10521. 0x023e: 0xab,
  10522. // «
  10523. 0x023f: 0xbb,
  10524. // »
  10525. 0x0320: 0xc3,
  10526. // Ã
  10527. 0x0321: 0xe3,
  10528. // ã
  10529. 0x0322: 0xcd,
  10530. // Í
  10531. 0x0323: 0xcc,
  10532. // Ì
  10533. 0x0324: 0xec,
  10534. // ì
  10535. 0x0325: 0xd2,
  10536. // Ò
  10537. 0x0326: 0xf2,
  10538. // ò
  10539. 0x0327: 0xd5,
  10540. // Õ
  10541. 0x0328: 0xf5,
  10542. // õ
  10543. 0x0329: 0x7b,
  10544. // {
  10545. 0x032a: 0x7d,
  10546. // }
  10547. 0x032b: 0x5c,
  10548. // \
  10549. 0x032c: 0x5e,
  10550. // ^
  10551. 0x032d: 0x5f,
  10552. // _
  10553. 0x032e: 0x7c,
  10554. // |
  10555. 0x032f: 0x7e,
  10556. // ~
  10557. 0x0330: 0xc4,
  10558. // Ä
  10559. 0x0331: 0xe4,
  10560. // ä
  10561. 0x0332: 0xd6,
  10562. // Ö
  10563. 0x0333: 0xf6,
  10564. // ö
  10565. 0x0334: 0xdf,
  10566. // ß
  10567. 0x0335: 0xa5,
  10568. // ¥
  10569. 0x0336: 0xa4,
  10570. // ¤
  10571. 0x0337: 0x2502,
  10572. // │
  10573. 0x0338: 0xc5,
  10574. // Å
  10575. 0x0339: 0xe5,
  10576. // å
  10577. 0x033a: 0xd8,
  10578. // Ø
  10579. 0x033b: 0xf8,
  10580. // ø
  10581. 0x033c: 0x250c,
  10582. // ┌
  10583. 0x033d: 0x2510,
  10584. // ┐
  10585. 0x033e: 0x2514,
  10586. // └
  10587. 0x033f: 0x2518 // ┘
  10588. };
  10589. var getCharFromCode = function (code) {
  10590. if (code === null) {
  10591. return '';
  10592. }
  10593. code = CHARACTER_TRANSLATION[code] || code;
  10594. return String.fromCharCode(code);
  10595. }; // the index of the last row in a CEA-608 display buffer
  10596. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  10597. // getting it through bit logic.
  10598. 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
  10599. // cells. The "bottom" row is the last element in the outer array.
  10600. var createDisplayBuffer = function () {
  10601. var result = [],
  10602. i = BOTTOM_ROW + 1;
  10603. while (i--) {
  10604. result.push('');
  10605. }
  10606. return result;
  10607. };
  10608. var Cea608Stream = function (field, dataChannel) {
  10609. Cea608Stream.prototype.init.call(this);
  10610. this.field_ = field || 0;
  10611. this.dataChannel_ = dataChannel || 0;
  10612. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  10613. this.setConstants();
  10614. this.reset();
  10615. this.push = function (packet) {
  10616. var data, swap, char0, char1, text; // remove the parity bits
  10617. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  10618. if (data === this.lastControlCode_) {
  10619. this.lastControlCode_ = null;
  10620. return;
  10621. } // Store control codes
  10622. if ((data & 0xf000) === 0x1000) {
  10623. this.lastControlCode_ = data;
  10624. } else if (data !== this.PADDING_) {
  10625. this.lastControlCode_ = null;
  10626. }
  10627. char0 = data >>> 8;
  10628. char1 = data & 0xff;
  10629. if (data === this.PADDING_) {
  10630. return;
  10631. } else if (data === this.RESUME_CAPTION_LOADING_) {
  10632. this.mode_ = 'popOn';
  10633. } else if (data === this.END_OF_CAPTION_) {
  10634. // If an EOC is received while in paint-on mode, the displayed caption
  10635. // text should be swapped to non-displayed memory as if it was a pop-on
  10636. // caption. Because of that, we should explicitly switch back to pop-on
  10637. // mode
  10638. this.mode_ = 'popOn';
  10639. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  10640. this.flushDisplayed(packet.pts); // flip memory
  10641. swap = this.displayed_;
  10642. this.displayed_ = this.nonDisplayed_;
  10643. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  10644. this.startPts_ = packet.pts;
  10645. } else if (data === this.ROLL_UP_2_ROWS_) {
  10646. this.rollUpRows_ = 2;
  10647. this.setRollUp(packet.pts);
  10648. } else if (data === this.ROLL_UP_3_ROWS_) {
  10649. this.rollUpRows_ = 3;
  10650. this.setRollUp(packet.pts);
  10651. } else if (data === this.ROLL_UP_4_ROWS_) {
  10652. this.rollUpRows_ = 4;
  10653. this.setRollUp(packet.pts);
  10654. } else if (data === this.CARRIAGE_RETURN_) {
  10655. this.clearFormatting(packet.pts);
  10656. this.flushDisplayed(packet.pts);
  10657. this.shiftRowsUp_();
  10658. this.startPts_ = packet.pts;
  10659. } else if (data === this.BACKSPACE_) {
  10660. if (this.mode_ === 'popOn') {
  10661. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  10662. } else {
  10663. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  10664. }
  10665. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  10666. this.flushDisplayed(packet.pts);
  10667. this.displayed_ = createDisplayBuffer();
  10668. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  10669. this.nonDisplayed_ = createDisplayBuffer();
  10670. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  10671. if (this.mode_ !== 'paintOn') {
  10672. // NOTE: This should be removed when proper caption positioning is
  10673. // implemented
  10674. this.flushDisplayed(packet.pts);
  10675. this.displayed_ = createDisplayBuffer();
  10676. }
  10677. this.mode_ = 'paintOn';
  10678. this.startPts_ = packet.pts; // Append special characters to caption text
  10679. } else if (this.isSpecialCharacter(char0, char1)) {
  10680. // Bitmask char0 so that we can apply character transformations
  10681. // regardless of field and data channel.
  10682. // Then byte-shift to the left and OR with char1 so we can pass the
  10683. // entire character code to `getCharFromCode`.
  10684. char0 = (char0 & 0x03) << 8;
  10685. text = getCharFromCode(char0 | char1);
  10686. this[this.mode_](packet.pts, text);
  10687. this.column_++; // Append extended characters to caption text
  10688. } else if (this.isExtCharacter(char0, char1)) {
  10689. // Extended characters always follow their "non-extended" equivalents.
  10690. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  10691. // decoders are supposed to drop the "è", while compliant decoders
  10692. // backspace the "e" and insert "è".
  10693. // Delete the previous character
  10694. if (this.mode_ === 'popOn') {
  10695. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  10696. } else {
  10697. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  10698. } // Bitmask char0 so that we can apply character transformations
  10699. // regardless of field and data channel.
  10700. // Then byte-shift to the left and OR with char1 so we can pass the
  10701. // entire character code to `getCharFromCode`.
  10702. char0 = (char0 & 0x03) << 8;
  10703. text = getCharFromCode(char0 | char1);
  10704. this[this.mode_](packet.pts, text);
  10705. this.column_++; // Process mid-row codes
  10706. } else if (this.isMidRowCode(char0, char1)) {
  10707. // Attributes are not additive, so clear all formatting
  10708. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  10709. // should be replaced with spaces, so add one now
  10710. this[this.mode_](packet.pts, ' ');
  10711. this.column_++;
  10712. if ((char1 & 0xe) === 0xe) {
  10713. this.addFormatting(packet.pts, ['i']);
  10714. }
  10715. if ((char1 & 0x1) === 0x1) {
  10716. this.addFormatting(packet.pts, ['u']);
  10717. } // Detect offset control codes and adjust cursor
  10718. } else if (this.isOffsetControlCode(char0, char1)) {
  10719. // Cursor position is set by indent PAC (see below) in 4-column
  10720. // increments, with an additional offset code of 1-3 to reach any
  10721. // of the 32 columns specified by CEA-608. So all we need to do
  10722. // here is increment the column cursor by the given offset.
  10723. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  10724. } else if (this.isPAC(char0, char1)) {
  10725. // There's no logic for PAC -> row mapping, so we have to just
  10726. // find the row code in an array and use its index :(
  10727. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  10728. if (this.mode_ === 'rollUp') {
  10729. // This implies that the base row is incorrectly set.
  10730. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  10731. // of roll-up rows set.
  10732. if (row - this.rollUpRows_ + 1 < 0) {
  10733. row = this.rollUpRows_ - 1;
  10734. }
  10735. this.setRollUp(packet.pts, row);
  10736. }
  10737. if (row !== this.row_) {
  10738. // formatting is only persistent for current row
  10739. this.clearFormatting(packet.pts);
  10740. this.row_ = row;
  10741. } // All PACs can apply underline, so detect and apply
  10742. // (All odd-numbered second bytes set underline)
  10743. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  10744. this.addFormatting(packet.pts, ['u']);
  10745. }
  10746. if ((data & 0x10) === 0x10) {
  10747. // We've got an indent level code. Each successive even number
  10748. // increments the column cursor by 4, so we can get the desired
  10749. // column position by bit-shifting to the right (to get n/2)
  10750. // and multiplying by 4.
  10751. this.column_ = ((data & 0xe) >> 1) * 4;
  10752. }
  10753. if (this.isColorPAC(char1)) {
  10754. // it's a color code, though we only support white, which
  10755. // can be either normal or italicized. white italics can be
  10756. // either 0x4e or 0x6e depending on the row, so we just
  10757. // bitwise-and with 0xe to see if italics should be turned on
  10758. if ((char1 & 0xe) === 0xe) {
  10759. this.addFormatting(packet.pts, ['i']);
  10760. }
  10761. } // We have a normal character in char0, and possibly one in char1
  10762. } else if (this.isNormalChar(char0)) {
  10763. if (char1 === 0x00) {
  10764. char1 = null;
  10765. }
  10766. text = getCharFromCode(char0);
  10767. text += getCharFromCode(char1);
  10768. this[this.mode_](packet.pts, text);
  10769. this.column_ += text.length;
  10770. } // finish data processing
  10771. };
  10772. };
  10773. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  10774. // display buffer
  10775. Cea608Stream.prototype.flushDisplayed = function (pts) {
  10776. var content = this.displayed_ // remove spaces from the start and end of the string
  10777. .map(function (row, index) {
  10778. try {
  10779. return row.trim();
  10780. } catch (e) {
  10781. // Ordinarily, this shouldn't happen. However, caption
  10782. // parsing errors should not throw exceptions and
  10783. // break playback.
  10784. this.trigger('log', {
  10785. level: 'warn',
  10786. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  10787. });
  10788. return '';
  10789. }
  10790. }, this) // combine all text rows to display in one cue
  10791. .join('\n') // and remove blank rows from the start and end, but not the middle
  10792. .replace(/^\n+|\n+$/g, '');
  10793. if (content.length) {
  10794. this.trigger('data', {
  10795. startPts: this.startPts_,
  10796. endPts: pts,
  10797. text: content,
  10798. stream: this.name_
  10799. });
  10800. }
  10801. };
  10802. /**
  10803. * Zero out the data, used for startup and on seek
  10804. */
  10805. Cea608Stream.prototype.reset = function () {
  10806. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  10807. // actually display captions. If a caption is shifted to a row
  10808. // with a lower index than this, it is cleared from the display
  10809. // buffer
  10810. this.topRow_ = 0;
  10811. this.startPts_ = 0;
  10812. this.displayed_ = createDisplayBuffer();
  10813. this.nonDisplayed_ = createDisplayBuffer();
  10814. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  10815. this.column_ = 0;
  10816. this.row_ = BOTTOM_ROW;
  10817. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  10818. this.formatting_ = [];
  10819. };
  10820. /**
  10821. * Sets up control code and related constants for this instance
  10822. */
  10823. Cea608Stream.prototype.setConstants = function () {
  10824. // The following attributes have these uses:
  10825. // ext_ : char0 for mid-row codes, and the base for extended
  10826. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  10827. // extended codes)
  10828. // control_: char0 for control codes, except byte-shifted to the
  10829. // left so that we can do this.control_ | CONTROL_CODE
  10830. // offset_: char0 for tab offset codes
  10831. //
  10832. // It's also worth noting that control codes, and _only_ control codes,
  10833. // differ between field 1 and field2. Field 2 control codes are always
  10834. // their field 1 value plus 1. That's why there's the "| field" on the
  10835. // control value.
  10836. if (this.dataChannel_ === 0) {
  10837. this.BASE_ = 0x10;
  10838. this.EXT_ = 0x11;
  10839. this.CONTROL_ = (0x14 | this.field_) << 8;
  10840. this.OFFSET_ = 0x17;
  10841. } else if (this.dataChannel_ === 1) {
  10842. this.BASE_ = 0x18;
  10843. this.EXT_ = 0x19;
  10844. this.CONTROL_ = (0x1c | this.field_) << 8;
  10845. this.OFFSET_ = 0x1f;
  10846. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  10847. // list is not exhaustive. For a more comprehensive listing and semantics see
  10848. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  10849. // Padding
  10850. this.PADDING_ = 0x0000; // Pop-on Mode
  10851. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  10852. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  10853. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  10854. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  10855. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  10856. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  10857. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  10858. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  10859. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  10860. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  10861. };
  10862. /**
  10863. * Detects if the 2-byte packet data is a special character
  10864. *
  10865. * Special characters have a second byte in the range 0x30 to 0x3f,
  10866. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  10867. * data channel 2).
  10868. *
  10869. * @param {Integer} char0 The first byte
  10870. * @param {Integer} char1 The second byte
  10871. * @return {Boolean} Whether the 2 bytes are an special character
  10872. */
  10873. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  10874. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  10875. };
  10876. /**
  10877. * Detects if the 2-byte packet data is an extended character
  10878. *
  10879. * Extended characters have a second byte in the range 0x20 to 0x3f,
  10880. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  10881. * 0x1a or 0x1b (for data channel 2).
  10882. *
  10883. * @param {Integer} char0 The first byte
  10884. * @param {Integer} char1 The second byte
  10885. * @return {Boolean} Whether the 2 bytes are an extended character
  10886. */
  10887. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  10888. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  10889. };
  10890. /**
  10891. * Detects if the 2-byte packet is a mid-row code
  10892. *
  10893. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  10894. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  10895. * channel 2).
  10896. *
  10897. * @param {Integer} char0 The first byte
  10898. * @param {Integer} char1 The second byte
  10899. * @return {Boolean} Whether the 2 bytes are a mid-row code
  10900. */
  10901. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  10902. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  10903. };
  10904. /**
  10905. * Detects if the 2-byte packet is an offset control code
  10906. *
  10907. * Offset control codes have a second byte in the range 0x21 to 0x23,
  10908. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  10909. * data channel 2).
  10910. *
  10911. * @param {Integer} char0 The first byte
  10912. * @param {Integer} char1 The second byte
  10913. * @return {Boolean} Whether the 2 bytes are an offset control code
  10914. */
  10915. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  10916. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  10917. };
  10918. /**
  10919. * Detects if the 2-byte packet is a Preamble Address Code
  10920. *
  10921. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  10922. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  10923. * range 0x40 to 0x7f.
  10924. *
  10925. * @param {Integer} char0 The first byte
  10926. * @param {Integer} char1 The second byte
  10927. * @return {Boolean} Whether the 2 bytes are a PAC
  10928. */
  10929. Cea608Stream.prototype.isPAC = function (char0, char1) {
  10930. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  10931. };
  10932. /**
  10933. * Detects if a packet's second byte is in the range of a PAC color code
  10934. *
  10935. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  10936. * 0x60 to 0x6f.
  10937. *
  10938. * @param {Integer} char1 The second byte
  10939. * @return {Boolean} Whether the byte is a color PAC
  10940. */
  10941. Cea608Stream.prototype.isColorPAC = function (char1) {
  10942. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  10943. };
  10944. /**
  10945. * Detects if a single byte is in the range of a normal character
  10946. *
  10947. * Normal text bytes are in the range 0x20 to 0x7f.
  10948. *
  10949. * @param {Integer} char The byte
  10950. * @return {Boolean} Whether the byte is a normal character
  10951. */
  10952. Cea608Stream.prototype.isNormalChar = function (char) {
  10953. return char >= 0x20 && char <= 0x7f;
  10954. };
  10955. /**
  10956. * Configures roll-up
  10957. *
  10958. * @param {Integer} pts Current PTS
  10959. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  10960. * a new position
  10961. */
  10962. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  10963. // Reset the base row to the bottom row when switching modes
  10964. if (this.mode_ !== 'rollUp') {
  10965. this.row_ = BOTTOM_ROW;
  10966. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  10967. this.flushDisplayed(pts);
  10968. this.nonDisplayed_ = createDisplayBuffer();
  10969. this.displayed_ = createDisplayBuffer();
  10970. }
  10971. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  10972. // move currently displayed captions (up or down) to the new base row
  10973. for (var i = 0; i < this.rollUpRows_; i++) {
  10974. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  10975. this.displayed_[this.row_ - i] = '';
  10976. }
  10977. }
  10978. if (newBaseRow === undefined) {
  10979. newBaseRow = this.row_;
  10980. }
  10981. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  10982. }; // Adds the opening HTML tag for the passed character to the caption text,
  10983. // and keeps track of it for later closing
  10984. Cea608Stream.prototype.addFormatting = function (pts, format) {
  10985. this.formatting_ = this.formatting_.concat(format);
  10986. var text = format.reduce(function (text, format) {
  10987. return text + '<' + format + '>';
  10988. }, '');
  10989. this[this.mode_](pts, text);
  10990. }; // Adds HTML closing tags for current formatting to caption text and
  10991. // clears remembered formatting
  10992. Cea608Stream.prototype.clearFormatting = function (pts) {
  10993. if (!this.formatting_.length) {
  10994. return;
  10995. }
  10996. var text = this.formatting_.reverse().reduce(function (text, format) {
  10997. return text + '</' + format + '>';
  10998. }, '');
  10999. this.formatting_ = [];
  11000. this[this.mode_](pts, text);
  11001. }; // Mode Implementations
  11002. Cea608Stream.prototype.popOn = function (pts, text) {
  11003. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  11004. baseRow += text;
  11005. this.nonDisplayed_[this.row_] = baseRow;
  11006. };
  11007. Cea608Stream.prototype.rollUp = function (pts, text) {
  11008. var baseRow = this.displayed_[this.row_];
  11009. baseRow += text;
  11010. this.displayed_[this.row_] = baseRow;
  11011. };
  11012. Cea608Stream.prototype.shiftRowsUp_ = function () {
  11013. var i; // clear out inactive rows
  11014. for (i = 0; i < this.topRow_; i++) {
  11015. this.displayed_[i] = '';
  11016. }
  11017. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  11018. this.displayed_[i] = '';
  11019. } // shift displayed rows up
  11020. for (i = this.topRow_; i < this.row_; i++) {
  11021. this.displayed_[i] = this.displayed_[i + 1];
  11022. } // clear out the bottom row
  11023. this.displayed_[this.row_] = '';
  11024. };
  11025. Cea608Stream.prototype.paintOn = function (pts, text) {
  11026. var baseRow = this.displayed_[this.row_];
  11027. baseRow += text;
  11028. this.displayed_[this.row_] = baseRow;
  11029. }; // exports
  11030. var captionStream = {
  11031. CaptionStream: CaptionStream$2,
  11032. Cea608Stream: Cea608Stream,
  11033. Cea708Stream: Cea708Stream
  11034. };
  11035. /**
  11036. * mux.js
  11037. *
  11038. * Copyright (c) Brightcove
  11039. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11040. */
  11041. var streamTypes = {
  11042. H264_STREAM_TYPE: 0x1B,
  11043. ADTS_STREAM_TYPE: 0x0F,
  11044. METADATA_STREAM_TYPE: 0x15
  11045. };
  11046. /**
  11047. * mux.js
  11048. *
  11049. * Copyright (c) Brightcove
  11050. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11051. *
  11052. * Accepts program elementary stream (PES) data events and corrects
  11053. * decode and presentation time stamps to account for a rollover
  11054. * of the 33 bit value.
  11055. */
  11056. var Stream$6 = stream;
  11057. var MAX_TS = 8589934592;
  11058. var RO_THRESH = 4294967296;
  11059. var TYPE_SHARED = 'shared';
  11060. var handleRollover$1 = function (value, reference) {
  11061. var direction = 1;
  11062. if (value > reference) {
  11063. // If the current timestamp value is greater than our reference timestamp and we detect a
  11064. // timestamp rollover, this means the roll over is happening in the opposite direction.
  11065. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  11066. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  11067. // rollover point. In loading this segment, the timestamp values will be very large,
  11068. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  11069. // the time stamp to be `value - 2^33`.
  11070. direction = -1;
  11071. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  11072. // cause an incorrect adjustment.
  11073. while (Math.abs(reference - value) > RO_THRESH) {
  11074. value += direction * MAX_TS;
  11075. }
  11076. return value;
  11077. };
  11078. var TimestampRolloverStream$1 = function (type) {
  11079. var lastDTS, referenceDTS;
  11080. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  11081. // video and audio. We could use `undefined` here, but having a string
  11082. // makes debugging a little clearer.
  11083. this.type_ = type || TYPE_SHARED;
  11084. this.push = function (data) {
  11085. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  11086. // streams will only accept data that matches their type.
  11087. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  11088. return;
  11089. }
  11090. if (referenceDTS === undefined) {
  11091. referenceDTS = data.dts;
  11092. }
  11093. data.dts = handleRollover$1(data.dts, referenceDTS);
  11094. data.pts = handleRollover$1(data.pts, referenceDTS);
  11095. lastDTS = data.dts;
  11096. this.trigger('data', data);
  11097. };
  11098. this.flush = function () {
  11099. referenceDTS = lastDTS;
  11100. this.trigger('done');
  11101. };
  11102. this.endTimeline = function () {
  11103. this.flush();
  11104. this.trigger('endedtimeline');
  11105. };
  11106. this.discontinuity = function () {
  11107. referenceDTS = void 0;
  11108. lastDTS = void 0;
  11109. };
  11110. this.reset = function () {
  11111. this.discontinuity();
  11112. this.trigger('reset');
  11113. };
  11114. };
  11115. TimestampRolloverStream$1.prototype = new Stream$6();
  11116. var timestampRolloverStream = {
  11117. TimestampRolloverStream: TimestampRolloverStream$1,
  11118. handleRollover: handleRollover$1
  11119. }; // Once IE11 support is dropped, this function should be removed.
  11120. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  11121. if (!typedArray) {
  11122. return -1;
  11123. }
  11124. var currentIndex = fromIndex;
  11125. for (; currentIndex < typedArray.length; currentIndex++) {
  11126. if (typedArray[currentIndex] === element) {
  11127. return currentIndex;
  11128. }
  11129. }
  11130. return -1;
  11131. };
  11132. var typedArray = {
  11133. typedArrayIndexOf: typedArrayIndexOf$1
  11134. };
  11135. /**
  11136. * mux.js
  11137. *
  11138. * Copyright (c) Brightcove
  11139. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11140. *
  11141. * Tools for parsing ID3 frame data
  11142. * @see http://id3.org/id3v2.3.0
  11143. */
  11144. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  11145. // Frames that allow different types of text encoding contain a text
  11146. // encoding description byte [ID3v2.4.0 section 4.]
  11147. textEncodingDescriptionByte = {
  11148. Iso88591: 0x00,
  11149. // ISO-8859-1, terminated with \0.
  11150. Utf16: 0x01,
  11151. // UTF-16 encoded Unicode BOM, terminated with \0\0
  11152. Utf16be: 0x02,
  11153. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  11154. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  11155. },
  11156. // return a percent-encoded representation of the specified byte range
  11157. // @see http://en.wikipedia.org/wiki/Percent-encoding
  11158. percentEncode$1 = function (bytes, start, end) {
  11159. var i,
  11160. result = '';
  11161. for (i = start; i < end; i++) {
  11162. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  11163. }
  11164. return result;
  11165. },
  11166. // return the string representation of the specified byte range,
  11167. // interpreted as UTf-8.
  11168. parseUtf8 = function (bytes, start, end) {
  11169. return decodeURIComponent(percentEncode$1(bytes, start, end));
  11170. },
  11171. // return the string representation of the specified byte range,
  11172. // interpreted as ISO-8859-1.
  11173. parseIso88591$1 = function (bytes, start, end) {
  11174. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  11175. },
  11176. parseSyncSafeInteger$1 = function (data) {
  11177. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  11178. },
  11179. frameParsers = {
  11180. 'APIC': function (frame) {
  11181. var i = 1,
  11182. mimeTypeEndIndex,
  11183. descriptionEndIndex,
  11184. LINK_MIME_TYPE = '-->';
  11185. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11186. // ignore frames with unrecognized character encodings
  11187. return;
  11188. } // parsing fields [ID3v2.4.0 section 4.14.]
  11189. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11190. if (mimeTypeEndIndex < 0) {
  11191. // malformed frame
  11192. return;
  11193. } // parsing Mime type field (terminated with \0)
  11194. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  11195. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  11196. frame.pictureType = frame.data[i];
  11197. i++;
  11198. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11199. if (descriptionEndIndex < 0) {
  11200. // malformed frame
  11201. return;
  11202. } // parsing Description field (terminated with \0)
  11203. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  11204. i = descriptionEndIndex + 1;
  11205. if (frame.mimeType === LINK_MIME_TYPE) {
  11206. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  11207. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  11208. } else {
  11209. // parsing Picture Data field as binary data
  11210. frame.pictureData = frame.data.subarray(i, frame.data.length);
  11211. }
  11212. },
  11213. 'T*': function (frame) {
  11214. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11215. // ignore frames with unrecognized character encodings
  11216. return;
  11217. } // parse text field, do not include null terminator in the frame value
  11218. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  11219. 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.]
  11220. frame.values = frame.value.split('\0');
  11221. },
  11222. 'TXXX': function (frame) {
  11223. var descriptionEndIndex;
  11224. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11225. // ignore frames with unrecognized character encodings
  11226. return;
  11227. }
  11228. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  11229. if (descriptionEndIndex === -1) {
  11230. return;
  11231. } // parse the text fields
  11232. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  11233. // frames that allow different types of encoding contain terminated text
  11234. // [ID3v2.4.0 section 4.]
  11235. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  11236. frame.data = frame.value;
  11237. },
  11238. 'W*': function (frame) {
  11239. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  11240. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  11241. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  11242. },
  11243. 'WXXX': function (frame) {
  11244. var descriptionEndIndex;
  11245. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11246. // ignore frames with unrecognized character encodings
  11247. return;
  11248. }
  11249. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  11250. if (descriptionEndIndex === -1) {
  11251. return;
  11252. } // parse the description and URL fields
  11253. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  11254. // if the value is followed by a string termination all the following information
  11255. // should be ignored [ID3v2.4.0 section 4.3]
  11256. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  11257. },
  11258. 'PRIV': function (frame) {
  11259. var i;
  11260. for (i = 0; i < frame.data.length; i++) {
  11261. if (frame.data[i] === 0) {
  11262. // parse the description and URL fields
  11263. frame.owner = parseIso88591$1(frame.data, 0, i);
  11264. break;
  11265. }
  11266. }
  11267. frame.privateData = frame.data.subarray(i + 1);
  11268. frame.data = frame.privateData;
  11269. }
  11270. };
  11271. var parseId3Frames$1 = function (data) {
  11272. var frameSize,
  11273. frameHeader,
  11274. frameStart = 10,
  11275. tagSize = 0,
  11276. frames = []; // If we don't have enough data for a header, 10 bytes,
  11277. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  11278. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  11279. return;
  11280. } // the frame size is transmitted as a 28-bit integer in the
  11281. // last four bytes of the ID3 header.
  11282. // The most significant bit of each byte is dropped and the
  11283. // results concatenated to recover the actual value.
  11284. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  11285. // convenient for our comparisons to include it
  11286. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  11287. var hasExtendedHeader = data[5] & 0x40;
  11288. if (hasExtendedHeader) {
  11289. // advance the frame start past the extended header
  11290. frameStart += 4; // header size field
  11291. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  11292. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  11293. } // parse one or more ID3 frames
  11294. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  11295. do {
  11296. // determine the number of bytes in this frame
  11297. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  11298. if (frameSize < 1) {
  11299. break;
  11300. }
  11301. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  11302. var frame = {
  11303. id: frameHeader,
  11304. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  11305. };
  11306. frame.key = frame.id; // parse frame values
  11307. if (frameParsers[frame.id]) {
  11308. // use frame specific parser
  11309. frameParsers[frame.id](frame);
  11310. } else if (frame.id[0] === 'T') {
  11311. // use text frame generic parser
  11312. frameParsers['T*'](frame);
  11313. } else if (frame.id[0] === 'W') {
  11314. // use URL link frame generic parser
  11315. frameParsers['W*'](frame);
  11316. }
  11317. frames.push(frame);
  11318. frameStart += 10; // advance past the frame header
  11319. frameStart += frameSize; // advance past the frame body
  11320. } while (frameStart < tagSize);
  11321. return frames;
  11322. };
  11323. var parseId3 = {
  11324. parseId3Frames: parseId3Frames$1,
  11325. parseSyncSafeInteger: parseSyncSafeInteger$1,
  11326. frameParsers: frameParsers
  11327. };
  11328. /**
  11329. * mux.js
  11330. *
  11331. * Copyright (c) Brightcove
  11332. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11333. *
  11334. * Accepts program elementary stream (PES) data events and parses out
  11335. * ID3 metadata from them, if present.
  11336. * @see http://id3.org/id3v2.3.0
  11337. */
  11338. var Stream$5 = stream,
  11339. StreamTypes$3 = streamTypes,
  11340. id3 = parseId3,
  11341. MetadataStream;
  11342. MetadataStream = function (options) {
  11343. var settings = {
  11344. // the bytes of the program-level descriptor field in MP2T
  11345. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  11346. // program element descriptors"
  11347. descriptor: options && options.descriptor
  11348. },
  11349. // the total size in bytes of the ID3 tag being parsed
  11350. tagSize = 0,
  11351. // tag data that is not complete enough to be parsed
  11352. buffer = [],
  11353. // the total number of bytes currently in the buffer
  11354. bufferSize = 0,
  11355. i;
  11356. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  11357. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  11358. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  11359. if (settings.descriptor) {
  11360. for (i = 0; i < settings.descriptor.length; i++) {
  11361. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  11362. }
  11363. }
  11364. this.push = function (chunk) {
  11365. var tag, frameStart, frameSize, frame, i, frameHeader;
  11366. if (chunk.type !== 'timed-metadata') {
  11367. return;
  11368. } // if data_alignment_indicator is set in the PES header,
  11369. // we must have the start of a new ID3 tag. Assume anything
  11370. // remaining in the buffer was malformed and throw it out
  11371. if (chunk.dataAlignmentIndicator) {
  11372. bufferSize = 0;
  11373. buffer.length = 0;
  11374. } // ignore events that don't look like ID3 data
  11375. 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))) {
  11376. this.trigger('log', {
  11377. level: 'warn',
  11378. message: 'Skipping unrecognized metadata packet'
  11379. });
  11380. return;
  11381. } // add this chunk to the data we've collected so far
  11382. buffer.push(chunk);
  11383. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  11384. if (buffer.length === 1) {
  11385. // the frame size is transmitted as a 28-bit integer in the
  11386. // last four bytes of the ID3 header.
  11387. // The most significant bit of each byte is dropped and the
  11388. // results concatenated to recover the actual value.
  11389. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  11390. // convenient for our comparisons to include it
  11391. tagSize += 10;
  11392. } // if the entire frame has not arrived, wait for more data
  11393. if (bufferSize < tagSize) {
  11394. return;
  11395. } // collect the entire frame so it can be parsed
  11396. tag = {
  11397. data: new Uint8Array(tagSize),
  11398. frames: [],
  11399. pts: buffer[0].pts,
  11400. dts: buffer[0].dts
  11401. };
  11402. for (i = 0; i < tagSize;) {
  11403. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  11404. i += buffer[0].data.byteLength;
  11405. bufferSize -= buffer[0].data.byteLength;
  11406. buffer.shift();
  11407. } // find the start of the first frame and the end of the tag
  11408. frameStart = 10;
  11409. if (tag.data[5] & 0x40) {
  11410. // advance the frame start past the extended header
  11411. frameStart += 4; // header size field
  11412. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  11413. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  11414. } // parse one or more ID3 frames
  11415. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  11416. do {
  11417. // determine the number of bytes in this frame
  11418. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  11419. if (frameSize < 1) {
  11420. this.trigger('log', {
  11421. level: 'warn',
  11422. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  11423. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  11424. // to be sent along.
  11425. break;
  11426. }
  11427. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  11428. frame = {
  11429. id: frameHeader,
  11430. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  11431. };
  11432. frame.key = frame.id; // parse frame values
  11433. if (id3.frameParsers[frame.id]) {
  11434. // use frame specific parser
  11435. id3.frameParsers[frame.id](frame);
  11436. } else if (frame.id[0] === 'T') {
  11437. // use text frame generic parser
  11438. id3.frameParsers['T*'](frame);
  11439. } else if (frame.id[0] === 'W') {
  11440. // use URL link frame generic parser
  11441. id3.frameParsers['W*'](frame);
  11442. } // handle the special PRIV frame used to indicate the start
  11443. // time for raw AAC data
  11444. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  11445. var d = frame.data,
  11446. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  11447. size *= 4;
  11448. size += d[7] & 0x03;
  11449. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  11450. // on the value of this frame
  11451. // we couldn't have known the appropriate pts and dts before
  11452. // parsing this ID3 tag so set those values now
  11453. if (tag.pts === undefined && tag.dts === undefined) {
  11454. tag.pts = frame.timeStamp;
  11455. tag.dts = frame.timeStamp;
  11456. }
  11457. this.trigger('timestamp', frame);
  11458. }
  11459. tag.frames.push(frame);
  11460. frameStart += 10; // advance past the frame header
  11461. frameStart += frameSize; // advance past the frame body
  11462. } while (frameStart < tagSize);
  11463. this.trigger('data', tag);
  11464. };
  11465. };
  11466. MetadataStream.prototype = new Stream$5();
  11467. var metadataStream = MetadataStream;
  11468. /**
  11469. * mux.js
  11470. *
  11471. * Copyright (c) Brightcove
  11472. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11473. *
  11474. * A stream-based mp2t to mp4 converter. This utility can be used to
  11475. * deliver mp4s to a SourceBuffer on platforms that support native
  11476. * Media Source Extensions.
  11477. */
  11478. var Stream$4 = stream,
  11479. CaptionStream$1 = captionStream,
  11480. StreamTypes$2 = streamTypes,
  11481. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  11482. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  11483. var MP2T_PACKET_LENGTH$1 = 188,
  11484. // bytes
  11485. SYNC_BYTE$1 = 0x47;
  11486. /**
  11487. * Splits an incoming stream of binary data into MPEG-2 Transport
  11488. * Stream packets.
  11489. */
  11490. TransportPacketStream = function () {
  11491. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  11492. bytesInBuffer = 0;
  11493. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  11494. /**
  11495. * Split a stream of data into M2TS packets
  11496. **/
  11497. this.push = function (bytes) {
  11498. var startIndex = 0,
  11499. endIndex = MP2T_PACKET_LENGTH$1,
  11500. everything; // If there are bytes remaining from the last segment, prepend them to the
  11501. // bytes that were pushed in
  11502. if (bytesInBuffer) {
  11503. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  11504. everything.set(buffer.subarray(0, bytesInBuffer));
  11505. everything.set(bytes, bytesInBuffer);
  11506. bytesInBuffer = 0;
  11507. } else {
  11508. everything = bytes;
  11509. } // While we have enough data for a packet
  11510. while (endIndex < everything.byteLength) {
  11511. // Look for a pair of start and end sync bytes in the data..
  11512. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  11513. // We found a packet so emit it and jump one whole packet forward in
  11514. // the stream
  11515. this.trigger('data', everything.subarray(startIndex, endIndex));
  11516. startIndex += MP2T_PACKET_LENGTH$1;
  11517. endIndex += MP2T_PACKET_LENGTH$1;
  11518. continue;
  11519. } // If we get here, we have somehow become de-synchronized and we need to step
  11520. // forward one byte at a time until we find a pair of sync bytes that denote
  11521. // a packet
  11522. startIndex++;
  11523. endIndex++;
  11524. } // If there was some data left over at the end of the segment that couldn't
  11525. // possibly be a whole packet, keep it because it might be the start of a packet
  11526. // that continues in the next segment
  11527. if (startIndex < everything.byteLength) {
  11528. buffer.set(everything.subarray(startIndex), 0);
  11529. bytesInBuffer = everything.byteLength - startIndex;
  11530. }
  11531. };
  11532. /**
  11533. * Passes identified M2TS packets to the TransportParseStream to be parsed
  11534. **/
  11535. this.flush = function () {
  11536. // If the buffer contains a whole packet when we are being flushed, emit it
  11537. // and empty the buffer. Otherwise hold onto the data because it may be
  11538. // important for decoding the next segment
  11539. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  11540. this.trigger('data', buffer);
  11541. bytesInBuffer = 0;
  11542. }
  11543. this.trigger('done');
  11544. };
  11545. this.endTimeline = function () {
  11546. this.flush();
  11547. this.trigger('endedtimeline');
  11548. };
  11549. this.reset = function () {
  11550. bytesInBuffer = 0;
  11551. this.trigger('reset');
  11552. };
  11553. };
  11554. TransportPacketStream.prototype = new Stream$4();
  11555. /**
  11556. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  11557. * forms of the individual transport stream packets.
  11558. */
  11559. TransportParseStream = function () {
  11560. var parsePsi, parsePat, parsePmt, self;
  11561. TransportParseStream.prototype.init.call(this);
  11562. self = this;
  11563. this.packetsWaitingForPmt = [];
  11564. this.programMapTable = undefined;
  11565. parsePsi = function (payload, psi) {
  11566. var offset = 0; // PSI packets may be split into multiple sections and those
  11567. // sections may be split into multiple packets. If a PSI
  11568. // section starts in this packet, the payload_unit_start_indicator
  11569. // will be true and the first byte of the payload will indicate
  11570. // the offset from the current position to the start of the
  11571. // section.
  11572. if (psi.payloadUnitStartIndicator) {
  11573. offset += payload[offset] + 1;
  11574. }
  11575. if (psi.type === 'pat') {
  11576. parsePat(payload.subarray(offset), psi);
  11577. } else {
  11578. parsePmt(payload.subarray(offset), psi);
  11579. }
  11580. };
  11581. parsePat = function (payload, pat) {
  11582. pat.section_number = payload[7]; // eslint-disable-line camelcase
  11583. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  11584. // skip the PSI header and parse the first PMT entry
  11585. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  11586. pat.pmtPid = self.pmtPid;
  11587. };
  11588. /**
  11589. * Parse out the relevant fields of a Program Map Table (PMT).
  11590. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  11591. * packet. The first byte in this array should be the table_id
  11592. * field.
  11593. * @param pmt {object} the object that should be decorated with
  11594. * fields parsed from the PMT.
  11595. */
  11596. parsePmt = function (payload, pmt) {
  11597. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  11598. // take effect. We don't believe this should ever be the case
  11599. // for HLS but we'll ignore "forward" PMT declarations if we see
  11600. // them. Future PMT declarations have the current_next_indicator
  11601. // set to zero.
  11602. if (!(payload[5] & 0x01)) {
  11603. return;
  11604. } // overwrite any existing program map table
  11605. self.programMapTable = {
  11606. video: null,
  11607. audio: null,
  11608. 'timed-metadata': {}
  11609. }; // the mapping table ends at the end of the current section
  11610. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  11611. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  11612. // long the program info descriptors are
  11613. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  11614. offset = 12 + programInfoLength;
  11615. while (offset < tableEnd) {
  11616. var streamType = payload[offset];
  11617. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  11618. // TODO: should this be done for metadata too? for now maintain behavior of
  11619. // multiple metadata streams
  11620. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  11621. self.programMapTable.video = pid;
  11622. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  11623. self.programMapTable.audio = pid;
  11624. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  11625. // map pid to stream type for metadata streams
  11626. self.programMapTable['timed-metadata'][pid] = streamType;
  11627. } // move to the next table entry
  11628. // skip past the elementary stream descriptors, if present
  11629. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  11630. } // record the map on the packet as well
  11631. pmt.programMapTable = self.programMapTable;
  11632. };
  11633. /**
  11634. * Deliver a new MP2T packet to the next stream in the pipeline.
  11635. */
  11636. this.push = function (packet) {
  11637. var result = {},
  11638. offset = 4;
  11639. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  11640. result.pid = packet[1] & 0x1f;
  11641. result.pid <<= 8;
  11642. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  11643. // fifth byte of the TS packet header. The adaptation field is
  11644. // used to add stuffing to PES packets that don't fill a complete
  11645. // TS packet, and to specify some forms of timing and control data
  11646. // that we do not currently use.
  11647. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  11648. offset += packet[offset] + 1;
  11649. } // parse the rest of the packet based on the type
  11650. if (result.pid === 0) {
  11651. result.type = 'pat';
  11652. parsePsi(packet.subarray(offset), result);
  11653. this.trigger('data', result);
  11654. } else if (result.pid === this.pmtPid) {
  11655. result.type = 'pmt';
  11656. parsePsi(packet.subarray(offset), result);
  11657. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  11658. while (this.packetsWaitingForPmt.length) {
  11659. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  11660. }
  11661. } else if (this.programMapTable === undefined) {
  11662. // When we have not seen a PMT yet, defer further processing of
  11663. // PES packets until one has been parsed
  11664. this.packetsWaitingForPmt.push([packet, offset, result]);
  11665. } else {
  11666. this.processPes_(packet, offset, result);
  11667. }
  11668. };
  11669. this.processPes_ = function (packet, offset, result) {
  11670. // set the appropriate stream type
  11671. if (result.pid === this.programMapTable.video) {
  11672. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  11673. } else if (result.pid === this.programMapTable.audio) {
  11674. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  11675. } else {
  11676. // if not video or audio, it is timed-metadata or unknown
  11677. // if unknown, streamType will be undefined
  11678. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  11679. }
  11680. result.type = 'pes';
  11681. result.data = packet.subarray(offset);
  11682. this.trigger('data', result);
  11683. };
  11684. };
  11685. TransportParseStream.prototype = new Stream$4();
  11686. TransportParseStream.STREAM_TYPES = {
  11687. h264: 0x1b,
  11688. adts: 0x0f
  11689. };
  11690. /**
  11691. * Reconsistutes program elementary stream (PES) packets from parsed
  11692. * transport stream packets. That is, if you pipe an
  11693. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  11694. * events will be events which capture the bytes for individual PES
  11695. * packets plus relevant metadata that has been extracted from the
  11696. * container.
  11697. */
  11698. ElementaryStream = function () {
  11699. var self = this,
  11700. segmentHadPmt = false,
  11701. // PES packet fragments
  11702. video = {
  11703. data: [],
  11704. size: 0
  11705. },
  11706. audio = {
  11707. data: [],
  11708. size: 0
  11709. },
  11710. timedMetadata = {
  11711. data: [],
  11712. size: 0
  11713. },
  11714. programMapTable,
  11715. parsePes = function (payload, pes) {
  11716. var ptsDtsFlags;
  11717. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  11718. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  11719. // that are frame data that is continuing from the previous fragment. This
  11720. // is to check that the pes data is the start of a new pes payload
  11721. if (startPrefix !== 1) {
  11722. return;
  11723. } // get the packet length, this will be 0 for video
  11724. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  11725. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  11726. // and a DTS value. Determine what combination of values is
  11727. // available to work with.
  11728. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  11729. // performs all bitwise operations on 32-bit integers but javascript
  11730. // supports a much greater range (52-bits) of integer using standard
  11731. // mathematical operations.
  11732. // We construct a 31-bit value using bitwise operators over the 31
  11733. // most significant bits and then multiply by 4 (equal to a left-shift
  11734. // of 2) before we add the final 2 least significant bits of the
  11735. // timestamp (equal to an OR.)
  11736. if (ptsDtsFlags & 0xC0) {
  11737. // the PTS and DTS are not written out directly. For information
  11738. // on how they are encoded, see
  11739. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  11740. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  11741. pes.pts *= 4; // Left shift by 2
  11742. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  11743. pes.dts = pes.pts;
  11744. if (ptsDtsFlags & 0x40) {
  11745. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  11746. pes.dts *= 4; // Left shift by 2
  11747. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  11748. }
  11749. } // the data section starts immediately after the PES header.
  11750. // pes_header_data_length specifies the number of header bytes
  11751. // that follow the last byte of the field.
  11752. pes.data = payload.subarray(9 + payload[8]);
  11753. },
  11754. /**
  11755. * Pass completely parsed PES packets to the next stream in the pipeline
  11756. **/
  11757. flushStream = function (stream, type, forceFlush) {
  11758. var packetData = new Uint8Array(stream.size),
  11759. event = {
  11760. type: type
  11761. },
  11762. i = 0,
  11763. offset = 0,
  11764. packetFlushable = false,
  11765. fragment; // do nothing if there is not enough buffered data for a complete
  11766. // PES header
  11767. if (!stream.data.length || stream.size < 9) {
  11768. return;
  11769. }
  11770. event.trackId = stream.data[0].pid; // reassemble the packet
  11771. for (i = 0; i < stream.data.length; i++) {
  11772. fragment = stream.data[i];
  11773. packetData.set(fragment.data, offset);
  11774. offset += fragment.data.byteLength;
  11775. } // parse assembled packet's PES header
  11776. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  11777. // check that there is enough stream data to fill the packet
  11778. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  11779. if (forceFlush || packetFlushable) {
  11780. stream.size = 0;
  11781. stream.data.length = 0;
  11782. } // only emit packets that are complete. this is to avoid assembling
  11783. // incomplete PES packets due to poor segmentation
  11784. if (packetFlushable) {
  11785. self.trigger('data', event);
  11786. }
  11787. };
  11788. ElementaryStream.prototype.init.call(this);
  11789. /**
  11790. * Identifies M2TS packet types and parses PES packets using metadata
  11791. * parsed from the PMT
  11792. **/
  11793. this.push = function (data) {
  11794. ({
  11795. pat: function () {// we have to wait for the PMT to arrive as well before we
  11796. // have any meaningful metadata
  11797. },
  11798. pes: function () {
  11799. var stream, streamType;
  11800. switch (data.streamType) {
  11801. case StreamTypes$2.H264_STREAM_TYPE:
  11802. stream = video;
  11803. streamType = 'video';
  11804. break;
  11805. case StreamTypes$2.ADTS_STREAM_TYPE:
  11806. stream = audio;
  11807. streamType = 'audio';
  11808. break;
  11809. case StreamTypes$2.METADATA_STREAM_TYPE:
  11810. stream = timedMetadata;
  11811. streamType = 'timed-metadata';
  11812. break;
  11813. default:
  11814. // ignore unknown stream types
  11815. return;
  11816. } // if a new packet is starting, we can flush the completed
  11817. // packet
  11818. if (data.payloadUnitStartIndicator) {
  11819. flushStream(stream, streamType, true);
  11820. } // buffer this fragment until we are sure we've received the
  11821. // complete payload
  11822. stream.data.push(data);
  11823. stream.size += data.data.byteLength;
  11824. },
  11825. pmt: function () {
  11826. var event = {
  11827. type: 'metadata',
  11828. tracks: []
  11829. };
  11830. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  11831. if (programMapTable.video !== null) {
  11832. event.tracks.push({
  11833. timelineStartInfo: {
  11834. baseMediaDecodeTime: 0
  11835. },
  11836. id: +programMapTable.video,
  11837. codec: 'avc',
  11838. type: 'video'
  11839. });
  11840. }
  11841. if (programMapTable.audio !== null) {
  11842. event.tracks.push({
  11843. timelineStartInfo: {
  11844. baseMediaDecodeTime: 0
  11845. },
  11846. id: +programMapTable.audio,
  11847. codec: 'adts',
  11848. type: 'audio'
  11849. });
  11850. }
  11851. segmentHadPmt = true;
  11852. self.trigger('data', event);
  11853. }
  11854. })[data.type]();
  11855. };
  11856. this.reset = function () {
  11857. video.size = 0;
  11858. video.data.length = 0;
  11859. audio.size = 0;
  11860. audio.data.length = 0;
  11861. this.trigger('reset');
  11862. };
  11863. /**
  11864. * Flush any remaining input. Video PES packets may be of variable
  11865. * length. Normally, the start of a new video packet can trigger the
  11866. * finalization of the previous packet. That is not possible if no
  11867. * more video is forthcoming, however. In that case, some other
  11868. * mechanism (like the end of the file) has to be employed. When it is
  11869. * clear that no additional data is forthcoming, calling this method
  11870. * will flush the buffered packets.
  11871. */
  11872. this.flushStreams_ = function () {
  11873. // !!THIS ORDER IS IMPORTANT!!
  11874. // video first then audio
  11875. flushStream(video, 'video');
  11876. flushStream(audio, 'audio');
  11877. flushStream(timedMetadata, 'timed-metadata');
  11878. };
  11879. this.flush = function () {
  11880. // if on flush we haven't had a pmt emitted
  11881. // and we have a pmt to emit. emit the pmt
  11882. // so that we trigger a trackinfo downstream.
  11883. if (!segmentHadPmt && programMapTable) {
  11884. var pmt = {
  11885. type: 'metadata',
  11886. tracks: []
  11887. }; // translate audio and video streams to tracks
  11888. if (programMapTable.video !== null) {
  11889. pmt.tracks.push({
  11890. timelineStartInfo: {
  11891. baseMediaDecodeTime: 0
  11892. },
  11893. id: +programMapTable.video,
  11894. codec: 'avc',
  11895. type: 'video'
  11896. });
  11897. }
  11898. if (programMapTable.audio !== null) {
  11899. pmt.tracks.push({
  11900. timelineStartInfo: {
  11901. baseMediaDecodeTime: 0
  11902. },
  11903. id: +programMapTable.audio,
  11904. codec: 'adts',
  11905. type: 'audio'
  11906. });
  11907. }
  11908. self.trigger('data', pmt);
  11909. }
  11910. segmentHadPmt = false;
  11911. this.flushStreams_();
  11912. this.trigger('done');
  11913. };
  11914. };
  11915. ElementaryStream.prototype = new Stream$4();
  11916. var m2ts$1 = {
  11917. PAT_PID: 0x0000,
  11918. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  11919. TransportPacketStream: TransportPacketStream,
  11920. TransportParseStream: TransportParseStream,
  11921. ElementaryStream: ElementaryStream,
  11922. TimestampRolloverStream: TimestampRolloverStream,
  11923. CaptionStream: CaptionStream$1.CaptionStream,
  11924. Cea608Stream: CaptionStream$1.Cea608Stream,
  11925. Cea708Stream: CaptionStream$1.Cea708Stream,
  11926. MetadataStream: metadataStream
  11927. };
  11928. for (var type in StreamTypes$2) {
  11929. if (StreamTypes$2.hasOwnProperty(type)) {
  11930. m2ts$1[type] = StreamTypes$2[type];
  11931. }
  11932. }
  11933. var m2ts_1 = m2ts$1;
  11934. /**
  11935. * mux.js
  11936. *
  11937. * Copyright (c) Brightcove
  11938. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11939. */
  11940. var Stream$3 = stream;
  11941. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  11942. var AdtsStream$1;
  11943. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  11944. /*
  11945. * Accepts a ElementaryStream and emits data events with parsed
  11946. * AAC Audio Frames of the individual packets. Input audio in ADTS
  11947. * format is unpacked and re-emitted as AAC frames.
  11948. *
  11949. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  11950. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  11951. */
  11952. AdtsStream$1 = function (handlePartialSegments) {
  11953. var buffer,
  11954. frameNum = 0;
  11955. AdtsStream$1.prototype.init.call(this);
  11956. this.skipWarn_ = function (start, end) {
  11957. this.trigger('log', {
  11958. level: 'warn',
  11959. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  11960. });
  11961. };
  11962. this.push = function (packet) {
  11963. var i = 0,
  11964. frameLength,
  11965. protectionSkipBytes,
  11966. oldBuffer,
  11967. sampleCount,
  11968. adtsFrameDuration;
  11969. if (!handlePartialSegments) {
  11970. frameNum = 0;
  11971. }
  11972. if (packet.type !== 'audio') {
  11973. // ignore non-audio data
  11974. return;
  11975. } // Prepend any data in the buffer to the input data so that we can parse
  11976. // aac frames the cross a PES packet boundary
  11977. if (buffer && buffer.length) {
  11978. oldBuffer = buffer;
  11979. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  11980. buffer.set(oldBuffer);
  11981. buffer.set(packet.data, oldBuffer.byteLength);
  11982. } else {
  11983. buffer = packet.data;
  11984. } // unpack any ADTS frames which have been fully received
  11985. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  11986. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  11987. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  11988. while (i + 7 < buffer.length) {
  11989. // Look for the start of an ADTS header..
  11990. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  11991. if (typeof skip !== 'number') {
  11992. skip = i;
  11993. } // If a valid header was not found, jump one forward and attempt to
  11994. // find a valid ADTS header starting at the next byte
  11995. i++;
  11996. continue;
  11997. }
  11998. if (typeof skip === 'number') {
  11999. this.skipWarn_(skip, i);
  12000. skip = null;
  12001. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  12002. // end of the ADTS header
  12003. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  12004. // end of the sync sequence
  12005. // NOTE: frame length includes the size of the header
  12006. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  12007. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  12008. 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,
  12009. // then we have to wait for more data
  12010. if (buffer.byteLength - i < frameLength) {
  12011. break;
  12012. } // Otherwise, deliver the complete AAC frame
  12013. this.trigger('data', {
  12014. pts: packet.pts + frameNum * adtsFrameDuration,
  12015. dts: packet.dts + frameNum * adtsFrameDuration,
  12016. sampleCount: sampleCount,
  12017. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  12018. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  12019. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  12020. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  12021. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  12022. samplesize: 16,
  12023. // data is the frame without it's header
  12024. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  12025. });
  12026. frameNum++;
  12027. i += frameLength;
  12028. }
  12029. if (typeof skip === 'number') {
  12030. this.skipWarn_(skip, i);
  12031. skip = null;
  12032. } // remove processed bytes from the buffer.
  12033. buffer = buffer.subarray(i);
  12034. };
  12035. this.flush = function () {
  12036. frameNum = 0;
  12037. this.trigger('done');
  12038. };
  12039. this.reset = function () {
  12040. buffer = void 0;
  12041. this.trigger('reset');
  12042. };
  12043. this.endTimeline = function () {
  12044. buffer = void 0;
  12045. this.trigger('endedtimeline');
  12046. };
  12047. };
  12048. AdtsStream$1.prototype = new Stream$3();
  12049. var adts = AdtsStream$1;
  12050. /**
  12051. * mux.js
  12052. *
  12053. * Copyright (c) Brightcove
  12054. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12055. */
  12056. var ExpGolomb$1;
  12057. /**
  12058. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  12059. * scheme used by h264.
  12060. */
  12061. ExpGolomb$1 = function (workingData) {
  12062. var // the number of bytes left to examine in workingData
  12063. workingBytesAvailable = workingData.byteLength,
  12064. // the current word being examined
  12065. workingWord = 0,
  12066. // :uint
  12067. // the number of bits left to examine in the current word
  12068. workingBitsAvailable = 0; // :uint;
  12069. // ():uint
  12070. this.length = function () {
  12071. return 8 * workingBytesAvailable;
  12072. }; // ():uint
  12073. this.bitsAvailable = function () {
  12074. return 8 * workingBytesAvailable + workingBitsAvailable;
  12075. }; // ():void
  12076. this.loadWord = function () {
  12077. var position = workingData.byteLength - workingBytesAvailable,
  12078. workingBytes = new Uint8Array(4),
  12079. availableBytes = Math.min(4, workingBytesAvailable);
  12080. if (availableBytes === 0) {
  12081. throw new Error('no bytes available');
  12082. }
  12083. workingBytes.set(workingData.subarray(position, position + availableBytes));
  12084. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  12085. workingBitsAvailable = availableBytes * 8;
  12086. workingBytesAvailable -= availableBytes;
  12087. }; // (count:int):void
  12088. this.skipBits = function (count) {
  12089. var skipBytes; // :int
  12090. if (workingBitsAvailable > count) {
  12091. workingWord <<= count;
  12092. workingBitsAvailable -= count;
  12093. } else {
  12094. count -= workingBitsAvailable;
  12095. skipBytes = Math.floor(count / 8);
  12096. count -= skipBytes * 8;
  12097. workingBytesAvailable -= skipBytes;
  12098. this.loadWord();
  12099. workingWord <<= count;
  12100. workingBitsAvailable -= count;
  12101. }
  12102. }; // (size:int):uint
  12103. this.readBits = function (size) {
  12104. var bits = Math.min(workingBitsAvailable, size),
  12105. // :uint
  12106. valu = workingWord >>> 32 - bits; // :uint
  12107. // if size > 31, handle error
  12108. workingBitsAvailable -= bits;
  12109. if (workingBitsAvailable > 0) {
  12110. workingWord <<= bits;
  12111. } else if (workingBytesAvailable > 0) {
  12112. this.loadWord();
  12113. }
  12114. bits = size - bits;
  12115. if (bits > 0) {
  12116. return valu << bits | this.readBits(bits);
  12117. }
  12118. return valu;
  12119. }; // ():uint
  12120. this.skipLeadingZeros = function () {
  12121. var leadingZeroCount; // :uint
  12122. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  12123. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  12124. // the first bit of working word is 1
  12125. workingWord <<= leadingZeroCount;
  12126. workingBitsAvailable -= leadingZeroCount;
  12127. return leadingZeroCount;
  12128. }
  12129. } // we exhausted workingWord and still have not found a 1
  12130. this.loadWord();
  12131. return leadingZeroCount + this.skipLeadingZeros();
  12132. }; // ():void
  12133. this.skipUnsignedExpGolomb = function () {
  12134. this.skipBits(1 + this.skipLeadingZeros());
  12135. }; // ():void
  12136. this.skipExpGolomb = function () {
  12137. this.skipBits(1 + this.skipLeadingZeros());
  12138. }; // ():uint
  12139. this.readUnsignedExpGolomb = function () {
  12140. var clz = this.skipLeadingZeros(); // :uint
  12141. return this.readBits(clz + 1) - 1;
  12142. }; // ():int
  12143. this.readExpGolomb = function () {
  12144. var valu = this.readUnsignedExpGolomb(); // :int
  12145. if (0x01 & valu) {
  12146. // the number is odd if the low order bit is set
  12147. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  12148. }
  12149. return -1 * (valu >>> 1); // divide by two then make it negative
  12150. }; // Some convenience functions
  12151. // :Boolean
  12152. this.readBoolean = function () {
  12153. return this.readBits(1) === 1;
  12154. }; // ():int
  12155. this.readUnsignedByte = function () {
  12156. return this.readBits(8);
  12157. };
  12158. this.loadWord();
  12159. };
  12160. var expGolomb = ExpGolomb$1;
  12161. /**
  12162. * mux.js
  12163. *
  12164. * Copyright (c) Brightcove
  12165. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12166. */
  12167. var Stream$2 = stream;
  12168. var ExpGolomb = expGolomb;
  12169. var H264Stream$1, NalByteStream;
  12170. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  12171. /**
  12172. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  12173. */
  12174. NalByteStream = function () {
  12175. var syncPoint = 0,
  12176. i,
  12177. buffer;
  12178. NalByteStream.prototype.init.call(this);
  12179. /*
  12180. * Scans a byte stream and triggers a data event with the NAL units found.
  12181. * @param {Object} data Event received from H264Stream
  12182. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  12183. *
  12184. * @see H264Stream.push
  12185. */
  12186. this.push = function (data) {
  12187. var swapBuffer;
  12188. if (!buffer) {
  12189. buffer = data.data;
  12190. } else {
  12191. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  12192. swapBuffer.set(buffer);
  12193. swapBuffer.set(data.data, buffer.byteLength);
  12194. buffer = swapBuffer;
  12195. }
  12196. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  12197. // scan for NAL unit boundaries
  12198. // a match looks like this:
  12199. // 0 0 1 .. NAL .. 0 0 1
  12200. // ^ sync point ^ i
  12201. // or this:
  12202. // 0 0 1 .. NAL .. 0 0 0
  12203. // ^ sync point ^ i
  12204. // advance the sync point to a NAL start, if necessary
  12205. for (; syncPoint < len - 3; syncPoint++) {
  12206. if (buffer[syncPoint + 2] === 1) {
  12207. // the sync point is properly aligned
  12208. i = syncPoint + 5;
  12209. break;
  12210. }
  12211. }
  12212. while (i < len) {
  12213. // look at the current byte to determine if we've hit the end of
  12214. // a NAL unit boundary
  12215. switch (buffer[i]) {
  12216. case 0:
  12217. // skip past non-sync sequences
  12218. if (buffer[i - 1] !== 0) {
  12219. i += 2;
  12220. break;
  12221. } else if (buffer[i - 2] !== 0) {
  12222. i++;
  12223. break;
  12224. } // deliver the NAL unit if it isn't empty
  12225. if (syncPoint + 3 !== i - 2) {
  12226. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  12227. } // drop trailing zeroes
  12228. do {
  12229. i++;
  12230. } while (buffer[i] !== 1 && i < len);
  12231. syncPoint = i - 2;
  12232. i += 3;
  12233. break;
  12234. case 1:
  12235. // skip past non-sync sequences
  12236. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  12237. i += 3;
  12238. break;
  12239. } // deliver the NAL unit
  12240. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  12241. syncPoint = i - 2;
  12242. i += 3;
  12243. break;
  12244. default:
  12245. // the current byte isn't a one or zero, so it cannot be part
  12246. // of a sync sequence
  12247. i += 3;
  12248. break;
  12249. }
  12250. } // filter out the NAL units that were delivered
  12251. buffer = buffer.subarray(syncPoint);
  12252. i -= syncPoint;
  12253. syncPoint = 0;
  12254. };
  12255. this.reset = function () {
  12256. buffer = null;
  12257. syncPoint = 0;
  12258. this.trigger('reset');
  12259. };
  12260. this.flush = function () {
  12261. // deliver the last buffered NAL unit
  12262. if (buffer && buffer.byteLength > 3) {
  12263. this.trigger('data', buffer.subarray(syncPoint + 3));
  12264. } // reset the stream state
  12265. buffer = null;
  12266. syncPoint = 0;
  12267. this.trigger('done');
  12268. };
  12269. this.endTimeline = function () {
  12270. this.flush();
  12271. this.trigger('endedtimeline');
  12272. };
  12273. };
  12274. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  12275. // see Recommendation ITU-T H.264 (4/2013),
  12276. // 7.3.2.1.1 Sequence parameter set data syntax
  12277. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  12278. 100: true,
  12279. 110: true,
  12280. 122: true,
  12281. 244: true,
  12282. 44: true,
  12283. 83: true,
  12284. 86: true,
  12285. 118: true,
  12286. 128: true,
  12287. // TODO: the three profiles below don't
  12288. // appear to have sps data in the specificiation anymore?
  12289. 138: true,
  12290. 139: true,
  12291. 134: true
  12292. };
  12293. /**
  12294. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  12295. * events.
  12296. */
  12297. H264Stream$1 = function () {
  12298. var nalByteStream = new NalByteStream(),
  12299. self,
  12300. trackId,
  12301. currentPts,
  12302. currentDts,
  12303. discardEmulationPreventionBytes,
  12304. readSequenceParameterSet,
  12305. skipScalingList;
  12306. H264Stream$1.prototype.init.call(this);
  12307. self = this;
  12308. /*
  12309. * Pushes a packet from a stream onto the NalByteStream
  12310. *
  12311. * @param {Object} packet - A packet received from a stream
  12312. * @param {Uint8Array} packet.data - The raw bytes of the packet
  12313. * @param {Number} packet.dts - Decode timestamp of the packet
  12314. * @param {Number} packet.pts - Presentation timestamp of the packet
  12315. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  12316. * @param {('video'|'audio')} packet.type - The type of packet
  12317. *
  12318. */
  12319. this.push = function (packet) {
  12320. if (packet.type !== 'video') {
  12321. return;
  12322. }
  12323. trackId = packet.trackId;
  12324. currentPts = packet.pts;
  12325. currentDts = packet.dts;
  12326. nalByteStream.push(packet);
  12327. };
  12328. /*
  12329. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  12330. * for the NALUs to the next stream component.
  12331. * Also, preprocess caption and sequence parameter NALUs.
  12332. *
  12333. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  12334. * @see NalByteStream.push
  12335. */
  12336. nalByteStream.on('data', function (data) {
  12337. var event = {
  12338. trackId: trackId,
  12339. pts: currentPts,
  12340. dts: currentDts,
  12341. data: data,
  12342. nalUnitTypeCode: data[0] & 0x1f
  12343. };
  12344. switch (event.nalUnitTypeCode) {
  12345. case 0x05:
  12346. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  12347. break;
  12348. case 0x06:
  12349. event.nalUnitType = 'sei_rbsp';
  12350. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  12351. break;
  12352. case 0x07:
  12353. event.nalUnitType = 'seq_parameter_set_rbsp';
  12354. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  12355. event.config = readSequenceParameterSet(event.escapedRBSP);
  12356. break;
  12357. case 0x08:
  12358. event.nalUnitType = 'pic_parameter_set_rbsp';
  12359. break;
  12360. case 0x09:
  12361. event.nalUnitType = 'access_unit_delimiter_rbsp';
  12362. break;
  12363. } // This triggers data on the H264Stream
  12364. self.trigger('data', event);
  12365. });
  12366. nalByteStream.on('done', function () {
  12367. self.trigger('done');
  12368. });
  12369. nalByteStream.on('partialdone', function () {
  12370. self.trigger('partialdone');
  12371. });
  12372. nalByteStream.on('reset', function () {
  12373. self.trigger('reset');
  12374. });
  12375. nalByteStream.on('endedtimeline', function () {
  12376. self.trigger('endedtimeline');
  12377. });
  12378. this.flush = function () {
  12379. nalByteStream.flush();
  12380. };
  12381. this.partialFlush = function () {
  12382. nalByteStream.partialFlush();
  12383. };
  12384. this.reset = function () {
  12385. nalByteStream.reset();
  12386. };
  12387. this.endTimeline = function () {
  12388. nalByteStream.endTimeline();
  12389. };
  12390. /**
  12391. * Advance the ExpGolomb decoder past a scaling list. The scaling
  12392. * list is optionally transmitted as part of a sequence parameter
  12393. * set and is not relevant to transmuxing.
  12394. * @param count {number} the number of entries in this scaling list
  12395. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  12396. * start of a scaling list
  12397. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  12398. */
  12399. skipScalingList = function (count, expGolombDecoder) {
  12400. var lastScale = 8,
  12401. nextScale = 8,
  12402. j,
  12403. deltaScale;
  12404. for (j = 0; j < count; j++) {
  12405. if (nextScale !== 0) {
  12406. deltaScale = expGolombDecoder.readExpGolomb();
  12407. nextScale = (lastScale + deltaScale + 256) % 256;
  12408. }
  12409. lastScale = nextScale === 0 ? lastScale : nextScale;
  12410. }
  12411. };
  12412. /**
  12413. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  12414. * Sequence Payload"
  12415. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  12416. * unit
  12417. * @return {Uint8Array} the RBSP without any Emulation
  12418. * Prevention Bytes
  12419. */
  12420. discardEmulationPreventionBytes = function (data) {
  12421. var length = data.byteLength,
  12422. emulationPreventionBytesPositions = [],
  12423. i = 1,
  12424. newLength,
  12425. newData; // Find all `Emulation Prevention Bytes`
  12426. while (i < length - 2) {
  12427. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  12428. emulationPreventionBytesPositions.push(i + 2);
  12429. i += 2;
  12430. } else {
  12431. i++;
  12432. }
  12433. } // If no Emulation Prevention Bytes were found just return the original
  12434. // array
  12435. if (emulationPreventionBytesPositions.length === 0) {
  12436. return data;
  12437. } // Create a new array to hold the NAL unit data
  12438. newLength = length - emulationPreventionBytesPositions.length;
  12439. newData = new Uint8Array(newLength);
  12440. var sourceIndex = 0;
  12441. for (i = 0; i < newLength; sourceIndex++, i++) {
  12442. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  12443. // Skip this byte
  12444. sourceIndex++; // Remove this position index
  12445. emulationPreventionBytesPositions.shift();
  12446. }
  12447. newData[i] = data[sourceIndex];
  12448. }
  12449. return newData;
  12450. };
  12451. /**
  12452. * Read a sequence parameter set and return some interesting video
  12453. * properties. A sequence parameter set is the H264 metadata that
  12454. * describes the properties of upcoming video frames.
  12455. * @param data {Uint8Array} the bytes of a sequence parameter set
  12456. * @return {object} an object with configuration parsed from the
  12457. * sequence parameter set, including the dimensions of the
  12458. * associated video frames.
  12459. */
  12460. readSequenceParameterSet = function (data) {
  12461. var frameCropLeftOffset = 0,
  12462. frameCropRightOffset = 0,
  12463. frameCropTopOffset = 0,
  12464. frameCropBottomOffset = 0,
  12465. expGolombDecoder,
  12466. profileIdc,
  12467. levelIdc,
  12468. profileCompatibility,
  12469. chromaFormatIdc,
  12470. picOrderCntType,
  12471. numRefFramesInPicOrderCntCycle,
  12472. picWidthInMbsMinus1,
  12473. picHeightInMapUnitsMinus1,
  12474. frameMbsOnlyFlag,
  12475. scalingListCount,
  12476. sarRatio = [1, 1],
  12477. aspectRatioIdc,
  12478. i;
  12479. expGolombDecoder = new ExpGolomb(data);
  12480. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  12481. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  12482. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  12483. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  12484. // some profiles have more optional data we don't need
  12485. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  12486. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  12487. if (chromaFormatIdc === 3) {
  12488. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  12489. }
  12490. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  12491. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  12492. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  12493. if (expGolombDecoder.readBoolean()) {
  12494. // seq_scaling_matrix_present_flag
  12495. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  12496. for (i = 0; i < scalingListCount; i++) {
  12497. if (expGolombDecoder.readBoolean()) {
  12498. // seq_scaling_list_present_flag[ i ]
  12499. if (i < 6) {
  12500. skipScalingList(16, expGolombDecoder);
  12501. } else {
  12502. skipScalingList(64, expGolombDecoder);
  12503. }
  12504. }
  12505. }
  12506. }
  12507. }
  12508. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  12509. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  12510. if (picOrderCntType === 0) {
  12511. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  12512. } else if (picOrderCntType === 1) {
  12513. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  12514. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  12515. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  12516. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  12517. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  12518. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  12519. }
  12520. }
  12521. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  12522. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  12523. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  12524. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  12525. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  12526. if (frameMbsOnlyFlag === 0) {
  12527. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  12528. }
  12529. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  12530. if (expGolombDecoder.readBoolean()) {
  12531. // frame_cropping_flag
  12532. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  12533. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  12534. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  12535. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  12536. }
  12537. if (expGolombDecoder.readBoolean()) {
  12538. // vui_parameters_present_flag
  12539. if (expGolombDecoder.readBoolean()) {
  12540. // aspect_ratio_info_present_flag
  12541. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  12542. switch (aspectRatioIdc) {
  12543. case 1:
  12544. sarRatio = [1, 1];
  12545. break;
  12546. case 2:
  12547. sarRatio = [12, 11];
  12548. break;
  12549. case 3:
  12550. sarRatio = [10, 11];
  12551. break;
  12552. case 4:
  12553. sarRatio = [16, 11];
  12554. break;
  12555. case 5:
  12556. sarRatio = [40, 33];
  12557. break;
  12558. case 6:
  12559. sarRatio = [24, 11];
  12560. break;
  12561. case 7:
  12562. sarRatio = [20, 11];
  12563. break;
  12564. case 8:
  12565. sarRatio = [32, 11];
  12566. break;
  12567. case 9:
  12568. sarRatio = [80, 33];
  12569. break;
  12570. case 10:
  12571. sarRatio = [18, 11];
  12572. break;
  12573. case 11:
  12574. sarRatio = [15, 11];
  12575. break;
  12576. case 12:
  12577. sarRatio = [64, 33];
  12578. break;
  12579. case 13:
  12580. sarRatio = [160, 99];
  12581. break;
  12582. case 14:
  12583. sarRatio = [4, 3];
  12584. break;
  12585. case 15:
  12586. sarRatio = [3, 2];
  12587. break;
  12588. case 16:
  12589. sarRatio = [2, 1];
  12590. break;
  12591. case 255:
  12592. {
  12593. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  12594. break;
  12595. }
  12596. }
  12597. if (sarRatio) {
  12598. sarRatio[0] / sarRatio[1];
  12599. }
  12600. }
  12601. }
  12602. return {
  12603. profileIdc: profileIdc,
  12604. levelIdc: levelIdc,
  12605. profileCompatibility: profileCompatibility,
  12606. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  12607. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  12608. // sar is sample aspect ratio
  12609. sarRatio: sarRatio
  12610. };
  12611. };
  12612. };
  12613. H264Stream$1.prototype = new Stream$2();
  12614. var h264 = {
  12615. H264Stream: H264Stream$1,
  12616. NalByteStream: NalByteStream
  12617. };
  12618. /**
  12619. * mux.js
  12620. *
  12621. * Copyright (c) Brightcove
  12622. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12623. *
  12624. * Utilities to detect basic properties and metadata about Aac data.
  12625. */
  12626. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  12627. var parseId3TagSize = function (header, byteIndex) {
  12628. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  12629. flags = header[byteIndex + 5],
  12630. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  12631. returnSize = returnSize >= 0 ? returnSize : 0;
  12632. if (footerPresent) {
  12633. return returnSize + 20;
  12634. }
  12635. return returnSize + 10;
  12636. };
  12637. var getId3Offset = function (data, offset) {
  12638. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  12639. return offset;
  12640. }
  12641. offset += parseId3TagSize(data, offset);
  12642. return getId3Offset(data, offset);
  12643. }; // TODO: use vhs-utils
  12644. var isLikelyAacData$1 = function (data) {
  12645. var offset = getId3Offset(data, 0);
  12646. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  12647. // is not mp3 data but aac data.
  12648. (data[offset + 1] & 0x16) === 0x10;
  12649. };
  12650. var parseSyncSafeInteger = function (data) {
  12651. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  12652. }; // return a percent-encoded representation of the specified byte range
  12653. // @see http://en.wikipedia.org/wiki/Percent-encoding
  12654. var percentEncode = function (bytes, start, end) {
  12655. var i,
  12656. result = '';
  12657. for (i = start; i < end; i++) {
  12658. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  12659. }
  12660. return result;
  12661. }; // return the string representation of the specified byte range,
  12662. // interpreted as ISO-8859-1.
  12663. var parseIso88591 = function (bytes, start, end) {
  12664. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  12665. };
  12666. var parseAdtsSize = function (header, byteIndex) {
  12667. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  12668. middle = header[byteIndex + 4] << 3,
  12669. highTwo = header[byteIndex + 3] & 0x3 << 11;
  12670. return highTwo | middle | lowThree;
  12671. };
  12672. var parseType$4 = function (header, byteIndex) {
  12673. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  12674. return 'timed-metadata';
  12675. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  12676. return 'audio';
  12677. }
  12678. return null;
  12679. };
  12680. var parseSampleRate = function (packet) {
  12681. var i = 0;
  12682. while (i + 5 < packet.length) {
  12683. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  12684. // If a valid header was not found, jump one forward and attempt to
  12685. // find a valid ADTS header starting at the next byte
  12686. i++;
  12687. continue;
  12688. }
  12689. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  12690. }
  12691. return null;
  12692. };
  12693. var parseAacTimestamp = function (packet) {
  12694. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  12695. frameStart = 10;
  12696. if (packet[5] & 0x40) {
  12697. // advance the frame start past the extended header
  12698. frameStart += 4; // header size field
  12699. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  12700. } // parse one or more ID3 frames
  12701. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  12702. do {
  12703. // determine the number of bytes in this frame
  12704. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  12705. if (frameSize < 1) {
  12706. return null;
  12707. }
  12708. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  12709. if (frameHeader === 'PRIV') {
  12710. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  12711. for (var i = 0; i < frame.byteLength; i++) {
  12712. if (frame[i] === 0) {
  12713. var owner = parseIso88591(frame, 0, i);
  12714. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  12715. var d = frame.subarray(i + 1);
  12716. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  12717. size *= 4;
  12718. size += d[7] & 0x03;
  12719. return size;
  12720. }
  12721. break;
  12722. }
  12723. }
  12724. }
  12725. frameStart += 10; // advance past the frame header
  12726. frameStart += frameSize; // advance past the frame body
  12727. } while (frameStart < packet.byteLength);
  12728. return null;
  12729. };
  12730. var utils = {
  12731. isLikelyAacData: isLikelyAacData$1,
  12732. parseId3TagSize: parseId3TagSize,
  12733. parseAdtsSize: parseAdtsSize,
  12734. parseType: parseType$4,
  12735. parseSampleRate: parseSampleRate,
  12736. parseAacTimestamp: parseAacTimestamp
  12737. };
  12738. /**
  12739. * mux.js
  12740. *
  12741. * Copyright (c) Brightcove
  12742. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12743. *
  12744. * A stream-based aac to mp4 converter. This utility can be used to
  12745. * deliver mp4s to a SourceBuffer on platforms that support native
  12746. * Media Source Extensions.
  12747. */
  12748. var Stream$1 = stream;
  12749. var aacUtils = utils; // Constants
  12750. var AacStream$1;
  12751. /**
  12752. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  12753. */
  12754. AacStream$1 = function () {
  12755. var everything = new Uint8Array(),
  12756. timeStamp = 0;
  12757. AacStream$1.prototype.init.call(this);
  12758. this.setTimestamp = function (timestamp) {
  12759. timeStamp = timestamp;
  12760. };
  12761. this.push = function (bytes) {
  12762. var frameSize = 0,
  12763. byteIndex = 0,
  12764. bytesLeft,
  12765. chunk,
  12766. packet,
  12767. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  12768. // bytes that were pushed in
  12769. if (everything.length) {
  12770. tempLength = everything.length;
  12771. everything = new Uint8Array(bytes.byteLength + tempLength);
  12772. everything.set(everything.subarray(0, tempLength));
  12773. everything.set(bytes, tempLength);
  12774. } else {
  12775. everything = bytes;
  12776. }
  12777. while (everything.length - byteIndex >= 3) {
  12778. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  12779. // Exit early because we don't have enough to parse
  12780. // the ID3 tag header
  12781. if (everything.length - byteIndex < 10) {
  12782. break;
  12783. } // check framesize
  12784. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  12785. // to emit a full packet
  12786. // Add to byteIndex to support multiple ID3 tags in sequence
  12787. if (byteIndex + frameSize > everything.length) {
  12788. break;
  12789. }
  12790. chunk = {
  12791. type: 'timed-metadata',
  12792. data: everything.subarray(byteIndex, byteIndex + frameSize)
  12793. };
  12794. this.trigger('data', chunk);
  12795. byteIndex += frameSize;
  12796. continue;
  12797. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  12798. // Exit early because we don't have enough to parse
  12799. // the ADTS frame header
  12800. if (everything.length - byteIndex < 7) {
  12801. break;
  12802. }
  12803. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  12804. // to emit a full packet
  12805. if (byteIndex + frameSize > everything.length) {
  12806. break;
  12807. }
  12808. packet = {
  12809. type: 'audio',
  12810. data: everything.subarray(byteIndex, byteIndex + frameSize),
  12811. pts: timeStamp,
  12812. dts: timeStamp
  12813. };
  12814. this.trigger('data', packet);
  12815. byteIndex += frameSize;
  12816. continue;
  12817. }
  12818. byteIndex++;
  12819. }
  12820. bytesLeft = everything.length - byteIndex;
  12821. if (bytesLeft > 0) {
  12822. everything = everything.subarray(byteIndex);
  12823. } else {
  12824. everything = new Uint8Array();
  12825. }
  12826. };
  12827. this.reset = function () {
  12828. everything = new Uint8Array();
  12829. this.trigger('reset');
  12830. };
  12831. this.endTimeline = function () {
  12832. everything = new Uint8Array();
  12833. this.trigger('endedtimeline');
  12834. };
  12835. };
  12836. AacStream$1.prototype = new Stream$1();
  12837. var aac = AacStream$1;
  12838. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  12839. var audioProperties = AUDIO_PROPERTIES$1;
  12840. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  12841. var videoProperties = VIDEO_PROPERTIES$1;
  12842. /**
  12843. * mux.js
  12844. *
  12845. * Copyright (c) Brightcove
  12846. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12847. *
  12848. * A stream-based mp2t to mp4 converter. This utility can be used to
  12849. * deliver mp4s to a SourceBuffer on platforms that support native
  12850. * Media Source Extensions.
  12851. */
  12852. var Stream = stream;
  12853. var mp4 = mp4Generator;
  12854. var frameUtils = frameUtils$1;
  12855. var audioFrameUtils = audioFrameUtils$1;
  12856. var trackDecodeInfo = trackDecodeInfo$1;
  12857. var m2ts = m2ts_1;
  12858. var clock = clock$2;
  12859. var AdtsStream = adts;
  12860. var H264Stream = h264.H264Stream;
  12861. var AacStream = aac;
  12862. var isLikelyAacData = utils.isLikelyAacData;
  12863. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  12864. var AUDIO_PROPERTIES = audioProperties;
  12865. var VIDEO_PROPERTIES = videoProperties; // object types
  12866. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  12867. var retriggerForStream = function (key, event) {
  12868. event.stream = key;
  12869. this.trigger('log', event);
  12870. };
  12871. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  12872. var keys = Object.keys(pipeline);
  12873. for (var i = 0; i < keys.length; i++) {
  12874. var key = keys[i]; // skip non-stream keys and headOfPipeline
  12875. // which is just a duplicate
  12876. if (key === 'headOfPipeline' || !pipeline[key].on) {
  12877. continue;
  12878. }
  12879. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  12880. }
  12881. };
  12882. /**
  12883. * Compare two arrays (even typed) for same-ness
  12884. */
  12885. var arrayEquals = function (a, b) {
  12886. var i;
  12887. if (a.length !== b.length) {
  12888. return false;
  12889. } // compare the value of each element in the array
  12890. for (i = 0; i < a.length; i++) {
  12891. if (a[i] !== b[i]) {
  12892. return false;
  12893. }
  12894. }
  12895. return true;
  12896. };
  12897. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  12898. var ptsOffsetFromDts = startPts - startDts,
  12899. decodeDuration = endDts - startDts,
  12900. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  12901. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  12902. // In order to provide relevant values for the player times, base timing info on the
  12903. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  12904. return {
  12905. start: {
  12906. dts: baseMediaDecodeTime,
  12907. pts: baseMediaDecodeTime + ptsOffsetFromDts
  12908. },
  12909. end: {
  12910. dts: baseMediaDecodeTime + decodeDuration,
  12911. pts: baseMediaDecodeTime + presentationDuration
  12912. },
  12913. prependedContentDuration: prependedContentDuration,
  12914. baseMediaDecodeTime: baseMediaDecodeTime
  12915. };
  12916. };
  12917. /**
  12918. * Constructs a single-track, ISO BMFF media segment from AAC data
  12919. * events. The output of this stream can be fed to a SourceBuffer
  12920. * configured with a suitable initialization segment.
  12921. * @param track {object} track metadata configuration
  12922. * @param options {object} transmuxer options object
  12923. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  12924. * in the source; false to adjust the first segment to start at 0.
  12925. */
  12926. AudioSegmentStream = function (track, options) {
  12927. var adtsFrames = [],
  12928. sequenceNumber,
  12929. earliestAllowedDts = 0,
  12930. audioAppendStartTs = 0,
  12931. videoBaseMediaDecodeTime = Infinity;
  12932. options = options || {};
  12933. sequenceNumber = options.firstSequenceNumber || 0;
  12934. AudioSegmentStream.prototype.init.call(this);
  12935. this.push = function (data) {
  12936. trackDecodeInfo.collectDtsInfo(track, data);
  12937. if (track) {
  12938. AUDIO_PROPERTIES.forEach(function (prop) {
  12939. track[prop] = data[prop];
  12940. });
  12941. } // buffer audio data until end() is called
  12942. adtsFrames.push(data);
  12943. };
  12944. this.setEarliestDts = function (earliestDts) {
  12945. earliestAllowedDts = earliestDts;
  12946. };
  12947. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  12948. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  12949. };
  12950. this.setAudioAppendStart = function (timestamp) {
  12951. audioAppendStartTs = timestamp;
  12952. };
  12953. this.flush = function () {
  12954. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  12955. if (adtsFrames.length === 0) {
  12956. this.trigger('done', 'AudioSegmentStream');
  12957. return;
  12958. }
  12959. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  12960. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  12961. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  12962. // samples (that is, adts frames) in the audio data
  12963. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  12964. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  12965. adtsFrames = [];
  12966. moof = mp4.moof(sequenceNumber, [track]);
  12967. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  12968. sequenceNumber++;
  12969. boxes.set(moof);
  12970. boxes.set(mdat, moof.byteLength);
  12971. trackDecodeInfo.clearDtsInfo(track);
  12972. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  12973. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  12974. // valid use-case where an init segment/data should be triggered without associated
  12975. // frames. Leaving for now, but should be looked into.
  12976. if (frames.length) {
  12977. segmentDuration = frames.length * frameDuration;
  12978. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  12979. // frame info is in video clock cycles. Convert to match expectation of
  12980. // listeners (that all timestamps will be based on video clock cycles).
  12981. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  12982. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  12983. this.trigger('timingInfo', {
  12984. start: frames[0].pts,
  12985. end: frames[0].pts + segmentDuration
  12986. });
  12987. }
  12988. this.trigger('data', {
  12989. track: track,
  12990. boxes: boxes
  12991. });
  12992. this.trigger('done', 'AudioSegmentStream');
  12993. };
  12994. this.reset = function () {
  12995. trackDecodeInfo.clearDtsInfo(track);
  12996. adtsFrames = [];
  12997. this.trigger('reset');
  12998. };
  12999. };
  13000. AudioSegmentStream.prototype = new Stream();
  13001. /**
  13002. * Constructs a single-track, ISO BMFF media segment from H264 data
  13003. * events. The output of this stream can be fed to a SourceBuffer
  13004. * configured with a suitable initialization segment.
  13005. * @param track {object} track metadata configuration
  13006. * @param options {object} transmuxer options object
  13007. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  13008. * gopsToAlignWith list when attempting to align gop pts
  13009. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  13010. * in the source; false to adjust the first segment to start at 0.
  13011. */
  13012. VideoSegmentStream = function (track, options) {
  13013. var sequenceNumber,
  13014. nalUnits = [],
  13015. gopsToAlignWith = [],
  13016. config,
  13017. pps;
  13018. options = options || {};
  13019. sequenceNumber = options.firstSequenceNumber || 0;
  13020. VideoSegmentStream.prototype.init.call(this);
  13021. delete track.minPTS;
  13022. this.gopCache_ = [];
  13023. /**
  13024. * Constructs a ISO BMFF segment given H264 nalUnits
  13025. * @param {Object} nalUnit A data event representing a nalUnit
  13026. * @param {String} nalUnit.nalUnitType
  13027. * @param {Object} nalUnit.config Properties for a mp4 track
  13028. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  13029. * @see lib/codecs/h264.js
  13030. **/
  13031. this.push = function (nalUnit) {
  13032. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  13033. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  13034. config = nalUnit.config;
  13035. track.sps = [nalUnit.data];
  13036. VIDEO_PROPERTIES.forEach(function (prop) {
  13037. track[prop] = config[prop];
  13038. }, this);
  13039. }
  13040. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  13041. pps = nalUnit.data;
  13042. track.pps = [nalUnit.data];
  13043. } // buffer video until flush() is called
  13044. nalUnits.push(nalUnit);
  13045. };
  13046. /**
  13047. * Pass constructed ISO BMFF track and boxes on to the
  13048. * next stream in the pipeline
  13049. **/
  13050. this.flush = function () {
  13051. var frames,
  13052. gopForFusion,
  13053. gops,
  13054. moof,
  13055. mdat,
  13056. boxes,
  13057. prependedContentDuration = 0,
  13058. firstGop,
  13059. lastGop; // Throw away nalUnits at the start of the byte stream until
  13060. // we find the first AUD
  13061. while (nalUnits.length) {
  13062. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  13063. break;
  13064. }
  13065. nalUnits.shift();
  13066. } // Return early if no video data has been observed
  13067. if (nalUnits.length === 0) {
  13068. this.resetStream_();
  13069. this.trigger('done', 'VideoSegmentStream');
  13070. return;
  13071. } // Organize the raw nal-units into arrays that represent
  13072. // higher-level constructs such as frames and gops
  13073. // (group-of-pictures)
  13074. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  13075. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  13076. // a problem since MSE (on Chrome) requires a leading keyframe.
  13077. //
  13078. // We have two approaches to repairing this situation:
  13079. // 1) GOP-FUSION:
  13080. // This is where we keep track of the GOPS (group-of-pictures)
  13081. // from previous fragments and attempt to find one that we can
  13082. // prepend to the current fragment in order to create a valid
  13083. // fragment.
  13084. // 2) KEYFRAME-PULLING:
  13085. // Here we search for the first keyframe in the fragment and
  13086. // throw away all the frames between the start of the fragment
  13087. // and that keyframe. We then extend the duration and pull the
  13088. // PTS of the keyframe forward so that it covers the time range
  13089. // of the frames that were disposed of.
  13090. //
  13091. // #1 is far prefereable over #2 which can cause "stuttering" but
  13092. // requires more things to be just right.
  13093. if (!gops[0][0].keyFrame) {
  13094. // Search for a gop for fusion from our gopCache
  13095. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  13096. if (gopForFusion) {
  13097. // in order to provide more accurate timing information about the segment, save
  13098. // the number of seconds prepended to the original segment due to GOP fusion
  13099. prependedContentDuration = gopForFusion.duration;
  13100. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  13101. // new gop at the beginning
  13102. gops.byteLength += gopForFusion.byteLength;
  13103. gops.nalCount += gopForFusion.nalCount;
  13104. gops.pts = gopForFusion.pts;
  13105. gops.dts = gopForFusion.dts;
  13106. gops.duration += gopForFusion.duration;
  13107. } else {
  13108. // If we didn't find a candidate gop fall back to keyframe-pulling
  13109. gops = frameUtils.extendFirstKeyFrame(gops);
  13110. }
  13111. } // Trim gops to align with gopsToAlignWith
  13112. if (gopsToAlignWith.length) {
  13113. var alignedGops;
  13114. if (options.alignGopsAtEnd) {
  13115. alignedGops = this.alignGopsAtEnd_(gops);
  13116. } else {
  13117. alignedGops = this.alignGopsAtStart_(gops);
  13118. }
  13119. if (!alignedGops) {
  13120. // save all the nals in the last GOP into the gop cache
  13121. this.gopCache_.unshift({
  13122. gop: gops.pop(),
  13123. pps: track.pps,
  13124. sps: track.sps
  13125. }); // Keep a maximum of 6 GOPs in the cache
  13126. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13127. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  13128. this.resetStream_();
  13129. this.trigger('done', 'VideoSegmentStream');
  13130. return;
  13131. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  13132. // when recalculated before sending off to CoalesceStream
  13133. trackDecodeInfo.clearDtsInfo(track);
  13134. gops = alignedGops;
  13135. }
  13136. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  13137. // samples (that is, frames) in the video data
  13138. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  13139. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  13140. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  13141. this.trigger('processedGopsInfo', gops.map(function (gop) {
  13142. return {
  13143. pts: gop.pts,
  13144. dts: gop.dts,
  13145. byteLength: gop.byteLength
  13146. };
  13147. }));
  13148. firstGop = gops[0];
  13149. lastGop = gops[gops.length - 1];
  13150. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  13151. this.trigger('timingInfo', {
  13152. start: gops[0].pts,
  13153. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  13154. }); // save all the nals in the last GOP into the gop cache
  13155. this.gopCache_.unshift({
  13156. gop: gops.pop(),
  13157. pps: track.pps,
  13158. sps: track.sps
  13159. }); // Keep a maximum of 6 GOPs in the cache
  13160. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13161. nalUnits = [];
  13162. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  13163. this.trigger('timelineStartInfo', track.timelineStartInfo);
  13164. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  13165. // throwing away hundreds of media segment fragments
  13166. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  13167. sequenceNumber++;
  13168. boxes.set(moof);
  13169. boxes.set(mdat, moof.byteLength);
  13170. this.trigger('data', {
  13171. track: track,
  13172. boxes: boxes
  13173. });
  13174. this.resetStream_(); // Continue with the flush process now
  13175. this.trigger('done', 'VideoSegmentStream');
  13176. };
  13177. this.reset = function () {
  13178. this.resetStream_();
  13179. nalUnits = [];
  13180. this.gopCache_.length = 0;
  13181. gopsToAlignWith.length = 0;
  13182. this.trigger('reset');
  13183. };
  13184. this.resetStream_ = function () {
  13185. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  13186. // for instance, when we are rendition switching
  13187. config = undefined;
  13188. pps = undefined;
  13189. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  13190. // return it or return null if no good candidate was found
  13191. this.getGopForFusion_ = function (nalUnit) {
  13192. var halfSecond = 45000,
  13193. // Half-a-second in a 90khz clock
  13194. allowableOverlap = 10000,
  13195. // About 3 frames @ 30fps
  13196. nearestDistance = Infinity,
  13197. dtsDistance,
  13198. nearestGopObj,
  13199. currentGop,
  13200. currentGopObj,
  13201. i; // Search for the GOP nearest to the beginning of this nal unit
  13202. for (i = 0; i < this.gopCache_.length; i++) {
  13203. currentGopObj = this.gopCache_[i];
  13204. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  13205. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  13206. continue;
  13207. } // Reject Gops that would require a negative baseMediaDecodeTime
  13208. if (currentGop.dts < track.timelineStartInfo.dts) {
  13209. continue;
  13210. } // The distance between the end of the gop and the start of the nalUnit
  13211. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  13212. // a half-second of the nal unit
  13213. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  13214. // Always use the closest GOP we found if there is more than
  13215. // one candidate
  13216. if (!nearestGopObj || nearestDistance > dtsDistance) {
  13217. nearestGopObj = currentGopObj;
  13218. nearestDistance = dtsDistance;
  13219. }
  13220. }
  13221. }
  13222. if (nearestGopObj) {
  13223. return nearestGopObj.gop;
  13224. }
  13225. return null;
  13226. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  13227. // of gopsToAlignWith starting from the START of the list
  13228. this.alignGopsAtStart_ = function (gops) {
  13229. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  13230. byteLength = gops.byteLength;
  13231. nalCount = gops.nalCount;
  13232. duration = gops.duration;
  13233. alignIndex = gopIndex = 0;
  13234. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  13235. align = gopsToAlignWith[alignIndex];
  13236. gop = gops[gopIndex];
  13237. if (align.pts === gop.pts) {
  13238. break;
  13239. }
  13240. if (gop.pts > align.pts) {
  13241. // this current gop starts after the current gop we want to align on, so increment
  13242. // align index
  13243. alignIndex++;
  13244. continue;
  13245. } // current gop starts before the current gop we want to align on. so increment gop
  13246. // index
  13247. gopIndex++;
  13248. byteLength -= gop.byteLength;
  13249. nalCount -= gop.nalCount;
  13250. duration -= gop.duration;
  13251. }
  13252. if (gopIndex === 0) {
  13253. // no gops to trim
  13254. return gops;
  13255. }
  13256. if (gopIndex === gops.length) {
  13257. // all gops trimmed, skip appending all gops
  13258. return null;
  13259. }
  13260. alignedGops = gops.slice(gopIndex);
  13261. alignedGops.byteLength = byteLength;
  13262. alignedGops.duration = duration;
  13263. alignedGops.nalCount = nalCount;
  13264. alignedGops.pts = alignedGops[0].pts;
  13265. alignedGops.dts = alignedGops[0].dts;
  13266. return alignedGops;
  13267. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  13268. // of gopsToAlignWith starting from the END of the list
  13269. this.alignGopsAtEnd_ = function (gops) {
  13270. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  13271. alignIndex = gopsToAlignWith.length - 1;
  13272. gopIndex = gops.length - 1;
  13273. alignEndIndex = null;
  13274. matchFound = false;
  13275. while (alignIndex >= 0 && gopIndex >= 0) {
  13276. align = gopsToAlignWith[alignIndex];
  13277. gop = gops[gopIndex];
  13278. if (align.pts === gop.pts) {
  13279. matchFound = true;
  13280. break;
  13281. }
  13282. if (align.pts > gop.pts) {
  13283. alignIndex--;
  13284. continue;
  13285. }
  13286. if (alignIndex === gopsToAlignWith.length - 1) {
  13287. // gop.pts is greater than the last alignment candidate. If no match is found
  13288. // by the end of this loop, we still want to append gops that come after this
  13289. // point
  13290. alignEndIndex = gopIndex;
  13291. }
  13292. gopIndex--;
  13293. }
  13294. if (!matchFound && alignEndIndex === null) {
  13295. return null;
  13296. }
  13297. var trimIndex;
  13298. if (matchFound) {
  13299. trimIndex = gopIndex;
  13300. } else {
  13301. trimIndex = alignEndIndex;
  13302. }
  13303. if (trimIndex === 0) {
  13304. return gops;
  13305. }
  13306. var alignedGops = gops.slice(trimIndex);
  13307. var metadata = alignedGops.reduce(function (total, gop) {
  13308. total.byteLength += gop.byteLength;
  13309. total.duration += gop.duration;
  13310. total.nalCount += gop.nalCount;
  13311. return total;
  13312. }, {
  13313. byteLength: 0,
  13314. duration: 0,
  13315. nalCount: 0
  13316. });
  13317. alignedGops.byteLength = metadata.byteLength;
  13318. alignedGops.duration = metadata.duration;
  13319. alignedGops.nalCount = metadata.nalCount;
  13320. alignedGops.pts = alignedGops[0].pts;
  13321. alignedGops.dts = alignedGops[0].dts;
  13322. return alignedGops;
  13323. };
  13324. this.alignGopsWith = function (newGopsToAlignWith) {
  13325. gopsToAlignWith = newGopsToAlignWith;
  13326. };
  13327. };
  13328. VideoSegmentStream.prototype = new Stream();
  13329. /**
  13330. * A Stream that can combine multiple streams (ie. audio & video)
  13331. * into a single output segment for MSE. Also supports audio-only
  13332. * and video-only streams.
  13333. * @param options {object} transmuxer options object
  13334. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  13335. * in the source; false to adjust the first segment to start at media timeline start.
  13336. */
  13337. CoalesceStream = function (options, metadataStream) {
  13338. // Number of Tracks per output segment
  13339. // If greater than 1, we combine multiple
  13340. // tracks into a single segment
  13341. this.numberOfTracks = 0;
  13342. this.metadataStream = metadataStream;
  13343. options = options || {};
  13344. if (typeof options.remux !== 'undefined') {
  13345. this.remuxTracks = !!options.remux;
  13346. } else {
  13347. this.remuxTracks = true;
  13348. }
  13349. if (typeof options.keepOriginalTimestamps === 'boolean') {
  13350. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  13351. } else {
  13352. this.keepOriginalTimestamps = false;
  13353. }
  13354. this.pendingTracks = [];
  13355. this.videoTrack = null;
  13356. this.pendingBoxes = [];
  13357. this.pendingCaptions = [];
  13358. this.pendingMetadata = [];
  13359. this.pendingBytes = 0;
  13360. this.emittedTracks = 0;
  13361. CoalesceStream.prototype.init.call(this); // Take output from multiple
  13362. this.push = function (output) {
  13363. // buffer incoming captions until the associated video segment
  13364. // finishes
  13365. if (output.text) {
  13366. return this.pendingCaptions.push(output);
  13367. } // buffer incoming id3 tags until the final flush
  13368. if (output.frames) {
  13369. return this.pendingMetadata.push(output);
  13370. } // Add this track to the list of pending tracks and store
  13371. // important information required for the construction of
  13372. // the final segment
  13373. this.pendingTracks.push(output.track);
  13374. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  13375. // We unshift audio and push video because
  13376. // as of Chrome 75 when switching from
  13377. // one init segment to another if the video
  13378. // mdat does not appear after the audio mdat
  13379. // only audio will play for the duration of our transmux.
  13380. if (output.track.type === 'video') {
  13381. this.videoTrack = output.track;
  13382. this.pendingBoxes.push(output.boxes);
  13383. }
  13384. if (output.track.type === 'audio') {
  13385. this.audioTrack = output.track;
  13386. this.pendingBoxes.unshift(output.boxes);
  13387. }
  13388. };
  13389. };
  13390. CoalesceStream.prototype = new Stream();
  13391. CoalesceStream.prototype.flush = function (flushSource) {
  13392. var offset = 0,
  13393. event = {
  13394. captions: [],
  13395. captionStreams: {},
  13396. metadata: [],
  13397. info: {}
  13398. },
  13399. caption,
  13400. id3,
  13401. initSegment,
  13402. timelineStartPts = 0,
  13403. i;
  13404. if (this.pendingTracks.length < this.numberOfTracks) {
  13405. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  13406. // Return because we haven't received a flush from a data-generating
  13407. // portion of the segment (meaning that we have only recieved meta-data
  13408. // or captions.)
  13409. return;
  13410. } else if (this.remuxTracks) {
  13411. // Return until we have enough tracks from the pipeline to remux (if we
  13412. // are remuxing audio and video into a single MP4)
  13413. return;
  13414. } else if (this.pendingTracks.length === 0) {
  13415. // In the case where we receive a flush without any data having been
  13416. // received we consider it an emitted track for the purposes of coalescing
  13417. // `done` events.
  13418. // We do this for the case where there is an audio and video track in the
  13419. // segment but no audio data. (seen in several playlists with alternate
  13420. // audio tracks and no audio present in the main TS segments.)
  13421. this.emittedTracks++;
  13422. if (this.emittedTracks >= this.numberOfTracks) {
  13423. this.trigger('done');
  13424. this.emittedTracks = 0;
  13425. }
  13426. return;
  13427. }
  13428. }
  13429. if (this.videoTrack) {
  13430. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  13431. VIDEO_PROPERTIES.forEach(function (prop) {
  13432. event.info[prop] = this.videoTrack[prop];
  13433. }, this);
  13434. } else if (this.audioTrack) {
  13435. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  13436. AUDIO_PROPERTIES.forEach(function (prop) {
  13437. event.info[prop] = this.audioTrack[prop];
  13438. }, this);
  13439. }
  13440. if (this.videoTrack || this.audioTrack) {
  13441. if (this.pendingTracks.length === 1) {
  13442. event.type = this.pendingTracks[0].type;
  13443. } else {
  13444. event.type = 'combined';
  13445. }
  13446. this.emittedTracks += this.pendingTracks.length;
  13447. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  13448. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  13449. // and track definitions
  13450. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  13451. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  13452. for (i = 0; i < this.pendingBoxes.length; i++) {
  13453. event.data.set(this.pendingBoxes[i], offset);
  13454. offset += this.pendingBoxes[i].byteLength;
  13455. } // Translate caption PTS times into second offsets to match the
  13456. // video timeline for the segment, and add track info
  13457. for (i = 0; i < this.pendingCaptions.length; i++) {
  13458. caption = this.pendingCaptions[i];
  13459. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  13460. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  13461. event.captionStreams[caption.stream] = true;
  13462. event.captions.push(caption);
  13463. } // Translate ID3 frame PTS times into second offsets to match the
  13464. // video timeline for the segment
  13465. for (i = 0; i < this.pendingMetadata.length; i++) {
  13466. id3 = this.pendingMetadata[i];
  13467. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  13468. event.metadata.push(id3);
  13469. } // We add this to every single emitted segment even though we only need
  13470. // it for the first
  13471. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  13472. this.pendingTracks.length = 0;
  13473. this.videoTrack = null;
  13474. this.pendingBoxes.length = 0;
  13475. this.pendingCaptions.length = 0;
  13476. this.pendingBytes = 0;
  13477. this.pendingMetadata.length = 0; // Emit the built segment
  13478. // We include captions and ID3 tags for backwards compatibility,
  13479. // ideally we should send only video and audio in the data event
  13480. this.trigger('data', event); // Emit each caption to the outside world
  13481. // Ideally, this would happen immediately on parsing captions,
  13482. // but we need to ensure that video data is sent back first
  13483. // so that caption timing can be adjusted to match video timing
  13484. for (i = 0; i < event.captions.length; i++) {
  13485. caption = event.captions[i];
  13486. this.trigger('caption', caption);
  13487. } // Emit each id3 tag to the outside world
  13488. // Ideally, this would happen immediately on parsing the tag,
  13489. // but we need to ensure that video data is sent back first
  13490. // so that ID3 frame timing can be adjusted to match video timing
  13491. for (i = 0; i < event.metadata.length; i++) {
  13492. id3 = event.metadata[i];
  13493. this.trigger('id3Frame', id3);
  13494. }
  13495. } // Only emit `done` if all tracks have been flushed and emitted
  13496. if (this.emittedTracks >= this.numberOfTracks) {
  13497. this.trigger('done');
  13498. this.emittedTracks = 0;
  13499. }
  13500. };
  13501. CoalesceStream.prototype.setRemux = function (val) {
  13502. this.remuxTracks = val;
  13503. };
  13504. /**
  13505. * A Stream that expects MP2T binary data as input and produces
  13506. * corresponding media segments, suitable for use with Media Source
  13507. * Extension (MSE) implementations that support the ISO BMFF byte
  13508. * stream format, like Chrome.
  13509. */
  13510. Transmuxer = function (options) {
  13511. var self = this,
  13512. hasFlushed = true,
  13513. videoTrack,
  13514. audioTrack;
  13515. Transmuxer.prototype.init.call(this);
  13516. options = options || {};
  13517. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  13518. this.transmuxPipeline_ = {};
  13519. this.setupAacPipeline = function () {
  13520. var pipeline = {};
  13521. this.transmuxPipeline_ = pipeline;
  13522. pipeline.type = 'aac';
  13523. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  13524. pipeline.aacStream = new AacStream();
  13525. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  13526. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  13527. pipeline.adtsStream = new AdtsStream();
  13528. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  13529. pipeline.headOfPipeline = pipeline.aacStream;
  13530. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  13531. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  13532. pipeline.metadataStream.on('timestamp', function (frame) {
  13533. pipeline.aacStream.setTimestamp(frame.timeStamp);
  13534. });
  13535. pipeline.aacStream.on('data', function (data) {
  13536. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  13537. return;
  13538. }
  13539. audioTrack = audioTrack || {
  13540. timelineStartInfo: {
  13541. baseMediaDecodeTime: self.baseMediaDecodeTime
  13542. },
  13543. codec: 'adts',
  13544. type: 'audio'
  13545. }; // hook up the audio segment stream to the first track with aac data
  13546. pipeline.coalesceStream.numberOfTracks++;
  13547. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  13548. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  13549. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  13550. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  13551. self.trigger('trackinfo', {
  13552. hasAudio: !!audioTrack,
  13553. hasVideo: !!videoTrack
  13554. });
  13555. }); // Re-emit any data coming from the coalesce stream to the outside world
  13556. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  13557. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  13558. addPipelineLogRetriggers(this, pipeline);
  13559. };
  13560. this.setupTsPipeline = function () {
  13561. var pipeline = {};
  13562. this.transmuxPipeline_ = pipeline;
  13563. pipeline.type = 'ts';
  13564. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  13565. pipeline.packetStream = new m2ts.TransportPacketStream();
  13566. pipeline.parseStream = new m2ts.TransportParseStream();
  13567. pipeline.elementaryStream = new m2ts.ElementaryStream();
  13568. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  13569. pipeline.adtsStream = new AdtsStream();
  13570. pipeline.h264Stream = new H264Stream();
  13571. pipeline.captionStream = new m2ts.CaptionStream(options);
  13572. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  13573. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  13574. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  13575. // demux the streams
  13576. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  13577. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  13578. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  13579. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  13580. pipeline.elementaryStream.on('data', function (data) {
  13581. var i;
  13582. if (data.type === 'metadata') {
  13583. i = data.tracks.length; // scan the tracks listed in the metadata
  13584. while (i--) {
  13585. if (!videoTrack && data.tracks[i].type === 'video') {
  13586. videoTrack = data.tracks[i];
  13587. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  13588. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  13589. audioTrack = data.tracks[i];
  13590. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  13591. }
  13592. } // hook up the video segment stream to the first track with h264 data
  13593. if (videoTrack && !pipeline.videoSegmentStream) {
  13594. pipeline.coalesceStream.numberOfTracks++;
  13595. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  13596. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  13597. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  13598. // When video emits timelineStartInfo data after a flush, we forward that
  13599. // info to the AudioSegmentStream, if it exists, because video timeline
  13600. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  13601. // because this is a particularly subtle form of timestamp alteration.
  13602. if (audioTrack && !options.keepOriginalTimestamps) {
  13603. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  13604. // very earliest DTS we have seen in video because Chrome will
  13605. // interpret any video track with a baseMediaDecodeTime that is
  13606. // non-zero as a gap.
  13607. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  13608. }
  13609. });
  13610. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  13611. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  13612. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  13613. if (audioTrack) {
  13614. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  13615. }
  13616. });
  13617. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  13618. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  13619. }
  13620. if (audioTrack && !pipeline.audioSegmentStream) {
  13621. // hook up the audio segment stream to the first track with aac data
  13622. pipeline.coalesceStream.numberOfTracks++;
  13623. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  13624. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  13625. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  13626. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  13627. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  13628. } // emit pmt info
  13629. self.trigger('trackinfo', {
  13630. hasAudio: !!audioTrack,
  13631. hasVideo: !!videoTrack
  13632. });
  13633. }
  13634. }); // Re-emit any data coming from the coalesce stream to the outside world
  13635. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  13636. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  13637. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  13638. self.trigger('id3Frame', id3Frame);
  13639. });
  13640. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  13641. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  13642. addPipelineLogRetriggers(this, pipeline);
  13643. }; // hook up the segment streams once track metadata is delivered
  13644. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  13645. var pipeline = this.transmuxPipeline_;
  13646. if (!options.keepOriginalTimestamps) {
  13647. this.baseMediaDecodeTime = baseMediaDecodeTime;
  13648. }
  13649. if (audioTrack) {
  13650. audioTrack.timelineStartInfo.dts = undefined;
  13651. audioTrack.timelineStartInfo.pts = undefined;
  13652. trackDecodeInfo.clearDtsInfo(audioTrack);
  13653. if (pipeline.audioTimestampRolloverStream) {
  13654. pipeline.audioTimestampRolloverStream.discontinuity();
  13655. }
  13656. }
  13657. if (videoTrack) {
  13658. if (pipeline.videoSegmentStream) {
  13659. pipeline.videoSegmentStream.gopCache_ = [];
  13660. }
  13661. videoTrack.timelineStartInfo.dts = undefined;
  13662. videoTrack.timelineStartInfo.pts = undefined;
  13663. trackDecodeInfo.clearDtsInfo(videoTrack);
  13664. pipeline.captionStream.reset();
  13665. }
  13666. if (pipeline.timestampRolloverStream) {
  13667. pipeline.timestampRolloverStream.discontinuity();
  13668. }
  13669. };
  13670. this.setAudioAppendStart = function (timestamp) {
  13671. if (audioTrack) {
  13672. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  13673. }
  13674. };
  13675. this.setRemux = function (val) {
  13676. var pipeline = this.transmuxPipeline_;
  13677. options.remux = val;
  13678. if (pipeline && pipeline.coalesceStream) {
  13679. pipeline.coalesceStream.setRemux(val);
  13680. }
  13681. };
  13682. this.alignGopsWith = function (gopsToAlignWith) {
  13683. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  13684. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  13685. }
  13686. };
  13687. this.getLogTrigger_ = function (key) {
  13688. var self = this;
  13689. return function (event) {
  13690. event.stream = key;
  13691. self.trigger('log', event);
  13692. };
  13693. }; // feed incoming data to the front of the parsing pipeline
  13694. this.push = function (data) {
  13695. if (hasFlushed) {
  13696. var isAac = isLikelyAacData(data);
  13697. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  13698. this.setupAacPipeline();
  13699. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  13700. this.setupTsPipeline();
  13701. }
  13702. hasFlushed = false;
  13703. }
  13704. this.transmuxPipeline_.headOfPipeline.push(data);
  13705. }; // flush any buffered data
  13706. this.flush = function () {
  13707. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  13708. this.transmuxPipeline_.headOfPipeline.flush();
  13709. };
  13710. this.endTimeline = function () {
  13711. this.transmuxPipeline_.headOfPipeline.endTimeline();
  13712. };
  13713. this.reset = function () {
  13714. if (this.transmuxPipeline_.headOfPipeline) {
  13715. this.transmuxPipeline_.headOfPipeline.reset();
  13716. }
  13717. }; // Caption data has to be reset when seeking outside buffered range
  13718. this.resetCaptions = function () {
  13719. if (this.transmuxPipeline_.captionStream) {
  13720. this.transmuxPipeline_.captionStream.reset();
  13721. }
  13722. };
  13723. };
  13724. Transmuxer.prototype = new Stream();
  13725. var transmuxer = {
  13726. Transmuxer: Transmuxer,
  13727. VideoSegmentStream: VideoSegmentStream,
  13728. AudioSegmentStream: AudioSegmentStream,
  13729. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  13730. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  13731. // exported for testing
  13732. generateSegmentTimingInfo: generateSegmentTimingInfo
  13733. };
  13734. /**
  13735. * mux.js
  13736. *
  13737. * Copyright (c) Brightcove
  13738. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13739. */
  13740. var toUnsigned$3 = function (value) {
  13741. return value >>> 0;
  13742. };
  13743. var toHexString$1 = function (value) {
  13744. return ('00' + value.toString(16)).slice(-2);
  13745. };
  13746. var bin = {
  13747. toUnsigned: toUnsigned$3,
  13748. toHexString: toHexString$1
  13749. };
  13750. var parseType$3 = function (buffer) {
  13751. var result = '';
  13752. result += String.fromCharCode(buffer[0]);
  13753. result += String.fromCharCode(buffer[1]);
  13754. result += String.fromCharCode(buffer[2]);
  13755. result += String.fromCharCode(buffer[3]);
  13756. return result;
  13757. };
  13758. var parseType_1 = parseType$3;
  13759. var toUnsigned$2 = bin.toUnsigned;
  13760. var parseType$2 = parseType_1;
  13761. var findBox$2 = function (data, path) {
  13762. var results = [],
  13763. i,
  13764. size,
  13765. type,
  13766. end,
  13767. subresults;
  13768. if (!path.length) {
  13769. // short-circuit the search for empty paths
  13770. return null;
  13771. }
  13772. for (i = 0; i < data.byteLength;) {
  13773. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  13774. type = parseType$2(data.subarray(i + 4, i + 8));
  13775. end = size > 1 ? i + size : data.byteLength;
  13776. if (type === path[0]) {
  13777. if (path.length === 1) {
  13778. // this is the end of the path and we've found the box we were
  13779. // looking for
  13780. results.push(data.subarray(i + 8, end));
  13781. } else {
  13782. // recursively search for the next box along the path
  13783. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  13784. if (subresults.length) {
  13785. results = results.concat(subresults);
  13786. }
  13787. }
  13788. }
  13789. i = end;
  13790. } // we've finished searching all of data
  13791. return results;
  13792. };
  13793. var findBox_1 = findBox$2;
  13794. var toUnsigned$1 = bin.toUnsigned;
  13795. var getUint64$2 = numbers.getUint64;
  13796. var tfdt = function (data) {
  13797. var result = {
  13798. version: data[0],
  13799. flags: new Uint8Array(data.subarray(1, 4))
  13800. };
  13801. if (result.version === 1) {
  13802. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  13803. } else {
  13804. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  13805. }
  13806. return result;
  13807. };
  13808. var parseTfdt$2 = tfdt;
  13809. var parseSampleFlags$1 = function (flags) {
  13810. return {
  13811. isLeading: (flags[0] & 0x0c) >>> 2,
  13812. dependsOn: flags[0] & 0x03,
  13813. isDependedOn: (flags[1] & 0xc0) >>> 6,
  13814. hasRedundancy: (flags[1] & 0x30) >>> 4,
  13815. paddingValue: (flags[1] & 0x0e) >>> 1,
  13816. isNonSyncSample: flags[1] & 0x01,
  13817. degradationPriority: flags[2] << 8 | flags[3]
  13818. };
  13819. };
  13820. var parseSampleFlags_1 = parseSampleFlags$1;
  13821. var parseSampleFlags = parseSampleFlags_1;
  13822. var trun = function (data) {
  13823. var result = {
  13824. version: data[0],
  13825. flags: new Uint8Array(data.subarray(1, 4)),
  13826. samples: []
  13827. },
  13828. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  13829. // Flag interpretation
  13830. dataOffsetPresent = result.flags[2] & 0x01,
  13831. // compare with 2nd byte of 0x1
  13832. firstSampleFlagsPresent = result.flags[2] & 0x04,
  13833. // compare with 2nd byte of 0x4
  13834. sampleDurationPresent = result.flags[1] & 0x01,
  13835. // compare with 2nd byte of 0x100
  13836. sampleSizePresent = result.flags[1] & 0x02,
  13837. // compare with 2nd byte of 0x200
  13838. sampleFlagsPresent = result.flags[1] & 0x04,
  13839. // compare with 2nd byte of 0x400
  13840. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  13841. // compare with 2nd byte of 0x800
  13842. sampleCount = view.getUint32(4),
  13843. offset = 8,
  13844. sample;
  13845. if (dataOffsetPresent) {
  13846. // 32 bit signed integer
  13847. result.dataOffset = view.getInt32(offset);
  13848. offset += 4;
  13849. } // Overrides the flags for the first sample only. The order of
  13850. // optional values will be: duration, size, compositionTimeOffset
  13851. if (firstSampleFlagsPresent && sampleCount) {
  13852. sample = {
  13853. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  13854. };
  13855. offset += 4;
  13856. if (sampleDurationPresent) {
  13857. sample.duration = view.getUint32(offset);
  13858. offset += 4;
  13859. }
  13860. if (sampleSizePresent) {
  13861. sample.size = view.getUint32(offset);
  13862. offset += 4;
  13863. }
  13864. if (sampleCompositionTimeOffsetPresent) {
  13865. if (result.version === 1) {
  13866. sample.compositionTimeOffset = view.getInt32(offset);
  13867. } else {
  13868. sample.compositionTimeOffset = view.getUint32(offset);
  13869. }
  13870. offset += 4;
  13871. }
  13872. result.samples.push(sample);
  13873. sampleCount--;
  13874. }
  13875. while (sampleCount--) {
  13876. sample = {};
  13877. if (sampleDurationPresent) {
  13878. sample.duration = view.getUint32(offset);
  13879. offset += 4;
  13880. }
  13881. if (sampleSizePresent) {
  13882. sample.size = view.getUint32(offset);
  13883. offset += 4;
  13884. }
  13885. if (sampleFlagsPresent) {
  13886. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  13887. offset += 4;
  13888. }
  13889. if (sampleCompositionTimeOffsetPresent) {
  13890. if (result.version === 1) {
  13891. sample.compositionTimeOffset = view.getInt32(offset);
  13892. } else {
  13893. sample.compositionTimeOffset = view.getUint32(offset);
  13894. }
  13895. offset += 4;
  13896. }
  13897. result.samples.push(sample);
  13898. }
  13899. return result;
  13900. };
  13901. var parseTrun$2 = trun;
  13902. var tfhd = function (data) {
  13903. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  13904. result = {
  13905. version: data[0],
  13906. flags: new Uint8Array(data.subarray(1, 4)),
  13907. trackId: view.getUint32(4)
  13908. },
  13909. baseDataOffsetPresent = result.flags[2] & 0x01,
  13910. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  13911. defaultSampleDurationPresent = result.flags[2] & 0x08,
  13912. defaultSampleSizePresent = result.flags[2] & 0x10,
  13913. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  13914. durationIsEmpty = result.flags[0] & 0x010000,
  13915. defaultBaseIsMoof = result.flags[0] & 0x020000,
  13916. i;
  13917. i = 8;
  13918. if (baseDataOffsetPresent) {
  13919. i += 4; // truncate top 4 bytes
  13920. // FIXME: should we read the full 64 bits?
  13921. result.baseDataOffset = view.getUint32(12);
  13922. i += 4;
  13923. }
  13924. if (sampleDescriptionIndexPresent) {
  13925. result.sampleDescriptionIndex = view.getUint32(i);
  13926. i += 4;
  13927. }
  13928. if (defaultSampleDurationPresent) {
  13929. result.defaultSampleDuration = view.getUint32(i);
  13930. i += 4;
  13931. }
  13932. if (defaultSampleSizePresent) {
  13933. result.defaultSampleSize = view.getUint32(i);
  13934. i += 4;
  13935. }
  13936. if (defaultSampleFlagsPresent) {
  13937. result.defaultSampleFlags = view.getUint32(i);
  13938. }
  13939. if (durationIsEmpty) {
  13940. result.durationIsEmpty = true;
  13941. }
  13942. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  13943. result.baseDataOffsetIsMoof = true;
  13944. }
  13945. return result;
  13946. };
  13947. var parseTfhd$2 = tfhd;
  13948. var win;
  13949. if (typeof window !== "undefined") {
  13950. win = window;
  13951. } else if (typeof commonjsGlobal !== "undefined") {
  13952. win = commonjsGlobal;
  13953. } else if (typeof self !== "undefined") {
  13954. win = self;
  13955. } else {
  13956. win = {};
  13957. }
  13958. var window_1 = win;
  13959. /**
  13960. * mux.js
  13961. *
  13962. * Copyright (c) Brightcove
  13963. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13964. *
  13965. * Reads in-band CEA-708 captions out of FMP4 segments.
  13966. * @see https://en.wikipedia.org/wiki/CEA-708
  13967. */
  13968. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  13969. var CaptionStream = captionStream.CaptionStream;
  13970. var findBox$1 = findBox_1;
  13971. var parseTfdt$1 = parseTfdt$2;
  13972. var parseTrun$1 = parseTrun$2;
  13973. var parseTfhd$1 = parseTfhd$2;
  13974. var window$2 = window_1;
  13975. /**
  13976. * Maps an offset in the mdat to a sample based on the the size of the samples.
  13977. * Assumes that `parseSamples` has been called first.
  13978. *
  13979. * @param {Number} offset - The offset into the mdat
  13980. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  13981. * @return {?Object} The matching sample, or null if no match was found.
  13982. *
  13983. * @see ISO-BMFF-12/2015, Section 8.8.8
  13984. **/
  13985. var mapToSample = function (offset, samples) {
  13986. var approximateOffset = offset;
  13987. for (var i = 0; i < samples.length; i++) {
  13988. var sample = samples[i];
  13989. if (approximateOffset < sample.size) {
  13990. return sample;
  13991. }
  13992. approximateOffset -= sample.size;
  13993. }
  13994. return null;
  13995. };
  13996. /**
  13997. * Finds SEI nal units contained in a Media Data Box.
  13998. * Assumes that `parseSamples` has been called first.
  13999. *
  14000. * @param {Uint8Array} avcStream - The bytes of the mdat
  14001. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  14002. * @param {Number} trackId - The trackId of this video track
  14003. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  14004. * The contents of the seiNal should match what is expected by
  14005. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  14006. *
  14007. * @see ISO-BMFF-12/2015, Section 8.1.1
  14008. * @see Rec. ITU-T H.264, 7.3.2.3.1
  14009. **/
  14010. var findSeiNals = function (avcStream, samples, trackId) {
  14011. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  14012. result = {
  14013. logs: [],
  14014. seiNals: []
  14015. },
  14016. seiNal,
  14017. i,
  14018. length,
  14019. lastMatchedSample;
  14020. for (i = 0; i + 4 < avcStream.length; i += length) {
  14021. length = avcView.getUint32(i);
  14022. i += 4; // Bail if this doesn't appear to be an H264 stream
  14023. if (length <= 0) {
  14024. continue;
  14025. }
  14026. switch (avcStream[i] & 0x1F) {
  14027. case 0x06:
  14028. var data = avcStream.subarray(i + 1, i + 1 + length);
  14029. var matchingSample = mapToSample(i, samples);
  14030. seiNal = {
  14031. nalUnitType: 'sei_rbsp',
  14032. size: length,
  14033. data: data,
  14034. escapedRBSP: discardEmulationPreventionBytes(data),
  14035. trackId: trackId
  14036. };
  14037. if (matchingSample) {
  14038. seiNal.pts = matchingSample.pts;
  14039. seiNal.dts = matchingSample.dts;
  14040. lastMatchedSample = matchingSample;
  14041. } else if (lastMatchedSample) {
  14042. // If a matching sample cannot be found, use the last
  14043. // sample's values as they should be as close as possible
  14044. seiNal.pts = lastMatchedSample.pts;
  14045. seiNal.dts = lastMatchedSample.dts;
  14046. } else {
  14047. result.logs.push({
  14048. level: 'warn',
  14049. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  14050. });
  14051. break;
  14052. }
  14053. result.seiNals.push(seiNal);
  14054. break;
  14055. }
  14056. }
  14057. return result;
  14058. };
  14059. /**
  14060. * Parses sample information out of Track Run Boxes and calculates
  14061. * the absolute presentation and decode timestamps of each sample.
  14062. *
  14063. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  14064. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  14065. @see ISO-BMFF-12/2015, Section 8.8.12
  14066. * @param {Object} tfhd - The parsed Track Fragment Header
  14067. * @see inspect.parseTfhd
  14068. * @return {Object[]} the parsed samples
  14069. *
  14070. * @see ISO-BMFF-12/2015, Section 8.8.8
  14071. **/
  14072. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  14073. var currentDts = baseMediaDecodeTime;
  14074. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  14075. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  14076. var trackId = tfhd.trackId;
  14077. var allSamples = [];
  14078. truns.forEach(function (trun) {
  14079. // Note: We currently do not parse the sample table as well
  14080. // as the trun. It's possible some sources will require this.
  14081. // moov > trak > mdia > minf > stbl
  14082. var trackRun = parseTrun$1(trun);
  14083. var samples = trackRun.samples;
  14084. samples.forEach(function (sample) {
  14085. if (sample.duration === undefined) {
  14086. sample.duration = defaultSampleDuration;
  14087. }
  14088. if (sample.size === undefined) {
  14089. sample.size = defaultSampleSize;
  14090. }
  14091. sample.trackId = trackId;
  14092. sample.dts = currentDts;
  14093. if (sample.compositionTimeOffset === undefined) {
  14094. sample.compositionTimeOffset = 0;
  14095. }
  14096. if (typeof currentDts === 'bigint') {
  14097. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  14098. currentDts += window$2.BigInt(sample.duration);
  14099. } else {
  14100. sample.pts = currentDts + sample.compositionTimeOffset;
  14101. currentDts += sample.duration;
  14102. }
  14103. });
  14104. allSamples = allSamples.concat(samples);
  14105. });
  14106. return allSamples;
  14107. };
  14108. /**
  14109. * Parses out caption nals from an FMP4 segment's video tracks.
  14110. *
  14111. * @param {Uint8Array} segment - The bytes of a single segment
  14112. * @param {Number} videoTrackId - The trackId of a video track in the segment
  14113. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  14114. * a list of seiNals found in that track
  14115. **/
  14116. var parseCaptionNals = function (segment, videoTrackId) {
  14117. // To get the samples
  14118. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  14119. var mdats = findBox$1(segment, ['mdat']);
  14120. var captionNals = {};
  14121. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  14122. mdats.forEach(function (mdat, index) {
  14123. var matchingTraf = trafs[index];
  14124. mdatTrafPairs.push({
  14125. mdat: mdat,
  14126. traf: matchingTraf
  14127. });
  14128. });
  14129. mdatTrafPairs.forEach(function (pair) {
  14130. var mdat = pair.mdat;
  14131. var traf = pair.traf;
  14132. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  14133. var headerInfo = parseTfhd$1(tfhd[0]);
  14134. var trackId = headerInfo.trackId;
  14135. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  14136. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  14137. var truns = findBox$1(traf, ['trun']);
  14138. var samples;
  14139. var result; // Only parse video data for the chosen video track
  14140. if (videoTrackId === trackId && truns.length > 0) {
  14141. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  14142. result = findSeiNals(mdat, samples, trackId);
  14143. if (!captionNals[trackId]) {
  14144. captionNals[trackId] = {
  14145. seiNals: [],
  14146. logs: []
  14147. };
  14148. }
  14149. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  14150. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  14151. }
  14152. });
  14153. return captionNals;
  14154. };
  14155. /**
  14156. * Parses out inband captions from an MP4 container and returns
  14157. * caption objects that can be used by WebVTT and the TextTrack API.
  14158. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  14159. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  14160. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  14161. *
  14162. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  14163. * @param {Number} trackId - The id of the video track to parse
  14164. * @param {Number} timescale - The timescale for the video track from the init segment
  14165. *
  14166. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  14167. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  14168. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  14169. * @return {String} parsedCaptions[].text - The visible content of the caption
  14170. **/
  14171. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  14172. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  14173. if (trackId === null) {
  14174. return null;
  14175. }
  14176. captionNals = parseCaptionNals(segment, trackId);
  14177. var trackNals = captionNals[trackId] || {};
  14178. return {
  14179. seiNals: trackNals.seiNals,
  14180. logs: trackNals.logs,
  14181. timescale: timescale
  14182. };
  14183. };
  14184. /**
  14185. * Converts SEI NALUs into captions that can be used by video.js
  14186. **/
  14187. var CaptionParser = function () {
  14188. var isInitialized = false;
  14189. var captionStream; // Stores segments seen before trackId and timescale are set
  14190. var segmentCache; // Stores video track ID of the track being parsed
  14191. var trackId; // Stores the timescale of the track being parsed
  14192. var timescale; // Stores captions parsed so far
  14193. var parsedCaptions; // Stores whether we are receiving partial data or not
  14194. var parsingPartial;
  14195. /**
  14196. * A method to indicate whether a CaptionParser has been initalized
  14197. * @returns {Boolean}
  14198. **/
  14199. this.isInitialized = function () {
  14200. return isInitialized;
  14201. };
  14202. /**
  14203. * Initializes the underlying CaptionStream, SEI NAL parsing
  14204. * and management, and caption collection
  14205. **/
  14206. this.init = function (options) {
  14207. captionStream = new CaptionStream();
  14208. isInitialized = true;
  14209. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  14210. captionStream.on('data', function (event) {
  14211. // Convert to seconds in the source's timescale
  14212. event.startTime = event.startPts / timescale;
  14213. event.endTime = event.endPts / timescale;
  14214. parsedCaptions.captions.push(event);
  14215. parsedCaptions.captionStreams[event.stream] = true;
  14216. });
  14217. captionStream.on('log', function (log) {
  14218. parsedCaptions.logs.push(log);
  14219. });
  14220. };
  14221. /**
  14222. * Determines if a new video track will be selected
  14223. * or if the timescale changed
  14224. * @return {Boolean}
  14225. **/
  14226. this.isNewInit = function (videoTrackIds, timescales) {
  14227. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  14228. return false;
  14229. }
  14230. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  14231. };
  14232. /**
  14233. * Parses out SEI captions and interacts with underlying
  14234. * CaptionStream to return dispatched captions
  14235. *
  14236. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  14237. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  14238. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  14239. * @see parseEmbeddedCaptions
  14240. * @see m2ts/caption-stream.js
  14241. **/
  14242. this.parse = function (segment, videoTrackIds, timescales) {
  14243. var parsedData;
  14244. if (!this.isInitialized()) {
  14245. return null; // This is not likely to be a video segment
  14246. } else if (!videoTrackIds || !timescales) {
  14247. return null;
  14248. } else if (this.isNewInit(videoTrackIds, timescales)) {
  14249. // Use the first video track only as there is no
  14250. // mechanism to switch to other video tracks
  14251. trackId = videoTrackIds[0];
  14252. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  14253. // data until we have one.
  14254. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  14255. } else if (trackId === null || !timescale) {
  14256. segmentCache.push(segment);
  14257. return null;
  14258. } // Now that a timescale and trackId is set, parse cached segments
  14259. while (segmentCache.length > 0) {
  14260. var cachedSegment = segmentCache.shift();
  14261. this.parse(cachedSegment, videoTrackIds, timescales);
  14262. }
  14263. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  14264. if (parsedData && parsedData.logs) {
  14265. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  14266. }
  14267. if (parsedData === null || !parsedData.seiNals) {
  14268. if (parsedCaptions.logs.length) {
  14269. return {
  14270. logs: parsedCaptions.logs,
  14271. captions: [],
  14272. captionStreams: []
  14273. };
  14274. }
  14275. return null;
  14276. }
  14277. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  14278. this.flushStream();
  14279. return parsedCaptions;
  14280. };
  14281. /**
  14282. * Pushes SEI NALUs onto CaptionStream
  14283. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  14284. * Assumes that `parseCaptionNals` has been called first
  14285. * @see m2ts/caption-stream.js
  14286. **/
  14287. this.pushNals = function (nals) {
  14288. if (!this.isInitialized() || !nals || nals.length === 0) {
  14289. return null;
  14290. }
  14291. nals.forEach(function (nal) {
  14292. captionStream.push(nal);
  14293. });
  14294. };
  14295. /**
  14296. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  14297. * @see m2ts/caption-stream.js
  14298. **/
  14299. this.flushStream = function () {
  14300. if (!this.isInitialized()) {
  14301. return null;
  14302. }
  14303. if (!parsingPartial) {
  14304. captionStream.flush();
  14305. } else {
  14306. captionStream.partialFlush();
  14307. }
  14308. };
  14309. /**
  14310. * Reset caption buckets for new data
  14311. **/
  14312. this.clearParsedCaptions = function () {
  14313. parsedCaptions.captions = [];
  14314. parsedCaptions.captionStreams = {};
  14315. parsedCaptions.logs = [];
  14316. };
  14317. /**
  14318. * Resets underlying CaptionStream
  14319. * @see m2ts/caption-stream.js
  14320. **/
  14321. this.resetCaptionStream = function () {
  14322. if (!this.isInitialized()) {
  14323. return null;
  14324. }
  14325. captionStream.reset();
  14326. };
  14327. /**
  14328. * Convenience method to clear all captions flushed from the
  14329. * CaptionStream and still being parsed
  14330. * @see m2ts/caption-stream.js
  14331. **/
  14332. this.clearAllCaptions = function () {
  14333. this.clearParsedCaptions();
  14334. this.resetCaptionStream();
  14335. };
  14336. /**
  14337. * Reset caption parser
  14338. **/
  14339. this.reset = function () {
  14340. segmentCache = [];
  14341. trackId = null;
  14342. timescale = null;
  14343. if (!parsedCaptions) {
  14344. parsedCaptions = {
  14345. captions: [],
  14346. // CC1, CC2, CC3, CC4
  14347. captionStreams: {},
  14348. logs: []
  14349. };
  14350. } else {
  14351. this.clearParsedCaptions();
  14352. }
  14353. this.resetCaptionStream();
  14354. };
  14355. this.reset();
  14356. };
  14357. var captionParser = CaptionParser;
  14358. /**
  14359. * Returns the first string in the data array ending with a null char '\0'
  14360. * @param {UInt8} data
  14361. * @returns the string with the null char
  14362. */
  14363. var uint8ToCString$1 = function (data) {
  14364. var index = 0;
  14365. var curChar = String.fromCharCode(data[index]);
  14366. var retString = '';
  14367. while (curChar !== '\0') {
  14368. retString += curChar;
  14369. index++;
  14370. curChar = String.fromCharCode(data[index]);
  14371. } // Add nullChar
  14372. retString += curChar;
  14373. return retString;
  14374. };
  14375. var string = {
  14376. uint8ToCString: uint8ToCString$1
  14377. };
  14378. var uint8ToCString = string.uint8ToCString;
  14379. var getUint64$1 = numbers.getUint64;
  14380. /**
  14381. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  14382. * References:
  14383. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  14384. * https://aomediacodec.github.io/id3-emsg/
  14385. *
  14386. * Takes emsg box data as a uint8 array and returns a emsg box object
  14387. * @param {UInt8Array} boxData data from emsg box
  14388. * @returns A parsed emsg box object
  14389. */
  14390. var parseEmsgBox = function (boxData) {
  14391. // version + flags
  14392. var offset = 4;
  14393. var version = boxData[0];
  14394. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  14395. if (version === 0) {
  14396. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  14397. offset += scheme_id_uri.length;
  14398. value = uint8ToCString(boxData.subarray(offset));
  14399. offset += value.length;
  14400. var dv = new DataView(boxData.buffer);
  14401. timescale = dv.getUint32(offset);
  14402. offset += 4;
  14403. presentation_time_delta = dv.getUint32(offset);
  14404. offset += 4;
  14405. event_duration = dv.getUint32(offset);
  14406. offset += 4;
  14407. id = dv.getUint32(offset);
  14408. offset += 4;
  14409. } else if (version === 1) {
  14410. var dv = new DataView(boxData.buffer);
  14411. timescale = dv.getUint32(offset);
  14412. offset += 4;
  14413. presentation_time = getUint64$1(boxData.subarray(offset));
  14414. offset += 8;
  14415. event_duration = dv.getUint32(offset);
  14416. offset += 4;
  14417. id = dv.getUint32(offset);
  14418. offset += 4;
  14419. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  14420. offset += scheme_id_uri.length;
  14421. value = uint8ToCString(boxData.subarray(offset));
  14422. offset += value.length;
  14423. }
  14424. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  14425. var emsgBox = {
  14426. scheme_id_uri,
  14427. value,
  14428. // if timescale is undefined or 0 set to 1
  14429. timescale: timescale ? timescale : 1,
  14430. presentation_time,
  14431. presentation_time_delta,
  14432. event_duration,
  14433. id,
  14434. message_data
  14435. };
  14436. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  14437. };
  14438. /**
  14439. * Scales a presentation time or time delta with an offset with a provided timescale
  14440. * @param {number} presentationTime
  14441. * @param {number} timescale
  14442. * @param {number} timeDelta
  14443. * @param {number} offset
  14444. * @returns the scaled time as a number
  14445. */
  14446. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  14447. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  14448. };
  14449. /**
  14450. * Checks the emsg box data for validity based on the version
  14451. * @param {number} version of the emsg box to validate
  14452. * @param {Object} emsg the emsg data to validate
  14453. * @returns if the box is valid as a boolean
  14454. */
  14455. var isValidEmsgBox = function (version, emsg) {
  14456. var hasScheme = emsg.scheme_id_uri !== '\0';
  14457. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  14458. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  14459. return !(version > 1) && isValidV0Box || isValidV1Box;
  14460. }; // Utility function to check if an object is defined
  14461. var isDefined = function (data) {
  14462. return data !== undefined || data !== null;
  14463. };
  14464. var emsg$1 = {
  14465. parseEmsgBox: parseEmsgBox,
  14466. scaleTime: scaleTime
  14467. };
  14468. /**
  14469. * mux.js
  14470. *
  14471. * Copyright (c) Brightcove
  14472. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14473. *
  14474. * Utilities to detect basic properties and metadata about MP4s.
  14475. */
  14476. var toUnsigned = bin.toUnsigned;
  14477. var toHexString = bin.toHexString;
  14478. var findBox = findBox_1;
  14479. var parseType$1 = parseType_1;
  14480. var emsg = emsg$1;
  14481. var parseTfhd = parseTfhd$2;
  14482. var parseTrun = parseTrun$2;
  14483. var parseTfdt = parseTfdt$2;
  14484. var getUint64 = numbers.getUint64;
  14485. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  14486. var window$1 = window_1;
  14487. var parseId3Frames = parseId3.parseId3Frames;
  14488. /**
  14489. * Parses an MP4 initialization segment and extracts the timescale
  14490. * values for any declared tracks. Timescale values indicate the
  14491. * number of clock ticks per second to assume for time-based values
  14492. * elsewhere in the MP4.
  14493. *
  14494. * To determine the start time of an MP4, you need two pieces of
  14495. * information: the timescale unit and the earliest base media decode
  14496. * time. Multiple timescales can be specified within an MP4 but the
  14497. * base media decode time is always expressed in the timescale from
  14498. * the media header box for the track:
  14499. * ```
  14500. * moov > trak > mdia > mdhd.timescale
  14501. * ```
  14502. * @param init {Uint8Array} the bytes of the init segment
  14503. * @return {object} a hash of track ids to timescale values or null if
  14504. * the init segment is malformed.
  14505. */
  14506. timescale = function (init) {
  14507. var result = {},
  14508. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  14509. return traks.reduce(function (result, trak) {
  14510. var tkhd, version, index, id, mdhd;
  14511. tkhd = findBox(trak, ['tkhd'])[0];
  14512. if (!tkhd) {
  14513. return null;
  14514. }
  14515. version = tkhd[0];
  14516. index = version === 0 ? 12 : 20;
  14517. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  14518. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  14519. if (!mdhd) {
  14520. return null;
  14521. }
  14522. version = mdhd[0];
  14523. index = version === 0 ? 12 : 20;
  14524. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  14525. return result;
  14526. }, result);
  14527. };
  14528. /**
  14529. * Determine the base media decode start time, in seconds, for an MP4
  14530. * fragment. If multiple fragments are specified, the earliest time is
  14531. * returned.
  14532. *
  14533. * The base media decode time can be parsed from track fragment
  14534. * metadata:
  14535. * ```
  14536. * moof > traf > tfdt.baseMediaDecodeTime
  14537. * ```
  14538. * It requires the timescale value from the mdhd to interpret.
  14539. *
  14540. * @param timescale {object} a hash of track ids to timescale values.
  14541. * @return {number} the earliest base media decode start time for the
  14542. * fragment, in seconds
  14543. */
  14544. startTime = function (timescale, fragment) {
  14545. var trafs; // we need info from two childrend of each track fragment box
  14546. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  14547. var lowestTime = trafs.reduce(function (acc, traf) {
  14548. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  14549. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  14550. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  14551. var tfdt = findBox(traf, ['tfdt'])[0];
  14552. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  14553. var baseTime; // version 1 is 64 bit
  14554. if (tfdt[0] === 1) {
  14555. baseTime = getUint64(tfdt.subarray(4, 12));
  14556. } else {
  14557. baseTime = dv.getUint32(4);
  14558. } // convert base time to seconds if it is a valid number.
  14559. let seconds;
  14560. if (typeof baseTime === 'bigint') {
  14561. seconds = baseTime / window$1.BigInt(scale);
  14562. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  14563. seconds = baseTime / scale;
  14564. }
  14565. if (seconds < Number.MAX_SAFE_INTEGER) {
  14566. seconds = Number(seconds);
  14567. }
  14568. if (seconds < acc) {
  14569. acc = seconds;
  14570. }
  14571. return acc;
  14572. }, Infinity);
  14573. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  14574. };
  14575. /**
  14576. * Determine the composition start, in seconds, for an MP4
  14577. * fragment.
  14578. *
  14579. * The composition start time of a fragment can be calculated using the base
  14580. * media decode time, composition time offset, and timescale, as follows:
  14581. *
  14582. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  14583. *
  14584. * All of the aforementioned information is contained within a media fragment's
  14585. * `traf` box, except for timescale info, which comes from the initialization
  14586. * segment, so a track id (also contained within a `traf`) is also necessary to
  14587. * associate it with a timescale
  14588. *
  14589. *
  14590. * @param timescales {object} - a hash of track ids to timescale values.
  14591. * @param fragment {Unit8Array} - the bytes of a media segment
  14592. * @return {number} the composition start time for the fragment, in seconds
  14593. **/
  14594. compositionStartTime = function (timescales, fragment) {
  14595. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  14596. var baseMediaDecodeTime = 0;
  14597. var compositionTimeOffset = 0;
  14598. var trackId;
  14599. if (trafBoxes && trafBoxes.length) {
  14600. // The spec states that track run samples contained within a `traf` box are contiguous, but
  14601. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  14602. // We will assume that they are, so we only need the first to calculate start time.
  14603. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  14604. var trun = findBox(trafBoxes[0], ['trun'])[0];
  14605. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  14606. if (tfhd) {
  14607. var parsedTfhd = parseTfhd(tfhd);
  14608. trackId = parsedTfhd.trackId;
  14609. }
  14610. if (tfdt) {
  14611. var parsedTfdt = parseTfdt(tfdt);
  14612. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  14613. }
  14614. if (trun) {
  14615. var parsedTrun = parseTrun(trun);
  14616. if (parsedTrun.samples && parsedTrun.samples.length) {
  14617. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  14618. }
  14619. }
  14620. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  14621. // specified.
  14622. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  14623. if (typeof baseMediaDecodeTime === 'bigint') {
  14624. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  14625. timescale = window$1.BigInt(timescale);
  14626. }
  14627. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  14628. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  14629. result = Number(result);
  14630. }
  14631. return result;
  14632. };
  14633. /**
  14634. * Find the trackIds of the video tracks in this source.
  14635. * Found by parsing the Handler Reference and Track Header Boxes:
  14636. * moov > trak > mdia > hdlr
  14637. * moov > trak > tkhd
  14638. *
  14639. * @param {Uint8Array} init - The bytes of the init segment for this source
  14640. * @return {Number[]} A list of trackIds
  14641. *
  14642. * @see ISO-BMFF-12/2015, Section 8.4.3
  14643. **/
  14644. getVideoTrackIds = function (init) {
  14645. var traks = findBox(init, ['moov', 'trak']);
  14646. var videoTrackIds = [];
  14647. traks.forEach(function (trak) {
  14648. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  14649. var tkhds = findBox(trak, ['tkhd']);
  14650. hdlrs.forEach(function (hdlr, index) {
  14651. var handlerType = parseType$1(hdlr.subarray(8, 12));
  14652. var tkhd = tkhds[index];
  14653. var view;
  14654. var version;
  14655. var trackId;
  14656. if (handlerType === 'vide') {
  14657. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  14658. version = view.getUint8(0);
  14659. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  14660. videoTrackIds.push(trackId);
  14661. }
  14662. });
  14663. });
  14664. return videoTrackIds;
  14665. };
  14666. getTimescaleFromMediaHeader = function (mdhd) {
  14667. // mdhd is a FullBox, meaning it will have its own version as the first byte
  14668. var version = mdhd[0];
  14669. var index = version === 0 ? 12 : 20;
  14670. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  14671. };
  14672. /**
  14673. * Get all the video, audio, and hint tracks from a non fragmented
  14674. * mp4 segment
  14675. */
  14676. getTracks = function (init) {
  14677. var traks = findBox(init, ['moov', 'trak']);
  14678. var tracks = [];
  14679. traks.forEach(function (trak) {
  14680. var track = {};
  14681. var tkhd = findBox(trak, ['tkhd'])[0];
  14682. var view, tkhdVersion; // id
  14683. if (tkhd) {
  14684. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  14685. tkhdVersion = view.getUint8(0);
  14686. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  14687. }
  14688. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  14689. if (hdlr) {
  14690. var type = parseType$1(hdlr.subarray(8, 12));
  14691. if (type === 'vide') {
  14692. track.type = 'video';
  14693. } else if (type === 'soun') {
  14694. track.type = 'audio';
  14695. } else {
  14696. track.type = type;
  14697. }
  14698. } // codec
  14699. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  14700. if (stsd) {
  14701. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  14702. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  14703. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  14704. var codecConfig, codecConfigType;
  14705. if (codecBox) {
  14706. // https://tools.ietf.org/html/rfc6381#section-3.3
  14707. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  14708. // we don't need anything but the "config" parameter of the
  14709. // avc1 codecBox
  14710. codecConfig = codecBox.subarray(78);
  14711. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  14712. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  14713. track.codec += '.'; // left padded with zeroes for single digit hex
  14714. // profile idc
  14715. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  14716. track.codec += toHexString(codecConfig[10]); // level idc
  14717. track.codec += toHexString(codecConfig[11]);
  14718. } else {
  14719. // TODO: show a warning that we couldn't parse the codec
  14720. // and are using the default
  14721. track.codec = 'avc1.4d400d';
  14722. }
  14723. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  14724. // we do not need anything but the streamDescriptor of the mp4a codecBox
  14725. codecConfig = codecBox.subarray(28);
  14726. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  14727. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  14728. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  14729. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  14730. } else {
  14731. // TODO: show a warning that we couldn't parse the codec
  14732. // and are using the default
  14733. track.codec = 'mp4a.40.2';
  14734. }
  14735. } else {
  14736. // flac, opus, etc
  14737. track.codec = track.codec.toLowerCase();
  14738. }
  14739. }
  14740. }
  14741. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  14742. if (mdhd) {
  14743. track.timescale = getTimescaleFromMediaHeader(mdhd);
  14744. }
  14745. tracks.push(track);
  14746. });
  14747. return tracks;
  14748. };
  14749. /**
  14750. * Returns an array of emsg ID3 data from the provided segmentData.
  14751. * An offset can also be provided as the Latest Arrival Time to calculate
  14752. * the Event Start Time of v0 EMSG boxes.
  14753. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  14754. *
  14755. * @param {Uint8Array} segmentData the segment byte array.
  14756. * @param {number} offset the segment start time or Latest Arrival Time,
  14757. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  14758. */
  14759. getEmsgID3 = function (segmentData, offset = 0) {
  14760. var emsgBoxes = findBox(segmentData, ['emsg']);
  14761. return emsgBoxes.map(data => {
  14762. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  14763. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  14764. return {
  14765. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  14766. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  14767. frames: parsedId3Frames
  14768. };
  14769. });
  14770. };
  14771. var probe$2 = {
  14772. // export mp4 inspector's findBox and parseType for backwards compatibility
  14773. findBox: findBox,
  14774. parseType: parseType$1,
  14775. timescale: timescale,
  14776. startTime: startTime,
  14777. compositionStartTime: compositionStartTime,
  14778. videoTrackIds: getVideoTrackIds,
  14779. tracks: getTracks,
  14780. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  14781. getEmsgID3: getEmsgID3
  14782. };
  14783. /**
  14784. * mux.js
  14785. *
  14786. * Copyright (c) Brightcove
  14787. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14788. *
  14789. * Utilities to detect basic properties and metadata about TS Segments.
  14790. */
  14791. var StreamTypes$1 = streamTypes;
  14792. var parsePid = function (packet) {
  14793. var pid = packet[1] & 0x1f;
  14794. pid <<= 8;
  14795. pid |= packet[2];
  14796. return pid;
  14797. };
  14798. var parsePayloadUnitStartIndicator = function (packet) {
  14799. return !!(packet[1] & 0x40);
  14800. };
  14801. var parseAdaptionField = function (packet) {
  14802. var offset = 0; // if an adaption field is present, its length is specified by the
  14803. // fifth byte of the TS packet header. The adaptation field is
  14804. // used to add stuffing to PES packets that don't fill a complete
  14805. // TS packet, and to specify some forms of timing and control data
  14806. // that we do not currently use.
  14807. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  14808. offset += packet[4] + 1;
  14809. }
  14810. return offset;
  14811. };
  14812. var parseType = function (packet, pmtPid) {
  14813. var pid = parsePid(packet);
  14814. if (pid === 0) {
  14815. return 'pat';
  14816. } else if (pid === pmtPid) {
  14817. return 'pmt';
  14818. } else if (pmtPid) {
  14819. return 'pes';
  14820. }
  14821. return null;
  14822. };
  14823. var parsePat = function (packet) {
  14824. var pusi = parsePayloadUnitStartIndicator(packet);
  14825. var offset = 4 + parseAdaptionField(packet);
  14826. if (pusi) {
  14827. offset += packet[offset] + 1;
  14828. }
  14829. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  14830. };
  14831. var parsePmt = function (packet) {
  14832. var programMapTable = {};
  14833. var pusi = parsePayloadUnitStartIndicator(packet);
  14834. var payloadOffset = 4 + parseAdaptionField(packet);
  14835. if (pusi) {
  14836. payloadOffset += packet[payloadOffset] + 1;
  14837. } // PMTs can be sent ahead of the time when they should actually
  14838. // take effect. We don't believe this should ever be the case
  14839. // for HLS but we'll ignore "forward" PMT declarations if we see
  14840. // them. Future PMT declarations have the current_next_indicator
  14841. // set to zero.
  14842. if (!(packet[payloadOffset + 5] & 0x01)) {
  14843. return;
  14844. }
  14845. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  14846. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  14847. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  14848. // long the program info descriptors are
  14849. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  14850. var offset = 12 + programInfoLength;
  14851. while (offset < tableEnd) {
  14852. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  14853. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  14854. // skip past the elementary stream descriptors, if present
  14855. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  14856. }
  14857. return programMapTable;
  14858. };
  14859. var parsePesType = function (packet, programMapTable) {
  14860. var pid = parsePid(packet);
  14861. var type = programMapTable[pid];
  14862. switch (type) {
  14863. case StreamTypes$1.H264_STREAM_TYPE:
  14864. return 'video';
  14865. case StreamTypes$1.ADTS_STREAM_TYPE:
  14866. return 'audio';
  14867. case StreamTypes$1.METADATA_STREAM_TYPE:
  14868. return 'timed-metadata';
  14869. default:
  14870. return null;
  14871. }
  14872. };
  14873. var parsePesTime = function (packet) {
  14874. var pusi = parsePayloadUnitStartIndicator(packet);
  14875. if (!pusi) {
  14876. return null;
  14877. }
  14878. var offset = 4 + parseAdaptionField(packet);
  14879. if (offset >= packet.byteLength) {
  14880. // From the H 222.0 MPEG-TS spec
  14881. // "For transport stream packets carrying PES packets, stuffing is needed when there
  14882. // is insufficient PES packet data to completely fill the transport stream packet
  14883. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  14884. // the sum of the lengths of the data elements in it, so that the payload bytes
  14885. // remaining after the adaptation field exactly accommodates the available PES packet
  14886. // data."
  14887. //
  14888. // If the offset is >= the length of the packet, then the packet contains no data
  14889. // and instead is just adaption field stuffing bytes
  14890. return null;
  14891. }
  14892. var pes = null;
  14893. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  14894. // and a DTS value. Determine what combination of values is
  14895. // available to work with.
  14896. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  14897. // performs all bitwise operations on 32-bit integers but javascript
  14898. // supports a much greater range (52-bits) of integer using standard
  14899. // mathematical operations.
  14900. // We construct a 31-bit value using bitwise operators over the 31
  14901. // most significant bits and then multiply by 4 (equal to a left-shift
  14902. // of 2) before we add the final 2 least significant bits of the
  14903. // timestamp (equal to an OR.)
  14904. if (ptsDtsFlags & 0xC0) {
  14905. pes = {}; // the PTS and DTS are not written out directly. For information
  14906. // on how they are encoded, see
  14907. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  14908. 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;
  14909. pes.pts *= 4; // Left shift by 2
  14910. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  14911. pes.dts = pes.pts;
  14912. if (ptsDtsFlags & 0x40) {
  14913. 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;
  14914. pes.dts *= 4; // Left shift by 2
  14915. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  14916. }
  14917. }
  14918. return pes;
  14919. };
  14920. var parseNalUnitType = function (type) {
  14921. switch (type) {
  14922. case 0x05:
  14923. return 'slice_layer_without_partitioning_rbsp_idr';
  14924. case 0x06:
  14925. return 'sei_rbsp';
  14926. case 0x07:
  14927. return 'seq_parameter_set_rbsp';
  14928. case 0x08:
  14929. return 'pic_parameter_set_rbsp';
  14930. case 0x09:
  14931. return 'access_unit_delimiter_rbsp';
  14932. default:
  14933. return null;
  14934. }
  14935. };
  14936. var videoPacketContainsKeyFrame = function (packet) {
  14937. var offset = 4 + parseAdaptionField(packet);
  14938. var frameBuffer = packet.subarray(offset);
  14939. var frameI = 0;
  14940. var frameSyncPoint = 0;
  14941. var foundKeyFrame = false;
  14942. var nalType; // advance the sync point to a NAL start, if necessary
  14943. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  14944. if (frameBuffer[frameSyncPoint + 2] === 1) {
  14945. // the sync point is properly aligned
  14946. frameI = frameSyncPoint + 5;
  14947. break;
  14948. }
  14949. }
  14950. while (frameI < frameBuffer.byteLength) {
  14951. // look at the current byte to determine if we've hit the end of
  14952. // a NAL unit boundary
  14953. switch (frameBuffer[frameI]) {
  14954. case 0:
  14955. // skip past non-sync sequences
  14956. if (frameBuffer[frameI - 1] !== 0) {
  14957. frameI += 2;
  14958. break;
  14959. } else if (frameBuffer[frameI - 2] !== 0) {
  14960. frameI++;
  14961. break;
  14962. }
  14963. if (frameSyncPoint + 3 !== frameI - 2) {
  14964. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  14965. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  14966. foundKeyFrame = true;
  14967. }
  14968. } // drop trailing zeroes
  14969. do {
  14970. frameI++;
  14971. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  14972. frameSyncPoint = frameI - 2;
  14973. frameI += 3;
  14974. break;
  14975. case 1:
  14976. // skip past non-sync sequences
  14977. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  14978. frameI += 3;
  14979. break;
  14980. }
  14981. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  14982. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  14983. foundKeyFrame = true;
  14984. }
  14985. frameSyncPoint = frameI - 2;
  14986. frameI += 3;
  14987. break;
  14988. default:
  14989. // the current byte isn't a one or zero, so it cannot be part
  14990. // of a sync sequence
  14991. frameI += 3;
  14992. break;
  14993. }
  14994. }
  14995. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  14996. frameI -= frameSyncPoint;
  14997. frameSyncPoint = 0; // parse the final nal
  14998. if (frameBuffer && frameBuffer.byteLength > 3) {
  14999. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  15000. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  15001. foundKeyFrame = true;
  15002. }
  15003. }
  15004. return foundKeyFrame;
  15005. };
  15006. var probe$1 = {
  15007. parseType: parseType,
  15008. parsePat: parsePat,
  15009. parsePmt: parsePmt,
  15010. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  15011. parsePesType: parsePesType,
  15012. parsePesTime: parsePesTime,
  15013. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  15014. };
  15015. /**
  15016. * mux.js
  15017. *
  15018. * Copyright (c) Brightcove
  15019. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  15020. *
  15021. * Parse mpeg2 transport stream packets to extract basic timing information
  15022. */
  15023. var StreamTypes = streamTypes;
  15024. var handleRollover = timestampRolloverStream.handleRollover;
  15025. var probe = {};
  15026. probe.ts = probe$1;
  15027. probe.aac = utils;
  15028. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  15029. var MP2T_PACKET_LENGTH = 188,
  15030. // bytes
  15031. SYNC_BYTE = 0x47;
  15032. /**
  15033. * walks through segment data looking for pat and pmt packets to parse out
  15034. * program map table information
  15035. */
  15036. var parsePsi_ = function (bytes, pmt) {
  15037. var startIndex = 0,
  15038. endIndex = MP2T_PACKET_LENGTH,
  15039. packet,
  15040. type;
  15041. while (endIndex < bytes.byteLength) {
  15042. // Look for a pair of start and end sync bytes in the data..
  15043. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15044. // We found a packet
  15045. packet = bytes.subarray(startIndex, endIndex);
  15046. type = probe.ts.parseType(packet, pmt.pid);
  15047. switch (type) {
  15048. case 'pat':
  15049. pmt.pid = probe.ts.parsePat(packet);
  15050. break;
  15051. case 'pmt':
  15052. var table = probe.ts.parsePmt(packet);
  15053. pmt.table = pmt.table || {};
  15054. Object.keys(table).forEach(function (key) {
  15055. pmt.table[key] = table[key];
  15056. });
  15057. break;
  15058. }
  15059. startIndex += MP2T_PACKET_LENGTH;
  15060. endIndex += MP2T_PACKET_LENGTH;
  15061. continue;
  15062. } // If we get here, we have somehow become de-synchronized and we need to step
  15063. // forward one byte at a time until we find a pair of sync bytes that denote
  15064. // a packet
  15065. startIndex++;
  15066. endIndex++;
  15067. }
  15068. };
  15069. /**
  15070. * walks through the segment data from the start and end to get timing information
  15071. * for the first and last audio pes packets
  15072. */
  15073. var parseAudioPes_ = function (bytes, pmt, result) {
  15074. var startIndex = 0,
  15075. endIndex = MP2T_PACKET_LENGTH,
  15076. packet,
  15077. type,
  15078. pesType,
  15079. pusi,
  15080. parsed;
  15081. var endLoop = false; // Start walking from start of segment to get first audio packet
  15082. while (endIndex <= bytes.byteLength) {
  15083. // Look for a pair of start and end sync bytes in the data..
  15084. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15085. // We found a packet
  15086. packet = bytes.subarray(startIndex, endIndex);
  15087. type = probe.ts.parseType(packet, pmt.pid);
  15088. switch (type) {
  15089. case 'pes':
  15090. pesType = probe.ts.parsePesType(packet, pmt.table);
  15091. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15092. if (pesType === 'audio' && pusi) {
  15093. parsed = probe.ts.parsePesTime(packet);
  15094. if (parsed) {
  15095. parsed.type = 'audio';
  15096. result.audio.push(parsed);
  15097. endLoop = true;
  15098. }
  15099. }
  15100. break;
  15101. }
  15102. if (endLoop) {
  15103. break;
  15104. }
  15105. startIndex += MP2T_PACKET_LENGTH;
  15106. endIndex += MP2T_PACKET_LENGTH;
  15107. continue;
  15108. } // If we get here, we have somehow become de-synchronized and we need to step
  15109. // forward one byte at a time until we find a pair of sync bytes that denote
  15110. // a packet
  15111. startIndex++;
  15112. endIndex++;
  15113. } // Start walking from end of segment to get last audio packet
  15114. endIndex = bytes.byteLength;
  15115. startIndex = endIndex - MP2T_PACKET_LENGTH;
  15116. endLoop = false;
  15117. while (startIndex >= 0) {
  15118. // Look for a pair of start and end sync bytes in the data..
  15119. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15120. // We found a packet
  15121. packet = bytes.subarray(startIndex, endIndex);
  15122. type = probe.ts.parseType(packet, pmt.pid);
  15123. switch (type) {
  15124. case 'pes':
  15125. pesType = probe.ts.parsePesType(packet, pmt.table);
  15126. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15127. if (pesType === 'audio' && pusi) {
  15128. parsed = probe.ts.parsePesTime(packet);
  15129. if (parsed) {
  15130. parsed.type = 'audio';
  15131. result.audio.push(parsed);
  15132. endLoop = true;
  15133. }
  15134. }
  15135. break;
  15136. }
  15137. if (endLoop) {
  15138. break;
  15139. }
  15140. startIndex -= MP2T_PACKET_LENGTH;
  15141. endIndex -= MP2T_PACKET_LENGTH;
  15142. continue;
  15143. } // If we get here, we have somehow become de-synchronized and we need to step
  15144. // forward one byte at a time until we find a pair of sync bytes that denote
  15145. // a packet
  15146. startIndex--;
  15147. endIndex--;
  15148. }
  15149. };
  15150. /**
  15151. * walks through the segment data from the start and end to get timing information
  15152. * for the first and last video pes packets as well as timing information for the first
  15153. * key frame.
  15154. */
  15155. var parseVideoPes_ = function (bytes, pmt, result) {
  15156. var startIndex = 0,
  15157. endIndex = MP2T_PACKET_LENGTH,
  15158. packet,
  15159. type,
  15160. pesType,
  15161. pusi,
  15162. parsed,
  15163. frame,
  15164. i,
  15165. pes;
  15166. var endLoop = false;
  15167. var currentFrame = {
  15168. data: [],
  15169. size: 0
  15170. }; // Start walking from start of segment to get first video packet
  15171. while (endIndex < bytes.byteLength) {
  15172. // Look for a pair of start and end sync bytes in the data..
  15173. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15174. // We found a packet
  15175. packet = bytes.subarray(startIndex, endIndex);
  15176. type = probe.ts.parseType(packet, pmt.pid);
  15177. switch (type) {
  15178. case 'pes':
  15179. pesType = probe.ts.parsePesType(packet, pmt.table);
  15180. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15181. if (pesType === 'video') {
  15182. if (pusi && !endLoop) {
  15183. parsed = probe.ts.parsePesTime(packet);
  15184. if (parsed) {
  15185. parsed.type = 'video';
  15186. result.video.push(parsed);
  15187. endLoop = true;
  15188. }
  15189. }
  15190. if (!result.firstKeyFrame) {
  15191. if (pusi) {
  15192. if (currentFrame.size !== 0) {
  15193. frame = new Uint8Array(currentFrame.size);
  15194. i = 0;
  15195. while (currentFrame.data.length) {
  15196. pes = currentFrame.data.shift();
  15197. frame.set(pes, i);
  15198. i += pes.byteLength;
  15199. }
  15200. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  15201. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  15202. // the keyframe seems to work fine with HLS playback
  15203. // and definitely preferable to a crash with TypeError...
  15204. if (firstKeyFrame) {
  15205. result.firstKeyFrame = firstKeyFrame;
  15206. result.firstKeyFrame.type = 'video';
  15207. } else {
  15208. // eslint-disable-next-line
  15209. 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.');
  15210. }
  15211. }
  15212. currentFrame.size = 0;
  15213. }
  15214. }
  15215. currentFrame.data.push(packet);
  15216. currentFrame.size += packet.byteLength;
  15217. }
  15218. }
  15219. break;
  15220. }
  15221. if (endLoop && result.firstKeyFrame) {
  15222. break;
  15223. }
  15224. startIndex += MP2T_PACKET_LENGTH;
  15225. endIndex += MP2T_PACKET_LENGTH;
  15226. continue;
  15227. } // If we get here, we have somehow become de-synchronized and we need to step
  15228. // forward one byte at a time until we find a pair of sync bytes that denote
  15229. // a packet
  15230. startIndex++;
  15231. endIndex++;
  15232. } // Start walking from end of segment to get last video packet
  15233. endIndex = bytes.byteLength;
  15234. startIndex = endIndex - MP2T_PACKET_LENGTH;
  15235. endLoop = false;
  15236. while (startIndex >= 0) {
  15237. // Look for a pair of start and end sync bytes in the data..
  15238. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15239. // We found a packet
  15240. packet = bytes.subarray(startIndex, endIndex);
  15241. type = probe.ts.parseType(packet, pmt.pid);
  15242. switch (type) {
  15243. case 'pes':
  15244. pesType = probe.ts.parsePesType(packet, pmt.table);
  15245. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15246. if (pesType === 'video' && pusi) {
  15247. parsed = probe.ts.parsePesTime(packet);
  15248. if (parsed) {
  15249. parsed.type = 'video';
  15250. result.video.push(parsed);
  15251. endLoop = true;
  15252. }
  15253. }
  15254. break;
  15255. }
  15256. if (endLoop) {
  15257. break;
  15258. }
  15259. startIndex -= MP2T_PACKET_LENGTH;
  15260. endIndex -= MP2T_PACKET_LENGTH;
  15261. continue;
  15262. } // If we get here, we have somehow become de-synchronized and we need to step
  15263. // forward one byte at a time until we find a pair of sync bytes that denote
  15264. // a packet
  15265. startIndex--;
  15266. endIndex--;
  15267. }
  15268. };
  15269. /**
  15270. * Adjusts the timestamp information for the segment to account for
  15271. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  15272. */
  15273. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  15274. if (segmentInfo.audio && segmentInfo.audio.length) {
  15275. var audioBaseTimestamp = baseTimestamp;
  15276. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  15277. audioBaseTimestamp = segmentInfo.audio[0].dts;
  15278. }
  15279. segmentInfo.audio.forEach(function (info) {
  15280. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  15281. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  15282. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  15283. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  15284. });
  15285. }
  15286. if (segmentInfo.video && segmentInfo.video.length) {
  15287. var videoBaseTimestamp = baseTimestamp;
  15288. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  15289. videoBaseTimestamp = segmentInfo.video[0].dts;
  15290. }
  15291. segmentInfo.video.forEach(function (info) {
  15292. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  15293. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  15294. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  15295. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  15296. });
  15297. if (segmentInfo.firstKeyFrame) {
  15298. var frame = segmentInfo.firstKeyFrame;
  15299. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  15300. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  15301. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  15302. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  15303. }
  15304. }
  15305. };
  15306. /**
  15307. * inspects the aac data stream for start and end time information
  15308. */
  15309. var inspectAac_ = function (bytes) {
  15310. var endLoop = false,
  15311. audioCount = 0,
  15312. sampleRate = null,
  15313. timestamp = null,
  15314. frameSize = 0,
  15315. byteIndex = 0,
  15316. packet;
  15317. while (bytes.length - byteIndex >= 3) {
  15318. var type = probe.aac.parseType(bytes, byteIndex);
  15319. switch (type) {
  15320. case 'timed-metadata':
  15321. // Exit early because we don't have enough to parse
  15322. // the ID3 tag header
  15323. if (bytes.length - byteIndex < 10) {
  15324. endLoop = true;
  15325. break;
  15326. }
  15327. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  15328. // to emit a full packet
  15329. if (frameSize > bytes.length) {
  15330. endLoop = true;
  15331. break;
  15332. }
  15333. if (timestamp === null) {
  15334. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  15335. timestamp = probe.aac.parseAacTimestamp(packet);
  15336. }
  15337. byteIndex += frameSize;
  15338. break;
  15339. case 'audio':
  15340. // Exit early because we don't have enough to parse
  15341. // the ADTS frame header
  15342. if (bytes.length - byteIndex < 7) {
  15343. endLoop = true;
  15344. break;
  15345. }
  15346. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  15347. // to emit a full packet
  15348. if (frameSize > bytes.length) {
  15349. endLoop = true;
  15350. break;
  15351. }
  15352. if (sampleRate === null) {
  15353. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  15354. sampleRate = probe.aac.parseSampleRate(packet);
  15355. }
  15356. audioCount++;
  15357. byteIndex += frameSize;
  15358. break;
  15359. default:
  15360. byteIndex++;
  15361. break;
  15362. }
  15363. if (endLoop) {
  15364. return null;
  15365. }
  15366. }
  15367. if (sampleRate === null || timestamp === null) {
  15368. return null;
  15369. }
  15370. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  15371. var result = {
  15372. audio: [{
  15373. type: 'audio',
  15374. dts: timestamp,
  15375. pts: timestamp
  15376. }, {
  15377. type: 'audio',
  15378. dts: timestamp + audioCount * 1024 * audioTimescale,
  15379. pts: timestamp + audioCount * 1024 * audioTimescale
  15380. }]
  15381. };
  15382. return result;
  15383. };
  15384. /**
  15385. * inspects the transport stream segment data for start and end time information
  15386. * of the audio and video tracks (when present) as well as the first key frame's
  15387. * start time.
  15388. */
  15389. var inspectTs_ = function (bytes) {
  15390. var pmt = {
  15391. pid: null,
  15392. table: null
  15393. };
  15394. var result = {};
  15395. parsePsi_(bytes, pmt);
  15396. for (var pid in pmt.table) {
  15397. if (pmt.table.hasOwnProperty(pid)) {
  15398. var type = pmt.table[pid];
  15399. switch (type) {
  15400. case StreamTypes.H264_STREAM_TYPE:
  15401. result.video = [];
  15402. parseVideoPes_(bytes, pmt, result);
  15403. if (result.video.length === 0) {
  15404. delete result.video;
  15405. }
  15406. break;
  15407. case StreamTypes.ADTS_STREAM_TYPE:
  15408. result.audio = [];
  15409. parseAudioPes_(bytes, pmt, result);
  15410. if (result.audio.length === 0) {
  15411. delete result.audio;
  15412. }
  15413. break;
  15414. }
  15415. }
  15416. }
  15417. return result;
  15418. };
  15419. /**
  15420. * Inspects segment byte data and returns an object with start and end timing information
  15421. *
  15422. * @param {Uint8Array} bytes The segment byte data
  15423. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  15424. * timestamps for rollover. This value must be in 90khz clock.
  15425. * @return {Object} Object containing start and end frame timing info of segment.
  15426. */
  15427. var inspect = function (bytes, baseTimestamp) {
  15428. var isAacData = probe.aac.isLikelyAacData(bytes);
  15429. var result;
  15430. if (isAacData) {
  15431. result = inspectAac_(bytes);
  15432. } else {
  15433. result = inspectTs_(bytes);
  15434. }
  15435. if (!result || !result.audio && !result.video) {
  15436. return null;
  15437. }
  15438. adjustTimestamp_(result, baseTimestamp);
  15439. return result;
  15440. };
  15441. var tsInspector = {
  15442. inspect: inspect,
  15443. parseAudioPes_: parseAudioPes_
  15444. };
  15445. /* global self */
  15446. /**
  15447. * Re-emits transmuxer events by converting them into messages to the
  15448. * world outside the worker.
  15449. *
  15450. * @param {Object} transmuxer the transmuxer to wire events on
  15451. * @private
  15452. */
  15453. const wireTransmuxerEvents = function (self, transmuxer) {
  15454. transmuxer.on('data', function (segment) {
  15455. // transfer ownership of the underlying ArrayBuffer
  15456. // instead of doing a copy to save memory
  15457. // ArrayBuffers are transferable but generic TypedArrays are not
  15458. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  15459. const initArray = segment.initSegment;
  15460. segment.initSegment = {
  15461. data: initArray.buffer,
  15462. byteOffset: initArray.byteOffset,
  15463. byteLength: initArray.byteLength
  15464. };
  15465. const typedArray = segment.data;
  15466. segment.data = typedArray.buffer;
  15467. self.postMessage({
  15468. action: 'data',
  15469. segment,
  15470. byteOffset: typedArray.byteOffset,
  15471. byteLength: typedArray.byteLength
  15472. }, [segment.data]);
  15473. });
  15474. transmuxer.on('done', function (data) {
  15475. self.postMessage({
  15476. action: 'done'
  15477. });
  15478. });
  15479. transmuxer.on('gopInfo', function (gopInfo) {
  15480. self.postMessage({
  15481. action: 'gopInfo',
  15482. gopInfo
  15483. });
  15484. });
  15485. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  15486. const videoSegmentTimingInfo = {
  15487. start: {
  15488. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  15489. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  15490. },
  15491. end: {
  15492. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  15493. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  15494. },
  15495. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  15496. };
  15497. if (timingInfo.prependedContentDuration) {
  15498. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  15499. }
  15500. self.postMessage({
  15501. action: 'videoSegmentTimingInfo',
  15502. videoSegmentTimingInfo
  15503. });
  15504. });
  15505. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  15506. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  15507. const audioSegmentTimingInfo = {
  15508. start: {
  15509. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  15510. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  15511. },
  15512. end: {
  15513. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  15514. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  15515. },
  15516. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  15517. };
  15518. if (timingInfo.prependedContentDuration) {
  15519. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  15520. }
  15521. self.postMessage({
  15522. action: 'audioSegmentTimingInfo',
  15523. audioSegmentTimingInfo
  15524. });
  15525. });
  15526. transmuxer.on('id3Frame', function (id3Frame) {
  15527. self.postMessage({
  15528. action: 'id3Frame',
  15529. id3Frame
  15530. });
  15531. });
  15532. transmuxer.on('caption', function (caption) {
  15533. self.postMessage({
  15534. action: 'caption',
  15535. caption
  15536. });
  15537. });
  15538. transmuxer.on('trackinfo', function (trackInfo) {
  15539. self.postMessage({
  15540. action: 'trackinfo',
  15541. trackInfo
  15542. });
  15543. });
  15544. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  15545. // convert to video TS since we prioritize video time over audio
  15546. self.postMessage({
  15547. action: 'audioTimingInfo',
  15548. audioTimingInfo: {
  15549. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  15550. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  15551. }
  15552. });
  15553. });
  15554. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  15555. self.postMessage({
  15556. action: 'videoTimingInfo',
  15557. videoTimingInfo: {
  15558. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  15559. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  15560. }
  15561. });
  15562. });
  15563. transmuxer.on('log', function (log) {
  15564. self.postMessage({
  15565. action: 'log',
  15566. log
  15567. });
  15568. });
  15569. };
  15570. /**
  15571. * All incoming messages route through this hash. If no function exists
  15572. * to handle an incoming message, then we ignore the message.
  15573. *
  15574. * @class MessageHandlers
  15575. * @param {Object} options the options to initialize with
  15576. */
  15577. class MessageHandlers {
  15578. constructor(self, options) {
  15579. this.options = options || {};
  15580. this.self = self;
  15581. this.init();
  15582. }
  15583. /**
  15584. * initialize our web worker and wire all the events.
  15585. */
  15586. init() {
  15587. if (this.transmuxer) {
  15588. this.transmuxer.dispose();
  15589. }
  15590. this.transmuxer = new transmuxer.Transmuxer(this.options);
  15591. wireTransmuxerEvents(this.self, this.transmuxer);
  15592. }
  15593. pushMp4Captions(data) {
  15594. if (!this.captionParser) {
  15595. this.captionParser = new captionParser();
  15596. this.captionParser.init();
  15597. }
  15598. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  15599. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  15600. this.self.postMessage({
  15601. action: 'mp4Captions',
  15602. captions: parsed && parsed.captions || [],
  15603. logs: parsed && parsed.logs || [],
  15604. data: segment.buffer
  15605. }, [segment.buffer]);
  15606. }
  15607. probeMp4StartTime({
  15608. timescales,
  15609. data
  15610. }) {
  15611. const startTime = probe$2.startTime(timescales, data);
  15612. this.self.postMessage({
  15613. action: 'probeMp4StartTime',
  15614. startTime,
  15615. data
  15616. }, [data.buffer]);
  15617. }
  15618. probeMp4Tracks({
  15619. data
  15620. }) {
  15621. const tracks = probe$2.tracks(data);
  15622. this.self.postMessage({
  15623. action: 'probeMp4Tracks',
  15624. tracks,
  15625. data
  15626. }, [data.buffer]);
  15627. }
  15628. /**
  15629. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  15630. * internal "media time," as well as whether it contains video and/or audio.
  15631. *
  15632. * @private
  15633. * @param {Uint8Array} bytes - segment bytes
  15634. * @param {number} baseStartTime
  15635. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  15636. * This value should be in seconds, as it's converted to a 90khz clock within the
  15637. * function body.
  15638. * @return {Object} The start time of the current segment in "media time" as well as
  15639. * whether it contains video and/or audio
  15640. */
  15641. probeTs({
  15642. data,
  15643. baseStartTime
  15644. }) {
  15645. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  15646. const timeInfo = tsInspector.inspect(data, tsStartTime);
  15647. let result = null;
  15648. if (timeInfo) {
  15649. result = {
  15650. // each type's time info comes back as an array of 2 times, start and end
  15651. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  15652. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  15653. };
  15654. if (result.hasVideo) {
  15655. result.videoStart = timeInfo.video[0].ptsTime;
  15656. }
  15657. if (result.hasAudio) {
  15658. result.audioStart = timeInfo.audio[0].ptsTime;
  15659. }
  15660. }
  15661. this.self.postMessage({
  15662. action: 'probeTs',
  15663. result,
  15664. data
  15665. }, [data.buffer]);
  15666. }
  15667. clearAllMp4Captions() {
  15668. if (this.captionParser) {
  15669. this.captionParser.clearAllCaptions();
  15670. }
  15671. }
  15672. clearParsedMp4Captions() {
  15673. if (this.captionParser) {
  15674. this.captionParser.clearParsedCaptions();
  15675. }
  15676. }
  15677. /**
  15678. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  15679. * processing.
  15680. *
  15681. * @param {ArrayBuffer} data data to push into the muxer
  15682. */
  15683. push(data) {
  15684. // Cast array buffer to correct type for transmuxer
  15685. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  15686. this.transmuxer.push(segment);
  15687. }
  15688. /**
  15689. * Recreate the transmuxer so that the next segment added via `push`
  15690. * start with a fresh transmuxer.
  15691. */
  15692. reset() {
  15693. this.transmuxer.reset();
  15694. }
  15695. /**
  15696. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  15697. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  15698. * set relative to the first based on the PTS values.
  15699. *
  15700. * @param {Object} data used to set the timestamp offset in the muxer
  15701. */
  15702. setTimestampOffset(data) {
  15703. const timestampOffset = data.timestampOffset || 0;
  15704. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  15705. }
  15706. setAudioAppendStart(data) {
  15707. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  15708. }
  15709. setRemux(data) {
  15710. this.transmuxer.setRemux(data.remux);
  15711. }
  15712. /**
  15713. * Forces the pipeline to finish processing the last segment and emit it's
  15714. * results.
  15715. *
  15716. * @param {Object} data event data, not really used
  15717. */
  15718. flush(data) {
  15719. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  15720. self.postMessage({
  15721. action: 'done',
  15722. type: 'transmuxed'
  15723. });
  15724. }
  15725. endTimeline() {
  15726. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  15727. // timelines
  15728. self.postMessage({
  15729. action: 'endedtimeline',
  15730. type: 'transmuxed'
  15731. });
  15732. }
  15733. alignGopsWith(data) {
  15734. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  15735. }
  15736. }
  15737. /**
  15738. * Our web worker interface so that things can talk to mux.js
  15739. * that will be running in a web worker. the scope is passed to this by
  15740. * webworkify.
  15741. *
  15742. * @param {Object} self the scope for the web worker
  15743. */
  15744. self.onmessage = function (event) {
  15745. if (event.data.action === 'init' && event.data.options) {
  15746. this.messageHandlers = new MessageHandlers(self, event.data.options);
  15747. return;
  15748. }
  15749. if (!this.messageHandlers) {
  15750. this.messageHandlers = new MessageHandlers(self);
  15751. }
  15752. if (event.data && event.data.action && event.data.action !== 'init') {
  15753. if (this.messageHandlers[event.data.action]) {
  15754. this.messageHandlers[event.data.action](event.data);
  15755. }
  15756. }
  15757. };
  15758. });
  15759. var TransmuxWorker = factory(workerCode$1);
  15760. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  15761. const handleData_ = (event, transmuxedData, callback) => {
  15762. const {
  15763. type,
  15764. initSegment,
  15765. captions,
  15766. captionStreams,
  15767. metadata,
  15768. videoFrameDtsTime,
  15769. videoFramePtsTime
  15770. } = event.data.segment;
  15771. transmuxedData.buffer.push({
  15772. captions,
  15773. captionStreams,
  15774. metadata
  15775. });
  15776. const boxes = event.data.segment.boxes || {
  15777. data: event.data.segment.data
  15778. };
  15779. const result = {
  15780. type,
  15781. // cast ArrayBuffer to TypedArray
  15782. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  15783. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  15784. };
  15785. if (typeof videoFrameDtsTime !== 'undefined') {
  15786. result.videoFrameDtsTime = videoFrameDtsTime;
  15787. }
  15788. if (typeof videoFramePtsTime !== 'undefined') {
  15789. result.videoFramePtsTime = videoFramePtsTime;
  15790. }
  15791. callback(result);
  15792. };
  15793. const handleDone_ = ({
  15794. transmuxedData,
  15795. callback
  15796. }) => {
  15797. // Previously we only returned data on data events,
  15798. // not on done events. Clear out the buffer to keep that consistent.
  15799. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  15800. // have received
  15801. callback(transmuxedData);
  15802. };
  15803. const handleGopInfo_ = (event, transmuxedData) => {
  15804. transmuxedData.gopInfo = event.data.gopInfo;
  15805. };
  15806. const processTransmux = options => {
  15807. const {
  15808. transmuxer,
  15809. bytes,
  15810. audioAppendStart,
  15811. gopsToAlignWith,
  15812. remux,
  15813. onData,
  15814. onTrackInfo,
  15815. onAudioTimingInfo,
  15816. onVideoTimingInfo,
  15817. onVideoSegmentTimingInfo,
  15818. onAudioSegmentTimingInfo,
  15819. onId3,
  15820. onCaptions,
  15821. onDone,
  15822. onEndedTimeline,
  15823. onTransmuxerLog,
  15824. isEndOfTimeline
  15825. } = options;
  15826. const transmuxedData = {
  15827. buffer: []
  15828. };
  15829. let waitForEndedTimelineEvent = isEndOfTimeline;
  15830. const handleMessage = event => {
  15831. if (transmuxer.currentTransmux !== options) {
  15832. // disposed
  15833. return;
  15834. }
  15835. if (event.data.action === 'data') {
  15836. handleData_(event, transmuxedData, onData);
  15837. }
  15838. if (event.data.action === 'trackinfo') {
  15839. onTrackInfo(event.data.trackInfo);
  15840. }
  15841. if (event.data.action === 'gopInfo') {
  15842. handleGopInfo_(event, transmuxedData);
  15843. }
  15844. if (event.data.action === 'audioTimingInfo') {
  15845. onAudioTimingInfo(event.data.audioTimingInfo);
  15846. }
  15847. if (event.data.action === 'videoTimingInfo') {
  15848. onVideoTimingInfo(event.data.videoTimingInfo);
  15849. }
  15850. if (event.data.action === 'videoSegmentTimingInfo') {
  15851. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  15852. }
  15853. if (event.data.action === 'audioSegmentTimingInfo') {
  15854. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  15855. }
  15856. if (event.data.action === 'id3Frame') {
  15857. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  15858. }
  15859. if (event.data.action === 'caption') {
  15860. onCaptions(event.data.caption);
  15861. }
  15862. if (event.data.action === 'endedtimeline') {
  15863. waitForEndedTimelineEvent = false;
  15864. onEndedTimeline();
  15865. }
  15866. if (event.data.action === 'log') {
  15867. onTransmuxerLog(event.data.log);
  15868. } // wait for the transmuxed event since we may have audio and video
  15869. if (event.data.type !== 'transmuxed') {
  15870. return;
  15871. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  15872. // of a timeline, that means there may still be data events before the segment
  15873. // processing can be considerred complete. In that case, the final event should be
  15874. // an "endedtimeline" event with the type "transmuxed."
  15875. if (waitForEndedTimelineEvent) {
  15876. return;
  15877. }
  15878. transmuxer.onmessage = null;
  15879. handleDone_({
  15880. transmuxedData,
  15881. callback: onDone
  15882. });
  15883. /* eslint-disable no-use-before-define */
  15884. dequeue(transmuxer);
  15885. /* eslint-enable */
  15886. };
  15887. transmuxer.onmessage = handleMessage;
  15888. if (audioAppendStart) {
  15889. transmuxer.postMessage({
  15890. action: 'setAudioAppendStart',
  15891. appendStart: audioAppendStart
  15892. });
  15893. } // allow empty arrays to be passed to clear out GOPs
  15894. if (Array.isArray(gopsToAlignWith)) {
  15895. transmuxer.postMessage({
  15896. action: 'alignGopsWith',
  15897. gopsToAlignWith
  15898. });
  15899. }
  15900. if (typeof remux !== 'undefined') {
  15901. transmuxer.postMessage({
  15902. action: 'setRemux',
  15903. remux
  15904. });
  15905. }
  15906. if (bytes.byteLength) {
  15907. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  15908. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  15909. transmuxer.postMessage({
  15910. action: 'push',
  15911. // Send the typed-array of data as an ArrayBuffer so that
  15912. // it can be sent as a "Transferable" and avoid the costly
  15913. // memory copy
  15914. data: buffer,
  15915. // To recreate the original typed-array, we need information
  15916. // about what portion of the ArrayBuffer it was a view into
  15917. byteOffset,
  15918. byteLength: bytes.byteLength
  15919. }, [buffer]);
  15920. }
  15921. if (isEndOfTimeline) {
  15922. transmuxer.postMessage({
  15923. action: 'endTimeline'
  15924. });
  15925. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  15926. // the end of the segment
  15927. transmuxer.postMessage({
  15928. action: 'flush'
  15929. });
  15930. };
  15931. const dequeue = transmuxer => {
  15932. transmuxer.currentTransmux = null;
  15933. if (transmuxer.transmuxQueue.length) {
  15934. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  15935. if (typeof transmuxer.currentTransmux === 'function') {
  15936. transmuxer.currentTransmux();
  15937. } else {
  15938. processTransmux(transmuxer.currentTransmux);
  15939. }
  15940. }
  15941. };
  15942. const processAction = (transmuxer, action) => {
  15943. transmuxer.postMessage({
  15944. action
  15945. });
  15946. dequeue(transmuxer);
  15947. };
  15948. const enqueueAction = (action, transmuxer) => {
  15949. if (!transmuxer.currentTransmux) {
  15950. transmuxer.currentTransmux = action;
  15951. processAction(transmuxer, action);
  15952. return;
  15953. }
  15954. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  15955. };
  15956. const reset = transmuxer => {
  15957. enqueueAction('reset', transmuxer);
  15958. };
  15959. const endTimeline = transmuxer => {
  15960. enqueueAction('endTimeline', transmuxer);
  15961. };
  15962. const transmux = options => {
  15963. if (!options.transmuxer.currentTransmux) {
  15964. options.transmuxer.currentTransmux = options;
  15965. processTransmux(options);
  15966. return;
  15967. }
  15968. options.transmuxer.transmuxQueue.push(options);
  15969. };
  15970. const createTransmuxer = options => {
  15971. const transmuxer = new TransmuxWorker();
  15972. transmuxer.currentTransmux = null;
  15973. transmuxer.transmuxQueue = [];
  15974. const term = transmuxer.terminate;
  15975. transmuxer.terminate = () => {
  15976. transmuxer.currentTransmux = null;
  15977. transmuxer.transmuxQueue.length = 0;
  15978. return term.call(transmuxer);
  15979. };
  15980. transmuxer.postMessage({
  15981. action: 'init',
  15982. options
  15983. });
  15984. return transmuxer;
  15985. };
  15986. var segmentTransmuxer = {
  15987. reset,
  15988. endTimeline,
  15989. transmux,
  15990. createTransmuxer
  15991. };
  15992. const workerCallback = function (options) {
  15993. const transmuxer = options.transmuxer;
  15994. const endAction = options.endAction || options.action;
  15995. const callback = options.callback;
  15996. const message = _extends({}, options, {
  15997. endAction: null,
  15998. transmuxer: null,
  15999. callback: null
  16000. });
  16001. const listenForEndEvent = event => {
  16002. if (event.data.action !== endAction) {
  16003. return;
  16004. }
  16005. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  16006. if (event.data.data) {
  16007. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  16008. if (options.data) {
  16009. options.data = event.data.data;
  16010. }
  16011. }
  16012. callback(event.data);
  16013. };
  16014. transmuxer.addEventListener('message', listenForEndEvent);
  16015. if (options.data) {
  16016. const isArrayBuffer = options.data instanceof ArrayBuffer;
  16017. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  16018. message.byteLength = options.data.byteLength;
  16019. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  16020. transmuxer.postMessage(message, transfers);
  16021. } else {
  16022. transmuxer.postMessage(message);
  16023. }
  16024. };
  16025. const REQUEST_ERRORS = {
  16026. FAILURE: 2,
  16027. TIMEOUT: -101,
  16028. ABORTED: -102
  16029. };
  16030. /**
  16031. * Abort all requests
  16032. *
  16033. * @param {Object} activeXhrs - an object that tracks all XHR requests
  16034. */
  16035. const abortAll = activeXhrs => {
  16036. activeXhrs.forEach(xhr => {
  16037. xhr.abort();
  16038. });
  16039. };
  16040. /**
  16041. * Gather important bandwidth stats once a request has completed
  16042. *
  16043. * @param {Object} request - the XHR request from which to gather stats
  16044. */
  16045. const getRequestStats = request => {
  16046. return {
  16047. bandwidth: request.bandwidth,
  16048. bytesReceived: request.bytesReceived || 0,
  16049. roundTripTime: request.roundTripTime || 0
  16050. };
  16051. };
  16052. /**
  16053. * If possible gather bandwidth stats as a request is in
  16054. * progress
  16055. *
  16056. * @param {Event} progressEvent - an event object from an XHR's progress event
  16057. */
  16058. const getProgressStats = progressEvent => {
  16059. const request = progressEvent.target;
  16060. const roundTripTime = Date.now() - request.requestTime;
  16061. const stats = {
  16062. bandwidth: Infinity,
  16063. bytesReceived: 0,
  16064. roundTripTime: roundTripTime || 0
  16065. };
  16066. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  16067. // because we should only use bandwidth stats on progress to determine when
  16068. // abort a request early due to insufficient bandwidth
  16069. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  16070. return stats;
  16071. };
  16072. /**
  16073. * Handle all error conditions in one place and return an object
  16074. * with all the information
  16075. *
  16076. * @param {Error|null} error - if non-null signals an error occured with the XHR
  16077. * @param {Object} request - the XHR request that possibly generated the error
  16078. */
  16079. const handleErrors = (error, request) => {
  16080. if (request.timedout) {
  16081. return {
  16082. status: request.status,
  16083. message: 'HLS request timed-out at URL: ' + request.uri,
  16084. code: REQUEST_ERRORS.TIMEOUT,
  16085. xhr: request
  16086. };
  16087. }
  16088. if (request.aborted) {
  16089. return {
  16090. status: request.status,
  16091. message: 'HLS request aborted at URL: ' + request.uri,
  16092. code: REQUEST_ERRORS.ABORTED,
  16093. xhr: request
  16094. };
  16095. }
  16096. if (error) {
  16097. return {
  16098. status: request.status,
  16099. message: 'HLS request errored at URL: ' + request.uri,
  16100. code: REQUEST_ERRORS.FAILURE,
  16101. xhr: request
  16102. };
  16103. }
  16104. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  16105. return {
  16106. status: request.status,
  16107. message: 'Empty HLS response at URL: ' + request.uri,
  16108. code: REQUEST_ERRORS.FAILURE,
  16109. xhr: request
  16110. };
  16111. }
  16112. return null;
  16113. };
  16114. /**
  16115. * Handle responses for key data and convert the key data to the correct format
  16116. * for the decryption step later
  16117. *
  16118. * @param {Object} segment - a simplified copy of the segmentInfo object
  16119. * from SegmentLoader
  16120. * @param {Array} objects - objects to add the key bytes to.
  16121. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16122. * this request
  16123. */
  16124. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  16125. const response = request.response;
  16126. const errorObj = handleErrors(error, request);
  16127. if (errorObj) {
  16128. return finishProcessingFn(errorObj, segment);
  16129. }
  16130. if (response.byteLength !== 16) {
  16131. return finishProcessingFn({
  16132. status: request.status,
  16133. message: 'Invalid HLS key at URL: ' + request.uri,
  16134. code: REQUEST_ERRORS.FAILURE,
  16135. xhr: request
  16136. }, segment);
  16137. }
  16138. const view = new DataView(response);
  16139. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  16140. for (let i = 0; i < objects.length; i++) {
  16141. objects[i].bytes = bytes;
  16142. }
  16143. return finishProcessingFn(null, segment);
  16144. };
  16145. const parseInitSegment = (segment, callback) => {
  16146. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  16147. // only know how to parse mp4 init segments at the moment
  16148. if (type !== 'mp4') {
  16149. const uri = segment.map.resolvedUri || segment.map.uri;
  16150. return callback({
  16151. internal: true,
  16152. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  16153. code: REQUEST_ERRORS.FAILURE
  16154. });
  16155. }
  16156. workerCallback({
  16157. action: 'probeMp4Tracks',
  16158. data: segment.map.bytes,
  16159. transmuxer: segment.transmuxer,
  16160. callback: ({
  16161. tracks,
  16162. data
  16163. }) => {
  16164. // transfer bytes back to us
  16165. segment.map.bytes = data;
  16166. tracks.forEach(function (track) {
  16167. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  16168. if (segment.map.tracks[track.type]) {
  16169. return;
  16170. }
  16171. segment.map.tracks[track.type] = track;
  16172. if (typeof track.id === 'number' && track.timescale) {
  16173. segment.map.timescales = segment.map.timescales || {};
  16174. segment.map.timescales[track.id] = track.timescale;
  16175. }
  16176. });
  16177. return callback(null);
  16178. }
  16179. });
  16180. };
  16181. /**
  16182. * Handle init-segment responses
  16183. *
  16184. * @param {Object} segment - a simplified copy of the segmentInfo object
  16185. * from SegmentLoader
  16186. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16187. * this request
  16188. */
  16189. const handleInitSegmentResponse = ({
  16190. segment,
  16191. finishProcessingFn
  16192. }) => (error, request) => {
  16193. const errorObj = handleErrors(error, request);
  16194. if (errorObj) {
  16195. return finishProcessingFn(errorObj, segment);
  16196. }
  16197. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  16198. // until the key request is done to decrypt.
  16199. if (segment.map.key) {
  16200. segment.map.encryptedBytes = bytes;
  16201. return finishProcessingFn(null, segment);
  16202. }
  16203. segment.map.bytes = bytes;
  16204. parseInitSegment(segment, function (parseError) {
  16205. if (parseError) {
  16206. parseError.xhr = request;
  16207. parseError.status = request.status;
  16208. return finishProcessingFn(parseError, segment);
  16209. }
  16210. finishProcessingFn(null, segment);
  16211. });
  16212. };
  16213. /**
  16214. * Response handler for segment-requests being sure to set the correct
  16215. * property depending on whether the segment is encryped or not
  16216. * Also records and keeps track of stats that are used for ABR purposes
  16217. *
  16218. * @param {Object} segment - a simplified copy of the segmentInfo object
  16219. * from SegmentLoader
  16220. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16221. * this request
  16222. */
  16223. const handleSegmentResponse = ({
  16224. segment,
  16225. finishProcessingFn,
  16226. responseType
  16227. }) => (error, request) => {
  16228. const errorObj = handleErrors(error, request);
  16229. if (errorObj) {
  16230. return finishProcessingFn(errorObj, segment);
  16231. }
  16232. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  16233. // thrown for two primary cases:
  16234. // 1. the mime type override stops working, or is not implemented for a specific
  16235. // browser
  16236. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  16237. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  16238. segment.stats = getRequestStats(request);
  16239. if (segment.key) {
  16240. segment.encryptedBytes = new Uint8Array(newBytes);
  16241. } else {
  16242. segment.bytes = new Uint8Array(newBytes);
  16243. }
  16244. return finishProcessingFn(null, segment);
  16245. };
  16246. const transmuxAndNotify = ({
  16247. segment,
  16248. bytes,
  16249. trackInfoFn,
  16250. timingInfoFn,
  16251. videoSegmentTimingInfoFn,
  16252. audioSegmentTimingInfoFn,
  16253. id3Fn,
  16254. captionsFn,
  16255. isEndOfTimeline,
  16256. endedTimelineFn,
  16257. dataFn,
  16258. doneFn,
  16259. onTransmuxerLog
  16260. }) => {
  16261. const fmp4Tracks = segment.map && segment.map.tracks || {};
  16262. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  16263. // One reason for this is that in the case of full segments, we want to trust start
  16264. // times from the probe, rather than the transmuxer.
  16265. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  16266. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  16267. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  16268. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  16269. const finish = () => transmux({
  16270. bytes,
  16271. transmuxer: segment.transmuxer,
  16272. audioAppendStart: segment.audioAppendStart,
  16273. gopsToAlignWith: segment.gopsToAlignWith,
  16274. remux: isMuxed,
  16275. onData: result => {
  16276. result.type = result.type === 'combined' ? 'video' : result.type;
  16277. dataFn(segment, result);
  16278. },
  16279. onTrackInfo: trackInfo => {
  16280. if (trackInfoFn) {
  16281. if (isMuxed) {
  16282. trackInfo.isMuxed = true;
  16283. }
  16284. trackInfoFn(segment, trackInfo);
  16285. }
  16286. },
  16287. onAudioTimingInfo: audioTimingInfo => {
  16288. // we only want the first start value we encounter
  16289. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  16290. audioStartFn(audioTimingInfo.start);
  16291. audioStartFn = null;
  16292. } // we want to continually update the end time
  16293. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  16294. audioEndFn(audioTimingInfo.end);
  16295. }
  16296. },
  16297. onVideoTimingInfo: videoTimingInfo => {
  16298. // we only want the first start value we encounter
  16299. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  16300. videoStartFn(videoTimingInfo.start);
  16301. videoStartFn = null;
  16302. } // we want to continually update the end time
  16303. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  16304. videoEndFn(videoTimingInfo.end);
  16305. }
  16306. },
  16307. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  16308. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  16309. },
  16310. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  16311. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  16312. },
  16313. onId3: (id3Frames, dispatchType) => {
  16314. id3Fn(segment, id3Frames, dispatchType);
  16315. },
  16316. onCaptions: captions => {
  16317. captionsFn(segment, [captions]);
  16318. },
  16319. isEndOfTimeline,
  16320. onEndedTimeline: () => {
  16321. endedTimelineFn();
  16322. },
  16323. onTransmuxerLog,
  16324. onDone: result => {
  16325. if (!doneFn) {
  16326. return;
  16327. }
  16328. result.type = result.type === 'combined' ? 'video' : result.type;
  16329. doneFn(null, segment, result);
  16330. }
  16331. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  16332. // Meaning cached frame data may corrupt our notion of where this segment
  16333. // really starts. To get around this, probe for the info needed.
  16334. workerCallback({
  16335. action: 'probeTs',
  16336. transmuxer: segment.transmuxer,
  16337. data: bytes,
  16338. baseStartTime: segment.baseStartTime,
  16339. callback: data => {
  16340. segment.bytes = bytes = data.data;
  16341. const probeResult = data.result;
  16342. if (probeResult) {
  16343. trackInfoFn(segment, {
  16344. hasAudio: probeResult.hasAudio,
  16345. hasVideo: probeResult.hasVideo,
  16346. isMuxed
  16347. });
  16348. trackInfoFn = null;
  16349. if (probeResult.hasAudio && !isMuxed) {
  16350. audioStartFn(probeResult.audioStart);
  16351. }
  16352. if (probeResult.hasVideo) {
  16353. videoStartFn(probeResult.videoStart);
  16354. }
  16355. audioStartFn = null;
  16356. videoStartFn = null;
  16357. }
  16358. finish();
  16359. }
  16360. });
  16361. };
  16362. const handleSegmentBytes = ({
  16363. segment,
  16364. bytes,
  16365. trackInfoFn,
  16366. timingInfoFn,
  16367. videoSegmentTimingInfoFn,
  16368. audioSegmentTimingInfoFn,
  16369. id3Fn,
  16370. captionsFn,
  16371. isEndOfTimeline,
  16372. endedTimelineFn,
  16373. dataFn,
  16374. doneFn,
  16375. onTransmuxerLog
  16376. }) => {
  16377. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  16378. // We should have a handler that fetches the number of bytes required
  16379. // to check if something is fmp4. This will allow us to save bandwidth
  16380. // because we can only exclude a playlist and abort requests
  16381. // by codec after trackinfo triggers.
  16382. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  16383. segment.isFmp4 = true;
  16384. const {
  16385. tracks
  16386. } = segment.map;
  16387. const trackInfo = {
  16388. isFmp4: true,
  16389. hasVideo: !!tracks.video,
  16390. hasAudio: !!tracks.audio
  16391. }; // if we have a audio track, with a codec that is not set to
  16392. // encrypted audio
  16393. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  16394. trackInfo.audioCodec = tracks.audio.codec;
  16395. } // if we have a video track, with a codec that is not set to
  16396. // encrypted video
  16397. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  16398. trackInfo.videoCodec = tracks.video.codec;
  16399. }
  16400. if (tracks.video && tracks.audio) {
  16401. trackInfo.isMuxed = true;
  16402. } // since we don't support appending fmp4 data on progress, we know we have the full
  16403. // segment here
  16404. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  16405. // time. The end time can be roughly calculated by the receiver using the duration.
  16406. //
  16407. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  16408. // that is the true start of the segment (where the playback engine should begin
  16409. // decoding).
  16410. const finishLoading = captions => {
  16411. // if the track still has audio at this point it is only possible
  16412. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  16413. // above.
  16414. // we make sure to use segment.bytes here as that
  16415. dataFn(segment, {
  16416. data: bytesAsUint8Array,
  16417. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  16418. });
  16419. if (captions && captions.length) {
  16420. captionsFn(segment, captions);
  16421. }
  16422. doneFn(null, segment, {});
  16423. };
  16424. workerCallback({
  16425. action: 'probeMp4StartTime',
  16426. timescales: segment.map.timescales,
  16427. data: bytesAsUint8Array,
  16428. transmuxer: segment.transmuxer,
  16429. callback: ({
  16430. data,
  16431. startTime
  16432. }) => {
  16433. // transfer bytes back to us
  16434. bytes = data.buffer;
  16435. segment.bytes = bytesAsUint8Array = data;
  16436. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  16437. timingInfoFn(segment, 'audio', 'start', startTime);
  16438. }
  16439. if (trackInfo.hasVideo) {
  16440. timingInfoFn(segment, 'video', 'start', startTime);
  16441. } // Run through the CaptionParser in case there are captions.
  16442. // Initialize CaptionParser if it hasn't been yet
  16443. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  16444. finishLoading();
  16445. return;
  16446. }
  16447. workerCallback({
  16448. action: 'pushMp4Captions',
  16449. endAction: 'mp4Captions',
  16450. transmuxer: segment.transmuxer,
  16451. data: bytesAsUint8Array,
  16452. timescales: segment.map.timescales,
  16453. trackIds: [tracks.video.id],
  16454. callback: message => {
  16455. // transfer bytes back to us
  16456. bytes = message.data.buffer;
  16457. segment.bytes = bytesAsUint8Array = message.data;
  16458. message.logs.forEach(function (log) {
  16459. onTransmuxerLog(merge$1(log, {
  16460. stream: 'mp4CaptionParser'
  16461. }));
  16462. });
  16463. finishLoading(message.captions);
  16464. }
  16465. });
  16466. }
  16467. });
  16468. return;
  16469. } // VTT or other segments that don't need processing
  16470. if (!segment.transmuxer) {
  16471. doneFn(null, segment, {});
  16472. return;
  16473. }
  16474. if (typeof segment.container === 'undefined') {
  16475. segment.container = detectContainerForBytes(bytesAsUint8Array);
  16476. }
  16477. if (segment.container !== 'ts' && segment.container !== 'aac') {
  16478. trackInfoFn(segment, {
  16479. hasAudio: false,
  16480. hasVideo: false
  16481. });
  16482. doneFn(null, segment, {});
  16483. return;
  16484. } // ts or aac
  16485. transmuxAndNotify({
  16486. segment,
  16487. bytes,
  16488. trackInfoFn,
  16489. timingInfoFn,
  16490. videoSegmentTimingInfoFn,
  16491. audioSegmentTimingInfoFn,
  16492. id3Fn,
  16493. captionsFn,
  16494. isEndOfTimeline,
  16495. endedTimelineFn,
  16496. dataFn,
  16497. doneFn,
  16498. onTransmuxerLog
  16499. });
  16500. };
  16501. const decrypt = function ({
  16502. id,
  16503. key,
  16504. encryptedBytes,
  16505. decryptionWorker
  16506. }, callback) {
  16507. const decryptionHandler = event => {
  16508. if (event.data.source === id) {
  16509. decryptionWorker.removeEventListener('message', decryptionHandler);
  16510. const decrypted = event.data.decrypted;
  16511. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  16512. }
  16513. };
  16514. decryptionWorker.addEventListener('message', decryptionHandler);
  16515. let keyBytes;
  16516. if (key.bytes.slice) {
  16517. keyBytes = key.bytes.slice();
  16518. } else {
  16519. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  16520. } // incrementally decrypt the bytes
  16521. decryptionWorker.postMessage(createTransferableMessage({
  16522. source: id,
  16523. encrypted: encryptedBytes,
  16524. key: keyBytes,
  16525. iv: key.iv
  16526. }), [encryptedBytes.buffer, keyBytes.buffer]);
  16527. };
  16528. /**
  16529. * Decrypt the segment via the decryption web worker
  16530. *
  16531. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  16532. * routines
  16533. * @param {Object} segment - a simplified copy of the segmentInfo object
  16534. * from SegmentLoader
  16535. * @param {Function} trackInfoFn - a callback that receives track info
  16536. * @param {Function} timingInfoFn - a callback that receives timing info
  16537. * @param {Function} videoSegmentTimingInfoFn
  16538. * a callback that receives video timing info based on media times and
  16539. * any adjustments made by the transmuxer
  16540. * @param {Function} audioSegmentTimingInfoFn
  16541. * a callback that receives audio timing info based on media times and
  16542. * any adjustments made by the transmuxer
  16543. * @param {boolean} isEndOfTimeline
  16544. * true if this segment represents the last segment in a timeline
  16545. * @param {Function} endedTimelineFn
  16546. * a callback made when a timeline is ended, will only be called if
  16547. * isEndOfTimeline is true
  16548. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16549. * and ready to use
  16550. * @param {Function} doneFn - a callback that is executed after decryption has completed
  16551. */
  16552. const decryptSegment = ({
  16553. decryptionWorker,
  16554. segment,
  16555. trackInfoFn,
  16556. timingInfoFn,
  16557. videoSegmentTimingInfoFn,
  16558. audioSegmentTimingInfoFn,
  16559. id3Fn,
  16560. captionsFn,
  16561. isEndOfTimeline,
  16562. endedTimelineFn,
  16563. dataFn,
  16564. doneFn,
  16565. onTransmuxerLog
  16566. }) => {
  16567. decrypt({
  16568. id: segment.requestId,
  16569. key: segment.key,
  16570. encryptedBytes: segment.encryptedBytes,
  16571. decryptionWorker
  16572. }, decryptedBytes => {
  16573. segment.bytes = decryptedBytes;
  16574. handleSegmentBytes({
  16575. segment,
  16576. bytes: segment.bytes,
  16577. trackInfoFn,
  16578. timingInfoFn,
  16579. videoSegmentTimingInfoFn,
  16580. audioSegmentTimingInfoFn,
  16581. id3Fn,
  16582. captionsFn,
  16583. isEndOfTimeline,
  16584. endedTimelineFn,
  16585. dataFn,
  16586. doneFn,
  16587. onTransmuxerLog
  16588. });
  16589. });
  16590. };
  16591. /**
  16592. * This function waits for all XHRs to finish (with either success or failure)
  16593. * before continueing processing via it's callback. The function gathers errors
  16594. * from each request into a single errors array so that the error status for
  16595. * each request can be examined later.
  16596. *
  16597. * @param {Object} activeXhrs - an object that tracks all XHR requests
  16598. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  16599. * routines
  16600. * @param {Function} trackInfoFn - a callback that receives track info
  16601. * @param {Function} timingInfoFn - a callback that receives timing info
  16602. * @param {Function} videoSegmentTimingInfoFn
  16603. * a callback that receives video timing info based on media times and
  16604. * any adjustments made by the transmuxer
  16605. * @param {Function} audioSegmentTimingInfoFn
  16606. * a callback that receives audio timing info based on media times and
  16607. * any adjustments made by the transmuxer
  16608. * @param {Function} id3Fn - a callback that receives ID3 metadata
  16609. * @param {Function} captionsFn - a callback that receives captions
  16610. * @param {boolean} isEndOfTimeline
  16611. * true if this segment represents the last segment in a timeline
  16612. * @param {Function} endedTimelineFn
  16613. * a callback made when a timeline is ended, will only be called if
  16614. * isEndOfTimeline is true
  16615. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16616. * and ready to use
  16617. * @param {Function} doneFn - a callback that is executed after all resources have been
  16618. * downloaded and any decryption completed
  16619. */
  16620. const waitForCompletion = ({
  16621. activeXhrs,
  16622. decryptionWorker,
  16623. trackInfoFn,
  16624. timingInfoFn,
  16625. videoSegmentTimingInfoFn,
  16626. audioSegmentTimingInfoFn,
  16627. id3Fn,
  16628. captionsFn,
  16629. isEndOfTimeline,
  16630. endedTimelineFn,
  16631. dataFn,
  16632. doneFn,
  16633. onTransmuxerLog
  16634. }) => {
  16635. let count = 0;
  16636. let didError = false;
  16637. return (error, segment) => {
  16638. if (didError) {
  16639. return;
  16640. }
  16641. if (error) {
  16642. didError = true; // If there are errors, we have to abort any outstanding requests
  16643. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  16644. // handle the aborted events from those requests, there are some cases where we may
  16645. // never get an aborted event. For instance, if the network connection is lost and
  16646. // there were two requests, the first may have triggered an error immediately, while
  16647. // the second request remains unsent. In that case, the aborted algorithm will not
  16648. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  16649. //
  16650. // We also can't rely on the ready state of the XHR, since the request that
  16651. // triggered the connection error may also show as a ready state of 0 (unsent).
  16652. // Therefore, we have to finish this group of requests immediately after the first
  16653. // seen error.
  16654. return doneFn(error, segment);
  16655. }
  16656. count += 1;
  16657. if (count === activeXhrs.length) {
  16658. const segmentFinish = function () {
  16659. if (segment.encryptedBytes) {
  16660. return decryptSegment({
  16661. decryptionWorker,
  16662. segment,
  16663. trackInfoFn,
  16664. timingInfoFn,
  16665. videoSegmentTimingInfoFn,
  16666. audioSegmentTimingInfoFn,
  16667. id3Fn,
  16668. captionsFn,
  16669. isEndOfTimeline,
  16670. endedTimelineFn,
  16671. dataFn,
  16672. doneFn,
  16673. onTransmuxerLog
  16674. });
  16675. } // Otherwise, everything is ready just continue
  16676. handleSegmentBytes({
  16677. segment,
  16678. bytes: segment.bytes,
  16679. trackInfoFn,
  16680. timingInfoFn,
  16681. videoSegmentTimingInfoFn,
  16682. audioSegmentTimingInfoFn,
  16683. id3Fn,
  16684. captionsFn,
  16685. isEndOfTimeline,
  16686. endedTimelineFn,
  16687. dataFn,
  16688. doneFn,
  16689. onTransmuxerLog
  16690. });
  16691. }; // Keep track of when *all* of the requests have completed
  16692. segment.endOfAllRequests = Date.now();
  16693. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  16694. return decrypt({
  16695. decryptionWorker,
  16696. // add -init to the "id" to differentiate between segment
  16697. // and init segment decryption, just in case they happen
  16698. // at the same time at some point in the future.
  16699. id: segment.requestId + '-init',
  16700. encryptedBytes: segment.map.encryptedBytes,
  16701. key: segment.map.key
  16702. }, decryptedBytes => {
  16703. segment.map.bytes = decryptedBytes;
  16704. parseInitSegment(segment, parseError => {
  16705. if (parseError) {
  16706. abortAll(activeXhrs);
  16707. return doneFn(parseError, segment);
  16708. }
  16709. segmentFinish();
  16710. });
  16711. });
  16712. }
  16713. segmentFinish();
  16714. }
  16715. };
  16716. };
  16717. /**
  16718. * Calls the abort callback if any request within the batch was aborted. Will only call
  16719. * the callback once per batch of requests, even if multiple were aborted.
  16720. *
  16721. * @param {Object} loadendState - state to check to see if the abort function was called
  16722. * @param {Function} abortFn - callback to call for abort
  16723. */
  16724. const handleLoadEnd = ({
  16725. loadendState,
  16726. abortFn
  16727. }) => event => {
  16728. const request = event.target;
  16729. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  16730. abortFn();
  16731. loadendState.calledAbortFn = true;
  16732. }
  16733. };
  16734. /**
  16735. * Simple progress event callback handler that gathers some stats before
  16736. * executing a provided callback with the `segment` object
  16737. *
  16738. * @param {Object} segment - a simplified copy of the segmentInfo object
  16739. * from SegmentLoader
  16740. * @param {Function} progressFn - a callback that is executed each time a progress event
  16741. * is received
  16742. * @param {Function} trackInfoFn - a callback that receives track info
  16743. * @param {Function} timingInfoFn - a callback that receives timing info
  16744. * @param {Function} videoSegmentTimingInfoFn
  16745. * a callback that receives video timing info based on media times and
  16746. * any adjustments made by the transmuxer
  16747. * @param {Function} audioSegmentTimingInfoFn
  16748. * a callback that receives audio timing info based on media times and
  16749. * any adjustments made by the transmuxer
  16750. * @param {boolean} isEndOfTimeline
  16751. * true if this segment represents the last segment in a timeline
  16752. * @param {Function} endedTimelineFn
  16753. * a callback made when a timeline is ended, will only be called if
  16754. * isEndOfTimeline is true
  16755. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  16756. * and ready to use
  16757. * @param {Event} event - the progress event object from XMLHttpRequest
  16758. */
  16759. const handleProgress = ({
  16760. segment,
  16761. progressFn,
  16762. trackInfoFn,
  16763. timingInfoFn,
  16764. videoSegmentTimingInfoFn,
  16765. audioSegmentTimingInfoFn,
  16766. id3Fn,
  16767. captionsFn,
  16768. isEndOfTimeline,
  16769. endedTimelineFn,
  16770. dataFn
  16771. }) => event => {
  16772. const request = event.target;
  16773. if (request.aborted) {
  16774. return;
  16775. }
  16776. segment.stats = merge$1(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  16777. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  16778. segment.stats.firstBytesReceivedAt = Date.now();
  16779. }
  16780. return progressFn(event, segment);
  16781. };
  16782. /**
  16783. * Load all resources and does any processing necessary for a media-segment
  16784. *
  16785. * Features:
  16786. * decrypts the media-segment if it has a key uri and an iv
  16787. * aborts *all* requests if *any* one request fails
  16788. *
  16789. * The segment object, at minimum, has the following format:
  16790. * {
  16791. * resolvedUri: String,
  16792. * [transmuxer]: Object,
  16793. * [byterange]: {
  16794. * offset: Number,
  16795. * length: Number
  16796. * },
  16797. * [key]: {
  16798. * resolvedUri: String
  16799. * [byterange]: {
  16800. * offset: Number,
  16801. * length: Number
  16802. * },
  16803. * iv: {
  16804. * bytes: Uint32Array
  16805. * }
  16806. * },
  16807. * [map]: {
  16808. * resolvedUri: String,
  16809. * [byterange]: {
  16810. * offset: Number,
  16811. * length: Number
  16812. * },
  16813. * [bytes]: Uint8Array
  16814. * }
  16815. * }
  16816. * ...where [name] denotes optional properties
  16817. *
  16818. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  16819. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  16820. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  16821. * decryption routines
  16822. * @param {Object} segment - a simplified copy of the segmentInfo object
  16823. * from SegmentLoader
  16824. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  16825. * aborted
  16826. * @param {Function} progressFn - a callback that receives progress events from the main
  16827. * segment's xhr request
  16828. * @param {Function} trackInfoFn - a callback that receives track info
  16829. * @param {Function} timingInfoFn - a callback that receives timing info
  16830. * @param {Function} videoSegmentTimingInfoFn
  16831. * a callback that receives video timing info based on media times and
  16832. * any adjustments made by the transmuxer
  16833. * @param {Function} audioSegmentTimingInfoFn
  16834. * a callback that receives audio timing info based on media times and
  16835. * any adjustments made by the transmuxer
  16836. * @param {Function} id3Fn - a callback that receives ID3 metadata
  16837. * @param {Function} captionsFn - a callback that receives captions
  16838. * @param {boolean} isEndOfTimeline
  16839. * true if this segment represents the last segment in a timeline
  16840. * @param {Function} endedTimelineFn
  16841. * a callback made when a timeline is ended, will only be called if
  16842. * isEndOfTimeline is true
  16843. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  16844. * request, transmuxed if needed
  16845. * @param {Function} doneFn - a callback that is executed only once all requests have
  16846. * succeeded or failed
  16847. * @return {Function} a function that, when invoked, immediately aborts all
  16848. * outstanding requests
  16849. */
  16850. const mediaSegmentRequest = ({
  16851. xhr,
  16852. xhrOptions,
  16853. decryptionWorker,
  16854. segment,
  16855. abortFn,
  16856. progressFn,
  16857. trackInfoFn,
  16858. timingInfoFn,
  16859. videoSegmentTimingInfoFn,
  16860. audioSegmentTimingInfoFn,
  16861. id3Fn,
  16862. captionsFn,
  16863. isEndOfTimeline,
  16864. endedTimelineFn,
  16865. dataFn,
  16866. doneFn,
  16867. onTransmuxerLog
  16868. }) => {
  16869. const activeXhrs = [];
  16870. const finishProcessingFn = waitForCompletion({
  16871. activeXhrs,
  16872. decryptionWorker,
  16873. trackInfoFn,
  16874. timingInfoFn,
  16875. videoSegmentTimingInfoFn,
  16876. audioSegmentTimingInfoFn,
  16877. id3Fn,
  16878. captionsFn,
  16879. isEndOfTimeline,
  16880. endedTimelineFn,
  16881. dataFn,
  16882. doneFn,
  16883. onTransmuxerLog
  16884. }); // optionally, request the decryption key
  16885. if (segment.key && !segment.key.bytes) {
  16886. const objects = [segment.key];
  16887. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  16888. objects.push(segment.map.key);
  16889. }
  16890. const keyRequestOptions = merge$1(xhrOptions, {
  16891. uri: segment.key.resolvedUri,
  16892. responseType: 'arraybuffer'
  16893. });
  16894. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  16895. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  16896. activeXhrs.push(keyXhr);
  16897. } // optionally, request the associated media init segment
  16898. if (segment.map && !segment.map.bytes) {
  16899. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  16900. if (differentMapKey) {
  16901. const mapKeyRequestOptions = merge$1(xhrOptions, {
  16902. uri: segment.map.key.resolvedUri,
  16903. responseType: 'arraybuffer'
  16904. });
  16905. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  16906. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  16907. activeXhrs.push(mapKeyXhr);
  16908. }
  16909. const initSegmentOptions = merge$1(xhrOptions, {
  16910. uri: segment.map.resolvedUri,
  16911. responseType: 'arraybuffer',
  16912. headers: segmentXhrHeaders(segment.map)
  16913. });
  16914. const initSegmentRequestCallback = handleInitSegmentResponse({
  16915. segment,
  16916. finishProcessingFn
  16917. });
  16918. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  16919. activeXhrs.push(initSegmentXhr);
  16920. }
  16921. const segmentRequestOptions = merge$1(xhrOptions, {
  16922. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  16923. responseType: 'arraybuffer',
  16924. headers: segmentXhrHeaders(segment)
  16925. });
  16926. const segmentRequestCallback = handleSegmentResponse({
  16927. segment,
  16928. finishProcessingFn,
  16929. responseType: segmentRequestOptions.responseType
  16930. });
  16931. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  16932. segmentXhr.addEventListener('progress', handleProgress({
  16933. segment,
  16934. progressFn,
  16935. trackInfoFn,
  16936. timingInfoFn,
  16937. videoSegmentTimingInfoFn,
  16938. audioSegmentTimingInfoFn,
  16939. id3Fn,
  16940. captionsFn,
  16941. isEndOfTimeline,
  16942. endedTimelineFn,
  16943. dataFn
  16944. }));
  16945. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  16946. // multiple times, provide a shared state object
  16947. const loadendState = {};
  16948. activeXhrs.forEach(activeXhr => {
  16949. activeXhr.addEventListener('loadend', handleLoadEnd({
  16950. loadendState,
  16951. abortFn
  16952. }));
  16953. });
  16954. return () => abortAll(activeXhrs);
  16955. };
  16956. /**
  16957. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  16958. * codec strings, or translating codec strings into objects that can be examined.
  16959. */
  16960. const logFn$1 = logger('CodecUtils');
  16961. /**
  16962. * Returns a set of codec strings parsed from the playlist or the default
  16963. * codec strings if no codecs were specified in the playlist
  16964. *
  16965. * @param {Playlist} media the current media playlist
  16966. * @return {Object} an object with the video and audio codecs
  16967. */
  16968. const getCodecs = function (media) {
  16969. // if the codecs were explicitly specified, use them instead of the
  16970. // defaults
  16971. const mediaAttributes = media.attributes || {};
  16972. if (mediaAttributes.CODECS) {
  16973. return parseCodecs(mediaAttributes.CODECS);
  16974. }
  16975. };
  16976. const isMaat = (main, media) => {
  16977. const mediaAttributes = media.attributes || {};
  16978. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  16979. };
  16980. const isMuxed = (main, media) => {
  16981. if (!isMaat(main, media)) {
  16982. return true;
  16983. }
  16984. const mediaAttributes = media.attributes || {};
  16985. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  16986. for (const groupId in audioGroup) {
  16987. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  16988. // or there are listed playlists (the case for DASH, as the manifest will have already
  16989. // provided all of the details necessary to generate the audio playlist, as opposed to
  16990. // HLS' externally requested playlists), then the content is demuxed.
  16991. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  16992. return true;
  16993. }
  16994. }
  16995. return false;
  16996. };
  16997. const unwrapCodecList = function (codecList) {
  16998. const codecs = {};
  16999. codecList.forEach(({
  17000. mediaType,
  17001. type,
  17002. details
  17003. }) => {
  17004. codecs[mediaType] = codecs[mediaType] || [];
  17005. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  17006. });
  17007. Object.keys(codecs).forEach(function (mediaType) {
  17008. if (codecs[mediaType].length > 1) {
  17009. 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.`);
  17010. codecs[mediaType] = null;
  17011. return;
  17012. }
  17013. codecs[mediaType] = codecs[mediaType][0];
  17014. });
  17015. return codecs;
  17016. };
  17017. const codecCount = function (codecObj) {
  17018. let count = 0;
  17019. if (codecObj.audio) {
  17020. count++;
  17021. }
  17022. if (codecObj.video) {
  17023. count++;
  17024. }
  17025. return count;
  17026. };
  17027. /**
  17028. * Calculates the codec strings for a working configuration of
  17029. * SourceBuffers to play variant streams in a main playlist. If
  17030. * there is no possible working configuration, an empty object will be
  17031. * returned.
  17032. *
  17033. * @param main {Object} the m3u8 object for the main playlist
  17034. * @param media {Object} the m3u8 object for the variant playlist
  17035. * @return {Object} the codec strings.
  17036. *
  17037. * @private
  17038. */
  17039. const codecsForPlaylist = function (main, media) {
  17040. const mediaAttributes = media.attributes || {};
  17041. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  17042. // Put another way, there is no way to have a video-only multiple-audio HLS!
  17043. if (isMaat(main, media) && !codecInfo.audio) {
  17044. if (!isMuxed(main, media)) {
  17045. // It is possible for codecs to be specified on the audio media group playlist but
  17046. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  17047. // video are always separate (and separately specified).
  17048. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  17049. if (defaultCodecs.audio) {
  17050. codecInfo.audio = defaultCodecs.audio;
  17051. }
  17052. }
  17053. }
  17054. return codecInfo;
  17055. };
  17056. const logFn = logger('PlaylistSelector');
  17057. const representationToString = function (representation) {
  17058. if (!representation || !representation.playlist) {
  17059. return;
  17060. }
  17061. const playlist = representation.playlist;
  17062. return JSON.stringify({
  17063. id: playlist.id,
  17064. bandwidth: representation.bandwidth,
  17065. width: representation.width,
  17066. height: representation.height,
  17067. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  17068. });
  17069. }; // Utilities
  17070. /**
  17071. * Returns the CSS value for the specified property on an element
  17072. * using `getComputedStyle`. Firefox has a long-standing issue where
  17073. * getComputedStyle() may return null when running in an iframe with
  17074. * `display: none`.
  17075. *
  17076. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  17077. * @param {HTMLElement} el the htmlelement to work on
  17078. * @param {string} the proprety to get the style for
  17079. */
  17080. const safeGetComputedStyle = function (el, property) {
  17081. if (!el) {
  17082. return '';
  17083. }
  17084. const result = window.getComputedStyle(el);
  17085. if (!result) {
  17086. return '';
  17087. }
  17088. return result[property];
  17089. };
  17090. /**
  17091. * Resuable stable sort function
  17092. *
  17093. * @param {Playlists} array
  17094. * @param {Function} sortFn Different comparators
  17095. * @function stableSort
  17096. */
  17097. const stableSort = function (array, sortFn) {
  17098. const newArray = array.slice();
  17099. array.sort(function (left, right) {
  17100. const cmp = sortFn(left, right);
  17101. if (cmp === 0) {
  17102. return newArray.indexOf(left) - newArray.indexOf(right);
  17103. }
  17104. return cmp;
  17105. });
  17106. };
  17107. /**
  17108. * A comparator function to sort two playlist object by bandwidth.
  17109. *
  17110. * @param {Object} left a media playlist object
  17111. * @param {Object} right a media playlist object
  17112. * @return {number} Greater than zero if the bandwidth attribute of
  17113. * left is greater than the corresponding attribute of right. Less
  17114. * than zero if the bandwidth of right is greater than left and
  17115. * exactly zero if the two are equal.
  17116. */
  17117. const comparePlaylistBandwidth = function (left, right) {
  17118. let leftBandwidth;
  17119. let rightBandwidth;
  17120. if (left.attributes.BANDWIDTH) {
  17121. leftBandwidth = left.attributes.BANDWIDTH;
  17122. }
  17123. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  17124. if (right.attributes.BANDWIDTH) {
  17125. rightBandwidth = right.attributes.BANDWIDTH;
  17126. }
  17127. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  17128. return leftBandwidth - rightBandwidth;
  17129. };
  17130. /**
  17131. * A comparator function to sort two playlist object by resolution (width).
  17132. *
  17133. * @param {Object} left a media playlist object
  17134. * @param {Object} right a media playlist object
  17135. * @return {number} Greater than zero if the resolution.width attribute of
  17136. * left is greater than the corresponding attribute of right. Less
  17137. * than zero if the resolution.width of right is greater than left and
  17138. * exactly zero if the two are equal.
  17139. */
  17140. const comparePlaylistResolution = function (left, right) {
  17141. let leftWidth;
  17142. let rightWidth;
  17143. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  17144. leftWidth = left.attributes.RESOLUTION.width;
  17145. }
  17146. leftWidth = leftWidth || window.Number.MAX_VALUE;
  17147. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  17148. rightWidth = right.attributes.RESOLUTION.width;
  17149. }
  17150. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  17151. // have the same media dimensions/ resolution
  17152. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  17153. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  17154. }
  17155. return leftWidth - rightWidth;
  17156. };
  17157. /**
  17158. * Chooses the appropriate media playlist based on bandwidth and player size
  17159. *
  17160. * @param {Object} main
  17161. * Object representation of the main manifest
  17162. * @param {number} playerBandwidth
  17163. * Current calculated bandwidth of the player
  17164. * @param {number} playerWidth
  17165. * Current width of the player element (should account for the device pixel ratio)
  17166. * @param {number} playerHeight
  17167. * Current height of the player element (should account for the device pixel ratio)
  17168. * @param {boolean} limitRenditionByPlayerDimensions
  17169. * True if the player width and height should be used during the selection, false otherwise
  17170. * @param {Object} playlistController
  17171. * the current playlistController object
  17172. * @return {Playlist} the highest bitrate playlist less than the
  17173. * currently detected bandwidth, accounting for some amount of
  17174. * bandwidth variance
  17175. */
  17176. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  17177. // If we end up getting called before `main` is available, exit early
  17178. if (!main) {
  17179. return;
  17180. }
  17181. const options = {
  17182. bandwidth: playerBandwidth,
  17183. width: playerWidth,
  17184. height: playerHeight,
  17185. limitRenditionByPlayerDimensions
  17186. };
  17187. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  17188. if (Playlist.isAudioOnly(main)) {
  17189. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  17190. // at the buttom of this function for debugging.
  17191. options.audioOnly = true;
  17192. } // convert the playlists to an intermediary representation to make comparisons easier
  17193. let sortedPlaylistReps = playlists.map(playlist => {
  17194. let bandwidth;
  17195. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  17196. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  17197. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  17198. bandwidth = bandwidth || window.Number.MAX_VALUE;
  17199. return {
  17200. bandwidth,
  17201. width,
  17202. height,
  17203. playlist
  17204. };
  17205. });
  17206. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  17207. // incompatible configurations
  17208. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  17209. // api or excluded temporarily due to playback errors.
  17210. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  17211. if (!enabledPlaylistReps.length) {
  17212. // if there are no enabled playlists, then they have all been excluded or disabled
  17213. // by the user through the representations api. In this case, ignore exclusion and
  17214. // fallback to what the user wants by using playlists the user has not disabled.
  17215. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  17216. } // filter out any variant that has greater effective bitrate
  17217. // than the current estimated bandwidth
  17218. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  17219. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  17220. // and then taking the very first element
  17221. 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.
  17222. if (limitRenditionByPlayerDimensions === false) {
  17223. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  17224. if (chosenRep && chosenRep.playlist) {
  17225. let type = 'sortedPlaylistReps';
  17226. if (bandwidthBestRep) {
  17227. type = 'bandwidthBestRep';
  17228. }
  17229. if (enabledPlaylistReps[0]) {
  17230. type = 'enabledPlaylistReps';
  17231. }
  17232. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  17233. return chosenRep.playlist;
  17234. }
  17235. logFn('could not choose a playlist with options', options);
  17236. return null;
  17237. } // filter out playlists without resolution information
  17238. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  17239. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  17240. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  17241. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  17242. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  17243. let resolutionPlusOneList;
  17244. let resolutionPlusOneSmallest;
  17245. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  17246. // if there is no match of exact resolution
  17247. if (!resolutionBestRep) {
  17248. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  17249. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  17250. // is just-larger-than the video player
  17251. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  17252. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  17253. }
  17254. let leastPixelDiffRep; // If this selector proves to be better than others,
  17255. // resolutionPlusOneRep and resolutionBestRep and all
  17256. // the code involving them should be removed.
  17257. if (playlistController.leastPixelDiffSelector) {
  17258. // find the variant that is closest to the player's pixel size
  17259. const leastPixelDiffList = haveResolution.map(rep => {
  17260. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  17261. return rep;
  17262. }); // get the highest bandwidth, closest resolution playlist
  17263. stableSort(leastPixelDiffList, (left, right) => {
  17264. // sort by highest bandwidth if pixelDiff is the same
  17265. if (left.pixelDiff === right.pixelDiff) {
  17266. return right.bandwidth - left.bandwidth;
  17267. }
  17268. return left.pixelDiff - right.pixelDiff;
  17269. });
  17270. leastPixelDiffRep = leastPixelDiffList[0];
  17271. } // fallback chain of variants
  17272. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  17273. if (chosenRep && chosenRep.playlist) {
  17274. let type = 'sortedPlaylistReps';
  17275. if (leastPixelDiffRep) {
  17276. type = 'leastPixelDiffRep';
  17277. } else if (resolutionPlusOneRep) {
  17278. type = 'resolutionPlusOneRep';
  17279. } else if (resolutionBestRep) {
  17280. type = 'resolutionBestRep';
  17281. } else if (bandwidthBestRep) {
  17282. type = 'bandwidthBestRep';
  17283. } else if (enabledPlaylistReps[0]) {
  17284. type = 'enabledPlaylistReps';
  17285. }
  17286. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  17287. return chosenRep.playlist;
  17288. }
  17289. logFn('could not choose a playlist with options', options);
  17290. return null;
  17291. };
  17292. /**
  17293. * Chooses the appropriate media playlist based on the most recent
  17294. * bandwidth estimate and the player size.
  17295. *
  17296. * Expects to be called within the context of an instance of VhsHandler
  17297. *
  17298. * @return {Playlist} the highest bitrate playlist less than the
  17299. * currently detected bandwidth, accounting for some amount of
  17300. * bandwidth variance
  17301. */
  17302. const lastBandwidthSelector = function () {
  17303. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  17304. 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_);
  17305. };
  17306. /**
  17307. * Chooses the appropriate media playlist based on an
  17308. * exponential-weighted moving average of the bandwidth after
  17309. * filtering for player size.
  17310. *
  17311. * Expects to be called within the context of an instance of VhsHandler
  17312. *
  17313. * @param {number} decay - a number between 0 and 1. Higher values of
  17314. * this parameter will cause previous bandwidth estimates to lose
  17315. * significance more quickly.
  17316. * @return {Function} a function which can be invoked to create a new
  17317. * playlist selector function.
  17318. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  17319. */
  17320. const movingAverageBandwidthSelector = function (decay) {
  17321. let average = -1;
  17322. let lastSystemBandwidth = -1;
  17323. if (decay < 0 || decay > 1) {
  17324. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  17325. }
  17326. return function () {
  17327. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  17328. if (average < 0) {
  17329. average = this.systemBandwidth;
  17330. lastSystemBandwidth = this.systemBandwidth;
  17331. } // stop the average value from decaying for every 250ms
  17332. // when the systemBandwidth is constant
  17333. // and
  17334. // stop average from setting to a very low value when the
  17335. // systemBandwidth becomes 0 in case of chunk cancellation
  17336. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  17337. average = decay * this.systemBandwidth + (1 - decay) * average;
  17338. lastSystemBandwidth = this.systemBandwidth;
  17339. }
  17340. 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_);
  17341. };
  17342. };
  17343. /**
  17344. * Chooses the appropriate media playlist based on the potential to rebuffer
  17345. *
  17346. * @param {Object} settings
  17347. * Object of information required to use this selector
  17348. * @param {Object} settings.main
  17349. * Object representation of the main manifest
  17350. * @param {number} settings.currentTime
  17351. * The current time of the player
  17352. * @param {number} settings.bandwidth
  17353. * Current measured bandwidth
  17354. * @param {number} settings.duration
  17355. * Duration of the media
  17356. * @param {number} settings.segmentDuration
  17357. * Segment duration to be used in round trip time calculations
  17358. * @param {number} settings.timeUntilRebuffer
  17359. * Time left in seconds until the player has to rebuffer
  17360. * @param {number} settings.currentTimeline
  17361. * The current timeline segments are being loaded from
  17362. * @param {SyncController} settings.syncController
  17363. * SyncController for determining if we have a sync point for a given playlist
  17364. * @return {Object|null}
  17365. * {Object} return.playlist
  17366. * The highest bandwidth playlist with the least amount of rebuffering
  17367. * {Number} return.rebufferingImpact
  17368. * The amount of time in seconds switching to this playlist will rebuffer. A
  17369. * negative value means that switching will cause zero rebuffering.
  17370. */
  17371. const minRebufferMaxBandwidthSelector = function (settings) {
  17372. const {
  17373. main,
  17374. currentTime,
  17375. bandwidth,
  17376. duration,
  17377. segmentDuration,
  17378. timeUntilRebuffer,
  17379. currentTimeline,
  17380. syncController
  17381. } = settings; // filter out any playlists that have been excluded due to
  17382. // incompatible configurations
  17383. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  17384. // api or excluded temporarily due to playback errors.
  17385. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  17386. if (!enabledPlaylists.length) {
  17387. // if there are no enabled playlists, then they have all been excluded or disabled
  17388. // by the user through the representations api. In this case, ignore exclusion and
  17389. // fallback to what the user wants by using playlists the user has not disabled.
  17390. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  17391. }
  17392. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  17393. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  17394. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  17395. // sync request first. This will double the request time
  17396. const numRequests = syncPoint ? 1 : 2;
  17397. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  17398. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  17399. return {
  17400. playlist,
  17401. rebufferingImpact
  17402. };
  17403. });
  17404. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  17405. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  17406. if (noRebufferingPlaylists.length) {
  17407. return noRebufferingPlaylists[0];
  17408. }
  17409. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  17410. return rebufferingEstimates[0] || null;
  17411. };
  17412. /**
  17413. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  17414. * one with video. If no renditions with video exist, return the lowest audio rendition.
  17415. *
  17416. * Expects to be called within the context of an instance of VhsHandler
  17417. *
  17418. * @return {Object|null}
  17419. * {Object} return.playlist
  17420. * The lowest bitrate playlist that contains a video codec. If no such rendition
  17421. * exists pick the lowest audio rendition.
  17422. */
  17423. const lowestBitrateCompatibleVariantSelector = function () {
  17424. // filter out any playlists that have been excluded due to
  17425. // incompatible configurations or playback errors
  17426. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  17427. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  17428. // (this is not necessarily true, although it is generally true).
  17429. //
  17430. // If an entire manifest has no valid videos everything will get filtered
  17431. // out.
  17432. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  17433. return playlistsWithVideo[0] || null;
  17434. };
  17435. /**
  17436. * Combine all segments into a single Uint8Array
  17437. *
  17438. * @param {Object} segmentObj
  17439. * @return {Uint8Array} concatenated bytes
  17440. * @private
  17441. */
  17442. const concatSegments = segmentObj => {
  17443. let offset = 0;
  17444. let tempBuffer;
  17445. if (segmentObj.bytes) {
  17446. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  17447. segmentObj.segments.forEach(segment => {
  17448. tempBuffer.set(segment, offset);
  17449. offset += segment.byteLength;
  17450. });
  17451. }
  17452. return tempBuffer;
  17453. };
  17454. /**
  17455. * @file text-tracks.js
  17456. */
  17457. /**
  17458. * Create captions text tracks on video.js if they do not exist
  17459. *
  17460. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  17461. * @param {Object} tech the video.js tech
  17462. * @param {Object} captionStream the caption stream to create
  17463. * @private
  17464. */
  17465. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  17466. if (!inbandTextTracks[captionStream]) {
  17467. tech.trigger({
  17468. type: 'usage',
  17469. name: 'vhs-608'
  17470. });
  17471. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  17472. if (/^cc708_/.test(captionStream)) {
  17473. instreamId = 'SERVICE' + captionStream.split('_')[1];
  17474. }
  17475. const track = tech.textTracks().getTrackById(instreamId);
  17476. if (track) {
  17477. // Resuse an existing track with a CC# id because this was
  17478. // very likely created by videojs-contrib-hls from information
  17479. // in the m3u8 for us to use
  17480. inbandTextTracks[captionStream] = track;
  17481. } else {
  17482. // This section gets called when we have caption services that aren't specified in the manifest.
  17483. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  17484. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  17485. let label = captionStream;
  17486. let language = captionStream;
  17487. let def = false;
  17488. const captionService = captionServices[instreamId];
  17489. if (captionService) {
  17490. label = captionService.label;
  17491. language = captionService.language;
  17492. def = captionService.default;
  17493. } // Otherwise, create a track with the default `CC#` label and
  17494. // without a language
  17495. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  17496. kind: 'captions',
  17497. id: instreamId,
  17498. // TODO: investigate why this doesn't seem to turn the caption on by default
  17499. default: def,
  17500. label,
  17501. language
  17502. }, false).track;
  17503. }
  17504. }
  17505. };
  17506. /**
  17507. * Add caption text track data to a source handler given an array of captions
  17508. *
  17509. * @param {Object}
  17510. * @param {Object} inbandTextTracks the inband text tracks
  17511. * @param {number} timestampOffset the timestamp offset of the source buffer
  17512. * @param {Array} captionArray an array of caption data
  17513. * @private
  17514. */
  17515. const addCaptionData = function ({
  17516. inbandTextTracks,
  17517. captionArray,
  17518. timestampOffset
  17519. }) {
  17520. if (!captionArray) {
  17521. return;
  17522. }
  17523. const Cue = window.WebKitDataCue || window.VTTCue;
  17524. captionArray.forEach(caption => {
  17525. const track = caption.stream;
  17526. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  17527. });
  17528. };
  17529. /**
  17530. * Define properties on a cue for backwards compatability,
  17531. * but warn the user that the way that they are using it
  17532. * is depricated and will be removed at a later date.
  17533. *
  17534. * @param {Cue} cue the cue to add the properties on
  17535. * @private
  17536. */
  17537. const deprecateOldCue = function (cue) {
  17538. Object.defineProperties(cue.frame, {
  17539. id: {
  17540. get() {
  17541. videojs__default["default"].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  17542. return cue.value.key;
  17543. }
  17544. },
  17545. value: {
  17546. get() {
  17547. videojs__default["default"].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  17548. return cue.value.data;
  17549. }
  17550. },
  17551. privateData: {
  17552. get() {
  17553. videojs__default["default"].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  17554. return cue.value.data;
  17555. }
  17556. }
  17557. });
  17558. };
  17559. /**
  17560. * Add metadata text track data to a source handler given an array of metadata
  17561. *
  17562. * @param {Object}
  17563. * @param {Object} inbandTextTracks the inband text tracks
  17564. * @param {Array} metadataArray an array of meta data
  17565. * @param {number} timestampOffset the timestamp offset of the source buffer
  17566. * @param {number} videoDuration the duration of the video
  17567. * @private
  17568. */
  17569. const addMetadata = ({
  17570. inbandTextTracks,
  17571. metadataArray,
  17572. timestampOffset,
  17573. videoDuration
  17574. }) => {
  17575. if (!metadataArray) {
  17576. return;
  17577. }
  17578. const Cue = window.WebKitDataCue || window.VTTCue;
  17579. const metadataTrack = inbandTextTracks.metadataTrack_;
  17580. if (!metadataTrack) {
  17581. return;
  17582. }
  17583. metadataArray.forEach(metadata => {
  17584. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  17585. // ignore this bit of metadata.
  17586. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  17587. // which is the "Title/Songname/Content description" frame
  17588. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  17589. return;
  17590. }
  17591. metadata.frames.forEach(frame => {
  17592. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  17593. cue.frame = frame;
  17594. cue.value = frame;
  17595. deprecateOldCue(cue);
  17596. metadataTrack.addCue(cue);
  17597. });
  17598. });
  17599. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  17600. return;
  17601. } // Updating the metadeta cues so that
  17602. // the endTime of each cue is the startTime of the next cue
  17603. // the endTime of last cue is the duration of the video
  17604. const cues = metadataTrack.cues;
  17605. const cuesArray = []; // Create a copy of the TextTrackCueList...
  17606. // ...disregarding cues with a falsey value
  17607. for (let i = 0; i < cues.length; i++) {
  17608. if (cues[i]) {
  17609. cuesArray.push(cues[i]);
  17610. }
  17611. } // Group cues by their startTime value
  17612. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  17613. const timeSlot = obj[cue.startTime] || [];
  17614. timeSlot.push(cue);
  17615. obj[cue.startTime] = timeSlot;
  17616. return obj;
  17617. }, {}); // Sort startTimes by ascending order
  17618. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  17619. sortedStartTimes.forEach((startTime, idx) => {
  17620. const cueGroup = cuesGroupedByStartTime[startTime];
  17621. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  17622. cueGroup.forEach(cue => {
  17623. cue.endTime = nextTime;
  17624. });
  17625. });
  17626. };
  17627. /**
  17628. * Create metadata text track on video.js if it does not exist
  17629. *
  17630. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  17631. * @param {string} dispatchType the inband metadata track dispatch type
  17632. * @param {Object} tech the video.js tech
  17633. * @private
  17634. */
  17635. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  17636. if (inbandTextTracks.metadataTrack_) {
  17637. return;
  17638. }
  17639. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  17640. kind: 'metadata',
  17641. label: 'Timed Metadata'
  17642. }, false).track;
  17643. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  17644. };
  17645. /**
  17646. * Remove cues from a track on video.js.
  17647. *
  17648. * @param {Double} start start of where we should remove the cue
  17649. * @param {Double} end end of where the we should remove the cue
  17650. * @param {Object} track the text track to remove the cues from
  17651. * @private
  17652. */
  17653. const removeCuesFromTrack = function (start, end, track) {
  17654. let i;
  17655. let cue;
  17656. if (!track) {
  17657. return;
  17658. }
  17659. if (!track.cues) {
  17660. return;
  17661. }
  17662. i = track.cues.length;
  17663. while (i--) {
  17664. cue = track.cues[i]; // Remove any cue within the provided start and end time
  17665. if (cue.startTime >= start && cue.endTime <= end) {
  17666. track.removeCue(cue);
  17667. }
  17668. }
  17669. };
  17670. /**
  17671. * Remove duplicate cues from a track on video.js (a cue is considered a
  17672. * duplicate if it has the same time interval and text as another)
  17673. *
  17674. * @param {Object} track the text track to remove the duplicate cues from
  17675. * @private
  17676. */
  17677. const removeDuplicateCuesFromTrack = function (track) {
  17678. const cues = track.cues;
  17679. if (!cues) {
  17680. return;
  17681. }
  17682. for (let i = 0; i < cues.length; i++) {
  17683. const duplicates = [];
  17684. let occurrences = 0;
  17685. for (let j = 0; j < cues.length; j++) {
  17686. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  17687. occurrences++;
  17688. if (occurrences > 1) {
  17689. duplicates.push(cues[j]);
  17690. }
  17691. }
  17692. }
  17693. if (duplicates.length) {
  17694. duplicates.forEach(dupe => track.removeCue(dupe));
  17695. }
  17696. }
  17697. };
  17698. /**
  17699. * mux.js
  17700. *
  17701. * Copyright (c) Brightcove
  17702. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  17703. */
  17704. var ONE_SECOND_IN_TS = 90000,
  17705. // 90kHz clock
  17706. secondsToVideoTs,
  17707. secondsToAudioTs,
  17708. videoTsToSeconds,
  17709. audioTsToSeconds,
  17710. audioTsToVideoTs,
  17711. videoTsToAudioTs,
  17712. metadataTsToSeconds;
  17713. secondsToVideoTs = function (seconds) {
  17714. return seconds * ONE_SECOND_IN_TS;
  17715. };
  17716. secondsToAudioTs = function (seconds, sampleRate) {
  17717. return seconds * sampleRate;
  17718. };
  17719. videoTsToSeconds = function (timestamp) {
  17720. return timestamp / ONE_SECOND_IN_TS;
  17721. };
  17722. audioTsToSeconds = function (timestamp, sampleRate) {
  17723. return timestamp / sampleRate;
  17724. };
  17725. audioTsToVideoTs = function (timestamp, sampleRate) {
  17726. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  17727. };
  17728. videoTsToAudioTs = function (timestamp, sampleRate) {
  17729. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  17730. };
  17731. /**
  17732. * Adjust ID3 tag or caption timing information by the timeline pts values
  17733. * (if keepOriginalTimestamps is false) and convert to seconds
  17734. */
  17735. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  17736. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  17737. };
  17738. var clock = {
  17739. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  17740. secondsToVideoTs: secondsToVideoTs,
  17741. secondsToAudioTs: secondsToAudioTs,
  17742. videoTsToSeconds: videoTsToSeconds,
  17743. audioTsToSeconds: audioTsToSeconds,
  17744. audioTsToVideoTs: audioTsToVideoTs,
  17745. videoTsToAudioTs: videoTsToAudioTs,
  17746. metadataTsToSeconds: metadataTsToSeconds
  17747. };
  17748. /**
  17749. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  17750. * front of current time.
  17751. *
  17752. * @param {Array} buffer
  17753. * The current buffer of gop information
  17754. * @param {number} currentTime
  17755. * The current time
  17756. * @param {Double} mapping
  17757. * Offset to map display time to stream presentation time
  17758. * @return {Array}
  17759. * List of gops considered safe to append over
  17760. */
  17761. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  17762. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  17763. return [];
  17764. } // pts value for current time + 3 seconds to give a bit more wiggle room
  17765. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  17766. let i;
  17767. for (i = 0; i < buffer.length; i++) {
  17768. if (buffer[i].pts > currentTimePts) {
  17769. break;
  17770. }
  17771. }
  17772. return buffer.slice(i);
  17773. };
  17774. /**
  17775. * Appends gop information (timing and byteLength) received by the transmuxer for the
  17776. * gops appended in the last call to appendBuffer
  17777. *
  17778. * @param {Array} buffer
  17779. * The current buffer of gop information
  17780. * @param {Array} gops
  17781. * List of new gop information
  17782. * @param {boolean} replace
  17783. * If true, replace the buffer with the new gop information. If false, append the
  17784. * new gop information to the buffer in the right location of time.
  17785. * @return {Array}
  17786. * Updated list of gop information
  17787. */
  17788. const updateGopBuffer = (buffer, gops, replace) => {
  17789. if (!gops.length) {
  17790. return buffer;
  17791. }
  17792. if (replace) {
  17793. // If we are in safe append mode, then completely overwrite the gop buffer
  17794. // with the most recent appeneded data. This will make sure that when appending
  17795. // future segments, we only try to align with gops that are both ahead of current
  17796. // time and in the last segment appended.
  17797. return gops.slice();
  17798. }
  17799. const start = gops[0].pts;
  17800. let i = 0;
  17801. for (i; i < buffer.length; i++) {
  17802. if (buffer[i].pts >= start) {
  17803. break;
  17804. }
  17805. }
  17806. return buffer.slice(0, i).concat(gops);
  17807. };
  17808. /**
  17809. * Removes gop information in buffer that overlaps with provided start and end
  17810. *
  17811. * @param {Array} buffer
  17812. * The current buffer of gop information
  17813. * @param {Double} start
  17814. * position to start the remove at
  17815. * @param {Double} end
  17816. * position to end the remove at
  17817. * @param {Double} mapping
  17818. * Offset to map display time to stream presentation time
  17819. */
  17820. const removeGopBuffer = (buffer, start, end, mapping) => {
  17821. const startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  17822. const endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  17823. const updatedBuffer = buffer.slice();
  17824. let i = buffer.length;
  17825. while (i--) {
  17826. if (buffer[i].pts <= endPts) {
  17827. break;
  17828. }
  17829. }
  17830. if (i === -1) {
  17831. // no removal because end of remove range is before start of buffer
  17832. return updatedBuffer;
  17833. }
  17834. let j = i + 1;
  17835. while (j--) {
  17836. if (buffer[j].pts <= startPts) {
  17837. break;
  17838. }
  17839. } // clamp remove range start to 0 index
  17840. j = Math.max(j, 0);
  17841. updatedBuffer.splice(j, i - j + 1);
  17842. return updatedBuffer;
  17843. };
  17844. const shallowEqual = function (a, b) {
  17845. // if both are undefined
  17846. // or one or the other is undefined
  17847. // they are not equal
  17848. if (!a && !b || !a && b || a && !b) {
  17849. return false;
  17850. } // they are the same object and thus, equal
  17851. if (a === b) {
  17852. return true;
  17853. } // sort keys so we can make sure they have
  17854. // all the same keys later.
  17855. const akeys = Object.keys(a).sort();
  17856. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  17857. if (akeys.length !== bkeys.length) {
  17858. return false;
  17859. }
  17860. for (let i = 0; i < akeys.length; i++) {
  17861. const key = akeys[i]; // different sorted keys, not equal
  17862. if (key !== bkeys[i]) {
  17863. return false;
  17864. } // different values, not equal
  17865. if (a[key] !== b[key]) {
  17866. return false;
  17867. }
  17868. }
  17869. return true;
  17870. };
  17871. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  17872. const QUOTA_EXCEEDED_ERR = 22;
  17873. /**
  17874. * The segment loader has no recourse except to fetch a segment in the
  17875. * current playlist and use the internal timestamps in that segment to
  17876. * generate a syncPoint. This function returns a good candidate index
  17877. * for that process.
  17878. *
  17879. * @param {Array} segments - the segments array from a playlist.
  17880. * @return {number} An index of a segment from the playlist to load
  17881. */
  17882. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  17883. segments = segments || [];
  17884. const timelineSegments = [];
  17885. let time = 0;
  17886. for (let i = 0; i < segments.length; i++) {
  17887. const segment = segments[i];
  17888. if (currentTimeline === segment.timeline) {
  17889. timelineSegments.push(i);
  17890. time += segment.duration;
  17891. if (time > targetTime) {
  17892. return i;
  17893. }
  17894. }
  17895. }
  17896. if (timelineSegments.length === 0) {
  17897. return 0;
  17898. } // default to the last timeline segment
  17899. return timelineSegments[timelineSegments.length - 1];
  17900. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  17901. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  17902. // as a start to prevent any potential issues with removing content too close to the
  17903. // playhead.
  17904. const MIN_BACK_BUFFER = 1; // in ms
  17905. const CHECK_BUFFER_DELAY = 500;
  17906. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  17907. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  17908. // not accurately reflect the rest of the content.
  17909. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  17910. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  17911. // Although these checks should most likely cover non 'main' types, for now it narrows
  17912. // the scope of our checks.
  17913. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  17914. return null;
  17915. }
  17916. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  17917. return 'Neither audio nor video found in segment.';
  17918. }
  17919. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  17920. 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.';
  17921. }
  17922. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  17923. 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.';
  17924. }
  17925. return null;
  17926. };
  17927. /**
  17928. * Calculates a time value that is safe to remove from the back buffer without interrupting
  17929. * playback.
  17930. *
  17931. * @param {TimeRange} seekable
  17932. * The current seekable range
  17933. * @param {number} currentTime
  17934. * The current time of the player
  17935. * @param {number} targetDuration
  17936. * The target duration of the current playlist
  17937. * @return {number}
  17938. * Time that is safe to remove from the back buffer without interrupting playback
  17939. */
  17940. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  17941. // 30 seconds before the playhead provides a safe default for trimming.
  17942. //
  17943. // Choosing a reasonable default is particularly important for high bitrate content and
  17944. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  17945. // throw an APPEND_BUFFER_ERR.
  17946. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  17947. if (seekable.length) {
  17948. // Some live playlists may have a shorter window of content than the full allowed back
  17949. // buffer. For these playlists, don't save content that's no longer within the window.
  17950. trimTime = Math.max(trimTime, seekable.start(0));
  17951. } // Don't remove within target duration of the current time to avoid the possibility of
  17952. // removing the GOP currently being played, as removing it can cause playback stalls.
  17953. const maxTrimTime = currentTime - targetDuration;
  17954. return Math.min(maxTrimTime, trimTime);
  17955. };
  17956. const segmentInfoString = segmentInfo => {
  17957. const {
  17958. startOfSegment,
  17959. duration,
  17960. segment,
  17961. part,
  17962. playlist: {
  17963. mediaSequence: seq,
  17964. id,
  17965. segments = []
  17966. },
  17967. mediaIndex: index,
  17968. partIndex,
  17969. timeline
  17970. } = segmentInfo;
  17971. const segmentLen = segments.length - 1;
  17972. let selection = 'mediaIndex/partIndex increment';
  17973. if (segmentInfo.getMediaInfoForTime) {
  17974. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  17975. } else if (segmentInfo.isSyncRequest) {
  17976. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  17977. }
  17978. if (segmentInfo.independent) {
  17979. selection += ` with independent ${segmentInfo.independent}`;
  17980. }
  17981. const hasPartIndex = typeof partIndex === 'number';
  17982. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  17983. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  17984. preloadSegment: segment
  17985. }) - 1 : 0;
  17986. 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}]`;
  17987. };
  17988. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  17989. /**
  17990. * Returns the timestamp offset to use for the segment.
  17991. *
  17992. * @param {number} segmentTimeline
  17993. * The timeline of the segment
  17994. * @param {number} currentTimeline
  17995. * The timeline currently being followed by the loader
  17996. * @param {number} startOfSegment
  17997. * The estimated segment start
  17998. * @param {TimeRange[]} buffered
  17999. * The loader's buffer
  18000. * @param {boolean} overrideCheck
  18001. * If true, no checks are made to see if the timestamp offset value should be set,
  18002. * but sets it directly to a value.
  18003. *
  18004. * @return {number|null}
  18005. * Either a number representing a new timestamp offset, or null if the segment is
  18006. * part of the same timeline
  18007. */
  18008. const timestampOffsetForSegment = ({
  18009. segmentTimeline,
  18010. currentTimeline,
  18011. startOfSegment,
  18012. buffered,
  18013. overrideCheck
  18014. }) => {
  18015. // Check to see if we are crossing a discontinuity to see if we need to set the
  18016. // timestamp offset on the transmuxer and source buffer.
  18017. //
  18018. // Previously, we changed the timestampOffset if the start of this segment was less than
  18019. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  18020. // behavior, especially around long running live streams.
  18021. if (!overrideCheck && segmentTimeline === currentTimeline) {
  18022. return null;
  18023. } // When changing renditions, it's possible to request a segment on an older timeline. For
  18024. // instance, given two renditions with the following:
  18025. //
  18026. // #EXTINF:10
  18027. // segment1
  18028. // #EXT-X-DISCONTINUITY
  18029. // #EXTINF:10
  18030. // segment2
  18031. // #EXTINF:10
  18032. // segment3
  18033. //
  18034. // And the current player state:
  18035. //
  18036. // current time: 8
  18037. // buffer: 0 => 20
  18038. //
  18039. // The next segment on the current rendition would be segment3, filling the buffer from
  18040. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  18041. // then the next segment to be requested will be segment1 from the new rendition in
  18042. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  18043. // content (since it would position segment1 of the new rendition starting at 20s). This
  18044. // case can be identified when the new segment's timeline is a prior value. Instead of
  18045. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  18046. // more accurate to the actual start time of the segment.
  18047. if (segmentTimeline < currentTimeline) {
  18048. return startOfSegment;
  18049. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  18050. // value uses the end of the last segment if it is available. While this value
  18051. // should often be correct, it's better to rely on the buffered end, as the new
  18052. // content post discontinuity should line up with the buffered end as if it were
  18053. // time 0 for the new content.
  18054. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  18055. };
  18056. /**
  18057. * Returns whether or not the loader should wait for a timeline change from the timeline
  18058. * change controller before processing the segment.
  18059. *
  18060. * Primary timing in VHS goes by video. This is different from most media players, as
  18061. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  18062. * will continue to use video as the primary timing source, due to the current logic and
  18063. * expectations built around it.
  18064. * Since the timing follows video, in order to maintain sync, the video loader is
  18065. * responsible for setting both audio and video source buffer timestamp offsets.
  18066. *
  18067. * Setting different values for audio and video source buffers could lead to
  18068. * desyncing. The following examples demonstrate some of the situations where this
  18069. * distinction is important. Note that all of these cases involve demuxed content. When
  18070. * content is muxed, the audio and video are packaged together, therefore syncing
  18071. * separate media playlists is not an issue.
  18072. *
  18073. * CASE 1: Audio prepares to load a new timeline before video:
  18074. *
  18075. * Timeline: 0 1
  18076. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18077. * Audio Loader: ^
  18078. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18079. * Video Loader ^
  18080. *
  18081. * In the above example, the audio loader is preparing to load the 6th segment, the first
  18082. * after a discontinuity, while the video loader is still loading the 5th segment, before
  18083. * the discontinuity.
  18084. *
  18085. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  18086. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  18087. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  18088. * the audio loader must provide the audioAppendStart value to trim the content in the
  18089. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  18090. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  18091. * segment until that value is provided.
  18092. *
  18093. * CASE 2: Video prepares to load a new timeline before audio:
  18094. *
  18095. * Timeline: 0 1
  18096. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18097. * Audio Loader: ^
  18098. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18099. * Video Loader ^
  18100. *
  18101. * In the above example, the video loader is preparing to load the 6th segment, the first
  18102. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  18103. * the discontinuity.
  18104. *
  18105. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  18106. * segment is loaded and processed, both the video and audio timestamp offsets will be
  18107. * set, since video is used as the primary timing source. This is to ensure content lines
  18108. * up appropriately, as any modifications to the video timing are reflected by audio when
  18109. * the video loader sets the audio and video timestamp offsets to the same value. However,
  18110. * setting the timestamp offset for audio before audio has had a chance to change
  18111. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  18112. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  18113. *
  18114. * CASE 3: When seeking, audio prepares to load a new timeline before video
  18115. *
  18116. * Timeline: 0 1
  18117. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18118. * Audio Loader: ^
  18119. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18120. * Video Loader ^
  18121. *
  18122. * In the above example, both audio and video loaders are loading segments from timeline
  18123. * 0, but imagine that the seek originated from timeline 1.
  18124. *
  18125. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  18126. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  18127. * must wait for the video loader to load its segment and update both the audio and video
  18128. * timestamp offsets before it may load and append its own segment. This is the case
  18129. * whether the seek results in a mismatched segment request (e.g., the audio loader
  18130. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  18131. * loaders choose to load the same segment index from each playlist, as the segments may
  18132. * not be aligned perfectly, even for matching segment indexes.
  18133. *
  18134. * @param {Object} timelinechangeController
  18135. * @param {number} currentTimeline
  18136. * The timeline currently being followed by the loader
  18137. * @param {number} segmentTimeline
  18138. * The timeline of the segment being loaded
  18139. * @param {('main'|'audio')} loaderType
  18140. * The loader type
  18141. * @param {boolean} audioDisabled
  18142. * Whether the audio is disabled for the loader. This should only be true when the
  18143. * loader may have muxed audio in its segment, but should not append it, e.g., for
  18144. * the main loader when an alternate audio playlist is active.
  18145. *
  18146. * @return {boolean}
  18147. * Whether the loader should wait for a timeline change from the timeline change
  18148. * controller before processing the segment
  18149. */
  18150. const shouldWaitForTimelineChange = ({
  18151. timelineChangeController,
  18152. currentTimeline,
  18153. segmentTimeline,
  18154. loaderType,
  18155. audioDisabled
  18156. }) => {
  18157. if (currentTimeline === segmentTimeline) {
  18158. return false;
  18159. }
  18160. if (loaderType === 'audio') {
  18161. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  18162. type: 'main'
  18163. }); // Audio loader should wait if:
  18164. //
  18165. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  18166. // * main hasn't yet changed to the timeline audio is looking to load
  18167. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  18168. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  18169. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  18170. // loader's segments (or the content is audio/video only and handled by the main
  18171. // loader).
  18172. if (loaderType === 'main' && audioDisabled) {
  18173. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  18174. type: 'audio'
  18175. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  18176. // change to the current timeline.
  18177. //
  18178. // Since the main loader is responsible for setting the timestamp offset for both
  18179. // audio and video, the main loader must wait for audio to be about to change to its
  18180. // timeline before setting the offset, otherwise, if audio is behind in loading,
  18181. // segments from the previous timeline would be adjusted by the new timestamp offset.
  18182. //
  18183. // This requirement means that video will not cross a timeline until the audio is
  18184. // about to cross to it, so that way audio and video will always cross the timeline
  18185. // together.
  18186. //
  18187. // In addition to normal timeline changes, these rules also apply to the start of a
  18188. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  18189. // that these rules apply to the first timeline change because if they did not, it's
  18190. // possible that the main loader will cross two timelines before the audio loader has
  18191. // crossed one. Logic may be implemented to handle the startup as a special case, but
  18192. // it's easier to simply treat all timeline changes the same.
  18193. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  18194. return false;
  18195. }
  18196. return true;
  18197. }
  18198. return false;
  18199. };
  18200. const mediaDuration = timingInfos => {
  18201. let maxDuration = 0;
  18202. ['video', 'audio'].forEach(function (type) {
  18203. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  18204. if (!typeTimingInfo) {
  18205. return;
  18206. }
  18207. const {
  18208. start,
  18209. end
  18210. } = typeTimingInfo;
  18211. let duration;
  18212. if (typeof start === 'bigint' || typeof end === 'bigint') {
  18213. duration = window.BigInt(end) - window.BigInt(start);
  18214. } else if (typeof start === 'number' && typeof end === 'number') {
  18215. duration = end - start;
  18216. }
  18217. if (typeof duration !== 'undefined' && duration > maxDuration) {
  18218. maxDuration = duration;
  18219. }
  18220. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  18221. // as we only need BigInt when we are above that.
  18222. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  18223. maxDuration = Number(maxDuration);
  18224. }
  18225. return maxDuration;
  18226. };
  18227. const segmentTooLong = ({
  18228. segmentDuration,
  18229. maxDuration
  18230. }) => {
  18231. // 0 duration segments are most likely due to metadata only segments or a lack of
  18232. // information.
  18233. if (!segmentDuration) {
  18234. return false;
  18235. } // For HLS:
  18236. //
  18237. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  18238. // The EXTINF duration of each Media Segment in the Playlist
  18239. // file, when rounded to the nearest integer, MUST be less than or equal
  18240. // to the target duration; longer segments can trigger playback stalls
  18241. // or other errors.
  18242. //
  18243. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  18244. // duration. Although that reported duration is occasionally approximate (i.e., not
  18245. // exact), a strict check may report that a segment is too long more often in DASH.
  18246. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  18247. };
  18248. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  18249. // Right now we aren't following DASH's timing model exactly, so only perform
  18250. // this check for HLS content.
  18251. if (sourceType !== 'hls') {
  18252. return null;
  18253. }
  18254. const segmentDuration = mediaDuration({
  18255. audioTimingInfo: segmentInfo.audioTimingInfo,
  18256. videoTimingInfo: segmentInfo.videoTimingInfo
  18257. }); // Don't report if we lack information.
  18258. //
  18259. // If the segment has a duration of 0 it is either a lack of information or a
  18260. // metadata only segment and shouldn't be reported here.
  18261. if (!segmentDuration) {
  18262. return null;
  18263. }
  18264. const targetDuration = segmentInfo.playlist.targetDuration;
  18265. const isSegmentWayTooLong = segmentTooLong({
  18266. segmentDuration,
  18267. maxDuration: targetDuration * 2
  18268. });
  18269. const isSegmentSlightlyTooLong = segmentTooLong({
  18270. segmentDuration,
  18271. maxDuration: targetDuration
  18272. });
  18273. 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';
  18274. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  18275. return {
  18276. severity: isSegmentWayTooLong ? 'warn' : 'info',
  18277. message: segmentTooLongMessage
  18278. };
  18279. }
  18280. return null;
  18281. };
  18282. /**
  18283. * An object that manages segment loading and appending.
  18284. *
  18285. * @class SegmentLoader
  18286. * @param {Object} options required and optional options
  18287. * @extends videojs.EventTarget
  18288. */
  18289. class SegmentLoader extends videojs__default["default"].EventTarget {
  18290. constructor(settings, options = {}) {
  18291. super(); // check pre-conditions
  18292. if (!settings) {
  18293. throw new TypeError('Initialization settings are required');
  18294. }
  18295. if (typeof settings.currentTime !== 'function') {
  18296. throw new TypeError('No currentTime getter specified');
  18297. }
  18298. if (!settings.mediaSource) {
  18299. throw new TypeError('No MediaSource specified');
  18300. } // public properties
  18301. this.bandwidth = settings.bandwidth;
  18302. this.throughput = {
  18303. rate: 0,
  18304. count: 0
  18305. };
  18306. this.roundTrip = NaN;
  18307. this.resetStats_();
  18308. this.mediaIndex = null;
  18309. this.partIndex = null; // private settings
  18310. this.hasPlayed_ = settings.hasPlayed;
  18311. this.currentTime_ = settings.currentTime;
  18312. this.seekable_ = settings.seekable;
  18313. this.seeking_ = settings.seeking;
  18314. this.duration_ = settings.duration;
  18315. this.mediaSource_ = settings.mediaSource;
  18316. this.vhs_ = settings.vhs;
  18317. this.loaderType_ = settings.loaderType;
  18318. this.currentMediaInfo_ = void 0;
  18319. this.startingMediaInfo_ = void 0;
  18320. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  18321. this.goalBufferLength_ = settings.goalBufferLength;
  18322. this.sourceType_ = settings.sourceType;
  18323. this.sourceUpdater_ = settings.sourceUpdater;
  18324. this.inbandTextTracks_ = settings.inbandTextTracks;
  18325. this.state_ = 'INIT';
  18326. this.timelineChangeController_ = settings.timelineChangeController;
  18327. this.shouldSaveSegmentTimingInfo_ = true;
  18328. this.parse708captions_ = settings.parse708captions;
  18329. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  18330. this.captionServices_ = settings.captionServices;
  18331. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  18332. this.checkBufferTimeout_ = null;
  18333. this.error_ = void 0;
  18334. this.currentTimeline_ = -1;
  18335. this.pendingSegment_ = null;
  18336. this.xhrOptions_ = null;
  18337. this.pendingSegments_ = [];
  18338. this.audioDisabled_ = false;
  18339. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  18340. this.gopBuffer_ = [];
  18341. this.timeMapping_ = 0;
  18342. this.safeAppend_ = videojs__default["default"].browser.IE_VERSION >= 11;
  18343. this.appendInitSegment_ = {
  18344. audio: true,
  18345. video: true
  18346. };
  18347. this.playlistOfLastInitSegment_ = {
  18348. audio: null,
  18349. video: null
  18350. };
  18351. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  18352. // information yet to start the loading process (e.g., if the audio loader wants to
  18353. // load a segment from the next timeline but the main loader hasn't yet crossed that
  18354. // timeline), then the load call will be added to the queue until it is ready to be
  18355. // processed.
  18356. this.loadQueue_ = [];
  18357. this.metadataQueue_ = {
  18358. id3: [],
  18359. caption: []
  18360. };
  18361. this.waitingOnRemove_ = false;
  18362. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  18363. this.activeInitSegmentId_ = null;
  18364. this.initSegments_ = {}; // HLSe playback
  18365. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  18366. this.keyCache_ = {};
  18367. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  18368. // between a time in the display time and a segment index within
  18369. // a playlist
  18370. this.syncController_ = settings.syncController;
  18371. this.syncPoint_ = {
  18372. segmentIndex: 0,
  18373. time: 0
  18374. };
  18375. this.transmuxer_ = this.createTransmuxer_();
  18376. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  18377. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  18378. this.mediaSource_.addEventListener('sourceopen', () => {
  18379. if (!this.isEndOfStream_()) {
  18380. this.ended_ = false;
  18381. }
  18382. }); // ...for determining the fetch location
  18383. this.fetchAtBuffer_ = false;
  18384. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  18385. Object.defineProperty(this, 'state', {
  18386. get() {
  18387. return this.state_;
  18388. },
  18389. set(newState) {
  18390. if (newState !== this.state_) {
  18391. this.logger_(`${this.state_} -> ${newState}`);
  18392. this.state_ = newState;
  18393. this.trigger('statechange');
  18394. }
  18395. }
  18396. });
  18397. this.sourceUpdater_.on('ready', () => {
  18398. if (this.hasEnoughInfoToAppend_()) {
  18399. this.processCallQueue_();
  18400. }
  18401. }); // Only the main loader needs to listen for pending timeline changes, as the main
  18402. // loader should wait for audio to be ready to change its timeline so that both main
  18403. // and audio timelines change together. For more details, see the
  18404. // shouldWaitForTimelineChange function.
  18405. if (this.loaderType_ === 'main') {
  18406. this.timelineChangeController_.on('pendingtimelinechange', () => {
  18407. if (this.hasEnoughInfoToAppend_()) {
  18408. this.processCallQueue_();
  18409. }
  18410. });
  18411. } // The main loader only listens on pending timeline changes, but the audio loader,
  18412. // since its loads follow main, needs to listen on timeline changes. For more details,
  18413. // see the shouldWaitForTimelineChange function.
  18414. if (this.loaderType_ === 'audio') {
  18415. this.timelineChangeController_.on('timelinechange', () => {
  18416. if (this.hasEnoughInfoToLoad_()) {
  18417. this.processLoadQueue_();
  18418. }
  18419. if (this.hasEnoughInfoToAppend_()) {
  18420. this.processCallQueue_();
  18421. }
  18422. });
  18423. }
  18424. }
  18425. createTransmuxer_() {
  18426. return segmentTransmuxer.createTransmuxer({
  18427. remux: false,
  18428. alignGopsAtEnd: this.safeAppend_,
  18429. keepOriginalTimestamps: true,
  18430. parse708captions: this.parse708captions_,
  18431. captionServices: this.captionServices_
  18432. });
  18433. }
  18434. /**
  18435. * reset all of our media stats
  18436. *
  18437. * @private
  18438. */
  18439. resetStats_() {
  18440. this.mediaBytesTransferred = 0;
  18441. this.mediaRequests = 0;
  18442. this.mediaRequestsAborted = 0;
  18443. this.mediaRequestsTimedout = 0;
  18444. this.mediaRequestsErrored = 0;
  18445. this.mediaTransferDuration = 0;
  18446. this.mediaSecondsLoaded = 0;
  18447. this.mediaAppends = 0;
  18448. }
  18449. /**
  18450. * dispose of the SegmentLoader and reset to the default state
  18451. */
  18452. dispose() {
  18453. this.trigger('dispose');
  18454. this.state = 'DISPOSED';
  18455. this.pause();
  18456. this.abort_();
  18457. if (this.transmuxer_) {
  18458. this.transmuxer_.terminate();
  18459. }
  18460. this.resetStats_();
  18461. if (this.checkBufferTimeout_) {
  18462. window.clearTimeout(this.checkBufferTimeout_);
  18463. }
  18464. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  18465. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  18466. }
  18467. this.off();
  18468. }
  18469. setAudio(enable) {
  18470. this.audioDisabled_ = !enable;
  18471. if (enable) {
  18472. this.appendInitSegment_.audio = true;
  18473. } else {
  18474. // remove current track audio if it gets disabled
  18475. this.sourceUpdater_.removeAudio(0, this.duration_());
  18476. }
  18477. }
  18478. /**
  18479. * abort anything that is currently doing on with the SegmentLoader
  18480. * and reset to a default state
  18481. */
  18482. abort() {
  18483. if (this.state !== 'WAITING') {
  18484. if (this.pendingSegment_) {
  18485. this.pendingSegment_ = null;
  18486. }
  18487. return;
  18488. }
  18489. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  18490. // since we are no longer "waiting" on any requests. XHR callback is not always run
  18491. // when the request is aborted. This will prevent the loader from being stuck in the
  18492. // WAITING state indefinitely.
  18493. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  18494. // next segment
  18495. if (!this.paused()) {
  18496. this.monitorBuffer_();
  18497. }
  18498. }
  18499. /**
  18500. * abort all pending xhr requests and null any pending segements
  18501. *
  18502. * @private
  18503. */
  18504. abort_() {
  18505. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  18506. this.pendingSegment_.abortRequests();
  18507. } // clear out the segment being processed
  18508. this.pendingSegment_ = null;
  18509. this.callQueue_ = [];
  18510. this.loadQueue_ = [];
  18511. this.metadataQueue_.id3 = [];
  18512. this.metadataQueue_.caption = [];
  18513. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  18514. this.waitingOnRemove_ = false;
  18515. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  18516. this.quotaExceededErrorRetryTimeout_ = null;
  18517. }
  18518. checkForAbort_(requestId) {
  18519. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  18520. // callback that happens should reset the state to READY so that loading can continue.
  18521. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  18522. this.state = 'READY';
  18523. return true;
  18524. }
  18525. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  18526. return true;
  18527. }
  18528. return false;
  18529. }
  18530. /**
  18531. * set an error on the segment loader and null out any pending segements
  18532. *
  18533. * @param {Error} error the error to set on the SegmentLoader
  18534. * @return {Error} the error that was set or that is currently set
  18535. */
  18536. error(error) {
  18537. if (typeof error !== 'undefined') {
  18538. this.logger_('error occurred:', error);
  18539. this.error_ = error;
  18540. }
  18541. this.pendingSegment_ = null;
  18542. return this.error_;
  18543. }
  18544. endOfStream() {
  18545. this.ended_ = true;
  18546. if (this.transmuxer_) {
  18547. // need to clear out any cached data to prepare for the new segment
  18548. segmentTransmuxer.reset(this.transmuxer_);
  18549. }
  18550. this.gopBuffer_.length = 0;
  18551. this.pause();
  18552. this.trigger('ended');
  18553. }
  18554. /**
  18555. * Indicates which time ranges are buffered
  18556. *
  18557. * @return {TimeRange}
  18558. * TimeRange object representing the current buffered ranges
  18559. */
  18560. buffered_() {
  18561. const trackInfo = this.getMediaInfo_();
  18562. if (!this.sourceUpdater_ || !trackInfo) {
  18563. return createTimeRanges();
  18564. }
  18565. if (this.loaderType_ === 'main') {
  18566. const {
  18567. hasAudio,
  18568. hasVideo,
  18569. isMuxed
  18570. } = trackInfo;
  18571. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  18572. return this.sourceUpdater_.buffered();
  18573. }
  18574. if (hasVideo) {
  18575. return this.sourceUpdater_.videoBuffered();
  18576. }
  18577. } // One case that can be ignored for now is audio only with alt audio,
  18578. // as we don't yet have proper support for that.
  18579. return this.sourceUpdater_.audioBuffered();
  18580. }
  18581. /**
  18582. * Gets and sets init segment for the provided map
  18583. *
  18584. * @param {Object} map
  18585. * The map object representing the init segment to get or set
  18586. * @param {boolean=} set
  18587. * If true, the init segment for the provided map should be saved
  18588. * @return {Object}
  18589. * map object for desired init segment
  18590. */
  18591. initSegmentForMap(map, set = false) {
  18592. if (!map) {
  18593. return null;
  18594. }
  18595. const id = initSegmentId(map);
  18596. let storedMap = this.initSegments_[id];
  18597. if (set && !storedMap && map.bytes) {
  18598. this.initSegments_[id] = storedMap = {
  18599. resolvedUri: map.resolvedUri,
  18600. byterange: map.byterange,
  18601. bytes: map.bytes,
  18602. tracks: map.tracks,
  18603. timescales: map.timescales
  18604. };
  18605. }
  18606. return storedMap || map;
  18607. }
  18608. /**
  18609. * Gets and sets key for the provided key
  18610. *
  18611. * @param {Object} key
  18612. * The key object representing the key to get or set
  18613. * @param {boolean=} set
  18614. * If true, the key for the provided key should be saved
  18615. * @return {Object}
  18616. * Key object for desired key
  18617. */
  18618. segmentKey(key, set = false) {
  18619. if (!key) {
  18620. return null;
  18621. }
  18622. const id = segmentKeyId(key);
  18623. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  18624. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  18625. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  18626. this.keyCache_[id] = storedKey = {
  18627. resolvedUri: key.resolvedUri,
  18628. bytes: key.bytes
  18629. };
  18630. }
  18631. const result = {
  18632. resolvedUri: (storedKey || key).resolvedUri
  18633. };
  18634. if (storedKey) {
  18635. result.bytes = storedKey.bytes;
  18636. }
  18637. return result;
  18638. }
  18639. /**
  18640. * Returns true if all configuration required for loading is present, otherwise false.
  18641. *
  18642. * @return {boolean} True if the all configuration is ready for loading
  18643. * @private
  18644. */
  18645. couldBeginLoading_() {
  18646. return this.playlist_ && !this.paused();
  18647. }
  18648. /**
  18649. * load a playlist and start to fill the buffer
  18650. */
  18651. load() {
  18652. // un-pause
  18653. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  18654. // specified
  18655. if (!this.playlist_) {
  18656. return;
  18657. } // if all the configuration is ready, initialize and begin loading
  18658. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  18659. return this.init_();
  18660. } // if we're in the middle of processing a segment already, don't
  18661. // kick off an additional segment request
  18662. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  18663. return;
  18664. }
  18665. this.state = 'READY';
  18666. }
  18667. /**
  18668. * Once all the starting parameters have been specified, begin
  18669. * operation. This method should only be invoked from the INIT
  18670. * state.
  18671. *
  18672. * @private
  18673. */
  18674. init_() {
  18675. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  18676. // audio data from the muxed content should be removed
  18677. this.resetEverything();
  18678. return this.monitorBuffer_();
  18679. }
  18680. /**
  18681. * set a playlist on the segment loader
  18682. *
  18683. * @param {PlaylistLoader} media the playlist to set on the segment loader
  18684. */
  18685. playlist(newPlaylist, options = {}) {
  18686. if (!newPlaylist) {
  18687. return;
  18688. }
  18689. const oldPlaylist = this.playlist_;
  18690. const segmentInfo = this.pendingSegment_;
  18691. this.playlist_ = newPlaylist;
  18692. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  18693. // is always our zero-time so force a sync update each time the playlist
  18694. // is refreshed from the server
  18695. //
  18696. // Use the INIT state to determine if playback has started, as the playlist sync info
  18697. // should be fixed once requests begin (as sync points are generated based on sync
  18698. // info), but not before then.
  18699. if (this.state === 'INIT') {
  18700. newPlaylist.syncInfo = {
  18701. mediaSequence: newPlaylist.mediaSequence,
  18702. time: 0
  18703. }; // Setting the date time mapping means mapping the program date time (if available)
  18704. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  18705. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  18706. // be updated as the playlist is refreshed before the loader starts loading, the
  18707. // program date time mapping needs to be updated as well.
  18708. //
  18709. // This mapping is only done for the main loader because a program date time should
  18710. // map equivalently between playlists.
  18711. if (this.loaderType_ === 'main') {
  18712. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  18713. }
  18714. }
  18715. let oldId = null;
  18716. if (oldPlaylist) {
  18717. if (oldPlaylist.id) {
  18718. oldId = oldPlaylist.id;
  18719. } else if (oldPlaylist.uri) {
  18720. oldId = oldPlaylist.uri;
  18721. }
  18722. }
  18723. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  18724. // in LIVE, we always want to update with new playlists (including refreshes)
  18725. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  18726. // buffering now
  18727. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  18728. return this.init_();
  18729. }
  18730. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  18731. if (this.mediaIndex !== null) {
  18732. // we must reset/resync the segment loader when we switch renditions and
  18733. // the segment loader is already synced to the previous rendition
  18734. // on playlist changes we want it to be possible to fetch
  18735. // at the buffer for vod but not for live. So we use resetLoader
  18736. // for live and resyncLoader for vod. We want this because
  18737. // if a playlist uses independent and non-independent segments/parts the
  18738. // buffer may not accurately reflect the next segment that we should try
  18739. // downloading.
  18740. if (!newPlaylist.endList) {
  18741. this.resetLoader();
  18742. } else {
  18743. this.resyncLoader();
  18744. }
  18745. }
  18746. this.currentMediaInfo_ = void 0;
  18747. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  18748. return;
  18749. } // we reloaded the same playlist so we are in a live scenario
  18750. // and we will likely need to adjust the mediaIndex
  18751. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  18752. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  18753. // this is important because we can abort a request and this value must be
  18754. // equal to the last appended mediaIndex
  18755. if (this.mediaIndex !== null) {
  18756. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  18757. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  18758. // new playlist was incremented by 1.
  18759. if (this.mediaIndex < 0) {
  18760. this.mediaIndex = null;
  18761. this.partIndex = null;
  18762. } else {
  18763. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  18764. // unless parts fell off of the playlist for this segment.
  18765. // In that case we need to reset partIndex and resync
  18766. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  18767. const mediaIndex = this.mediaIndex;
  18768. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  18769. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  18770. // as the part was dropped from our current playlists segment.
  18771. // The mediaIndex will still be valid so keep that around.
  18772. this.mediaIndex = mediaIndex;
  18773. }
  18774. }
  18775. } // update the mediaIndex on the SegmentInfo object
  18776. // this is important because we will update this.mediaIndex with this value
  18777. // in `handleAppendsDone_` after the segment has been successfully appended
  18778. if (segmentInfo) {
  18779. segmentInfo.mediaIndex -= mediaSequenceDiff;
  18780. if (segmentInfo.mediaIndex < 0) {
  18781. segmentInfo.mediaIndex = null;
  18782. segmentInfo.partIndex = null;
  18783. } else {
  18784. // we need to update the referenced segment so that timing information is
  18785. // saved for the new playlist's segment, however, if the segment fell off the
  18786. // playlist, we can leave the old reference and just lose the timing info
  18787. if (segmentInfo.mediaIndex >= 0) {
  18788. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  18789. }
  18790. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  18791. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  18792. }
  18793. }
  18794. }
  18795. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  18796. }
  18797. /**
  18798. * Prevent the loader from fetching additional segments. If there
  18799. * is a segment request outstanding, it will finish processing
  18800. * before the loader halts. A segment loader can be unpaused by
  18801. * calling load().
  18802. */
  18803. pause() {
  18804. if (this.checkBufferTimeout_) {
  18805. window.clearTimeout(this.checkBufferTimeout_);
  18806. this.checkBufferTimeout_ = null;
  18807. }
  18808. }
  18809. /**
  18810. * Returns whether the segment loader is fetching additional
  18811. * segments when given the opportunity. This property can be
  18812. * modified through calls to pause() and load().
  18813. */
  18814. paused() {
  18815. return this.checkBufferTimeout_ === null;
  18816. }
  18817. /**
  18818. * Delete all the buffered data and reset the SegmentLoader
  18819. *
  18820. * @param {Function} [done] an optional callback to be executed when the remove
  18821. * operation is complete
  18822. */
  18823. resetEverything(done) {
  18824. this.ended_ = false;
  18825. this.activeInitSegmentId_ = null;
  18826. this.appendInitSegment_ = {
  18827. audio: true,
  18828. video: true
  18829. };
  18830. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  18831. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  18832. // we then clamp the value to duration if necessary.
  18833. this.remove(0, Infinity, done); // clears fmp4 captions
  18834. if (this.transmuxer_) {
  18835. this.transmuxer_.postMessage({
  18836. action: 'clearAllMp4Captions'
  18837. }); // reset the cache in the transmuxer
  18838. this.transmuxer_.postMessage({
  18839. action: 'reset'
  18840. });
  18841. }
  18842. }
  18843. /**
  18844. * Force the SegmentLoader to resync and start loading around the currentTime instead
  18845. * of starting at the end of the buffer
  18846. *
  18847. * Useful for fast quality changes
  18848. */
  18849. resetLoader() {
  18850. this.fetchAtBuffer_ = false;
  18851. this.resyncLoader();
  18852. }
  18853. /**
  18854. * Force the SegmentLoader to restart synchronization and make a conservative guess
  18855. * before returning to the simple walk-forward method
  18856. */
  18857. resyncLoader() {
  18858. if (this.transmuxer_) {
  18859. // need to clear out any cached data to prepare for the new segment
  18860. segmentTransmuxer.reset(this.transmuxer_);
  18861. }
  18862. this.mediaIndex = null;
  18863. this.partIndex = null;
  18864. this.syncPoint_ = null;
  18865. this.isPendingTimestampOffset_ = false;
  18866. this.callQueue_ = [];
  18867. this.loadQueue_ = [];
  18868. this.metadataQueue_.id3 = [];
  18869. this.metadataQueue_.caption = [];
  18870. this.abort();
  18871. if (this.transmuxer_) {
  18872. this.transmuxer_.postMessage({
  18873. action: 'clearParsedMp4Captions'
  18874. });
  18875. }
  18876. }
  18877. /**
  18878. * Remove any data in the source buffer between start and end times
  18879. *
  18880. * @param {number} start - the start time of the region to remove from the buffer
  18881. * @param {number} end - the end time of the region to remove from the buffer
  18882. * @param {Function} [done] - an optional callback to be executed when the remove
  18883. * @param {boolean} force - force all remove operations to happen
  18884. * operation is complete
  18885. */
  18886. remove(start, end, done = () => {}, force = false) {
  18887. // clamp end to duration if we need to remove everything.
  18888. // This is due to a browser bug that causes issues if we remove to Infinity.
  18889. // videojs/videojs-contrib-hls#1225
  18890. if (end === Infinity) {
  18891. end = this.duration_();
  18892. } // skip removes that would throw an error
  18893. // commonly happens during a rendition switch at the start of a video
  18894. // from start 0 to end 0
  18895. if (end <= start) {
  18896. this.logger_('skipping remove because end ${end} is <= start ${start}');
  18897. return;
  18898. }
  18899. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  18900. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  18901. return;
  18902. } // set it to one to complete this function's removes
  18903. let removesRemaining = 1;
  18904. const removeFinished = () => {
  18905. removesRemaining--;
  18906. if (removesRemaining === 0) {
  18907. done();
  18908. }
  18909. };
  18910. if (force || !this.audioDisabled_) {
  18911. removesRemaining++;
  18912. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  18913. } // While it would be better to only remove video if the main loader has video, this
  18914. // should be safe with audio only as removeVideo will call back even if there's no
  18915. // video buffer.
  18916. //
  18917. // In theory we can check to see if there's video before calling the remove, but in
  18918. // the event that we're switching between renditions and from video to audio only
  18919. // (when we add support for that), we may need to clear the video contents despite
  18920. // what the new media will contain.
  18921. if (force || this.loaderType_ === 'main') {
  18922. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  18923. removesRemaining++;
  18924. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  18925. } // remove any captions and ID3 tags
  18926. for (const track in this.inbandTextTracks_) {
  18927. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  18928. }
  18929. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  18930. removeFinished();
  18931. }
  18932. /**
  18933. * (re-)schedule monitorBufferTick_ to run as soon as possible
  18934. *
  18935. * @private
  18936. */
  18937. monitorBuffer_() {
  18938. if (this.checkBufferTimeout_) {
  18939. window.clearTimeout(this.checkBufferTimeout_);
  18940. }
  18941. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  18942. }
  18943. /**
  18944. * As long as the SegmentLoader is in the READY state, periodically
  18945. * invoke fillBuffer_().
  18946. *
  18947. * @private
  18948. */
  18949. monitorBufferTick_() {
  18950. if (this.state === 'READY') {
  18951. this.fillBuffer_();
  18952. }
  18953. if (this.checkBufferTimeout_) {
  18954. window.clearTimeout(this.checkBufferTimeout_);
  18955. }
  18956. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  18957. }
  18958. /**
  18959. * fill the buffer with segements unless the sourceBuffers are
  18960. * currently updating
  18961. *
  18962. * Note: this function should only ever be called by monitorBuffer_
  18963. * and never directly
  18964. *
  18965. * @private
  18966. */
  18967. fillBuffer_() {
  18968. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  18969. // except when we're ready for the next segment, this check can most likely be removed
  18970. if (this.sourceUpdater_.updating()) {
  18971. return;
  18972. } // see if we need to begin loading immediately
  18973. const segmentInfo = this.chooseNextRequest_();
  18974. if (!segmentInfo) {
  18975. return;
  18976. }
  18977. if (typeof segmentInfo.timestampOffset === 'number') {
  18978. this.isPendingTimestampOffset_ = false;
  18979. this.timelineChangeController_.pendingTimelineChange({
  18980. type: this.loaderType_,
  18981. from: this.currentTimeline_,
  18982. to: segmentInfo.timeline
  18983. });
  18984. }
  18985. this.loadSegment_(segmentInfo);
  18986. }
  18987. /**
  18988. * Determines if we should call endOfStream on the media source based
  18989. * on the state of the buffer or if appened segment was the final
  18990. * segment in the playlist.
  18991. *
  18992. * @param {number} [mediaIndex] the media index of segment we last appended
  18993. * @param {Object} [playlist] a media playlist object
  18994. * @return {boolean} do we need to call endOfStream on the MediaSource
  18995. */
  18996. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  18997. if (!playlist || !this.mediaSource_) {
  18998. return false;
  18999. }
  19000. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  19001. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  19002. 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
  19003. // so that MediaSources can trigger the `ended` event when it runs out of
  19004. // buffered data instead of waiting for me
  19005. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  19006. }
  19007. /**
  19008. * Determines what request should be made given current segment loader state.
  19009. *
  19010. * @return {Object} a request object that describes the segment/part to load
  19011. */
  19012. chooseNextRequest_() {
  19013. const buffered = this.buffered_();
  19014. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  19015. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  19016. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  19017. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  19018. const segments = this.playlist_.segments; // return no segment if:
  19019. // 1. we don't have segments
  19020. // 2. The video has not yet played and we already downloaded a segment
  19021. // 3. we already have enough buffered time
  19022. if (!segments.length || preloaded || haveEnoughBuffer) {
  19023. return null;
  19024. }
  19025. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  19026. const next = {
  19027. partIndex: null,
  19028. mediaIndex: null,
  19029. startOfSegment: null,
  19030. playlist: this.playlist_,
  19031. isSyncRequest: Boolean(!this.syncPoint_)
  19032. };
  19033. if (next.isSyncRequest) {
  19034. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  19035. } else if (this.mediaIndex !== null) {
  19036. const segment = segments[this.mediaIndex];
  19037. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  19038. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  19039. if (segment.parts && segment.parts[partIndex + 1]) {
  19040. next.mediaIndex = this.mediaIndex;
  19041. next.partIndex = partIndex + 1;
  19042. } else {
  19043. next.mediaIndex = this.mediaIndex + 1;
  19044. }
  19045. } else {
  19046. // Find the segment containing the end of the buffer or current time.
  19047. const {
  19048. segmentIndex,
  19049. startTime,
  19050. partIndex
  19051. } = Playlist.getMediaInfoForTime({
  19052. exactManifestTimings: this.exactManifestTimings,
  19053. playlist: this.playlist_,
  19054. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  19055. startingPartIndex: this.syncPoint_.partIndex,
  19056. startingSegmentIndex: this.syncPoint_.segmentIndex,
  19057. startTime: this.syncPoint_.time
  19058. });
  19059. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  19060. next.mediaIndex = segmentIndex;
  19061. next.startOfSegment = startTime;
  19062. next.partIndex = partIndex;
  19063. }
  19064. const nextSegment = segments[next.mediaIndex];
  19065. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  19066. // the next partIndex is invalid do not choose a next segment.
  19067. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  19068. return null;
  19069. } // if the next segment has parts, and we don't have a partIndex.
  19070. // Set partIndex to 0
  19071. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  19072. next.partIndex = 0;
  19073. nextPart = nextSegment.parts[0];
  19074. } // if we have no buffered data then we need to make sure
  19075. // that the next part we append is "independent" if possible.
  19076. // So we check if the previous part is independent, and request
  19077. // it if it is.
  19078. if (!bufferedTime && nextPart && !nextPart.independent) {
  19079. if (next.partIndex === 0) {
  19080. const lastSegment = segments[next.mediaIndex - 1];
  19081. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  19082. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  19083. next.mediaIndex -= 1;
  19084. next.partIndex = lastSegment.parts.length - 1;
  19085. next.independent = 'previous segment';
  19086. }
  19087. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  19088. next.partIndex -= 1;
  19089. next.independent = 'previous part';
  19090. }
  19091. }
  19092. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  19093. // 1. this is the last segment in the playlist
  19094. // 2. end of stream has been called on the media source already
  19095. // 3. the player is not seeking
  19096. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  19097. return null;
  19098. }
  19099. return this.generateSegmentInfo_(next);
  19100. }
  19101. generateSegmentInfo_(options) {
  19102. const {
  19103. independent,
  19104. playlist,
  19105. mediaIndex,
  19106. startOfSegment,
  19107. isSyncRequest,
  19108. partIndex,
  19109. forceTimestampOffset,
  19110. getMediaInfoForTime
  19111. } = options;
  19112. const segment = playlist.segments[mediaIndex];
  19113. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  19114. const segmentInfo = {
  19115. requestId: 'segment-loader-' + Math.random(),
  19116. // resolve the segment URL relative to the playlist
  19117. uri: part && part.resolvedUri || segment.resolvedUri,
  19118. // the segment's mediaIndex at the time it was requested
  19119. mediaIndex,
  19120. partIndex: part ? partIndex : null,
  19121. // whether or not to update the SegmentLoader's state with this
  19122. // segment's mediaIndex
  19123. isSyncRequest,
  19124. startOfSegment,
  19125. // the segment's playlist
  19126. playlist,
  19127. // unencrypted bytes of the segment
  19128. bytes: null,
  19129. // when a key is defined for this segment, the encrypted bytes
  19130. encryptedBytes: null,
  19131. // The target timestampOffset for this segment when we append it
  19132. // to the source buffer
  19133. timestampOffset: null,
  19134. // The timeline that the segment is in
  19135. timeline: segment.timeline,
  19136. // The expected duration of the segment in seconds
  19137. duration: part && part.duration || segment.duration,
  19138. // retain the segment in case the playlist updates while doing an async process
  19139. segment,
  19140. part,
  19141. byteLength: 0,
  19142. transmuxer: this.transmuxer_,
  19143. // type of getMediaInfoForTime that was used to get this segment
  19144. getMediaInfoForTime,
  19145. independent
  19146. };
  19147. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  19148. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  19149. segmentTimeline: segment.timeline,
  19150. currentTimeline: this.currentTimeline_,
  19151. startOfSegment,
  19152. buffered: this.buffered_(),
  19153. overrideCheck
  19154. });
  19155. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  19156. if (typeof audioBufferedEnd === 'number') {
  19157. // since the transmuxer is using the actual timing values, but the buffer is
  19158. // adjusted by the timestamp offset, we must adjust the value here
  19159. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  19160. }
  19161. if (this.sourceUpdater_.videoBuffered().length) {
  19162. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  19163. // adjusted by the timestmap offset, we must adjust the value here
  19164. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  19165. }
  19166. return segmentInfo;
  19167. } // get the timestampoffset for a segment,
  19168. // added so that vtt segment loader can override and prevent
  19169. // adding timestamp offsets.
  19170. timestampOffsetForSegment_(options) {
  19171. return timestampOffsetForSegment(options);
  19172. }
  19173. /**
  19174. * Determines if the network has enough bandwidth to complete the current segment
  19175. * request in a timely manner. If not, the request will be aborted early and bandwidth
  19176. * updated to trigger a playlist switch.
  19177. *
  19178. * @param {Object} stats
  19179. * Object containing stats about the request timing and size
  19180. * @private
  19181. */
  19182. earlyAbortWhenNeeded_(stats) {
  19183. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  19184. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  19185. // the lowestEnabledRendition.
  19186. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  19187. !this.playlist_.attributes.BANDWIDTH) {
  19188. return;
  19189. } // Wait at least 1 second since the first byte of data has been received before
  19190. // using the calculated bandwidth from the progress event to allow the bitrate
  19191. // to stabilize
  19192. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  19193. return;
  19194. }
  19195. const currentTime = this.currentTime_();
  19196. const measuredBandwidth = stats.bandwidth;
  19197. const segmentDuration = this.pendingSegment_.duration;
  19198. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  19199. // if we are only left with less than 1 second when the request completes.
  19200. // A negative timeUntilRebuffering indicates we are already rebuffering
  19201. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  19202. // is larger than the estimated time until the player runs out of forward buffer
  19203. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  19204. return;
  19205. }
  19206. const switchCandidate = minRebufferMaxBandwidthSelector({
  19207. main: this.vhs_.playlists.main,
  19208. currentTime,
  19209. bandwidth: measuredBandwidth,
  19210. duration: this.duration_(),
  19211. segmentDuration,
  19212. timeUntilRebuffer: timeUntilRebuffer$1,
  19213. currentTimeline: this.currentTimeline_,
  19214. syncController: this.syncController_
  19215. });
  19216. if (!switchCandidate) {
  19217. return;
  19218. }
  19219. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  19220. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  19221. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  19222. // potential round trip time of the new request so that we are not too aggressive
  19223. // with switching to a playlist that might save us a fraction of a second.
  19224. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  19225. minimumTimeSaving = 1;
  19226. }
  19227. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  19228. return;
  19229. } // set the bandwidth to that of the desired playlist being sure to scale by
  19230. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  19231. // don't trigger a bandwidthupdate as the bandwidth is artifial
  19232. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  19233. this.trigger('earlyabort');
  19234. }
  19235. handleAbort_(segmentInfo) {
  19236. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  19237. this.mediaRequestsAborted += 1;
  19238. }
  19239. /**
  19240. * XHR `progress` event handler
  19241. *
  19242. * @param {Event}
  19243. * The XHR `progress` event
  19244. * @param {Object} simpleSegment
  19245. * A simplified segment object copy
  19246. * @private
  19247. */
  19248. handleProgress_(event, simpleSegment) {
  19249. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19250. if (this.checkForAbort_(simpleSegment.requestId)) {
  19251. return;
  19252. }
  19253. this.trigger('progress');
  19254. }
  19255. handleTrackInfo_(simpleSegment, trackInfo) {
  19256. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19257. if (this.checkForAbort_(simpleSegment.requestId)) {
  19258. return;
  19259. }
  19260. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  19261. return;
  19262. }
  19263. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  19264. // Guard against cases where we're not getting track info at all until we are
  19265. // certain that all streams will provide it.
  19266. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  19267. this.appendInitSegment_ = {
  19268. audio: true,
  19269. video: true
  19270. };
  19271. this.startingMediaInfo_ = trackInfo;
  19272. this.currentMediaInfo_ = trackInfo;
  19273. this.logger_('trackinfo update', trackInfo);
  19274. this.trigger('trackinfo');
  19275. } // trackinfo may cause an abort if the trackinfo
  19276. // causes a codec change to an unsupported codec.
  19277. if (this.checkForAbort_(simpleSegment.requestId)) {
  19278. return;
  19279. } // set trackinfo on the pending segment so that
  19280. // it can append.
  19281. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  19282. if (this.hasEnoughInfoToAppend_()) {
  19283. this.processCallQueue_();
  19284. }
  19285. }
  19286. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  19287. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19288. if (this.checkForAbort_(simpleSegment.requestId)) {
  19289. return;
  19290. }
  19291. const segmentInfo = this.pendingSegment_;
  19292. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  19293. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  19294. segmentInfo[timingInfoProperty][timeType] = time;
  19295. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  19296. if (this.hasEnoughInfoToAppend_()) {
  19297. this.processCallQueue_();
  19298. }
  19299. }
  19300. handleCaptions_(simpleSegment, captionData) {
  19301. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19302. if (this.checkForAbort_(simpleSegment.requestId)) {
  19303. return;
  19304. } // This could only happen with fmp4 segments, but
  19305. // should still not happen in general
  19306. if (captionData.length === 0) {
  19307. this.logger_('SegmentLoader received no captions from a caption event');
  19308. return;
  19309. }
  19310. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  19311. // can be adjusted by the timestamp offset
  19312. if (!segmentInfo.hasAppendedData_) {
  19313. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  19314. return;
  19315. }
  19316. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  19317. const captionTracks = {}; // get total start/end and captions for each track/stream
  19318. captionData.forEach(caption => {
  19319. // caption.stream is actually a track name...
  19320. // set to the existing values in tracks or default values
  19321. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  19322. // Infinity, as any other value will be less than this
  19323. startTime: Infinity,
  19324. captions: [],
  19325. // 0 as an other value will be more than this
  19326. endTime: 0
  19327. };
  19328. const captionTrack = captionTracks[caption.stream];
  19329. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  19330. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  19331. captionTrack.captions.push(caption);
  19332. });
  19333. Object.keys(captionTracks).forEach(trackName => {
  19334. const {
  19335. startTime,
  19336. endTime,
  19337. captions
  19338. } = captionTracks[trackName];
  19339. const inbandTextTracks = this.inbandTextTracks_;
  19340. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  19341. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  19342. // We do this because a rendition change that also changes the timescale for captions
  19343. // will result in captions being re-parsed for certain segments. If we add them again
  19344. // without clearing we will have two of the same captions visible.
  19345. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  19346. addCaptionData({
  19347. captionArray: captions,
  19348. inbandTextTracks,
  19349. timestampOffset
  19350. });
  19351. }); // Reset stored captions since we added parsed
  19352. // captions to a text track at this point
  19353. if (this.transmuxer_) {
  19354. this.transmuxer_.postMessage({
  19355. action: 'clearParsedMp4Captions'
  19356. });
  19357. }
  19358. }
  19359. handleId3_(simpleSegment, id3Frames, dispatchType) {
  19360. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19361. if (this.checkForAbort_(simpleSegment.requestId)) {
  19362. return;
  19363. }
  19364. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  19365. if (!segmentInfo.hasAppendedData_) {
  19366. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  19367. return;
  19368. }
  19369. 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
  19370. // audio/video source with a metadata track, and an alt audio with a metadata track.
  19371. // However, this probably won't happen, and if it does it can be handled then.
  19372. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  19373. addMetadata({
  19374. inbandTextTracks: this.inbandTextTracks_,
  19375. metadataArray: id3Frames,
  19376. timestampOffset,
  19377. videoDuration: this.duration_()
  19378. });
  19379. }
  19380. processMetadataQueue_() {
  19381. this.metadataQueue_.id3.forEach(fn => fn());
  19382. this.metadataQueue_.caption.forEach(fn => fn());
  19383. this.metadataQueue_.id3 = [];
  19384. this.metadataQueue_.caption = [];
  19385. }
  19386. processCallQueue_() {
  19387. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  19388. // functions may check the length of the load queue and default to pushing themselves
  19389. // back onto the queue.
  19390. this.callQueue_ = [];
  19391. callQueue.forEach(fun => fun());
  19392. }
  19393. processLoadQueue_() {
  19394. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  19395. // functions may check the length of the load queue and default to pushing themselves
  19396. // back onto the queue.
  19397. this.loadQueue_ = [];
  19398. loadQueue.forEach(fun => fun());
  19399. }
  19400. /**
  19401. * Determines whether the loader has enough info to load the next segment.
  19402. *
  19403. * @return {boolean}
  19404. * Whether or not the loader has enough info to load the next segment
  19405. */
  19406. hasEnoughInfoToLoad_() {
  19407. // Since primary timing goes by video, only the audio loader potentially needs to wait
  19408. // to load.
  19409. if (this.loaderType_ !== 'audio') {
  19410. return true;
  19411. }
  19412. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  19413. // enough info to load.
  19414. if (!segmentInfo) {
  19415. return false;
  19416. } // The first segment can and should be loaded immediately so that source buffers are
  19417. // created together (before appending). Source buffer creation uses the presence of
  19418. // audio and video data to determine whether to create audio/video source buffers, and
  19419. // uses processed (transmuxed or parsed) media to determine the types required.
  19420. if (!this.getCurrentMediaInfo_()) {
  19421. return true;
  19422. }
  19423. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  19424. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  19425. // But in practice, there are a few reasons why it is better to wait until a loader
  19426. // is ready to append that segment before requesting and downloading:
  19427. //
  19428. // 1. Because audio and main loaders cross discontinuities together, if this loader
  19429. // is waiting for the other to catch up, then instead of requesting another
  19430. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  19431. // allotted to the loader currently behind.
  19432. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  19433. // is ready to be processed or not, isolating the queueing behavior to the loader.
  19434. // 3. The audio loader bases some of its segment properties on timing information
  19435. // provided by the main loader, meaning that, if the logic for waiting on
  19436. // processing was in media-segment-request, then it would also need to know how
  19437. // to re-generate the segment information after the main loader caught up.
  19438. shouldWaitForTimelineChange({
  19439. timelineChangeController: this.timelineChangeController_,
  19440. currentTimeline: this.currentTimeline_,
  19441. segmentTimeline: segmentInfo.timeline,
  19442. loaderType: this.loaderType_,
  19443. audioDisabled: this.audioDisabled_
  19444. })) {
  19445. return false;
  19446. }
  19447. return true;
  19448. }
  19449. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  19450. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  19451. }
  19452. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  19453. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  19454. }
  19455. getPendingSegmentPlaylist() {
  19456. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  19457. }
  19458. hasEnoughInfoToAppend_() {
  19459. if (!this.sourceUpdater_.ready()) {
  19460. return false;
  19461. } // If content needs to be removed or the loader is waiting on an append reattempt,
  19462. // then no additional content should be appended until the prior append is resolved.
  19463. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  19464. return false;
  19465. }
  19466. const segmentInfo = this.pendingSegment_;
  19467. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  19468. // we do not have information on this specific
  19469. // segment yet
  19470. if (!segmentInfo || !trackInfo) {
  19471. return false;
  19472. }
  19473. const {
  19474. hasAudio,
  19475. hasVideo,
  19476. isMuxed
  19477. } = trackInfo;
  19478. if (hasVideo && !segmentInfo.videoTimingInfo) {
  19479. return false;
  19480. } // muxed content only relies on video timing information for now.
  19481. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  19482. return false;
  19483. }
  19484. if (shouldWaitForTimelineChange({
  19485. timelineChangeController: this.timelineChangeController_,
  19486. currentTimeline: this.currentTimeline_,
  19487. segmentTimeline: segmentInfo.timeline,
  19488. loaderType: this.loaderType_,
  19489. audioDisabled: this.audioDisabled_
  19490. })) {
  19491. return false;
  19492. }
  19493. return true;
  19494. }
  19495. handleData_(simpleSegment, result) {
  19496. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  19497. if (this.checkForAbort_(simpleSegment.requestId)) {
  19498. return;
  19499. } // If there's anything in the call queue, then this data came later and should be
  19500. // executed after the calls currently queued.
  19501. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  19502. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  19503. return;
  19504. }
  19505. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  19506. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  19507. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  19508. // logic may change behavior depending on the state, and changing state too early may
  19509. // inflate our estimates of bandwidth. In the future this should be re-examined to
  19510. // note more granular states.
  19511. // don't process and append data if the mediaSource is closed
  19512. if (this.mediaSource_.readyState === 'closed') {
  19513. return;
  19514. } // if this request included an initialization segment, save that data
  19515. // to the initSegment cache
  19516. if (simpleSegment.map) {
  19517. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  19518. segmentInfo.segment.map = simpleSegment.map;
  19519. } // if this request included a segment key, save that data in the cache
  19520. if (simpleSegment.key) {
  19521. this.segmentKey(simpleSegment.key, true);
  19522. }
  19523. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  19524. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  19525. if (segmentInfo.isFmp4) {
  19526. this.trigger('fmp4');
  19527. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  19528. } else {
  19529. const trackInfo = this.getCurrentMediaInfo_();
  19530. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  19531. let firstVideoFrameTimeForData;
  19532. if (useVideoTimingInfo) {
  19533. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  19534. } // Segment loader knows more about segment timing than the transmuxer (in certain
  19535. // aspects), so make any changes required for a more accurate start time.
  19536. // Don't set the end time yet, as the segment may not be finished processing.
  19537. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  19538. currentStart: segmentInfo.timingInfo.start,
  19539. playlist: segmentInfo.playlist,
  19540. mediaIndex: segmentInfo.mediaIndex,
  19541. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  19542. useVideoTimingInfo,
  19543. firstVideoFrameTimeForData,
  19544. videoTimingInfo: segmentInfo.videoTimingInfo,
  19545. audioTimingInfo: segmentInfo.audioTimingInfo
  19546. });
  19547. } // Init segments for audio and video only need to be appended in certain cases. Now
  19548. // that data is about to be appended, we can check the final cases to determine
  19549. // whether we should append an init segment.
  19550. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  19551. // as we use the start of the segment to offset the best guess (playlist provided)
  19552. // timestamp offset.
  19553. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  19554. // be appended or not.
  19555. if (segmentInfo.isSyncRequest) {
  19556. // first save/update our timing info for this segment.
  19557. // this is what allows us to choose an accurate segment
  19558. // and the main reason we make a sync request.
  19559. this.updateTimingInfoEnd_(segmentInfo);
  19560. this.syncController_.saveSegmentTimingInfo({
  19561. segmentInfo,
  19562. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  19563. });
  19564. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  19565. // after taking into account its timing info, do not append it.
  19566. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  19567. this.logger_('sync segment was incorrect, not appending');
  19568. return;
  19569. } // otherwise append it like any other segment as our guess was correct.
  19570. this.logger_('sync segment was correct, appending');
  19571. } // Save some state so that in the future anything waiting on first append (and/or
  19572. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  19573. // we need some notion of whether the timestamp offset or other relevant information
  19574. // has had a chance to be set.
  19575. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  19576. this.processMetadataQueue_();
  19577. this.appendData_(segmentInfo, result);
  19578. }
  19579. updateAppendInitSegmentStatus(segmentInfo, type) {
  19580. // alt audio doesn't manage timestamp offset
  19581. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
  19582. // segment for each chunk
  19583. !segmentInfo.changedTimestampOffset) {
  19584. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  19585. // append init segments
  19586. this.appendInitSegment_ = {
  19587. audio: true,
  19588. video: true
  19589. };
  19590. }
  19591. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  19592. // make sure we append init segment on playlist changes, in case the media config
  19593. // changed
  19594. this.appendInitSegment_[type] = true;
  19595. }
  19596. }
  19597. getInitSegmentAndUpdateState_({
  19598. type,
  19599. initSegment,
  19600. map,
  19601. playlist
  19602. }) {
  19603. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  19604. // (Section 3) required to parse the applicable Media Segments. It applies to every
  19605. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  19606. // or until the end of the playlist."
  19607. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  19608. if (map) {
  19609. const id = initSegmentId(map);
  19610. if (this.activeInitSegmentId_ === id) {
  19611. // don't need to re-append the init segment if the ID matches
  19612. return null;
  19613. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  19614. // obtained) init segment
  19615. //
  19616. // this also caches the init segment for later use
  19617. initSegment = this.initSegmentForMap(map, true).bytes;
  19618. this.activeInitSegmentId_ = id;
  19619. } // We used to always prepend init segments for video, however, that shouldn't be
  19620. // necessary. Instead, we should only append on changes, similar to what we've always
  19621. // done for audio. This is more important (though may not be that important) for
  19622. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  19623. // appends.
  19624. if (initSegment && this.appendInitSegment_[type]) {
  19625. // Make sure we track the playlist that we last used for the init segment, so that
  19626. // we can re-append the init segment in the event that we get data from a new
  19627. // playlist. Discontinuities and track changes are handled in other sections.
  19628. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  19629. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  19630. // we are appending the muxer init segment
  19631. this.activeInitSegmentId_ = null;
  19632. return initSegment;
  19633. }
  19634. return null;
  19635. }
  19636. handleQuotaExceededError_({
  19637. segmentInfo,
  19638. type,
  19639. bytes
  19640. }, error) {
  19641. const audioBuffered = this.sourceUpdater_.audioBuffered();
  19642. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  19643. // should be cleared out during the buffer removals. However, log in case it helps
  19644. // debug.
  19645. if (audioBuffered.length > 1) {
  19646. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  19647. }
  19648. if (videoBuffered.length > 1) {
  19649. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  19650. }
  19651. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  19652. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  19653. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  19654. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  19655. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  19656. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  19657. // allow for appends of segments this size). In the future, it may be possible to
  19658. // split up the segment and append in pieces, but for now, error out this playlist
  19659. // in an attempt to switch to a more manageable rendition.
  19660. 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(', ')}, `);
  19661. this.error({
  19662. message: 'Quota exceeded error with append of a single segment of content',
  19663. excludeUntil: Infinity
  19664. });
  19665. this.trigger('error');
  19666. return;
  19667. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  19668. // that the segment-loader should block on future events until this one is handled, so
  19669. // that it doesn't keep moving onto further segments. Adding the call to the call
  19670. // queue will prevent further appends until waitingOnRemove_ and
  19671. // quotaExceededErrorRetryTimeout_ are cleared.
  19672. //
  19673. // Note that this will only block the current loader. In the case of demuxed content,
  19674. // the other load may keep filling as fast as possible. In practice, this should be
  19675. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  19676. // source buffer, or video fills without enough room for audio to append (and without
  19677. // the availability of clearing out seconds of back buffer to make room for audio).
  19678. // But it might still be good to handle this case in the future as a TODO.
  19679. this.waitingOnRemove_ = true;
  19680. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  19681. segmentInfo,
  19682. type,
  19683. bytes
  19684. }));
  19685. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  19686. // before retrying.
  19687. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  19688. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  19689. this.remove(0, timeToRemoveUntil, () => {
  19690. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  19691. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  19692. // attempts (since we can't clear less than the minimum)
  19693. this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
  19694. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  19695. this.quotaExceededErrorRetryTimeout_ = null;
  19696. this.processCallQueue_();
  19697. }, MIN_BACK_BUFFER * 1000);
  19698. }, true);
  19699. }
  19700. handleAppendError_({
  19701. segmentInfo,
  19702. type,
  19703. bytes
  19704. }, error) {
  19705. // if there's no error, nothing to do
  19706. if (!error) {
  19707. return;
  19708. }
  19709. if (error.code === QUOTA_EXCEEDED_ERR) {
  19710. this.handleQuotaExceededError_({
  19711. segmentInfo,
  19712. type,
  19713. bytes
  19714. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  19715. // to trigger an append error.
  19716. return;
  19717. }
  19718. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  19719. 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.
  19720. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  19721. //
  19722. // Trigger a special error so that it can be handled separately from normal,
  19723. // recoverable errors.
  19724. this.trigger('appenderror');
  19725. }
  19726. appendToSourceBuffer_({
  19727. segmentInfo,
  19728. type,
  19729. initSegment,
  19730. data,
  19731. bytes
  19732. }) {
  19733. // If this is a re-append, bytes were already created and don't need to be recreated
  19734. if (!bytes) {
  19735. const segments = [data];
  19736. let byteLength = data.byteLength;
  19737. if (initSegment) {
  19738. // if the media initialization segment is changing, append it before the content
  19739. // segment
  19740. segments.unshift(initSegment);
  19741. byteLength += initSegment.byteLength;
  19742. } // Technically we should be OK appending the init segment separately, however, we
  19743. // haven't yet tested that, and prepending is how we have always done things.
  19744. bytes = concatSegments({
  19745. bytes: byteLength,
  19746. segments
  19747. });
  19748. }
  19749. this.sourceUpdater_.appendBuffer({
  19750. segmentInfo,
  19751. type,
  19752. bytes
  19753. }, this.handleAppendError_.bind(this, {
  19754. segmentInfo,
  19755. type,
  19756. bytes
  19757. }));
  19758. }
  19759. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  19760. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  19761. return;
  19762. }
  19763. const segment = this.pendingSegment_.segment;
  19764. const timingInfoProperty = `${type}TimingInfo`;
  19765. if (!segment[timingInfoProperty]) {
  19766. segment[timingInfoProperty] = {};
  19767. }
  19768. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  19769. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  19770. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  19771. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  19772. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  19773. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  19774. }
  19775. appendData_(segmentInfo, result) {
  19776. const {
  19777. type,
  19778. data
  19779. } = result;
  19780. if (!data || !data.byteLength) {
  19781. return;
  19782. }
  19783. if (type === 'audio' && this.audioDisabled_) {
  19784. return;
  19785. }
  19786. const initSegment = this.getInitSegmentAndUpdateState_({
  19787. type,
  19788. initSegment: result.initSegment,
  19789. playlist: segmentInfo.playlist,
  19790. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  19791. });
  19792. this.appendToSourceBuffer_({
  19793. segmentInfo,
  19794. type,
  19795. initSegment,
  19796. data
  19797. });
  19798. }
  19799. /**
  19800. * load a specific segment from a request into the buffer
  19801. *
  19802. * @private
  19803. */
  19804. loadSegment_(segmentInfo) {
  19805. this.state = 'WAITING';
  19806. this.pendingSegment_ = segmentInfo;
  19807. this.trimBackBuffer_(segmentInfo);
  19808. if (typeof segmentInfo.timestampOffset === 'number') {
  19809. if (this.transmuxer_) {
  19810. this.transmuxer_.postMessage({
  19811. action: 'clearAllMp4Captions'
  19812. });
  19813. }
  19814. }
  19815. if (!this.hasEnoughInfoToLoad_()) {
  19816. this.loadQueue_.push(() => {
  19817. // regenerate the audioAppendStart, timestampOffset, etc as they
  19818. // may have changed since this function was added to the queue.
  19819. const options = _extends({}, segmentInfo, {
  19820. forceTimestampOffset: true
  19821. });
  19822. _extends(segmentInfo, this.generateSegmentInfo_(options));
  19823. this.isPendingTimestampOffset_ = false;
  19824. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  19825. });
  19826. return;
  19827. }
  19828. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  19829. }
  19830. updateTransmuxerAndRequestSegment_(segmentInfo) {
  19831. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  19832. // the transmuxer still needs to be updated before then.
  19833. //
  19834. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  19835. // offset must be passed to the transmuxer for stream correcting adjustments.
  19836. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  19837. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  19838. segmentInfo.gopsToAlignWith = [];
  19839. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  19840. this.transmuxer_.postMessage({
  19841. action: 'reset'
  19842. });
  19843. this.transmuxer_.postMessage({
  19844. action: 'setTimestampOffset',
  19845. timestampOffset: segmentInfo.timestampOffset
  19846. });
  19847. }
  19848. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  19849. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  19850. const isWalkingForward = this.mediaIndex !== null;
  19851. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  19852. // the first timeline
  19853. segmentInfo.timeline > 0;
  19854. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  19855. 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),
  19856. // then this init segment has never been seen before and should be appended.
  19857. //
  19858. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  19859. // both to true and leave the decision of whether to append the init segment to append time.
  19860. if (simpleSegment.map && !simpleSegment.map.bytes) {
  19861. this.logger_('going to request init segment.');
  19862. this.appendInitSegment_ = {
  19863. video: true,
  19864. audio: true
  19865. };
  19866. }
  19867. segmentInfo.abortRequests = mediaSegmentRequest({
  19868. xhr: this.vhs_.xhr,
  19869. xhrOptions: this.xhrOptions_,
  19870. decryptionWorker: this.decrypter_,
  19871. segment: simpleSegment,
  19872. abortFn: this.handleAbort_.bind(this, segmentInfo),
  19873. progressFn: this.handleProgress_.bind(this),
  19874. trackInfoFn: this.handleTrackInfo_.bind(this),
  19875. timingInfoFn: this.handleTimingInfo_.bind(this),
  19876. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  19877. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  19878. captionsFn: this.handleCaptions_.bind(this),
  19879. isEndOfTimeline,
  19880. endedTimelineFn: () => {
  19881. this.logger_('received endedtimeline callback');
  19882. },
  19883. id3Fn: this.handleId3_.bind(this),
  19884. dataFn: this.handleData_.bind(this),
  19885. doneFn: this.segmentRequestFinished_.bind(this),
  19886. onTransmuxerLog: ({
  19887. message,
  19888. level,
  19889. stream
  19890. }) => {
  19891. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  19892. }
  19893. });
  19894. }
  19895. /**
  19896. * trim the back buffer so that we don't have too much data
  19897. * in the source buffer
  19898. *
  19899. * @private
  19900. *
  19901. * @param {Object} segmentInfo - the current segment
  19902. */
  19903. trimBackBuffer_(segmentInfo) {
  19904. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  19905. // buffer and a very conservative "garbage collector"
  19906. // We manually clear out the old buffer to ensure
  19907. // we don't trigger the QuotaExceeded error
  19908. // on the source buffer during subsequent appends
  19909. if (removeToTime > 0) {
  19910. this.remove(0, removeToTime);
  19911. }
  19912. }
  19913. /**
  19914. * created a simplified copy of the segment object with just the
  19915. * information necessary to perform the XHR and decryption
  19916. *
  19917. * @private
  19918. *
  19919. * @param {Object} segmentInfo - the current segment
  19920. * @return {Object} a simplified segment object copy
  19921. */
  19922. createSimplifiedSegmentObj_(segmentInfo) {
  19923. const segment = segmentInfo.segment;
  19924. const part = segmentInfo.part;
  19925. const simpleSegment = {
  19926. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  19927. byterange: part ? part.byterange : segment.byterange,
  19928. requestId: segmentInfo.requestId,
  19929. transmuxer: segmentInfo.transmuxer,
  19930. audioAppendStart: segmentInfo.audioAppendStart,
  19931. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  19932. part: segmentInfo.part
  19933. };
  19934. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  19935. if (previousSegment && previousSegment.timeline === segment.timeline) {
  19936. // The baseStartTime of a segment is used to handle rollover when probing the TS
  19937. // segment to retrieve timing information. Since the probe only looks at the media's
  19938. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  19939. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  19940. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  19941. // seconds of media time, so should be used here. The previous segment is used since
  19942. // the end of the previous segment should represent the beginning of the current
  19943. // segment, so long as they are on the same timeline.
  19944. if (previousSegment.videoTimingInfo) {
  19945. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  19946. } else if (previousSegment.audioTimingInfo) {
  19947. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  19948. }
  19949. }
  19950. if (segment.key) {
  19951. // if the media sequence is greater than 2^32, the IV will be incorrect
  19952. // assuming 10s segments, that would be about 1300 years
  19953. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  19954. simpleSegment.key = this.segmentKey(segment.key);
  19955. simpleSegment.key.iv = iv;
  19956. }
  19957. if (segment.map) {
  19958. simpleSegment.map = this.initSegmentForMap(segment.map);
  19959. }
  19960. return simpleSegment;
  19961. }
  19962. saveTransferStats_(stats) {
  19963. // every request counts as a media request even if it has been aborted
  19964. // or canceled due to a timeout
  19965. this.mediaRequests += 1;
  19966. if (stats) {
  19967. this.mediaBytesTransferred += stats.bytesReceived;
  19968. this.mediaTransferDuration += stats.roundTripTime;
  19969. }
  19970. }
  19971. saveBandwidthRelatedStats_(duration, stats) {
  19972. // byteLength will be used for throughput, and should be based on bytes receieved,
  19973. // which we only know at the end of the request and should reflect total bytes
  19974. // downloaded rather than just bytes processed from components of the segment
  19975. this.pendingSegment_.byteLength = stats.bytesReceived;
  19976. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  19977. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  19978. return;
  19979. }
  19980. this.bandwidth = stats.bandwidth;
  19981. this.roundTrip = stats.roundTripTime;
  19982. }
  19983. handleTimeout_() {
  19984. // although the VTT segment loader bandwidth isn't really used, it's good to
  19985. // maintain functinality between segment loaders
  19986. this.mediaRequestsTimedout += 1;
  19987. this.bandwidth = 1;
  19988. this.roundTrip = NaN;
  19989. this.trigger('bandwidthupdate');
  19990. this.trigger('timeout');
  19991. }
  19992. /**
  19993. * Handle the callback from the segmentRequest function and set the
  19994. * associated SegmentLoader state and errors if necessary
  19995. *
  19996. * @private
  19997. */
  19998. segmentRequestFinished_(error, simpleSegment, result) {
  19999. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  20000. // check the call queue directly since this function doesn't need to deal with any
  20001. // data, and can continue even if the source buffers are not set up and we didn't get
  20002. // any data from the segment
  20003. if (this.callQueue_.length) {
  20004. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  20005. return;
  20006. }
  20007. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  20008. if (!this.pendingSegment_) {
  20009. return;
  20010. } // the request was aborted and the SegmentLoader has already started
  20011. // another request. this can happen when the timeout for an aborted
  20012. // request triggers due to a limitation in the XHR library
  20013. // do not count this as any sort of request or we risk double-counting
  20014. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  20015. return;
  20016. } // an error occurred from the active pendingSegment_ so reset everything
  20017. if (error) {
  20018. this.pendingSegment_ = null;
  20019. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  20020. if (error.code === REQUEST_ERRORS.ABORTED) {
  20021. return;
  20022. }
  20023. this.pause(); // the error is really just that at least one of the requests timed-out
  20024. // set the bandwidth to a very low value and trigger an ABR switch to
  20025. // take emergency action
  20026. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  20027. this.handleTimeout_();
  20028. return;
  20029. } // if control-flow has arrived here, then the error is real
  20030. // emit an error event to exclude the current playlist
  20031. this.mediaRequestsErrored += 1;
  20032. this.error(error);
  20033. this.trigger('error');
  20034. return;
  20035. }
  20036. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  20037. // generated for ABR purposes
  20038. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  20039. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  20040. if (result.gopInfo) {
  20041. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  20042. } // Although we may have already started appending on progress, we shouldn't switch the
  20043. // state away from loading until we are officially done loading the segment data.
  20044. this.state = 'APPENDING'; // used for testing
  20045. this.trigger('appending');
  20046. this.waitForAppendsToComplete_(segmentInfo);
  20047. }
  20048. setTimeMapping_(timeline) {
  20049. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  20050. if (timelineMapping !== null) {
  20051. this.timeMapping_ = timelineMapping;
  20052. }
  20053. }
  20054. updateMediaSecondsLoaded_(segment) {
  20055. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  20056. this.mediaSecondsLoaded += segment.end - segment.start;
  20057. } else {
  20058. this.mediaSecondsLoaded += segment.duration;
  20059. }
  20060. }
  20061. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  20062. if (timestampOffset === null) {
  20063. return false;
  20064. } // note that we're potentially using the same timestamp offset for both video and
  20065. // audio
  20066. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  20067. return true;
  20068. }
  20069. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  20070. return true;
  20071. }
  20072. return false;
  20073. }
  20074. trueSegmentStart_({
  20075. currentStart,
  20076. playlist,
  20077. mediaIndex,
  20078. firstVideoFrameTimeForData,
  20079. currentVideoTimestampOffset,
  20080. useVideoTimingInfo,
  20081. videoTimingInfo,
  20082. audioTimingInfo
  20083. }) {
  20084. if (typeof currentStart !== 'undefined') {
  20085. // if start was set once, keep using it
  20086. return currentStart;
  20087. }
  20088. if (!useVideoTimingInfo) {
  20089. return audioTimingInfo.start;
  20090. }
  20091. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  20092. // within that segment. Since the transmuxer maintains a cache of incomplete data
  20093. // from and/or the last frame seen, the start time may reflect a frame that starts
  20094. // in the previous segment. Check for that case and ensure the start time is
  20095. // accurate for the segment.
  20096. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  20097. return firstVideoFrameTimeForData;
  20098. }
  20099. return videoTimingInfo.start;
  20100. }
  20101. waitForAppendsToComplete_(segmentInfo) {
  20102. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  20103. if (!trackInfo) {
  20104. this.error({
  20105. message: 'No starting media returned, likely due to an unsupported media format.',
  20106. playlistExclusionDuration: Infinity
  20107. });
  20108. this.trigger('error');
  20109. return;
  20110. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  20111. // on each queue this loader is responsible for to ensure that the appends are
  20112. // complete.
  20113. const {
  20114. hasAudio,
  20115. hasVideo,
  20116. isMuxed
  20117. } = trackInfo;
  20118. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  20119. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  20120. segmentInfo.waitingOnAppends = 0; // segments with no data
  20121. if (!segmentInfo.hasAppendedData_) {
  20122. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  20123. // When there's no audio or video data in the segment, there's no audio or video
  20124. // timing information.
  20125. //
  20126. // If there's no audio or video timing information, then the timestamp offset
  20127. // can't be adjusted to the appropriate value for the transmuxer and source
  20128. // buffers.
  20129. //
  20130. // Therefore, the next segment should be used to set the timestamp offset.
  20131. this.isPendingTimestampOffset_ = true;
  20132. } // override settings for metadata only segments
  20133. segmentInfo.timingInfo = {
  20134. start: 0
  20135. };
  20136. segmentInfo.waitingOnAppends++;
  20137. if (!this.isPendingTimestampOffset_) {
  20138. // update the timestampoffset
  20139. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  20140. // no video/audio data.
  20141. this.processMetadataQueue_();
  20142. } // append is "done" instantly with no data.
  20143. this.checkAppendsDone_(segmentInfo);
  20144. return;
  20145. } // Since source updater could call back synchronously, do the increments first.
  20146. if (waitForVideo) {
  20147. segmentInfo.waitingOnAppends++;
  20148. }
  20149. if (waitForAudio) {
  20150. segmentInfo.waitingOnAppends++;
  20151. }
  20152. if (waitForVideo) {
  20153. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  20154. }
  20155. if (waitForAudio) {
  20156. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  20157. }
  20158. }
  20159. checkAppendsDone_(segmentInfo) {
  20160. if (this.checkForAbort_(segmentInfo.requestId)) {
  20161. return;
  20162. }
  20163. segmentInfo.waitingOnAppends--;
  20164. if (segmentInfo.waitingOnAppends === 0) {
  20165. this.handleAppendsDone_();
  20166. }
  20167. }
  20168. checkForIllegalMediaSwitch(trackInfo) {
  20169. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  20170. if (illegalMediaSwitchError) {
  20171. this.error({
  20172. message: illegalMediaSwitchError,
  20173. playlistExclusionDuration: Infinity
  20174. });
  20175. this.trigger('error');
  20176. return true;
  20177. }
  20178. return false;
  20179. }
  20180. updateSourceBufferTimestampOffset_(segmentInfo) {
  20181. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  20182. // priority, timing-wise, so we must wait
  20183. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  20184. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  20185. this.loaderType_ !== 'main') {
  20186. return;
  20187. }
  20188. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  20189. // the timing info here comes from video. In the event that the audio is longer than
  20190. // the video, this will trim the start of the audio.
  20191. // This also trims any offset from 0 at the beginning of the media
  20192. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  20193. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  20194. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  20195. timingInfo: segmentInfo.timingInfo
  20196. }); // In the event that there are part segment downloads, each will try to update the
  20197. // timestamp offset. Retaining this bit of state prevents us from updating in the
  20198. // future (within the same segment), however, there may be a better way to handle it.
  20199. segmentInfo.changedTimestampOffset = true;
  20200. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  20201. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  20202. didChange = true;
  20203. }
  20204. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  20205. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  20206. didChange = true;
  20207. }
  20208. if (didChange) {
  20209. this.trigger('timestampoffset');
  20210. }
  20211. }
  20212. getSegmentStartTimeForTimestampOffsetCalculation_({
  20213. videoTimingInfo,
  20214. audioTimingInfo,
  20215. timingInfo
  20216. }) {
  20217. if (!this.useDtsForTimestampOffset_) {
  20218. return timingInfo.start;
  20219. }
  20220. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  20221. return videoTimingInfo.transmuxedDecodeStart;
  20222. } // handle audio only
  20223. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  20224. return audioTimingInfo.transmuxedDecodeStart;
  20225. } // handle content not transmuxed (e.g., MP4)
  20226. return timingInfo.start;
  20227. }
  20228. updateTimingInfoEnd_(segmentInfo) {
  20229. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  20230. const trackInfo = this.getMediaInfo_();
  20231. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  20232. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  20233. if (!prioritizedTimingInfo) {
  20234. return;
  20235. }
  20236. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  20237. // current example is the case of fmp4), so use the rough duration to calculate an
  20238. // end time.
  20239. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  20240. }
  20241. /**
  20242. * callback to run when appendBuffer is finished. detects if we are
  20243. * in a good state to do things with the data we got, or if we need
  20244. * to wait for more
  20245. *
  20246. * @private
  20247. */
  20248. handleAppendsDone_() {
  20249. // appendsdone can cause an abort
  20250. if (this.pendingSegment_) {
  20251. this.trigger('appendsdone');
  20252. }
  20253. if (!this.pendingSegment_) {
  20254. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  20255. // all appending cases?
  20256. if (!this.paused()) {
  20257. this.monitorBuffer_();
  20258. }
  20259. return;
  20260. }
  20261. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  20262. // best to wait until all appends are done so we're sure that the primary media is
  20263. // finished (and we have its end time).
  20264. this.updateTimingInfoEnd_(segmentInfo);
  20265. if (this.shouldSaveSegmentTimingInfo_) {
  20266. // Timeline mappings should only be saved for the main loader. This is for multiple
  20267. // reasons:
  20268. //
  20269. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  20270. // and the main loader try to save the timeline mapping, whichever comes later
  20271. // will overwrite the first. In theory this is OK, as the mappings should be the
  20272. // same, however, it breaks for (2)
  20273. // 2) In the event of a live stream, the initial live point will make for a somewhat
  20274. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  20275. // the mapping will be off for one of the streams, dependent on which one was
  20276. // first saved (see (1)).
  20277. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  20278. //
  20279. // Since the audio loader will wait for the main loader to load the first segment,
  20280. // the main loader will save the first timeline mapping, and ensure that there won't
  20281. // be a case where audio loads two segments without saving a mapping (thus leading
  20282. // to missing segment timing info).
  20283. this.syncController_.saveSegmentTimingInfo({
  20284. segmentInfo,
  20285. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  20286. });
  20287. }
  20288. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  20289. if (segmentDurationMessage) {
  20290. if (segmentDurationMessage.severity === 'warn') {
  20291. videojs__default["default"].log.warn(segmentDurationMessage.message);
  20292. } else {
  20293. this.logger_(segmentDurationMessage.message);
  20294. }
  20295. }
  20296. this.recordThroughput_(segmentInfo);
  20297. this.pendingSegment_ = null;
  20298. this.state = 'READY';
  20299. if (segmentInfo.isSyncRequest) {
  20300. this.trigger('syncinfoupdate'); // if the sync request was not appended
  20301. // then it was not the correct segment.
  20302. // throw it away and use the data it gave us
  20303. // to get the correct one.
  20304. if (!segmentInfo.hasAppendedData_) {
  20305. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  20306. return;
  20307. }
  20308. }
  20309. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  20310. this.addSegmentMetadataCue_(segmentInfo);
  20311. this.fetchAtBuffer_ = true;
  20312. if (this.currentTimeline_ !== segmentInfo.timeline) {
  20313. this.timelineChangeController_.lastTimelineChange({
  20314. type: this.loaderType_,
  20315. from: this.currentTimeline_,
  20316. to: segmentInfo.timeline
  20317. }); // If audio is not disabled, the main segment loader is responsible for updating
  20318. // the audio timeline as well. If the content is video only, this won't have any
  20319. // impact.
  20320. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  20321. this.timelineChangeController_.lastTimelineChange({
  20322. type: 'audio',
  20323. from: this.currentTimeline_,
  20324. to: segmentInfo.timeline
  20325. });
  20326. }
  20327. }
  20328. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  20329. // the following conditional otherwise it may consider this a bad "guess"
  20330. // and attempt to resync when the post-update seekable window and live
  20331. // point would mean that this was the perfect segment to fetch
  20332. this.trigger('syncinfoupdate');
  20333. const segment = segmentInfo.segment;
  20334. const part = segmentInfo.part;
  20335. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  20336. 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
  20337. // the currentTime_ that means that our conservative guess was too conservative.
  20338. // In that case, reset the loader state so that we try to use any information gained
  20339. // from the previous request to create a new, more accurate, sync-point.
  20340. if (badSegmentGuess || badPartGuess) {
  20341. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  20342. this.resetEverything();
  20343. return;
  20344. }
  20345. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  20346. // and conservatively guess
  20347. if (isWalkingForward) {
  20348. this.trigger('bandwidthupdate');
  20349. }
  20350. this.trigger('progress');
  20351. this.mediaIndex = segmentInfo.mediaIndex;
  20352. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  20353. // buffer, end the stream. this ensures the "ended" event will
  20354. // fire if playback reaches that point.
  20355. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  20356. this.endOfStream();
  20357. } // used for testing
  20358. this.trigger('appended');
  20359. if (segmentInfo.hasAppendedData_) {
  20360. this.mediaAppends++;
  20361. }
  20362. if (!this.paused()) {
  20363. this.monitorBuffer_();
  20364. }
  20365. }
  20366. /**
  20367. * Records the current throughput of the decrypt, transmux, and append
  20368. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  20369. * moving average of the throughput. `throughput.count` is the number of
  20370. * data points in the average.
  20371. *
  20372. * @private
  20373. * @param {Object} segmentInfo the object returned by loadSegment
  20374. */
  20375. recordThroughput_(segmentInfo) {
  20376. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  20377. 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}`);
  20378. return;
  20379. }
  20380. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  20381. // by zero in the case where the throughput is ridiculously high
  20382. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  20383. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  20384. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  20385. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  20386. }
  20387. /**
  20388. * Adds a cue to the segment-metadata track with some metadata information about the
  20389. * segment
  20390. *
  20391. * @private
  20392. * @param {Object} segmentInfo
  20393. * the object returned by loadSegment
  20394. * @method addSegmentMetadataCue_
  20395. */
  20396. addSegmentMetadataCue_(segmentInfo) {
  20397. if (!this.segmentMetadataTrack_) {
  20398. return;
  20399. }
  20400. const segment = segmentInfo.segment;
  20401. const start = segment.start;
  20402. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  20403. if (!finite(start) || !finite(end)) {
  20404. return;
  20405. }
  20406. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  20407. const Cue = window.WebKitDataCue || window.VTTCue;
  20408. const value = {
  20409. custom: segment.custom,
  20410. dateTimeObject: segment.dateTimeObject,
  20411. dateTimeString: segment.dateTimeString,
  20412. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  20413. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  20414. codecs: segmentInfo.playlist.attributes.CODECS,
  20415. byteLength: segmentInfo.byteLength,
  20416. uri: segmentInfo.uri,
  20417. timeline: segmentInfo.timeline,
  20418. playlist: segmentInfo.playlist.id,
  20419. start,
  20420. end
  20421. };
  20422. const data = JSON.stringify(value);
  20423. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  20424. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  20425. cue.value = value;
  20426. this.segmentMetadataTrack_.addCue(cue);
  20427. }
  20428. }
  20429. function noop() {}
  20430. const toTitleCase = function (string) {
  20431. if (typeof string !== 'string') {
  20432. return string;
  20433. }
  20434. return string.replace(/./, w => w.toUpperCase());
  20435. };
  20436. /**
  20437. * @file source-updater.js
  20438. */
  20439. const bufferTypes = ['video', 'audio'];
  20440. const updating = (type, sourceUpdater) => {
  20441. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20442. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  20443. };
  20444. const nextQueueIndexOfType = (type, queue) => {
  20445. for (let i = 0; i < queue.length; i++) {
  20446. const queueEntry = queue[i];
  20447. if (queueEntry.type === 'mediaSource') {
  20448. // If the next entry is a media source entry (uses multiple source buffers), block
  20449. // processing to allow it to go through first.
  20450. return null;
  20451. }
  20452. if (queueEntry.type === type) {
  20453. return i;
  20454. }
  20455. }
  20456. return null;
  20457. };
  20458. const shiftQueue = (type, sourceUpdater) => {
  20459. if (sourceUpdater.queue.length === 0) {
  20460. return;
  20461. }
  20462. let queueIndex = 0;
  20463. let queueEntry = sourceUpdater.queue[queueIndex];
  20464. if (queueEntry.type === 'mediaSource') {
  20465. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  20466. sourceUpdater.queue.shift();
  20467. queueEntry.action(sourceUpdater);
  20468. if (queueEntry.doneFn) {
  20469. queueEntry.doneFn();
  20470. } // Only specific source buffer actions must wait for async updateend events. Media
  20471. // Source actions process synchronously. Therefore, both audio and video source
  20472. // buffers are now clear to process the next queue entries.
  20473. shiftQueue('audio', sourceUpdater);
  20474. shiftQueue('video', sourceUpdater);
  20475. } // Media Source actions require both source buffers, so if the media source action
  20476. // couldn't process yet (because one or both source buffers are busy), block other
  20477. // queue actions until both are available and the media source action can process.
  20478. return;
  20479. }
  20480. if (type === 'mediaSource') {
  20481. // If the queue was shifted by a media source action (this happens when pushing a
  20482. // media source action onto the queue), then it wasn't from an updateend event from an
  20483. // audio or video source buffer, so there's no change from previous state, and no
  20484. // processing should be done.
  20485. return;
  20486. } // Media source queue entries don't need to consider whether the source updater is
  20487. // started (i.e., source buffers are created) as they don't need the source buffers, but
  20488. // source buffer queue entries do.
  20489. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  20490. return;
  20491. }
  20492. if (queueEntry.type !== type) {
  20493. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  20494. if (queueIndex === null) {
  20495. // Either there's no queue entry that uses this source buffer type in the queue, or
  20496. // there's a media source queue entry before the next entry of this type, in which
  20497. // case wait for that action to process first.
  20498. return;
  20499. }
  20500. queueEntry = sourceUpdater.queue[queueIndex];
  20501. }
  20502. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  20503. //
  20504. // The queue pending operation must be set before the action is performed in the event
  20505. // that the action results in a synchronous event that is acted upon. For instance, if
  20506. // an exception is thrown that can be handled, it's possible that new actions will be
  20507. // appended to an empty queue and immediately executed, but would not have the correct
  20508. // pending information if this property was set after the action was performed.
  20509. sourceUpdater.queuePending[type] = queueEntry;
  20510. queueEntry.action(type, sourceUpdater);
  20511. if (!queueEntry.doneFn) {
  20512. // synchronous operation, process next entry
  20513. sourceUpdater.queuePending[type] = null;
  20514. shiftQueue(type, sourceUpdater);
  20515. return;
  20516. }
  20517. };
  20518. const cleanupBuffer = (type, sourceUpdater) => {
  20519. const buffer = sourceUpdater[`${type}Buffer`];
  20520. const titleType = toTitleCase(type);
  20521. if (!buffer) {
  20522. return;
  20523. }
  20524. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  20525. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  20526. sourceUpdater.codecs[type] = null;
  20527. sourceUpdater[`${type}Buffer`] = null;
  20528. };
  20529. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  20530. const actions = {
  20531. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  20532. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20533. // or the media source does not contain this source buffer.
  20534. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20535. return;
  20536. }
  20537. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  20538. try {
  20539. sourceBuffer.appendBuffer(bytes);
  20540. } catch (e) {
  20541. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  20542. sourceUpdater.queuePending[type] = null;
  20543. onError(e);
  20544. }
  20545. },
  20546. remove: (start, end) => (type, sourceUpdater) => {
  20547. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20548. // or the media source does not contain this source buffer.
  20549. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20550. return;
  20551. }
  20552. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  20553. try {
  20554. sourceBuffer.remove(start, end);
  20555. } catch (e) {
  20556. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  20557. }
  20558. },
  20559. timestampOffset: offset => (type, sourceUpdater) => {
  20560. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20561. // or the media source does not contain this source buffer.
  20562. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20563. return;
  20564. }
  20565. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  20566. sourceBuffer.timestampOffset = offset;
  20567. },
  20568. callback: callback => (type, sourceUpdater) => {
  20569. callback();
  20570. },
  20571. endOfStream: error => sourceUpdater => {
  20572. if (sourceUpdater.mediaSource.readyState !== 'open') {
  20573. return;
  20574. }
  20575. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  20576. try {
  20577. sourceUpdater.mediaSource.endOfStream(error);
  20578. } catch (e) {
  20579. videojs__default["default"].log.warn('Failed to call media source endOfStream', e);
  20580. }
  20581. },
  20582. duration: duration => sourceUpdater => {
  20583. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  20584. try {
  20585. sourceUpdater.mediaSource.duration = duration;
  20586. } catch (e) {
  20587. videojs__default["default"].log.warn('Failed to set media source duration', e);
  20588. }
  20589. },
  20590. abort: () => (type, sourceUpdater) => {
  20591. if (sourceUpdater.mediaSource.readyState !== 'open') {
  20592. return;
  20593. }
  20594. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  20595. // or the media source does not contain this source buffer.
  20596. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20597. return;
  20598. }
  20599. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  20600. try {
  20601. sourceBuffer.abort();
  20602. } catch (e) {
  20603. videojs__default["default"].log.warn(`Failed to abort on ${type}Buffer`, e);
  20604. }
  20605. },
  20606. addSourceBuffer: (type, codec) => sourceUpdater => {
  20607. const titleType = toTitleCase(type);
  20608. const mime = getMimeForCodec(codec);
  20609. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  20610. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  20611. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  20612. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  20613. sourceUpdater.codecs[type] = codec;
  20614. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  20615. },
  20616. removeSourceBuffer: type => sourceUpdater => {
  20617. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20618. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  20619. // or the media source does not contain this source buffer.
  20620. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20621. return;
  20622. }
  20623. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  20624. try {
  20625. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  20626. } catch (e) {
  20627. videojs__default["default"].log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  20628. }
  20629. },
  20630. changeType: codec => (type, sourceUpdater) => {
  20631. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  20632. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  20633. // or the media source does not contain this source buffer.
  20634. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  20635. return;
  20636. } // do not update codec if we don't need to.
  20637. if (sourceUpdater.codecs[type] === codec) {
  20638. return;
  20639. }
  20640. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  20641. sourceBuffer.changeType(mime);
  20642. sourceUpdater.codecs[type] = codec;
  20643. }
  20644. };
  20645. const pushQueue = ({
  20646. type,
  20647. sourceUpdater,
  20648. action,
  20649. doneFn,
  20650. name
  20651. }) => {
  20652. sourceUpdater.queue.push({
  20653. type,
  20654. action,
  20655. doneFn,
  20656. name
  20657. });
  20658. shiftQueue(type, sourceUpdater);
  20659. };
  20660. const onUpdateend = (type, sourceUpdater) => e => {
  20661. // Although there should, in theory, be a pending action for any updateend receieved,
  20662. // there are some actions that may trigger updateend events without set definitions in
  20663. // the w3c spec. For instance, setting the duration on the media source may trigger
  20664. // updateend events on source buffers. This does not appear to be in the spec. As such,
  20665. // if we encounter an updateend without a corresponding pending action from our queue
  20666. // for that source buffer type, process the next action.
  20667. if (sourceUpdater.queuePending[type]) {
  20668. const doneFn = sourceUpdater.queuePending[type].doneFn;
  20669. sourceUpdater.queuePending[type] = null;
  20670. if (doneFn) {
  20671. // if there's an error, report it
  20672. doneFn(sourceUpdater[`${type}Error_`]);
  20673. }
  20674. }
  20675. shiftQueue(type, sourceUpdater);
  20676. };
  20677. /**
  20678. * A queue of callbacks to be serialized and applied when a
  20679. * MediaSource and its associated SourceBuffers are not in the
  20680. * updating state. It is used by the segment loader to update the
  20681. * underlying SourceBuffers when new data is loaded, for instance.
  20682. *
  20683. * @class SourceUpdater
  20684. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  20685. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  20686. */
  20687. class SourceUpdater extends videojs__default["default"].EventTarget {
  20688. constructor(mediaSource) {
  20689. super();
  20690. this.mediaSource = mediaSource;
  20691. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  20692. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  20693. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  20694. this.audioTimestampOffset_ = 0;
  20695. this.videoTimestampOffset_ = 0;
  20696. this.queue = [];
  20697. this.queuePending = {
  20698. audio: null,
  20699. video: null
  20700. };
  20701. this.delayedAudioAppendQueue_ = [];
  20702. this.videoAppendQueued_ = false;
  20703. this.codecs = {};
  20704. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  20705. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  20706. this.onVideoError_ = e => {
  20707. // used for debugging
  20708. this.videoError_ = e;
  20709. };
  20710. this.onAudioError_ = e => {
  20711. // used for debugging
  20712. this.audioError_ = e;
  20713. };
  20714. this.createdSourceBuffers_ = false;
  20715. this.initializedEme_ = false;
  20716. this.triggeredReady_ = false;
  20717. }
  20718. initializedEme() {
  20719. this.initializedEme_ = true;
  20720. this.triggerReady();
  20721. }
  20722. hasCreatedSourceBuffers() {
  20723. // if false, likely waiting on one of the segment loaders to get enough data to create
  20724. // source buffers
  20725. return this.createdSourceBuffers_;
  20726. }
  20727. hasInitializedAnyEme() {
  20728. return this.initializedEme_;
  20729. }
  20730. ready() {
  20731. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  20732. }
  20733. createSourceBuffers(codecs) {
  20734. if (this.hasCreatedSourceBuffers()) {
  20735. // already created them before
  20736. return;
  20737. } // the intial addOrChangeSourceBuffers will always be
  20738. // two add buffers.
  20739. this.addOrChangeSourceBuffers(codecs);
  20740. this.createdSourceBuffers_ = true;
  20741. this.trigger('createdsourcebuffers');
  20742. this.triggerReady();
  20743. }
  20744. triggerReady() {
  20745. // only allow ready to be triggered once, this prevents the case
  20746. // where:
  20747. // 1. we trigger createdsourcebuffers
  20748. // 2. ie 11 synchronously initializates eme
  20749. // 3. the synchronous initialization causes us to trigger ready
  20750. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  20751. if (this.ready() && !this.triggeredReady_) {
  20752. this.triggeredReady_ = true;
  20753. this.trigger('ready');
  20754. }
  20755. }
  20756. /**
  20757. * Add a type of source buffer to the media source.
  20758. *
  20759. * @param {string} type
  20760. * The type of source buffer to add.
  20761. *
  20762. * @param {string} codec
  20763. * The codec to add the source buffer with.
  20764. */
  20765. addSourceBuffer(type, codec) {
  20766. pushQueue({
  20767. type: 'mediaSource',
  20768. sourceUpdater: this,
  20769. action: actions.addSourceBuffer(type, codec),
  20770. name: 'addSourceBuffer'
  20771. });
  20772. }
  20773. /**
  20774. * call abort on a source buffer.
  20775. *
  20776. * @param {string} type
  20777. * The type of source buffer to call abort on.
  20778. */
  20779. abort(type) {
  20780. pushQueue({
  20781. type,
  20782. sourceUpdater: this,
  20783. action: actions.abort(type),
  20784. name: 'abort'
  20785. });
  20786. }
  20787. /**
  20788. * Call removeSourceBuffer and remove a specific type
  20789. * of source buffer on the mediaSource.
  20790. *
  20791. * @param {string} type
  20792. * The type of source buffer to remove.
  20793. */
  20794. removeSourceBuffer(type) {
  20795. if (!this.canRemoveSourceBuffer()) {
  20796. videojs__default["default"].log.error('removeSourceBuffer is not supported!');
  20797. return;
  20798. }
  20799. pushQueue({
  20800. type: 'mediaSource',
  20801. sourceUpdater: this,
  20802. action: actions.removeSourceBuffer(type),
  20803. name: 'removeSourceBuffer'
  20804. });
  20805. }
  20806. /**
  20807. * Whether or not the removeSourceBuffer function is supported
  20808. * on the mediaSource.
  20809. *
  20810. * @return {boolean}
  20811. * if removeSourceBuffer can be called.
  20812. */
  20813. canRemoveSourceBuffer() {
  20814. // IE reports that it supports removeSourceBuffer, but often throws
  20815. // errors when attempting to use the function. So we report that it
  20816. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  20817. // throws errors, so we report that it does not support this as well.
  20818. return !videojs__default["default"].browser.IE_VERSION && !videojs__default["default"].browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  20819. }
  20820. /**
  20821. * Whether or not the changeType function is supported
  20822. * on our SourceBuffers.
  20823. *
  20824. * @return {boolean}
  20825. * if changeType can be called.
  20826. */
  20827. static canChangeType() {
  20828. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  20829. }
  20830. /**
  20831. * Whether or not the changeType function is supported
  20832. * on our SourceBuffers.
  20833. *
  20834. * @return {boolean}
  20835. * if changeType can be called.
  20836. */
  20837. canChangeType() {
  20838. return this.constructor.canChangeType();
  20839. }
  20840. /**
  20841. * Call the changeType function on a source buffer, given the code and type.
  20842. *
  20843. * @param {string} type
  20844. * The type of source buffer to call changeType on.
  20845. *
  20846. * @param {string} codec
  20847. * The codec string to change type with on the source buffer.
  20848. */
  20849. changeType(type, codec) {
  20850. if (!this.canChangeType()) {
  20851. videojs__default["default"].log.error('changeType is not supported!');
  20852. return;
  20853. }
  20854. pushQueue({
  20855. type,
  20856. sourceUpdater: this,
  20857. action: actions.changeType(codec),
  20858. name: 'changeType'
  20859. });
  20860. }
  20861. /**
  20862. * Add source buffers with a codec or, if they are already created,
  20863. * call changeType on source buffers using changeType.
  20864. *
  20865. * @param {Object} codecs
  20866. * Codecs to switch to
  20867. */
  20868. addOrChangeSourceBuffers(codecs) {
  20869. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  20870. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  20871. }
  20872. Object.keys(codecs).forEach(type => {
  20873. const codec = codecs[type];
  20874. if (!this.hasCreatedSourceBuffers()) {
  20875. return this.addSourceBuffer(type, codec);
  20876. }
  20877. if (this.canChangeType()) {
  20878. this.changeType(type, codec);
  20879. }
  20880. });
  20881. }
  20882. /**
  20883. * Queue an update to append an ArrayBuffer.
  20884. *
  20885. * @param {MediaObject} object containing audioBytes and/or videoBytes
  20886. * @param {Function} done the function to call when done
  20887. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  20888. */
  20889. appendBuffer(options, doneFn) {
  20890. const {
  20891. segmentInfo,
  20892. type,
  20893. bytes
  20894. } = options;
  20895. this.processedAppend_ = true;
  20896. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  20897. this.delayedAudioAppendQueue_.push([options, doneFn]);
  20898. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  20899. return;
  20900. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  20901. // not be fired. This means that the queue will be blocked until the next action
  20902. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  20903. // these errors by calling the doneFn with the specific error.
  20904. const onError = doneFn;
  20905. pushQueue({
  20906. type,
  20907. sourceUpdater: this,
  20908. action: actions.appendBuffer(bytes, segmentInfo || {
  20909. mediaIndex: -1
  20910. }, onError),
  20911. doneFn,
  20912. name: 'appendBuffer'
  20913. });
  20914. if (type === 'video') {
  20915. this.videoAppendQueued_ = true;
  20916. if (!this.delayedAudioAppendQueue_.length) {
  20917. return;
  20918. }
  20919. const queue = this.delayedAudioAppendQueue_.slice();
  20920. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  20921. this.delayedAudioAppendQueue_.length = 0;
  20922. queue.forEach(que => {
  20923. this.appendBuffer.apply(this, que);
  20924. });
  20925. }
  20926. }
  20927. /**
  20928. * Get the audio buffer's buffered timerange.
  20929. *
  20930. * @return {TimeRange}
  20931. * The audio buffer's buffered time range
  20932. */
  20933. audioBuffered() {
  20934. // no media source/source buffer or it isn't in the media sources
  20935. // source buffer list
  20936. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  20937. return createTimeRanges();
  20938. }
  20939. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  20940. }
  20941. /**
  20942. * Get the video buffer's buffered timerange.
  20943. *
  20944. * @return {TimeRange}
  20945. * The video buffer's buffered time range
  20946. */
  20947. videoBuffered() {
  20948. // no media source/source buffer or it isn't in the media sources
  20949. // source buffer list
  20950. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  20951. return createTimeRanges();
  20952. }
  20953. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  20954. }
  20955. /**
  20956. * Get a combined video/audio buffer's buffered timerange.
  20957. *
  20958. * @return {TimeRange}
  20959. * the combined time range
  20960. */
  20961. buffered() {
  20962. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  20963. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  20964. if (audio && !video) {
  20965. return this.audioBuffered();
  20966. }
  20967. if (video && !audio) {
  20968. return this.videoBuffered();
  20969. }
  20970. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  20971. }
  20972. /**
  20973. * Add a callback to the queue that will set duration on the mediaSource.
  20974. *
  20975. * @param {number} duration
  20976. * The duration to set
  20977. *
  20978. * @param {Function} [doneFn]
  20979. * function to run after duration has been set.
  20980. */
  20981. setDuration(duration, doneFn = noop) {
  20982. // In order to set the duration on the media source, it's necessary to wait for all
  20983. // source buffers to no longer be updating. "If the updating attribute equals true on
  20984. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  20985. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  20986. pushQueue({
  20987. type: 'mediaSource',
  20988. sourceUpdater: this,
  20989. action: actions.duration(duration),
  20990. name: 'duration',
  20991. doneFn
  20992. });
  20993. }
  20994. /**
  20995. * Add a mediaSource endOfStream call to the queue
  20996. *
  20997. * @param {Error} [error]
  20998. * Call endOfStream with an error
  20999. *
  21000. * @param {Function} [doneFn]
  21001. * A function that should be called when the
  21002. * endOfStream call has finished.
  21003. */
  21004. endOfStream(error = null, doneFn = noop) {
  21005. if (typeof error !== 'string') {
  21006. error = undefined;
  21007. } // In order to set the duration on the media source, it's necessary to wait for all
  21008. // source buffers to no longer be updating. "If the updating attribute equals true on
  21009. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  21010. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  21011. pushQueue({
  21012. type: 'mediaSource',
  21013. sourceUpdater: this,
  21014. action: actions.endOfStream(error),
  21015. name: 'endOfStream',
  21016. doneFn
  21017. });
  21018. }
  21019. /**
  21020. * Queue an update to remove a time range from the buffer.
  21021. *
  21022. * @param {number} start where to start the removal
  21023. * @param {number} end where to end the removal
  21024. * @param {Function} [done=noop] optional callback to be executed when the remove
  21025. * operation is complete
  21026. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  21027. */
  21028. removeAudio(start, end, done = noop) {
  21029. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  21030. done();
  21031. return;
  21032. }
  21033. pushQueue({
  21034. type: 'audio',
  21035. sourceUpdater: this,
  21036. action: actions.remove(start, end),
  21037. doneFn: done,
  21038. name: 'remove'
  21039. });
  21040. }
  21041. /**
  21042. * Queue an update to remove a time range from the buffer.
  21043. *
  21044. * @param {number} start where to start the removal
  21045. * @param {number} end where to end the removal
  21046. * @param {Function} [done=noop] optional callback to be executed when the remove
  21047. * operation is complete
  21048. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  21049. */
  21050. removeVideo(start, end, done = noop) {
  21051. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  21052. done();
  21053. return;
  21054. }
  21055. pushQueue({
  21056. type: 'video',
  21057. sourceUpdater: this,
  21058. action: actions.remove(start, end),
  21059. doneFn: done,
  21060. name: 'remove'
  21061. });
  21062. }
  21063. /**
  21064. * Whether the underlying sourceBuffer is updating or not
  21065. *
  21066. * @return {boolean} the updating status of the SourceBuffer
  21067. */
  21068. updating() {
  21069. // the audio/video source buffer is updating
  21070. if (updating('audio', this) || updating('video', this)) {
  21071. return true;
  21072. }
  21073. return false;
  21074. }
  21075. /**
  21076. * Set/get the timestampoffset on the audio SourceBuffer
  21077. *
  21078. * @return {number} the timestamp offset
  21079. */
  21080. audioTimestampOffset(offset) {
  21081. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  21082. this.audioTimestampOffset_ !== offset) {
  21083. pushQueue({
  21084. type: 'audio',
  21085. sourceUpdater: this,
  21086. action: actions.timestampOffset(offset),
  21087. name: 'timestampOffset'
  21088. });
  21089. this.audioTimestampOffset_ = offset;
  21090. }
  21091. return this.audioTimestampOffset_;
  21092. }
  21093. /**
  21094. * Set/get the timestampoffset on the video SourceBuffer
  21095. *
  21096. * @return {number} the timestamp offset
  21097. */
  21098. videoTimestampOffset(offset) {
  21099. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  21100. this.videoTimestampOffset !== offset) {
  21101. pushQueue({
  21102. type: 'video',
  21103. sourceUpdater: this,
  21104. action: actions.timestampOffset(offset),
  21105. name: 'timestampOffset'
  21106. });
  21107. this.videoTimestampOffset_ = offset;
  21108. }
  21109. return this.videoTimestampOffset_;
  21110. }
  21111. /**
  21112. * Add a function to the queue that will be called
  21113. * when it is its turn to run in the audio queue.
  21114. *
  21115. * @param {Function} callback
  21116. * The callback to queue.
  21117. */
  21118. audioQueueCallback(callback) {
  21119. if (!this.audioBuffer) {
  21120. return;
  21121. }
  21122. pushQueue({
  21123. type: 'audio',
  21124. sourceUpdater: this,
  21125. action: actions.callback(callback),
  21126. name: 'callback'
  21127. });
  21128. }
  21129. /**
  21130. * Add a function to the queue that will be called
  21131. * when it is its turn to run in the video queue.
  21132. *
  21133. * @param {Function} callback
  21134. * The callback to queue.
  21135. */
  21136. videoQueueCallback(callback) {
  21137. if (!this.videoBuffer) {
  21138. return;
  21139. }
  21140. pushQueue({
  21141. type: 'video',
  21142. sourceUpdater: this,
  21143. action: actions.callback(callback),
  21144. name: 'callback'
  21145. });
  21146. }
  21147. /**
  21148. * dispose of the source updater and the underlying sourceBuffer
  21149. */
  21150. dispose() {
  21151. this.trigger('dispose');
  21152. bufferTypes.forEach(type => {
  21153. this.abort(type);
  21154. if (this.canRemoveSourceBuffer()) {
  21155. this.removeSourceBuffer(type);
  21156. } else {
  21157. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  21158. }
  21159. });
  21160. this.videoAppendQueued_ = false;
  21161. this.delayedAudioAppendQueue_.length = 0;
  21162. if (this.sourceopenListener_) {
  21163. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  21164. }
  21165. this.off();
  21166. }
  21167. }
  21168. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  21169. /**
  21170. * @file vtt-segment-loader.js
  21171. */
  21172. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  21173. class NoVttJsError extends Error {
  21174. constructor() {
  21175. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  21176. }
  21177. }
  21178. /**
  21179. * An object that manages segment loading and appending.
  21180. *
  21181. * @class VTTSegmentLoader
  21182. * @param {Object} options required and optional options
  21183. * @extends videojs.EventTarget
  21184. */
  21185. class VTTSegmentLoader extends SegmentLoader {
  21186. constructor(settings, options = {}) {
  21187. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  21188. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  21189. this.mediaSource_ = null;
  21190. this.subtitlesTrack_ = null;
  21191. this.loaderType_ = 'subtitle';
  21192. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  21193. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  21194. // the sync controller leads to improper behavior.
  21195. this.shouldSaveSegmentTimingInfo_ = false;
  21196. }
  21197. createTransmuxer_() {
  21198. // don't need to transmux any subtitles
  21199. return null;
  21200. }
  21201. /**
  21202. * Indicates which time ranges are buffered
  21203. *
  21204. * @return {TimeRange}
  21205. * TimeRange object representing the current buffered ranges
  21206. */
  21207. buffered_() {
  21208. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  21209. return createTimeRanges();
  21210. }
  21211. const cues = this.subtitlesTrack_.cues;
  21212. const start = cues[0].startTime;
  21213. const end = cues[cues.length - 1].startTime;
  21214. return createTimeRanges([[start, end]]);
  21215. }
  21216. /**
  21217. * Gets and sets init segment for the provided map
  21218. *
  21219. * @param {Object} map
  21220. * The map object representing the init segment to get or set
  21221. * @param {boolean=} set
  21222. * If true, the init segment for the provided map should be saved
  21223. * @return {Object}
  21224. * map object for desired init segment
  21225. */
  21226. initSegmentForMap(map, set = false) {
  21227. if (!map) {
  21228. return null;
  21229. }
  21230. const id = initSegmentId(map);
  21231. let storedMap = this.initSegments_[id];
  21232. if (set && !storedMap && map.bytes) {
  21233. // append WebVTT line terminators to the media initialization segment if it exists
  21234. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  21235. // requires two or more WebVTT line terminators between the WebVTT header and the
  21236. // rest of the file
  21237. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  21238. const combinedSegment = new Uint8Array(combinedByteLength);
  21239. combinedSegment.set(map.bytes);
  21240. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  21241. this.initSegments_[id] = storedMap = {
  21242. resolvedUri: map.resolvedUri,
  21243. byterange: map.byterange,
  21244. bytes: combinedSegment
  21245. };
  21246. }
  21247. return storedMap || map;
  21248. }
  21249. /**
  21250. * Returns true if all configuration required for loading is present, otherwise false.
  21251. *
  21252. * @return {boolean} True if the all configuration is ready for loading
  21253. * @private
  21254. */
  21255. couldBeginLoading_() {
  21256. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  21257. }
  21258. /**
  21259. * Once all the starting parameters have been specified, begin
  21260. * operation. This method should only be invoked from the INIT
  21261. * state.
  21262. *
  21263. * @private
  21264. */
  21265. init_() {
  21266. this.state = 'READY';
  21267. this.resetEverything();
  21268. return this.monitorBuffer_();
  21269. }
  21270. /**
  21271. * Set a subtitle track on the segment loader to add subtitles to
  21272. *
  21273. * @param {TextTrack=} track
  21274. * The text track to add loaded subtitles to
  21275. * @return {TextTrack}
  21276. * Returns the subtitles track
  21277. */
  21278. track(track) {
  21279. if (typeof track === 'undefined') {
  21280. return this.subtitlesTrack_;
  21281. }
  21282. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  21283. // buffering now
  21284. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  21285. this.init_();
  21286. }
  21287. return this.subtitlesTrack_;
  21288. }
  21289. /**
  21290. * Remove any data in the source buffer between start and end times
  21291. *
  21292. * @param {number} start - the start time of the region to remove from the buffer
  21293. * @param {number} end - the end time of the region to remove from the buffer
  21294. */
  21295. remove(start, end) {
  21296. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  21297. }
  21298. /**
  21299. * fill the buffer with segements unless the sourceBuffers are
  21300. * currently updating
  21301. *
  21302. * Note: this function should only ever be called by monitorBuffer_
  21303. * and never directly
  21304. *
  21305. * @private
  21306. */
  21307. fillBuffer_() {
  21308. // see if we need to begin loading immediately
  21309. const segmentInfo = this.chooseNextRequest_();
  21310. if (!segmentInfo) {
  21311. return;
  21312. }
  21313. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  21314. // We don't have the timestamp offset that we need to sync subtitles.
  21315. // Rerun on a timestamp offset or user interaction.
  21316. const checkTimestampOffset = () => {
  21317. this.state = 'READY';
  21318. if (!this.paused()) {
  21319. // if not paused, queue a buffer check as soon as possible
  21320. this.monitorBuffer_();
  21321. }
  21322. };
  21323. this.syncController_.one('timestampoffset', checkTimestampOffset);
  21324. this.state = 'WAITING_ON_TIMELINE';
  21325. return;
  21326. }
  21327. this.loadSegment_(segmentInfo);
  21328. } // never set a timestamp offset for vtt segments.
  21329. timestampOffsetForSegment_() {
  21330. return null;
  21331. }
  21332. chooseNextRequest_() {
  21333. return this.skipEmptySegments_(super.chooseNextRequest_());
  21334. }
  21335. /**
  21336. * Prevents the segment loader from requesting segments we know contain no subtitles
  21337. * by walking forward until we find the next segment that we don't know whether it is
  21338. * empty or not.
  21339. *
  21340. * @param {Object} segmentInfo
  21341. * a segment info object that describes the current segment
  21342. * @return {Object}
  21343. * a segment info object that describes the current segment
  21344. */
  21345. skipEmptySegments_(segmentInfo) {
  21346. while (segmentInfo && segmentInfo.segment.empty) {
  21347. // stop at the last possible segmentInfo
  21348. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  21349. segmentInfo = null;
  21350. break;
  21351. }
  21352. segmentInfo = this.generateSegmentInfo_({
  21353. playlist: segmentInfo.playlist,
  21354. mediaIndex: segmentInfo.mediaIndex + 1,
  21355. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  21356. isSyncRequest: segmentInfo.isSyncRequest
  21357. });
  21358. }
  21359. return segmentInfo;
  21360. }
  21361. stopForError(error) {
  21362. this.error(error);
  21363. this.state = 'READY';
  21364. this.pause();
  21365. this.trigger('error');
  21366. }
  21367. /**
  21368. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  21369. *
  21370. * @private
  21371. */
  21372. segmentRequestFinished_(error, simpleSegment, result) {
  21373. if (!this.subtitlesTrack_) {
  21374. this.state = 'READY';
  21375. return;
  21376. }
  21377. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  21378. if (!this.pendingSegment_) {
  21379. this.state = 'READY';
  21380. this.mediaRequestsAborted += 1;
  21381. return;
  21382. }
  21383. if (error) {
  21384. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  21385. this.handleTimeout_();
  21386. }
  21387. if (error.code === REQUEST_ERRORS.ABORTED) {
  21388. this.mediaRequestsAborted += 1;
  21389. } else {
  21390. this.mediaRequestsErrored += 1;
  21391. }
  21392. this.stopForError(error);
  21393. return;
  21394. }
  21395. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  21396. // maintain functionality between segment loaders
  21397. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  21398. if (simpleSegment.key) {
  21399. this.segmentKey(simpleSegment.key, true);
  21400. }
  21401. this.state = 'APPENDING'; // used for tests
  21402. this.trigger('appending');
  21403. const segment = segmentInfo.segment;
  21404. if (segment.map) {
  21405. segment.map.bytes = simpleSegment.map.bytes;
  21406. }
  21407. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  21408. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  21409. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  21410. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  21411. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  21412. message: 'Error loading vtt.js'
  21413. }));
  21414. return;
  21415. }
  21416. segment.requested = true;
  21417. try {
  21418. this.parseVTTCues_(segmentInfo);
  21419. } catch (e) {
  21420. this.stopForError({
  21421. message: e.message
  21422. });
  21423. return;
  21424. }
  21425. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  21426. if (segmentInfo.cues.length) {
  21427. segmentInfo.timingInfo = {
  21428. start: segmentInfo.cues[0].startTime,
  21429. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  21430. };
  21431. } else {
  21432. segmentInfo.timingInfo = {
  21433. start: segmentInfo.startOfSegment,
  21434. end: segmentInfo.startOfSegment + segmentInfo.duration
  21435. };
  21436. }
  21437. if (segmentInfo.isSyncRequest) {
  21438. this.trigger('syncinfoupdate');
  21439. this.pendingSegment_ = null;
  21440. this.state = 'READY';
  21441. return;
  21442. }
  21443. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  21444. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  21445. // the subtitle track
  21446. segmentInfo.cues.forEach(cue => {
  21447. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  21448. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  21449. // cues to have identical time-intervals, but if the text is also identical
  21450. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  21451. // "overlaps" VTT segments)
  21452. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  21453. this.handleAppendsDone_();
  21454. }
  21455. handleData_() {// noop as we shouldn't be getting video/audio data captions
  21456. // that we do not support here.
  21457. }
  21458. updateTimingInfoEnd_() {// noop
  21459. }
  21460. /**
  21461. * Uses the WebVTT parser to parse the segment response
  21462. *
  21463. * @throws NoVttJsError
  21464. *
  21465. * @param {Object} segmentInfo
  21466. * a segment info object that describes the current segment
  21467. * @private
  21468. */
  21469. parseVTTCues_(segmentInfo) {
  21470. let decoder;
  21471. let decodeBytesToString = false;
  21472. if (typeof window.WebVTT !== 'function') {
  21473. // caller is responsible for exception handling.
  21474. throw new NoVttJsError();
  21475. }
  21476. if (typeof window.TextDecoder === 'function') {
  21477. decoder = new window.TextDecoder('utf8');
  21478. } else {
  21479. decoder = window.WebVTT.StringDecoder();
  21480. decodeBytesToString = true;
  21481. }
  21482. const parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  21483. segmentInfo.cues = [];
  21484. segmentInfo.timestampmap = {
  21485. MPEGTS: 0,
  21486. LOCAL: 0
  21487. };
  21488. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  21489. parser.ontimestampmap = map => {
  21490. segmentInfo.timestampmap = map;
  21491. };
  21492. parser.onparsingerror = error => {
  21493. videojs__default["default"].log.warn('Error encountered when parsing cues: ' + error.message);
  21494. };
  21495. if (segmentInfo.segment.map) {
  21496. let mapData = segmentInfo.segment.map.bytes;
  21497. if (decodeBytesToString) {
  21498. mapData = uint8ToUtf8(mapData);
  21499. }
  21500. parser.parse(mapData);
  21501. }
  21502. let segmentData = segmentInfo.bytes;
  21503. if (decodeBytesToString) {
  21504. segmentData = uint8ToUtf8(segmentData);
  21505. }
  21506. parser.parse(segmentData);
  21507. parser.flush();
  21508. }
  21509. /**
  21510. * Updates the start and end times of any cues parsed by the WebVTT parser using
  21511. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  21512. * from the SyncController
  21513. *
  21514. * @param {Object} segmentInfo
  21515. * a segment info object that describes the current segment
  21516. * @param {Object} mappingObj
  21517. * object containing a mapping from TS to media time
  21518. * @param {Object} playlist
  21519. * the playlist object containing the segment
  21520. * @private
  21521. */
  21522. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  21523. const segment = segmentInfo.segment;
  21524. if (!mappingObj) {
  21525. // If the sync controller does not have a mapping of TS to Media Time for the
  21526. // timeline, then we don't have enough information to update the cue
  21527. // start/end times
  21528. return;
  21529. }
  21530. if (!segmentInfo.cues.length) {
  21531. // If there are no cues, we also do not have enough information to figure out
  21532. // segment timing. Mark that the segment contains no cues so we don't re-request
  21533. // an empty segment.
  21534. segment.empty = true;
  21535. return;
  21536. }
  21537. const timestampmap = segmentInfo.timestampmap;
  21538. const diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  21539. segmentInfo.cues.forEach(cue => {
  21540. // First convert cue time to TS time using the timestamp-map provided within the vtt
  21541. cue.startTime += diff;
  21542. cue.endTime += diff;
  21543. });
  21544. if (!playlist.syncInfo) {
  21545. const firstStart = segmentInfo.cues[0].startTime;
  21546. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  21547. playlist.syncInfo = {
  21548. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  21549. time: Math.min(firstStart, lastStart - segment.duration)
  21550. };
  21551. }
  21552. }
  21553. }
  21554. /**
  21555. * @file ad-cue-tags.js
  21556. */
  21557. /**
  21558. * Searches for an ad cue that overlaps with the given mediaTime
  21559. *
  21560. * @param {Object} track
  21561. * the track to find the cue for
  21562. *
  21563. * @param {number} mediaTime
  21564. * the time to find the cue at
  21565. *
  21566. * @return {Object|null}
  21567. * the found cue or null
  21568. */
  21569. const findAdCue = function (track, mediaTime) {
  21570. const cues = track.cues;
  21571. for (let i = 0; i < cues.length; i++) {
  21572. const cue = cues[i];
  21573. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  21574. return cue;
  21575. }
  21576. }
  21577. return null;
  21578. };
  21579. const updateAdCues = function (media, track, offset = 0) {
  21580. if (!media.segments) {
  21581. return;
  21582. }
  21583. let mediaTime = offset;
  21584. let cue;
  21585. for (let i = 0; i < media.segments.length; i++) {
  21586. const segment = media.segments[i];
  21587. if (!cue) {
  21588. // Since the cues will span for at least the segment duration, adding a fudge
  21589. // factor of half segment duration will prevent duplicate cues from being
  21590. // created when timing info is not exact (e.g. cue start time initialized
  21591. // at 10.006677, but next call mediaTime is 10.003332 )
  21592. cue = findAdCue(track, mediaTime + segment.duration / 2);
  21593. }
  21594. if (cue) {
  21595. if ('cueIn' in segment) {
  21596. // Found a CUE-IN so end the cue
  21597. cue.endTime = mediaTime;
  21598. cue.adEndTime = mediaTime;
  21599. mediaTime += segment.duration;
  21600. cue = null;
  21601. continue;
  21602. }
  21603. if (mediaTime < cue.endTime) {
  21604. // Already processed this mediaTime for this cue
  21605. mediaTime += segment.duration;
  21606. continue;
  21607. } // otherwise extend cue until a CUE-IN is found
  21608. cue.endTime += segment.duration;
  21609. } else {
  21610. if ('cueOut' in segment) {
  21611. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  21612. cue.adStartTime = mediaTime; // Assumes tag format to be
  21613. // #EXT-X-CUE-OUT:30
  21614. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  21615. track.addCue(cue);
  21616. }
  21617. if ('cueOutCont' in segment) {
  21618. // Entered into the middle of an ad cue
  21619. // Assumes tag formate to be
  21620. // #EXT-X-CUE-OUT-CONT:10/30
  21621. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  21622. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  21623. cue.adStartTime = mediaTime - adOffset;
  21624. cue.adEndTime = cue.adStartTime + adTotal;
  21625. track.addCue(cue);
  21626. }
  21627. }
  21628. mediaTime += segment.duration;
  21629. }
  21630. };
  21631. /**
  21632. * @file sync-controller.js
  21633. */
  21634. // synchronize expired playlist segments.
  21635. // the max media sequence diff is 48 hours of live stream
  21636. // content with two second segments. Anything larger than that
  21637. // will likely be invalid.
  21638. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  21639. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  21640. // the equivalence display-time 0 === segment-index 0
  21641. {
  21642. name: 'VOD',
  21643. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21644. if (duration !== Infinity) {
  21645. const syncPoint = {
  21646. time: 0,
  21647. segmentIndex: 0,
  21648. partIndex: null
  21649. };
  21650. return syncPoint;
  21651. }
  21652. return null;
  21653. }
  21654. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  21655. {
  21656. name: 'ProgramDateTime',
  21657. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21658. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  21659. return null;
  21660. }
  21661. let syncPoint = null;
  21662. let lastDistance = null;
  21663. const partsAndSegments = getPartsAndSegments(playlist);
  21664. currentTime = currentTime || 0;
  21665. for (let i = 0; i < partsAndSegments.length; i++) {
  21666. // start from the end and loop backwards for live
  21667. // or start from the front and loop forwards for non-live
  21668. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  21669. const partAndSegment = partsAndSegments[index];
  21670. const segment = partAndSegment.segment;
  21671. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  21672. if (!datetimeMapping || !segment.dateTimeObject) {
  21673. continue;
  21674. }
  21675. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  21676. let start = segmentTime + datetimeMapping; // take part duration into account.
  21677. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  21678. for (let z = 0; z < partAndSegment.partIndex; z++) {
  21679. start += segment.parts[z].duration;
  21680. }
  21681. }
  21682. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  21683. // currentTime and can stop looking for better candidates
  21684. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  21685. break;
  21686. }
  21687. lastDistance = distance;
  21688. syncPoint = {
  21689. time: start,
  21690. segmentIndex: partAndSegment.segmentIndex,
  21691. partIndex: partAndSegment.partIndex
  21692. };
  21693. }
  21694. return syncPoint;
  21695. }
  21696. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  21697. // segment in the current timeline with timing data
  21698. {
  21699. name: 'Segment',
  21700. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21701. let syncPoint = null;
  21702. let lastDistance = null;
  21703. currentTime = currentTime || 0;
  21704. const partsAndSegments = getPartsAndSegments(playlist);
  21705. for (let i = 0; i < partsAndSegments.length; i++) {
  21706. // start from the end and loop backwards for live
  21707. // or start from the front and loop forwards for non-live
  21708. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  21709. const partAndSegment = partsAndSegments[index];
  21710. const segment = partAndSegment.segment;
  21711. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  21712. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  21713. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  21714. // currentTime and can stop looking for better candidates
  21715. if (lastDistance !== null && lastDistance < distance) {
  21716. break;
  21717. }
  21718. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  21719. lastDistance = distance;
  21720. syncPoint = {
  21721. time: start,
  21722. segmentIndex: partAndSegment.segmentIndex,
  21723. partIndex: partAndSegment.partIndex
  21724. };
  21725. }
  21726. }
  21727. }
  21728. return syncPoint;
  21729. }
  21730. }, // Stategy "Discontinuity": We have a discontinuity with a known
  21731. // display-time
  21732. {
  21733. name: 'Discontinuity',
  21734. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21735. let syncPoint = null;
  21736. currentTime = currentTime || 0;
  21737. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  21738. let lastDistance = null;
  21739. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  21740. const segmentIndex = playlist.discontinuityStarts[i];
  21741. const discontinuity = playlist.discontinuitySequence + i + 1;
  21742. const discontinuitySync = syncController.discontinuities[discontinuity];
  21743. if (discontinuitySync) {
  21744. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  21745. // currentTime and can stop looking for better candidates
  21746. if (lastDistance !== null && lastDistance < distance) {
  21747. break;
  21748. }
  21749. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  21750. lastDistance = distance;
  21751. syncPoint = {
  21752. time: discontinuitySync.time,
  21753. segmentIndex,
  21754. partIndex: null
  21755. };
  21756. }
  21757. }
  21758. }
  21759. }
  21760. return syncPoint;
  21761. }
  21762. }, // Stategy "Playlist": We have a playlist with a known mapping of
  21763. // segment index to display time
  21764. {
  21765. name: 'Playlist',
  21766. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  21767. if (playlist.syncInfo) {
  21768. const syncPoint = {
  21769. time: playlist.syncInfo.time,
  21770. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  21771. partIndex: null
  21772. };
  21773. return syncPoint;
  21774. }
  21775. return null;
  21776. }
  21777. }];
  21778. class SyncController extends videojs__default["default"].EventTarget {
  21779. constructor(options = {}) {
  21780. super(); // ...for synching across variants
  21781. this.timelines = [];
  21782. this.discontinuities = [];
  21783. this.timelineToDatetimeMappings = {};
  21784. this.logger_ = logger('SyncController');
  21785. }
  21786. /**
  21787. * Find a sync-point for the playlist specified
  21788. *
  21789. * A sync-point is defined as a known mapping from display-time to
  21790. * a segment-index in the current playlist.
  21791. *
  21792. * @param {Playlist} playlist
  21793. * The playlist that needs a sync-point
  21794. * @param {number} duration
  21795. * Duration of the MediaSource (Infinite if playing a live source)
  21796. * @param {number} currentTimeline
  21797. * The last timeline from which a segment was loaded
  21798. * @return {Object}
  21799. * A sync-point object
  21800. */
  21801. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  21802. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  21803. if (!syncPoints.length) {
  21804. // Signal that we need to attempt to get a sync-point manually
  21805. // by fetching a segment in the playlist and constructing
  21806. // a sync-point from that information
  21807. return null;
  21808. } // Now find the sync-point that is closest to the currentTime because
  21809. // that should result in the most accurate guess about which segment
  21810. // to fetch
  21811. return this.selectSyncPoint_(syncPoints, {
  21812. key: 'time',
  21813. value: currentTime
  21814. });
  21815. }
  21816. /**
  21817. * Calculate the amount of time that has expired off the playlist during playback
  21818. *
  21819. * @param {Playlist} playlist
  21820. * Playlist object to calculate expired from
  21821. * @param {number} duration
  21822. * Duration of the MediaSource (Infinity if playling a live source)
  21823. * @return {number|null}
  21824. * The amount of time that has expired off the playlist during playback. Null
  21825. * if no sync-points for the playlist can be found.
  21826. */
  21827. getExpiredTime(playlist, duration) {
  21828. if (!playlist || !playlist.segments) {
  21829. return null;
  21830. }
  21831. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  21832. if (!syncPoints.length) {
  21833. return null;
  21834. }
  21835. const syncPoint = this.selectSyncPoint_(syncPoints, {
  21836. key: 'segmentIndex',
  21837. value: 0
  21838. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  21839. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  21840. if (syncPoint.segmentIndex > 0) {
  21841. syncPoint.time *= -1;
  21842. }
  21843. return Math.abs(syncPoint.time + sumDurations({
  21844. defaultDuration: playlist.targetDuration,
  21845. durationList: playlist.segments,
  21846. startIndex: syncPoint.segmentIndex,
  21847. endIndex: 0
  21848. }));
  21849. }
  21850. /**
  21851. * Runs each sync-point strategy and returns a list of sync-points returned by the
  21852. * strategies
  21853. *
  21854. * @private
  21855. * @param {Playlist} playlist
  21856. * The playlist that needs a sync-point
  21857. * @param {number} duration
  21858. * Duration of the MediaSource (Infinity if playing a live source)
  21859. * @param {number} currentTimeline
  21860. * The last timeline from which a segment was loaded
  21861. * @return {Array}
  21862. * A list of sync-point objects
  21863. */
  21864. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  21865. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  21866. for (let i = 0; i < syncPointStrategies.length; i++) {
  21867. const strategy = syncPointStrategies[i];
  21868. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  21869. if (syncPoint) {
  21870. syncPoint.strategy = strategy.name;
  21871. syncPoints.push({
  21872. strategy: strategy.name,
  21873. syncPoint
  21874. });
  21875. }
  21876. }
  21877. return syncPoints;
  21878. }
  21879. /**
  21880. * Selects the sync-point nearest the specified target
  21881. *
  21882. * @private
  21883. * @param {Array} syncPoints
  21884. * List of sync-points to select from
  21885. * @param {Object} target
  21886. * Object specifying the property and value we are targeting
  21887. * @param {string} target.key
  21888. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  21889. * @param {number} target.value
  21890. * The value to target for the specified key.
  21891. * @return {Object}
  21892. * The sync-point nearest the target
  21893. */
  21894. selectSyncPoint_(syncPoints, target) {
  21895. let bestSyncPoint = syncPoints[0].syncPoint;
  21896. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  21897. let bestStrategy = syncPoints[0].strategy;
  21898. for (let i = 1; i < syncPoints.length; i++) {
  21899. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  21900. if (newDistance < bestDistance) {
  21901. bestDistance = newDistance;
  21902. bestSyncPoint = syncPoints[i].syncPoint;
  21903. bestStrategy = syncPoints[i].strategy;
  21904. }
  21905. }
  21906. 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}` : '') + ']');
  21907. return bestSyncPoint;
  21908. }
  21909. /**
  21910. * Save any meta-data present on the segments when segments leave
  21911. * the live window to the playlist to allow for synchronization at the
  21912. * playlist level later.
  21913. *
  21914. * @param {Playlist} oldPlaylist - The previous active playlist
  21915. * @param {Playlist} newPlaylist - The updated and most current playlist
  21916. */
  21917. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  21918. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  21919. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  21920. videojs__default["default"].log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  21921. return;
  21922. } // When a segment expires from the playlist and it has a start time
  21923. // save that information as a possible sync-point reference in future
  21924. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  21925. const lastRemovedSegment = oldPlaylist.segments[i];
  21926. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  21927. newPlaylist.syncInfo = {
  21928. mediaSequence: oldPlaylist.mediaSequence + i,
  21929. time: lastRemovedSegment.start
  21930. };
  21931. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  21932. this.trigger('syncinfoupdate');
  21933. break;
  21934. }
  21935. }
  21936. }
  21937. /**
  21938. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  21939. * before segments start to load.
  21940. *
  21941. * @param {Playlist} playlist - The currently active playlist
  21942. */
  21943. setDateTimeMappingForStart(playlist) {
  21944. // It's possible for the playlist to be updated before playback starts, meaning time
  21945. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  21946. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  21947. // unless the mappings are cleared.
  21948. this.timelineToDatetimeMappings = {};
  21949. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  21950. const firstSegment = playlist.segments[0];
  21951. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  21952. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  21953. }
  21954. }
  21955. /**
  21956. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  21957. * based on the latest timing information.
  21958. *
  21959. * @param {Object} options
  21960. * Options object
  21961. * @param {SegmentInfo} options.segmentInfo
  21962. * The current active request information
  21963. * @param {boolean} options.shouldSaveTimelineMapping
  21964. * If there's a timeline change, determines if the timeline mapping should be
  21965. * saved for timeline mapping and program date time mappings.
  21966. */
  21967. saveSegmentTimingInfo({
  21968. segmentInfo,
  21969. shouldSaveTimelineMapping
  21970. }) {
  21971. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  21972. const segment = segmentInfo.segment;
  21973. if (didCalculateSegmentTimeMapping) {
  21974. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  21975. // now with segment timing information
  21976. if (!segmentInfo.playlist.syncInfo) {
  21977. segmentInfo.playlist.syncInfo = {
  21978. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  21979. time: segment.start
  21980. };
  21981. }
  21982. }
  21983. const dateTime = segment.dateTimeObject;
  21984. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  21985. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  21986. }
  21987. }
  21988. timestampOffsetForTimeline(timeline) {
  21989. if (typeof this.timelines[timeline] === 'undefined') {
  21990. return null;
  21991. }
  21992. return this.timelines[timeline].time;
  21993. }
  21994. mappingForTimeline(timeline) {
  21995. if (typeof this.timelines[timeline] === 'undefined') {
  21996. return null;
  21997. }
  21998. return this.timelines[timeline].mapping;
  21999. }
  22000. /**
  22001. * Use the "media time" for a segment to generate a mapping to "display time" and
  22002. * save that display time to the segment.
  22003. *
  22004. * @private
  22005. * @param {SegmentInfo} segmentInfo
  22006. * The current active request information
  22007. * @param {Object} timingInfo
  22008. * The start and end time of the current segment in "media time"
  22009. * @param {boolean} shouldSaveTimelineMapping
  22010. * If there's a timeline change, determines if the timeline mapping should be
  22011. * saved in timelines.
  22012. * @return {boolean}
  22013. * Returns false if segment time mapping could not be calculated
  22014. */
  22015. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  22016. // TODO: remove side effects
  22017. const segment = segmentInfo.segment;
  22018. const part = segmentInfo.part;
  22019. let mappingObj = this.timelines[segmentInfo.timeline];
  22020. let start;
  22021. let end;
  22022. if (typeof segmentInfo.timestampOffset === 'number') {
  22023. mappingObj = {
  22024. time: segmentInfo.startOfSegment,
  22025. mapping: segmentInfo.startOfSegment - timingInfo.start
  22026. };
  22027. if (shouldSaveTimelineMapping) {
  22028. this.timelines[segmentInfo.timeline] = mappingObj;
  22029. this.trigger('timestampoffset');
  22030. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  22031. }
  22032. start = segmentInfo.startOfSegment;
  22033. end = timingInfo.end + mappingObj.mapping;
  22034. } else if (mappingObj) {
  22035. start = timingInfo.start + mappingObj.mapping;
  22036. end = timingInfo.end + mappingObj.mapping;
  22037. } else {
  22038. return false;
  22039. }
  22040. if (part) {
  22041. part.start = start;
  22042. part.end = end;
  22043. } // If we don't have a segment start yet or the start value we got
  22044. // is less than our current segment.start value, save a new start value.
  22045. // We have to do this because parts will have segment timing info saved
  22046. // multiple times and we want segment start to be the earliest part start
  22047. // value for that segment.
  22048. if (!segment.start || start < segment.start) {
  22049. segment.start = start;
  22050. }
  22051. segment.end = end;
  22052. return true;
  22053. }
  22054. /**
  22055. * Each time we have discontinuity in the playlist, attempt to calculate the location
  22056. * in display of the start of the discontinuity and save that. We also save an accuracy
  22057. * value so that we save values with the most accuracy (closest to 0.)
  22058. *
  22059. * @private
  22060. * @param {SegmentInfo} segmentInfo - The current active request information
  22061. */
  22062. saveDiscontinuitySyncInfo_(segmentInfo) {
  22063. const playlist = segmentInfo.playlist;
  22064. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  22065. // the start of the range and it's accuracy is 0 (greater accuracy values
  22066. // mean more approximation)
  22067. if (segment.discontinuity) {
  22068. this.discontinuities[segment.timeline] = {
  22069. time: segment.start,
  22070. accuracy: 0
  22071. };
  22072. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  22073. // Search for future discontinuities that we can provide better timing
  22074. // information for and save that information for sync purposes
  22075. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  22076. const segmentIndex = playlist.discontinuityStarts[i];
  22077. const discontinuity = playlist.discontinuitySequence + i + 1;
  22078. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  22079. const accuracy = Math.abs(mediaIndexDiff);
  22080. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  22081. let time;
  22082. if (mediaIndexDiff < 0) {
  22083. time = segment.start - sumDurations({
  22084. defaultDuration: playlist.targetDuration,
  22085. durationList: playlist.segments,
  22086. startIndex: segmentInfo.mediaIndex,
  22087. endIndex: segmentIndex
  22088. });
  22089. } else {
  22090. time = segment.end + sumDurations({
  22091. defaultDuration: playlist.targetDuration,
  22092. durationList: playlist.segments,
  22093. startIndex: segmentInfo.mediaIndex + 1,
  22094. endIndex: segmentIndex
  22095. });
  22096. }
  22097. this.discontinuities[discontinuity] = {
  22098. time,
  22099. accuracy
  22100. };
  22101. }
  22102. }
  22103. }
  22104. }
  22105. dispose() {
  22106. this.trigger('dispose');
  22107. this.off();
  22108. }
  22109. }
  22110. /**
  22111. * The TimelineChangeController acts as a source for segment loaders to listen for and
  22112. * keep track of latest and pending timeline changes. This is useful to ensure proper
  22113. * sync, as each loader may need to make a consideration for what timeline the other
  22114. * loader is on before making changes which could impact the other loader's media.
  22115. *
  22116. * @class TimelineChangeController
  22117. * @extends videojs.EventTarget
  22118. */
  22119. class TimelineChangeController extends videojs__default["default"].EventTarget {
  22120. constructor() {
  22121. super();
  22122. this.pendingTimelineChanges_ = {};
  22123. this.lastTimelineChanges_ = {};
  22124. }
  22125. clearPendingTimelineChange(type) {
  22126. this.pendingTimelineChanges_[type] = null;
  22127. this.trigger('pendingtimelinechange');
  22128. }
  22129. pendingTimelineChange({
  22130. type,
  22131. from,
  22132. to
  22133. }) {
  22134. if (typeof from === 'number' && typeof to === 'number') {
  22135. this.pendingTimelineChanges_[type] = {
  22136. type,
  22137. from,
  22138. to
  22139. };
  22140. this.trigger('pendingtimelinechange');
  22141. }
  22142. return this.pendingTimelineChanges_[type];
  22143. }
  22144. lastTimelineChange({
  22145. type,
  22146. from,
  22147. to
  22148. }) {
  22149. if (typeof from === 'number' && typeof to === 'number') {
  22150. this.lastTimelineChanges_[type] = {
  22151. type,
  22152. from,
  22153. to
  22154. };
  22155. delete this.pendingTimelineChanges_[type];
  22156. this.trigger('timelinechange');
  22157. }
  22158. return this.lastTimelineChanges_[type];
  22159. }
  22160. dispose() {
  22161. this.trigger('dispose');
  22162. this.pendingTimelineChanges_ = {};
  22163. this.lastTimelineChanges_ = {};
  22164. this.off();
  22165. }
  22166. }
  22167. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  22168. const workerCode = transform(function (self) {
  22169. /**
  22170. * @file stream.js
  22171. */
  22172. /**
  22173. * A lightweight readable stream implemention that handles event dispatching.
  22174. *
  22175. * @class Stream
  22176. */
  22177. var Stream = /*#__PURE__*/function () {
  22178. function Stream() {
  22179. this.listeners = {};
  22180. }
  22181. /**
  22182. * Add a listener for a specified event type.
  22183. *
  22184. * @param {string} type the event name
  22185. * @param {Function} listener the callback to be invoked when an event of
  22186. * the specified type occurs
  22187. */
  22188. var _proto = Stream.prototype;
  22189. _proto.on = function on(type, listener) {
  22190. if (!this.listeners[type]) {
  22191. this.listeners[type] = [];
  22192. }
  22193. this.listeners[type].push(listener);
  22194. }
  22195. /**
  22196. * Remove a listener for a specified event type.
  22197. *
  22198. * @param {string} type the event name
  22199. * @param {Function} listener a function previously registered for this
  22200. * type of event through `on`
  22201. * @return {boolean} if we could turn it off or not
  22202. */
  22203. ;
  22204. _proto.off = function off(type, listener) {
  22205. if (!this.listeners[type]) {
  22206. return false;
  22207. }
  22208. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  22209. // In Video.js we slice listener functions
  22210. // on trigger so that it does not mess up the order
  22211. // while we loop through.
  22212. //
  22213. // Here we slice on off so that the loop in trigger
  22214. // can continue using it's old reference to loop without
  22215. // messing up the order.
  22216. this.listeners[type] = this.listeners[type].slice(0);
  22217. this.listeners[type].splice(index, 1);
  22218. return index > -1;
  22219. }
  22220. /**
  22221. * Trigger an event of the specified type on this stream. Any additional
  22222. * arguments to this function are passed as parameters to event listeners.
  22223. *
  22224. * @param {string} type the event name
  22225. */
  22226. ;
  22227. _proto.trigger = function trigger(type) {
  22228. var callbacks = this.listeners[type];
  22229. if (!callbacks) {
  22230. return;
  22231. } // Slicing the arguments on every invocation of this method
  22232. // can add a significant amount of overhead. Avoid the
  22233. // intermediate object creation for the common case of a
  22234. // single callback argument
  22235. if (arguments.length === 2) {
  22236. var length = callbacks.length;
  22237. for (var i = 0; i < length; ++i) {
  22238. callbacks[i].call(this, arguments[1]);
  22239. }
  22240. } else {
  22241. var args = Array.prototype.slice.call(arguments, 1);
  22242. var _length = callbacks.length;
  22243. for (var _i = 0; _i < _length; ++_i) {
  22244. callbacks[_i].apply(this, args);
  22245. }
  22246. }
  22247. }
  22248. /**
  22249. * Destroys the stream and cleans up.
  22250. */
  22251. ;
  22252. _proto.dispose = function dispose() {
  22253. this.listeners = {};
  22254. }
  22255. /**
  22256. * Forwards all `data` events on this stream to the destination stream. The
  22257. * destination stream should provide a method `push` to receive the data
  22258. * events as they arrive.
  22259. *
  22260. * @param {Stream} destination the stream that will receive all `data` events
  22261. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  22262. */
  22263. ;
  22264. _proto.pipe = function pipe(destination) {
  22265. this.on('data', function (data) {
  22266. destination.push(data);
  22267. });
  22268. };
  22269. return Stream;
  22270. }();
  22271. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  22272. /**
  22273. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  22274. *
  22275. * @param padded {Uint8Array} unencrypted bytes that have been padded
  22276. * @return {Uint8Array} the unpadded bytes
  22277. * @see http://tools.ietf.org/html/rfc5652
  22278. */
  22279. function unpad(padded) {
  22280. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  22281. }
  22282. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  22283. /**
  22284. * @file aes.js
  22285. *
  22286. * This file contains an adaptation of the AES decryption algorithm
  22287. * from the Standford Javascript Cryptography Library. That work is
  22288. * covered by the following copyright and permissions notice:
  22289. *
  22290. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  22291. * All rights reserved.
  22292. *
  22293. * Redistribution and use in source and binary forms, with or without
  22294. * modification, are permitted provided that the following conditions are
  22295. * met:
  22296. *
  22297. * 1. Redistributions of source code must retain the above copyright
  22298. * notice, this list of conditions and the following disclaimer.
  22299. *
  22300. * 2. Redistributions in binary form must reproduce the above
  22301. * copyright notice, this list of conditions and the following
  22302. * disclaimer in the documentation and/or other materials provided
  22303. * with the distribution.
  22304. *
  22305. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  22306. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22307. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  22308. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  22309. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22310. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22311. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  22312. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  22313. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  22314. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  22315. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22316. *
  22317. * The views and conclusions contained in the software and documentation
  22318. * are those of the authors and should not be interpreted as representing
  22319. * official policies, either expressed or implied, of the authors.
  22320. */
  22321. /**
  22322. * Expand the S-box tables.
  22323. *
  22324. * @private
  22325. */
  22326. const precompute = function () {
  22327. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  22328. const encTable = tables[0];
  22329. const decTable = tables[1];
  22330. const sbox = encTable[4];
  22331. const sboxInv = decTable[4];
  22332. let i;
  22333. let x;
  22334. let xInv;
  22335. const d = [];
  22336. const th = [];
  22337. let x2;
  22338. let x4;
  22339. let x8;
  22340. let s;
  22341. let tEnc;
  22342. let tDec; // Compute double and third tables
  22343. for (i = 0; i < 256; i++) {
  22344. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  22345. }
  22346. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  22347. // Compute sbox
  22348. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  22349. s = s >> 8 ^ s & 255 ^ 99;
  22350. sbox[x] = s;
  22351. sboxInv[s] = x; // Compute MixColumns
  22352. x8 = d[x4 = d[x2 = d[x]]];
  22353. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  22354. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  22355. for (i = 0; i < 4; i++) {
  22356. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  22357. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  22358. }
  22359. } // Compactify. Considerable speedup on Firefox.
  22360. for (i = 0; i < 5; i++) {
  22361. encTable[i] = encTable[i].slice(0);
  22362. decTable[i] = decTable[i].slice(0);
  22363. }
  22364. return tables;
  22365. };
  22366. let aesTables = null;
  22367. /**
  22368. * Schedule out an AES key for both encryption and decryption. This
  22369. * is a low-level class. Use a cipher mode to do bulk encryption.
  22370. *
  22371. * @class AES
  22372. * @param key {Array} The key as an array of 4, 6 or 8 words.
  22373. */
  22374. class AES {
  22375. constructor(key) {
  22376. /**
  22377. * The expanded S-box and inverse S-box tables. These will be computed
  22378. * on the client so that we don't have to send them down the wire.
  22379. *
  22380. * There are two tables, _tables[0] is for encryption and
  22381. * _tables[1] is for decryption.
  22382. *
  22383. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  22384. * last (_tables[01][4]) is the S-box itself.
  22385. *
  22386. * @private
  22387. */
  22388. // if we have yet to precompute the S-box tables
  22389. // do so now
  22390. if (!aesTables) {
  22391. aesTables = precompute();
  22392. } // then make a copy of that object for use
  22393. 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()]];
  22394. let i;
  22395. let j;
  22396. let tmp;
  22397. const sbox = this._tables[0][4];
  22398. const decTable = this._tables[1];
  22399. const keyLen = key.length;
  22400. let rcon = 1;
  22401. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  22402. throw new Error('Invalid aes key size');
  22403. }
  22404. const encKey = key.slice(0);
  22405. const decKey = [];
  22406. this._key = [encKey, decKey]; // schedule encryption keys
  22407. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  22408. tmp = encKey[i - 1]; // apply sbox
  22409. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  22410. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  22411. if (i % keyLen === 0) {
  22412. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  22413. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  22414. }
  22415. }
  22416. encKey[i] = encKey[i - keyLen] ^ tmp;
  22417. } // schedule decryption keys
  22418. for (j = 0; i; j++, i--) {
  22419. tmp = encKey[j & 3 ? i : i - 4];
  22420. if (i <= 4 || j < 4) {
  22421. decKey[j] = tmp;
  22422. } else {
  22423. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  22424. }
  22425. }
  22426. }
  22427. /**
  22428. * Decrypt 16 bytes, specified as four 32-bit words.
  22429. *
  22430. * @param {number} encrypted0 the first word to decrypt
  22431. * @param {number} encrypted1 the second word to decrypt
  22432. * @param {number} encrypted2 the third word to decrypt
  22433. * @param {number} encrypted3 the fourth word to decrypt
  22434. * @param {Int32Array} out the array to write the decrypted words
  22435. * into
  22436. * @param {number} offset the offset into the output array to start
  22437. * writing results
  22438. * @return {Array} The plaintext.
  22439. */
  22440. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  22441. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  22442. let a = encrypted0 ^ key[0];
  22443. let b = encrypted3 ^ key[1];
  22444. let c = encrypted2 ^ key[2];
  22445. let d = encrypted1 ^ key[3];
  22446. let a2;
  22447. let b2;
  22448. let c2; // key.length === 2 ?
  22449. const nInnerRounds = key.length / 4 - 2;
  22450. let i;
  22451. let kIndex = 4;
  22452. const table = this._tables[1]; // load up the tables
  22453. const table0 = table[0];
  22454. const table1 = table[1];
  22455. const table2 = table[2];
  22456. const table3 = table[3];
  22457. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  22458. for (i = 0; i < nInnerRounds; i++) {
  22459. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  22460. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  22461. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  22462. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  22463. kIndex += 4;
  22464. a = a2;
  22465. b = b2;
  22466. c = c2;
  22467. } // Last round.
  22468. for (i = 0; i < 4; i++) {
  22469. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  22470. a2 = a;
  22471. a = b;
  22472. b = c;
  22473. c = d;
  22474. d = a2;
  22475. }
  22476. }
  22477. }
  22478. /**
  22479. * @file async-stream.js
  22480. */
  22481. /**
  22482. * A wrapper around the Stream class to use setTimeout
  22483. * and run stream "jobs" Asynchronously
  22484. *
  22485. * @class AsyncStream
  22486. * @extends Stream
  22487. */
  22488. class AsyncStream extends Stream {
  22489. constructor() {
  22490. super(Stream);
  22491. this.jobs = [];
  22492. this.delay = 1;
  22493. this.timeout_ = null;
  22494. }
  22495. /**
  22496. * process an async job
  22497. *
  22498. * @private
  22499. */
  22500. processJob_() {
  22501. this.jobs.shift()();
  22502. if (this.jobs.length) {
  22503. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  22504. } else {
  22505. this.timeout_ = null;
  22506. }
  22507. }
  22508. /**
  22509. * push a job into the stream
  22510. *
  22511. * @param {Function} job the job to push into the stream
  22512. */
  22513. push(job) {
  22514. this.jobs.push(job);
  22515. if (!this.timeout_) {
  22516. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  22517. }
  22518. }
  22519. }
  22520. /**
  22521. * @file decrypter.js
  22522. *
  22523. * An asynchronous implementation of AES-128 CBC decryption with
  22524. * PKCS#7 padding.
  22525. */
  22526. /**
  22527. * Convert network-order (big-endian) bytes into their little-endian
  22528. * representation.
  22529. */
  22530. const ntoh = function (word) {
  22531. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  22532. };
  22533. /**
  22534. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  22535. *
  22536. * @param {Uint8Array} encrypted the encrypted bytes
  22537. * @param {Uint32Array} key the bytes of the decryption key
  22538. * @param {Uint32Array} initVector the initialization vector (IV) to
  22539. * use for the first round of CBC.
  22540. * @return {Uint8Array} the decrypted bytes
  22541. *
  22542. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  22543. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  22544. * @see https://tools.ietf.org/html/rfc2315
  22545. */
  22546. const decrypt = function (encrypted, key, initVector) {
  22547. // word-level access to the encrypted bytes
  22548. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  22549. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  22550. const decrypted = new Uint8Array(encrypted.byteLength);
  22551. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  22552. // decrypted data
  22553. let init0;
  22554. let init1;
  22555. let init2;
  22556. let init3;
  22557. let encrypted0;
  22558. let encrypted1;
  22559. let encrypted2;
  22560. let encrypted3; // iteration variable
  22561. let wordIx; // pull out the words of the IV to ensure we don't modify the
  22562. // passed-in reference and easier access
  22563. init0 = initVector[0];
  22564. init1 = initVector[1];
  22565. init2 = initVector[2];
  22566. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  22567. // to each decrypted block
  22568. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  22569. // convert big-endian (network order) words into little-endian
  22570. // (javascript order)
  22571. encrypted0 = ntoh(encrypted32[wordIx]);
  22572. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  22573. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  22574. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  22575. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  22576. // plaintext
  22577. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  22578. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  22579. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  22580. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  22581. init0 = encrypted0;
  22582. init1 = encrypted1;
  22583. init2 = encrypted2;
  22584. init3 = encrypted3;
  22585. }
  22586. return decrypted;
  22587. };
  22588. /**
  22589. * The `Decrypter` class that manages decryption of AES
  22590. * data through `AsyncStream` objects and the `decrypt`
  22591. * function
  22592. *
  22593. * @param {Uint8Array} encrypted the encrypted bytes
  22594. * @param {Uint32Array} key the bytes of the decryption key
  22595. * @param {Uint32Array} initVector the initialization vector (IV) to
  22596. * @param {Function} done the function to run when done
  22597. * @class Decrypter
  22598. */
  22599. class Decrypter {
  22600. constructor(encrypted, key, initVector, done) {
  22601. const step = Decrypter.STEP;
  22602. const encrypted32 = new Int32Array(encrypted.buffer);
  22603. const decrypted = new Uint8Array(encrypted.byteLength);
  22604. let i = 0;
  22605. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  22606. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  22607. for (i = step; i < encrypted32.length; i += step) {
  22608. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  22609. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  22610. } // invoke the done() callback when everything is finished
  22611. this.asyncStream_.push(function () {
  22612. // remove pkcs#7 padding from the decrypted bytes
  22613. done(null, unpad(decrypted));
  22614. });
  22615. }
  22616. /**
  22617. * a getter for step the maximum number of bytes to process at one time
  22618. *
  22619. * @return {number} the value of step 32000
  22620. */
  22621. static get STEP() {
  22622. // 4 * 8000;
  22623. return 32000;
  22624. }
  22625. /**
  22626. * @private
  22627. */
  22628. decryptChunk_(encrypted, key, initVector, decrypted) {
  22629. return function () {
  22630. const bytes = decrypt(encrypted, key, initVector);
  22631. decrypted.set(bytes, encrypted.byteOffset);
  22632. };
  22633. }
  22634. }
  22635. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  22636. var win;
  22637. if (typeof window !== "undefined") {
  22638. win = window;
  22639. } else if (typeof commonjsGlobal !== "undefined") {
  22640. win = commonjsGlobal;
  22641. } else if (typeof self !== "undefined") {
  22642. win = self;
  22643. } else {
  22644. win = {};
  22645. }
  22646. var window_1 = win;
  22647. var isArrayBufferView = function isArrayBufferView(obj) {
  22648. if (ArrayBuffer.isView === 'function') {
  22649. return ArrayBuffer.isView(obj);
  22650. }
  22651. return obj && obj.buffer instanceof ArrayBuffer;
  22652. };
  22653. var BigInt = window_1.BigInt || Number;
  22654. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  22655. (function () {
  22656. var a = new Uint16Array([0xFFCC]);
  22657. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  22658. if (b[0] === 0xFF) {
  22659. return 'big';
  22660. }
  22661. if (b[0] === 0xCC) {
  22662. return 'little';
  22663. }
  22664. return 'unknown';
  22665. })();
  22666. /**
  22667. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  22668. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  22669. *
  22670. * @param {Object} message
  22671. * Object of properties and values to send to the web worker
  22672. * @return {Object}
  22673. * Modified message with TypedArray values expanded
  22674. * @function createTransferableMessage
  22675. */
  22676. const createTransferableMessage = function (message) {
  22677. const transferable = {};
  22678. Object.keys(message).forEach(key => {
  22679. const value = message[key];
  22680. if (isArrayBufferView(value)) {
  22681. transferable[key] = {
  22682. bytes: value.buffer,
  22683. byteOffset: value.byteOffset,
  22684. byteLength: value.byteLength
  22685. };
  22686. } else {
  22687. transferable[key] = value;
  22688. }
  22689. });
  22690. return transferable;
  22691. };
  22692. /* global self */
  22693. /**
  22694. * Our web worker interface so that things can talk to aes-decrypter
  22695. * that will be running in a web worker. the scope is passed to this by
  22696. * webworkify.
  22697. */
  22698. self.onmessage = function (event) {
  22699. const data = event.data;
  22700. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  22701. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  22702. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  22703. /* eslint-disable no-new, handle-callback-err */
  22704. new Decrypter(encrypted, key, iv, function (err, bytes) {
  22705. self.postMessage(createTransferableMessage({
  22706. source: data.source,
  22707. decrypted: bytes
  22708. }), [bytes.buffer]);
  22709. });
  22710. /* eslint-enable */
  22711. };
  22712. });
  22713. var Decrypter = factory(workerCode);
  22714. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  22715. /**
  22716. * Convert the properties of an HLS track into an audioTrackKind.
  22717. *
  22718. * @private
  22719. */
  22720. const audioTrackKind_ = properties => {
  22721. let kind = properties.default ? 'main' : 'alternative';
  22722. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  22723. kind = 'main-desc';
  22724. }
  22725. return kind;
  22726. };
  22727. /**
  22728. * Pause provided segment loader and playlist loader if active
  22729. *
  22730. * @param {SegmentLoader} segmentLoader
  22731. * SegmentLoader to pause
  22732. * @param {Object} mediaType
  22733. * Active media type
  22734. * @function stopLoaders
  22735. */
  22736. const stopLoaders = (segmentLoader, mediaType) => {
  22737. segmentLoader.abort();
  22738. segmentLoader.pause();
  22739. if (mediaType && mediaType.activePlaylistLoader) {
  22740. mediaType.activePlaylistLoader.pause();
  22741. mediaType.activePlaylistLoader = null;
  22742. }
  22743. };
  22744. /**
  22745. * Start loading provided segment loader and playlist loader
  22746. *
  22747. * @param {PlaylistLoader} playlistLoader
  22748. * PlaylistLoader to start loading
  22749. * @param {Object} mediaType
  22750. * Active media type
  22751. * @function startLoaders
  22752. */
  22753. const startLoaders = (playlistLoader, mediaType) => {
  22754. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  22755. // playlist loader
  22756. mediaType.activePlaylistLoader = playlistLoader;
  22757. playlistLoader.load();
  22758. };
  22759. /**
  22760. * Returns a function to be called when the media group changes. It performs a
  22761. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  22762. * change of group is merely a rendition switch of the same content at another encoding,
  22763. * rather than a change of content, such as switching audio from English to Spanish.
  22764. *
  22765. * @param {string} type
  22766. * MediaGroup type
  22767. * @param {Object} settings
  22768. * Object containing required information for media groups
  22769. * @return {Function}
  22770. * Handler for a non-destructive resync of SegmentLoader when the active media
  22771. * group changes.
  22772. * @function onGroupChanged
  22773. */
  22774. const onGroupChanged = (type, settings) => () => {
  22775. const {
  22776. segmentLoaders: {
  22777. [type]: segmentLoader,
  22778. main: mainSegmentLoader
  22779. },
  22780. mediaTypes: {
  22781. [type]: mediaType
  22782. }
  22783. } = settings;
  22784. const activeTrack = mediaType.activeTrack();
  22785. const activeGroup = mediaType.getActiveGroup();
  22786. const previousActiveLoader = mediaType.activePlaylistLoader;
  22787. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  22788. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  22789. return;
  22790. }
  22791. mediaType.lastGroup_ = activeGroup;
  22792. mediaType.lastTrack_ = activeTrack;
  22793. stopLoaders(segmentLoader, mediaType);
  22794. if (!activeGroup || activeGroup.isMainPlaylist) {
  22795. // there is no group active or active group is a main playlist and won't change
  22796. return;
  22797. }
  22798. if (!activeGroup.playlistLoader) {
  22799. if (previousActiveLoader) {
  22800. // The previous group had a playlist loader but the new active group does not
  22801. // this means we are switching from demuxed to muxed audio. In this case we want to
  22802. // do a destructive reset of the main segment loader and not restart the audio
  22803. // loaders.
  22804. mainSegmentLoader.resetEverything();
  22805. }
  22806. return;
  22807. } // Non-destructive resync
  22808. segmentLoader.resyncLoader();
  22809. startLoaders(activeGroup.playlistLoader, mediaType);
  22810. };
  22811. const onGroupChanging = (type, settings) => () => {
  22812. const {
  22813. segmentLoaders: {
  22814. [type]: segmentLoader
  22815. },
  22816. mediaTypes: {
  22817. [type]: mediaType
  22818. }
  22819. } = settings;
  22820. mediaType.lastGroup_ = null;
  22821. segmentLoader.abort();
  22822. segmentLoader.pause();
  22823. };
  22824. /**
  22825. * Returns a function to be called when the media track changes. It performs a
  22826. * destructive reset of the SegmentLoader to ensure we start loading as close to
  22827. * currentTime as possible.
  22828. *
  22829. * @param {string} type
  22830. * MediaGroup type
  22831. * @param {Object} settings
  22832. * Object containing required information for media groups
  22833. * @return {Function}
  22834. * Handler for a destructive reset of SegmentLoader when the active media
  22835. * track changes.
  22836. * @function onTrackChanged
  22837. */
  22838. const onTrackChanged = (type, settings) => () => {
  22839. const {
  22840. mainPlaylistLoader,
  22841. segmentLoaders: {
  22842. [type]: segmentLoader,
  22843. main: mainSegmentLoader
  22844. },
  22845. mediaTypes: {
  22846. [type]: mediaType
  22847. }
  22848. } = settings;
  22849. const activeTrack = mediaType.activeTrack();
  22850. const activeGroup = mediaType.getActiveGroup();
  22851. const previousActiveLoader = mediaType.activePlaylistLoader;
  22852. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  22853. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  22854. return;
  22855. }
  22856. mediaType.lastGroup_ = activeGroup;
  22857. mediaType.lastTrack_ = activeTrack;
  22858. stopLoaders(segmentLoader, mediaType);
  22859. if (!activeGroup) {
  22860. // there is no group active so we do not want to restart loaders
  22861. return;
  22862. }
  22863. if (activeGroup.isMainPlaylist) {
  22864. // track did not change, do nothing
  22865. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  22866. return;
  22867. }
  22868. const pc = settings.vhs.playlistController_;
  22869. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  22870. if (pc.media() === newPlaylist) {
  22871. return;
  22872. }
  22873. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  22874. mainPlaylistLoader.pause();
  22875. mainSegmentLoader.resetEverything();
  22876. pc.fastQualityChange_(newPlaylist);
  22877. return;
  22878. }
  22879. if (type === 'AUDIO') {
  22880. if (!activeGroup.playlistLoader) {
  22881. // when switching from demuxed audio/video to muxed audio/video (noted by no
  22882. // playlist loader for the audio group), we want to do a destructive reset of the
  22883. // main segment loader and not restart the audio loaders
  22884. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  22885. // it should be stopped
  22886. mainSegmentLoader.resetEverything();
  22887. return;
  22888. } // although the segment loader is an audio segment loader, call the setAudio
  22889. // function to ensure it is prepared to re-append the init segment (or handle other
  22890. // config changes)
  22891. segmentLoader.setAudio(true);
  22892. mainSegmentLoader.setAudio(false);
  22893. }
  22894. if (previousActiveLoader === activeGroup.playlistLoader) {
  22895. // Nothing has actually changed. This can happen because track change events can fire
  22896. // multiple times for a "single" change. One for enabling the new active track, and
  22897. // one for disabling the track that was active
  22898. startLoaders(activeGroup.playlistLoader, mediaType);
  22899. return;
  22900. }
  22901. if (segmentLoader.track) {
  22902. // For WebVTT, set the new text track in the segmentloader
  22903. segmentLoader.track(activeTrack);
  22904. } // destructive reset
  22905. segmentLoader.resetEverything();
  22906. startLoaders(activeGroup.playlistLoader, mediaType);
  22907. };
  22908. const onError = {
  22909. /**
  22910. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  22911. * an error.
  22912. *
  22913. * @param {string} type
  22914. * MediaGroup type
  22915. * @param {Object} settings
  22916. * Object containing required information for media groups
  22917. * @return {Function}
  22918. * Error handler. Logs warning (or error if the playlist is excluded) to
  22919. * console and switches back to default audio track.
  22920. * @function onError.AUDIO
  22921. */
  22922. AUDIO: (type, settings) => () => {
  22923. const {
  22924. segmentLoaders: {
  22925. [type]: segmentLoader
  22926. },
  22927. mediaTypes: {
  22928. [type]: mediaType
  22929. },
  22930. excludePlaylist
  22931. } = settings;
  22932. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  22933. const activeTrack = mediaType.activeTrack();
  22934. const activeGroup = mediaType.activeGroup();
  22935. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  22936. const defaultTrack = mediaType.tracks[id];
  22937. if (activeTrack === defaultTrack) {
  22938. // Default track encountered an error. All we can do now is exclude the current
  22939. // rendition and hope another will switch audio groups
  22940. excludePlaylist({
  22941. error: {
  22942. message: 'Problem encountered loading the default audio track.'
  22943. }
  22944. });
  22945. return;
  22946. }
  22947. videojs__default["default"].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  22948. for (const trackId in mediaType.tracks) {
  22949. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  22950. }
  22951. mediaType.onTrackChanged();
  22952. },
  22953. /**
  22954. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  22955. * an error.
  22956. *
  22957. * @param {string} type
  22958. * MediaGroup type
  22959. * @param {Object} settings
  22960. * Object containing required information for media groups
  22961. * @return {Function}
  22962. * Error handler. Logs warning to console and disables the active subtitle track
  22963. * @function onError.SUBTITLES
  22964. */
  22965. SUBTITLES: (type, settings) => () => {
  22966. const {
  22967. segmentLoaders: {
  22968. [type]: segmentLoader
  22969. },
  22970. mediaTypes: {
  22971. [type]: mediaType
  22972. }
  22973. } = settings;
  22974. videojs__default["default"].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  22975. stopLoaders(segmentLoader, mediaType);
  22976. const track = mediaType.activeTrack();
  22977. if (track) {
  22978. track.mode = 'disabled';
  22979. }
  22980. mediaType.onTrackChanged();
  22981. }
  22982. };
  22983. const setupListeners = {
  22984. /**
  22985. * Setup event listeners for audio playlist loader
  22986. *
  22987. * @param {string} type
  22988. * MediaGroup type
  22989. * @param {PlaylistLoader|null} playlistLoader
  22990. * PlaylistLoader to register listeners on
  22991. * @param {Object} settings
  22992. * Object containing required information for media groups
  22993. * @function setupListeners.AUDIO
  22994. */
  22995. AUDIO: (type, playlistLoader, settings) => {
  22996. if (!playlistLoader) {
  22997. // no playlist loader means audio will be muxed with the video
  22998. return;
  22999. }
  23000. const {
  23001. tech,
  23002. requestOptions,
  23003. segmentLoaders: {
  23004. [type]: segmentLoader
  23005. }
  23006. } = settings;
  23007. playlistLoader.on('loadedmetadata', () => {
  23008. const media = playlistLoader.media();
  23009. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  23010. // permits, start downloading segments
  23011. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  23012. segmentLoader.load();
  23013. }
  23014. });
  23015. playlistLoader.on('loadedplaylist', () => {
  23016. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  23017. if (!tech.paused()) {
  23018. segmentLoader.load();
  23019. }
  23020. });
  23021. playlistLoader.on('error', onError[type](type, settings));
  23022. },
  23023. /**
  23024. * Setup event listeners for subtitle playlist loader
  23025. *
  23026. * @param {string} type
  23027. * MediaGroup type
  23028. * @param {PlaylistLoader|null} playlistLoader
  23029. * PlaylistLoader to register listeners on
  23030. * @param {Object} settings
  23031. * Object containing required information for media groups
  23032. * @function setupListeners.SUBTITLES
  23033. */
  23034. SUBTITLES: (type, playlistLoader, settings) => {
  23035. const {
  23036. tech,
  23037. requestOptions,
  23038. segmentLoaders: {
  23039. [type]: segmentLoader
  23040. },
  23041. mediaTypes: {
  23042. [type]: mediaType
  23043. }
  23044. } = settings;
  23045. playlistLoader.on('loadedmetadata', () => {
  23046. const media = playlistLoader.media();
  23047. segmentLoader.playlist(media, requestOptions);
  23048. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  23049. // permits, start downloading segments
  23050. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  23051. segmentLoader.load();
  23052. }
  23053. });
  23054. playlistLoader.on('loadedplaylist', () => {
  23055. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  23056. if (!tech.paused()) {
  23057. segmentLoader.load();
  23058. }
  23059. });
  23060. playlistLoader.on('error', onError[type](type, settings));
  23061. }
  23062. };
  23063. const initialize = {
  23064. /**
  23065. * Setup PlaylistLoaders and AudioTracks for the audio groups
  23066. *
  23067. * @param {string} type
  23068. * MediaGroup type
  23069. * @param {Object} settings
  23070. * Object containing required information for media groups
  23071. * @function initialize.AUDIO
  23072. */
  23073. 'AUDIO': (type, settings) => {
  23074. const {
  23075. vhs,
  23076. sourceType,
  23077. segmentLoaders: {
  23078. [type]: segmentLoader
  23079. },
  23080. requestOptions,
  23081. main: {
  23082. mediaGroups
  23083. },
  23084. mediaTypes: {
  23085. [type]: {
  23086. groups,
  23087. tracks,
  23088. logger_
  23089. }
  23090. },
  23091. mainPlaylistLoader
  23092. } = settings;
  23093. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  23094. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  23095. mediaGroups[type] = {
  23096. main: {
  23097. default: {
  23098. default: true
  23099. }
  23100. }
  23101. };
  23102. if (audioOnlyMain) {
  23103. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  23104. }
  23105. }
  23106. for (const groupId in mediaGroups[type]) {
  23107. if (!groups[groupId]) {
  23108. groups[groupId] = [];
  23109. }
  23110. for (const variantLabel in mediaGroups[type][groupId]) {
  23111. let properties = mediaGroups[type][groupId][variantLabel];
  23112. let playlistLoader;
  23113. if (audioOnlyMain) {
  23114. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  23115. properties.isMainPlaylist = true;
  23116. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  23117. // use the resolved media playlist object
  23118. } else if (sourceType === 'vhs-json' && properties.playlists) {
  23119. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  23120. } else if (properties.resolvedUri) {
  23121. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  23122. // should we even have properties.playlists in this check.
  23123. } else if (properties.playlists && sourceType === 'dash') {
  23124. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  23125. } else {
  23126. // no resolvedUri means the audio is muxed with the video when using this
  23127. // audio track
  23128. playlistLoader = null;
  23129. }
  23130. properties = merge$1({
  23131. id: variantLabel,
  23132. playlistLoader
  23133. }, properties);
  23134. setupListeners[type](type, properties.playlistLoader, settings);
  23135. groups[groupId].push(properties);
  23136. if (typeof tracks[variantLabel] === 'undefined') {
  23137. const track = new videojs__default["default"].AudioTrack({
  23138. id: variantLabel,
  23139. kind: audioTrackKind_(properties),
  23140. enabled: false,
  23141. language: properties.language,
  23142. default: properties.default,
  23143. label: variantLabel
  23144. });
  23145. tracks[variantLabel] = track;
  23146. }
  23147. }
  23148. } // setup single error event handler for the segment loader
  23149. segmentLoader.on('error', onError[type](type, settings));
  23150. },
  23151. /**
  23152. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  23153. *
  23154. * @param {string} type
  23155. * MediaGroup type
  23156. * @param {Object} settings
  23157. * Object containing required information for media groups
  23158. * @function initialize.SUBTITLES
  23159. */
  23160. 'SUBTITLES': (type, settings) => {
  23161. const {
  23162. tech,
  23163. vhs,
  23164. sourceType,
  23165. segmentLoaders: {
  23166. [type]: segmentLoader
  23167. },
  23168. requestOptions,
  23169. main: {
  23170. mediaGroups
  23171. },
  23172. mediaTypes: {
  23173. [type]: {
  23174. groups,
  23175. tracks
  23176. }
  23177. },
  23178. mainPlaylistLoader
  23179. } = settings;
  23180. for (const groupId in mediaGroups[type]) {
  23181. if (!groups[groupId]) {
  23182. groups[groupId] = [];
  23183. }
  23184. for (const variantLabel in mediaGroups[type][groupId]) {
  23185. if (mediaGroups[type][groupId][variantLabel].forced) {
  23186. // Subtitle playlists with the forced attribute are not selectable in Safari.
  23187. // According to Apple's HLS Authoring Specification:
  23188. // If content has forced subtitles and regular subtitles in a given language,
  23189. // the regular subtitles track in that language MUST contain both the forced
  23190. // subtitles and the regular subtitles for that language.
  23191. // Because of this requirement and that Safari does not add forced subtitles,
  23192. // forced subtitles are skipped here to maintain consistent experience across
  23193. // all platforms
  23194. continue;
  23195. }
  23196. let properties = mediaGroups[type][groupId][variantLabel];
  23197. let playlistLoader;
  23198. if (sourceType === 'hls') {
  23199. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  23200. } else if (sourceType === 'dash') {
  23201. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  23202. if (!playlists.length) {
  23203. return;
  23204. }
  23205. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  23206. } else if (sourceType === 'vhs-json') {
  23207. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  23208. // as provided, otherwise use the resolved URI to load the playlist
  23209. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  23210. }
  23211. properties = merge$1({
  23212. id: variantLabel,
  23213. playlistLoader
  23214. }, properties);
  23215. setupListeners[type](type, properties.playlistLoader, settings);
  23216. groups[groupId].push(properties);
  23217. if (typeof tracks[variantLabel] === 'undefined') {
  23218. const track = tech.addRemoteTextTrack({
  23219. id: variantLabel,
  23220. kind: 'subtitles',
  23221. default: properties.default && properties.autoselect,
  23222. language: properties.language,
  23223. label: variantLabel
  23224. }, false).track;
  23225. tracks[variantLabel] = track;
  23226. }
  23227. }
  23228. } // setup single error event handler for the segment loader
  23229. segmentLoader.on('error', onError[type](type, settings));
  23230. },
  23231. /**
  23232. * Setup TextTracks for the closed-caption groups
  23233. *
  23234. * @param {String} type
  23235. * MediaGroup type
  23236. * @param {Object} settings
  23237. * Object containing required information for media groups
  23238. * @function initialize['CLOSED-CAPTIONS']
  23239. */
  23240. 'CLOSED-CAPTIONS': (type, settings) => {
  23241. const {
  23242. tech,
  23243. main: {
  23244. mediaGroups
  23245. },
  23246. mediaTypes: {
  23247. [type]: {
  23248. groups,
  23249. tracks
  23250. }
  23251. }
  23252. } = settings;
  23253. for (const groupId in mediaGroups[type]) {
  23254. if (!groups[groupId]) {
  23255. groups[groupId] = [];
  23256. }
  23257. for (const variantLabel in mediaGroups[type][groupId]) {
  23258. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  23259. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  23260. continue;
  23261. }
  23262. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  23263. let newProps = {
  23264. label: variantLabel,
  23265. language: properties.language,
  23266. instreamId: properties.instreamId,
  23267. default: properties.default && properties.autoselect
  23268. };
  23269. if (captionServices[newProps.instreamId]) {
  23270. newProps = merge$1(newProps, captionServices[newProps.instreamId]);
  23271. }
  23272. if (newProps.default === undefined) {
  23273. delete newProps.default;
  23274. } // No PlaylistLoader is required for Closed-Captions because the captions are
  23275. // embedded within the video stream
  23276. groups[groupId].push(merge$1({
  23277. id: variantLabel
  23278. }, properties));
  23279. if (typeof tracks[variantLabel] === 'undefined') {
  23280. const track = tech.addRemoteTextTrack({
  23281. id: newProps.instreamId,
  23282. kind: 'captions',
  23283. default: newProps.default,
  23284. language: newProps.language,
  23285. label: newProps.label
  23286. }, false).track;
  23287. tracks[variantLabel] = track;
  23288. }
  23289. }
  23290. }
  23291. }
  23292. };
  23293. const groupMatch = (list, media) => {
  23294. for (let i = 0; i < list.length; i++) {
  23295. if (playlistMatch(media, list[i])) {
  23296. return true;
  23297. }
  23298. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  23299. return true;
  23300. }
  23301. }
  23302. return false;
  23303. };
  23304. /**
  23305. * Returns a function used to get the active group of the provided type
  23306. *
  23307. * @param {string} type
  23308. * MediaGroup type
  23309. * @param {Object} settings
  23310. * Object containing required information for media groups
  23311. * @return {Function}
  23312. * Function that returns the active media group for the provided type. Takes an
  23313. * optional parameter {TextTrack} track. If no track is provided, a list of all
  23314. * variants in the group, otherwise the variant corresponding to the provided
  23315. * track is returned.
  23316. * @function activeGroup
  23317. */
  23318. const activeGroup = (type, settings) => track => {
  23319. const {
  23320. mainPlaylistLoader,
  23321. mediaTypes: {
  23322. [type]: {
  23323. groups
  23324. }
  23325. }
  23326. } = settings;
  23327. const media = mainPlaylistLoader.media();
  23328. if (!media) {
  23329. return null;
  23330. }
  23331. let variants = null; // set to variants to main media active group
  23332. if (media.attributes[type]) {
  23333. variants = groups[media.attributes[type]];
  23334. }
  23335. const groupKeys = Object.keys(groups);
  23336. if (!variants) {
  23337. // find the mainPlaylistLoader media
  23338. // that is in a media group if we are dealing
  23339. // with audio only
  23340. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  23341. for (let i = 0; i < groupKeys.length; i++) {
  23342. const groupPropertyList = groups[groupKeys[i]];
  23343. if (groupMatch(groupPropertyList, media)) {
  23344. variants = groupPropertyList;
  23345. break;
  23346. }
  23347. } // use the main group if it exists
  23348. } else if (groups.main) {
  23349. variants = groups.main; // only one group, use that one
  23350. } else if (groupKeys.length === 1) {
  23351. variants = groups[groupKeys[0]];
  23352. }
  23353. }
  23354. if (typeof track === 'undefined') {
  23355. return variants;
  23356. }
  23357. if (track === null || !variants) {
  23358. // An active track was specified so a corresponding group is expected. track === null
  23359. // means no track is currently active so there is no corresponding group
  23360. return null;
  23361. }
  23362. return variants.filter(props => props.id === track.id)[0] || null;
  23363. };
  23364. const activeTrack = {
  23365. /**
  23366. * Returns a function used to get the active track of type provided
  23367. *
  23368. * @param {string} type
  23369. * MediaGroup type
  23370. * @param {Object} settings
  23371. * Object containing required information for media groups
  23372. * @return {Function}
  23373. * Function that returns the active media track for the provided type. Returns
  23374. * null if no track is active
  23375. * @function activeTrack.AUDIO
  23376. */
  23377. AUDIO: (type, settings) => () => {
  23378. const {
  23379. mediaTypes: {
  23380. [type]: {
  23381. tracks
  23382. }
  23383. }
  23384. } = settings;
  23385. for (const id in tracks) {
  23386. if (tracks[id].enabled) {
  23387. return tracks[id];
  23388. }
  23389. }
  23390. return null;
  23391. },
  23392. /**
  23393. * Returns a function used to get the active track of type provided
  23394. *
  23395. * @param {string} type
  23396. * MediaGroup type
  23397. * @param {Object} settings
  23398. * Object containing required information for media groups
  23399. * @return {Function}
  23400. * Function that returns the active media track for the provided type. Returns
  23401. * null if no track is active
  23402. * @function activeTrack.SUBTITLES
  23403. */
  23404. SUBTITLES: (type, settings) => () => {
  23405. const {
  23406. mediaTypes: {
  23407. [type]: {
  23408. tracks
  23409. }
  23410. }
  23411. } = settings;
  23412. for (const id in tracks) {
  23413. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  23414. return tracks[id];
  23415. }
  23416. }
  23417. return null;
  23418. }
  23419. };
  23420. const getActiveGroup = (type, {
  23421. mediaTypes
  23422. }) => () => {
  23423. const activeTrack_ = mediaTypes[type].activeTrack();
  23424. if (!activeTrack_) {
  23425. return null;
  23426. }
  23427. return mediaTypes[type].activeGroup(activeTrack_);
  23428. };
  23429. /**
  23430. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  23431. * Closed-Captions) specified in the main manifest.
  23432. *
  23433. * @param {Object} settings
  23434. * Object containing required information for setting up the media groups
  23435. * @param {Tech} settings.tech
  23436. * The tech of the player
  23437. * @param {Object} settings.requestOptions
  23438. * XHR request options used by the segment loaders
  23439. * @param {PlaylistLoader} settings.mainPlaylistLoader
  23440. * PlaylistLoader for the main source
  23441. * @param {VhsHandler} settings.vhs
  23442. * VHS SourceHandler
  23443. * @param {Object} settings.main
  23444. * The parsed main manifest
  23445. * @param {Object} settings.mediaTypes
  23446. * Object to store the loaders, tracks, and utility methods for each media type
  23447. * @param {Function} settings.excludePlaylist
  23448. * Excludes the current rendition and forces a rendition switch.
  23449. * @function setupMediaGroups
  23450. */
  23451. const setupMediaGroups = settings => {
  23452. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  23453. initialize[type](type, settings);
  23454. });
  23455. const {
  23456. mediaTypes,
  23457. mainPlaylistLoader,
  23458. tech,
  23459. vhs,
  23460. segmentLoaders: {
  23461. ['AUDIO']: audioSegmentLoader,
  23462. main: mainSegmentLoader
  23463. }
  23464. } = settings; // setup active group and track getters and change event handlers
  23465. ['AUDIO', 'SUBTITLES'].forEach(type => {
  23466. mediaTypes[type].activeGroup = activeGroup(type, settings);
  23467. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  23468. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  23469. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  23470. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  23471. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  23472. }); // DO NOT enable the default subtitle or caption track.
  23473. // DO enable the default audio track
  23474. const audioGroup = mediaTypes.AUDIO.activeGroup();
  23475. if (audioGroup) {
  23476. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  23477. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  23478. mediaTypes.AUDIO.onGroupChanged();
  23479. mediaTypes.AUDIO.onTrackChanged();
  23480. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  23481. // track is changed, but needs to be handled here since the track may not be considered
  23482. // changed on the first call to onTrackChanged
  23483. if (!activeAudioGroup.playlistLoader) {
  23484. // either audio is muxed with video or the stream is audio only
  23485. mainSegmentLoader.setAudio(true);
  23486. } else {
  23487. // audio is demuxed
  23488. mainSegmentLoader.setAudio(false);
  23489. audioSegmentLoader.setAudio(true);
  23490. }
  23491. }
  23492. mainPlaylistLoader.on('mediachange', () => {
  23493. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  23494. });
  23495. mainPlaylistLoader.on('mediachanging', () => {
  23496. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  23497. }); // custom audio track change event handler for usage event
  23498. const onAudioTrackChanged = () => {
  23499. mediaTypes.AUDIO.onTrackChanged();
  23500. tech.trigger({
  23501. type: 'usage',
  23502. name: 'vhs-audio-change'
  23503. });
  23504. };
  23505. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  23506. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  23507. vhs.on('dispose', () => {
  23508. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  23509. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  23510. }); // clear existing audio tracks and add the ones we just created
  23511. tech.clearTracks('audio');
  23512. for (const id in mediaTypes.AUDIO.tracks) {
  23513. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  23514. }
  23515. };
  23516. /**
  23517. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  23518. * media type
  23519. *
  23520. * @return {Object}
  23521. * Object to store the loaders, tracks, and utility methods for each media type
  23522. * @function createMediaTypes
  23523. */
  23524. const createMediaTypes = () => {
  23525. const mediaTypes = {};
  23526. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  23527. mediaTypes[type] = {
  23528. groups: {},
  23529. tracks: {},
  23530. activePlaylistLoader: null,
  23531. activeGroup: noop,
  23532. activeTrack: noop,
  23533. getActiveGroup: noop,
  23534. onGroupChanged: noop,
  23535. onTrackChanged: noop,
  23536. lastTrack_: null,
  23537. logger_: logger(`MediaGroups[${type}]`)
  23538. };
  23539. });
  23540. return mediaTypes;
  23541. };
  23542. /**
  23543. * @file playlist-controller.js
  23544. */
  23545. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  23546. let Vhs$1; // SegmentLoader stats that need to have each loader's
  23547. // values summed to calculate the final value
  23548. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  23549. const sumLoaderStat = function (stat) {
  23550. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  23551. };
  23552. const shouldSwitchToMedia = function ({
  23553. currentPlaylist,
  23554. buffered,
  23555. currentTime,
  23556. nextPlaylist,
  23557. bufferLowWaterLine,
  23558. bufferHighWaterLine,
  23559. duration,
  23560. bufferBasedABR,
  23561. log
  23562. }) {
  23563. // we have no other playlist to switch to
  23564. if (!nextPlaylist) {
  23565. videojs__default["default"].log.warn('We received no playlist to switch to. Please check your stream.');
  23566. return false;
  23567. }
  23568. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  23569. if (!currentPlaylist) {
  23570. log(`${sharedLogLine} as current playlist is not set`);
  23571. return true;
  23572. } // no need to switch if playlist is the same
  23573. if (nextPlaylist.id === currentPlaylist.id) {
  23574. return false;
  23575. } // determine if current time is in a buffered range.
  23576. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  23577. // This is because in LIVE, the player plays 3 segments from the end of the
  23578. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  23579. // in those segments, a viewer will never experience a rendition upswitch.
  23580. if (!currentPlaylist.endList) {
  23581. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  23582. // doubles the time to first playback.
  23583. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  23584. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  23585. return false;
  23586. }
  23587. log(`${sharedLogLine} as current playlist is live`);
  23588. return true;
  23589. }
  23590. const forwardBuffer = timeAheadOf(buffered, currentTime);
  23591. 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
  23592. // duration is below the max potential low water line
  23593. if (duration < maxBufferLowWaterLine) {
  23594. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  23595. return true;
  23596. }
  23597. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  23598. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  23599. // we can switch down
  23600. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  23601. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  23602. if (bufferBasedABR) {
  23603. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  23604. }
  23605. log(logLine);
  23606. return true;
  23607. } // and if our buffer is higher than the low water line,
  23608. // we can switch up
  23609. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  23610. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  23611. if (bufferBasedABR) {
  23612. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  23613. }
  23614. log(logLine);
  23615. return true;
  23616. }
  23617. log(`not ${sharedLogLine} as no switching criteria met`);
  23618. return false;
  23619. };
  23620. /**
  23621. * the main playlist controller controller all interactons
  23622. * between playlists and segmentloaders. At this time this mainly
  23623. * involves a main playlist and a series of audio playlists
  23624. * if they are available
  23625. *
  23626. * @class PlaylistController
  23627. * @extends videojs.EventTarget
  23628. */
  23629. class PlaylistController extends videojs__default["default"].EventTarget {
  23630. constructor(options) {
  23631. super();
  23632. const {
  23633. src,
  23634. withCredentials,
  23635. tech,
  23636. bandwidth,
  23637. externVhs,
  23638. useCueTags,
  23639. playlistExclusionDuration,
  23640. enableLowInitialPlaylist,
  23641. sourceType,
  23642. cacheEncryptionKeys,
  23643. bufferBasedABR,
  23644. leastPixelDiffSelector,
  23645. captionServices
  23646. } = options;
  23647. if (!src) {
  23648. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  23649. }
  23650. let {
  23651. maxPlaylistRetries
  23652. } = options;
  23653. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  23654. maxPlaylistRetries = Infinity;
  23655. }
  23656. Vhs$1 = externVhs;
  23657. this.bufferBasedABR = Boolean(bufferBasedABR);
  23658. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  23659. this.withCredentials = withCredentials;
  23660. this.tech_ = tech;
  23661. this.vhs_ = tech.vhs;
  23662. this.sourceType_ = sourceType;
  23663. this.useCueTags_ = useCueTags;
  23664. this.playlistExclusionDuration = playlistExclusionDuration;
  23665. this.maxPlaylistRetries = maxPlaylistRetries;
  23666. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  23667. if (this.useCueTags_) {
  23668. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  23669. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  23670. }
  23671. this.requestOptions_ = {
  23672. withCredentials,
  23673. maxPlaylistRetries,
  23674. timeout: null
  23675. };
  23676. this.on('error', this.pauseLoading);
  23677. this.mediaTypes_ = createMediaTypes();
  23678. this.mediaSource = new window.MediaSource();
  23679. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  23680. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  23681. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  23682. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  23683. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  23684. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  23685. // everything, and the MediaSource should not be detached without a proper disposal
  23686. this.seekable_ = createTimeRanges();
  23687. this.hasPlayed_ = false;
  23688. this.syncController_ = new SyncController(options);
  23689. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  23690. kind: 'metadata',
  23691. label: 'segment-metadata'
  23692. }, false).track;
  23693. this.decrypter_ = new Decrypter();
  23694. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  23695. this.inbandTextTracks_ = {};
  23696. this.timelineChangeController_ = new TimelineChangeController();
  23697. const segmentLoaderSettings = {
  23698. vhs: this.vhs_,
  23699. parse708captions: options.parse708captions,
  23700. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  23701. captionServices,
  23702. mediaSource: this.mediaSource,
  23703. currentTime: this.tech_.currentTime.bind(this.tech_),
  23704. seekable: () => this.seekable(),
  23705. seeking: () => this.tech_.seeking(),
  23706. duration: () => this.duration(),
  23707. hasPlayed: () => this.hasPlayed_,
  23708. goalBufferLength: () => this.goalBufferLength(),
  23709. bandwidth,
  23710. syncController: this.syncController_,
  23711. decrypter: this.decrypter_,
  23712. sourceType: this.sourceType_,
  23713. inbandTextTracks: this.inbandTextTracks_,
  23714. cacheEncryptionKeys,
  23715. sourceUpdater: this.sourceUpdater_,
  23716. timelineChangeController: this.timelineChangeController_,
  23717. exactManifestTimings: options.exactManifestTimings
  23718. }; // The source type check not only determines whether a special DASH playlist loader
  23719. // should be used, but also covers the case where the provided src is a vhs-json
  23720. // manifest object (instead of a URL). In the case of vhs-json, the default
  23721. // PlaylistLoader should be used.
  23722. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  23723. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  23724. // combined audio/video or just video when alternate audio track is selected
  23725. this.mainSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  23726. segmentMetadataTrack: this.segmentMetadataTrack_,
  23727. loaderType: 'main'
  23728. }), options); // alternate audio track
  23729. this.audioSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  23730. loaderType: 'audio'
  23731. }), options);
  23732. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge$1(segmentLoaderSettings, {
  23733. loaderType: 'vtt',
  23734. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  23735. loadVttJs: () => new Promise((resolve, reject) => {
  23736. function onLoad() {
  23737. tech.off('vttjserror', onError);
  23738. resolve();
  23739. }
  23740. function onError() {
  23741. tech.off('vttjsloaded', onLoad);
  23742. reject();
  23743. }
  23744. tech.one('vttjsloaded', onLoad);
  23745. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  23746. tech.addWebVttScript_();
  23747. })
  23748. }), options);
  23749. this.setupSegmentLoaderListeners_();
  23750. if (this.bufferBasedABR) {
  23751. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  23752. this.tech_.on('pause', () => this.stopABRTimer_());
  23753. this.tech_.on('play', () => this.startABRTimer_());
  23754. } // Create SegmentLoader stat-getters
  23755. // mediaRequests_
  23756. // mediaRequestsAborted_
  23757. // mediaRequestsTimedout_
  23758. // mediaRequestsErrored_
  23759. // mediaTransferDuration_
  23760. // mediaBytesTransferred_
  23761. // mediaAppends_
  23762. loaderStats.forEach(stat => {
  23763. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  23764. });
  23765. this.logger_ = logger('pc');
  23766. this.triggeredFmp4Usage = false;
  23767. if (this.tech_.preload() === 'none') {
  23768. this.loadOnPlay_ = () => {
  23769. this.loadOnPlay_ = null;
  23770. this.mainPlaylistLoader_.load();
  23771. };
  23772. this.tech_.one('play', this.loadOnPlay_);
  23773. } else {
  23774. this.mainPlaylistLoader_.load();
  23775. }
  23776. this.timeToLoadedData__ = -1;
  23777. this.mainAppendsToLoadedData__ = -1;
  23778. this.audioAppendsToLoadedData__ = -1;
  23779. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  23780. this.tech_.one(event, () => {
  23781. const timeToLoadedDataStart = Date.now();
  23782. this.tech_.one('loadeddata', () => {
  23783. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  23784. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  23785. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  23786. });
  23787. });
  23788. }
  23789. mainAppendsToLoadedData_() {
  23790. return this.mainAppendsToLoadedData__;
  23791. }
  23792. audioAppendsToLoadedData_() {
  23793. return this.audioAppendsToLoadedData__;
  23794. }
  23795. appendsToLoadedData_() {
  23796. const main = this.mainAppendsToLoadedData_();
  23797. const audio = this.audioAppendsToLoadedData_();
  23798. if (main === -1 || audio === -1) {
  23799. return -1;
  23800. }
  23801. return main + audio;
  23802. }
  23803. timeToLoadedData_() {
  23804. return this.timeToLoadedData__;
  23805. }
  23806. /**
  23807. * Run selectPlaylist and switch to the new playlist if we should
  23808. *
  23809. * @param {string} [reason=abr] a reason for why the ABR check is made
  23810. * @private
  23811. */
  23812. checkABR_(reason = 'abr') {
  23813. const nextPlaylist = this.selectPlaylist();
  23814. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  23815. this.switchMedia_(nextPlaylist, reason);
  23816. }
  23817. }
  23818. switchMedia_(playlist, cause, delay) {
  23819. const oldMedia = this.media();
  23820. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  23821. const newId = playlist.id || playlist.uri;
  23822. if (oldId && oldId !== newId) {
  23823. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  23824. this.tech_.trigger({
  23825. type: 'usage',
  23826. name: `vhs-rendition-change-${cause}`
  23827. });
  23828. }
  23829. this.mainPlaylistLoader_.media(playlist, delay);
  23830. }
  23831. /**
  23832. * Start a timer that periodically calls checkABR_
  23833. *
  23834. * @private
  23835. */
  23836. startABRTimer_() {
  23837. this.stopABRTimer_();
  23838. this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
  23839. }
  23840. /**
  23841. * Stop the timer that periodically calls checkABR_
  23842. *
  23843. * @private
  23844. */
  23845. stopABRTimer_() {
  23846. // if we're scrubbing, we don't need to pause.
  23847. // This getter will be added to Video.js in version 7.11.
  23848. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  23849. return;
  23850. }
  23851. window.clearInterval(this.abrTimer_);
  23852. this.abrTimer_ = null;
  23853. }
  23854. /**
  23855. * Get a list of playlists for the currently selected audio playlist
  23856. *
  23857. * @return {Array} the array of audio playlists
  23858. */
  23859. getAudioTrackPlaylists_() {
  23860. const main = this.main();
  23861. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  23862. // assume that the audio tracks are contained in main
  23863. // playlist array, use that or an empty array.
  23864. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  23865. return defaultPlaylists;
  23866. }
  23867. const AUDIO = main.mediaGroups.AUDIO;
  23868. const groupKeys = Object.keys(AUDIO);
  23869. let track; // get the current active track
  23870. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  23871. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  23872. } else {
  23873. // default group is `main` or just the first group.
  23874. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  23875. for (const label in defaultGroup) {
  23876. if (defaultGroup[label].default) {
  23877. track = {
  23878. label
  23879. };
  23880. break;
  23881. }
  23882. }
  23883. } // no active track no playlists.
  23884. if (!track) {
  23885. return defaultPlaylists;
  23886. }
  23887. const playlists = []; // get all of the playlists that are possible for the
  23888. // active track.
  23889. for (const group in AUDIO) {
  23890. if (AUDIO[group][track.label]) {
  23891. const properties = AUDIO[group][track.label];
  23892. if (properties.playlists && properties.playlists.length) {
  23893. playlists.push.apply(playlists, properties.playlists);
  23894. } else if (properties.uri) {
  23895. playlists.push(properties);
  23896. } else if (main.playlists.length) {
  23897. // if an audio group does not have a uri
  23898. // see if we have main playlists that use it as a group.
  23899. // if we do then add those to the playlists list.
  23900. for (let i = 0; i < main.playlists.length; i++) {
  23901. const playlist = main.playlists[i];
  23902. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  23903. playlists.push(playlist);
  23904. }
  23905. }
  23906. }
  23907. }
  23908. }
  23909. if (!playlists.length) {
  23910. return defaultPlaylists;
  23911. }
  23912. return playlists;
  23913. }
  23914. /**
  23915. * Register event handlers on the main playlist loader. A helper
  23916. * function for construction time.
  23917. *
  23918. * @private
  23919. */
  23920. setupMainPlaylistLoaderListeners_() {
  23921. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  23922. const media = this.mainPlaylistLoader_.media();
  23923. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  23924. // timeout the request.
  23925. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  23926. this.requestOptions_.timeout = 0;
  23927. } else {
  23928. this.requestOptions_.timeout = requestTimeout;
  23929. } // if this isn't a live video and preload permits, start
  23930. // downloading segments
  23931. if (media.endList && this.tech_.preload() !== 'none') {
  23932. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  23933. this.mainSegmentLoader_.load();
  23934. }
  23935. setupMediaGroups({
  23936. sourceType: this.sourceType_,
  23937. segmentLoaders: {
  23938. AUDIO: this.audioSegmentLoader_,
  23939. SUBTITLES: this.subtitleSegmentLoader_,
  23940. main: this.mainSegmentLoader_
  23941. },
  23942. tech: this.tech_,
  23943. requestOptions: this.requestOptions_,
  23944. mainPlaylistLoader: this.mainPlaylistLoader_,
  23945. vhs: this.vhs_,
  23946. main: this.main(),
  23947. mediaTypes: this.mediaTypes_,
  23948. excludePlaylist: this.excludePlaylist.bind(this)
  23949. });
  23950. this.triggerPresenceUsage_(this.main(), media);
  23951. this.setupFirstPlay();
  23952. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  23953. this.trigger('selectedinitialmedia');
  23954. } else {
  23955. // We must wait for the active audio playlist loader to
  23956. // finish setting up before triggering this event so the
  23957. // representations API and EME setup is correct
  23958. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  23959. this.trigger('selectedinitialmedia');
  23960. });
  23961. }
  23962. });
  23963. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  23964. if (this.loadOnPlay_) {
  23965. this.tech_.off('play', this.loadOnPlay_);
  23966. }
  23967. let updatedPlaylist = this.mainPlaylistLoader_.media();
  23968. if (!updatedPlaylist) {
  23969. // exclude any variants that are not supported by the browser before selecting
  23970. // an initial media as the playlist selectors do not consider browser support
  23971. this.excludeUnsupportedVariants_();
  23972. let selectedMedia;
  23973. if (this.enableLowInitialPlaylist) {
  23974. selectedMedia = this.selectInitialPlaylist();
  23975. }
  23976. if (!selectedMedia) {
  23977. selectedMedia = this.selectPlaylist();
  23978. }
  23979. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  23980. return;
  23981. }
  23982. this.initialMedia_ = selectedMedia;
  23983. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  23984. // fire again since the playlist will be requested. In the case of vhs-json
  23985. // (where the manifest object is provided as the source), when the media
  23986. // playlist's `segments` list is already available, a media playlist won't be
  23987. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  23988. // called on its own here.
  23989. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  23990. if (!haveJsonSource) {
  23991. return;
  23992. }
  23993. updatedPlaylist = this.initialMedia_;
  23994. }
  23995. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  23996. });
  23997. this.mainPlaylistLoader_.on('error', () => {
  23998. const error = this.mainPlaylistLoader_.error;
  23999. this.excludePlaylist({
  24000. playlistToExclude: error.playlist,
  24001. error
  24002. });
  24003. });
  24004. this.mainPlaylistLoader_.on('mediachanging', () => {
  24005. this.mainSegmentLoader_.abort();
  24006. this.mainSegmentLoader_.pause();
  24007. });
  24008. this.mainPlaylistLoader_.on('mediachange', () => {
  24009. const media = this.mainPlaylistLoader_.media();
  24010. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  24011. // timeout the request.
  24012. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  24013. this.requestOptions_.timeout = 0;
  24014. } else {
  24015. this.requestOptions_.timeout = requestTimeout;
  24016. }
  24017. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  24018. // that the segments have changed in some way and use that to
  24019. // update the SegmentLoader instead of doing it twice here and
  24020. // on `loadedplaylist`
  24021. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  24022. this.mainSegmentLoader_.load();
  24023. this.tech_.trigger({
  24024. type: 'mediachange',
  24025. bubbles: true
  24026. });
  24027. });
  24028. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  24029. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  24030. // excluded for not-changing. We likely just have a really slowly updating
  24031. // playlist.
  24032. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  24033. return;
  24034. }
  24035. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  24036. if (playlistOutdated) {
  24037. // Playlist has stopped updating and we're stuck at its end. Try to
  24038. // exclude it and switch to another playlist in the hope that that
  24039. // one is updating (and give the player a chance to re-adjust to the
  24040. // safe live point).
  24041. this.excludePlaylist({
  24042. error: {
  24043. message: 'Playlist no longer updating.',
  24044. reason: 'playlist-unchanged'
  24045. }
  24046. }); // useful for monitoring QoS
  24047. this.tech_.trigger('playliststuck');
  24048. }
  24049. });
  24050. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  24051. this.tech_.trigger({
  24052. type: 'usage',
  24053. name: 'vhs-rendition-disabled'
  24054. });
  24055. });
  24056. this.mainPlaylistLoader_.on('renditionenabled', () => {
  24057. this.tech_.trigger({
  24058. type: 'usage',
  24059. name: 'vhs-rendition-enabled'
  24060. });
  24061. });
  24062. }
  24063. /**
  24064. * Given an updated media playlist (whether it was loaded for the first time, or
  24065. * refreshed for live playlists), update any relevant properties and state to reflect
  24066. * changes in the media that should be accounted for (e.g., cues and duration).
  24067. *
  24068. * @param {Object} updatedPlaylist the updated media playlist object
  24069. *
  24070. * @private
  24071. */
  24072. handleUpdatedMediaPlaylist(updatedPlaylist) {
  24073. if (this.useCueTags_) {
  24074. this.updateAdCues_(updatedPlaylist);
  24075. } // TODO: Create a new event on the PlaylistLoader that signals
  24076. // that the segments have changed in some way and use that to
  24077. // update the SegmentLoader instead of doing it twice here and
  24078. // on `mediachange`
  24079. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  24080. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  24081. // as it is possible that it was temporarily stopped while waiting for
  24082. // a playlist (e.g., in case the playlist errored and we re-requested it).
  24083. if (!this.tech_.paused()) {
  24084. this.mainSegmentLoader_.load();
  24085. if (this.audioSegmentLoader_) {
  24086. this.audioSegmentLoader_.load();
  24087. }
  24088. }
  24089. }
  24090. /**
  24091. * A helper function for triggerring presence usage events once per source
  24092. *
  24093. * @private
  24094. */
  24095. triggerPresenceUsage_(main, media) {
  24096. const mediaGroups = main.mediaGroups || {};
  24097. let defaultDemuxed = true;
  24098. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  24099. for (const mediaGroup in mediaGroups.AUDIO) {
  24100. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  24101. const properties = mediaGroups.AUDIO[mediaGroup][label];
  24102. if (!properties.uri) {
  24103. defaultDemuxed = false;
  24104. }
  24105. }
  24106. }
  24107. if (defaultDemuxed) {
  24108. this.tech_.trigger({
  24109. type: 'usage',
  24110. name: 'vhs-demuxed'
  24111. });
  24112. }
  24113. if (Object.keys(mediaGroups.SUBTITLES).length) {
  24114. this.tech_.trigger({
  24115. type: 'usage',
  24116. name: 'vhs-webvtt'
  24117. });
  24118. }
  24119. if (Vhs$1.Playlist.isAes(media)) {
  24120. this.tech_.trigger({
  24121. type: 'usage',
  24122. name: 'vhs-aes'
  24123. });
  24124. }
  24125. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  24126. this.tech_.trigger({
  24127. type: 'usage',
  24128. name: 'vhs-alternate-audio'
  24129. });
  24130. }
  24131. if (this.useCueTags_) {
  24132. this.tech_.trigger({
  24133. type: 'usage',
  24134. name: 'vhs-playlist-cue-tags'
  24135. });
  24136. }
  24137. }
  24138. shouldSwitchToMedia_(nextPlaylist) {
  24139. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  24140. const currentTime = this.tech_.currentTime();
  24141. const bufferLowWaterLine = this.bufferLowWaterLine();
  24142. const bufferHighWaterLine = this.bufferHighWaterLine();
  24143. const buffered = this.tech_.buffered();
  24144. return shouldSwitchToMedia({
  24145. buffered,
  24146. currentTime,
  24147. currentPlaylist,
  24148. nextPlaylist,
  24149. bufferLowWaterLine,
  24150. bufferHighWaterLine,
  24151. duration: this.duration(),
  24152. bufferBasedABR: this.bufferBasedABR,
  24153. log: this.logger_
  24154. });
  24155. }
  24156. /**
  24157. * Register event handlers on the segment loaders. A helper function
  24158. * for construction time.
  24159. *
  24160. * @private
  24161. */
  24162. setupSegmentLoaderListeners_() {
  24163. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  24164. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  24165. // useful to check to see if a rendition switch should be made.
  24166. this.checkABR_('bandwidthupdate');
  24167. this.tech_.trigger('bandwidthupdate');
  24168. });
  24169. this.mainSegmentLoader_.on('timeout', () => {
  24170. if (this.bufferBasedABR) {
  24171. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  24172. // Here the only consideration is that for buffer based ABR there's no guarantee
  24173. // of an immediate switch (since the bandwidth is averaged with a timeout
  24174. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  24175. this.mainSegmentLoader_.load();
  24176. }
  24177. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  24178. // based ABR.
  24179. if (!this.bufferBasedABR) {
  24180. this.mainSegmentLoader_.on('progress', () => {
  24181. this.trigger('progress');
  24182. });
  24183. }
  24184. this.mainSegmentLoader_.on('error', () => {
  24185. const error = this.mainSegmentLoader_.error();
  24186. this.excludePlaylist({
  24187. playlistToExclude: error.playlist,
  24188. error
  24189. });
  24190. });
  24191. this.mainSegmentLoader_.on('appenderror', () => {
  24192. this.error = this.mainSegmentLoader_.error_;
  24193. this.trigger('error');
  24194. });
  24195. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  24196. this.onSyncInfoUpdate_();
  24197. });
  24198. this.mainSegmentLoader_.on('timestampoffset', () => {
  24199. this.tech_.trigger({
  24200. type: 'usage',
  24201. name: 'vhs-timestamp-offset'
  24202. });
  24203. });
  24204. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  24205. this.onSyncInfoUpdate_();
  24206. });
  24207. this.audioSegmentLoader_.on('appenderror', () => {
  24208. this.error = this.audioSegmentLoader_.error_;
  24209. this.trigger('error');
  24210. });
  24211. this.mainSegmentLoader_.on('ended', () => {
  24212. this.logger_('main segment loader ended');
  24213. this.onEndOfStream();
  24214. });
  24215. this.mainSegmentLoader_.on('earlyabort', event => {
  24216. // never try to early abort with the new ABR algorithm
  24217. if (this.bufferBasedABR) {
  24218. return;
  24219. }
  24220. this.delegateLoaders_('all', ['abort']);
  24221. this.excludePlaylist({
  24222. error: {
  24223. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  24224. },
  24225. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  24226. });
  24227. });
  24228. const updateCodecs = () => {
  24229. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  24230. return this.tryToCreateSourceBuffers_();
  24231. }
  24232. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  24233. if (!codecs) {
  24234. return;
  24235. }
  24236. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  24237. };
  24238. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  24239. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  24240. this.mainSegmentLoader_.on('fmp4', () => {
  24241. if (!this.triggeredFmp4Usage) {
  24242. this.tech_.trigger({
  24243. type: 'usage',
  24244. name: 'vhs-fmp4'
  24245. });
  24246. this.triggeredFmp4Usage = true;
  24247. }
  24248. });
  24249. this.audioSegmentLoader_.on('fmp4', () => {
  24250. if (!this.triggeredFmp4Usage) {
  24251. this.tech_.trigger({
  24252. type: 'usage',
  24253. name: 'vhs-fmp4'
  24254. });
  24255. this.triggeredFmp4Usage = true;
  24256. }
  24257. });
  24258. this.audioSegmentLoader_.on('ended', () => {
  24259. this.logger_('audioSegmentLoader ended');
  24260. this.onEndOfStream();
  24261. });
  24262. }
  24263. mediaSecondsLoaded_() {
  24264. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  24265. }
  24266. /**
  24267. * Call load on our SegmentLoaders
  24268. */
  24269. load() {
  24270. this.mainSegmentLoader_.load();
  24271. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24272. this.audioSegmentLoader_.load();
  24273. }
  24274. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  24275. this.subtitleSegmentLoader_.load();
  24276. }
  24277. }
  24278. /**
  24279. * Re-tune playback quality level for the current player
  24280. * conditions. This method will perform destructive actions like removing
  24281. * already buffered content in order to readjust the currently active
  24282. * playlist quickly. This is good for manual quality changes
  24283. *
  24284. * @private
  24285. */
  24286. fastQualityChange_(media = this.selectPlaylist()) {
  24287. if (media === this.mainPlaylistLoader_.media()) {
  24288. this.logger_('skipping fastQualityChange because new media is same as old');
  24289. return;
  24290. }
  24291. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  24292. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  24293. // ahead is roughly the minimum that will accomplish this across a variety of content
  24294. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  24295. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  24296. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  24297. this.mainSegmentLoader_.resetEverything(() => {
  24298. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  24299. // from the previously enabled rendition to load before the new playlist has finished loading
  24300. if (videojs__default["default"].browser.IE_VERSION || videojs__default["default"].browser.IS_EDGE) {
  24301. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  24302. } else {
  24303. this.tech_.setCurrentTime(this.tech_.currentTime());
  24304. }
  24305. }); // don't need to reset audio as it is reset when media changes
  24306. }
  24307. /**
  24308. * Begin playback.
  24309. */
  24310. play() {
  24311. if (this.setupFirstPlay()) {
  24312. return;
  24313. }
  24314. if (this.tech_.ended()) {
  24315. this.tech_.setCurrentTime(0);
  24316. }
  24317. if (this.hasPlayed_) {
  24318. this.load();
  24319. }
  24320. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  24321. // seek forward to the live point
  24322. if (this.tech_.duration() === Infinity) {
  24323. if (this.tech_.currentTime() < seekable.start(0)) {
  24324. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  24325. }
  24326. }
  24327. }
  24328. /**
  24329. * Seek to the latest media position if this is a live video and the
  24330. * player and video are loaded and initialized.
  24331. */
  24332. setupFirstPlay() {
  24333. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  24334. // If 1) there is no active media
  24335. // 2) the player is paused
  24336. // 3) the first play has already been setup
  24337. // then exit early
  24338. if (!media || this.tech_.paused() || this.hasPlayed_) {
  24339. return false;
  24340. } // when the video is a live stream
  24341. if (!media.endList) {
  24342. const seekable = this.seekable();
  24343. if (!seekable.length) {
  24344. // without a seekable range, the player cannot seek to begin buffering at the live
  24345. // point
  24346. return false;
  24347. }
  24348. if (videojs__default["default"].browser.IE_VERSION && this.tech_.readyState() === 0) {
  24349. // IE11 throws an InvalidStateError if you try to set currentTime while the
  24350. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  24351. this.tech_.one('loadedmetadata', () => {
  24352. this.trigger('firstplay');
  24353. this.tech_.setCurrentTime(seekable.end(0));
  24354. this.hasPlayed_ = true;
  24355. });
  24356. return false;
  24357. } // trigger firstplay to inform the source handler to ignore the next seek event
  24358. this.trigger('firstplay'); // seek to the live point
  24359. this.tech_.setCurrentTime(seekable.end(0));
  24360. }
  24361. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  24362. this.load();
  24363. return true;
  24364. }
  24365. /**
  24366. * handle the sourceopen event on the MediaSource
  24367. *
  24368. * @private
  24369. */
  24370. handleSourceOpen_() {
  24371. // Only attempt to create the source buffer if none already exist.
  24372. // handleSourceOpen is also called when we are "re-opening" a source buffer
  24373. // after `endOfStream` has been called (in response to a seek for instance)
  24374. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  24375. // code in video.js but is required because play() must be invoked
  24376. // *after* the media source has opened.
  24377. if (this.tech_.autoplay()) {
  24378. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  24379. // on browsers which return a promise
  24380. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  24381. playPromise.then(null, e => {});
  24382. }
  24383. }
  24384. this.trigger('sourceopen');
  24385. }
  24386. /**
  24387. * handle the sourceended event on the MediaSource
  24388. *
  24389. * @private
  24390. */
  24391. handleSourceEnded_() {
  24392. if (!this.inbandTextTracks_.metadataTrack_) {
  24393. return;
  24394. }
  24395. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  24396. if (!cues || !cues.length) {
  24397. return;
  24398. }
  24399. const duration = this.duration();
  24400. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  24401. }
  24402. /**
  24403. * handle the durationchange event on the MediaSource
  24404. *
  24405. * @private
  24406. */
  24407. handleDurationChange_() {
  24408. this.tech_.trigger('durationchange');
  24409. }
  24410. /**
  24411. * Calls endOfStream on the media source when all active stream types have called
  24412. * endOfStream
  24413. *
  24414. * @param {string} streamType
  24415. * Stream type of the segment loader that called endOfStream
  24416. * @private
  24417. */
  24418. onEndOfStream() {
  24419. let isEndOfStream = this.mainSegmentLoader_.ended_;
  24420. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24421. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  24422. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  24423. // if we do not know if the main segment loader contains video yet or if we
  24424. // definitively know the main segment loader contains video, then we need to wait
  24425. // for both main and audio segment loaders to call endOfStream
  24426. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  24427. } else {
  24428. // otherwise just rely on the audio loader
  24429. isEndOfStream = this.audioSegmentLoader_.ended_;
  24430. }
  24431. }
  24432. if (!isEndOfStream) {
  24433. return;
  24434. }
  24435. this.stopABRTimer_();
  24436. this.sourceUpdater_.endOfStream();
  24437. }
  24438. /**
  24439. * Check if a playlist has stopped being updated
  24440. *
  24441. * @param {Object} playlist the media playlist object
  24442. * @return {boolean} whether the playlist has stopped being updated or not
  24443. */
  24444. stuckAtPlaylistEnd_(playlist) {
  24445. const seekable = this.seekable();
  24446. if (!seekable.length) {
  24447. // playlist doesn't have enough information to determine whether we are stuck
  24448. return false;
  24449. }
  24450. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  24451. if (expired === null) {
  24452. return false;
  24453. } // does not use the safe live end to calculate playlist end, since we
  24454. // don't want to say we are stuck while there is still content
  24455. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  24456. const currentTime = this.tech_.currentTime();
  24457. const buffered = this.tech_.buffered();
  24458. if (!buffered.length) {
  24459. // return true if the playhead reached the absolute end of the playlist
  24460. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  24461. }
  24462. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  24463. // end of playlist
  24464. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  24465. }
  24466. /**
  24467. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  24468. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  24469. *
  24470. * @param {Object=} playlistToExclude
  24471. * the playlist to exclude, defaults to the currently selected playlist
  24472. * @param {Object=} error
  24473. * an optional error
  24474. * @param {number=} playlistExclusionDuration
  24475. * an optional number of seconds to exclude the playlist
  24476. */
  24477. excludePlaylist({
  24478. playlistToExclude = this.mainPlaylistLoader_.media(),
  24479. error = {},
  24480. playlistExclusionDuration
  24481. }) {
  24482. // If the `error` was generated by the playlist loader, it will contain
  24483. // the playlist we were trying to load (but failed) and that should be
  24484. // excluded instead of the currently selected playlist which is likely
  24485. // out-of-date in this scenario
  24486. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  24487. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  24488. // trying to load the main OR while we were disposing of the tech
  24489. if (!playlistToExclude) {
  24490. this.error = error;
  24491. if (this.mediaSource.readyState !== 'open') {
  24492. this.trigger('error');
  24493. } else {
  24494. this.sourceUpdater_.endOfStream('network');
  24495. }
  24496. return;
  24497. }
  24498. playlistToExclude.playlistErrors_++;
  24499. const playlists = this.mainPlaylistLoader_.main.playlists;
  24500. const enabledPlaylists = playlists.filter(isEnabled);
  24501. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  24502. // forever
  24503. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  24504. videojs__default["default"].log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  24505. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  24506. return this.mainPlaylistLoader_.load(isFinalRendition);
  24507. }
  24508. if (isFinalRendition) {
  24509. // Since we're on the final non-excluded playlist, and we're about to exclude
  24510. // it, instead of erring the player or retrying this playlist, clear out the current
  24511. // exclusion list. This allows other playlists to be attempted in case any have been
  24512. // fixed.
  24513. let reincluded = false;
  24514. playlists.forEach(playlist => {
  24515. // skip current playlist which is about to be excluded
  24516. if (playlist === playlistToExclude) {
  24517. return;
  24518. }
  24519. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  24520. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  24521. reincluded = true;
  24522. delete playlist.excludeUntil;
  24523. }
  24524. });
  24525. if (reincluded) {
  24526. videojs__default["default"].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
  24527. // playlist. This is needed for users relying on the retryplaylist event to catch a
  24528. // case where the player might be stuck and looping through "dead" playlists.
  24529. this.tech_.trigger('retryplaylist');
  24530. }
  24531. } // Exclude this playlist
  24532. let excludeUntil;
  24533. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  24534. excludeUntil = Infinity;
  24535. } else {
  24536. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  24537. }
  24538. playlistToExclude.excludeUntil = excludeUntil;
  24539. if (error.reason) {
  24540. playlistToExclude.lastExcludeReason_ = error.reason;
  24541. }
  24542. this.tech_.trigger('excludeplaylist');
  24543. this.tech_.trigger({
  24544. type: 'usage',
  24545. name: 'vhs-rendition-excluded'
  24546. }); // TODO: only load a new playlist if we're excluding the current playlist
  24547. // If this function was called with a playlist that's not the current active playlist
  24548. // (e.g., media().id !== playlistToExclude.id),
  24549. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  24550. const nextPlaylist = this.selectPlaylist();
  24551. if (!nextPlaylist) {
  24552. this.error = 'Playback cannot continue. No available working or supported playlists.';
  24553. this.trigger('error');
  24554. return;
  24555. }
  24556. const logFn = error.internal ? this.logger_ : videojs__default["default"].log.warn;
  24557. const errorMessage = error.message ? ' ' + error.message : '';
  24558. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  24559. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  24560. this.delegateLoaders_('audio', ['abort', 'pause']);
  24561. } // if subtitle group changed reset subtitle loaders
  24562. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  24563. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  24564. }
  24565. this.delegateLoaders_('main', ['abort', 'pause']);
  24566. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  24567. 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
  24568. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  24569. }
  24570. /**
  24571. * Pause all segment/playlist loaders
  24572. */
  24573. pauseLoading() {
  24574. this.delegateLoaders_('all', ['abort', 'pause']);
  24575. this.stopABRTimer_();
  24576. }
  24577. /**
  24578. * Call a set of functions in order on playlist loaders, segment loaders,
  24579. * or both types of loaders.
  24580. *
  24581. * @param {string} filter
  24582. * Filter loaders that should call fnNames using a string. Can be:
  24583. * * all - run on all loaders
  24584. * * audio - run on all audio loaders
  24585. * * subtitle - run on all subtitle loaders
  24586. * * main - run on the main loaders
  24587. *
  24588. * @param {Array|string} fnNames
  24589. * A string or array of function names to call.
  24590. */
  24591. delegateLoaders_(filter, fnNames) {
  24592. const loaders = [];
  24593. const dontFilterPlaylist = filter === 'all';
  24594. if (dontFilterPlaylist || filter === 'main') {
  24595. loaders.push(this.mainPlaylistLoader_);
  24596. }
  24597. const mediaTypes = [];
  24598. if (dontFilterPlaylist || filter === 'audio') {
  24599. mediaTypes.push('AUDIO');
  24600. }
  24601. if (dontFilterPlaylist || filter === 'subtitle') {
  24602. mediaTypes.push('CLOSED-CAPTIONS');
  24603. mediaTypes.push('SUBTITLES');
  24604. }
  24605. mediaTypes.forEach(mediaType => {
  24606. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  24607. if (loader) {
  24608. loaders.push(loader);
  24609. }
  24610. });
  24611. ['main', 'audio', 'subtitle'].forEach(name => {
  24612. const loader = this[`${name}SegmentLoader_`];
  24613. if (loader && (filter === name || filter === 'all')) {
  24614. loaders.push(loader);
  24615. }
  24616. });
  24617. loaders.forEach(loader => fnNames.forEach(fnName => {
  24618. if (typeof loader[fnName] === 'function') {
  24619. loader[fnName]();
  24620. }
  24621. }));
  24622. }
  24623. /**
  24624. * set the current time on all segment loaders
  24625. *
  24626. * @param {TimeRange} currentTime the current time to set
  24627. * @return {TimeRange} the current time
  24628. */
  24629. setCurrentTime(currentTime) {
  24630. const buffered = findRange(this.tech_.buffered(), currentTime);
  24631. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  24632. // return immediately if the metadata is not ready yet
  24633. return 0;
  24634. } // it's clearly an edge-case but don't thrown an error if asked to
  24635. // seek within an empty playlist
  24636. if (!this.mainPlaylistLoader_.media().segments) {
  24637. return 0;
  24638. } // if the seek location is already buffered, continue buffering as usual
  24639. if (buffered && buffered.length) {
  24640. return currentTime;
  24641. } // cancel outstanding requests so we begin buffering at the new
  24642. // location
  24643. this.mainSegmentLoader_.resetEverything();
  24644. this.mainSegmentLoader_.abort();
  24645. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24646. this.audioSegmentLoader_.resetEverything();
  24647. this.audioSegmentLoader_.abort();
  24648. }
  24649. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  24650. this.subtitleSegmentLoader_.resetEverything();
  24651. this.subtitleSegmentLoader_.abort();
  24652. } // start segment loader loading in case they are paused
  24653. this.load();
  24654. }
  24655. /**
  24656. * get the current duration
  24657. *
  24658. * @return {TimeRange} the duration
  24659. */
  24660. duration() {
  24661. if (!this.mainPlaylistLoader_) {
  24662. return 0;
  24663. }
  24664. const media = this.mainPlaylistLoader_.media();
  24665. if (!media) {
  24666. // no playlists loaded yet, so can't determine a duration
  24667. return 0;
  24668. } // Don't rely on the media source for duration in the case of a live playlist since
  24669. // setting the native MediaSource's duration to infinity ends up with consequences to
  24670. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  24671. //
  24672. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  24673. // however, few browsers have support for setLiveSeekableRange()
  24674. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  24675. //
  24676. // Until a time when the duration of the media source can be set to infinity, and a
  24677. // seekable range specified across browsers, just return Infinity.
  24678. if (!media.endList) {
  24679. return Infinity;
  24680. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  24681. // available). If it's not available, fall back to a playlist-calculated estimate.
  24682. if (this.mediaSource) {
  24683. return this.mediaSource.duration;
  24684. }
  24685. return Vhs$1.Playlist.duration(media);
  24686. }
  24687. /**
  24688. * check the seekable range
  24689. *
  24690. * @return {TimeRange} the seekable range
  24691. */
  24692. seekable() {
  24693. return this.seekable_;
  24694. }
  24695. onSyncInfoUpdate_() {
  24696. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  24697. //
  24698. // A fix was made to this function where a check for
  24699. // this.sourceUpdater_.hasCreatedSourceBuffers
  24700. // was added to ensure that both source buffers were created before seekable was
  24701. // updated. However, it originally had a bug where it was checking for a true and
  24702. // returning early instead of checking for false. Setting it to check for false to
  24703. // return early though created other issues. A call to play() would check for seekable
  24704. // end without verifying that a seekable range was present. In addition, even checking
  24705. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  24706. // due to a media update calling load on the segment loaders, skipping a seek to live,
  24707. // thereby starting live streams at the beginning of the stream rather than at the end.
  24708. //
  24709. // This conditional should be fixed to wait for the creation of two source buffers at
  24710. // the same time as the other sections of code are fixed to properly seek to live and
  24711. // not throw an error due to checking for a seekable end when no seekable range exists.
  24712. //
  24713. // For now, fall back to the older behavior, with the understanding that the seekable
  24714. // range may not be completely correct, leading to a suboptimal initial live point.
  24715. if (!this.mainPlaylistLoader_) {
  24716. return;
  24717. }
  24718. let media = this.mainPlaylistLoader_.media();
  24719. if (!media) {
  24720. return;
  24721. }
  24722. let expired = this.syncController_.getExpiredTime(media, this.duration());
  24723. if (expired === null) {
  24724. // not enough information to update seekable
  24725. return;
  24726. }
  24727. const main = this.mainPlaylistLoader_.main;
  24728. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  24729. if (mainSeekable.length === 0) {
  24730. return;
  24731. }
  24732. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  24733. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  24734. expired = this.syncController_.getExpiredTime(media, this.duration());
  24735. if (expired === null) {
  24736. return;
  24737. }
  24738. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  24739. if (audioSeekable.length === 0) {
  24740. return;
  24741. }
  24742. }
  24743. let oldEnd;
  24744. let oldStart;
  24745. if (this.seekable_ && this.seekable_.length) {
  24746. oldEnd = this.seekable_.end(0);
  24747. oldStart = this.seekable_.start(0);
  24748. }
  24749. if (!audioSeekable) {
  24750. // seekable has been calculated based on buffering video data so it
  24751. // can be returned directly
  24752. this.seekable_ = mainSeekable;
  24753. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  24754. // seekables are pretty far off, rely on main
  24755. this.seekable_ = mainSeekable;
  24756. } else {
  24757. 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)]]);
  24758. } // seekable is the same as last time
  24759. if (this.seekable_ && this.seekable_.length) {
  24760. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  24761. return;
  24762. }
  24763. }
  24764. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  24765. this.tech_.trigger('seekablechanged');
  24766. }
  24767. /**
  24768. * Update the player duration
  24769. */
  24770. updateDuration(isLive) {
  24771. if (this.updateDuration_) {
  24772. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  24773. this.updateDuration_ = null;
  24774. }
  24775. if (this.mediaSource.readyState !== 'open') {
  24776. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  24777. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  24778. return;
  24779. }
  24780. if (isLive) {
  24781. const seekable = this.seekable();
  24782. if (!seekable.length) {
  24783. return;
  24784. } // Even in the case of a live playlist, the native MediaSource's duration should not
  24785. // be set to Infinity (even though this would be expected for a live playlist), since
  24786. // setting the native MediaSource's duration to infinity ends up with consequences to
  24787. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  24788. //
  24789. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  24790. // however, few browsers have support for setLiveSeekableRange()
  24791. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  24792. //
  24793. // Until a time when the duration of the media source can be set to infinity, and a
  24794. // seekable range specified across browsers, the duration should be greater than or
  24795. // equal to the last possible seekable value.
  24796. // MediaSource duration starts as NaN
  24797. // It is possible (and probable) that this case will never be reached for many
  24798. // sources, since the MediaSource reports duration as the highest value without
  24799. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  24800. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  24801. // time will be between 0 and 100, the native media source may report the duration
  24802. // as 200. However, since we report duration separate from the media source (as
  24803. // Infinity), and as long as the native media source duration value is greater than
  24804. // our reported seekable range, seeks will work as expected. The large number as
  24805. // duration for live is actually a strategy used by some players to work around the
  24806. // issue of live seekable ranges cited above.
  24807. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  24808. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  24809. }
  24810. return;
  24811. }
  24812. const buffered = this.tech_.buffered();
  24813. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  24814. if (buffered.length > 0) {
  24815. duration = Math.max(duration, buffered.end(buffered.length - 1));
  24816. }
  24817. if (this.mediaSource.duration !== duration) {
  24818. this.sourceUpdater_.setDuration(duration);
  24819. }
  24820. }
  24821. /**
  24822. * dispose of the PlaylistController and everything
  24823. * that it controls
  24824. */
  24825. dispose() {
  24826. this.trigger('dispose');
  24827. this.decrypter_.terminate();
  24828. this.mainPlaylistLoader_.dispose();
  24829. this.mainSegmentLoader_.dispose();
  24830. if (this.loadOnPlay_) {
  24831. this.tech_.off('play', this.loadOnPlay_);
  24832. }
  24833. ['AUDIO', 'SUBTITLES'].forEach(type => {
  24834. const groups = this.mediaTypes_[type].groups;
  24835. for (const id in groups) {
  24836. groups[id].forEach(group => {
  24837. if (group.playlistLoader) {
  24838. group.playlistLoader.dispose();
  24839. }
  24840. });
  24841. }
  24842. });
  24843. this.audioSegmentLoader_.dispose();
  24844. this.subtitleSegmentLoader_.dispose();
  24845. this.sourceUpdater_.dispose();
  24846. this.timelineChangeController_.dispose();
  24847. this.stopABRTimer_();
  24848. if (this.updateDuration_) {
  24849. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  24850. }
  24851. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  24852. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  24853. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  24854. this.off();
  24855. }
  24856. /**
  24857. * return the main playlist object if we have one
  24858. *
  24859. * @return {Object} the main playlist object that we parsed
  24860. */
  24861. main() {
  24862. return this.mainPlaylistLoader_.main;
  24863. }
  24864. /**
  24865. * return the currently selected playlist
  24866. *
  24867. * @return {Object} the currently selected playlist object that we parsed
  24868. */
  24869. media() {
  24870. // playlist loader will not return media if it has not been fully loaded
  24871. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  24872. }
  24873. areMediaTypesKnown_() {
  24874. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  24875. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  24876. // otherwise check on the segment loader.
  24877. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  24878. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  24879. return false;
  24880. }
  24881. return true;
  24882. }
  24883. getCodecsOrExclude_() {
  24884. const media = {
  24885. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  24886. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  24887. };
  24888. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  24889. media.video = media.main;
  24890. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  24891. const codecs = {};
  24892. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  24893. if (media.main.hasVideo) {
  24894. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  24895. }
  24896. if (media.main.isMuxed) {
  24897. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  24898. }
  24899. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  24900. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  24901. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  24902. } // no codecs, no playback.
  24903. if (!codecs.audio && !codecs.video) {
  24904. this.excludePlaylist({
  24905. playlistToExclude: playlist,
  24906. error: {
  24907. message: 'Could not determine codecs for playlist.'
  24908. },
  24909. playlistExclusionDuration: Infinity
  24910. });
  24911. return;
  24912. } // fmp4 relies on browser support, while ts relies on muxer support
  24913. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  24914. const unsupportedCodecs = {};
  24915. let unsupportedAudio;
  24916. ['video', 'audio'].forEach(function (type) {
  24917. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  24918. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  24919. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  24920. unsupportedCodecs[supporter].push(codecs[type]);
  24921. if (type === 'audio') {
  24922. unsupportedAudio = supporter;
  24923. }
  24924. }
  24925. });
  24926. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  24927. const audioGroup = playlist.attributes.AUDIO;
  24928. this.main().playlists.forEach(variant => {
  24929. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  24930. if (variantAudioGroup === audioGroup && variant !== playlist) {
  24931. variant.excludeUntil = Infinity;
  24932. }
  24933. });
  24934. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  24935. } // if we have any unsupported codecs exclude this playlist.
  24936. if (Object.keys(unsupportedCodecs).length) {
  24937. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  24938. if (acc) {
  24939. acc += ', ';
  24940. }
  24941. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  24942. return acc;
  24943. }, '') + '.';
  24944. this.excludePlaylist({
  24945. playlistToExclude: playlist,
  24946. error: {
  24947. internal: true,
  24948. message
  24949. },
  24950. playlistExclusionDuration: Infinity
  24951. });
  24952. return;
  24953. } // check if codec switching is happening
  24954. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  24955. const switchMessages = [];
  24956. ['video', 'audio'].forEach(type => {
  24957. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  24958. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  24959. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  24960. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  24961. }
  24962. });
  24963. if (switchMessages.length) {
  24964. this.excludePlaylist({
  24965. playlistToExclude: playlist,
  24966. error: {
  24967. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  24968. internal: true
  24969. },
  24970. playlistExclusionDuration: Infinity
  24971. });
  24972. return;
  24973. }
  24974. } // TODO: when using the muxer shouldn't we just return
  24975. // the codecs that the muxer outputs?
  24976. return codecs;
  24977. }
  24978. /**
  24979. * Create source buffers and exlude any incompatible renditions.
  24980. *
  24981. * @private
  24982. */
  24983. tryToCreateSourceBuffers_() {
  24984. // media source is not ready yet or sourceBuffers are already
  24985. // created.
  24986. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  24987. return;
  24988. }
  24989. if (!this.areMediaTypesKnown_()) {
  24990. return;
  24991. }
  24992. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  24993. if (!codecs) {
  24994. return;
  24995. }
  24996. this.sourceUpdater_.createSourceBuffers(codecs);
  24997. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  24998. this.excludeIncompatibleVariants_(codecString);
  24999. }
  25000. /**
  25001. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  25002. */
  25003. excludeUnsupportedVariants_() {
  25004. const playlists = this.main().playlists;
  25005. const ids = []; // TODO: why don't we have a property to loop through all
  25006. // playlist? Why did we ever mix indexes and keys?
  25007. Object.keys(playlists).forEach(key => {
  25008. const variant = playlists[key]; // check if we already processed this playlist.
  25009. if (ids.indexOf(variant.id) !== -1) {
  25010. return;
  25011. }
  25012. ids.push(variant.id);
  25013. const codecs = codecsForPlaylist(this.main, variant);
  25014. const unsupported = [];
  25015. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  25016. unsupported.push(`audio codec ${codecs.audio}`);
  25017. }
  25018. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  25019. unsupported.push(`video codec ${codecs.video}`);
  25020. }
  25021. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  25022. unsupported.push(`text codec ${codecs.text}`);
  25023. }
  25024. if (unsupported.length) {
  25025. variant.excludeUntil = Infinity;
  25026. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  25027. }
  25028. });
  25029. }
  25030. /**
  25031. * Exclude playlists that are known to be codec or
  25032. * stream-incompatible with the SourceBuffer configuration. For
  25033. * instance, Media Source Extensions would cause the video element to
  25034. * stall waiting for video data if you switched from a variant with
  25035. * video and audio to an audio-only one.
  25036. *
  25037. * @param {Object} media a media playlist compatible with the current
  25038. * set of SourceBuffers. Variants in the current main playlist that
  25039. * do not appear to have compatible codec or stream configurations
  25040. * will be excluded from the default playlist selection algorithm
  25041. * indefinitely.
  25042. * @private
  25043. */
  25044. excludeIncompatibleVariants_(codecString) {
  25045. const ids = [];
  25046. const playlists = this.main().playlists;
  25047. const codecs = unwrapCodecList(parseCodecs(codecString));
  25048. const codecCount_ = codecCount(codecs);
  25049. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  25050. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  25051. Object.keys(playlists).forEach(key => {
  25052. const variant = playlists[key]; // check if we already processed this playlist.
  25053. // or it if it is already excluded forever.
  25054. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  25055. return;
  25056. }
  25057. ids.push(variant.id);
  25058. const exclusionReasons = []; // get codecs from the playlist for this variant
  25059. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  25060. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  25061. // variant is incompatible. Wait for mux.js to probe
  25062. if (!variantCodecs.audio && !variantCodecs.video) {
  25063. return;
  25064. } // TODO: we can support this by removing the
  25065. // old media source and creating a new one, but it will take some work.
  25066. // The number of streams cannot change
  25067. if (variantCodecCount !== codecCount_) {
  25068. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  25069. } // only exclude playlists by codec change, if codecs cannot switch
  25070. // during playback.
  25071. if (!this.sourceUpdater_.canChangeType()) {
  25072. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  25073. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  25074. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  25075. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  25076. } // the audio codec cannot change
  25077. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  25078. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  25079. }
  25080. }
  25081. if (exclusionReasons.length) {
  25082. variant.excludeUntil = Infinity;
  25083. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  25084. }
  25085. });
  25086. }
  25087. updateAdCues_(media) {
  25088. let offset = 0;
  25089. const seekable = this.seekable();
  25090. if (seekable.length) {
  25091. offset = seekable.start(0);
  25092. }
  25093. updateAdCues(media, this.cueTagsTrack_, offset);
  25094. }
  25095. /**
  25096. * Calculates the desired forward buffer length based on current time
  25097. *
  25098. * @return {number} Desired forward buffer length in seconds
  25099. */
  25100. goalBufferLength() {
  25101. const currentTime = this.tech_.currentTime();
  25102. const initial = Config.GOAL_BUFFER_LENGTH;
  25103. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  25104. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  25105. return Math.min(initial + currentTime * rate, max);
  25106. }
  25107. /**
  25108. * Calculates the desired buffer low water line based on current time
  25109. *
  25110. * @return {number} Desired buffer low water line in seconds
  25111. */
  25112. bufferLowWaterLine() {
  25113. const currentTime = this.tech_.currentTime();
  25114. const initial = Config.BUFFER_LOW_WATER_LINE;
  25115. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  25116. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  25117. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  25118. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  25119. }
  25120. bufferHighWaterLine() {
  25121. return Config.BUFFER_HIGH_WATER_LINE;
  25122. }
  25123. }
  25124. /**
  25125. * Returns a function that acts as the Enable/disable playlist function.
  25126. *
  25127. * @param {PlaylistLoader} loader - The main playlist loader
  25128. * @param {string} playlistID - id of the playlist
  25129. * @param {Function} changePlaylistFn - A function to be called after a
  25130. * playlist's enabled-state has been changed. Will NOT be called if a
  25131. * playlist's enabled-state is unchanged
  25132. * @param {boolean=} enable - Value to set the playlist enabled-state to
  25133. * or if undefined returns the current enabled-state for the playlist
  25134. * @return {Function} Function for setting/getting enabled
  25135. */
  25136. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  25137. const playlist = loader.main.playlists[playlistID];
  25138. const incompatible = isIncompatible(playlist);
  25139. const currentlyEnabled = isEnabled(playlist);
  25140. if (typeof enable === 'undefined') {
  25141. return currentlyEnabled;
  25142. }
  25143. if (enable) {
  25144. delete playlist.disabled;
  25145. } else {
  25146. playlist.disabled = true;
  25147. }
  25148. if (enable !== currentlyEnabled && !incompatible) {
  25149. // Ensure the outside world knows about our changes
  25150. changePlaylistFn();
  25151. if (enable) {
  25152. loader.trigger('renditionenabled');
  25153. } else {
  25154. loader.trigger('renditiondisabled');
  25155. }
  25156. }
  25157. return enable;
  25158. };
  25159. /**
  25160. * The representation object encapsulates the publicly visible information
  25161. * in a media playlist along with a setter/getter-type function (enabled)
  25162. * for changing the enabled-state of a particular playlist entry
  25163. *
  25164. * @class Representation
  25165. */
  25166. class Representation {
  25167. constructor(vhsHandler, playlist, id) {
  25168. const {
  25169. playlistController_: pc
  25170. } = vhsHandler;
  25171. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  25172. if (playlist.attributes) {
  25173. const resolution = playlist.attributes.RESOLUTION;
  25174. this.width = resolution && resolution.width;
  25175. this.height = resolution && resolution.height;
  25176. this.bandwidth = playlist.attributes.BANDWIDTH;
  25177. this.frameRate = playlist.attributes['FRAME-RATE'];
  25178. }
  25179. this.codecs = codecsForPlaylist(pc.main(), playlist);
  25180. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  25181. // within the main playlist
  25182. this.id = id; // Partially-apply the enableFunction to create a playlist-
  25183. // specific variant
  25184. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  25185. }
  25186. }
  25187. /**
  25188. * A mixin function that adds the `representations` api to an instance
  25189. * of the VhsHandler class
  25190. *
  25191. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  25192. * representation API into
  25193. */
  25194. const renditionSelectionMixin = function (vhsHandler) {
  25195. // Add a single API-specific function to the VhsHandler instance
  25196. vhsHandler.representations = () => {
  25197. const main = vhsHandler.playlistController_.main();
  25198. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  25199. if (!playlists) {
  25200. return [];
  25201. }
  25202. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  25203. };
  25204. };
  25205. /**
  25206. * @file playback-watcher.js
  25207. *
  25208. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  25209. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  25210. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  25211. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  25212. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  25213. */
  25214. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  25215. /**
  25216. * @class PlaybackWatcher
  25217. */
  25218. class PlaybackWatcher {
  25219. /**
  25220. * Represents an PlaybackWatcher object.
  25221. *
  25222. * @class
  25223. * @param {Object} options an object that includes the tech and settings
  25224. */
  25225. constructor(options) {
  25226. this.playlistController_ = options.playlistController;
  25227. this.tech_ = options.tech;
  25228. this.seekable = options.seekable;
  25229. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  25230. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  25231. this.media = options.media;
  25232. this.consecutiveUpdates = 0;
  25233. this.lastRecordedTime = null;
  25234. this.checkCurrentTimeTimeout_ = null;
  25235. this.logger_ = logger('PlaybackWatcher');
  25236. this.logger_('initialize');
  25237. const playHandler = () => this.monitorCurrentTime_();
  25238. const canPlayHandler = () => this.monitorCurrentTime_();
  25239. const waitingHandler = () => this.techWaiting_();
  25240. const cancelTimerHandler = () => this.resetTimeUpdate_();
  25241. const pc = this.playlistController_;
  25242. const loaderTypes = ['main', 'subtitle', 'audio'];
  25243. const loaderChecks = {};
  25244. loaderTypes.forEach(type => {
  25245. loaderChecks[type] = {
  25246. reset: () => this.resetSegmentDownloads_(type),
  25247. updateend: () => this.checkSegmentDownloads_(type)
  25248. };
  25249. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  25250. // isn't changing we want to reset. We cannot assume that the new rendition
  25251. // will also be stalled, until after new appends.
  25252. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  25253. // This prevents one segment playlists (single vtt or single segment content)
  25254. // from being detected as stalling. As the buffer will not change in those cases, since
  25255. // the buffer is the entire video duration.
  25256. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  25257. });
  25258. /**
  25259. * We check if a seek was into a gap through the following steps:
  25260. * 1. We get a seeking event and we do not get a seeked event. This means that
  25261. * a seek was attempted but not completed.
  25262. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  25263. * removed everything from our buffer and appended a segment, and should be ready
  25264. * to check for gaps.
  25265. */
  25266. const setSeekingHandlers = fn => {
  25267. ['main', 'audio'].forEach(type => {
  25268. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  25269. });
  25270. };
  25271. this.seekingAppendCheck_ = () => {
  25272. if (this.fixesBadSeeks_()) {
  25273. this.consecutiveUpdates = 0;
  25274. this.lastRecordedTime = this.tech_.currentTime();
  25275. setSeekingHandlers('off');
  25276. }
  25277. };
  25278. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  25279. this.watchForBadSeeking_ = () => {
  25280. this.clearSeekingAppendCheck_();
  25281. setSeekingHandlers('on');
  25282. };
  25283. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  25284. this.tech_.on('seeking', this.watchForBadSeeking_);
  25285. this.tech_.on('waiting', waitingHandler);
  25286. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  25287. this.tech_.on('canplay', canPlayHandler);
  25288. /*
  25289. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  25290. is surfaced in one of two ways:
  25291. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  25292. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  25293. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  25294. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  25295. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  25296. even if the player is in a playing state
  25297. */
  25298. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  25299. this.dispose = () => {
  25300. this.clearSeekingAppendCheck_();
  25301. this.logger_('dispose');
  25302. this.tech_.off('waiting', waitingHandler);
  25303. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  25304. this.tech_.off('canplay', canPlayHandler);
  25305. this.tech_.off('play', playHandler);
  25306. this.tech_.off('seeking', this.watchForBadSeeking_);
  25307. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  25308. loaderTypes.forEach(type => {
  25309. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  25310. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  25311. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  25312. });
  25313. if (this.checkCurrentTimeTimeout_) {
  25314. window.clearTimeout(this.checkCurrentTimeTimeout_);
  25315. }
  25316. this.resetTimeUpdate_();
  25317. };
  25318. }
  25319. /**
  25320. * Periodically check current time to see if playback stopped
  25321. *
  25322. * @private
  25323. */
  25324. monitorCurrentTime_() {
  25325. this.checkCurrentTime_();
  25326. if (this.checkCurrentTimeTimeout_) {
  25327. window.clearTimeout(this.checkCurrentTimeTimeout_);
  25328. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  25329. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  25330. }
  25331. /**
  25332. * Reset stalled download stats for a specific type of loader
  25333. *
  25334. * @param {string} type
  25335. * The segment loader type to check.
  25336. *
  25337. * @listens SegmentLoader#playlistupdate
  25338. * @listens Tech#seeking
  25339. * @listens Tech#seeked
  25340. */
  25341. resetSegmentDownloads_(type) {
  25342. const loader = this.playlistController_[`${type}SegmentLoader_`];
  25343. if (this[`${type}StalledDownloads_`] > 0) {
  25344. this.logger_(`resetting possible stalled download count for ${type} loader`);
  25345. }
  25346. this[`${type}StalledDownloads_`] = 0;
  25347. this[`${type}Buffered_`] = loader.buffered_();
  25348. }
  25349. /**
  25350. * Checks on every segment `appendsdone` to see
  25351. * if segment appends are making progress. If they are not
  25352. * and we are still downloading bytes. We exclude the playlist.
  25353. *
  25354. * @param {string} type
  25355. * The segment loader type to check.
  25356. *
  25357. * @listens SegmentLoader#appendsdone
  25358. */
  25359. checkSegmentDownloads_(type) {
  25360. const pc = this.playlistController_;
  25361. const loader = pc[`${type}SegmentLoader_`];
  25362. const buffered = loader.buffered_();
  25363. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  25364. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  25365. // the buffered value for this loader changed
  25366. // appends are working
  25367. if (isBufferedDifferent) {
  25368. this.resetSegmentDownloads_(type);
  25369. return;
  25370. }
  25371. this[`${type}StalledDownloads_`]++;
  25372. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  25373. playlistId: loader.playlist_ && loader.playlist_.id,
  25374. buffered: timeRangesToArray(buffered)
  25375. }); // after 10 possibly stalled appends with no reset, exclude
  25376. if (this[`${type}StalledDownloads_`] < 10) {
  25377. return;
  25378. }
  25379. this.logger_(`${type} loader stalled download exclusion`);
  25380. this.resetSegmentDownloads_(type);
  25381. this.tech_.trigger({
  25382. type: 'usage',
  25383. name: `vhs-${type}-download-exclusion`
  25384. });
  25385. if (type === 'subtitle') {
  25386. return;
  25387. } // TODO: should we exclude audio tracks rather than main tracks
  25388. // when type is audio?
  25389. pc.excludePlaylist({
  25390. error: {
  25391. message: `Excessive ${type} segment downloading detected.`
  25392. },
  25393. playlistExclusionDuration: Infinity
  25394. });
  25395. }
  25396. /**
  25397. * The purpose of this function is to emulate the "waiting" event on
  25398. * browsers that do not emit it when they are waiting for more
  25399. * data to continue playback
  25400. *
  25401. * @private
  25402. */
  25403. checkCurrentTime_() {
  25404. if (this.tech_.paused() || this.tech_.seeking()) {
  25405. return;
  25406. }
  25407. const currentTime = this.tech_.currentTime();
  25408. const buffered = this.tech_.buffered();
  25409. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  25410. // If current time is at the end of the final buffered region, then any playback
  25411. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  25412. // should fire a `waiting` event in this scenario, but due to browser and tech
  25413. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  25414. // responding to a native `waiting` event when the tech fails to emit one.
  25415. return this.techWaiting_();
  25416. }
  25417. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  25418. this.consecutiveUpdates++;
  25419. this.waiting_();
  25420. } else if (currentTime === this.lastRecordedTime) {
  25421. this.consecutiveUpdates++;
  25422. } else {
  25423. this.consecutiveUpdates = 0;
  25424. this.lastRecordedTime = currentTime;
  25425. }
  25426. }
  25427. /**
  25428. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  25429. *
  25430. * @private
  25431. */
  25432. resetTimeUpdate_() {
  25433. this.consecutiveUpdates = 0;
  25434. }
  25435. /**
  25436. * Fixes situations where there's a bad seek
  25437. *
  25438. * @return {boolean} whether an action was taken to fix the seek
  25439. * @private
  25440. */
  25441. fixesBadSeeks_() {
  25442. const seeking = this.tech_.seeking();
  25443. if (!seeking) {
  25444. return false;
  25445. } // TODO: It's possible that these seekable checks should be moved out of this function
  25446. // and into a function that runs on seekablechange. It's also possible that we only need
  25447. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  25448. // seekable range.
  25449. const seekable = this.seekable();
  25450. const currentTime = this.tech_.currentTime();
  25451. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  25452. let seekTo;
  25453. if (isAfterSeekableRange) {
  25454. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  25455. seekTo = seekableEnd;
  25456. }
  25457. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  25458. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  25459. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  25460. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  25461. // happen in live with a 3 segment playlist), then don't use a time delta
  25462. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  25463. }
  25464. if (typeof seekTo !== 'undefined') {
  25465. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  25466. this.tech_.setCurrentTime(seekTo);
  25467. return true;
  25468. }
  25469. const sourceUpdater = this.playlistController_.sourceUpdater_;
  25470. const buffered = this.tech_.buffered();
  25471. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  25472. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  25473. const media = this.media(); // verify that at least two segment durations or one part duration have been
  25474. // appended before checking for a gap.
  25475. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  25476. // appended before checking for a gap.
  25477. const bufferedToCheck = [audioBuffered, videoBuffered];
  25478. for (let i = 0; i < bufferedToCheck.length; i++) {
  25479. // skip null buffered
  25480. if (!bufferedToCheck[i]) {
  25481. continue;
  25482. }
  25483. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  25484. // duration behind we haven't appended enough to call this a bad seek.
  25485. if (timeAhead < minAppendedDuration) {
  25486. return false;
  25487. }
  25488. }
  25489. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  25490. // to seek over the gap
  25491. if (nextRange.length === 0) {
  25492. return false;
  25493. }
  25494. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  25495. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  25496. this.tech_.setCurrentTime(seekTo);
  25497. return true;
  25498. }
  25499. /**
  25500. * Handler for situations when we determine the player is waiting.
  25501. *
  25502. * @private
  25503. */
  25504. waiting_() {
  25505. if (this.techWaiting_()) {
  25506. return;
  25507. } // All tech waiting checks failed. Use last resort correction
  25508. const currentTime = this.tech_.currentTime();
  25509. const buffered = this.tech_.buffered();
  25510. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  25511. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  25512. // currentTime is usually enough to kickstart the player. This checks that the player
  25513. // is currently within a buffered region before attempting a corrective seek.
  25514. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  25515. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  25516. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  25517. // to avoid triggering an `unknownwaiting` event when the network is slow.
  25518. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  25519. this.resetTimeUpdate_();
  25520. this.tech_.setCurrentTime(currentTime);
  25521. 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
  25522. this.tech_.trigger({
  25523. type: 'usage',
  25524. name: 'vhs-unknown-waiting'
  25525. });
  25526. return;
  25527. }
  25528. }
  25529. /**
  25530. * Handler for situations when the tech fires a `waiting` event
  25531. *
  25532. * @return {boolean}
  25533. * True if an action (or none) was needed to correct the waiting. False if no
  25534. * checks passed
  25535. * @private
  25536. */
  25537. techWaiting_() {
  25538. const seekable = this.seekable();
  25539. const currentTime = this.tech_.currentTime();
  25540. if (this.tech_.seeking()) {
  25541. // Tech is seeking or already waiting on another action, no action needed
  25542. return true;
  25543. }
  25544. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  25545. const livePoint = seekable.end(seekable.length - 1);
  25546. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  25547. this.resetTimeUpdate_();
  25548. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  25549. this.tech_.trigger({
  25550. type: 'usage',
  25551. name: 'vhs-live-resync'
  25552. });
  25553. return true;
  25554. }
  25555. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  25556. const buffered = this.tech_.buffered();
  25557. const videoUnderflow = this.videoUnderflow_({
  25558. audioBuffered: sourceUpdater.audioBuffered(),
  25559. videoBuffered: sourceUpdater.videoBuffered(),
  25560. currentTime
  25561. });
  25562. if (videoUnderflow) {
  25563. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  25564. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  25565. // allows the video to catch up to the audio position without losing any audio
  25566. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  25567. this.resetTimeUpdate_();
  25568. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  25569. this.tech_.trigger({
  25570. type: 'usage',
  25571. name: 'vhs-video-underflow'
  25572. });
  25573. return true;
  25574. }
  25575. const nextRange = findNextRange(buffered, currentTime); // check for gap
  25576. if (nextRange.length > 0) {
  25577. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  25578. this.resetTimeUpdate_();
  25579. this.skipTheGap_(currentTime);
  25580. return true;
  25581. } // All checks failed. Returning false to indicate failure to correct waiting
  25582. return false;
  25583. }
  25584. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  25585. if (!seekable.length) {
  25586. // we can't make a solid case if there's no seekable, default to false
  25587. return false;
  25588. }
  25589. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  25590. const isLive = !playlist.endList;
  25591. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  25592. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  25593. }
  25594. if (currentTime > allowedEnd) {
  25595. return true;
  25596. }
  25597. return false;
  25598. }
  25599. beforeSeekableWindow_(seekable, currentTime) {
  25600. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  25601. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  25602. return true;
  25603. }
  25604. return false;
  25605. }
  25606. videoUnderflow_({
  25607. videoBuffered,
  25608. audioBuffered,
  25609. currentTime
  25610. }) {
  25611. // audio only content will not have video underflow :)
  25612. if (!videoBuffered) {
  25613. return;
  25614. }
  25615. let gap; // find a gap in demuxed content.
  25616. if (videoBuffered.length && audioBuffered.length) {
  25617. // in Chrome audio will continue to play for ~3s when we run out of video
  25618. // so we have to check that the video buffer did have some buffer in the
  25619. // past.
  25620. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  25621. const videoRange = findRange(videoBuffered, currentTime);
  25622. const audioRange = findRange(audioBuffered, currentTime);
  25623. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  25624. gap = {
  25625. start: lastVideoRange.end(0),
  25626. end: audioRange.end(0)
  25627. };
  25628. } // find a gap in muxed content.
  25629. } else {
  25630. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  25631. // stuck in a gap due to video underflow.
  25632. if (!nextRange.length) {
  25633. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  25634. }
  25635. }
  25636. if (gap) {
  25637. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  25638. return true;
  25639. }
  25640. return false;
  25641. }
  25642. /**
  25643. * Timer callback. If playback still has not proceeded, then we seek
  25644. * to the start of the next buffered region.
  25645. *
  25646. * @private
  25647. */
  25648. skipTheGap_(scheduledCurrentTime) {
  25649. const buffered = this.tech_.buffered();
  25650. const currentTime = this.tech_.currentTime();
  25651. const nextRange = findNextRange(buffered, currentTime);
  25652. this.resetTimeUpdate_();
  25653. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  25654. return;
  25655. }
  25656. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  25657. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  25658. this.tech_.trigger({
  25659. type: 'usage',
  25660. name: 'vhs-gap-skip'
  25661. });
  25662. }
  25663. gapFromVideoUnderflow_(buffered, currentTime) {
  25664. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  25665. // playing for ~3 seconds after the video gap starts. This is done to account for
  25666. // video buffer underflow/underrun (note that this is not done when there is audio
  25667. // buffer underflow/underrun -- in that case the video will stop as soon as it
  25668. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  25669. // video stalls). The player's time will reflect the playthrough of audio, so the
  25670. // time will appear as if we are in a buffered region, even if we are stuck in a
  25671. // "gap."
  25672. //
  25673. // Example:
  25674. // video buffer: 0 => 10.1, 10.2 => 20
  25675. // audio buffer: 0 => 20
  25676. // overall buffer: 0 => 10.1, 10.2 => 20
  25677. // current time: 13
  25678. //
  25679. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  25680. // however, the audio continued playing until it reached ~3 seconds past the gap
  25681. // (13 seconds), at which point it stops as well. Since current time is past the
  25682. // gap, findNextRange will return no ranges.
  25683. //
  25684. // To check for this issue, we see if there is a gap that starts somewhere within
  25685. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  25686. const gaps = findGaps(buffered);
  25687. for (let i = 0; i < gaps.length; i++) {
  25688. const start = gaps.start(i);
  25689. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  25690. if (currentTime - start < 4 && currentTime - start > 2) {
  25691. return {
  25692. start,
  25693. end
  25694. };
  25695. }
  25696. }
  25697. return null;
  25698. }
  25699. }
  25700. const defaultOptions = {
  25701. errorInterval: 30,
  25702. getSource(next) {
  25703. const tech = this.tech({
  25704. IWillNotUseThisInPlugins: true
  25705. });
  25706. const sourceObj = tech.currentSource_ || this.currentSource();
  25707. return next(sourceObj);
  25708. }
  25709. };
  25710. /**
  25711. * Main entry point for the plugin
  25712. *
  25713. * @param {Player} player a reference to a videojs Player instance
  25714. * @param {Object} [options] an object with plugin options
  25715. * @private
  25716. */
  25717. const initPlugin = function (player, options) {
  25718. let lastCalled = 0;
  25719. let seekTo = 0;
  25720. const localOptions = merge$1(defaultOptions, options);
  25721. player.ready(() => {
  25722. player.trigger({
  25723. type: 'usage',
  25724. name: 'vhs-error-reload-initialized'
  25725. });
  25726. });
  25727. /**
  25728. * Player modifications to perform that must wait until `loadedmetadata`
  25729. * has been triggered
  25730. *
  25731. * @private
  25732. */
  25733. const loadedMetadataHandler = function () {
  25734. if (seekTo) {
  25735. player.currentTime(seekTo);
  25736. }
  25737. };
  25738. /**
  25739. * Set the source on the player element, play, and seek if necessary
  25740. *
  25741. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  25742. * @private
  25743. */
  25744. const setSource = function (sourceObj) {
  25745. if (sourceObj === null || sourceObj === undefined) {
  25746. return;
  25747. }
  25748. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  25749. player.one('loadedmetadata', loadedMetadataHandler);
  25750. player.src(sourceObj);
  25751. player.trigger({
  25752. type: 'usage',
  25753. name: 'vhs-error-reload'
  25754. });
  25755. player.play();
  25756. };
  25757. /**
  25758. * Attempt to get a source from either the built-in getSource function
  25759. * or a custom function provided via the options
  25760. *
  25761. * @private
  25762. */
  25763. const errorHandler = function () {
  25764. // Do not attempt to reload the source if a source-reload occurred before
  25765. // 'errorInterval' time has elapsed since the last source-reload
  25766. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  25767. player.trigger({
  25768. type: 'usage',
  25769. name: 'vhs-error-reload-canceled'
  25770. });
  25771. return;
  25772. }
  25773. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  25774. videojs__default["default"].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  25775. return;
  25776. }
  25777. lastCalled = Date.now();
  25778. return localOptions.getSource.call(player, setSource);
  25779. };
  25780. /**
  25781. * Unbind any event handlers that were bound by the plugin
  25782. *
  25783. * @private
  25784. */
  25785. const cleanupEvents = function () {
  25786. player.off('loadedmetadata', loadedMetadataHandler);
  25787. player.off('error', errorHandler);
  25788. player.off('dispose', cleanupEvents);
  25789. };
  25790. /**
  25791. * Cleanup before re-initializing the plugin
  25792. *
  25793. * @param {Object} [newOptions] an object with plugin options
  25794. * @private
  25795. */
  25796. const reinitPlugin = function (newOptions) {
  25797. cleanupEvents();
  25798. initPlugin(player, newOptions);
  25799. };
  25800. player.on('error', errorHandler);
  25801. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  25802. // initializing the plugin
  25803. player.reloadSourceOnError = reinitPlugin;
  25804. };
  25805. /**
  25806. * Reload the source when an error is detected as long as there
  25807. * wasn't an error previously within the last 30 seconds
  25808. *
  25809. * @param {Object} [options] an object with plugin options
  25810. */
  25811. const reloadSourceOnError = function (options) {
  25812. initPlugin(this, options);
  25813. };
  25814. var version$4 = "3.0.2";
  25815. var version$3 = "6.3.0";
  25816. var version$2 = "1.0.1";
  25817. var version$1 = "6.0.0";
  25818. var version = "4.0.1";
  25819. /**
  25820. * @file videojs-http-streaming.js
  25821. *
  25822. * The main file for the VHS project.
  25823. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  25824. */
  25825. const Vhs = {
  25826. PlaylistLoader,
  25827. Playlist,
  25828. utils,
  25829. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  25830. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  25831. lastBandwidthSelector,
  25832. movingAverageBandwidthSelector,
  25833. comparePlaylistBandwidth,
  25834. comparePlaylistResolution,
  25835. xhr: xhrFactory()
  25836. }; // Define getter/setters for config properties
  25837. Object.keys(Config).forEach(prop => {
  25838. Object.defineProperty(Vhs, prop, {
  25839. get() {
  25840. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  25841. return Config[prop];
  25842. },
  25843. set(value) {
  25844. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  25845. if (typeof value !== 'number' || value < 0) {
  25846. videojs__default["default"].log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  25847. return;
  25848. }
  25849. Config[prop] = value;
  25850. }
  25851. });
  25852. });
  25853. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  25854. /**
  25855. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  25856. *
  25857. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  25858. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  25859. * @function handleVhsMediaChange
  25860. */
  25861. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  25862. const newPlaylist = playlistLoader.media();
  25863. let selectedIndex = -1;
  25864. for (let i = 0; i < qualityLevels.length; i++) {
  25865. if (qualityLevels[i].id === newPlaylist.id) {
  25866. selectedIndex = i;
  25867. break;
  25868. }
  25869. }
  25870. qualityLevels.selectedIndex_ = selectedIndex;
  25871. qualityLevels.trigger({
  25872. selectedIndex,
  25873. type: 'change'
  25874. });
  25875. };
  25876. /**
  25877. * Adds quality levels to list once playlist metadata is available
  25878. *
  25879. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  25880. * @param {Object} vhs Vhs object to listen to for media events.
  25881. * @function handleVhsLoadedMetadata
  25882. */
  25883. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  25884. vhs.representations().forEach(rep => {
  25885. qualityLevels.addQualityLevel(rep);
  25886. });
  25887. handleVhsMediaChange(qualityLevels, vhs.playlists);
  25888. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  25889. // as one do not cause exceptions.
  25890. Vhs.canPlaySource = function () {
  25891. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  25892. };
  25893. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  25894. if (!keySystemOptions) {
  25895. return keySystemOptions;
  25896. }
  25897. let codecs = {};
  25898. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  25899. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  25900. }
  25901. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  25902. codecs.audio = audioPlaylist.attributes.CODECS;
  25903. }
  25904. const videoContentType = getMimeForCodec(codecs.video);
  25905. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  25906. const keySystemContentTypes = {};
  25907. for (const keySystem in keySystemOptions) {
  25908. keySystemContentTypes[keySystem] = {};
  25909. if (audioContentType) {
  25910. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  25911. }
  25912. if (videoContentType) {
  25913. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  25914. } // Default to using the video playlist's PSSH even though they may be different, as
  25915. // videojs-contrib-eme will only accept one in the options.
  25916. //
  25917. // This shouldn't be an issue for most cases as early intialization will handle all
  25918. // unique PSSH values, and if they aren't, then encrypted events should have the
  25919. // specific information needed for the unique license.
  25920. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  25921. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  25922. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  25923. // so we need to prevent overwriting the URL entirely
  25924. if (typeof keySystemOptions[keySystem] === 'string') {
  25925. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  25926. }
  25927. }
  25928. return merge$1(keySystemOptions, keySystemContentTypes);
  25929. };
  25930. /**
  25931. * @typedef {Object} KeySystems
  25932. *
  25933. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  25934. * Note: not all options are listed here.
  25935. *
  25936. * @property {Uint8Array} [pssh]
  25937. * Protection System Specific Header
  25938. */
  25939. /**
  25940. * Goes through all the playlists and collects an array of KeySystems options objects
  25941. * containing each playlist's keySystems and their pssh values, if available.
  25942. *
  25943. * @param {Object[]} playlists
  25944. * The playlists to look through
  25945. * @param {string[]} keySystems
  25946. * The keySystems to collect pssh values for
  25947. *
  25948. * @return {KeySystems[]}
  25949. * An array of KeySystems objects containing available key systems and their
  25950. * pssh values
  25951. */
  25952. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  25953. return playlists.reduce((keySystemsArr, playlist) => {
  25954. if (!playlist.contentProtection) {
  25955. return keySystemsArr;
  25956. }
  25957. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  25958. const keySystemOptions = playlist.contentProtection[keySystem];
  25959. if (keySystemOptions && keySystemOptions.pssh) {
  25960. keySystemsObj[keySystem] = {
  25961. pssh: keySystemOptions.pssh
  25962. };
  25963. }
  25964. return keySystemsObj;
  25965. }, {});
  25966. if (Object.keys(keySystemsOptions).length) {
  25967. keySystemsArr.push(keySystemsOptions);
  25968. }
  25969. return keySystemsArr;
  25970. }, []);
  25971. };
  25972. /**
  25973. * Returns a promise that waits for the
  25974. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  25975. *
  25976. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  25977. * browsers.
  25978. *
  25979. * As per the above ticket, this is particularly important for Chrome, where, if
  25980. * unencrypted content is appended before encrypted content and the key session has not
  25981. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  25982. * during playback.
  25983. *
  25984. * @param {Object} player
  25985. * The player instance
  25986. * @param {Object[]} sourceKeySystems
  25987. * The key systems options from the player source
  25988. * @param {Object} [audioMedia]
  25989. * The active audio media playlist (optional)
  25990. * @param {Object[]} mainPlaylists
  25991. * The playlists found on the main playlist object
  25992. *
  25993. * @return {Object}
  25994. * Promise that resolves when the key session has been created
  25995. */
  25996. const waitForKeySessionCreation = ({
  25997. player,
  25998. sourceKeySystems,
  25999. audioMedia,
  26000. mainPlaylists
  26001. }) => {
  26002. if (!player.eme.initializeMediaKeys) {
  26003. return Promise.resolve();
  26004. } // TODO should all audio PSSH values be initialized for DRM?
  26005. //
  26006. // All unique video rendition pssh values are initialized for DRM, but here only
  26007. // the initial audio playlist license is initialized. In theory, an encrypted
  26008. // event should be fired if the user switches to an alternative audio playlist
  26009. // where a license is required, but this case hasn't yet been tested. In addition, there
  26010. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  26011. // languages).
  26012. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  26013. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  26014. const initializationFinishedPromises = [];
  26015. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  26016. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  26017. // return for IE11 above, and the existence of modern EME APIs in addition to
  26018. // ms-prefixed APIs on Edge should prevent this from being a concern.
  26019. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  26020. keySystemsOptionsArr.forEach(keySystemsOptions => {
  26021. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  26022. player.tech_.one('keysessioncreated', resolve);
  26023. }));
  26024. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  26025. player.eme.initializeMediaKeys({
  26026. keySystems: keySystemsOptions
  26027. }, err => {
  26028. if (err) {
  26029. reject(err);
  26030. return;
  26031. }
  26032. resolve();
  26033. });
  26034. }));
  26035. }); // The reasons Promise.race is chosen over Promise.any:
  26036. //
  26037. // * Promise.any is only available in Safari 14+.
  26038. // * None of these promises are expected to reject. If they do reject, it might be
  26039. // better here for the race to surface the rejection, rather than mask it by using
  26040. // Promise.any.
  26041. return Promise.race([// If a session was previously created, these will all finish resolving without
  26042. // creating a new session, otherwise it will take until the end of all license
  26043. // requests, which is why the key session check is used (to make setup much faster).
  26044. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  26045. Promise.race(keySessionCreatedPromises)]);
  26046. };
  26047. /**
  26048. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  26049. * there are keySystems on the source, sets up source options to prepare the source for
  26050. * eme.
  26051. *
  26052. * @param {Object} player
  26053. * The player instance
  26054. * @param {Object[]} sourceKeySystems
  26055. * The key systems options from the player source
  26056. * @param {Object} media
  26057. * The active media playlist
  26058. * @param {Object} [audioMedia]
  26059. * The active audio media playlist (optional)
  26060. *
  26061. * @return {boolean}
  26062. * Whether or not options were configured and EME is available
  26063. */
  26064. const setupEmeOptions = ({
  26065. player,
  26066. sourceKeySystems,
  26067. media,
  26068. audioMedia
  26069. }) => {
  26070. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  26071. if (!sourceOptions) {
  26072. return false;
  26073. }
  26074. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  26075. // do nothing.
  26076. if (sourceOptions && !player.eme) {
  26077. videojs__default["default"].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  26078. return false;
  26079. }
  26080. return true;
  26081. };
  26082. const getVhsLocalStorage = () => {
  26083. if (!window.localStorage) {
  26084. return null;
  26085. }
  26086. const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  26087. if (!storedObject) {
  26088. return null;
  26089. }
  26090. try {
  26091. return JSON.parse(storedObject);
  26092. } catch (e) {
  26093. // someone may have tampered with the value
  26094. return null;
  26095. }
  26096. };
  26097. const updateVhsLocalStorage = options => {
  26098. if (!window.localStorage) {
  26099. return false;
  26100. }
  26101. let objectToStore = getVhsLocalStorage();
  26102. objectToStore = objectToStore ? merge$1(objectToStore, options) : options;
  26103. try {
  26104. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  26105. } catch (e) {
  26106. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  26107. // storage is set to 0).
  26108. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  26109. // No need to perform any operation.
  26110. return false;
  26111. }
  26112. return objectToStore;
  26113. };
  26114. /**
  26115. * Parses VHS-supported media types from data URIs. See
  26116. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  26117. * for information on data URIs.
  26118. *
  26119. * @param {string} dataUri
  26120. * The data URI
  26121. *
  26122. * @return {string|Object}
  26123. * The parsed object/string, or the original string if no supported media type
  26124. * was found
  26125. */
  26126. const expandDataUri = dataUri => {
  26127. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  26128. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  26129. } // no known case for this data URI, return the string as-is
  26130. return dataUri;
  26131. };
  26132. /**
  26133. * Whether the browser has built-in HLS support.
  26134. */
  26135. Vhs.supportsNativeHls = function () {
  26136. if (!document || !document.createElement) {
  26137. return false;
  26138. }
  26139. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  26140. if (!videojs__default["default"].getTech('Html5').isSupported()) {
  26141. return false;
  26142. } // HLS manifests can go by many mime-types
  26143. const canPlay = [// Apple santioned
  26144. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  26145. 'audio/mpegurl', // Very common
  26146. 'audio/x-mpegurl', // Very common
  26147. 'application/x-mpegurl', // Included for completeness
  26148. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  26149. return canPlay.some(function (canItPlay) {
  26150. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  26151. });
  26152. }();
  26153. Vhs.supportsNativeDash = function () {
  26154. if (!document || !document.createElement || !videojs__default["default"].getTech('Html5').isSupported()) {
  26155. return false;
  26156. }
  26157. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  26158. }();
  26159. Vhs.supportsTypeNatively = type => {
  26160. if (type === 'hls') {
  26161. return Vhs.supportsNativeHls;
  26162. }
  26163. if (type === 'dash') {
  26164. return Vhs.supportsNativeDash;
  26165. }
  26166. return false;
  26167. };
  26168. /**
  26169. * VHS is a source handler, not a tech. Make sure attempts to use it
  26170. * as one do not cause exceptions.
  26171. */
  26172. Vhs.isSupported = function () {
  26173. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  26174. };
  26175. const Component = videojs__default["default"].getComponent('Component');
  26176. /**
  26177. * The Vhs Handler object, where we orchestrate all of the parts
  26178. * of VHS to interact with video.js
  26179. *
  26180. * @class VhsHandler
  26181. * @extends videojs.Component
  26182. * @param {Object} source the soruce object
  26183. * @param {Tech} tech the parent tech object
  26184. * @param {Object} options optional and required options
  26185. */
  26186. class VhsHandler extends Component {
  26187. constructor(source, tech, options) {
  26188. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  26189. // use that over the VHS level `bandwidth` option
  26190. if (typeof options.initialBandwidth === 'number') {
  26191. this.options_.bandwidth = options.initialBandwidth;
  26192. }
  26193. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  26194. // so, get it from Video.js via the `playerId`
  26195. if (tech.options_ && tech.options_.playerId) {
  26196. const _player = videojs__default["default"].getPlayer(tech.options_.playerId);
  26197. this.player_ = _player;
  26198. }
  26199. this.tech_ = tech;
  26200. this.source_ = source;
  26201. this.stats = {};
  26202. this.ignoreNextSeekingEvent_ = false;
  26203. this.setOptions_();
  26204. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  26205. tech.overrideNativeAudioTracks(true);
  26206. tech.overrideNativeVideoTracks(true);
  26207. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  26208. // overriding native VHS only works if audio tracks have been emulated
  26209. // error early if we're misconfigured
  26210. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  26211. } // listen for fullscreenchange events for this player so that we
  26212. // can adjust our quality selection quickly
  26213. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  26214. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  26215. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  26216. this.playlistController_.fastQualityChange_();
  26217. } else {
  26218. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  26219. // than full screen, see if there should be a rendition switch down to preserve
  26220. // bandwidth.
  26221. this.playlistController_.checkABR_();
  26222. }
  26223. });
  26224. this.on(this.tech_, 'seeking', function () {
  26225. if (this.ignoreNextSeekingEvent_) {
  26226. this.ignoreNextSeekingEvent_ = false;
  26227. return;
  26228. }
  26229. this.setCurrentTime(this.tech_.currentTime());
  26230. });
  26231. this.on(this.tech_, 'error', function () {
  26232. // verify that the error was real and we are loaded
  26233. // enough to have pc loaded.
  26234. if (this.tech_.error() && this.playlistController_) {
  26235. this.playlistController_.pauseLoading();
  26236. }
  26237. });
  26238. this.on(this.tech_, 'play', this.play);
  26239. }
  26240. setOptions_() {
  26241. // defaults
  26242. this.options_.withCredentials = this.options_.withCredentials || false;
  26243. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  26244. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  26245. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  26246. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  26247. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  26248. this.options_.customTagParsers = this.options_.customTagParsers || [];
  26249. this.options_.customTagMappers = this.options_.customTagMappers || [];
  26250. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  26251. this.options_.llhls = this.options_.llhls === false ? false : true;
  26252. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  26253. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  26254. this.options_.playlistExclusionDuration = 5 * 60;
  26255. }
  26256. if (typeof this.options_.bandwidth !== 'number') {
  26257. if (this.options_.useBandwidthFromLocalStorage) {
  26258. const storedObject = getVhsLocalStorage();
  26259. if (storedObject && storedObject.bandwidth) {
  26260. this.options_.bandwidth = storedObject.bandwidth;
  26261. this.tech_.trigger({
  26262. type: 'usage',
  26263. name: 'vhs-bandwidth-from-local-storage'
  26264. });
  26265. }
  26266. if (storedObject && storedObject.throughput) {
  26267. this.options_.throughput = storedObject.throughput;
  26268. this.tech_.trigger({
  26269. type: 'usage',
  26270. name: 'vhs-throughput-from-local-storage'
  26271. });
  26272. }
  26273. }
  26274. } // if bandwidth was not set by options or pulled from local storage, start playlist
  26275. // selection at a reasonable bandwidth
  26276. if (typeof this.options_.bandwidth !== 'number') {
  26277. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  26278. } // If the bandwidth number is unchanged from the initial setting
  26279. // then this takes precedence over the enableLowInitialPlaylist option
  26280. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  26281. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  26282. if (typeof this.source_[option] !== 'undefined') {
  26283. this.options_[option] = this.source_[option];
  26284. }
  26285. });
  26286. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  26287. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  26288. }
  26289. /**
  26290. * called when player.src gets called, handle a new source
  26291. *
  26292. * @param {Object} src the source object to handle
  26293. */
  26294. src(src, type) {
  26295. // do nothing if the src is falsey
  26296. if (!src) {
  26297. return;
  26298. }
  26299. this.setOptions_(); // add main playlist controller options
  26300. this.options_.src = expandDataUri(this.source_.src);
  26301. this.options_.tech = this.tech_;
  26302. this.options_.externVhs = Vhs;
  26303. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  26304. this.options_.seekTo = time => {
  26305. this.tech_.setCurrentTime(time);
  26306. };
  26307. this.playlistController_ = new PlaylistController(this.options_);
  26308. const playbackWatcherOptions = merge$1({
  26309. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  26310. }, this.options_, {
  26311. seekable: () => this.seekable(),
  26312. media: () => this.playlistController_.media(),
  26313. playlistController: this.playlistController_
  26314. });
  26315. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  26316. this.playlistController_.on('error', () => {
  26317. const player = videojs__default["default"].players[this.tech_.options_.playerId];
  26318. let error = this.playlistController_.error;
  26319. if (typeof error === 'object' && !error.code) {
  26320. error.code = 3;
  26321. } else if (typeof error === 'string') {
  26322. error = {
  26323. message: error,
  26324. code: 3
  26325. };
  26326. }
  26327. player.error(error);
  26328. });
  26329. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  26330. // compatibility with < v2
  26331. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  26332. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  26333. this.playlists = this.playlistController_.mainPlaylistLoader_;
  26334. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  26335. // controller. Using a custom property for backwards compatibility
  26336. // with < v2
  26337. Object.defineProperties(this, {
  26338. selectPlaylist: {
  26339. get() {
  26340. return this.playlistController_.selectPlaylist;
  26341. },
  26342. set(selectPlaylist) {
  26343. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  26344. }
  26345. },
  26346. throughput: {
  26347. get() {
  26348. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  26349. },
  26350. set(throughput) {
  26351. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  26352. // for the cumulative average
  26353. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  26354. }
  26355. },
  26356. bandwidth: {
  26357. get() {
  26358. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  26359. const networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  26360. const tenMbpsAsBitsPerSecond = 10e6;
  26361. if (this.options_.useNetworkInformationApi && networkInformation) {
  26362. // downlink returns Mbps
  26363. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  26364. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  26365. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  26366. // high quality streams are not filtered out.
  26367. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  26368. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  26369. } else {
  26370. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  26371. }
  26372. }
  26373. return playerBandwidthEst;
  26374. },
  26375. set(bandwidth) {
  26376. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  26377. // `count` is set to zero that current value of `rate` isn't included
  26378. // in the cumulative average
  26379. this.playlistController_.mainSegmentLoader_.throughput = {
  26380. rate: 0,
  26381. count: 0
  26382. };
  26383. }
  26384. },
  26385. /**
  26386. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  26387. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  26388. * the entire process after that - decryption, transmuxing, and appending - provided
  26389. * by `throughput`.
  26390. *
  26391. * Since the two process are serial, the overall system bandwidth is given by:
  26392. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  26393. */
  26394. systemBandwidth: {
  26395. get() {
  26396. const invBandwidth = 1 / (this.bandwidth || 1);
  26397. let invThroughput;
  26398. if (this.throughput > 0) {
  26399. invThroughput = 1 / this.throughput;
  26400. } else {
  26401. invThroughput = 0;
  26402. }
  26403. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  26404. return systemBitrate;
  26405. },
  26406. set() {
  26407. videojs__default["default"].log.error('The "systemBandwidth" property is read-only');
  26408. }
  26409. }
  26410. });
  26411. if (this.options_.bandwidth) {
  26412. this.bandwidth = this.options_.bandwidth;
  26413. }
  26414. if (this.options_.throughput) {
  26415. this.throughput = this.options_.throughput;
  26416. }
  26417. Object.defineProperties(this.stats, {
  26418. bandwidth: {
  26419. get: () => this.bandwidth || 0,
  26420. enumerable: true
  26421. },
  26422. mediaRequests: {
  26423. get: () => this.playlistController_.mediaRequests_() || 0,
  26424. enumerable: true
  26425. },
  26426. mediaRequestsAborted: {
  26427. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  26428. enumerable: true
  26429. },
  26430. mediaRequestsTimedout: {
  26431. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  26432. enumerable: true
  26433. },
  26434. mediaRequestsErrored: {
  26435. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  26436. enumerable: true
  26437. },
  26438. mediaTransferDuration: {
  26439. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  26440. enumerable: true
  26441. },
  26442. mediaBytesTransferred: {
  26443. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  26444. enumerable: true
  26445. },
  26446. mediaSecondsLoaded: {
  26447. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  26448. enumerable: true
  26449. },
  26450. mediaAppends: {
  26451. get: () => this.playlistController_.mediaAppends_() || 0,
  26452. enumerable: true
  26453. },
  26454. mainAppendsToLoadedData: {
  26455. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  26456. enumerable: true
  26457. },
  26458. audioAppendsToLoadedData: {
  26459. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  26460. enumerable: true
  26461. },
  26462. appendsToLoadedData: {
  26463. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  26464. enumerable: true
  26465. },
  26466. timeToLoadedData: {
  26467. get: () => this.playlistController_.timeToLoadedData_() || 0,
  26468. enumerable: true
  26469. },
  26470. buffered: {
  26471. get: () => timeRangesToArray(this.tech_.buffered()),
  26472. enumerable: true
  26473. },
  26474. currentTime: {
  26475. get: () => this.tech_.currentTime(),
  26476. enumerable: true
  26477. },
  26478. currentSource: {
  26479. get: () => this.tech_.currentSource_,
  26480. enumerable: true
  26481. },
  26482. currentTech: {
  26483. get: () => this.tech_.name_,
  26484. enumerable: true
  26485. },
  26486. duration: {
  26487. get: () => this.tech_.duration(),
  26488. enumerable: true
  26489. },
  26490. main: {
  26491. get: () => this.playlists.main,
  26492. enumerable: true
  26493. },
  26494. playerDimensions: {
  26495. get: () => this.tech_.currentDimensions(),
  26496. enumerable: true
  26497. },
  26498. seekable: {
  26499. get: () => timeRangesToArray(this.tech_.seekable()),
  26500. enumerable: true
  26501. },
  26502. timestamp: {
  26503. get: () => Date.now(),
  26504. enumerable: true
  26505. },
  26506. videoPlaybackQuality: {
  26507. get: () => this.tech_.getVideoPlaybackQuality(),
  26508. enumerable: true
  26509. }
  26510. });
  26511. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  26512. this.tech_.on('bandwidthupdate', () => {
  26513. if (this.options_.useBandwidthFromLocalStorage) {
  26514. updateVhsLocalStorage({
  26515. bandwidth: this.bandwidth,
  26516. throughput: Math.round(this.throughput)
  26517. });
  26518. }
  26519. });
  26520. this.playlistController_.on('selectedinitialmedia', () => {
  26521. // Add the manual rendition mix-in to VhsHandler
  26522. renditionSelectionMixin(this);
  26523. });
  26524. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  26525. this.setupEme_();
  26526. }); // the bandwidth of the primary segment loader is our best
  26527. // estimate of overall bandwidth
  26528. this.on(this.playlistController_, 'progress', function () {
  26529. this.tech_.trigger('progress');
  26530. }); // In the live case, we need to ignore the very first `seeking` event since
  26531. // that will be the result of the seek-to-live behavior
  26532. this.on(this.playlistController_, 'firstplay', function () {
  26533. this.ignoreNextSeekingEvent_ = true;
  26534. });
  26535. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  26536. // this can occur if someone sets the src in player.ready(), for instance
  26537. if (!this.tech_.el()) {
  26538. return;
  26539. }
  26540. this.mediaSourceUrl_ = window.URL.createObjectURL(this.playlistController_.mediaSource);
  26541. this.tech_.src(this.mediaSourceUrl_);
  26542. }
  26543. createKeySessions_() {
  26544. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  26545. this.logger_('waiting for EME key session creation');
  26546. waitForKeySessionCreation({
  26547. player: this.player_,
  26548. sourceKeySystems: this.source_.keySystems,
  26549. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  26550. mainPlaylists: this.playlists.main.playlists
  26551. }).then(() => {
  26552. this.logger_('created EME key session');
  26553. this.playlistController_.sourceUpdater_.initializedEme();
  26554. }).catch(err => {
  26555. this.logger_('error while creating EME key session', err);
  26556. this.player_.error({
  26557. message: 'Failed to initialize media keys for EME',
  26558. code: 3
  26559. });
  26560. });
  26561. }
  26562. handleWaitingForKey_() {
  26563. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  26564. // the key is in the manifest. While this should've happened on initial source load, it
  26565. // may happen again in live streams where the keys change, and the manifest info
  26566. // reflects the update.
  26567. //
  26568. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  26569. // already requested keys for, we don't have to worry about this generating extraneous
  26570. // requests.
  26571. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  26572. this.createKeySessions_();
  26573. }
  26574. /**
  26575. * If necessary and EME is available, sets up EME options and waits for key session
  26576. * creation.
  26577. *
  26578. * This function also updates the source updater so taht it can be used, as for some
  26579. * browsers, EME must be configured before content is appended (if appending unencrypted
  26580. * content before encrypted content).
  26581. */
  26582. setupEme_() {
  26583. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  26584. const didSetupEmeOptions = setupEmeOptions({
  26585. player: this.player_,
  26586. sourceKeySystems: this.source_.keySystems,
  26587. media: this.playlists.media(),
  26588. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  26589. });
  26590. this.player_.tech_.on('keystatuschange', e => {
  26591. if (e.status !== 'output-restricted') {
  26592. return;
  26593. }
  26594. const mainPlaylist = this.playlistController_.main();
  26595. if (!mainPlaylist || !mainPlaylist.playlists) {
  26596. return;
  26597. }
  26598. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  26599. mainPlaylist.playlists.forEach(playlist => {
  26600. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  26601. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  26602. playlist.excludeUntil = Infinity;
  26603. excludedHDPlaylists.push(playlist);
  26604. }
  26605. }
  26606. });
  26607. if (excludedHDPlaylists.length) {
  26608. videojs__default["default"].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
  26609. this.playlistController_.fastQualityChange_();
  26610. }
  26611. });
  26612. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  26613. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  26614. // promises.
  26615. if (videojs__default["default"].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  26616. // If EME options were not set up, we've done all we could to initialize EME.
  26617. this.playlistController_.sourceUpdater_.initializedEme();
  26618. return;
  26619. }
  26620. this.createKeySessions_();
  26621. }
  26622. /**
  26623. * Initializes the quality levels and sets listeners to update them.
  26624. *
  26625. * @method setupQualityLevels_
  26626. * @private
  26627. */
  26628. setupQualityLevels_() {
  26629. const player = videojs__default["default"].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  26630. // or qualityLevels_ listeners have already been setup, do nothing.
  26631. if (!player || !player.qualityLevels || this.qualityLevels_) {
  26632. return;
  26633. }
  26634. this.qualityLevels_ = player.qualityLevels();
  26635. this.playlistController_.on('selectedinitialmedia', () => {
  26636. handleVhsLoadedMetadata(this.qualityLevels_, this);
  26637. });
  26638. this.playlists.on('mediachange', () => {
  26639. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  26640. });
  26641. }
  26642. /**
  26643. * return the version
  26644. */
  26645. static version() {
  26646. return {
  26647. '@videojs/http-streaming': version$4,
  26648. 'mux.js': version$3,
  26649. 'mpd-parser': version$2,
  26650. 'm3u8-parser': version$1,
  26651. 'aes-decrypter': version
  26652. };
  26653. }
  26654. /**
  26655. * return the version
  26656. */
  26657. version() {
  26658. return this.constructor.version();
  26659. }
  26660. canChangeType() {
  26661. return SourceUpdater.canChangeType();
  26662. }
  26663. /**
  26664. * Begin playing the video.
  26665. */
  26666. play() {
  26667. this.playlistController_.play();
  26668. }
  26669. /**
  26670. * a wrapper around the function in PlaylistController
  26671. */
  26672. setCurrentTime(currentTime) {
  26673. this.playlistController_.setCurrentTime(currentTime);
  26674. }
  26675. /**
  26676. * a wrapper around the function in PlaylistController
  26677. */
  26678. duration() {
  26679. return this.playlistController_.duration();
  26680. }
  26681. /**
  26682. * a wrapper around the function in PlaylistController
  26683. */
  26684. seekable() {
  26685. return this.playlistController_.seekable();
  26686. }
  26687. /**
  26688. * Abort all outstanding work and cleanup.
  26689. */
  26690. dispose() {
  26691. if (this.playbackWatcher_) {
  26692. this.playbackWatcher_.dispose();
  26693. }
  26694. if (this.playlistController_) {
  26695. this.playlistController_.dispose();
  26696. }
  26697. if (this.qualityLevels_) {
  26698. this.qualityLevels_.dispose();
  26699. }
  26700. if (this.tech_ && this.tech_.vhs) {
  26701. delete this.tech_.vhs;
  26702. }
  26703. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  26704. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  26705. this.mediaSourceUrl_ = null;
  26706. }
  26707. if (this.tech_) {
  26708. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  26709. }
  26710. super.dispose();
  26711. }
  26712. convertToProgramTime(time, callback) {
  26713. return getProgramTime({
  26714. playlist: this.playlistController_.media(),
  26715. time,
  26716. callback
  26717. });
  26718. } // the player must be playing before calling this
  26719. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  26720. return seekToProgramTime({
  26721. programTime,
  26722. playlist: this.playlistController_.media(),
  26723. retryCount,
  26724. pauseAfterSeek,
  26725. seekTo: this.options_.seekTo,
  26726. tech: this.options_.tech,
  26727. callback
  26728. });
  26729. }
  26730. }
  26731. /**
  26732. * The Source Handler object, which informs video.js what additional
  26733. * MIME types are supported and sets up playback. It is registered
  26734. * automatically to the appropriate tech based on the capabilities of
  26735. * the browser it is running in. It is not necessary to use or modify
  26736. * this object in normal usage.
  26737. */
  26738. const VhsSourceHandler = {
  26739. name: 'videojs-http-streaming',
  26740. VERSION: version$4,
  26741. canHandleSource(srcObj, options = {}) {
  26742. const localOptions = merge$1(videojs__default["default"].options, options);
  26743. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  26744. },
  26745. handleSource(source, tech, options = {}) {
  26746. const localOptions = merge$1(videojs__default["default"].options, options);
  26747. tech.vhs = new VhsHandler(source, tech, localOptions);
  26748. tech.vhs.xhr = xhrFactory();
  26749. tech.vhs.src(source.src, source.type);
  26750. return tech.vhs;
  26751. },
  26752. canPlayType(type, options) {
  26753. const simpleType = simpleTypeFromSourceType(type);
  26754. if (!simpleType) {
  26755. return '';
  26756. }
  26757. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  26758. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  26759. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  26760. return canUseMsePlayback ? 'maybe' : '';
  26761. },
  26762. getOverrideNative(options = {}) {
  26763. const {
  26764. vhs = {}
  26765. } = options;
  26766. const defaultOverrideNative = !(videojs__default["default"].browser.IS_ANY_SAFARI || videojs__default["default"].browser.IS_IOS);
  26767. const {
  26768. overrideNative = defaultOverrideNative
  26769. } = vhs;
  26770. return overrideNative;
  26771. }
  26772. };
  26773. /**
  26774. * Check to see if the native MediaSource object exists and supports
  26775. * an MP4 container with both H.264 video and AAC-LC audio.
  26776. *
  26777. * @return {boolean} if native media sources are supported
  26778. */
  26779. const supportsNativeMediaSources = () => {
  26780. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  26781. }; // register source handlers with the appropriate techs
  26782. if (supportsNativeMediaSources()) {
  26783. videojs__default["default"].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  26784. }
  26785. videojs__default["default"].VhsHandler = VhsHandler;
  26786. videojs__default["default"].VhsSourceHandler = VhsSourceHandler;
  26787. videojs__default["default"].Vhs = Vhs;
  26788. if (!videojs__default["default"].use) {
  26789. videojs__default["default"].registerComponent('Vhs', Vhs);
  26790. }
  26791. videojs__default["default"].options.vhs = videojs__default["default"].options.vhs || {};
  26792. if (!videojs__default["default"].getPlugin || !videojs__default["default"].getPlugin('reloadSourceOnError')) {
  26793. videojs__default["default"].registerPlugin('reloadSourceOnError', reloadSourceOnError);
  26794. }
  26795. exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
  26796. exports.Vhs = Vhs;
  26797. exports.VhsHandler = VhsHandler;
  26798. exports.VhsSourceHandler = VhsSourceHandler;
  26799. exports.emeKeySystems = emeKeySystems;
  26800. exports.expandDataUri = expandDataUri;
  26801. exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
  26802. exports.setupEmeOptions = setupEmeOptions;
  26803. exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
  26804. exports.waitForKeySessionCreation = waitForKeySessionCreation;
  26805. Object.defineProperty(exports, '__esModule', { value: true });
  26806. }));