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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532
  1. /*! @name @videojs/http-streaming @version 3.10.0 @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. function _extends() {
  10. _extends = Object.assign || function (target) {
  11. for (var i = 1; i < arguments.length; i++) {
  12. var source = arguments[i];
  13. for (var key in source) {
  14. if (Object.prototype.hasOwnProperty.call(source, key)) {
  15. target[key] = source[key];
  16. }
  17. }
  18. }
  19. return target;
  20. };
  21. return _extends.apply(this, arguments);
  22. }
  23. var urlToolkit = {exports: {}};
  24. (function (module, exports) {
  25. // see https://tools.ietf.org/html/rfc1808
  26. (function (root) {
  27. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
  28. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
  29. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  30. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  31. var URLToolkit = {
  32. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  33. // E.g
  34. // With opts.alwaysNormalize = false (default, spec compliant)
  35. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  36. // With opts.alwaysNormalize = true (not spec compliant)
  37. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  38. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  39. opts = opts || {}; // remove any remaining space and CRLF
  40. baseURL = baseURL.trim();
  41. relativeURL = relativeURL.trim();
  42. if (!relativeURL) {
  43. // 2a) If the embedded URL is entirely empty, it inherits the
  44. // entire base URL (i.e., is set equal to the base URL)
  45. // and we are done.
  46. if (!opts.alwaysNormalize) {
  47. return baseURL;
  48. }
  49. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  50. if (!basePartsForNormalise) {
  51. throw new Error('Error trying to parse base URL.');
  52. }
  53. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  54. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  55. }
  56. var relativeParts = URLToolkit.parseURL(relativeURL);
  57. if (!relativeParts) {
  58. throw new Error('Error trying to parse relative URL.');
  59. }
  60. if (relativeParts.scheme) {
  61. // 2b) If the embedded URL starts with a scheme name, it is
  62. // interpreted as an absolute URL and we are done.
  63. if (!opts.alwaysNormalize) {
  64. return relativeURL;
  65. }
  66. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  67. return URLToolkit.buildURLFromParts(relativeParts);
  68. }
  69. var baseParts = URLToolkit.parseURL(baseURL);
  70. if (!baseParts) {
  71. throw new Error('Error trying to parse base URL.');
  72. }
  73. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  74. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  75. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  76. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  77. baseParts.netLoc = pathParts[1];
  78. baseParts.path = pathParts[2];
  79. }
  80. if (baseParts.netLoc && !baseParts.path) {
  81. baseParts.path = '/';
  82. }
  83. var builtParts = {
  84. // 2c) Otherwise, the embedded URL inherits the scheme of
  85. // the base URL.
  86. scheme: baseParts.scheme,
  87. netLoc: relativeParts.netLoc,
  88. path: null,
  89. params: relativeParts.params,
  90. query: relativeParts.query,
  91. fragment: relativeParts.fragment
  92. };
  93. if (!relativeParts.netLoc) {
  94. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  95. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  96. // (if any) of the base URL.
  97. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
  98. // path is not relative and we skip to Step 7.
  99. if (relativeParts.path[0] !== '/') {
  100. if (!relativeParts.path) {
  101. // 5) If the embedded URL path is empty (and not preceded by a
  102. // slash), then the embedded URL inherits the base URL path
  103. builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to
  104. // step 7; otherwise, it inherits the <params> of the base
  105. // URL (if any) and
  106. if (!relativeParts.params) {
  107. builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to
  108. // step 7; otherwise, it inherits the <query> of the base
  109. // URL (if any) and we skip to step 7.
  110. if (!relativeParts.query) {
  111. builtParts.query = baseParts.query;
  112. }
  113. }
  114. } else {
  115. // 6) The last segment of the base URL's path (anything
  116. // following the rightmost slash "/", or the entire path if no
  117. // slash is present) is removed and the embedded URL's path is
  118. // appended in its place.
  119. var baseURLPath = baseParts.path;
  120. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  121. builtParts.path = URLToolkit.normalizePath(newPath);
  122. }
  123. }
  124. }
  125. if (builtParts.path === null) {
  126. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  127. }
  128. return URLToolkit.buildURLFromParts(builtParts);
  129. },
  130. parseURL: function (url) {
  131. var parts = URL_REGEX.exec(url);
  132. if (!parts) {
  133. return null;
  134. }
  135. return {
  136. scheme: parts[1] || '',
  137. netLoc: parts[2] || '',
  138. path: parts[3] || '',
  139. params: parts[4] || '',
  140. query: parts[5] || '',
  141. fragment: parts[6] || ''
  142. };
  143. },
  144. normalizePath: function (path) {
  145. // The following operations are
  146. // then applied, in order, to the new path:
  147. // 6a) All occurrences of "./", where "." is a complete path
  148. // segment, are removed.
  149. // 6b) If the path ends with "." as a complete path segment,
  150. // that "." is removed.
  151. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a
  152. // complete path segment not equal to "..", are removed.
  153. // Removal of these path segments is performed iteratively,
  154. // removing the leftmost matching pattern on each iteration,
  155. // until no matching pattern remains.
  156. // 6d) If the path ends with "<segment>/..", where <segment> is a
  157. // complete path segment not equal to "..", that
  158. // "<segment>/.." is removed.
  159. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  160. return path.split('').reverse().join('');
  161. },
  162. buildURLFromParts: function (parts) {
  163. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  164. }
  165. };
  166. module.exports = URLToolkit;
  167. })();
  168. })(urlToolkit);
  169. var URLToolkit = urlToolkit.exports;
  170. var DEFAULT_LOCATION = 'http://example.com';
  171. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  172. // return early if we don't need to resolve
  173. if (/^[a-z]+:/i.test(relativeUrl)) {
  174. return relativeUrl;
  175. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  176. if (/^data:/.test(baseUrl)) {
  177. baseUrl = window.location && window.location.href || '';
  178. } // IE11 supports URL but not the URL constructor
  179. // feature detect the behavior we want
  180. var nativeURL = typeof window.URL === 'function';
  181. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  182. // and if baseUrl isn't an absolute url
  183. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  184. if (nativeURL) {
  185. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  186. } else if (!/\/\//i.test(baseUrl)) {
  187. baseUrl = URLToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  188. }
  189. if (nativeURL) {
  190. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  191. // and if we're location-less, remove the location
  192. // otherwise, return the url unmodified
  193. if (removeLocation) {
  194. return newUrl.href.slice(DEFAULT_LOCATION.length);
  195. } else if (protocolLess) {
  196. return newUrl.href.slice(newUrl.protocol.length);
  197. }
  198. return newUrl.href;
  199. }
  200. return URLToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  201. };
  202. /**
  203. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  204. */
  205. const resolveUrl = resolveUrl$1;
  206. /**
  207. * If the xhr request was redirected, return the responseURL, otherwise,
  208. * return the original url.
  209. *
  210. * @api private
  211. *
  212. * @param {string} url - an url being requested
  213. * @param {XMLHttpRequest} req - xhr request result
  214. *
  215. * @return {string}
  216. */
  217. const resolveManifestRedirect = (url, req) => {
  218. // To understand how the responseURL below is set and generated:
  219. // - https://fetch.spec.whatwg.org/#concept-response-url
  220. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  221. if (req && req.responseURL && url !== req.responseURL) {
  222. return req.responseURL;
  223. }
  224. return url;
  225. };
  226. const logger = source => {
  227. if (videojs__default["default"].log.debug) {
  228. return videojs__default["default"].log.debug.bind(videojs__default["default"], 'VHS:', `${source} >`);
  229. }
  230. return function () {};
  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 7.1.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. }
  883. match = /^#EXT-X-DATERANGE:(.*)$/.exec(newLine);
  884. if (match && match[1]) {
  885. event = {
  886. type: 'tag',
  887. tagType: 'daterange'
  888. };
  889. event.attributes = parseAttributes$1(match[1]);
  890. ['ID', 'CLASS'].forEach(function (key) {
  891. if (event.attributes.hasOwnProperty(key)) {
  892. event.attributes[key] = String(event.attributes[key]);
  893. }
  894. });
  895. ['START-DATE', 'END-DATE'].forEach(function (key) {
  896. if (event.attributes.hasOwnProperty(key)) {
  897. event.attributes[key] = new Date(event.attributes[key]);
  898. }
  899. });
  900. ['DURATION', 'PLANNED-DURATION'].forEach(function (key) {
  901. if (event.attributes.hasOwnProperty(key)) {
  902. event.attributes[key] = parseFloat(event.attributes[key]);
  903. }
  904. });
  905. ['END-ON-NEXT'].forEach(function (key) {
  906. if (event.attributes.hasOwnProperty(key)) {
  907. event.attributes[key] = /YES/i.test(event.attributes[key]);
  908. }
  909. });
  910. ['SCTE35-CMD', ' SCTE35-OUT', 'SCTE35-IN'].forEach(function (key) {
  911. if (event.attributes.hasOwnProperty(key)) {
  912. event.attributes[key] = event.attributes[key].toString(16);
  913. }
  914. });
  915. const clientAttributePattern = /^X-([A-Z]+-)+[A-Z]+$/;
  916. for (const key in event.attributes) {
  917. if (!clientAttributePattern.test(key)) {
  918. continue;
  919. }
  920. const isHexaDecimal = /[0-9A-Fa-f]{6}/g.test(event.attributes[key]);
  921. const isDecimalFloating = /^\d+(\.\d+)?$/.test(event.attributes[key]);
  922. event.attributes[key] = isHexaDecimal ? event.attributes[key].toString(16) : isDecimalFloating ? parseFloat(event.attributes[key]) : String(event.attributes[key]);
  923. }
  924. this.trigger('data', event);
  925. return;
  926. }
  927. match = /^#EXT-X-INDEPENDENT-SEGMENTS/.exec(newLine);
  928. if (match) {
  929. this.trigger('data', {
  930. type: 'tag',
  931. tagType: 'independent-segments'
  932. });
  933. return;
  934. }
  935. match = /^#EXT-X-CONTENT-STEERING:(.*)$/.exec(newLine);
  936. if (match) {
  937. event = {
  938. type: 'tag',
  939. tagType: 'content-steering'
  940. };
  941. event.attributes = parseAttributes$1(match[1]);
  942. this.trigger('data', event);
  943. return;
  944. } // unknown tag type
  945. this.trigger('data', {
  946. type: 'tag',
  947. data: newLine.slice(4)
  948. });
  949. });
  950. }
  951. /**
  952. * Add a parser for custom headers
  953. *
  954. * @param {Object} options a map of options for the added parser
  955. * @param {RegExp} options.expression a regular expression to match the custom header
  956. * @param {string} options.customType the custom type to register to the output
  957. * @param {Function} [options.dataParser] function to parse the line into an object
  958. * @param {boolean} [options.segment] should tag data be attached to the segment object
  959. */
  960. addParser({
  961. expression,
  962. customType,
  963. dataParser,
  964. segment
  965. }) {
  966. if (typeof dataParser !== 'function') {
  967. dataParser = line => line;
  968. }
  969. this.customParsers.push(line => {
  970. const match = expression.exec(line);
  971. if (match) {
  972. this.trigger('data', {
  973. type: 'custom',
  974. data: dataParser(line),
  975. customType,
  976. segment
  977. });
  978. return true;
  979. }
  980. });
  981. }
  982. /**
  983. * Add a custom header mapper
  984. *
  985. * @param {Object} options
  986. * @param {RegExp} options.expression a regular expression to match the custom header
  987. * @param {Function} options.map function to translate tag into a different tag
  988. */
  989. addTagMapper({
  990. expression,
  991. map
  992. }) {
  993. const mapFn = line => {
  994. if (expression.test(line)) {
  995. return map(line);
  996. }
  997. return line;
  998. };
  999. this.tagMappers.push(mapFn);
  1000. }
  1001. }
  1002. const camelCase = str => str.toLowerCase().replace(/-(\w)/g, a => a[1].toUpperCase());
  1003. const camelCaseKeys = function (attributes) {
  1004. const result = {};
  1005. Object.keys(attributes).forEach(function (key) {
  1006. result[camelCase(key)] = attributes[key];
  1007. });
  1008. return result;
  1009. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  1010. // we need this helper because defaults are based upon targetDuration and
  1011. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  1012. // target durations are set.
  1013. const setHoldBack = function (manifest) {
  1014. const {
  1015. serverControl,
  1016. targetDuration,
  1017. partTargetDuration
  1018. } = manifest;
  1019. if (!serverControl) {
  1020. return;
  1021. }
  1022. const tag = '#EXT-X-SERVER-CONTROL';
  1023. const hb = 'holdBack';
  1024. const phb = 'partHoldBack';
  1025. const minTargetDuration = targetDuration && targetDuration * 3;
  1026. const minPartDuration = partTargetDuration && partTargetDuration * 2;
  1027. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  1028. serverControl[hb] = minTargetDuration;
  1029. this.trigger('info', {
  1030. message: `${tag} defaulting HOLD-BACK to targetDuration * 3 (${minTargetDuration}).`
  1031. });
  1032. }
  1033. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  1034. this.trigger('warn', {
  1035. message: `${tag} clamping HOLD-BACK (${serverControl[hb]}) to targetDuration * 3 (${minTargetDuration})`
  1036. });
  1037. serverControl[hb] = minTargetDuration;
  1038. } // default no part hold back to part target duration * 3
  1039. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  1040. serverControl[phb] = partTargetDuration * 3;
  1041. this.trigger('info', {
  1042. message: `${tag} defaulting PART-HOLD-BACK to partTargetDuration * 3 (${serverControl[phb]}).`
  1043. });
  1044. } // if part hold back is too small default it to part target duration * 2
  1045. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  1046. this.trigger('warn', {
  1047. message: `${tag} clamping PART-HOLD-BACK (${serverControl[phb]}) to partTargetDuration * 2 (${minPartDuration}).`
  1048. });
  1049. serverControl[phb] = minPartDuration;
  1050. }
  1051. };
  1052. /**
  1053. * A parser for M3U8 files. The current interpretation of the input is
  1054. * exposed as a property `manifest` on parser objects. It's just two lines to
  1055. * create and parse a manifest once you have the contents available as a string:
  1056. *
  1057. * ```js
  1058. * var parser = new m3u8.Parser();
  1059. * parser.push(xhr.responseText);
  1060. * ```
  1061. *
  1062. * New input can later be applied to update the manifest object by calling
  1063. * `push` again.
  1064. *
  1065. * The parser attempts to create a usable manifest object even if the
  1066. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  1067. * events during the parse if it encounters input that seems invalid or
  1068. * requires some property of the manifest object to be defaulted.
  1069. *
  1070. * @class Parser
  1071. * @extends Stream
  1072. */
  1073. class Parser extends Stream {
  1074. constructor() {
  1075. super();
  1076. this.lineStream = new LineStream();
  1077. this.parseStream = new ParseStream();
  1078. this.lineStream.pipe(this.parseStream);
  1079. this.lastProgramDateTime = null;
  1080. /* eslint-disable consistent-this */
  1081. const self = this;
  1082. /* eslint-enable consistent-this */
  1083. const uris = [];
  1084. let currentUri = {}; // if specified, the active EXT-X-MAP definition
  1085. let currentMap; // if specified, the active decryption key
  1086. let key;
  1087. let hasParts = false;
  1088. const noop = function () {};
  1089. const defaultMediaGroups = {
  1090. 'AUDIO': {},
  1091. 'VIDEO': {},
  1092. 'CLOSED-CAPTIONS': {},
  1093. 'SUBTITLES': {}
  1094. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  1095. // used in MPDs with Widevine encrypted streams.
  1096. const widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  1097. let currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  1098. this.manifest = {
  1099. allowCache: true,
  1100. discontinuityStarts: [],
  1101. dateRanges: [],
  1102. segments: []
  1103. }; // keep track of the last seen segment's byte range end, as segments are not required
  1104. // to provide the offset, in which case it defaults to the next byte after the
  1105. // previous segment
  1106. let lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  1107. let lastPartByterangeEnd = 0;
  1108. const dateRangeTags = {};
  1109. this.on('end', () => {
  1110. // only add preloadSegment if we don't yet have a uri for it.
  1111. // and we actually have parts/preloadHints
  1112. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  1113. return;
  1114. }
  1115. if (!currentUri.map && currentMap) {
  1116. currentUri.map = currentMap;
  1117. }
  1118. if (!currentUri.key && key) {
  1119. currentUri.key = key;
  1120. }
  1121. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  1122. currentUri.timeline = currentTimeline;
  1123. }
  1124. this.manifest.preloadSegment = currentUri;
  1125. }); // update the manifest with the m3u8 entry from the parse stream
  1126. this.parseStream.on('data', function (entry) {
  1127. let mediaGroup;
  1128. let rendition;
  1129. ({
  1130. tag() {
  1131. // switch based on the tag type
  1132. (({
  1133. version() {
  1134. if (entry.version) {
  1135. this.manifest.version = entry.version;
  1136. }
  1137. },
  1138. 'allow-cache'() {
  1139. this.manifest.allowCache = entry.allowed;
  1140. if (!('allowed' in entry)) {
  1141. this.trigger('info', {
  1142. message: 'defaulting allowCache to YES'
  1143. });
  1144. this.manifest.allowCache = true;
  1145. }
  1146. },
  1147. byterange() {
  1148. const byterange = {};
  1149. if ('length' in entry) {
  1150. currentUri.byterange = byterange;
  1151. byterange.length = entry.length;
  1152. if (!('offset' in entry)) {
  1153. /*
  1154. * From the latest spec (as of this writing):
  1155. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  1156. *
  1157. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  1158. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  1159. *
  1160. * "If o [offset] is not present, the sub-range begins at the next byte
  1161. * following the sub-range of the previous media segment."
  1162. */
  1163. entry.offset = lastByterangeEnd;
  1164. }
  1165. }
  1166. if ('offset' in entry) {
  1167. currentUri.byterange = byterange;
  1168. byterange.offset = entry.offset;
  1169. }
  1170. lastByterangeEnd = byterange.offset + byterange.length;
  1171. },
  1172. endlist() {
  1173. this.manifest.endList = true;
  1174. },
  1175. inf() {
  1176. if (!('mediaSequence' in this.manifest)) {
  1177. this.manifest.mediaSequence = 0;
  1178. this.trigger('info', {
  1179. message: 'defaulting media sequence to zero'
  1180. });
  1181. }
  1182. if (!('discontinuitySequence' in this.manifest)) {
  1183. this.manifest.discontinuitySequence = 0;
  1184. this.trigger('info', {
  1185. message: 'defaulting discontinuity sequence to zero'
  1186. });
  1187. }
  1188. if (entry.title) {
  1189. currentUri.title = entry.title;
  1190. }
  1191. if (entry.duration > 0) {
  1192. currentUri.duration = entry.duration;
  1193. }
  1194. if (entry.duration === 0) {
  1195. currentUri.duration = 0.01;
  1196. this.trigger('info', {
  1197. message: 'updating zero segment duration to a small value'
  1198. });
  1199. }
  1200. this.manifest.segments = uris;
  1201. },
  1202. key() {
  1203. if (!entry.attributes) {
  1204. this.trigger('warn', {
  1205. message: 'ignoring key declaration without attribute list'
  1206. });
  1207. return;
  1208. } // clear the active encryption key
  1209. if (entry.attributes.METHOD === 'NONE') {
  1210. key = null;
  1211. return;
  1212. }
  1213. if (!entry.attributes.URI) {
  1214. this.trigger('warn', {
  1215. message: 'ignoring key declaration without URI'
  1216. });
  1217. return;
  1218. }
  1219. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  1220. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1221. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  1222. attributes: entry.attributes
  1223. };
  1224. return;
  1225. }
  1226. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  1227. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  1228. this.manifest.contentProtection['com.microsoft.playready'] = {
  1229. uri: entry.attributes.URI
  1230. };
  1231. return;
  1232. } // check if the content is encrypted for Widevine
  1233. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  1234. if (entry.attributes.KEYFORMAT === widevineUuid) {
  1235. const VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  1236. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  1237. this.trigger('warn', {
  1238. message: 'invalid key method provided for Widevine'
  1239. });
  1240. return;
  1241. }
  1242. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  1243. this.trigger('warn', {
  1244. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  1245. });
  1246. }
  1247. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  1248. this.trigger('warn', {
  1249. message: 'invalid key URI provided for Widevine'
  1250. });
  1251. return;
  1252. }
  1253. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  1254. this.trigger('warn', {
  1255. message: 'invalid key ID provided for Widevine'
  1256. });
  1257. return;
  1258. } // if Widevine key attributes are valid, store them as `contentProtection`
  1259. // on the manifest to emulate Widevine tag structure in a DASH mpd
  1260. this.manifest.contentProtection = this.manifest.contentProtection || {};
  1261. this.manifest.contentProtection['com.widevine.alpha'] = {
  1262. attributes: {
  1263. schemeIdUri: entry.attributes.KEYFORMAT,
  1264. // remove '0x' from the key id string
  1265. keyId: entry.attributes.KEYID.substring(2)
  1266. },
  1267. // decode the base64-encoded PSSH box
  1268. pssh: decodeB64ToUint8Array(entry.attributes.URI.split(',')[1])
  1269. };
  1270. return;
  1271. }
  1272. if (!entry.attributes.METHOD) {
  1273. this.trigger('warn', {
  1274. message: 'defaulting key method to AES-128'
  1275. });
  1276. } // setup an encryption key for upcoming segments
  1277. key = {
  1278. method: entry.attributes.METHOD || 'AES-128',
  1279. uri: entry.attributes.URI
  1280. };
  1281. if (typeof entry.attributes.IV !== 'undefined') {
  1282. key.iv = entry.attributes.IV;
  1283. }
  1284. },
  1285. 'media-sequence'() {
  1286. if (!isFinite(entry.number)) {
  1287. this.trigger('warn', {
  1288. message: 'ignoring invalid media sequence: ' + entry.number
  1289. });
  1290. return;
  1291. }
  1292. this.manifest.mediaSequence = entry.number;
  1293. },
  1294. 'discontinuity-sequence'() {
  1295. if (!isFinite(entry.number)) {
  1296. this.trigger('warn', {
  1297. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  1298. });
  1299. return;
  1300. }
  1301. this.manifest.discontinuitySequence = entry.number;
  1302. currentTimeline = entry.number;
  1303. },
  1304. 'playlist-type'() {
  1305. if (!/VOD|EVENT/.test(entry.playlistType)) {
  1306. this.trigger('warn', {
  1307. message: 'ignoring unknown playlist type: ' + entry.playlist
  1308. });
  1309. return;
  1310. }
  1311. this.manifest.playlistType = entry.playlistType;
  1312. },
  1313. map() {
  1314. currentMap = {};
  1315. if (entry.uri) {
  1316. currentMap.uri = entry.uri;
  1317. }
  1318. if (entry.byterange) {
  1319. currentMap.byterange = entry.byterange;
  1320. }
  1321. if (key) {
  1322. currentMap.key = key;
  1323. }
  1324. },
  1325. 'stream-inf'() {
  1326. this.manifest.playlists = uris;
  1327. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1328. if (!entry.attributes) {
  1329. this.trigger('warn', {
  1330. message: 'ignoring empty stream-inf attributes'
  1331. });
  1332. return;
  1333. }
  1334. if (!currentUri.attributes) {
  1335. currentUri.attributes = {};
  1336. }
  1337. _extends(currentUri.attributes, entry.attributes);
  1338. },
  1339. media() {
  1340. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  1341. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  1342. this.trigger('warn', {
  1343. message: 'ignoring incomplete or missing media group'
  1344. });
  1345. return;
  1346. } // find the media group, creating defaults as necessary
  1347. const mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  1348. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  1349. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  1350. rendition = {
  1351. default: /yes/i.test(entry.attributes.DEFAULT)
  1352. };
  1353. if (rendition.default) {
  1354. rendition.autoselect = true;
  1355. } else {
  1356. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  1357. }
  1358. if (entry.attributes.LANGUAGE) {
  1359. rendition.language = entry.attributes.LANGUAGE;
  1360. }
  1361. if (entry.attributes.URI) {
  1362. rendition.uri = entry.attributes.URI;
  1363. }
  1364. if (entry.attributes['INSTREAM-ID']) {
  1365. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  1366. }
  1367. if (entry.attributes.CHARACTERISTICS) {
  1368. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  1369. }
  1370. if (entry.attributes.FORCED) {
  1371. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  1372. } // insert the new rendition
  1373. mediaGroup[entry.attributes.NAME] = rendition;
  1374. },
  1375. discontinuity() {
  1376. currentTimeline += 1;
  1377. currentUri.discontinuity = true;
  1378. this.manifest.discontinuityStarts.push(uris.length);
  1379. },
  1380. 'program-date-time'() {
  1381. if (typeof this.manifest.dateTimeString === 'undefined') {
  1382. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  1383. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  1384. // to the manifest object
  1385. // TODO: Consider removing this in future major version
  1386. this.manifest.dateTimeString = entry.dateTimeString;
  1387. this.manifest.dateTimeObject = entry.dateTimeObject;
  1388. }
  1389. currentUri.dateTimeString = entry.dateTimeString;
  1390. currentUri.dateTimeObject = entry.dateTimeObject;
  1391. const {
  1392. lastProgramDateTime
  1393. } = this;
  1394. this.lastProgramDateTime = new Date(entry.dateTimeString).getTime(); // We should extrapolate Program Date Time backward only during first program date time occurrence.
  1395. // Once we have at least one program date time point, we can always extrapolate it forward using lastProgramDateTime reference.
  1396. if (lastProgramDateTime === null) {
  1397. // Extrapolate Program Date Time backward
  1398. // Since it is first program date time occurrence we're assuming that
  1399. // all this.manifest.segments have no program date time info
  1400. this.manifest.segments.reduceRight((programDateTime, segment) => {
  1401. segment.programDateTime = programDateTime - segment.duration * 1000;
  1402. return segment.programDateTime;
  1403. }, this.lastProgramDateTime);
  1404. }
  1405. },
  1406. targetduration() {
  1407. if (!isFinite(entry.duration) || entry.duration < 0) {
  1408. this.trigger('warn', {
  1409. message: 'ignoring invalid target duration: ' + entry.duration
  1410. });
  1411. return;
  1412. }
  1413. this.manifest.targetDuration = entry.duration;
  1414. setHoldBack.call(this, this.manifest);
  1415. },
  1416. start() {
  1417. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  1418. this.trigger('warn', {
  1419. message: 'ignoring start declaration without appropriate attribute list'
  1420. });
  1421. return;
  1422. }
  1423. this.manifest.start = {
  1424. timeOffset: entry.attributes['TIME-OFFSET'],
  1425. precise: entry.attributes.PRECISE
  1426. };
  1427. },
  1428. 'cue-out'() {
  1429. currentUri.cueOut = entry.data;
  1430. },
  1431. 'cue-out-cont'() {
  1432. currentUri.cueOutCont = entry.data;
  1433. },
  1434. 'cue-in'() {
  1435. currentUri.cueIn = entry.data;
  1436. },
  1437. 'skip'() {
  1438. this.manifest.skip = camelCaseKeys(entry.attributes);
  1439. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  1440. },
  1441. 'part'() {
  1442. hasParts = true; // parts are always specifed before a segment
  1443. const segmentIndex = this.manifest.segments.length;
  1444. const part = camelCaseKeys(entry.attributes);
  1445. currentUri.parts = currentUri.parts || [];
  1446. currentUri.parts.push(part);
  1447. if (part.byterange) {
  1448. if (!part.byterange.hasOwnProperty('offset')) {
  1449. part.byterange.offset = lastPartByterangeEnd;
  1450. }
  1451. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  1452. }
  1453. const partIndex = currentUri.parts.length - 1;
  1454. this.warnOnMissingAttributes_(`#EXT-X-PART #${partIndex} for segment #${segmentIndex}`, entry.attributes, ['URI', 'DURATION']);
  1455. if (this.manifest.renditionReports) {
  1456. this.manifest.renditionReports.forEach((r, i) => {
  1457. if (!r.hasOwnProperty('lastPart')) {
  1458. this.trigger('warn', {
  1459. message: `#EXT-X-RENDITION-REPORT #${i} lacks required attribute(s): LAST-PART`
  1460. });
  1461. }
  1462. });
  1463. }
  1464. },
  1465. 'server-control'() {
  1466. const attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  1467. if (!attrs.hasOwnProperty('canBlockReload')) {
  1468. attrs.canBlockReload = false;
  1469. this.trigger('info', {
  1470. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  1471. });
  1472. }
  1473. setHoldBack.call(this, this.manifest);
  1474. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  1475. this.trigger('warn', {
  1476. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  1477. });
  1478. }
  1479. },
  1480. 'preload-hint'() {
  1481. // parts are always specifed before a segment
  1482. const segmentIndex = this.manifest.segments.length;
  1483. const hint = camelCaseKeys(entry.attributes);
  1484. const isPart = hint.type && hint.type === 'PART';
  1485. currentUri.preloadHints = currentUri.preloadHints || [];
  1486. currentUri.preloadHints.push(hint);
  1487. if (hint.byterange) {
  1488. if (!hint.byterange.hasOwnProperty('offset')) {
  1489. // use last part byterange end or zero if not a part.
  1490. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  1491. if (isPart) {
  1492. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  1493. }
  1494. }
  1495. }
  1496. const index = currentUri.preloadHints.length - 1;
  1497. this.warnOnMissingAttributes_(`#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex}`, entry.attributes, ['TYPE', 'URI']);
  1498. if (!hint.type) {
  1499. return;
  1500. } // search through all preload hints except for the current one for
  1501. // a duplicate type.
  1502. for (let i = 0; i < currentUri.preloadHints.length - 1; i++) {
  1503. const otherHint = currentUri.preloadHints[i];
  1504. if (!otherHint.type) {
  1505. continue;
  1506. }
  1507. if (otherHint.type === hint.type) {
  1508. this.trigger('warn', {
  1509. message: `#EXT-X-PRELOAD-HINT #${index} for segment #${segmentIndex} has the same TYPE ${hint.type} as preload hint #${i}`
  1510. });
  1511. }
  1512. }
  1513. },
  1514. 'rendition-report'() {
  1515. const report = camelCaseKeys(entry.attributes);
  1516. this.manifest.renditionReports = this.manifest.renditionReports || [];
  1517. this.manifest.renditionReports.push(report);
  1518. const index = this.manifest.renditionReports.length - 1;
  1519. const required = ['LAST-MSN', 'URI'];
  1520. if (hasParts) {
  1521. required.push('LAST-PART');
  1522. }
  1523. this.warnOnMissingAttributes_(`#EXT-X-RENDITION-REPORT #${index}`, entry.attributes, required);
  1524. },
  1525. 'part-inf'() {
  1526. this.manifest.partInf = camelCaseKeys(entry.attributes);
  1527. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  1528. if (this.manifest.partInf.partTarget) {
  1529. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  1530. }
  1531. setHoldBack.call(this, this.manifest);
  1532. },
  1533. 'daterange'() {
  1534. this.manifest.dateRanges.push(camelCaseKeys(entry.attributes));
  1535. const index = this.manifest.dateRanges.length - 1;
  1536. this.warnOnMissingAttributes_(`#EXT-X-DATERANGE #${index}`, entry.attributes, ['ID', 'START-DATE']);
  1537. const dateRange = this.manifest.dateRanges[index];
  1538. if (dateRange.endDate && dateRange.startDate && new Date(dateRange.endDate) < new Date(dateRange.startDate)) {
  1539. this.trigger('warn', {
  1540. message: 'EXT-X-DATERANGE END-DATE must be equal to or later than the value of the START-DATE'
  1541. });
  1542. }
  1543. if (dateRange.duration && dateRange.duration < 0) {
  1544. this.trigger('warn', {
  1545. message: 'EXT-X-DATERANGE DURATION must not be negative'
  1546. });
  1547. }
  1548. if (dateRange.plannedDuration && dateRange.plannedDuration < 0) {
  1549. this.trigger('warn', {
  1550. message: 'EXT-X-DATERANGE PLANNED-DURATION must not be negative'
  1551. });
  1552. }
  1553. const endOnNextYes = !!dateRange.endOnNext;
  1554. if (endOnNextYes && !dateRange.class) {
  1555. this.trigger('warn', {
  1556. message: 'EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must have a CLASS attribute'
  1557. });
  1558. }
  1559. if (endOnNextYes && (dateRange.duration || dateRange.endDate)) {
  1560. this.trigger('warn', {
  1561. message: 'EXT-X-DATERANGE with an END-ON-NEXT=YES attribute must not contain DURATION or END-DATE attributes'
  1562. });
  1563. }
  1564. if (dateRange.duration && dateRange.endDate) {
  1565. const startDate = dateRange.startDate;
  1566. const newDateInSeconds = startDate.getTime() + dateRange.duration * 1000;
  1567. this.manifest.dateRanges[index].endDate = new Date(newDateInSeconds);
  1568. }
  1569. if (!dateRangeTags[dateRange.id]) {
  1570. dateRangeTags[dateRange.id] = dateRange;
  1571. } else {
  1572. for (const attribute in dateRangeTags[dateRange.id]) {
  1573. if (!!dateRange[attribute] && JSON.stringify(dateRangeTags[dateRange.id][attribute]) !== JSON.stringify(dateRange[attribute])) {
  1574. this.trigger('warn', {
  1575. message: 'EXT-X-DATERANGE tags with the same ID in a playlist must have the same attributes values'
  1576. });
  1577. break;
  1578. }
  1579. } // if tags with the same ID do not have conflicting attributes, merge them
  1580. const dateRangeWithSameId = this.manifest.dateRanges.findIndex(dateRangeToFind => dateRangeToFind.id === dateRange.id);
  1581. this.manifest.dateRanges[dateRangeWithSameId] = _extends(this.manifest.dateRanges[dateRangeWithSameId], dateRange);
  1582. dateRangeTags[dateRange.id] = _extends(dateRangeTags[dateRange.id], dateRange); // after merging, delete the duplicate dateRange that was added last
  1583. this.manifest.dateRanges.pop();
  1584. }
  1585. },
  1586. 'independent-segments'() {
  1587. this.manifest.independentSegments = true;
  1588. },
  1589. 'content-steering'() {
  1590. this.manifest.contentSteering = camelCaseKeys(entry.attributes);
  1591. this.warnOnMissingAttributes_('#EXT-X-CONTENT-STEERING', entry.attributes, ['SERVER-URI']);
  1592. }
  1593. })[entry.tagType] || noop).call(self);
  1594. },
  1595. uri() {
  1596. currentUri.uri = entry.uri;
  1597. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  1598. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  1599. this.trigger('warn', {
  1600. message: 'defaulting segment duration to the target duration'
  1601. });
  1602. currentUri.duration = this.manifest.targetDuration;
  1603. } // annotate with encryption information, if necessary
  1604. if (key) {
  1605. currentUri.key = key;
  1606. }
  1607. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  1608. if (currentMap) {
  1609. currentUri.map = currentMap;
  1610. } // reset the last byterange end as it needs to be 0 between parts
  1611. lastPartByterangeEnd = 0; // Once we have at least one program date time we can always extrapolate it forward
  1612. if (this.lastProgramDateTime !== null) {
  1613. currentUri.programDateTime = this.lastProgramDateTime;
  1614. this.lastProgramDateTime += currentUri.duration * 1000;
  1615. } // prepare for the next URI
  1616. currentUri = {};
  1617. },
  1618. comment() {// comments are not important for playback
  1619. },
  1620. custom() {
  1621. // if this is segment-level data attach the output to the segment
  1622. if (entry.segment) {
  1623. currentUri.custom = currentUri.custom || {};
  1624. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  1625. } else {
  1626. this.manifest.custom = this.manifest.custom || {};
  1627. this.manifest.custom[entry.customType] = entry.data;
  1628. }
  1629. }
  1630. })[entry.type].call(self);
  1631. });
  1632. }
  1633. warnOnMissingAttributes_(identifier, attributes, required) {
  1634. const missing = [];
  1635. required.forEach(function (key) {
  1636. if (!attributes.hasOwnProperty(key)) {
  1637. missing.push(key);
  1638. }
  1639. });
  1640. if (missing.length) {
  1641. this.trigger('warn', {
  1642. message: `${identifier} lacks required attribute(s): ${missing.join(', ')}`
  1643. });
  1644. }
  1645. }
  1646. /**
  1647. * Parse the input string and update the manifest object.
  1648. *
  1649. * @param {string} chunk a potentially incomplete portion of the manifest
  1650. */
  1651. push(chunk) {
  1652. this.lineStream.push(chunk);
  1653. }
  1654. /**
  1655. * Flush any remaining input. This can be handy if the last line of an M3U8
  1656. * manifest did not contain a trailing newline but the file has been
  1657. * completely received.
  1658. */
  1659. end() {
  1660. // flush any buffered input
  1661. this.lineStream.push('\n');
  1662. if (this.manifest.dateRanges.length && this.lastProgramDateTime === null) {
  1663. this.trigger('warn', {
  1664. message: 'A playlist with EXT-X-DATERANGE tag must contain atleast one EXT-X-PROGRAM-DATE-TIME tag'
  1665. });
  1666. }
  1667. this.lastProgramDateTime = null;
  1668. this.trigger('end');
  1669. }
  1670. /**
  1671. * Add an additional parser for non-standard tags
  1672. *
  1673. * @param {Object} options a map of options for the added parser
  1674. * @param {RegExp} options.expression a regular expression to match the custom header
  1675. * @param {string} options.customType the custom type to register to the output
  1676. * @param {Function} [options.dataParser] function to parse the line into an object
  1677. * @param {boolean} [options.segment] should tag data be attached to the segment object
  1678. */
  1679. addParser(options) {
  1680. this.parseStream.addParser(options);
  1681. }
  1682. /**
  1683. * Add a custom header mapper
  1684. *
  1685. * @param {Object} options
  1686. * @param {RegExp} options.expression a regular expression to match the custom header
  1687. * @param {Function} options.map function to translate tag into a different tag
  1688. */
  1689. addTagMapper(options) {
  1690. this.parseStream.addTagMapper(options);
  1691. }
  1692. }
  1693. var regexs = {
  1694. // to determine mime types
  1695. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  1696. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  1697. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  1698. // to determine if a codec is audio or video
  1699. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  1700. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  1701. text: /^(stpp.ttml.im1t)/,
  1702. // mux.js support regex
  1703. muxerVideo: /^(avc0?1)/,
  1704. muxerAudio: /^(mp4a)/,
  1705. // match nothing as muxer does not support text right now.
  1706. // there cannot never be a character before the start of a string
  1707. // so this matches nothing.
  1708. muxerText: /a^/
  1709. };
  1710. var mediaTypes = ['video', 'audio', 'text'];
  1711. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  1712. /**
  1713. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  1714. * `avc1.<hhhhhh>`
  1715. *
  1716. * @param {string} codec
  1717. * Codec string to translate
  1718. * @return {string}
  1719. * The translated codec string
  1720. */
  1721. var translateLegacyCodec = function translateLegacyCodec(codec) {
  1722. if (!codec) {
  1723. return codec;
  1724. }
  1725. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  1726. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  1727. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  1728. return 'avc1.' + profileHex + '00' + avcLevelHex;
  1729. });
  1730. };
  1731. /**
  1732. * @typedef {Object} ParsedCodecInfo
  1733. * @property {number} codecCount
  1734. * Number of codecs parsed
  1735. * @property {string} [videoCodec]
  1736. * Parsed video codec (if found)
  1737. * @property {string} [videoObjectTypeIndicator]
  1738. * Video object type indicator (if found)
  1739. * @property {string|null} audioProfile
  1740. * Audio profile
  1741. */
  1742. /**
  1743. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  1744. * object type indicator, and the audio profile.
  1745. *
  1746. * @param {string} [codecString]
  1747. * The codec string to parse
  1748. * @return {ParsedCodecInfo}
  1749. * Parsed codec info
  1750. */
  1751. var parseCodecs = function parseCodecs(codecString) {
  1752. if (codecString === void 0) {
  1753. codecString = '';
  1754. }
  1755. var codecs = codecString.split(',');
  1756. var result = [];
  1757. codecs.forEach(function (codec) {
  1758. codec = codec.trim();
  1759. var codecType;
  1760. mediaTypes.forEach(function (name) {
  1761. var match = regexs[name].exec(codec.toLowerCase());
  1762. if (!match || match.length <= 1) {
  1763. return;
  1764. }
  1765. codecType = name; // maintain codec case
  1766. var type = codec.substring(0, match[1].length);
  1767. var details = codec.replace(type, '');
  1768. result.push({
  1769. type: type,
  1770. details: details,
  1771. mediaType: name
  1772. });
  1773. });
  1774. if (!codecType) {
  1775. result.push({
  1776. type: codec,
  1777. details: '',
  1778. mediaType: 'unknown'
  1779. });
  1780. }
  1781. });
  1782. return result;
  1783. };
  1784. /**
  1785. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  1786. * a default alternate audio playlist for the provided audio group.
  1787. *
  1788. * @param {Object} master
  1789. * The master playlist
  1790. * @param {string} audioGroupId
  1791. * ID of the audio group for which to find the default codec info
  1792. * @return {ParsedCodecInfo}
  1793. * Parsed codec info
  1794. */
  1795. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  1796. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  1797. return null;
  1798. }
  1799. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  1800. if (!audioGroup) {
  1801. return null;
  1802. }
  1803. for (var name in audioGroup) {
  1804. var audioType = audioGroup[name];
  1805. if (audioType.default && audioType.playlists) {
  1806. // codec should be the same for all playlists within the audio type
  1807. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  1808. }
  1809. }
  1810. return null;
  1811. };
  1812. var isAudioCodec = function isAudioCodec(codec) {
  1813. if (codec === void 0) {
  1814. codec = '';
  1815. }
  1816. return regexs.audio.test(codec.trim().toLowerCase());
  1817. };
  1818. var isTextCodec = function isTextCodec(codec) {
  1819. if (codec === void 0) {
  1820. codec = '';
  1821. }
  1822. return regexs.text.test(codec.trim().toLowerCase());
  1823. };
  1824. var getMimeForCodec = function getMimeForCodec(codecString) {
  1825. if (!codecString || typeof codecString !== 'string') {
  1826. return;
  1827. }
  1828. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  1829. return translateLegacyCodec(c.trim());
  1830. }); // default to video type
  1831. var type = 'video'; // only change to audio type if the only codec we have is
  1832. // audio
  1833. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  1834. type = 'audio';
  1835. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  1836. // text uses application/<container> for now
  1837. type = 'application';
  1838. } // default the container to mp4
  1839. var container = 'mp4'; // every codec must be able to go into the container
  1840. // for that container to be the correct one
  1841. if (codecs.every(function (c) {
  1842. return regexs.mp4.test(c);
  1843. })) {
  1844. container = 'mp4';
  1845. } else if (codecs.every(function (c) {
  1846. return regexs.webm.test(c);
  1847. })) {
  1848. container = 'webm';
  1849. } else if (codecs.every(function (c) {
  1850. return regexs.ogg.test(c);
  1851. })) {
  1852. container = 'ogg';
  1853. }
  1854. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  1855. };
  1856. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  1857. if (codecString === void 0) {
  1858. codecString = '';
  1859. }
  1860. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  1861. };
  1862. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  1863. if (codecString === void 0) {
  1864. codecString = '';
  1865. }
  1866. return codecString.toLowerCase().split(',').every(function (codec) {
  1867. codec = codec.trim(); // any match is supported.
  1868. for (var i = 0; i < upperMediaTypes.length; i++) {
  1869. var type = upperMediaTypes[i];
  1870. if (regexs["muxer" + type].test(codec)) {
  1871. return true;
  1872. }
  1873. }
  1874. return false;
  1875. });
  1876. };
  1877. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  1878. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  1879. /**
  1880. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  1881. */
  1882. /**
  1883. * Delegates to videojs.obj.merge (Video.js 8) or
  1884. * videojs.mergeOptions (Video.js 7).
  1885. */
  1886. function merge$1(...args) {
  1887. const context = videojs__default["default"].obj || videojs__default["default"];
  1888. const fn = context.merge || context.mergeOptions;
  1889. return fn.apply(context, args);
  1890. }
  1891. /**
  1892. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  1893. * videojs.createTimeRanges (Video.js 7).
  1894. */
  1895. function createTimeRanges(...args) {
  1896. const context = videojs__default["default"].time || videojs__default["default"];
  1897. const fn = context.createTimeRanges || context.createTimeRanges;
  1898. return fn.apply(context, args);
  1899. }
  1900. /**
  1901. * ranges
  1902. *
  1903. * Utilities for working with TimeRanges.
  1904. *
  1905. */
  1906. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  1907. // can be misleading because of precision differences or when the current media has poorly
  1908. // aligned audio and video, which can cause values to be slightly off from what you would
  1909. // expect. This value is what we consider to be safe to use in such comparisons to account
  1910. // for these scenarios.
  1911. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  1912. const filterRanges = function (timeRanges, predicate) {
  1913. const results = [];
  1914. let i;
  1915. if (timeRanges && timeRanges.length) {
  1916. // Search for ranges that match the predicate
  1917. for (i = 0; i < timeRanges.length; i++) {
  1918. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  1919. results.push([timeRanges.start(i), timeRanges.end(i)]);
  1920. }
  1921. }
  1922. }
  1923. return createTimeRanges(results);
  1924. };
  1925. /**
  1926. * Attempts to find the buffered TimeRange that contains the specified
  1927. * time.
  1928. *
  1929. * @param {TimeRanges} buffered - the TimeRanges object to query
  1930. * @param {number} time - the time to filter on.
  1931. * @return {TimeRanges} a new TimeRanges object
  1932. */
  1933. const findRange = function (buffered, time) {
  1934. return filterRanges(buffered, function (start, end) {
  1935. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  1936. });
  1937. };
  1938. /**
  1939. * Returns the TimeRanges that begin later than the specified time.
  1940. *
  1941. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  1942. * @param {number} time - the time to filter on.
  1943. * @return {TimeRanges} a new TimeRanges object.
  1944. */
  1945. const findNextRange = function (timeRanges, time) {
  1946. return filterRanges(timeRanges, function (start) {
  1947. return start - TIME_FUDGE_FACTOR >= time;
  1948. });
  1949. };
  1950. /**
  1951. * Returns gaps within a list of TimeRanges
  1952. *
  1953. * @param {TimeRanges} buffered - the TimeRanges object
  1954. * @return {TimeRanges} a TimeRanges object of gaps
  1955. */
  1956. const findGaps = function (buffered) {
  1957. if (buffered.length < 2) {
  1958. return createTimeRanges();
  1959. }
  1960. const ranges = [];
  1961. for (let i = 1; i < buffered.length; i++) {
  1962. const start = buffered.end(i - 1);
  1963. const end = buffered.start(i);
  1964. ranges.push([start, end]);
  1965. }
  1966. return createTimeRanges(ranges);
  1967. };
  1968. /**
  1969. * Calculate the intersection of two TimeRanges
  1970. *
  1971. * @param {TimeRanges} bufferA
  1972. * @param {TimeRanges} bufferB
  1973. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  1974. */
  1975. const bufferIntersection = function (bufferA, bufferB) {
  1976. let start = null;
  1977. let end = null;
  1978. let arity = 0;
  1979. const extents = [];
  1980. const ranges = [];
  1981. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  1982. return createTimeRanges();
  1983. } // Handle the case where we have both buffers and create an
  1984. // intersection of the two
  1985. let count = bufferA.length; // A) Gather up all start and end times
  1986. while (count--) {
  1987. extents.push({
  1988. time: bufferA.start(count),
  1989. type: 'start'
  1990. });
  1991. extents.push({
  1992. time: bufferA.end(count),
  1993. type: 'end'
  1994. });
  1995. }
  1996. count = bufferB.length;
  1997. while (count--) {
  1998. extents.push({
  1999. time: bufferB.start(count),
  2000. type: 'start'
  2001. });
  2002. extents.push({
  2003. time: bufferB.end(count),
  2004. type: 'end'
  2005. });
  2006. } // B) Sort them by time
  2007. extents.sort(function (a, b) {
  2008. return a.time - b.time;
  2009. }); // C) Go along one by one incrementing arity for start and decrementing
  2010. // arity for ends
  2011. for (count = 0; count < extents.length; count++) {
  2012. if (extents[count].type === 'start') {
  2013. arity++; // D) If arity is ever incremented to 2 we are entering an
  2014. // overlapping range
  2015. if (arity === 2) {
  2016. start = extents[count].time;
  2017. }
  2018. } else if (extents[count].type === 'end') {
  2019. arity--; // E) If arity is ever decremented to 1 we leaving an
  2020. // overlapping range
  2021. if (arity === 1) {
  2022. end = extents[count].time;
  2023. }
  2024. } // F) Record overlapping ranges
  2025. if (start !== null && end !== null) {
  2026. ranges.push([start, end]);
  2027. start = null;
  2028. end = null;
  2029. }
  2030. }
  2031. return createTimeRanges(ranges);
  2032. };
  2033. /**
  2034. * Gets a human readable string for a TimeRange
  2035. *
  2036. * @param {TimeRange} range
  2037. * @return {string} a human readable string
  2038. */
  2039. const printableRange = range => {
  2040. const strArr = [];
  2041. if (!range || !range.length) {
  2042. return '';
  2043. }
  2044. for (let i = 0; i < range.length; i++) {
  2045. strArr.push(range.start(i) + ' => ' + range.end(i));
  2046. }
  2047. return strArr.join(', ');
  2048. };
  2049. /**
  2050. * Calculates the amount of time left in seconds until the player hits the end of the
  2051. * buffer and causes a rebuffer
  2052. *
  2053. * @param {TimeRange} buffered
  2054. * The state of the buffer
  2055. * @param {Numnber} currentTime
  2056. * The current time of the player
  2057. * @param {number} playbackRate
  2058. * The current playback rate of the player. Defaults to 1.
  2059. * @return {number}
  2060. * Time until the player has to start rebuffering in seconds.
  2061. * @function timeUntilRebuffer
  2062. */
  2063. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  2064. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  2065. return (bufferedEnd - currentTime) / playbackRate;
  2066. };
  2067. /**
  2068. * Converts a TimeRanges object into an array representation
  2069. *
  2070. * @param {TimeRanges} timeRanges
  2071. * @return {Array}
  2072. */
  2073. const timeRangesToArray = timeRanges => {
  2074. const timeRangesList = [];
  2075. for (let i = 0; i < timeRanges.length; i++) {
  2076. timeRangesList.push({
  2077. start: timeRanges.start(i),
  2078. end: timeRanges.end(i)
  2079. });
  2080. }
  2081. return timeRangesList;
  2082. };
  2083. /**
  2084. * Determines if two time range objects are different.
  2085. *
  2086. * @param {TimeRange} a
  2087. * the first time range object to check
  2088. *
  2089. * @param {TimeRange} b
  2090. * the second time range object to check
  2091. *
  2092. * @return {Boolean}
  2093. * Whether the time range objects differ
  2094. */
  2095. const isRangeDifferent = function (a, b) {
  2096. // same object
  2097. if (a === b) {
  2098. return false;
  2099. } // one or the other is undefined
  2100. if (!a && b || !b && a) {
  2101. return true;
  2102. } // length is different
  2103. if (a.length !== b.length) {
  2104. return true;
  2105. } // see if any start/end pair is different
  2106. for (let i = 0; i < a.length; i++) {
  2107. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  2108. return true;
  2109. }
  2110. } // if the length and every pair is the same
  2111. // this is the same time range
  2112. return false;
  2113. };
  2114. const lastBufferedEnd = function (a) {
  2115. if (!a || !a.length || !a.end) {
  2116. return;
  2117. }
  2118. return a.end(a.length - 1);
  2119. };
  2120. /**
  2121. * A utility function to add up the amount of time in a timeRange
  2122. * after a specified startTime.
  2123. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  2124. * would return 40 as there are 40s seconds after 0 in the timeRange
  2125. *
  2126. * @param {TimeRange} range
  2127. * The range to check against
  2128. * @param {number} startTime
  2129. * The time in the time range that you should start counting from
  2130. *
  2131. * @return {number}
  2132. * The number of seconds in the buffer passed the specified time.
  2133. */
  2134. const timeAheadOf = function (range, startTime) {
  2135. let time = 0;
  2136. if (!range || !range.length) {
  2137. return time;
  2138. }
  2139. for (let i = 0; i < range.length; i++) {
  2140. const start = range.start(i);
  2141. const end = range.end(i); // startTime is after this range entirely
  2142. if (startTime > end) {
  2143. continue;
  2144. } // startTime is within this range
  2145. if (startTime > start && startTime <= end) {
  2146. time += end - startTime;
  2147. continue;
  2148. } // startTime is before this range.
  2149. time += end - start;
  2150. }
  2151. return time;
  2152. };
  2153. /**
  2154. * @file playlist.js
  2155. *
  2156. * Playlist related utilities.
  2157. */
  2158. /**
  2159. * Get the duration of a segment, with special cases for
  2160. * llhls segments that do not have a duration yet.
  2161. *
  2162. * @param {Object} playlist
  2163. * the playlist that the segment belongs to.
  2164. * @param {Object} segment
  2165. * the segment to get a duration for.
  2166. *
  2167. * @return {number}
  2168. * the segment duration
  2169. */
  2170. const segmentDurationWithParts = (playlist, segment) => {
  2171. // if this isn't a preload segment
  2172. // then we will have a segment duration that is accurate.
  2173. if (!segment.preload) {
  2174. return segment.duration;
  2175. } // otherwise we have to add up parts and preload hints
  2176. // to get an up to date duration.
  2177. let result = 0;
  2178. (segment.parts || []).forEach(function (p) {
  2179. result += p.duration;
  2180. }); // for preload hints we have to use partTargetDuration
  2181. // as they won't even have a duration yet.
  2182. (segment.preloadHints || []).forEach(function (p) {
  2183. if (p.type === 'PART') {
  2184. result += playlist.partTargetDuration;
  2185. }
  2186. });
  2187. return result;
  2188. };
  2189. /**
  2190. * A function to get a combined list of parts and segments with durations
  2191. * and indexes.
  2192. *
  2193. * @param {Playlist} playlist the playlist to get the list for.
  2194. *
  2195. * @return {Array} The part/segment list.
  2196. */
  2197. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  2198. if (segment.parts) {
  2199. segment.parts.forEach(function (part, pi) {
  2200. acc.push({
  2201. duration: part.duration,
  2202. segmentIndex: si,
  2203. partIndex: pi,
  2204. part,
  2205. segment
  2206. });
  2207. });
  2208. } else {
  2209. acc.push({
  2210. duration: segment.duration,
  2211. segmentIndex: si,
  2212. partIndex: null,
  2213. segment,
  2214. part: null
  2215. });
  2216. }
  2217. return acc;
  2218. }, []);
  2219. const getLastParts = media => {
  2220. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  2221. return lastSegment && lastSegment.parts || [];
  2222. };
  2223. const getKnownPartCount = ({
  2224. preloadSegment
  2225. }) => {
  2226. if (!preloadSegment) {
  2227. return;
  2228. }
  2229. const {
  2230. parts,
  2231. preloadHints
  2232. } = preloadSegment;
  2233. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  2234. partCount += parts && parts.length ? parts.length : 0;
  2235. return partCount;
  2236. };
  2237. /**
  2238. * Get the number of seconds to delay from the end of a
  2239. * live playlist.
  2240. *
  2241. * @param {Playlist} main the main playlist
  2242. * @param {Playlist} media the media playlist
  2243. * @return {number} the hold back in seconds.
  2244. */
  2245. const liveEdgeDelay = (main, media) => {
  2246. if (media.endList) {
  2247. return 0;
  2248. } // dash suggestedPresentationDelay trumps everything
  2249. if (main && main.suggestedPresentationDelay) {
  2250. return main.suggestedPresentationDelay;
  2251. }
  2252. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  2253. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  2254. return media.serverControl.partHoldBack;
  2255. } else if (hasParts && media.partTargetDuration) {
  2256. return media.partTargetDuration * 3; // finally look for full segment delays
  2257. } else if (media.serverControl && media.serverControl.holdBack) {
  2258. return media.serverControl.holdBack;
  2259. } else if (media.targetDuration) {
  2260. return media.targetDuration * 3;
  2261. }
  2262. return 0;
  2263. };
  2264. /**
  2265. * walk backward until we find a duration we can use
  2266. * or return a failure
  2267. *
  2268. * @param {Playlist} playlist the playlist to walk through
  2269. * @param {Number} endSequence the mediaSequence to stop walking on
  2270. */
  2271. const backwardDuration = function (playlist, endSequence) {
  2272. let result = 0;
  2273. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  2274. // the interval, use it
  2275. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  2276. // information that is earlier than endSequence
  2277. if (segment) {
  2278. if (typeof segment.start !== 'undefined') {
  2279. return {
  2280. result: segment.start,
  2281. precise: true
  2282. };
  2283. }
  2284. if (typeof segment.end !== 'undefined') {
  2285. return {
  2286. result: segment.end - segment.duration,
  2287. precise: true
  2288. };
  2289. }
  2290. }
  2291. while (i--) {
  2292. segment = playlist.segments[i];
  2293. if (typeof segment.end !== 'undefined') {
  2294. return {
  2295. result: result + segment.end,
  2296. precise: true
  2297. };
  2298. }
  2299. result += segmentDurationWithParts(playlist, segment);
  2300. if (typeof segment.start !== 'undefined') {
  2301. return {
  2302. result: result + segment.start,
  2303. precise: true
  2304. };
  2305. }
  2306. }
  2307. return {
  2308. result,
  2309. precise: false
  2310. };
  2311. };
  2312. /**
  2313. * walk forward until we find a duration we can use
  2314. * or return a failure
  2315. *
  2316. * @param {Playlist} playlist the playlist to walk through
  2317. * @param {number} endSequence the mediaSequence to stop walking on
  2318. */
  2319. const forwardDuration = function (playlist, endSequence) {
  2320. let result = 0;
  2321. let segment;
  2322. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  2323. // information
  2324. for (; i < playlist.segments.length; i++) {
  2325. segment = playlist.segments[i];
  2326. if (typeof segment.start !== 'undefined') {
  2327. return {
  2328. result: segment.start - result,
  2329. precise: true
  2330. };
  2331. }
  2332. result += segmentDurationWithParts(playlist, segment);
  2333. if (typeof segment.end !== 'undefined') {
  2334. return {
  2335. result: segment.end - result,
  2336. precise: true
  2337. };
  2338. }
  2339. } // indicate we didn't find a useful duration estimate
  2340. return {
  2341. result: -1,
  2342. precise: false
  2343. };
  2344. };
  2345. /**
  2346. * Calculate the media duration from the segments associated with a
  2347. * playlist. The duration of a subinterval of the available segments
  2348. * may be calculated by specifying an end index.
  2349. *
  2350. * @param {Object} playlist a media playlist object
  2351. * @param {number=} endSequence an exclusive upper boundary
  2352. * for the playlist. Defaults to playlist length.
  2353. * @param {number} expired the amount of time that has dropped
  2354. * off the front of the playlist in a live scenario
  2355. * @return {number} the duration between the first available segment
  2356. * and end index.
  2357. */
  2358. const intervalDuration = function (playlist, endSequence, expired) {
  2359. if (typeof endSequence === 'undefined') {
  2360. endSequence = playlist.mediaSequence + playlist.segments.length;
  2361. }
  2362. if (endSequence < playlist.mediaSequence) {
  2363. return 0;
  2364. } // do a backward walk to estimate the duration
  2365. const backward = backwardDuration(playlist, endSequence);
  2366. if (backward.precise) {
  2367. // if we were able to base our duration estimate on timing
  2368. // information provided directly from the Media Source, return
  2369. // it
  2370. return backward.result;
  2371. } // walk forward to see if a precise duration estimate can be made
  2372. // that way
  2373. const forward = forwardDuration(playlist, endSequence);
  2374. if (forward.precise) {
  2375. // we found a segment that has been buffered and so it's
  2376. // position is known precisely
  2377. return forward.result;
  2378. } // return the less-precise, playlist-based duration estimate
  2379. return backward.result + expired;
  2380. };
  2381. /**
  2382. * Calculates the duration of a playlist. If a start and end index
  2383. * are specified, the duration will be for the subset of the media
  2384. * timeline between those two indices. The total duration for live
  2385. * playlists is always Infinity.
  2386. *
  2387. * @param {Object} playlist a media playlist object
  2388. * @param {number=} endSequence an exclusive upper
  2389. * boundary for the playlist. Defaults to the playlist media
  2390. * sequence number plus its length.
  2391. * @param {number=} expired the amount of time that has
  2392. * dropped off the front of the playlist in a live scenario
  2393. * @return {number} the duration between the start index and end
  2394. * index.
  2395. */
  2396. const duration = function (playlist, endSequence, expired) {
  2397. if (!playlist) {
  2398. return 0;
  2399. }
  2400. if (typeof expired !== 'number') {
  2401. expired = 0;
  2402. } // if a slice of the total duration is not requested, use
  2403. // playlist-level duration indicators when they're present
  2404. if (typeof endSequence === 'undefined') {
  2405. // if present, use the duration specified in the playlist
  2406. if (playlist.totalDuration) {
  2407. return playlist.totalDuration;
  2408. } // duration should be Infinity for live playlists
  2409. if (!playlist.endList) {
  2410. return window.Infinity;
  2411. }
  2412. } // calculate the total duration based on the segment durations
  2413. return intervalDuration(playlist, endSequence, expired);
  2414. };
  2415. /**
  2416. * Calculate the time between two indexes in the current playlist
  2417. * neight the start- nor the end-index need to be within the current
  2418. * playlist in which case, the targetDuration of the playlist is used
  2419. * to approximate the durations of the segments
  2420. *
  2421. * @param {Array} options.durationList list to iterate over for durations.
  2422. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  2423. * @param {number} options.startIndex partsAndSegments index to start
  2424. * @param {number} options.endIndex partsAndSegments index to end.
  2425. * @return {number} the number of seconds between startIndex and endIndex
  2426. */
  2427. const sumDurations = function ({
  2428. defaultDuration,
  2429. durationList,
  2430. startIndex,
  2431. endIndex
  2432. }) {
  2433. let durations = 0;
  2434. if (startIndex > endIndex) {
  2435. [startIndex, endIndex] = [endIndex, startIndex];
  2436. }
  2437. if (startIndex < 0) {
  2438. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  2439. durations += defaultDuration;
  2440. }
  2441. startIndex = 0;
  2442. }
  2443. for (let i = startIndex; i < endIndex; i++) {
  2444. durations += durationList[i].duration;
  2445. }
  2446. return durations;
  2447. };
  2448. /**
  2449. * Calculates the playlist end time
  2450. *
  2451. * @param {Object} playlist a media playlist object
  2452. * @param {number=} expired the amount of time that has
  2453. * dropped off the front of the playlist in a live scenario
  2454. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  2455. * playlist end calculation should consider the safe live end
  2456. * (truncate the playlist end by three segments). This is normally
  2457. * used for calculating the end of the playlist's seekable range.
  2458. * This takes into account the value of liveEdgePadding.
  2459. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  2460. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  2461. * If this is provided, it is used in the safe live end calculation.
  2462. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  2463. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2464. * @return {number} the end time of playlist
  2465. * @function playlistEnd
  2466. */
  2467. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  2468. if (!playlist || !playlist.segments) {
  2469. return null;
  2470. }
  2471. if (playlist.endList) {
  2472. return duration(playlist);
  2473. }
  2474. if (expired === null) {
  2475. return null;
  2476. }
  2477. expired = expired || 0;
  2478. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  2479. if (useSafeLiveEnd) {
  2480. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  2481. lastSegmentEndTime -= liveEdgePadding;
  2482. } // don't return a time less than zero
  2483. return Math.max(0, lastSegmentEndTime);
  2484. };
  2485. /**
  2486. * Calculates the interval of time that is currently seekable in a
  2487. * playlist. The returned time ranges are relative to the earliest
  2488. * moment in the specified playlist that is still available. A full
  2489. * seekable implementation for live streams would need to offset
  2490. * these values by the duration of content that has expired from the
  2491. * stream.
  2492. *
  2493. * @param {Object} playlist a media playlist object
  2494. * dropped off the front of the playlist in a live scenario
  2495. * @param {number=} expired the amount of time that has
  2496. * dropped off the front of the playlist in a live scenario
  2497. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  2498. * Corresponds to suggestedPresentationDelay in DASH manifests.
  2499. * @return {TimeRanges} the periods of time that are valid targets
  2500. * for seeking
  2501. */
  2502. const seekable = function (playlist, expired, liveEdgePadding) {
  2503. const useSafeLiveEnd = true;
  2504. const seekableStart = expired || 0;
  2505. let seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  2506. if (seekableEnd === null) {
  2507. return createTimeRanges();
  2508. } // Clamp seekable end since it can not be less than the seekable start
  2509. if (seekableEnd < seekableStart) {
  2510. seekableEnd = seekableStart;
  2511. }
  2512. return createTimeRanges(seekableStart, seekableEnd);
  2513. };
  2514. /**
  2515. * Determine the index and estimated starting time of the segment that
  2516. * contains a specified playback position in a media playlist.
  2517. *
  2518. * @param {Object} options.playlist the media playlist to query
  2519. * @param {number} options.currentTime The number of seconds since the earliest
  2520. * possible position to determine the containing segment for
  2521. * @param {number} options.startTime the time when the segment/part starts
  2522. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  2523. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  2524. *
  2525. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  2526. */
  2527. const getMediaInfoForTime = function ({
  2528. playlist,
  2529. currentTime,
  2530. startingSegmentIndex,
  2531. startingPartIndex,
  2532. startTime,
  2533. exactManifestTimings
  2534. }) {
  2535. let time = currentTime - startTime;
  2536. const partsAndSegments = getPartsAndSegments(playlist);
  2537. let startIndex = 0;
  2538. for (let i = 0; i < partsAndSegments.length; i++) {
  2539. const partAndSegment = partsAndSegments[i];
  2540. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  2541. continue;
  2542. } // skip this if part index does not match.
  2543. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  2544. continue;
  2545. }
  2546. startIndex = i;
  2547. break;
  2548. }
  2549. if (time < 0) {
  2550. // Walk backward from startIndex in the playlist, adding durations
  2551. // until we find a segment that contains `time` and return it
  2552. if (startIndex > 0) {
  2553. for (let i = startIndex - 1; i >= 0; i--) {
  2554. const partAndSegment = partsAndSegments[i];
  2555. time += partAndSegment.duration;
  2556. if (exactManifestTimings) {
  2557. if (time < 0) {
  2558. continue;
  2559. }
  2560. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  2561. continue;
  2562. }
  2563. return {
  2564. partIndex: partAndSegment.partIndex,
  2565. segmentIndex: partAndSegment.segmentIndex,
  2566. startTime: startTime - sumDurations({
  2567. defaultDuration: playlist.targetDuration,
  2568. durationList: partsAndSegments,
  2569. startIndex,
  2570. endIndex: i
  2571. })
  2572. };
  2573. }
  2574. } // We were unable to find a good segment within the playlist
  2575. // so select the first segment
  2576. return {
  2577. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2578. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2579. startTime: currentTime
  2580. };
  2581. } // When startIndex is negative, we first walk forward to first segment
  2582. // adding target durations. If we "run out of time" before getting to
  2583. // the first segment, return the first segment
  2584. if (startIndex < 0) {
  2585. for (let i = startIndex; i < 0; i++) {
  2586. time -= playlist.targetDuration;
  2587. if (time < 0) {
  2588. return {
  2589. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  2590. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  2591. startTime: currentTime
  2592. };
  2593. }
  2594. }
  2595. startIndex = 0;
  2596. } // Walk forward from startIndex in the playlist, subtracting durations
  2597. // until we find a segment that contains `time` and return it
  2598. for (let i = startIndex; i < partsAndSegments.length; i++) {
  2599. const partAndSegment = partsAndSegments[i];
  2600. time -= partAndSegment.duration;
  2601. const canUseFudgeFactor = partAndSegment.duration > TIME_FUDGE_FACTOR;
  2602. const isExactlyAtTheEnd = time === 0;
  2603. const isExtremelyCloseToTheEnd = canUseFudgeFactor && time + TIME_FUDGE_FACTOR >= 0;
  2604. if (isExactlyAtTheEnd || isExtremelyCloseToTheEnd) {
  2605. // 1) We are exactly at the end of the current segment.
  2606. // 2) We are extremely close to the end of the current segment (The difference is less than 1 / 30).
  2607. // We may encounter this situation when
  2608. // we don't have exact match between segment duration info in the manifest and the actual duration of the segment
  2609. // For example:
  2610. // We appended 3 segments 10 seconds each, meaning we should have 30 sec buffered,
  2611. // but we the actual buffered is 29.99999
  2612. //
  2613. // In both cases:
  2614. // if we passed current time -> it means that we already played current segment
  2615. // if we passed buffered.end -> it means that this segment is already loaded and buffered
  2616. // we should select the next segment if we have one:
  2617. if (i !== partsAndSegments.length - 1) {
  2618. continue;
  2619. }
  2620. }
  2621. if (exactManifestTimings) {
  2622. if (time > 0) {
  2623. continue;
  2624. }
  2625. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  2626. continue;
  2627. }
  2628. return {
  2629. partIndex: partAndSegment.partIndex,
  2630. segmentIndex: partAndSegment.segmentIndex,
  2631. startTime: startTime + sumDurations({
  2632. defaultDuration: playlist.targetDuration,
  2633. durationList: partsAndSegments,
  2634. startIndex,
  2635. endIndex: i
  2636. })
  2637. };
  2638. } // We are out of possible candidates so load the last one...
  2639. return {
  2640. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  2641. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  2642. startTime: currentTime
  2643. };
  2644. };
  2645. /**
  2646. * Check whether the playlist is excluded or not.
  2647. *
  2648. * @param {Object} playlist the media playlist object
  2649. * @return {boolean} whether the playlist is excluded or not
  2650. * @function isExcluded
  2651. */
  2652. const isExcluded = function (playlist) {
  2653. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  2654. };
  2655. /**
  2656. * Check whether the playlist is compatible with current playback configuration or has
  2657. * been excluded permanently for being incompatible.
  2658. *
  2659. * @param {Object} playlist the media playlist object
  2660. * @return {boolean} whether the playlist is incompatible or not
  2661. * @function isIncompatible
  2662. */
  2663. const isIncompatible = function (playlist) {
  2664. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  2665. };
  2666. /**
  2667. * Check whether the playlist is enabled or not.
  2668. *
  2669. * @param {Object} playlist the media playlist object
  2670. * @return {boolean} whether the playlist is enabled or not
  2671. * @function isEnabled
  2672. */
  2673. const isEnabled = function (playlist) {
  2674. const excluded = isExcluded(playlist);
  2675. return !playlist.disabled && !excluded;
  2676. };
  2677. /**
  2678. * Check whether the playlist has been manually disabled through the representations api.
  2679. *
  2680. * @param {Object} playlist the media playlist object
  2681. * @return {boolean} whether the playlist is disabled manually or not
  2682. * @function isDisabled
  2683. */
  2684. const isDisabled = function (playlist) {
  2685. return playlist.disabled;
  2686. };
  2687. /**
  2688. * Returns whether the current playlist is an AES encrypted HLS stream
  2689. *
  2690. * @return {boolean} true if it's an AES encrypted HLS stream
  2691. */
  2692. const isAes = function (media) {
  2693. for (let i = 0; i < media.segments.length; i++) {
  2694. if (media.segments[i].key) {
  2695. return true;
  2696. }
  2697. }
  2698. return false;
  2699. };
  2700. /**
  2701. * Checks if the playlist has a value for the specified attribute
  2702. *
  2703. * @param {string} attr
  2704. * Attribute to check for
  2705. * @param {Object} playlist
  2706. * The media playlist object
  2707. * @return {boolean}
  2708. * Whether the playlist contains a value for the attribute or not
  2709. * @function hasAttribute
  2710. */
  2711. const hasAttribute = function (attr, playlist) {
  2712. return playlist.attributes && playlist.attributes[attr];
  2713. };
  2714. /**
  2715. * Estimates the time required to complete a segment download from the specified playlist
  2716. *
  2717. * @param {number} segmentDuration
  2718. * Duration of requested segment
  2719. * @param {number} bandwidth
  2720. * Current measured bandwidth of the player
  2721. * @param {Object} playlist
  2722. * The media playlist object
  2723. * @param {number=} bytesReceived
  2724. * Number of bytes already received for the request. Defaults to 0
  2725. * @return {number|NaN}
  2726. * The estimated time to request the segment. NaN if bandwidth information for
  2727. * the given playlist is unavailable
  2728. * @function estimateSegmentRequestTime
  2729. */
  2730. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  2731. if (!hasAttribute('BANDWIDTH', playlist)) {
  2732. return NaN;
  2733. }
  2734. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  2735. return (size - bytesReceived * 8) / bandwidth;
  2736. };
  2737. /*
  2738. * Returns whether the current playlist is the lowest rendition
  2739. *
  2740. * @return {Boolean} true if on lowest rendition
  2741. */
  2742. const isLowestEnabledRendition = (main, media) => {
  2743. if (main.playlists.length === 1) {
  2744. return true;
  2745. }
  2746. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  2747. return main.playlists.filter(playlist => {
  2748. if (!isEnabled(playlist)) {
  2749. return false;
  2750. }
  2751. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  2752. }).length === 0;
  2753. };
  2754. const playlistMatch = (a, b) => {
  2755. // both playlits are null
  2756. // or only one playlist is non-null
  2757. // no match
  2758. if (!a && !b || !a && b || a && !b) {
  2759. return false;
  2760. } // playlist objects are the same, match
  2761. if (a === b) {
  2762. return true;
  2763. } // first try to use id as it should be the most
  2764. // accurate
  2765. if (a.id && b.id && a.id === b.id) {
  2766. return true;
  2767. } // next try to use reslovedUri as it should be the
  2768. // second most accurate.
  2769. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  2770. return true;
  2771. } // finally try to use uri as it should be accurate
  2772. // but might miss a few cases for relative uris
  2773. if (a.uri && b.uri && a.uri === b.uri) {
  2774. return true;
  2775. }
  2776. return false;
  2777. };
  2778. const someAudioVariant = function (main, callback) {
  2779. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  2780. let found = false;
  2781. for (const groupName in AUDIO) {
  2782. for (const label in AUDIO[groupName]) {
  2783. found = callback(AUDIO[groupName][label]);
  2784. if (found) {
  2785. break;
  2786. }
  2787. }
  2788. if (found) {
  2789. break;
  2790. }
  2791. }
  2792. return !!found;
  2793. };
  2794. const isAudioOnly = main => {
  2795. // we are audio only if we have no main playlists but do
  2796. // have media group playlists.
  2797. if (!main || !main.playlists || !main.playlists.length) {
  2798. // without audio variants or playlists this
  2799. // is not an audio only main.
  2800. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  2801. return found;
  2802. } // if every playlist has only an audio codec it is audio only
  2803. for (let i = 0; i < main.playlists.length; i++) {
  2804. const playlist = main.playlists[i];
  2805. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  2806. if (CODECS && CODECS.split(',').every(c => isAudioCodec(c))) {
  2807. continue;
  2808. } // playlist is in an audio group it is audio only
  2809. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  2810. if (found) {
  2811. continue;
  2812. } // if we make it here this playlist isn't audio and we
  2813. // are not audio only
  2814. return false;
  2815. } // if we make it past every playlist without returning, then
  2816. // this is an audio only playlist.
  2817. return true;
  2818. }; // exports
  2819. var Playlist = {
  2820. liveEdgeDelay,
  2821. duration,
  2822. seekable,
  2823. getMediaInfoForTime,
  2824. isEnabled,
  2825. isDisabled,
  2826. isExcluded,
  2827. isIncompatible,
  2828. playlistEnd,
  2829. isAes,
  2830. hasAttribute,
  2831. estimateSegmentRequestTime,
  2832. isLowestEnabledRendition,
  2833. isAudioOnly,
  2834. playlistMatch,
  2835. segmentDurationWithParts
  2836. };
  2837. const {
  2838. log
  2839. } = videojs__default["default"];
  2840. const createPlaylistID = (index, uri) => {
  2841. return `${index}-${uri}`;
  2842. }; // default function for creating a group id
  2843. const groupID = (type, group, label) => {
  2844. return `placeholder-uri-${type}-${group}-${label}`;
  2845. };
  2846. /**
  2847. * Parses a given m3u8 playlist
  2848. *
  2849. * @param {Function} [onwarn]
  2850. * a function to call when the parser triggers a warning event.
  2851. * @param {Function} [oninfo]
  2852. * a function to call when the parser triggers an info event.
  2853. * @param {string} manifestString
  2854. * The downloaded manifest string
  2855. * @param {Object[]} [customTagParsers]
  2856. * An array of custom tag parsers for the m3u8-parser instance
  2857. * @param {Object[]} [customTagMappers]
  2858. * An array of custom tag mappers for the m3u8-parser instance
  2859. * @param {boolean} [llhls]
  2860. * Whether to keep ll-hls features in the manifest after parsing.
  2861. * @return {Object}
  2862. * The manifest object
  2863. */
  2864. const parseManifest = ({
  2865. onwarn,
  2866. oninfo,
  2867. manifestString,
  2868. customTagParsers = [],
  2869. customTagMappers = [],
  2870. llhls
  2871. }) => {
  2872. const parser = new Parser();
  2873. if (onwarn) {
  2874. parser.on('warn', onwarn);
  2875. }
  2876. if (oninfo) {
  2877. parser.on('info', oninfo);
  2878. }
  2879. customTagParsers.forEach(customParser => parser.addParser(customParser));
  2880. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  2881. parser.push(manifestString);
  2882. parser.end();
  2883. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  2884. // if we don't want llhls support.
  2885. if (!llhls) {
  2886. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  2887. if (manifest.hasOwnProperty(k)) {
  2888. delete manifest[k];
  2889. }
  2890. });
  2891. if (manifest.segments) {
  2892. manifest.segments.forEach(function (segment) {
  2893. ['parts', 'preloadHints'].forEach(function (k) {
  2894. if (segment.hasOwnProperty(k)) {
  2895. delete segment[k];
  2896. }
  2897. });
  2898. });
  2899. }
  2900. }
  2901. if (!manifest.targetDuration) {
  2902. let targetDuration = 10;
  2903. if (manifest.segments && manifest.segments.length) {
  2904. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  2905. }
  2906. if (onwarn) {
  2907. onwarn({
  2908. message: `manifest has no targetDuration defaulting to ${targetDuration}`
  2909. });
  2910. }
  2911. manifest.targetDuration = targetDuration;
  2912. }
  2913. const parts = getLastParts(manifest);
  2914. if (parts.length && !manifest.partTargetDuration) {
  2915. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  2916. if (onwarn) {
  2917. onwarn({
  2918. message: `manifest has no partTargetDuration defaulting to ${partTargetDuration}`
  2919. });
  2920. 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.');
  2921. }
  2922. manifest.partTargetDuration = partTargetDuration;
  2923. }
  2924. return manifest;
  2925. };
  2926. /**
  2927. * Loops through all supported media groups in main and calls the provided
  2928. * callback for each group
  2929. *
  2930. * @param {Object} main
  2931. * The parsed main manifest object
  2932. * @param {Function} callback
  2933. * Callback to call for each media group
  2934. */
  2935. const forEachMediaGroup$1 = (main, callback) => {
  2936. if (!main.mediaGroups) {
  2937. return;
  2938. }
  2939. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  2940. if (!main.mediaGroups[mediaType]) {
  2941. return;
  2942. }
  2943. for (const groupKey in main.mediaGroups[mediaType]) {
  2944. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  2945. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  2946. callback(mediaProperties, mediaType, groupKey, labelKey);
  2947. }
  2948. }
  2949. });
  2950. };
  2951. /**
  2952. * Adds properties and attributes to the playlist to keep consistent functionality for
  2953. * playlists throughout VHS.
  2954. *
  2955. * @param {Object} config
  2956. * Arguments object
  2957. * @param {Object} config.playlist
  2958. * The media playlist
  2959. * @param {string} [config.uri]
  2960. * The uri to the media playlist (if media playlist is not from within a main
  2961. * playlist)
  2962. * @param {string} id
  2963. * ID to use for the playlist
  2964. */
  2965. const setupMediaPlaylist = ({
  2966. playlist,
  2967. uri,
  2968. id
  2969. }) => {
  2970. playlist.id = id;
  2971. playlist.playlistErrors_ = 0;
  2972. if (uri) {
  2973. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  2974. // playlists do not contain their own source URI, but one is needed for consistency in
  2975. // VHS.
  2976. playlist.uri = uri;
  2977. } // For HLS main playlists, even though certain attributes MUST be defined, the
  2978. // stream may still be played without them.
  2979. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  2980. // manifest.
  2981. //
  2982. // To avoid undefined reference errors through the project, and make the code easier
  2983. // to write/read, add an empty attributes object for these cases.
  2984. playlist.attributes = playlist.attributes || {};
  2985. };
  2986. /**
  2987. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  2988. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  2989. * playlist references to the playlists array.
  2990. *
  2991. * @param {Object} main
  2992. * The main playlist
  2993. */
  2994. const setupMediaPlaylists = main => {
  2995. let i = main.playlists.length;
  2996. while (i--) {
  2997. const playlist = main.playlists[i];
  2998. setupMediaPlaylist({
  2999. playlist,
  3000. id: createPlaylistID(i, playlist.uri)
  3001. });
  3002. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  3003. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  3004. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  3005. // the stream can be played without it. Although an attributes property may have been
  3006. // added to the playlist to prevent undefined references, issue a warning to fix the
  3007. // manifest.
  3008. if (!playlist.attributes.BANDWIDTH) {
  3009. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  3010. }
  3011. }
  3012. };
  3013. /**
  3014. * Adds resolvedUri properties to each media group.
  3015. *
  3016. * @param {Object} main
  3017. * The main playlist
  3018. */
  3019. const resolveMediaGroupUris = main => {
  3020. forEachMediaGroup$1(main, properties => {
  3021. if (properties.uri) {
  3022. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  3023. }
  3024. });
  3025. };
  3026. /**
  3027. * Creates a main playlist wrapper to insert a sole media playlist into.
  3028. *
  3029. * @param {Object} media
  3030. * Media playlist
  3031. * @param {string} uri
  3032. * The media URI
  3033. *
  3034. * @return {Object}
  3035. * main playlist
  3036. */
  3037. const mainForMedia = (media, uri) => {
  3038. const id = createPlaylistID(0, uri);
  3039. const main = {
  3040. mediaGroups: {
  3041. 'AUDIO': {},
  3042. 'VIDEO': {},
  3043. 'CLOSED-CAPTIONS': {},
  3044. 'SUBTITLES': {}
  3045. },
  3046. uri: window.location.href,
  3047. resolvedUri: window.location.href,
  3048. playlists: [{
  3049. uri,
  3050. id,
  3051. resolvedUri: uri,
  3052. // m3u8-parser does not attach an attributes property to media playlists so make
  3053. // sure that the property is attached to avoid undefined reference errors
  3054. attributes: {}
  3055. }]
  3056. }; // set up ID reference
  3057. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  3058. main.playlists[uri] = main.playlists[0];
  3059. return main;
  3060. };
  3061. /**
  3062. * Does an in-place update of the main manifest to add updated playlist URI references
  3063. * as well as other properties needed by VHS that aren't included by the parser.
  3064. *
  3065. * @param {Object} main
  3066. * main manifest object
  3067. * @param {string} uri
  3068. * The source URI
  3069. * @param {function} createGroupID
  3070. * A function to determine how to create the groupID for mediaGroups
  3071. */
  3072. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  3073. main.uri = uri;
  3074. for (let i = 0; i < main.playlists.length; i++) {
  3075. if (!main.playlists[i].uri) {
  3076. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  3077. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  3078. // TODO: consider adding dummy URIs in mpd-parser
  3079. const phonyUri = `placeholder-uri-${i}`;
  3080. main.playlists[i].uri = phonyUri;
  3081. }
  3082. }
  3083. const audioOnlyMain = isAudioOnly(main);
  3084. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  3085. // add a playlist array under properties
  3086. if (!properties.playlists || !properties.playlists.length) {
  3087. // If the manifest is audio only and this media group does not have a uri, check
  3088. // if the media group is located in the main list of playlists. If it is, don't add
  3089. // placeholder properties as it shouldn't be considered an alternate audio track.
  3090. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  3091. for (let i = 0; i < main.playlists.length; i++) {
  3092. const p = main.playlists[i];
  3093. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  3094. return;
  3095. }
  3096. }
  3097. }
  3098. properties.playlists = [_extends({}, properties)];
  3099. }
  3100. properties.playlists.forEach(function (p, i) {
  3101. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  3102. const id = createPlaylistID(i, groupId);
  3103. if (p.uri) {
  3104. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  3105. } else {
  3106. // DEPRECATED, this has been added to prevent a breaking change.
  3107. // previously we only ever had a single media group playlist, so
  3108. // we mark the first playlist uri without prepending the index as we used to
  3109. // ideally we would do all of the playlists the same way.
  3110. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  3111. // the placeholder again
  3112. p.resolvedUri = p.uri;
  3113. }
  3114. p.id = p.id || id; // add an empty attributes object, all playlists are
  3115. // expected to have this.
  3116. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  3117. main.playlists[p.id] = p;
  3118. main.playlists[p.uri] = p;
  3119. });
  3120. });
  3121. setupMediaPlaylists(main);
  3122. resolveMediaGroupUris(main);
  3123. };
  3124. class DateRangesStorage {
  3125. constructor() {
  3126. this.offset_ = null;
  3127. this.pendingDateRanges_ = new Map();
  3128. this.processedDateRanges_ = new Map();
  3129. }
  3130. setOffset(segments = []) {
  3131. // already set
  3132. if (this.offset_ !== null) {
  3133. return;
  3134. } // no segment to process
  3135. if (!segments.length) {
  3136. return;
  3137. }
  3138. const [firstSegment] = segments; // no program date time
  3139. if (firstSegment.programDateTime === undefined) {
  3140. return;
  3141. } // Set offset as ProgramDateTime for the very first segment of the very first playlist load:
  3142. this.offset_ = firstSegment.programDateTime / 1000;
  3143. }
  3144. setPendingDateRanges(dateRanges = []) {
  3145. if (!dateRanges.length) {
  3146. return;
  3147. }
  3148. const [dateRange] = dateRanges;
  3149. const startTime = dateRange.startDate.getTime();
  3150. this.trimProcessedDateRanges_(startTime);
  3151. this.pendingDateRanges_ = dateRanges.reduce((map, pendingDateRange) => {
  3152. map.set(pendingDateRange.id, pendingDateRange);
  3153. return map;
  3154. }, new Map());
  3155. }
  3156. processDateRange(dateRange) {
  3157. this.pendingDateRanges_.delete(dateRange.id);
  3158. this.processedDateRanges_.set(dateRange.id, dateRange);
  3159. }
  3160. getDateRangesToProcess() {
  3161. if (this.offset_ === null) {
  3162. return [];
  3163. }
  3164. const dateRangeClasses = {};
  3165. const dateRangesToProcess = [];
  3166. this.pendingDateRanges_.forEach((dateRange, id) => {
  3167. if (this.processedDateRanges_.has(id)) {
  3168. return;
  3169. }
  3170. dateRange.startTime = dateRange.startDate.getTime() / 1000 - this.offset_;
  3171. dateRange.processDateRange = () => this.processDateRange(dateRange);
  3172. dateRangesToProcess.push(dateRange);
  3173. if (!dateRange.class) {
  3174. return;
  3175. }
  3176. if (dateRangeClasses[dateRange.class]) {
  3177. const length = dateRangeClasses[dateRange.class].push(dateRange);
  3178. dateRange.classListIndex = length - 1;
  3179. } else {
  3180. dateRangeClasses[dateRange.class] = [dateRange];
  3181. dateRange.classListIndex = 0;
  3182. }
  3183. });
  3184. for (const dateRange of dateRangesToProcess) {
  3185. const classList = dateRangeClasses[dateRange.class] || [];
  3186. if (dateRange.endDate) {
  3187. dateRange.endTime = dateRange.endDate.getTime() / 1000 - this.offset_;
  3188. } else if (dateRange.endOnNext && classList[dateRange.classListIndex + 1]) {
  3189. dateRange.endTime = classList[dateRange.classListIndex + 1].startTime;
  3190. } else if (dateRange.duration) {
  3191. dateRange.endTime = dateRange.startTime + dateRange.duration;
  3192. } else if (dateRange.plannedDuration) {
  3193. dateRange.endTime = dateRange.startTime + dateRange.plannedDuration;
  3194. } else {
  3195. dateRange.endTime = dateRange.startTime;
  3196. }
  3197. }
  3198. return dateRangesToProcess;
  3199. }
  3200. trimProcessedDateRanges_(startTime) {
  3201. const copy = new Map(this.processedDateRanges_);
  3202. copy.forEach((dateRange, id) => {
  3203. if (dateRange.startDate.getTime() < startTime) {
  3204. this.processedDateRanges_.delete(id);
  3205. }
  3206. });
  3207. }
  3208. }
  3209. const {
  3210. EventTarget: EventTarget$1
  3211. } = videojs__default["default"];
  3212. const addLLHLSQueryDirectives = (uri, media) => {
  3213. if (media.endList || !media.serverControl) {
  3214. return uri;
  3215. }
  3216. const parameters = {};
  3217. if (media.serverControl.canBlockReload) {
  3218. const {
  3219. preloadSegment
  3220. } = media; // next msn is a zero based value, length is not.
  3221. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  3222. // that we are going to request a part of that preload segment.
  3223. // the logic below is used to determine that.
  3224. if (preloadSegment) {
  3225. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  3226. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  3227. // length of parts, then we know we had part preload hints
  3228. // and we need to add the _HLS_part= query
  3229. if (nextPart > -1 && nextPart !== parts.length - 1) {
  3230. // add existing parts to our preload hints
  3231. // eslint-disable-next-line
  3232. parameters._HLS_part = nextPart;
  3233. } // this if statement makes sure that we request the msn
  3234. // of the preload segment if:
  3235. // 1. the preload segment had parts (and was not yet a full segment)
  3236. // but was added to our segments array
  3237. // 2. the preload segment had preload hints for parts that are not in
  3238. // the manifest yet.
  3239. // in all other cases we want the segment after the preload segment
  3240. // which will be given by using media.segments.length because it is 1 based
  3241. // rather than 0 based.
  3242. if (nextPart > -1 || parts.length) {
  3243. nextMSN--;
  3244. }
  3245. } // add _HLS_msn= in front of any _HLS_part query
  3246. // eslint-disable-next-line
  3247. parameters._HLS_msn = nextMSN;
  3248. }
  3249. if (media.serverControl && media.serverControl.canSkipUntil) {
  3250. // add _HLS_skip= infront of all other queries.
  3251. // eslint-disable-next-line
  3252. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  3253. }
  3254. if (Object.keys(parameters).length) {
  3255. const parsedUri = new window.URL(uri);
  3256. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  3257. if (!parameters.hasOwnProperty(name)) {
  3258. return;
  3259. }
  3260. parsedUri.searchParams.set(name, parameters[name]);
  3261. });
  3262. uri = parsedUri.toString();
  3263. }
  3264. return uri;
  3265. };
  3266. /**
  3267. * Returns a new segment object with properties and
  3268. * the parts array merged.
  3269. *
  3270. * @param {Object} a the old segment
  3271. * @param {Object} b the new segment
  3272. *
  3273. * @return {Object} the merged segment
  3274. */
  3275. const updateSegment = (a, b) => {
  3276. if (!a) {
  3277. return b;
  3278. }
  3279. const result = merge$1(a, b); // if only the old segment has preload hints
  3280. // and the new one does not, remove preload hints.
  3281. if (a.preloadHints && !b.preloadHints) {
  3282. delete result.preloadHints;
  3283. } // if only the old segment has parts
  3284. // then the parts are no longer valid
  3285. if (a.parts && !b.parts) {
  3286. delete result.parts; // if both segments have parts
  3287. // copy part propeties from the old segment
  3288. // to the new one.
  3289. } else if (a.parts && b.parts) {
  3290. for (let i = 0; i < b.parts.length; i++) {
  3291. if (a.parts && a.parts[i]) {
  3292. result.parts[i] = merge$1(a.parts[i], b.parts[i]);
  3293. }
  3294. }
  3295. } // set skipped to false for segments that have
  3296. // have had information merged from the old segment.
  3297. if (!a.skipped && b.skipped) {
  3298. result.skipped = false;
  3299. } // set preload to false for segments that have
  3300. // had information added in the new segment.
  3301. if (a.preload && !b.preload) {
  3302. result.preload = false;
  3303. }
  3304. return result;
  3305. };
  3306. /**
  3307. * Returns a new array of segments that is the result of merging
  3308. * properties from an older list of segments onto an updated
  3309. * list. No properties on the updated playlist will be ovewritten.
  3310. *
  3311. * @param {Array} original the outdated list of segments
  3312. * @param {Array} update the updated list of segments
  3313. * @param {number=} offset the index of the first update
  3314. * segment in the original segment list. For non-live playlists,
  3315. * this should always be zero and does not need to be
  3316. * specified. For live playlists, it should be the difference
  3317. * between the media sequence numbers in the original and updated
  3318. * playlists.
  3319. * @return {Array} a list of merged segment objects
  3320. */
  3321. const updateSegments = (original, update, offset) => {
  3322. const oldSegments = original.slice();
  3323. const newSegments = update.slice();
  3324. offset = offset || 0;
  3325. const result = [];
  3326. let currentMap;
  3327. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  3328. const oldSegment = oldSegments[newIndex + offset];
  3329. const newSegment = newSegments[newIndex];
  3330. if (oldSegment) {
  3331. currentMap = oldSegment.map || currentMap;
  3332. result.push(updateSegment(oldSegment, newSegment));
  3333. } else {
  3334. // carry over map to new segment if it is missing
  3335. if (currentMap && !newSegment.map) {
  3336. newSegment.map = currentMap;
  3337. }
  3338. result.push(newSegment);
  3339. }
  3340. }
  3341. return result;
  3342. };
  3343. const resolveSegmentUris = (segment, baseUri) => {
  3344. // preloadSegment will not have a uri at all
  3345. // as the segment isn't actually in the manifest yet, only parts
  3346. if (!segment.resolvedUri && segment.uri) {
  3347. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  3348. }
  3349. if (segment.key && !segment.key.resolvedUri) {
  3350. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  3351. }
  3352. if (segment.map && !segment.map.resolvedUri) {
  3353. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  3354. }
  3355. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  3356. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  3357. }
  3358. if (segment.parts && segment.parts.length) {
  3359. segment.parts.forEach(p => {
  3360. if (p.resolvedUri) {
  3361. return;
  3362. }
  3363. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3364. });
  3365. }
  3366. if (segment.preloadHints && segment.preloadHints.length) {
  3367. segment.preloadHints.forEach(p => {
  3368. if (p.resolvedUri) {
  3369. return;
  3370. }
  3371. p.resolvedUri = resolveUrl(baseUri, p.uri);
  3372. });
  3373. }
  3374. };
  3375. const getAllSegments = function (media) {
  3376. const segments = media.segments || [];
  3377. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  3378. // a usable segment, only include a preloadSegment that has
  3379. // parts.
  3380. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  3381. // if preloadHints has a MAP that means that the
  3382. // init segment is going to change. We cannot use any of the parts
  3383. // from this preload segment.
  3384. if (preloadSegment.preloadHints) {
  3385. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  3386. if (preloadSegment.preloadHints[i].type === 'MAP') {
  3387. return segments;
  3388. }
  3389. }
  3390. } // set the duration for our preload segment to target duration.
  3391. preloadSegment.duration = media.targetDuration;
  3392. preloadSegment.preload = true;
  3393. segments.push(preloadSegment);
  3394. }
  3395. return segments;
  3396. }; // consider the playlist unchanged if the playlist object is the same or
  3397. // the number of segments is equal, the media sequence number is unchanged,
  3398. // and this playlist hasn't become the end of the playlist
  3399. 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;
  3400. /**
  3401. * Returns a new main playlist that is the result of merging an
  3402. * updated media playlist into the original version. If the
  3403. * updated media playlist does not match any of the playlist
  3404. * entries in the original main playlist, null is returned.
  3405. *
  3406. * @param {Object} main a parsed main M3U8 object
  3407. * @param {Object} media a parsed media M3U8 object
  3408. * @return {Object} a new object that represents the original
  3409. * main playlist with the updated media playlist merged in, or
  3410. * null if the merge produced no change.
  3411. */
  3412. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  3413. const result = merge$1(main, {});
  3414. const oldMedia = result.playlists[newMedia.id];
  3415. if (!oldMedia) {
  3416. return null;
  3417. }
  3418. if (unchangedCheck(oldMedia, newMedia)) {
  3419. return null;
  3420. }
  3421. newMedia.segments = getAllSegments(newMedia);
  3422. const mergedPlaylist = merge$1(oldMedia, newMedia); // always use the new media's preload segment
  3423. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  3424. delete mergedPlaylist.preloadSegment;
  3425. } // if the update could overlap existing segment information, merge the two segment lists
  3426. if (oldMedia.segments) {
  3427. if (newMedia.skip) {
  3428. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  3429. // old properties into the new segments
  3430. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  3431. newMedia.segments.unshift({
  3432. skipped: true
  3433. });
  3434. }
  3435. }
  3436. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  3437. } // resolve any segment URIs to prevent us from having to do it later
  3438. mergedPlaylist.segments.forEach(segment => {
  3439. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  3440. }); // TODO Right now in the playlists array there are two references to each playlist, one
  3441. // that is referenced by index, and one by URI. The index reference may no longer be
  3442. // necessary.
  3443. for (let i = 0; i < result.playlists.length; i++) {
  3444. if (result.playlists[i].id === newMedia.id) {
  3445. result.playlists[i] = mergedPlaylist;
  3446. }
  3447. }
  3448. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  3449. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  3450. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  3451. if (!properties.playlists) {
  3452. return;
  3453. }
  3454. for (let i = 0; i < properties.playlists.length; i++) {
  3455. if (newMedia.id === properties.playlists[i].id) {
  3456. properties.playlists[i] = mergedPlaylist;
  3457. }
  3458. }
  3459. });
  3460. return result;
  3461. };
  3462. /**
  3463. * Calculates the time to wait before refreshing a live playlist
  3464. *
  3465. * @param {Object} media
  3466. * The current media
  3467. * @param {boolean} update
  3468. * True if there were any updates from the last refresh, false otherwise
  3469. * @return {number}
  3470. * The time in ms to wait before refreshing the live playlist
  3471. */
  3472. const refreshDelay = (media, update) => {
  3473. const segments = media.segments || [];
  3474. const lastSegment = segments[segments.length - 1];
  3475. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  3476. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  3477. if (update && lastDuration) {
  3478. return lastDuration * 1000;
  3479. } // if the playlist is unchanged since the last reload or last segment duration
  3480. // cannot be determined, try again after half the target duration
  3481. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  3482. };
  3483. /**
  3484. * Load a playlist from a remote location
  3485. *
  3486. * @class PlaylistLoader
  3487. * @extends Stream
  3488. * @param {string|Object} src url or object of manifest
  3489. * @param {boolean} withCredentials the withCredentials xhr option
  3490. * @class
  3491. */
  3492. class PlaylistLoader extends EventTarget$1 {
  3493. constructor(src, vhs, options = {}) {
  3494. super();
  3495. if (!src) {
  3496. throw new Error('A non-empty playlist URL or object is required');
  3497. }
  3498. this.logger_ = logger('PlaylistLoader');
  3499. const {
  3500. withCredentials = false
  3501. } = options;
  3502. this.src = src;
  3503. this.vhs_ = vhs;
  3504. this.withCredentials = withCredentials;
  3505. this.addDateRangesToTextTrack_ = options.addDateRangesToTextTrack;
  3506. const vhsOptions = vhs.options_;
  3507. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  3508. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  3509. this.llhls = vhsOptions && vhsOptions.llhls;
  3510. this.dateRangesStorage_ = new DateRangesStorage(); // initialize the loader state
  3511. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  3512. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  3513. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  3514. this.on('loadedplaylist', this.handleLoadedPlaylist_.bind(this));
  3515. }
  3516. handleLoadedPlaylist_() {
  3517. const mediaPlaylist = this.media();
  3518. if (!mediaPlaylist) {
  3519. return;
  3520. }
  3521. this.dateRangesStorage_.setOffset(mediaPlaylist.segments);
  3522. this.dateRangesStorage_.setPendingDateRanges(mediaPlaylist.dateRanges);
  3523. const availableDateRanges = this.dateRangesStorage_.getDateRangesToProcess();
  3524. if (!availableDateRanges.length || !this.addDateRangesToTextTrack_) {
  3525. return;
  3526. }
  3527. this.addDateRangesToTextTrack_(availableDateRanges);
  3528. }
  3529. handleMediaupdatetimeout_() {
  3530. if (this.state !== 'HAVE_METADATA') {
  3531. // only refresh the media playlist if no other activity is going on
  3532. return;
  3533. }
  3534. const media = this.media();
  3535. let uri = resolveUrl(this.main.uri, media.uri);
  3536. if (this.llhls) {
  3537. uri = addLLHLSQueryDirectives(uri, media);
  3538. }
  3539. this.state = 'HAVE_CURRENT_METADATA';
  3540. this.request = this.vhs_.xhr({
  3541. uri,
  3542. withCredentials: this.withCredentials
  3543. }, (error, req) => {
  3544. // disposed
  3545. if (!this.request) {
  3546. return;
  3547. }
  3548. if (error) {
  3549. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  3550. }
  3551. this.haveMetadata({
  3552. playlistString: this.request.responseText,
  3553. url: this.media().uri,
  3554. id: this.media().id
  3555. });
  3556. });
  3557. }
  3558. playlistRequestError(xhr, playlist, startingState) {
  3559. const {
  3560. uri,
  3561. id
  3562. } = playlist; // any in-flight request is now finished
  3563. this.request = null;
  3564. if (startingState) {
  3565. this.state = startingState;
  3566. }
  3567. this.error = {
  3568. playlist: this.main.playlists[id],
  3569. status: xhr.status,
  3570. message: `HLS playlist request error at URL: ${uri}.`,
  3571. responseText: xhr.responseText,
  3572. code: xhr.status >= 500 ? 4 : 2
  3573. };
  3574. this.trigger('error');
  3575. }
  3576. parseManifest_({
  3577. url,
  3578. manifestString
  3579. }) {
  3580. return parseManifest({
  3581. onwarn: ({
  3582. message
  3583. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  3584. oninfo: ({
  3585. message
  3586. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  3587. manifestString,
  3588. customTagParsers: this.customTagParsers,
  3589. customTagMappers: this.customTagMappers,
  3590. llhls: this.llhls
  3591. });
  3592. }
  3593. /**
  3594. * Update the playlist loader's state in response to a new or updated playlist.
  3595. *
  3596. * @param {string} [playlistString]
  3597. * Playlist string (if playlistObject is not provided)
  3598. * @param {Object} [playlistObject]
  3599. * Playlist object (if playlistString is not provided)
  3600. * @param {string} url
  3601. * URL of playlist
  3602. * @param {string} id
  3603. * ID to use for playlist
  3604. */
  3605. haveMetadata({
  3606. playlistString,
  3607. playlistObject,
  3608. url,
  3609. id
  3610. }) {
  3611. // any in-flight request is now finished
  3612. this.request = null;
  3613. this.state = 'HAVE_METADATA';
  3614. const playlist = playlistObject || this.parseManifest_({
  3615. url,
  3616. manifestString: playlistString
  3617. });
  3618. playlist.lastRequest = Date.now();
  3619. setupMediaPlaylist({
  3620. playlist,
  3621. uri: url,
  3622. id
  3623. }); // merge this playlist into the main manifest
  3624. const update = updateMain$1(this.main, playlist);
  3625. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  3626. this.pendingMedia_ = null;
  3627. if (update) {
  3628. this.main = update;
  3629. this.media_ = this.main.playlists[id];
  3630. } else {
  3631. this.trigger('playlistunchanged');
  3632. }
  3633. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  3634. this.trigger('loadedplaylist');
  3635. }
  3636. /**
  3637. * Abort any outstanding work and clean up.
  3638. */
  3639. dispose() {
  3640. this.trigger('dispose');
  3641. this.stopRequest();
  3642. window.clearTimeout(this.mediaUpdateTimeout);
  3643. window.clearTimeout(this.finalRenditionTimeout);
  3644. this.dateRangesStorage_ = new DateRangesStorage();
  3645. this.off();
  3646. }
  3647. stopRequest() {
  3648. if (this.request) {
  3649. const oldRequest = this.request;
  3650. this.request = null;
  3651. oldRequest.onreadystatechange = null;
  3652. oldRequest.abort();
  3653. }
  3654. }
  3655. /**
  3656. * When called without any arguments, returns the currently
  3657. * active media playlist. When called with a single argument,
  3658. * triggers the playlist loader to asynchronously switch to the
  3659. * specified media playlist. Calling this method while the
  3660. * loader is in the HAVE_NOTHING causes an error to be emitted
  3661. * but otherwise has no effect.
  3662. *
  3663. * @param {Object=} playlist the parsed media playlist
  3664. * object to switch to
  3665. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  3666. *
  3667. * @return {Playlist} the current loaded media
  3668. */
  3669. media(playlist, shouldDelay) {
  3670. // getter
  3671. if (!playlist) {
  3672. return this.media_;
  3673. } // setter
  3674. if (this.state === 'HAVE_NOTHING') {
  3675. throw new Error('Cannot switch media playlist from ' + this.state);
  3676. } // find the playlist object if the target playlist has been
  3677. // specified by URI
  3678. if (typeof playlist === 'string') {
  3679. if (!this.main.playlists[playlist]) {
  3680. throw new Error('Unknown playlist URI: ' + playlist);
  3681. }
  3682. playlist = this.main.playlists[playlist];
  3683. }
  3684. window.clearTimeout(this.finalRenditionTimeout);
  3685. if (shouldDelay) {
  3686. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  3687. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  3688. return;
  3689. }
  3690. const startingState = this.state;
  3691. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  3692. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  3693. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  3694. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  3695. playlist.endList && playlist.segments.length) {
  3696. // abort outstanding playlist requests
  3697. if (this.request) {
  3698. this.request.onreadystatechange = null;
  3699. this.request.abort();
  3700. this.request = null;
  3701. }
  3702. this.state = 'HAVE_METADATA';
  3703. this.media_ = playlist; // trigger media change if the active media has been updated
  3704. if (mediaChange) {
  3705. this.trigger('mediachanging');
  3706. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3707. // The initial playlist was a main manifest, and the first media selected was
  3708. // also provided (in the form of a resolved playlist object) as part of the
  3709. // source object (rather than just a URL). Therefore, since the media playlist
  3710. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  3711. // normal flow, and needs an explicit trigger here.
  3712. this.trigger('loadedmetadata');
  3713. } else {
  3714. this.trigger('mediachange');
  3715. }
  3716. }
  3717. return;
  3718. } // We update/set the timeout here so that live playlists
  3719. // that are not a media change will "start" the loader as expected.
  3720. // We expect that this function will start the media update timeout
  3721. // cycle again. This also prevents a playlist switch failure from
  3722. // causing us to stall during live.
  3723. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  3724. if (!mediaChange) {
  3725. return;
  3726. }
  3727. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  3728. if (this.request) {
  3729. if (playlist.resolvedUri === this.request.url) {
  3730. // requesting to switch to the same playlist multiple times
  3731. // has no effect after the first
  3732. return;
  3733. }
  3734. this.request.onreadystatechange = null;
  3735. this.request.abort();
  3736. this.request = null;
  3737. } // request the new playlist
  3738. if (this.media_) {
  3739. this.trigger('mediachanging');
  3740. }
  3741. this.pendingMedia_ = playlist;
  3742. this.request = this.vhs_.xhr({
  3743. uri: playlist.resolvedUri,
  3744. withCredentials: this.withCredentials
  3745. }, (error, req) => {
  3746. // disposed
  3747. if (!this.request) {
  3748. return;
  3749. }
  3750. playlist.lastRequest = Date.now();
  3751. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  3752. if (error) {
  3753. return this.playlistRequestError(this.request, playlist, startingState);
  3754. }
  3755. this.haveMetadata({
  3756. playlistString: req.responseText,
  3757. url: playlist.uri,
  3758. id: playlist.id
  3759. }); // fire loadedmetadata the first time a media playlist is loaded
  3760. if (startingState === 'HAVE_MAIN_MANIFEST') {
  3761. this.trigger('loadedmetadata');
  3762. } else {
  3763. this.trigger('mediachange');
  3764. }
  3765. });
  3766. }
  3767. /**
  3768. * pause loading of the playlist
  3769. */
  3770. pause() {
  3771. if (this.mediaUpdateTimeout) {
  3772. window.clearTimeout(this.mediaUpdateTimeout);
  3773. this.mediaUpdateTimeout = null;
  3774. }
  3775. this.stopRequest();
  3776. if (this.state === 'HAVE_NOTHING') {
  3777. // If we pause the loader before any data has been retrieved, its as if we never
  3778. // started, so reset to an unstarted state.
  3779. this.started = false;
  3780. } // Need to restore state now that no activity is happening
  3781. if (this.state === 'SWITCHING_MEDIA') {
  3782. // if the loader was in the process of switching media, it should either return to
  3783. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  3784. // playlist yet. This is determined by the existence of loader.media_
  3785. if (this.media_) {
  3786. this.state = 'HAVE_METADATA';
  3787. } else {
  3788. this.state = 'HAVE_MAIN_MANIFEST';
  3789. }
  3790. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  3791. this.state = 'HAVE_METADATA';
  3792. }
  3793. }
  3794. /**
  3795. * start loading of the playlist
  3796. */
  3797. load(shouldDelay) {
  3798. if (this.mediaUpdateTimeout) {
  3799. window.clearTimeout(this.mediaUpdateTimeout);
  3800. this.mediaUpdateTimeout = null;
  3801. }
  3802. const media = this.media();
  3803. if (shouldDelay) {
  3804. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  3805. this.mediaUpdateTimeout = window.setTimeout(() => {
  3806. this.mediaUpdateTimeout = null;
  3807. this.load();
  3808. }, delay);
  3809. return;
  3810. }
  3811. if (!this.started) {
  3812. this.start();
  3813. return;
  3814. }
  3815. if (media && !media.endList) {
  3816. this.trigger('mediaupdatetimeout');
  3817. } else {
  3818. this.trigger('loadedplaylist');
  3819. }
  3820. }
  3821. updateMediaUpdateTimeout_(delay) {
  3822. if (this.mediaUpdateTimeout) {
  3823. window.clearTimeout(this.mediaUpdateTimeout);
  3824. this.mediaUpdateTimeout = null;
  3825. } // we only have use mediaupdatetimeout for live playlists.
  3826. if (!this.media() || this.media().endList) {
  3827. return;
  3828. }
  3829. this.mediaUpdateTimeout = window.setTimeout(() => {
  3830. this.mediaUpdateTimeout = null;
  3831. this.trigger('mediaupdatetimeout');
  3832. this.updateMediaUpdateTimeout_(delay);
  3833. }, delay);
  3834. }
  3835. /**
  3836. * start loading of the playlist
  3837. */
  3838. start() {
  3839. this.started = true;
  3840. if (typeof this.src === 'object') {
  3841. // in the case of an entirely constructed manifest object (meaning there's no actual
  3842. // manifest on a server), default the uri to the page's href
  3843. if (!this.src.uri) {
  3844. this.src.uri = window.location.href;
  3845. } // resolvedUri is added on internally after the initial request. Since there's no
  3846. // request for pre-resolved manifests, add on resolvedUri here.
  3847. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  3848. // request can be skipped (since the top level of the manifest, at a minimum, is
  3849. // already available as a parsed manifest object). However, if the manifest object
  3850. // represents a main playlist, some media playlists may need to be resolved before
  3851. // the starting segment list is available. Therefore, go directly to setup of the
  3852. // initial playlist, and let the normal flow continue from there.
  3853. //
  3854. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  3855. // that the first request is asynchronous.
  3856. setTimeout(() => {
  3857. this.setupInitialPlaylist(this.src);
  3858. }, 0);
  3859. return;
  3860. } // request the specified URL
  3861. this.request = this.vhs_.xhr({
  3862. uri: this.src,
  3863. withCredentials: this.withCredentials
  3864. }, (error, req) => {
  3865. // disposed
  3866. if (!this.request) {
  3867. return;
  3868. } // clear the loader's request reference
  3869. this.request = null;
  3870. if (error) {
  3871. this.error = {
  3872. status: req.status,
  3873. message: `HLS playlist request error at URL: ${this.src}.`,
  3874. responseText: req.responseText,
  3875. // MEDIA_ERR_NETWORK
  3876. code: 2
  3877. };
  3878. if (this.state === 'HAVE_NOTHING') {
  3879. this.started = false;
  3880. }
  3881. return this.trigger('error');
  3882. }
  3883. this.src = resolveManifestRedirect(this.src, req);
  3884. const manifest = this.parseManifest_({
  3885. manifestString: req.responseText,
  3886. url: this.src
  3887. });
  3888. this.setupInitialPlaylist(manifest);
  3889. });
  3890. }
  3891. srcUri() {
  3892. return typeof this.src === 'string' ? this.src : this.src.uri;
  3893. }
  3894. /**
  3895. * Given a manifest object that's either a main or media playlist, trigger the proper
  3896. * events and set the state of the playlist loader.
  3897. *
  3898. * If the manifest object represents a main playlist, `loadedplaylist` will be
  3899. * triggered to allow listeners to select a playlist. If none is selected, the loader
  3900. * will default to the first one in the playlists array.
  3901. *
  3902. * If the manifest object represents a media playlist, `loadedplaylist` will be
  3903. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  3904. *
  3905. * In the case of a media playlist, a main playlist object wrapper with one playlist
  3906. * will be created so that all logic can handle playlists in the same fashion (as an
  3907. * assumed manifest object schema).
  3908. *
  3909. * @param {Object} manifest
  3910. * The parsed manifest object
  3911. */
  3912. setupInitialPlaylist(manifest) {
  3913. this.state = 'HAVE_MAIN_MANIFEST';
  3914. if (manifest.playlists) {
  3915. this.main = manifest;
  3916. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  3917. // then resolve URIs in advance, as they are usually done after a playlist request,
  3918. // which may not happen if the playlist is resolved.
  3919. manifest.playlists.forEach(playlist => {
  3920. playlist.segments = getAllSegments(playlist);
  3921. playlist.segments.forEach(segment => {
  3922. resolveSegmentUris(segment, playlist.resolvedUri);
  3923. });
  3924. });
  3925. this.trigger('loadedplaylist');
  3926. if (!this.request) {
  3927. // no media playlist was specifically selected so start
  3928. // from the first listed one
  3929. this.media(this.main.playlists[0]);
  3930. }
  3931. return;
  3932. } // In order to support media playlists passed in as vhs-json, the case where the uri
  3933. // is not provided as part of the manifest should be considered, and an appropriate
  3934. // default used.
  3935. const uri = this.srcUri() || window.location.href;
  3936. this.main = mainForMedia(manifest, uri);
  3937. this.haveMetadata({
  3938. playlistObject: manifest,
  3939. url: uri,
  3940. id: this.main.playlists[0].id
  3941. });
  3942. this.trigger('loadedmetadata');
  3943. }
  3944. /**
  3945. * Updates or deletes a preexisting pathway clone.
  3946. * Ensures that all playlists related to the old pathway clone are
  3947. * either updated or deleted.
  3948. *
  3949. * @param {Object} clone On update, the pathway clone object for the newly updated pathway clone.
  3950. * On delete, the old pathway clone object to be deleted.
  3951. * @param {boolean} isUpdate True if the pathway is to be updated,
  3952. * false if it is meant to be deleted.
  3953. */
  3954. updateOrDeleteClone(clone, isUpdate) {
  3955. const main = this.main;
  3956. const pathway = clone.ID;
  3957. let i = main.playlists.length; // Iterate backwards through the playlist so we can remove playlists if necessary.
  3958. while (i--) {
  3959. const p = main.playlists[i];
  3960. if (p.attributes['PATHWAY-ID'] === pathway) {
  3961. const oldPlaylistUri = p.resolvedUri;
  3962. const oldPlaylistId = p.id; // update the indexed playlist and add new playlists by ID and URI
  3963. if (isUpdate) {
  3964. const newPlaylistUri = this.createCloneURI_(p.resolvedUri, clone);
  3965. const newPlaylistId = createPlaylistID(pathway, newPlaylistUri);
  3966. const attributes = this.createCloneAttributes_(pathway, p.attributes);
  3967. const updatedPlaylist = this.createClonePlaylist_(p, newPlaylistId, clone, attributes);
  3968. main.playlists[i] = updatedPlaylist;
  3969. main.playlists[newPlaylistId] = updatedPlaylist;
  3970. main.playlists[newPlaylistUri] = updatedPlaylist;
  3971. } else {
  3972. // Remove the indexed playlist.
  3973. main.playlists.splice(i, 1);
  3974. } // Remove playlists by the old ID and URI.
  3975. delete main.playlists[oldPlaylistId];
  3976. delete main.playlists[oldPlaylistUri];
  3977. }
  3978. }
  3979. this.updateOrDeleteCloneMedia(clone, isUpdate);
  3980. }
  3981. /**
  3982. * Updates or deletes media data based on the pathway clone object.
  3983. * Due to the complexity of the media groups and playlists, in all cases
  3984. * we remove all of the old media groups and playlists.
  3985. * On updates, we then create new media groups and playlists based on the
  3986. * new pathway clone object.
  3987. *
  3988. * @param {Object} clone The pathway clone object for the newly updated pathway clone.
  3989. * @param {boolean} isUpdate True if the pathway is to be updated,
  3990. * false if it is meant to be deleted.
  3991. */
  3992. updateOrDeleteCloneMedia(clone, isUpdate) {
  3993. const main = this.main;
  3994. const id = clone.ID;
  3995. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  3996. if (!main.mediaGroups[mediaType] || !main.mediaGroups[mediaType][id]) {
  3997. return;
  3998. }
  3999. for (const groupKey in main.mediaGroups[mediaType]) {
  4000. // Remove all media playlists for the media group for this pathway clone.
  4001. if (groupKey === id) {
  4002. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  4003. const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];
  4004. oldMedia.playlists.forEach((p, i) => {
  4005. const oldMediaPlaylist = main.playlists[p.id];
  4006. const oldPlaylistId = oldMediaPlaylist.id;
  4007. const oldPlaylistUri = oldMediaPlaylist.resolvedUri;
  4008. delete main.playlists[oldPlaylistId];
  4009. delete main.playlists[oldPlaylistUri];
  4010. });
  4011. } // Delete the old media group.
  4012. delete main.mediaGroups[mediaType][groupKey];
  4013. }
  4014. }
  4015. }); // Create the new media groups and playlists if there is an update.
  4016. if (isUpdate) {
  4017. this.createClonedMediaGroups_(clone);
  4018. }
  4019. }
  4020. /**
  4021. * Given a pathway clone object, clones all necessary playlists.
  4022. *
  4023. * @param {Object} clone The pathway clone object.
  4024. * @param {Object} basePlaylist The original playlist to clone from.
  4025. */
  4026. addClonePathway(clone, basePlaylist = {}) {
  4027. const main = this.main;
  4028. const index = main.playlists.length;
  4029. const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);
  4030. const playlistId = createPlaylistID(clone.ID, uri);
  4031. const attributes = this.createCloneAttributes_(clone.ID, basePlaylist.attributes);
  4032. const playlist = this.createClonePlaylist_(basePlaylist, playlistId, clone, attributes);
  4033. main.playlists[index] = playlist; // add playlist by ID and URI
  4034. main.playlists[playlistId] = playlist;
  4035. main.playlists[uri] = playlist;
  4036. this.createClonedMediaGroups_(clone);
  4037. }
  4038. /**
  4039. * Given a pathway clone object we create clones of all media.
  4040. * In this function, all necessary information and updated playlists
  4041. * are added to the `mediaGroup` object.
  4042. * Playlists are also added to the `playlists` array so the media groups
  4043. * will be properly linked.
  4044. *
  4045. * @param {Object} clone The pathway clone object.
  4046. */
  4047. createClonedMediaGroups_(clone) {
  4048. const id = clone.ID;
  4049. const baseID = clone['BASE-ID'];
  4050. const main = this.main;
  4051. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  4052. // If the media type doesn't exist, or there is already a clone, skip
  4053. // to the next media type.
  4054. if (!main.mediaGroups[mediaType] || main.mediaGroups[mediaType][id]) {
  4055. return;
  4056. }
  4057. for (const groupKey in main.mediaGroups[mediaType]) {
  4058. if (groupKey === baseID) {
  4059. // Create the group.
  4060. main.mediaGroups[mediaType][id] = {};
  4061. } else {
  4062. // There is no need to iterate over label keys in this case.
  4063. continue;
  4064. }
  4065. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  4066. const oldMedia = main.mediaGroups[mediaType][groupKey][labelKey];
  4067. main.mediaGroups[mediaType][id][labelKey] = _extends({}, oldMedia);
  4068. const newMedia = main.mediaGroups[mediaType][id][labelKey]; // update URIs on the media
  4069. const newUri = this.createCloneURI_(oldMedia.resolvedUri, clone);
  4070. newMedia.resolvedUri = newUri;
  4071. newMedia.uri = newUri; // Reset playlists in the new media group.
  4072. newMedia.playlists = []; // Create new playlists in the newly cloned media group.
  4073. oldMedia.playlists.forEach((p, i) => {
  4074. const oldMediaPlaylist = main.playlists[p.id];
  4075. const group = groupID(mediaType, id, labelKey);
  4076. const newPlaylistID = createPlaylistID(id, group); // Check to see if it already exists
  4077. if (oldMediaPlaylist && !main.playlists[newPlaylistID]) {
  4078. const newMediaPlaylist = this.createClonePlaylist_(oldMediaPlaylist, newPlaylistID, clone);
  4079. const newPlaylistUri = newMediaPlaylist.resolvedUri;
  4080. main.playlists[newPlaylistID] = newMediaPlaylist;
  4081. main.playlists[newPlaylistUri] = newMediaPlaylist;
  4082. }
  4083. newMedia.playlists[i] = this.createClonePlaylist_(p, newPlaylistID, clone);
  4084. });
  4085. }
  4086. }
  4087. });
  4088. }
  4089. /**
  4090. * Using the original playlist to be cloned, and the pathway clone object
  4091. * information, we create a new playlist.
  4092. *
  4093. * @param {Object} basePlaylist The original playlist to be cloned from.
  4094. * @param {string} id The desired id of the newly cloned playlist.
  4095. * @param {Object} clone The pathway clone object.
  4096. * @param {Object} attributes An optional object to populate the `attributes` property in the playlist.
  4097. *
  4098. * @return {Object} The combined cloned playlist.
  4099. */
  4100. createClonePlaylist_(basePlaylist, id, clone, attributes) {
  4101. const uri = this.createCloneURI_(basePlaylist.resolvedUri, clone);
  4102. const newProps = {
  4103. resolvedUri: uri,
  4104. uri,
  4105. id
  4106. }; // Remove all segments from previous playlist in the clone.
  4107. if (basePlaylist.segments) {
  4108. newProps.segments = [];
  4109. }
  4110. if (attributes) {
  4111. newProps.attributes = attributes;
  4112. }
  4113. return merge$1(basePlaylist, newProps);
  4114. }
  4115. /**
  4116. * Generates an updated URI for a cloned pathway based on the original
  4117. * pathway's URI and the paramaters from the pathway clone object in the
  4118. * content steering server response.
  4119. *
  4120. * @param {string} baseUri URI to be updated in the cloned pathway.
  4121. * @param {Object} clone The pathway clone object.
  4122. *
  4123. * @return {string} The updated URI for the cloned pathway.
  4124. */
  4125. createCloneURI_(baseURI, clone) {
  4126. const uri = new URL(baseURI);
  4127. uri.hostname = clone['URI-REPLACEMENT'].HOST;
  4128. const params = clone['URI-REPLACEMENT'].PARAMS; // Add params to the cloned URL.
  4129. for (const key of Object.keys(params)) {
  4130. uri.searchParams.set(key, params[key]);
  4131. }
  4132. return uri.href;
  4133. }
  4134. /**
  4135. * Helper function to create the attributes needed for the new clone.
  4136. * This mainly adds the necessary media attributes.
  4137. *
  4138. * @param {string} id The pathway clone object ID.
  4139. * @param {Object} oldAttributes The old attributes to compare to.
  4140. * @return {Object} The new attributes to add to the playlist.
  4141. */
  4142. createCloneAttributes_(id, oldAttributes) {
  4143. const attributes = {
  4144. ['PATHWAY-ID']: id
  4145. };
  4146. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(mediaType => {
  4147. if (oldAttributes[mediaType]) {
  4148. attributes[mediaType] = id;
  4149. }
  4150. });
  4151. return attributes;
  4152. }
  4153. /**
  4154. * Returns the key ID set from a playlist
  4155. *
  4156. * @param {playlist} playlist to fetch the key ID set from.
  4157. * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.
  4158. */
  4159. getKeyIdSet(playlist) {
  4160. if (playlist.contentProtection) {
  4161. const keyIds = new Set();
  4162. for (const keysystem in playlist.contentProtection) {
  4163. const keyId = playlist.contentProtection[keysystem].attributes.keyId;
  4164. if (keyId) {
  4165. keyIds.add(keyId.toLowerCase());
  4166. }
  4167. }
  4168. return keyIds;
  4169. }
  4170. }
  4171. }
  4172. /**
  4173. * @file xhr.js
  4174. */
  4175. const {
  4176. xhr: videojsXHR
  4177. } = videojs__default["default"];
  4178. const callbackWrapper = function (request, error, response, callback) {
  4179. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  4180. if (!error && reqResponse) {
  4181. request.responseTime = Date.now();
  4182. request.roundTripTime = request.responseTime - request.requestTime;
  4183. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  4184. if (!request.bandwidth) {
  4185. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  4186. }
  4187. }
  4188. if (response.headers) {
  4189. request.responseHeaders = response.headers;
  4190. } // videojs.xhr now uses a specific code on the error
  4191. // object to signal that a request has timed out instead
  4192. // of setting a boolean on the request object
  4193. if (error && error.code === 'ETIMEDOUT') {
  4194. request.timedout = true;
  4195. } // videojs.xhr no longer considers status codes outside of 200 and 0
  4196. // (for file uris) to be errors, but the old XHR did, so emulate that
  4197. // behavior. Status 206 may be used in response to byterange requests.
  4198. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  4199. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  4200. }
  4201. callback(error, request);
  4202. };
  4203. /**
  4204. * Iterates over the request hooks Set and calls them in order
  4205. *
  4206. * @param {Set} hooks the hook Set to iterate over
  4207. * @param {Object} options the request options to pass to the xhr wrapper
  4208. * @return the callback hook function return value, the modified or new options Object.
  4209. */
  4210. const callAllRequestHooks = (requestSet, options) => {
  4211. if (!requestSet || !requestSet.size) {
  4212. return;
  4213. }
  4214. let newOptions = options;
  4215. requestSet.forEach(requestCallback => {
  4216. newOptions = requestCallback(newOptions);
  4217. });
  4218. return newOptions;
  4219. };
  4220. /**
  4221. * Iterates over the response hooks Set and calls them in order.
  4222. *
  4223. * @param {Set} hooks the hook Set to iterate over
  4224. * @param {Object} request the xhr request object
  4225. * @param {Object} error the xhr error object
  4226. * @param {Object} response the xhr response object
  4227. */
  4228. const callAllResponseHooks = (responseSet, request, error, response) => {
  4229. if (!responseSet || !responseSet.size) {
  4230. return;
  4231. }
  4232. responseSet.forEach(responseCallback => {
  4233. responseCallback(request, error, response);
  4234. });
  4235. };
  4236. const xhrFactory = function () {
  4237. const xhr = function XhrFunction(options, callback) {
  4238. // Add a default timeout
  4239. options = merge$1({
  4240. timeout: 45e3
  4241. }, options); // Allow an optional user-specified function to modify the option
  4242. // object before we construct the xhr request
  4243. // TODO: Remove beforeRequest in the next major release.
  4244. const beforeRequest = XhrFunction.beforeRequest || videojs__default["default"].Vhs.xhr.beforeRequest; // onRequest and onResponse hooks as a Set, at either the player or global level.
  4245. // TODO: new Set added here for beforeRequest alias. Remove this when beforeRequest is removed.
  4246. const _requestCallbackSet = XhrFunction._requestCallbackSet || videojs__default["default"].Vhs.xhr._requestCallbackSet || new Set();
  4247. const _responseCallbackSet = XhrFunction._responseCallbackSet || videojs__default["default"].Vhs.xhr._responseCallbackSet;
  4248. if (beforeRequest && typeof beforeRequest === 'function') {
  4249. videojs__default["default"].log.warn('beforeRequest is deprecated, use onRequest instead.');
  4250. _requestCallbackSet.add(beforeRequest);
  4251. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  4252. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  4253. const xhrMethod = videojs__default["default"].Vhs.xhr.original === true ? videojsXHR : videojs__default["default"].Vhs.xhr; // call all registered onRequest hooks, assign new options.
  4254. const beforeRequestOptions = callAllRequestHooks(_requestCallbackSet, options); // Remove the beforeRequest function from the hooks set so stale beforeRequest functions are not called.
  4255. _requestCallbackSet.delete(beforeRequest); // xhrMethod will call XMLHttpRequest.open and XMLHttpRequest.send
  4256. const request = xhrMethod(beforeRequestOptions || options, function (error, response) {
  4257. // call all registered onResponse hooks
  4258. callAllResponseHooks(_responseCallbackSet, request, error, response);
  4259. return callbackWrapper(request, error, response, callback);
  4260. });
  4261. const originalAbort = request.abort;
  4262. request.abort = function () {
  4263. request.aborted = true;
  4264. return originalAbort.apply(request, arguments);
  4265. };
  4266. request.uri = options.uri;
  4267. request.requestTime = Date.now();
  4268. return request;
  4269. };
  4270. xhr.original = true;
  4271. return xhr;
  4272. };
  4273. /**
  4274. * Turns segment byterange into a string suitable for use in
  4275. * HTTP Range requests
  4276. *
  4277. * @param {Object} byterange - an object with two values defining the start and end
  4278. * of a byte-range
  4279. */
  4280. const byterangeStr = function (byterange) {
  4281. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  4282. // header uses inclusive ranges
  4283. let byterangeEnd;
  4284. const byterangeStart = byterange.offset;
  4285. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  4286. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  4287. } else {
  4288. byterangeEnd = byterange.offset + byterange.length - 1;
  4289. }
  4290. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  4291. };
  4292. /**
  4293. * Defines headers for use in the xhr request for a particular segment.
  4294. *
  4295. * @param {Object} segment - a simplified copy of the segmentInfo object
  4296. * from SegmentLoader
  4297. */
  4298. const segmentXhrHeaders = function (segment) {
  4299. const headers = {};
  4300. if (segment.byterange) {
  4301. headers.Range = byterangeStr(segment.byterange);
  4302. }
  4303. return headers;
  4304. };
  4305. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  4306. var DASH_REGEX = /^application\/dash\+xml/i;
  4307. /**
  4308. * Returns a string that describes the type of source based on a video source object's
  4309. * media type.
  4310. *
  4311. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  4312. *
  4313. * @param {string} type
  4314. * Video source object media type
  4315. * @return {('hls'|'dash'|'vhs-json'|null)}
  4316. * VHS source type string
  4317. */
  4318. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  4319. if (MPEGURL_REGEX.test(type)) {
  4320. return 'hls';
  4321. }
  4322. if (DASH_REGEX.test(type)) {
  4323. return 'dash';
  4324. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  4325. // source URL.
  4326. //
  4327. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  4328. //
  4329. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  4330. // project, and the +json suffix identifies the structure of the media type.
  4331. if (type === 'application/vnd.videojs.vhs+json') {
  4332. return 'vhs-json';
  4333. }
  4334. return null;
  4335. };
  4336. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  4337. // we used to do this with log2 but BigInt does not support builtin math
  4338. // Math.ceil(log2(x));
  4339. var countBits = function countBits(x) {
  4340. return x.toString(2).length;
  4341. }; // count the number of whole bytes it would take to represent a number
  4342. var countBytes = function countBytes(x) {
  4343. return Math.ceil(countBits(x) / 8);
  4344. };
  4345. var isArrayBufferView = function isArrayBufferView(obj) {
  4346. if (ArrayBuffer.isView === 'function') {
  4347. return ArrayBuffer.isView(obj);
  4348. }
  4349. return obj && obj.buffer instanceof ArrayBuffer;
  4350. };
  4351. var isTypedArray = function isTypedArray(obj) {
  4352. return isArrayBufferView(obj);
  4353. };
  4354. var toUint8 = function toUint8(bytes) {
  4355. if (bytes instanceof Uint8Array) {
  4356. return bytes;
  4357. }
  4358. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  4359. // any non-number or NaN leads to empty uint8array
  4360. // eslint-disable-next-line
  4361. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  4362. bytes = 0;
  4363. } else {
  4364. bytes = [bytes];
  4365. }
  4366. }
  4367. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  4368. };
  4369. var BigInt = window.BigInt || Number;
  4370. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  4371. (function () {
  4372. var a = new Uint16Array([0xFFCC]);
  4373. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  4374. if (b[0] === 0xFF) {
  4375. return 'big';
  4376. }
  4377. if (b[0] === 0xCC) {
  4378. return 'little';
  4379. }
  4380. return 'unknown';
  4381. })();
  4382. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  4383. var _ref = _temp === void 0 ? {} : _temp,
  4384. _ref$signed = _ref.signed,
  4385. signed = _ref$signed === void 0 ? false : _ref$signed,
  4386. _ref$le = _ref.le,
  4387. le = _ref$le === void 0 ? false : _ref$le;
  4388. bytes = toUint8(bytes);
  4389. var fn = le ? 'reduce' : 'reduceRight';
  4390. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  4391. var number = obj.call(bytes, function (total, byte, i) {
  4392. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  4393. return total + BigInt(byte) * BYTE_TABLE[exponent];
  4394. }, BigInt(0));
  4395. if (signed) {
  4396. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  4397. number = BigInt(number);
  4398. if (number > max) {
  4399. number -= max;
  4400. number -= max;
  4401. number -= BigInt(2);
  4402. }
  4403. }
  4404. return Number(number);
  4405. };
  4406. var numberToBytes = function numberToBytes(number, _temp2) {
  4407. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  4408. _ref2$le = _ref2.le,
  4409. le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
  4410. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  4411. number = 0;
  4412. }
  4413. number = BigInt(number);
  4414. var byteCount = countBytes(number);
  4415. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  4416. for (var i = 0; i < byteCount; i++) {
  4417. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  4418. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  4419. if (number < 0) {
  4420. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  4421. bytes[byteIndex] -= i === 0 ? 1 : 2;
  4422. }
  4423. }
  4424. return bytes;
  4425. };
  4426. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  4427. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  4428. string = string.toString();
  4429. }
  4430. if (typeof string !== 'string') {
  4431. return new Uint8Array();
  4432. } // If the string already is bytes, we don't have to do this
  4433. // otherwise we do this so that we split multi length characters
  4434. // into individual bytes
  4435. if (!stringIsBytes) {
  4436. string = unescape(encodeURIComponent(string));
  4437. }
  4438. var view = new Uint8Array(string.length);
  4439. for (var i = 0; i < string.length; i++) {
  4440. view[i] = string.charCodeAt(i);
  4441. }
  4442. return view;
  4443. };
  4444. var concatTypedArrays = function concatTypedArrays() {
  4445. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  4446. buffers[_key] = arguments[_key];
  4447. }
  4448. buffers = buffers.filter(function (b) {
  4449. return b && (b.byteLength || b.length) && typeof b !== 'string';
  4450. });
  4451. if (buffers.length <= 1) {
  4452. // for 0 length we will return empty uint8
  4453. // for 1 length we return the first uint8
  4454. return toUint8(buffers[0]);
  4455. }
  4456. var totalLen = buffers.reduce(function (total, buf, i) {
  4457. return total + (buf.byteLength || buf.length);
  4458. }, 0);
  4459. var tempBuffer = new Uint8Array(totalLen);
  4460. var offset = 0;
  4461. buffers.forEach(function (buf) {
  4462. buf = toUint8(buf);
  4463. tempBuffer.set(buf, offset);
  4464. offset += buf.byteLength;
  4465. });
  4466. return tempBuffer;
  4467. };
  4468. /**
  4469. * Check if the bytes "b" are contained within bytes "a".
  4470. *
  4471. * @param {Uint8Array|Array} a
  4472. * Bytes to check in
  4473. *
  4474. * @param {Uint8Array|Array} b
  4475. * Bytes to check for
  4476. *
  4477. * @param {Object} options
  4478. * options
  4479. *
  4480. * @param {Array|Uint8Array} [offset=0]
  4481. * offset to use when looking at bytes in a
  4482. *
  4483. * @param {Array|Uint8Array} [mask=[]]
  4484. * mask to use on bytes before comparison.
  4485. *
  4486. * @return {boolean}
  4487. * If all bytes in b are inside of a, taking into account
  4488. * bit masks.
  4489. */
  4490. var bytesMatch = function bytesMatch(a, b, _temp3) {
  4491. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  4492. _ref3$offset = _ref3.offset,
  4493. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  4494. _ref3$mask = _ref3.mask,
  4495. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  4496. a = toUint8(a);
  4497. b = toUint8(b); // ie 11 does not support uint8 every
  4498. var fn = b.every ? b.every : Array.prototype.every;
  4499. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  4500. fn.call(b, function (bByte, i) {
  4501. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  4502. return bByte === aByte;
  4503. });
  4504. };
  4505. /**
  4506. * @file bin-utils.js
  4507. */
  4508. /**
  4509. * convert a TimeRange to text
  4510. *
  4511. * @param {TimeRange} range the timerange to use for conversion
  4512. * @param {number} i the iterator on the range to convert
  4513. * @return {string} the range in string format
  4514. */
  4515. const textRange = function (range, i) {
  4516. return range.start(i) + '-' + range.end(i);
  4517. };
  4518. /**
  4519. * format a number as hex string
  4520. *
  4521. * @param {number} e The number
  4522. * @param {number} i the iterator
  4523. * @return {string} the hex formatted number as a string
  4524. */
  4525. const formatHexString = function (e, i) {
  4526. const value = e.toString(16);
  4527. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  4528. };
  4529. const formatAsciiString = function (e) {
  4530. if (e >= 0x20 && e < 0x7e) {
  4531. return String.fromCharCode(e);
  4532. }
  4533. return '.';
  4534. };
  4535. /**
  4536. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  4537. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  4538. *
  4539. * @param {Object} message
  4540. * Object of properties and values to send to the web worker
  4541. * @return {Object}
  4542. * Modified message with TypedArray values expanded
  4543. * @function createTransferableMessage
  4544. */
  4545. const createTransferableMessage = function (message) {
  4546. const transferable = {};
  4547. Object.keys(message).forEach(key => {
  4548. const value = message[key];
  4549. if (isArrayBufferView(value)) {
  4550. transferable[key] = {
  4551. bytes: value.buffer,
  4552. byteOffset: value.byteOffset,
  4553. byteLength: value.byteLength
  4554. };
  4555. } else {
  4556. transferable[key] = value;
  4557. }
  4558. });
  4559. return transferable;
  4560. };
  4561. /**
  4562. * Returns a unique string identifier for a media initialization
  4563. * segment.
  4564. *
  4565. * @param {Object} initSegment
  4566. * the init segment object.
  4567. *
  4568. * @return {string} the generated init segment id
  4569. */
  4570. const initSegmentId = function (initSegment) {
  4571. const byterange = initSegment.byterange || {
  4572. length: Infinity,
  4573. offset: 0
  4574. };
  4575. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  4576. };
  4577. /**
  4578. * Returns a unique string identifier for a media segment key.
  4579. *
  4580. * @param {Object} key the encryption key
  4581. * @return {string} the unique id for the media segment key.
  4582. */
  4583. const segmentKeyId = function (key) {
  4584. return key.resolvedUri;
  4585. };
  4586. /**
  4587. * utils to help dump binary data to the console
  4588. *
  4589. * @param {Array|TypedArray} data
  4590. * data to dump to a string
  4591. *
  4592. * @return {string} the data as a hex string.
  4593. */
  4594. const hexDump = data => {
  4595. const bytes = Array.prototype.slice.call(data);
  4596. const step = 16;
  4597. let result = '';
  4598. let hex;
  4599. let ascii;
  4600. for (let j = 0; j < bytes.length / step; j++) {
  4601. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  4602. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  4603. result += hex + ' ' + ascii + '\n';
  4604. }
  4605. return result;
  4606. };
  4607. const tagDump = ({
  4608. bytes
  4609. }) => hexDump(bytes);
  4610. const textRanges = ranges => {
  4611. let result = '';
  4612. let i;
  4613. for (i = 0; i < ranges.length; i++) {
  4614. result += textRange(ranges, i) + ' ';
  4615. }
  4616. return result;
  4617. };
  4618. var utils = /*#__PURE__*/Object.freeze({
  4619. __proto__: null,
  4620. createTransferableMessage: createTransferableMessage,
  4621. initSegmentId: initSegmentId,
  4622. segmentKeyId: segmentKeyId,
  4623. hexDump: hexDump,
  4624. tagDump: tagDump,
  4625. textRanges: textRanges
  4626. });
  4627. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  4628. // 25% was arbitrarily chosen, and may need to be refined over time.
  4629. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  4630. /**
  4631. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  4632. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  4633. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  4634. *
  4635. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  4636. * point" (a point where we have a mapping from program time to player time, with player
  4637. * time being the post transmux start of the segment).
  4638. *
  4639. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  4640. *
  4641. * @param {number} playerTime the player time
  4642. * @param {Object} segment the segment which contains the player time
  4643. * @return {Date} program time
  4644. */
  4645. const playerTimeToProgramTime = (playerTime, segment) => {
  4646. if (!segment.dateTimeObject) {
  4647. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  4648. // be used to map the start of a segment with a real world time).
  4649. return null;
  4650. }
  4651. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  4652. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  4653. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  4654. const offsetFromSegmentStart = playerTime - startOfSegment;
  4655. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  4656. };
  4657. const originalSegmentVideoDuration = videoTimingInfo => {
  4658. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  4659. };
  4660. /**
  4661. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  4662. * returned segment might be an estimate or an accurate match.
  4663. *
  4664. * @param {string} programTime The ISO-8601 programTime to find a match for
  4665. * @param {Object} playlist A playlist object to search within
  4666. */
  4667. const findSegmentForProgramTime = (programTime, playlist) => {
  4668. // Assumptions:
  4669. // - verifyProgramDateTimeTags has already been run
  4670. // - live streams have been started
  4671. let dateTimeObject;
  4672. try {
  4673. dateTimeObject = new Date(programTime);
  4674. } catch (e) {
  4675. return null;
  4676. }
  4677. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4678. return null;
  4679. }
  4680. let segment = playlist.segments[0];
  4681. if (dateTimeObject < new Date(segment.dateTimeObject)) {
  4682. // Requested time is before stream start.
  4683. return null;
  4684. }
  4685. for (let i = 0; i < playlist.segments.length - 1; i++) {
  4686. segment = playlist.segments[i];
  4687. const nextSegmentStart = new Date(playlist.segments[i + 1].dateTimeObject);
  4688. if (dateTimeObject < nextSegmentStart) {
  4689. break;
  4690. }
  4691. }
  4692. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4693. const lastSegmentStart = lastSegment.dateTimeObject;
  4694. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  4695. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  4696. if (dateTimeObject > lastSegmentEnd) {
  4697. // Beyond the end of the stream, or our best guess of the end of the stream.
  4698. return null;
  4699. }
  4700. if (dateTimeObject > new Date(lastSegmentStart)) {
  4701. segment = lastSegment;
  4702. }
  4703. return {
  4704. segment,
  4705. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  4706. // Although, given that all segments have accurate date time objects, the segment
  4707. // selected should be accurate, unless the video has been transmuxed at some point
  4708. // (determined by the presence of the videoTimingInfo object), the segment's "player
  4709. // time" (the start time in the player) can't be considered accurate.
  4710. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4711. };
  4712. };
  4713. /**
  4714. * Finds a segment that contains the given player time(in seconds).
  4715. *
  4716. * @param {number} time The player time to find a match for
  4717. * @param {Object} playlist A playlist object to search within
  4718. */
  4719. const findSegmentForPlayerTime = (time, playlist) => {
  4720. // Assumptions:
  4721. // - there will always be a segment.duration
  4722. // - we can start from zero
  4723. // - segments are in time order
  4724. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  4725. return null;
  4726. }
  4727. let segmentEnd = 0;
  4728. let segment;
  4729. for (let i = 0; i < playlist.segments.length; i++) {
  4730. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  4731. // should contain the most accurate values we have for the segment's player times.
  4732. //
  4733. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  4734. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  4735. // calculate an end value.
  4736. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  4737. if (time <= segmentEnd) {
  4738. break;
  4739. }
  4740. }
  4741. const lastSegment = playlist.segments[playlist.segments.length - 1];
  4742. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  4743. // The time requested is beyond the stream end.
  4744. return null;
  4745. }
  4746. if (time > segmentEnd) {
  4747. // The time is within or beyond the last segment.
  4748. //
  4749. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  4750. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  4751. // Technically, because the duration value is only an estimate, the time may still
  4752. // exist in the last segment, however, there isn't enough information to make even
  4753. // a reasonable estimate.
  4754. return null;
  4755. }
  4756. segment = lastSegment;
  4757. }
  4758. return {
  4759. segment,
  4760. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  4761. // Because videoTimingInfo is only set after transmux, it is the only way to get
  4762. // accurate timing values.
  4763. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  4764. };
  4765. };
  4766. /**
  4767. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  4768. * If the offset returned is positive, the programTime occurs after the
  4769. * comparisonTimestamp.
  4770. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  4771. *
  4772. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  4773. * @param {string} programTime The programTime as an ISO-8601 string
  4774. * @return {number} offset
  4775. */
  4776. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  4777. let segmentDateTime;
  4778. let programDateTime;
  4779. try {
  4780. segmentDateTime = new Date(comparisonTimeStamp);
  4781. programDateTime = new Date(programTime);
  4782. } catch (e) {// TODO handle error
  4783. }
  4784. const segmentTimeEpoch = segmentDateTime.getTime();
  4785. const programTimeEpoch = programDateTime.getTime();
  4786. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  4787. };
  4788. /**
  4789. * Checks that all segments in this playlist have programDateTime tags.
  4790. *
  4791. * @param {Object} playlist A playlist object
  4792. */
  4793. const verifyProgramDateTimeTags = playlist => {
  4794. if (!playlist.segments || playlist.segments.length === 0) {
  4795. return false;
  4796. }
  4797. for (let i = 0; i < playlist.segments.length; i++) {
  4798. const segment = playlist.segments[i];
  4799. if (!segment.dateTimeObject) {
  4800. return false;
  4801. }
  4802. }
  4803. return true;
  4804. };
  4805. /**
  4806. * Returns the programTime of the media given a playlist and a playerTime.
  4807. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  4808. * If the segments containing the time requested have not been buffered yet, an estimate
  4809. * may be returned to the callback.
  4810. *
  4811. * @param {Object} args
  4812. * @param {Object} args.playlist A playlist object to search within
  4813. * @param {number} time A playerTime in seconds
  4814. * @param {Function} callback(err, programTime)
  4815. * @return {string} err.message A detailed error message
  4816. * @return {Object} programTime
  4817. * @return {number} programTime.mediaSeconds The streamTime in seconds
  4818. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  4819. */
  4820. const getProgramTime = ({
  4821. playlist,
  4822. time = undefined,
  4823. callback
  4824. }) => {
  4825. if (!callback) {
  4826. throw new Error('getProgramTime: callback must be provided');
  4827. }
  4828. if (!playlist || time === undefined) {
  4829. return callback({
  4830. message: 'getProgramTime: playlist and time must be provided'
  4831. });
  4832. }
  4833. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  4834. if (!matchedSegment) {
  4835. return callback({
  4836. message: 'valid programTime was not found'
  4837. });
  4838. }
  4839. if (matchedSegment.type === 'estimate') {
  4840. return callback({
  4841. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  4842. seekTime: matchedSegment.estimatedStart
  4843. });
  4844. }
  4845. const programTimeObject = {
  4846. mediaSeconds: time
  4847. };
  4848. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  4849. if (programTime) {
  4850. programTimeObject.programDateTime = programTime.toISOString();
  4851. }
  4852. return callback(null, programTimeObject);
  4853. };
  4854. /**
  4855. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  4856. *
  4857. * @param {Object} args
  4858. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  4859. * @param {Object} args.playlist A playlist to look within
  4860. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  4861. * @param {Function} args.seekTo A method to perform a seek
  4862. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  4863. * @param {Object} args.tech The tech to seek on
  4864. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  4865. * @return {string} err.message A detailed error message
  4866. * @return {number} newTime The exact time that was seeked to in seconds
  4867. */
  4868. const seekToProgramTime = ({
  4869. programTime,
  4870. playlist,
  4871. retryCount = 2,
  4872. seekTo,
  4873. pauseAfterSeek = true,
  4874. tech,
  4875. callback
  4876. }) => {
  4877. if (!callback) {
  4878. throw new Error('seekToProgramTime: callback must be provided');
  4879. }
  4880. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  4881. return callback({
  4882. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  4883. });
  4884. }
  4885. if (!playlist.endList && !tech.hasStarted_) {
  4886. return callback({
  4887. message: 'player must be playing a live stream to start buffering'
  4888. });
  4889. }
  4890. if (!verifyProgramDateTimeTags(playlist)) {
  4891. return callback({
  4892. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  4893. });
  4894. }
  4895. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  4896. if (!matchedSegment) {
  4897. return callback({
  4898. message: `${programTime} was not found in the stream`
  4899. });
  4900. }
  4901. const segment = matchedSegment.segment;
  4902. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  4903. if (matchedSegment.type === 'estimate') {
  4904. // we've run out of retries
  4905. if (retryCount === 0) {
  4906. return callback({
  4907. message: `${programTime} is not buffered yet. Try again`
  4908. });
  4909. }
  4910. seekTo(matchedSegment.estimatedStart + mediaOffset);
  4911. tech.one('seeked', () => {
  4912. seekToProgramTime({
  4913. programTime,
  4914. playlist,
  4915. retryCount: retryCount - 1,
  4916. seekTo,
  4917. pauseAfterSeek,
  4918. tech,
  4919. callback
  4920. });
  4921. });
  4922. return;
  4923. } // Since the segment.start value is determined from the buffered end or ending time
  4924. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  4925. // modifications.
  4926. const seekToTime = segment.start + mediaOffset;
  4927. const seekedCallback = () => {
  4928. return callback(null, tech.currentTime());
  4929. }; // listen for seeked event
  4930. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  4931. if (pauseAfterSeek) {
  4932. tech.pause();
  4933. }
  4934. seekTo(seekToTime);
  4935. };
  4936. /**
  4937. * Loops through all supported media groups in master and calls the provided
  4938. * callback for each group
  4939. *
  4940. * @param {Object} master
  4941. * The parsed master manifest object
  4942. * @param {string[]} groups
  4943. * The media groups to call the callback for
  4944. * @param {Function} callback
  4945. * Callback to call for each media group
  4946. */
  4947. var forEachMediaGroup = function forEachMediaGroup(master, groups, callback) {
  4948. groups.forEach(function (mediaType) {
  4949. for (var groupKey in master.mediaGroups[mediaType]) {
  4950. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  4951. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  4952. callback(mediaProperties, mediaType, groupKey, labelKey);
  4953. }
  4954. }
  4955. });
  4956. };
  4957. /*! @name mpd-parser @version 1.3.0 @license Apache-2.0 */
  4958. const isObject = obj => {
  4959. return !!obj && typeof obj === 'object';
  4960. };
  4961. const merge = (...objects) => {
  4962. return objects.reduce((result, source) => {
  4963. if (typeof source !== 'object') {
  4964. return result;
  4965. }
  4966. Object.keys(source).forEach(key => {
  4967. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  4968. result[key] = result[key].concat(source[key]);
  4969. } else if (isObject(result[key]) && isObject(source[key])) {
  4970. result[key] = merge(result[key], source[key]);
  4971. } else {
  4972. result[key] = source[key];
  4973. }
  4974. });
  4975. return result;
  4976. }, {});
  4977. };
  4978. const values = o => Object.keys(o).map(k => o[k]);
  4979. const range = (start, end) => {
  4980. const result = [];
  4981. for (let i = start; i < end; i++) {
  4982. result.push(i);
  4983. }
  4984. return result;
  4985. };
  4986. const flatten = lists => lists.reduce((x, y) => x.concat(y), []);
  4987. const from = list => {
  4988. if (!list.length) {
  4989. return [];
  4990. }
  4991. const result = [];
  4992. for (let i = 0; i < list.length; i++) {
  4993. result.push(list[i]);
  4994. }
  4995. return result;
  4996. };
  4997. const findIndexes = (l, key) => l.reduce((a, e, i) => {
  4998. if (e[key]) {
  4999. a.push(i);
  5000. }
  5001. return a;
  5002. }, []);
  5003. /**
  5004. * Returns a union of the included lists provided each element can be identified by a key.
  5005. *
  5006. * @param {Array} list - list of lists to get the union of
  5007. * @param {Function} keyFunction - the function to use as a key for each element
  5008. *
  5009. * @return {Array} the union of the arrays
  5010. */
  5011. const union = (lists, keyFunction) => {
  5012. return values(lists.reduce((acc, list) => {
  5013. list.forEach(el => {
  5014. acc[keyFunction(el)] = el;
  5015. });
  5016. return acc;
  5017. }, {}));
  5018. };
  5019. var errors = {
  5020. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  5021. INVALID_NUMBER_OF_CONTENT_STEERING: 'INVALID_NUMBER_OF_CONTENT_STEERING',
  5022. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  5023. DASH_INVALID_XML: 'DASH_INVALID_XML',
  5024. NO_BASE_URL: 'NO_BASE_URL',
  5025. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  5026. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  5027. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  5028. };
  5029. /**
  5030. * @typedef {Object} SingleUri
  5031. * @property {string} uri - relative location of segment
  5032. * @property {string} resolvedUri - resolved location of segment
  5033. * @property {Object} byterange - Object containing information on how to make byte range
  5034. * requests following byte-range-spec per RFC2616.
  5035. * @property {String} byterange.length - length of range request
  5036. * @property {String} byterange.offset - byte offset of range request
  5037. *
  5038. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  5039. */
  5040. /**
  5041. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  5042. * that conforms to how m3u8-parser is structured
  5043. *
  5044. * @see https://github.com/videojs/m3u8-parser
  5045. *
  5046. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  5047. * @param {string} source - source url for segment
  5048. * @param {string} range - optional range used for range calls,
  5049. * follows RFC 2616, Clause 14.35.1
  5050. * @return {SingleUri} full segment information transformed into a format similar
  5051. * to m3u8-parser
  5052. */
  5053. const urlTypeToSegment = ({
  5054. baseUrl = '',
  5055. source = '',
  5056. range = '',
  5057. indexRange = ''
  5058. }) => {
  5059. const segment = {
  5060. uri: source,
  5061. resolvedUri: resolveUrl$1(baseUrl || '', source)
  5062. };
  5063. if (range || indexRange) {
  5064. const rangeStr = range ? range : indexRange;
  5065. const ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  5066. let startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  5067. let endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  5068. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  5069. startRange = Number(startRange);
  5070. }
  5071. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  5072. endRange = Number(endRange);
  5073. }
  5074. let length;
  5075. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  5076. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  5077. } else {
  5078. length = endRange - startRange + 1;
  5079. }
  5080. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  5081. length = Number(length);
  5082. } // byterange should be inclusive according to
  5083. // RFC 2616, Clause 14.35.1
  5084. segment.byterange = {
  5085. length,
  5086. offset: startRange
  5087. };
  5088. }
  5089. return segment;
  5090. };
  5091. const byteRangeToString = byterange => {
  5092. // `endRange` is one less than `offset + length` because the HTTP range
  5093. // header uses inclusive ranges
  5094. let endRange;
  5095. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  5096. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  5097. } else {
  5098. endRange = byterange.offset + byterange.length - 1;
  5099. }
  5100. return `${byterange.offset}-${endRange}`;
  5101. };
  5102. /**
  5103. * parse the end number attribue that can be a string
  5104. * number, or undefined.
  5105. *
  5106. * @param {string|number|undefined} endNumber
  5107. * The end number attribute.
  5108. *
  5109. * @return {number|null}
  5110. * The result of parsing the end number.
  5111. */
  5112. const parseEndNumber = endNumber => {
  5113. if (endNumber && typeof endNumber !== 'number') {
  5114. endNumber = parseInt(endNumber, 10);
  5115. }
  5116. if (isNaN(endNumber)) {
  5117. return null;
  5118. }
  5119. return endNumber;
  5120. };
  5121. /**
  5122. * Functions for calculating the range of available segments in static and dynamic
  5123. * manifests.
  5124. */
  5125. const segmentRange = {
  5126. /**
  5127. * Returns the entire range of available segments for a static MPD
  5128. *
  5129. * @param {Object} attributes
  5130. * Inheritied MPD attributes
  5131. * @return {{ start: number, end: number }}
  5132. * The start and end numbers for available segments
  5133. */
  5134. static(attributes) {
  5135. const {
  5136. duration,
  5137. timescale = 1,
  5138. sourceDuration,
  5139. periodDuration
  5140. } = attributes;
  5141. const endNumber = parseEndNumber(attributes.endNumber);
  5142. const segmentDuration = duration / timescale;
  5143. if (typeof endNumber === 'number') {
  5144. return {
  5145. start: 0,
  5146. end: endNumber
  5147. };
  5148. }
  5149. if (typeof periodDuration === 'number') {
  5150. return {
  5151. start: 0,
  5152. end: periodDuration / segmentDuration
  5153. };
  5154. }
  5155. return {
  5156. start: 0,
  5157. end: sourceDuration / segmentDuration
  5158. };
  5159. },
  5160. /**
  5161. * Returns the current live window range of available segments for a dynamic MPD
  5162. *
  5163. * @param {Object} attributes
  5164. * Inheritied MPD attributes
  5165. * @return {{ start: number, end: number }}
  5166. * The start and end numbers for available segments
  5167. */
  5168. dynamic(attributes) {
  5169. const {
  5170. NOW,
  5171. clientOffset,
  5172. availabilityStartTime,
  5173. timescale = 1,
  5174. duration,
  5175. periodStart = 0,
  5176. minimumUpdatePeriod = 0,
  5177. timeShiftBufferDepth = Infinity
  5178. } = attributes;
  5179. const endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  5180. // after retrieving UTC server time.
  5181. const now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  5182. // Convert the period start time to EPOCH.
  5183. const periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  5184. const periodEndWC = now + minimumUpdatePeriod;
  5185. const periodDuration = periodEndWC - periodStartWC;
  5186. const segmentCount = Math.ceil(periodDuration * timescale / duration);
  5187. const availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  5188. const availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  5189. return {
  5190. start: Math.max(0, availableStart),
  5191. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  5192. };
  5193. }
  5194. };
  5195. /**
  5196. * Maps a range of numbers to objects with information needed to build the corresponding
  5197. * segment list
  5198. *
  5199. * @name toSegmentsCallback
  5200. * @function
  5201. * @param {number} number
  5202. * Number of the segment
  5203. * @param {number} index
  5204. * Index of the number in the range list
  5205. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  5206. * Object with segment timing and duration info
  5207. */
  5208. /**
  5209. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  5210. * information needed to build the segment list.
  5211. *
  5212. * @param {Object} attributes
  5213. * Inherited MPD attributes
  5214. * @return {toSegmentsCallback}
  5215. * Callback map function
  5216. */
  5217. const toSegments = attributes => number => {
  5218. const {
  5219. duration,
  5220. timescale = 1,
  5221. periodStart,
  5222. startNumber = 1
  5223. } = attributes;
  5224. return {
  5225. number: startNumber + number,
  5226. duration: duration / timescale,
  5227. timeline: periodStart,
  5228. time: number * duration
  5229. };
  5230. };
  5231. /**
  5232. * Returns a list of objects containing segment timing and duration info used for
  5233. * building the list of segments. This uses the @duration attribute specified
  5234. * in the MPD manifest to derive the range of segments.
  5235. *
  5236. * @param {Object} attributes
  5237. * Inherited MPD attributes
  5238. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  5239. * List of Objects with segment timing and duration info
  5240. */
  5241. const parseByDuration = attributes => {
  5242. const {
  5243. type,
  5244. duration,
  5245. timescale = 1,
  5246. periodDuration,
  5247. sourceDuration
  5248. } = attributes;
  5249. const {
  5250. start,
  5251. end
  5252. } = segmentRange[type](attributes);
  5253. const segments = range(start, end).map(toSegments(attributes));
  5254. if (type === 'static') {
  5255. const index = segments.length - 1; // section is either a period or the full source
  5256. const sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  5257. segments[index].duration = sectionDuration - duration / timescale * index;
  5258. }
  5259. return segments;
  5260. };
  5261. /**
  5262. * Translates SegmentBase into a set of segments.
  5263. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  5264. * node should be translated into segment.
  5265. *
  5266. * @param {Object} attributes
  5267. * Object containing all inherited attributes from parent elements with attribute
  5268. * names as keys
  5269. * @return {Object.<Array>} list of segments
  5270. */
  5271. const segmentsFromBase = attributes => {
  5272. const {
  5273. baseUrl,
  5274. initialization = {},
  5275. sourceDuration,
  5276. indexRange = '',
  5277. periodStart,
  5278. presentationTime,
  5279. number = 0,
  5280. duration
  5281. } = attributes; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  5282. if (!baseUrl) {
  5283. throw new Error(errors.NO_BASE_URL);
  5284. }
  5285. const initSegment = urlTypeToSegment({
  5286. baseUrl,
  5287. source: initialization.sourceURL,
  5288. range: initialization.range
  5289. });
  5290. const segment = urlTypeToSegment({
  5291. baseUrl,
  5292. source: baseUrl,
  5293. indexRange
  5294. });
  5295. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  5296. // (since SegmentBase is only for one total segment)
  5297. if (duration) {
  5298. const segmentTimeInfo = parseByDuration(attributes);
  5299. if (segmentTimeInfo.length) {
  5300. segment.duration = segmentTimeInfo[0].duration;
  5301. segment.timeline = segmentTimeInfo[0].timeline;
  5302. }
  5303. } else if (sourceDuration) {
  5304. segment.duration = sourceDuration;
  5305. segment.timeline = periodStart;
  5306. } // If presentation time is provided, these segments are being generated by SIDX
  5307. // references, and should use the time provided. For the general case of SegmentBase,
  5308. // there should only be one segment in the period, so its presentation time is the same
  5309. // as its period start.
  5310. segment.presentationTime = presentationTime || periodStart;
  5311. segment.number = number;
  5312. return [segment];
  5313. };
  5314. /**
  5315. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  5316. * according to the sidx information given.
  5317. *
  5318. * playlist.sidx has metadadata about the sidx where-as the sidx param
  5319. * is the parsed sidx box itself.
  5320. *
  5321. * @param {Object} playlist the playlist to update the sidx information for
  5322. * @param {Object} sidx the parsed sidx box
  5323. * @return {Object} the playlist object with the updated sidx information
  5324. */
  5325. const addSidxSegmentsToPlaylist$1 = (playlist, sidx, baseUrl) => {
  5326. // Retain init segment information
  5327. const initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  5328. const sourceDuration = playlist.sidx.duration; // Retain source timeline
  5329. const timeline = playlist.timeline || 0;
  5330. const sidxByteRange = playlist.sidx.byterange;
  5331. const sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  5332. const timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  5333. const mediaReferences = sidx.references.filter(r => r.referenceType !== 1);
  5334. const segments = [];
  5335. const type = playlist.endList ? 'static' : 'dynamic';
  5336. const periodStart = playlist.sidx.timeline;
  5337. let presentationTime = periodStart;
  5338. let number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  5339. let startIndex; // eslint-disable-next-line
  5340. if (typeof sidx.firstOffset === 'bigint') {
  5341. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  5342. } else {
  5343. startIndex = sidxEnd + sidx.firstOffset;
  5344. }
  5345. for (let i = 0; i < mediaReferences.length; i++) {
  5346. const reference = sidx.references[i]; // size of the referenced (sub)segment
  5347. const size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  5348. // this will be converted to seconds when generating segments
  5349. const duration = reference.subsegmentDuration; // should be an inclusive range
  5350. let endIndex; // eslint-disable-next-line
  5351. if (typeof startIndex === 'bigint') {
  5352. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  5353. } else {
  5354. endIndex = startIndex + size - 1;
  5355. }
  5356. const indexRange = `${startIndex}-${endIndex}`;
  5357. const attributes = {
  5358. baseUrl,
  5359. timescale,
  5360. timeline,
  5361. periodStart,
  5362. presentationTime,
  5363. number,
  5364. duration,
  5365. sourceDuration,
  5366. indexRange,
  5367. type
  5368. };
  5369. const segment = segmentsFromBase(attributes)[0];
  5370. if (initSegment) {
  5371. segment.map = initSegment;
  5372. }
  5373. segments.push(segment);
  5374. if (typeof startIndex === 'bigint') {
  5375. startIndex += window.BigInt(size);
  5376. } else {
  5377. startIndex += size;
  5378. }
  5379. presentationTime += duration / timescale;
  5380. number++;
  5381. }
  5382. playlist.segments = segments;
  5383. return playlist;
  5384. };
  5385. const SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  5386. const TIME_FUDGE = 1 / 60;
  5387. /**
  5388. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  5389. *
  5390. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  5391. *
  5392. * @return {TimelineStart[]} the combined and deduped timeline starts
  5393. */
  5394. const getUniqueTimelineStarts = timelineStarts => {
  5395. return union(timelineStarts, ({
  5396. timeline
  5397. }) => timeline).sort((a, b) => a.timeline > b.timeline ? 1 : -1);
  5398. };
  5399. /**
  5400. * Finds the playlist with the matching NAME attribute.
  5401. *
  5402. * @param {Array} playlists - playlists to search through
  5403. * @param {string} name - the NAME attribute to search for
  5404. *
  5405. * @return {Object|null} the matching playlist object, or null
  5406. */
  5407. const findPlaylistWithName = (playlists, name) => {
  5408. for (let i = 0; i < playlists.length; i++) {
  5409. if (playlists[i].attributes.NAME === name) {
  5410. return playlists[i];
  5411. }
  5412. }
  5413. return null;
  5414. };
  5415. /**
  5416. * Gets a flattened array of media group playlists.
  5417. *
  5418. * @param {Object} manifest - the main manifest object
  5419. *
  5420. * @return {Array} the media group playlists
  5421. */
  5422. const getMediaGroupPlaylists = manifest => {
  5423. let mediaGroupPlaylists = [];
  5424. forEachMediaGroup(manifest, SUPPORTED_MEDIA_TYPES, (properties, type, group, label) => {
  5425. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  5426. });
  5427. return mediaGroupPlaylists;
  5428. };
  5429. /**
  5430. * Updates the playlist's media sequence numbers.
  5431. *
  5432. * @param {Object} config - options object
  5433. * @param {Object} config.playlist - the playlist to update
  5434. * @param {number} config.mediaSequence - the mediaSequence number to start with
  5435. */
  5436. const updateMediaSequenceForPlaylist = ({
  5437. playlist,
  5438. mediaSequence
  5439. }) => {
  5440. playlist.mediaSequence = mediaSequence;
  5441. playlist.segments.forEach((segment, index) => {
  5442. segment.number = playlist.mediaSequence + index;
  5443. });
  5444. };
  5445. /**
  5446. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  5447. * and a complete list of timeline starts.
  5448. *
  5449. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  5450. * will be updated.
  5451. *
  5452. * Since early available timelines are not supported, at least one segment must be present.
  5453. *
  5454. * @param {Object} config - options object
  5455. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  5456. * @param {Object[]} newPlaylists - the new playlists to update
  5457. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  5458. */
  5459. const updateSequenceNumbers = ({
  5460. oldPlaylists,
  5461. newPlaylists,
  5462. timelineStarts
  5463. }) => {
  5464. newPlaylists.forEach(playlist => {
  5465. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  5466. timeline
  5467. }) {
  5468. return timeline === playlist.timeline;
  5469. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  5470. // (see ISO_23009-1-2012 5.3.5.2).
  5471. //
  5472. // If the same Representation existed in a prior Period, it will retain the same NAME.
  5473. const oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  5474. if (!oldPlaylist) {
  5475. // Since this is a new playlist, the media sequence values can start from 0 without
  5476. // consequence.
  5477. return;
  5478. } // TODO better support for live SIDX
  5479. //
  5480. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  5481. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  5482. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  5483. // not supported when the SIDX properties change on refreshes.
  5484. //
  5485. // In the future, if support needs to be added, the merging logic here can be called
  5486. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  5487. // thrown due to undefined references.
  5488. if (playlist.sidx) {
  5489. return;
  5490. } // Since we don't yet support early available timelines, we don't need to support
  5491. // playlists with no segments.
  5492. const firstNewSegment = playlist.segments[0];
  5493. const oldMatchingSegmentIndex = oldPlaylist.segments.findIndex(function (oldSegment) {
  5494. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  5495. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  5496. // In this case the media sequence should account for this update, and the new segments
  5497. // should be marked as discontinuous from the prior content, since the last prior
  5498. // timeline was removed.
  5499. if (oldMatchingSegmentIndex === -1) {
  5500. updateMediaSequenceForPlaylist({
  5501. playlist,
  5502. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  5503. });
  5504. playlist.segments[0].discontinuity = true;
  5505. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  5506. //
  5507. // If the new playlist's timeline is the same as the last seen segment's timeline,
  5508. // then a discontinuity can be added to identify that there's potentially missing
  5509. // content. If there's no missing content, the discontinuity should still be rather
  5510. // harmless. It's possible that if segment durations are accurate enough, that the
  5511. // existence of a gap can be determined using the presentation times and durations,
  5512. // but if the segment timing info is off, it may introduce more problems than simply
  5513. // adding the discontinuity.
  5514. //
  5515. // If the new playlist's timeline is different from the last seen segment's timeline,
  5516. // then a discontinuity can be added to identify that this is the first seen segment
  5517. // of a new timeline. However, the logic at the start of this function that
  5518. // determined the disconinuity sequence by timeline index is now off by one (the
  5519. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  5520. // we added it), so the disconinuity sequence must be decremented.
  5521. //
  5522. // A period may also have a duration of zero, so the case of no segments is handled
  5523. // here even though we don't yet support early available periods.
  5524. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  5525. playlist.discontinuitySequence--;
  5526. }
  5527. return;
  5528. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  5529. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  5530. // timeline's matching one, but instead should be the one prior, and the first segment
  5531. // of the new manifest should be marked with a discontinuity.
  5532. //
  5533. // The reason for this special case is that discontinuity sequence shows how many
  5534. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  5535. // the first segment of a new "timeline." Because of this, while DASH will retain that
  5536. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  5537. // sequence, and that first segment is an indicator, but can be removed before that
  5538. // timeline is gone.
  5539. const oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  5540. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  5541. firstNewSegment.discontinuity = true;
  5542. playlist.discontinuityStarts.unshift(0);
  5543. playlist.discontinuitySequence--;
  5544. }
  5545. updateMediaSequenceForPlaylist({
  5546. playlist,
  5547. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  5548. });
  5549. });
  5550. };
  5551. /**
  5552. * Given an old parsed manifest object and a new parsed manifest object, updates the
  5553. * sequence and timing values within the new manifest to ensure that it lines up with the
  5554. * old.
  5555. *
  5556. * @param {Array} oldManifest - the old main manifest object
  5557. * @param {Array} newManifest - the new main manifest object
  5558. *
  5559. * @return {Object} the updated new manifest object
  5560. */
  5561. const positionManifestOnTimeline = ({
  5562. oldManifest,
  5563. newManifest
  5564. }) => {
  5565. // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  5566. //
  5567. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  5568. //
  5569. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  5570. //
  5571. // Because of this change, and the difficulty of supporting periods with changing start
  5572. // times, periods with changing start times are not supported. This makes the logic much
  5573. // simpler, since periods with the same start time can be considerred the same period
  5574. // across refreshes.
  5575. //
  5576. // To give an example as to the difficulty of handling periods where the start time may
  5577. // change, if a single period manifest is refreshed with another manifest with a single
  5578. // period, and both the start and end times are increased, then the only way to determine
  5579. // if it's a new period or an old one that has changed is to look through the segments of
  5580. // each playlist and determine the presentation time bounds to find a match. In addition,
  5581. // if the period start changed to exceed the old period end, then there would be no
  5582. // match, and it would not be possible to determine whether the refreshed period is a new
  5583. // one or the old one.
  5584. const oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  5585. const newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  5586. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  5587. // of properties are saved for each seen Period. Even long running live streams won't
  5588. // generate too many Periods, unless the stream is watched for decades. In the future,
  5589. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  5590. // but it may not become an issue, and the additional info can be useful for debugging.
  5591. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  5592. updateSequenceNumbers({
  5593. oldPlaylists,
  5594. newPlaylists,
  5595. timelineStarts: newManifest.timelineStarts
  5596. });
  5597. return newManifest;
  5598. };
  5599. const generateSidxKey = sidx => sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  5600. const mergeDiscontiguousPlaylists = playlists => {
  5601. // Break out playlists into groups based on their baseUrl
  5602. const playlistsByBaseUrl = playlists.reduce(function (acc, cur) {
  5603. if (!acc[cur.attributes.baseUrl]) {
  5604. acc[cur.attributes.baseUrl] = [];
  5605. }
  5606. acc[cur.attributes.baseUrl].push(cur);
  5607. return acc;
  5608. }, {});
  5609. let allPlaylists = [];
  5610. Object.values(playlistsByBaseUrl).forEach(playlistGroup => {
  5611. const mergedPlaylists = values(playlistGroup.reduce((acc, playlist) => {
  5612. // assuming playlist IDs are the same across periods
  5613. // TODO: handle multiperiod where representation sets are not the same
  5614. // across periods
  5615. const name = playlist.attributes.id + (playlist.attributes.lang || '');
  5616. if (!acc[name]) {
  5617. // First Period
  5618. acc[name] = playlist;
  5619. acc[name].attributes.timelineStarts = [];
  5620. } else {
  5621. // Subsequent Periods
  5622. if (playlist.segments) {
  5623. // first segment of subsequent periods signal a discontinuity
  5624. if (playlist.segments[0]) {
  5625. playlist.segments[0].discontinuity = true;
  5626. }
  5627. acc[name].segments.push(...playlist.segments);
  5628. } // bubble up contentProtection, this assumes all DRM content
  5629. // has the same contentProtection
  5630. if (playlist.attributes.contentProtection) {
  5631. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  5632. }
  5633. }
  5634. acc[name].attributes.timelineStarts.push({
  5635. // Although they represent the same number, it's important to have both to make it
  5636. // compatible with HLS potentially having a similar attribute.
  5637. start: playlist.attributes.periodStart,
  5638. timeline: playlist.attributes.periodStart
  5639. });
  5640. return acc;
  5641. }, {}));
  5642. allPlaylists = allPlaylists.concat(mergedPlaylists);
  5643. });
  5644. return allPlaylists.map(playlist => {
  5645. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  5646. return playlist;
  5647. });
  5648. };
  5649. const addSidxSegmentsToPlaylist = (playlist, sidxMapping) => {
  5650. const sidxKey = generateSidxKey(playlist.sidx);
  5651. const sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  5652. if (sidxMatch) {
  5653. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  5654. }
  5655. return playlist;
  5656. };
  5657. const addSidxSegmentsToPlaylists = (playlists, sidxMapping = {}) => {
  5658. if (!Object.keys(sidxMapping).length) {
  5659. return playlists;
  5660. }
  5661. for (const i in playlists) {
  5662. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  5663. }
  5664. return playlists;
  5665. };
  5666. const formatAudioPlaylist = ({
  5667. attributes,
  5668. segments,
  5669. sidx,
  5670. mediaSequence,
  5671. discontinuitySequence,
  5672. discontinuityStarts
  5673. }, isAudioOnly) => {
  5674. const playlist = {
  5675. attributes: {
  5676. NAME: attributes.id,
  5677. BANDWIDTH: attributes.bandwidth,
  5678. CODECS: attributes.codecs,
  5679. ['PROGRAM-ID']: 1
  5680. },
  5681. uri: '',
  5682. endList: attributes.type === 'static',
  5683. timeline: attributes.periodStart,
  5684. resolvedUri: attributes.baseUrl || '',
  5685. targetDuration: attributes.duration,
  5686. discontinuitySequence,
  5687. discontinuityStarts,
  5688. timelineStarts: attributes.timelineStarts,
  5689. mediaSequence,
  5690. segments
  5691. };
  5692. if (attributes.contentProtection) {
  5693. playlist.contentProtection = attributes.contentProtection;
  5694. }
  5695. if (attributes.serviceLocation) {
  5696. playlist.attributes.serviceLocation = attributes.serviceLocation;
  5697. }
  5698. if (sidx) {
  5699. playlist.sidx = sidx;
  5700. }
  5701. if (isAudioOnly) {
  5702. playlist.attributes.AUDIO = 'audio';
  5703. playlist.attributes.SUBTITLES = 'subs';
  5704. }
  5705. return playlist;
  5706. };
  5707. const formatVttPlaylist = ({
  5708. attributes,
  5709. segments,
  5710. mediaSequence,
  5711. discontinuityStarts,
  5712. discontinuitySequence
  5713. }) => {
  5714. if (typeof segments === 'undefined') {
  5715. // vtt tracks may use single file in BaseURL
  5716. segments = [{
  5717. uri: attributes.baseUrl,
  5718. timeline: attributes.periodStart,
  5719. resolvedUri: attributes.baseUrl || '',
  5720. duration: attributes.sourceDuration,
  5721. number: 0
  5722. }]; // targetDuration should be the same duration as the only segment
  5723. attributes.duration = attributes.sourceDuration;
  5724. }
  5725. const m3u8Attributes = {
  5726. NAME: attributes.id,
  5727. BANDWIDTH: attributes.bandwidth,
  5728. ['PROGRAM-ID']: 1
  5729. };
  5730. if (attributes.codecs) {
  5731. m3u8Attributes.CODECS = attributes.codecs;
  5732. }
  5733. const vttPlaylist = {
  5734. attributes: m3u8Attributes,
  5735. uri: '',
  5736. endList: attributes.type === 'static',
  5737. timeline: attributes.periodStart,
  5738. resolvedUri: attributes.baseUrl || '',
  5739. targetDuration: attributes.duration,
  5740. timelineStarts: attributes.timelineStarts,
  5741. discontinuityStarts,
  5742. discontinuitySequence,
  5743. mediaSequence,
  5744. segments
  5745. };
  5746. if (attributes.serviceLocation) {
  5747. vttPlaylist.attributes.serviceLocation = attributes.serviceLocation;
  5748. }
  5749. return vttPlaylist;
  5750. };
  5751. const organizeAudioPlaylists = (playlists, sidxMapping = {}, isAudioOnly = false) => {
  5752. let mainPlaylist;
  5753. const formattedPlaylists = playlists.reduce((a, playlist) => {
  5754. const role = playlist.attributes.role && playlist.attributes.role.value || '';
  5755. const language = playlist.attributes.lang || '';
  5756. let label = playlist.attributes.label || 'main';
  5757. if (language && !playlist.attributes.label) {
  5758. const roleLabel = role ? ` (${role})` : '';
  5759. label = `${playlist.attributes.lang}${roleLabel}`;
  5760. }
  5761. if (!a[label]) {
  5762. a[label] = {
  5763. language,
  5764. autoselect: true,
  5765. default: role === 'main',
  5766. playlists: [],
  5767. uri: ''
  5768. };
  5769. }
  5770. const formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  5771. a[label].playlists.push(formatted);
  5772. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  5773. mainPlaylist = playlist;
  5774. mainPlaylist.default = true;
  5775. }
  5776. return a;
  5777. }, {}); // if no playlists have role "main", mark the first as main
  5778. if (!mainPlaylist) {
  5779. const firstLabel = Object.keys(formattedPlaylists)[0];
  5780. formattedPlaylists[firstLabel].default = true;
  5781. }
  5782. return formattedPlaylists;
  5783. };
  5784. const organizeVttPlaylists = (playlists, sidxMapping = {}) => {
  5785. return playlists.reduce((a, playlist) => {
  5786. const label = playlist.attributes.label || playlist.attributes.lang || 'text';
  5787. if (!a[label]) {
  5788. a[label] = {
  5789. language: label,
  5790. default: false,
  5791. autoselect: false,
  5792. playlists: [],
  5793. uri: ''
  5794. };
  5795. }
  5796. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  5797. return a;
  5798. }, {});
  5799. };
  5800. const organizeCaptionServices = captionServices => captionServices.reduce((svcObj, svc) => {
  5801. if (!svc) {
  5802. return svcObj;
  5803. }
  5804. svc.forEach(service => {
  5805. const {
  5806. channel,
  5807. language
  5808. } = service;
  5809. svcObj[language] = {
  5810. autoselect: false,
  5811. default: false,
  5812. instreamId: channel,
  5813. language
  5814. };
  5815. if (service.hasOwnProperty('aspectRatio')) {
  5816. svcObj[language].aspectRatio = service.aspectRatio;
  5817. }
  5818. if (service.hasOwnProperty('easyReader')) {
  5819. svcObj[language].easyReader = service.easyReader;
  5820. }
  5821. if (service.hasOwnProperty('3D')) {
  5822. svcObj[language]['3D'] = service['3D'];
  5823. }
  5824. });
  5825. return svcObj;
  5826. }, {});
  5827. const formatVideoPlaylist = ({
  5828. attributes,
  5829. segments,
  5830. sidx,
  5831. discontinuityStarts
  5832. }) => {
  5833. const playlist = {
  5834. attributes: {
  5835. NAME: attributes.id,
  5836. AUDIO: 'audio',
  5837. SUBTITLES: 'subs',
  5838. RESOLUTION: {
  5839. width: attributes.width,
  5840. height: attributes.height
  5841. },
  5842. CODECS: attributes.codecs,
  5843. BANDWIDTH: attributes.bandwidth,
  5844. ['PROGRAM-ID']: 1
  5845. },
  5846. uri: '',
  5847. endList: attributes.type === 'static',
  5848. timeline: attributes.periodStart,
  5849. resolvedUri: attributes.baseUrl || '',
  5850. targetDuration: attributes.duration,
  5851. discontinuityStarts,
  5852. timelineStarts: attributes.timelineStarts,
  5853. segments
  5854. };
  5855. if (attributes.frameRate) {
  5856. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  5857. }
  5858. if (attributes.contentProtection) {
  5859. playlist.contentProtection = attributes.contentProtection;
  5860. }
  5861. if (attributes.serviceLocation) {
  5862. playlist.attributes.serviceLocation = attributes.serviceLocation;
  5863. }
  5864. if (sidx) {
  5865. playlist.sidx = sidx;
  5866. }
  5867. return playlist;
  5868. };
  5869. const videoOnly = ({
  5870. attributes
  5871. }) => attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  5872. const audioOnly = ({
  5873. attributes
  5874. }) => attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  5875. const vttOnly = ({
  5876. attributes
  5877. }) => attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  5878. /**
  5879. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  5880. * be the same number.
  5881. *
  5882. * @typedef {Object} TimelineStart
  5883. * @property {number} start - the start time of the timeline
  5884. * @property {number} timeline - the timeline number
  5885. */
  5886. /**
  5887. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  5888. *
  5889. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  5890. * DASH specific attribute used in constructing segment URI's from templates. However, from
  5891. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  5892. * value, which should start at the original media sequence value (or 0) and increment by 1
  5893. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  5894. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  5895. * from a 0 mediaSequence value and increment from there.
  5896. *
  5897. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  5898. * debugging and making sense of the manifest.
  5899. *
  5900. * For live playlists, to account for values increasing in manifests when periods are
  5901. * removed on refreshes, merging logic should be used to update the numbers to their
  5902. * appropriate values (to ensure they're sequential and increasing).
  5903. *
  5904. * @param {Object[]} playlists - the playlists to update
  5905. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  5906. */
  5907. const addMediaSequenceValues = (playlists, timelineStarts) => {
  5908. // increment all segments sequentially
  5909. playlists.forEach(playlist => {
  5910. playlist.mediaSequence = 0;
  5911. playlist.discontinuitySequence = timelineStarts.findIndex(function ({
  5912. timeline
  5913. }) {
  5914. return timeline === playlist.timeline;
  5915. });
  5916. if (!playlist.segments) {
  5917. return;
  5918. }
  5919. playlist.segments.forEach((segment, index) => {
  5920. segment.number = index;
  5921. });
  5922. });
  5923. };
  5924. /**
  5925. * Given a media group object, flattens all playlists within the media group into a single
  5926. * array.
  5927. *
  5928. * @param {Object} mediaGroupObject - the media group object
  5929. *
  5930. * @return {Object[]}
  5931. * The media group playlists
  5932. */
  5933. const flattenMediaGroupPlaylists = mediaGroupObject => {
  5934. if (!mediaGroupObject) {
  5935. return [];
  5936. }
  5937. return Object.keys(mediaGroupObject).reduce((acc, label) => {
  5938. const labelContents = mediaGroupObject[label];
  5939. return acc.concat(labelContents.playlists);
  5940. }, []);
  5941. };
  5942. const toM3u8 = ({
  5943. dashPlaylists,
  5944. locations,
  5945. contentSteering,
  5946. sidxMapping = {},
  5947. previousManifest,
  5948. eventStream
  5949. }) => {
  5950. if (!dashPlaylists.length) {
  5951. return {};
  5952. } // grab all main manifest attributes
  5953. const {
  5954. sourceDuration: duration,
  5955. type,
  5956. suggestedPresentationDelay,
  5957. minimumUpdatePeriod
  5958. } = dashPlaylists[0].attributes;
  5959. const videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  5960. const audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  5961. const vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  5962. const captions = dashPlaylists.map(playlist => playlist.attributes.captionServices).filter(Boolean);
  5963. const manifest = {
  5964. allowCache: true,
  5965. discontinuityStarts: [],
  5966. segments: [],
  5967. endList: true,
  5968. mediaGroups: {
  5969. AUDIO: {},
  5970. VIDEO: {},
  5971. ['CLOSED-CAPTIONS']: {},
  5972. SUBTITLES: {}
  5973. },
  5974. uri: '',
  5975. duration,
  5976. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  5977. };
  5978. if (minimumUpdatePeriod >= 0) {
  5979. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  5980. }
  5981. if (locations) {
  5982. manifest.locations = locations;
  5983. }
  5984. if (contentSteering) {
  5985. manifest.contentSteering = contentSteering;
  5986. }
  5987. if (type === 'dynamic') {
  5988. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  5989. }
  5990. if (eventStream && eventStream.length > 0) {
  5991. manifest.eventStream = eventStream;
  5992. }
  5993. const isAudioOnly = manifest.playlists.length === 0;
  5994. const organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  5995. const organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  5996. const formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  5997. const playlistTimelineStarts = formattedPlaylists.map(({
  5998. timelineStarts
  5999. }) => timelineStarts);
  6000. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  6001. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  6002. if (organizedAudioGroup) {
  6003. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  6004. }
  6005. if (organizedVttGroup) {
  6006. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  6007. }
  6008. if (captions.length) {
  6009. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  6010. }
  6011. if (previousManifest) {
  6012. return positionManifestOnTimeline({
  6013. oldManifest: previousManifest,
  6014. newManifest: manifest
  6015. });
  6016. }
  6017. return manifest;
  6018. };
  6019. /**
  6020. * Calculates the R (repetition) value for a live stream (for the final segment
  6021. * in a manifest where the r value is negative 1)
  6022. *
  6023. * @param {Object} attributes
  6024. * Object containing all inherited attributes from parent elements with attribute
  6025. * names as keys
  6026. * @param {number} time
  6027. * current time (typically the total time up until the final segment)
  6028. * @param {number} duration
  6029. * duration property for the given <S />
  6030. *
  6031. * @return {number}
  6032. * R value to reach the end of the given period
  6033. */
  6034. const getLiveRValue = (attributes, time, duration) => {
  6035. const {
  6036. NOW,
  6037. clientOffset,
  6038. availabilityStartTime,
  6039. timescale = 1,
  6040. periodStart = 0,
  6041. minimumUpdatePeriod = 0
  6042. } = attributes;
  6043. const now = (NOW + clientOffset) / 1000;
  6044. const periodStartWC = availabilityStartTime + periodStart;
  6045. const periodEndWC = now + minimumUpdatePeriod;
  6046. const periodDuration = periodEndWC - periodStartWC;
  6047. return Math.ceil((periodDuration * timescale - time) / duration);
  6048. };
  6049. /**
  6050. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  6051. * timing and duration
  6052. *
  6053. * @param {Object} attributes
  6054. * Object containing all inherited attributes from parent elements with attribute
  6055. * names as keys
  6056. * @param {Object[]} segmentTimeline
  6057. * List of objects representing the attributes of each S element contained within
  6058. *
  6059. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  6060. * List of Objects with segment timing and duration info
  6061. */
  6062. const parseByTimeline = (attributes, segmentTimeline) => {
  6063. const {
  6064. type,
  6065. minimumUpdatePeriod = 0,
  6066. media = '',
  6067. sourceDuration,
  6068. timescale = 1,
  6069. startNumber = 1,
  6070. periodStart: timeline
  6071. } = attributes;
  6072. const segments = [];
  6073. let time = -1;
  6074. for (let sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  6075. const S = segmentTimeline[sIndex];
  6076. const duration = S.d;
  6077. const repeat = S.r || 0;
  6078. const segmentTime = S.t || 0;
  6079. if (time < 0) {
  6080. // first segment
  6081. time = segmentTime;
  6082. }
  6083. if (segmentTime && segmentTime > time) {
  6084. // discontinuity
  6085. // TODO: How to handle this type of discontinuity
  6086. // timeline++ here would treat it like HLS discontuity and content would
  6087. // get appended without gap
  6088. // E.G.
  6089. // <S t="0" d="1" />
  6090. // <S d="1" />
  6091. // <S d="1" />
  6092. // <S t="5" d="1" />
  6093. // would have $Time$ values of [0, 1, 2, 5]
  6094. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  6095. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  6096. // does the value of sourceDuration consider this when calculating arbitrary
  6097. // negative @r repeat value?
  6098. // E.G. Same elements as above with this added at the end
  6099. // <S d="1" r="-1" />
  6100. // with a sourceDuration of 10
  6101. // Would the 2 gaps be included in the time duration calculations resulting in
  6102. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  6103. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  6104. time = segmentTime;
  6105. }
  6106. let count;
  6107. if (repeat < 0) {
  6108. const nextS = sIndex + 1;
  6109. if (nextS === segmentTimeline.length) {
  6110. // last segment
  6111. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  6112. count = getLiveRValue(attributes, time, duration);
  6113. } else {
  6114. // TODO: This may be incorrect depending on conclusion of TODO above
  6115. count = (sourceDuration * timescale - time) / duration;
  6116. }
  6117. } else {
  6118. count = (segmentTimeline[nextS].t - time) / duration;
  6119. }
  6120. } else {
  6121. count = repeat + 1;
  6122. }
  6123. const end = startNumber + segments.length + count;
  6124. let number = startNumber + segments.length;
  6125. while (number < end) {
  6126. segments.push({
  6127. number,
  6128. duration: duration / timescale,
  6129. time,
  6130. timeline
  6131. });
  6132. time += duration;
  6133. number++;
  6134. }
  6135. }
  6136. return segments;
  6137. };
  6138. const identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  6139. /**
  6140. * Replaces template identifiers with corresponding values. To be used as the callback
  6141. * for String.prototype.replace
  6142. *
  6143. * @name replaceCallback
  6144. * @function
  6145. * @param {string} match
  6146. * Entire match of identifier
  6147. * @param {string} identifier
  6148. * Name of matched identifier
  6149. * @param {string} format
  6150. * Format tag string. Its presence indicates that padding is expected
  6151. * @param {string} width
  6152. * Desired length of the replaced value. Values less than this width shall be left
  6153. * zero padded
  6154. * @return {string}
  6155. * Replacement for the matched identifier
  6156. */
  6157. /**
  6158. * Returns a function to be used as a callback for String.prototype.replace to replace
  6159. * template identifiers
  6160. *
  6161. * @param {Obect} values
  6162. * Object containing values that shall be used to replace known identifiers
  6163. * @param {number} values.RepresentationID
  6164. * Value of the Representation@id attribute
  6165. * @param {number} values.Number
  6166. * Number of the corresponding segment
  6167. * @param {number} values.Bandwidth
  6168. * Value of the Representation@bandwidth attribute.
  6169. * @param {number} values.Time
  6170. * Timestamp value of the corresponding segment
  6171. * @return {replaceCallback}
  6172. * Callback to be used with String.prototype.replace to replace identifiers
  6173. */
  6174. const identifierReplacement = values => (match, identifier, format, width) => {
  6175. if (match === '$$') {
  6176. // escape sequence
  6177. return '$';
  6178. }
  6179. if (typeof values[identifier] === 'undefined') {
  6180. return match;
  6181. }
  6182. const value = '' + values[identifier];
  6183. if (identifier === 'RepresentationID') {
  6184. // Format tag shall not be present with RepresentationID
  6185. return value;
  6186. }
  6187. if (!format) {
  6188. width = 1;
  6189. } else {
  6190. width = parseInt(width, 10);
  6191. }
  6192. if (value.length >= width) {
  6193. return value;
  6194. }
  6195. return `${new Array(width - value.length + 1).join('0')}${value}`;
  6196. };
  6197. /**
  6198. * Constructs a segment url from a template string
  6199. *
  6200. * @param {string} url
  6201. * Template string to construct url from
  6202. * @param {Obect} values
  6203. * Object containing values that shall be used to replace known identifiers
  6204. * @param {number} values.RepresentationID
  6205. * Value of the Representation@id attribute
  6206. * @param {number} values.Number
  6207. * Number of the corresponding segment
  6208. * @param {number} values.Bandwidth
  6209. * Value of the Representation@bandwidth attribute.
  6210. * @param {number} values.Time
  6211. * Timestamp value of the corresponding segment
  6212. * @return {string}
  6213. * Segment url with identifiers replaced
  6214. */
  6215. const constructTemplateUrl = (url, values) => url.replace(identifierPattern, identifierReplacement(values));
  6216. /**
  6217. * Generates a list of objects containing timing and duration information about each
  6218. * segment needed to generate segment uris and the complete segment object
  6219. *
  6220. * @param {Object} attributes
  6221. * Object containing all inherited attributes from parent elements with attribute
  6222. * names as keys
  6223. * @param {Object[]|undefined} segmentTimeline
  6224. * List of objects representing the attributes of each S element contained within
  6225. * the SegmentTimeline element
  6226. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  6227. * List of Objects with segment timing and duration info
  6228. */
  6229. const parseTemplateInfo = (attributes, segmentTimeline) => {
  6230. if (!attributes.duration && !segmentTimeline) {
  6231. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  6232. // one media segment
  6233. return [{
  6234. number: attributes.startNumber || 1,
  6235. duration: attributes.sourceDuration,
  6236. time: 0,
  6237. timeline: attributes.periodStart
  6238. }];
  6239. }
  6240. if (attributes.duration) {
  6241. return parseByDuration(attributes);
  6242. }
  6243. return parseByTimeline(attributes, segmentTimeline);
  6244. };
  6245. /**
  6246. * Generates a list of segments using information provided by the SegmentTemplate element
  6247. *
  6248. * @param {Object} attributes
  6249. * Object containing all inherited attributes from parent elements with attribute
  6250. * names as keys
  6251. * @param {Object[]|undefined} segmentTimeline
  6252. * List of objects representing the attributes of each S element contained within
  6253. * the SegmentTimeline element
  6254. * @return {Object[]}
  6255. * List of segment objects
  6256. */
  6257. const segmentsFromTemplate = (attributes, segmentTimeline) => {
  6258. const templateValues = {
  6259. RepresentationID: attributes.id,
  6260. Bandwidth: attributes.bandwidth || 0
  6261. };
  6262. const {
  6263. initialization = {
  6264. sourceURL: '',
  6265. range: ''
  6266. }
  6267. } = attributes;
  6268. const mapSegment = urlTypeToSegment({
  6269. baseUrl: attributes.baseUrl,
  6270. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  6271. range: initialization.range
  6272. });
  6273. const segments = parseTemplateInfo(attributes, segmentTimeline);
  6274. return segments.map(segment => {
  6275. templateValues.Number = segment.number;
  6276. templateValues.Time = segment.time;
  6277. const uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  6278. // - if timescale isn't present on any level, default to 1.
  6279. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  6280. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  6281. const presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is
  6282. // calculated in mpd-parser prior to this, so it's assumed to be available.
  6283. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  6284. const map = {
  6285. uri,
  6286. timeline: segment.timeline,
  6287. duration: segment.duration,
  6288. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  6289. map: mapSegment,
  6290. number: segment.number,
  6291. presentationTime
  6292. };
  6293. return map;
  6294. });
  6295. };
  6296. /**
  6297. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  6298. * to an object that matches the output of a segment in videojs/mpd-parser
  6299. *
  6300. * @param {Object} attributes
  6301. * Object containing all inherited attributes from parent elements with attribute
  6302. * names as keys
  6303. * @param {Object} segmentUrl
  6304. * <SegmentURL> node to translate into a segment object
  6305. * @return {Object} translated segment object
  6306. */
  6307. const SegmentURLToSegmentObject = (attributes, segmentUrl) => {
  6308. const {
  6309. baseUrl,
  6310. initialization = {}
  6311. } = attributes;
  6312. const initSegment = urlTypeToSegment({
  6313. baseUrl,
  6314. source: initialization.sourceURL,
  6315. range: initialization.range
  6316. });
  6317. const segment = urlTypeToSegment({
  6318. baseUrl,
  6319. source: segmentUrl.media,
  6320. range: segmentUrl.mediaRange
  6321. });
  6322. segment.map = initSegment;
  6323. return segment;
  6324. };
  6325. /**
  6326. * Generates a list of segments using information provided by the SegmentList element
  6327. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  6328. * node should be translated into segment.
  6329. *
  6330. * @param {Object} attributes
  6331. * Object containing all inherited attributes from parent elements with attribute
  6332. * names as keys
  6333. * @param {Object[]|undefined} segmentTimeline
  6334. * List of objects representing the attributes of each S element contained within
  6335. * the SegmentTimeline element
  6336. * @return {Object.<Array>} list of segments
  6337. */
  6338. const segmentsFromList = (attributes, segmentTimeline) => {
  6339. const {
  6340. duration,
  6341. segmentUrls = [],
  6342. periodStart
  6343. } = attributes; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  6344. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  6345. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  6346. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  6347. }
  6348. const segmentUrlMap = segmentUrls.map(segmentUrlObject => SegmentURLToSegmentObject(attributes, segmentUrlObject));
  6349. let segmentTimeInfo;
  6350. if (duration) {
  6351. segmentTimeInfo = parseByDuration(attributes);
  6352. }
  6353. if (segmentTimeline) {
  6354. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  6355. }
  6356. const segments = segmentTimeInfo.map((segmentTime, index) => {
  6357. if (segmentUrlMap[index]) {
  6358. const segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  6359. // - if timescale isn't present on any level, default to 1.
  6360. const timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  6361. const presentationTimeOffset = attributes.presentationTimeOffset || 0;
  6362. segment.timeline = segmentTime.timeline;
  6363. segment.duration = segmentTime.duration;
  6364. segment.number = segmentTime.number;
  6365. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  6366. return segment;
  6367. } // Since we're mapping we should get rid of any blank segments (in case
  6368. // the given SegmentTimeline is handling for more elements than we have
  6369. // SegmentURLs for).
  6370. }).filter(segment => segment);
  6371. return segments;
  6372. };
  6373. const generateSegments = ({
  6374. attributes,
  6375. segmentInfo
  6376. }) => {
  6377. let segmentAttributes;
  6378. let segmentsFn;
  6379. if (segmentInfo.template) {
  6380. segmentsFn = segmentsFromTemplate;
  6381. segmentAttributes = merge(attributes, segmentInfo.template);
  6382. } else if (segmentInfo.base) {
  6383. segmentsFn = segmentsFromBase;
  6384. segmentAttributes = merge(attributes, segmentInfo.base);
  6385. } else if (segmentInfo.list) {
  6386. segmentsFn = segmentsFromList;
  6387. segmentAttributes = merge(attributes, segmentInfo.list);
  6388. }
  6389. const segmentsInfo = {
  6390. attributes
  6391. };
  6392. if (!segmentsFn) {
  6393. return segmentsInfo;
  6394. }
  6395. const segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  6396. // must be in seconds. Since we've generated the segment list, we no longer need
  6397. // @duration to be in @timescale units, so we can convert it here.
  6398. if (segmentAttributes.duration) {
  6399. const {
  6400. duration,
  6401. timescale = 1
  6402. } = segmentAttributes;
  6403. segmentAttributes.duration = duration / timescale;
  6404. } else if (segments.length) {
  6405. // if there is no @duration attribute, use the largest segment duration as
  6406. // as target duration
  6407. segmentAttributes.duration = segments.reduce((max, segment) => {
  6408. return Math.max(max, Math.ceil(segment.duration));
  6409. }, 0);
  6410. } else {
  6411. segmentAttributes.duration = 0;
  6412. }
  6413. segmentsInfo.attributes = segmentAttributes;
  6414. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  6415. if (segmentInfo.base && segmentAttributes.indexRange) {
  6416. segmentsInfo.sidx = segments[0];
  6417. segmentsInfo.segments = [];
  6418. }
  6419. return segmentsInfo;
  6420. };
  6421. const toPlaylists = representations => representations.map(generateSegments);
  6422. const findChildren = (element, name) => from(element.childNodes).filter(({
  6423. tagName
  6424. }) => tagName === name);
  6425. const getContent = element => element.textContent.trim();
  6426. /**
  6427. * Converts the provided string that may contain a division operation to a number.
  6428. *
  6429. * @param {string} value - the provided string value
  6430. *
  6431. * @return {number} the parsed string value
  6432. */
  6433. const parseDivisionValue = value => {
  6434. return parseFloat(value.split('/').reduce((prev, current) => prev / current));
  6435. };
  6436. const parseDuration = str => {
  6437. const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  6438. const SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  6439. const SECONDS_IN_DAY = 24 * 60 * 60;
  6440. const SECONDS_IN_HOUR = 60 * 60;
  6441. const SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  6442. const durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  6443. const match = durationRegex.exec(str);
  6444. if (!match) {
  6445. return 0;
  6446. }
  6447. const [year, month, day, hour, minute, second] = match.slice(1);
  6448. 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);
  6449. };
  6450. const parseDate = str => {
  6451. // Date format without timezone according to ISO 8601
  6452. // YYY-MM-DDThh:mm:ss.ssssss
  6453. 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
  6454. // expressed by ending with 'Z'
  6455. if (dateRegex.test(str)) {
  6456. str += 'Z';
  6457. }
  6458. return Date.parse(str);
  6459. };
  6460. const parsers = {
  6461. /**
  6462. * Specifies the duration of the entire Media Presentation. Format is a duration string
  6463. * as specified in ISO 8601
  6464. *
  6465. * @param {string} value
  6466. * value of attribute as a string
  6467. * @return {number}
  6468. * The duration in seconds
  6469. */
  6470. mediaPresentationDuration(value) {
  6471. return parseDuration(value);
  6472. },
  6473. /**
  6474. * Specifies the Segment availability start time for all Segments referred to in this
  6475. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  6476. * time. Format is a date string as specified in ISO 8601
  6477. *
  6478. * @param {string} value
  6479. * value of attribute as a string
  6480. * @return {number}
  6481. * The date as seconds from unix epoch
  6482. */
  6483. availabilityStartTime(value) {
  6484. return parseDate(value) / 1000;
  6485. },
  6486. /**
  6487. * Specifies the smallest period between potential changes to the MPD. Format is a
  6488. * duration string as specified in ISO 8601
  6489. *
  6490. * @param {string} value
  6491. * value of attribute as a string
  6492. * @return {number}
  6493. * The duration in seconds
  6494. */
  6495. minimumUpdatePeriod(value) {
  6496. return parseDuration(value);
  6497. },
  6498. /**
  6499. * Specifies the suggested presentation delay. Format is a
  6500. * duration string as specified in ISO 8601
  6501. *
  6502. * @param {string} value
  6503. * value of attribute as a string
  6504. * @return {number}
  6505. * The duration in seconds
  6506. */
  6507. suggestedPresentationDelay(value) {
  6508. return parseDuration(value);
  6509. },
  6510. /**
  6511. * specifices the type of mpd. Can be either "static" or "dynamic"
  6512. *
  6513. * @param {string} value
  6514. * value of attribute as a string
  6515. *
  6516. * @return {string}
  6517. * The type as a string
  6518. */
  6519. type(value) {
  6520. return value;
  6521. },
  6522. /**
  6523. * Specifies the duration of the smallest time shifting buffer for any Representation
  6524. * in the MPD. Format is a duration string as specified in ISO 8601
  6525. *
  6526. * @param {string} value
  6527. * value of attribute as a string
  6528. * @return {number}
  6529. * The duration in seconds
  6530. */
  6531. timeShiftBufferDepth(value) {
  6532. return parseDuration(value);
  6533. },
  6534. /**
  6535. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  6536. * Format is a duration string as specified in ISO 8601
  6537. *
  6538. * @param {string} value
  6539. * value of attribute as a string
  6540. * @return {number}
  6541. * The duration in seconds
  6542. */
  6543. start(value) {
  6544. return parseDuration(value);
  6545. },
  6546. /**
  6547. * Specifies the width of the visual presentation
  6548. *
  6549. * @param {string} value
  6550. * value of attribute as a string
  6551. * @return {number}
  6552. * The parsed width
  6553. */
  6554. width(value) {
  6555. return parseInt(value, 10);
  6556. },
  6557. /**
  6558. * Specifies the height of the visual presentation
  6559. *
  6560. * @param {string} value
  6561. * value of attribute as a string
  6562. * @return {number}
  6563. * The parsed height
  6564. */
  6565. height(value) {
  6566. return parseInt(value, 10);
  6567. },
  6568. /**
  6569. * Specifies the bitrate of the representation
  6570. *
  6571. * @param {string} value
  6572. * value of attribute as a string
  6573. * @return {number}
  6574. * The parsed bandwidth
  6575. */
  6576. bandwidth(value) {
  6577. return parseInt(value, 10);
  6578. },
  6579. /**
  6580. * Specifies the frame rate of the representation
  6581. *
  6582. * @param {string} value
  6583. * value of attribute as a string
  6584. * @return {number}
  6585. * The parsed frame rate
  6586. */
  6587. frameRate(value) {
  6588. return parseDivisionValue(value);
  6589. },
  6590. /**
  6591. * Specifies the number of the first Media Segment in this Representation in the Period
  6592. *
  6593. * @param {string} value
  6594. * value of attribute as a string
  6595. * @return {number}
  6596. * The parsed number
  6597. */
  6598. startNumber(value) {
  6599. return parseInt(value, 10);
  6600. },
  6601. /**
  6602. * Specifies the timescale in units per seconds
  6603. *
  6604. * @param {string} value
  6605. * value of attribute as a string
  6606. * @return {number}
  6607. * The parsed timescale
  6608. */
  6609. timescale(value) {
  6610. return parseInt(value, 10);
  6611. },
  6612. /**
  6613. * Specifies the presentationTimeOffset.
  6614. *
  6615. * @param {string} value
  6616. * value of the attribute as a string
  6617. *
  6618. * @return {number}
  6619. * The parsed presentationTimeOffset
  6620. */
  6621. presentationTimeOffset(value) {
  6622. return parseInt(value, 10);
  6623. },
  6624. /**
  6625. * Specifies the constant approximate Segment duration
  6626. * NOTE: The <Period> element also contains an @duration attribute. This duration
  6627. * specifies the duration of the Period. This attribute is currently not
  6628. * supported by the rest of the parser, however we still check for it to prevent
  6629. * errors.
  6630. *
  6631. * @param {string} value
  6632. * value of attribute as a string
  6633. * @return {number}
  6634. * The parsed duration
  6635. */
  6636. duration(value) {
  6637. const parsedValue = parseInt(value, 10);
  6638. if (isNaN(parsedValue)) {
  6639. return parseDuration(value);
  6640. }
  6641. return parsedValue;
  6642. },
  6643. /**
  6644. * Specifies the Segment duration, in units of the value of the @timescale.
  6645. *
  6646. * @param {string} value
  6647. * value of attribute as a string
  6648. * @return {number}
  6649. * The parsed duration
  6650. */
  6651. d(value) {
  6652. return parseInt(value, 10);
  6653. },
  6654. /**
  6655. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  6656. * starts relative to the beginning of the Period
  6657. *
  6658. * @param {string} value
  6659. * value of attribute as a string
  6660. * @return {number}
  6661. * The parsed time
  6662. */
  6663. t(value) {
  6664. return parseInt(value, 10);
  6665. },
  6666. /**
  6667. * Specifies the repeat count of the number of following contiguous Segments with the
  6668. * same duration expressed by the value of @d
  6669. *
  6670. * @param {string} value
  6671. * value of attribute as a string
  6672. * @return {number}
  6673. * The parsed number
  6674. */
  6675. r(value) {
  6676. return parseInt(value, 10);
  6677. },
  6678. /**
  6679. * Specifies the presentationTime.
  6680. *
  6681. * @param {string} value
  6682. * value of the attribute as a string
  6683. *
  6684. * @return {number}
  6685. * The parsed presentationTime
  6686. */
  6687. presentationTime(value) {
  6688. return parseInt(value, 10);
  6689. },
  6690. /**
  6691. * Default parser for all other attributes. Acts as a no-op and just returns the value
  6692. * as a string
  6693. *
  6694. * @param {string} value
  6695. * value of attribute as a string
  6696. * @return {string}
  6697. * Unparsed value
  6698. */
  6699. DEFAULT(value) {
  6700. return value;
  6701. }
  6702. };
  6703. /**
  6704. * Gets all the attributes and values of the provided node, parses attributes with known
  6705. * types, and returns an object with attribute names mapped to values.
  6706. *
  6707. * @param {Node} el
  6708. * The node to parse attributes from
  6709. * @return {Object}
  6710. * Object with all attributes of el parsed
  6711. */
  6712. const parseAttributes = el => {
  6713. if (!(el && el.attributes)) {
  6714. return {};
  6715. }
  6716. return from(el.attributes).reduce((a, e) => {
  6717. const parseFn = parsers[e.name] || parsers.DEFAULT;
  6718. a[e.name] = parseFn(e.value);
  6719. return a;
  6720. }, {});
  6721. };
  6722. const keySystemsMap = {
  6723. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  6724. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  6725. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  6726. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime',
  6727. // ISO_IEC 23009-1_2022 5.8.5.2.2 The mp4 Protection Scheme
  6728. 'urn:mpeg:dash:mp4protection:2011': 'mp4protection'
  6729. };
  6730. /**
  6731. * Builds a list of urls that is the product of the reference urls and BaseURL values
  6732. *
  6733. * @param {Object[]} references
  6734. * List of objects containing the reference URL as well as its attributes
  6735. * @param {Node[]} baseUrlElements
  6736. * List of BaseURL nodes from the mpd
  6737. * @return {Object[]}
  6738. * List of objects with resolved urls and attributes
  6739. */
  6740. const buildBaseUrls = (references, baseUrlElements) => {
  6741. if (!baseUrlElements.length) {
  6742. return references;
  6743. }
  6744. return flatten(references.map(function (reference) {
  6745. return baseUrlElements.map(function (baseUrlElement) {
  6746. const initialBaseUrl = getContent(baseUrlElement);
  6747. const resolvedBaseUrl = resolveUrl$1(reference.baseUrl, initialBaseUrl);
  6748. const finalBaseUrl = merge(parseAttributes(baseUrlElement), {
  6749. baseUrl: resolvedBaseUrl
  6750. }); // If the URL is resolved, we want to get the serviceLocation from the reference
  6751. // assuming there is no serviceLocation on the initialBaseUrl
  6752. if (resolvedBaseUrl !== initialBaseUrl && !finalBaseUrl.serviceLocation && reference.serviceLocation) {
  6753. finalBaseUrl.serviceLocation = reference.serviceLocation;
  6754. }
  6755. return finalBaseUrl;
  6756. });
  6757. }));
  6758. };
  6759. /**
  6760. * Contains all Segment information for its containing AdaptationSet
  6761. *
  6762. * @typedef {Object} SegmentInformation
  6763. * @property {Object|undefined} template
  6764. * Contains the attributes for the SegmentTemplate node
  6765. * @property {Object[]|undefined} segmentTimeline
  6766. * Contains a list of atrributes for each S node within the SegmentTimeline node
  6767. * @property {Object|undefined} list
  6768. * Contains the attributes for the SegmentList node
  6769. * @property {Object|undefined} base
  6770. * Contains the attributes for the SegmentBase node
  6771. */
  6772. /**
  6773. * Returns all available Segment information contained within the AdaptationSet node
  6774. *
  6775. * @param {Node} adaptationSet
  6776. * The AdaptationSet node to get Segment information from
  6777. * @return {SegmentInformation}
  6778. * The Segment information contained within the provided AdaptationSet
  6779. */
  6780. const getSegmentInformation = adaptationSet => {
  6781. const segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  6782. const segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  6783. const segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(s => merge({
  6784. tag: 'SegmentURL'
  6785. }, parseAttributes(s)));
  6786. const segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  6787. const segmentTimelineParentNode = segmentList || segmentTemplate;
  6788. const segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  6789. const segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  6790. const segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  6791. // @initialization and an <Initialization> node. @initialization can be templated,
  6792. // while the node can have a url and range specified. If the <SegmentTemplate> has
  6793. // both @initialization and an <Initialization> subelement we opt to override with
  6794. // the node, as this interaction is not defined in the spec.
  6795. const template = segmentTemplate && parseAttributes(segmentTemplate);
  6796. if (template && segmentInitialization) {
  6797. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  6798. } else if (template && template.initialization) {
  6799. // If it is @initialization we convert it to an object since this is the format that
  6800. // later functions will rely on for the initialization segment. This is only valid
  6801. // for <SegmentTemplate>
  6802. template.initialization = {
  6803. sourceURL: template.initialization
  6804. };
  6805. }
  6806. const segmentInfo = {
  6807. template,
  6808. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(s => parseAttributes(s)),
  6809. list: segmentList && merge(parseAttributes(segmentList), {
  6810. segmentUrls,
  6811. initialization: parseAttributes(segmentInitialization)
  6812. }),
  6813. base: segmentBase && merge(parseAttributes(segmentBase), {
  6814. initialization: parseAttributes(segmentInitialization)
  6815. })
  6816. };
  6817. Object.keys(segmentInfo).forEach(key => {
  6818. if (!segmentInfo[key]) {
  6819. delete segmentInfo[key];
  6820. }
  6821. });
  6822. return segmentInfo;
  6823. };
  6824. /**
  6825. * Contains Segment information and attributes needed to construct a Playlist object
  6826. * from a Representation
  6827. *
  6828. * @typedef {Object} RepresentationInformation
  6829. * @property {SegmentInformation} segmentInfo
  6830. * Segment information for this Representation
  6831. * @property {Object} attributes
  6832. * Inherited attributes for this Representation
  6833. */
  6834. /**
  6835. * Maps a Representation node to an object containing Segment information and attributes
  6836. *
  6837. * @name inheritBaseUrlsCallback
  6838. * @function
  6839. * @param {Node} representation
  6840. * Representation node from the mpd
  6841. * @return {RepresentationInformation}
  6842. * Representation information needed to construct a Playlist object
  6843. */
  6844. /**
  6845. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  6846. * Segment information and attributes using inherited BaseURL nodes.
  6847. *
  6848. * @param {Object} adaptationSetAttributes
  6849. * Contains attributes inherited by the AdaptationSet
  6850. * @param {Object[]} adaptationSetBaseUrls
  6851. * List of objects containing resolved base URLs and attributes
  6852. * inherited by the AdaptationSet
  6853. * @param {SegmentInformation} adaptationSetSegmentInfo
  6854. * Contains Segment information for the AdaptationSet
  6855. * @return {inheritBaseUrlsCallback}
  6856. * Callback map function
  6857. */
  6858. const inheritBaseUrls = (adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) => representation => {
  6859. const repBaseUrlElements = findChildren(representation, 'BaseURL');
  6860. const repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  6861. const attributes = merge(adaptationSetAttributes, parseAttributes(representation));
  6862. const representationSegmentInfo = getSegmentInformation(representation);
  6863. return repBaseUrls.map(baseUrl => {
  6864. return {
  6865. segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
  6866. attributes: merge(attributes, baseUrl)
  6867. };
  6868. });
  6869. };
  6870. /**
  6871. * Tranforms a series of content protection nodes to
  6872. * an object containing pssh data by key system
  6873. *
  6874. * @param {Node[]} contentProtectionNodes
  6875. * Content protection nodes
  6876. * @return {Object}
  6877. * Object containing pssh data by key system
  6878. */
  6879. const generateKeySystemInformation = contentProtectionNodes => {
  6880. return contentProtectionNodes.reduce((acc, node) => {
  6881. 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
  6882. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  6883. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  6884. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  6885. if (attributes.schemeIdUri) {
  6886. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  6887. }
  6888. const keySystem = keySystemsMap[attributes.schemeIdUri];
  6889. if (keySystem) {
  6890. acc[keySystem] = {
  6891. attributes
  6892. };
  6893. const psshNode = findChildren(node, 'cenc:pssh')[0];
  6894. if (psshNode) {
  6895. const pssh = getContent(psshNode);
  6896. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  6897. }
  6898. }
  6899. return acc;
  6900. }, {});
  6901. }; // defined in ANSI_SCTE 214-1 2016
  6902. const parseCaptionServiceMetadata = service => {
  6903. // 608 captions
  6904. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  6905. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6906. return values.map(value => {
  6907. let channel;
  6908. let language; // default language to value
  6909. language = value;
  6910. if (/^CC\d=/.test(value)) {
  6911. [channel, language] = value.split('=');
  6912. } else if (/^CC\d$/.test(value)) {
  6913. channel = value;
  6914. }
  6915. return {
  6916. channel,
  6917. language
  6918. };
  6919. });
  6920. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  6921. const values = typeof service.value !== 'string' ? [] : service.value.split(';');
  6922. return values.map(value => {
  6923. const flags = {
  6924. // service or channel number 1-63
  6925. 'channel': undefined,
  6926. // language is a 3ALPHA per ISO 639.2/B
  6927. // field is required
  6928. 'language': undefined,
  6929. // BIT 1/0 or ?
  6930. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  6931. 'aspectRatio': 1,
  6932. // BIT 1/0
  6933. // easy reader flag indicated the text is tailed to the needs of beginning readers
  6934. // default 0, or off
  6935. 'easyReader': 0,
  6936. // BIT 1/0
  6937. // If 3d metadata is present (CEA-708.1) then 1
  6938. // default 0
  6939. '3D': 0
  6940. };
  6941. if (/=/.test(value)) {
  6942. const [channel, opts = ''] = value.split('=');
  6943. flags.channel = channel;
  6944. flags.language = value;
  6945. opts.split(',').forEach(opt => {
  6946. const [name, val] = opt.split(':');
  6947. if (name === 'lang') {
  6948. flags.language = val; // er for easyReadery
  6949. } else if (name === 'er') {
  6950. flags.easyReader = Number(val); // war for wide aspect ratio
  6951. } else if (name === 'war') {
  6952. flags.aspectRatio = Number(val);
  6953. } else if (name === '3D') {
  6954. flags['3D'] = Number(val);
  6955. }
  6956. });
  6957. } else {
  6958. flags.language = value;
  6959. }
  6960. if (flags.channel) {
  6961. flags.channel = 'SERVICE' + flags.channel;
  6962. }
  6963. return flags;
  6964. });
  6965. }
  6966. };
  6967. /**
  6968. * A map callback that will parse all event stream data for a collection of periods
  6969. * DASH ISO_IEC_23009 5.10.2.2
  6970. * https://dashif-documents.azurewebsites.net/Events/master/event.html#mpd-event-timing
  6971. *
  6972. * @param {PeriodInformation} period object containing necessary period information
  6973. * @return a collection of parsed eventstream event objects
  6974. */
  6975. const toEventStream = period => {
  6976. // get and flatten all EventStreams tags and parse attributes and children
  6977. return flatten(findChildren(period.node, 'EventStream').map(eventStream => {
  6978. const eventStreamAttributes = parseAttributes(eventStream);
  6979. const schemeIdUri = eventStreamAttributes.schemeIdUri; // find all Events per EventStream tag and map to return objects
  6980. return findChildren(eventStream, 'Event').map(event => {
  6981. const eventAttributes = parseAttributes(event);
  6982. const presentationTime = eventAttributes.presentationTime || 0;
  6983. const timescale = eventStreamAttributes.timescale || 1;
  6984. const duration = eventAttributes.duration || 0;
  6985. const start = presentationTime / timescale + period.attributes.start;
  6986. return {
  6987. schemeIdUri,
  6988. value: eventStreamAttributes.value,
  6989. id: eventAttributes.id,
  6990. start,
  6991. end: start + duration / timescale,
  6992. messageData: getContent(event) || eventAttributes.messageData,
  6993. contentEncoding: eventStreamAttributes.contentEncoding,
  6994. presentationTimeOffset: eventStreamAttributes.presentationTimeOffset || 0
  6995. };
  6996. });
  6997. }));
  6998. };
  6999. /**
  7000. * Maps an AdaptationSet node to a list of Representation information objects
  7001. *
  7002. * @name toRepresentationsCallback
  7003. * @function
  7004. * @param {Node} adaptationSet
  7005. * AdaptationSet node from the mpd
  7006. * @return {RepresentationInformation[]}
  7007. * List of objects containing Representaion information
  7008. */
  7009. /**
  7010. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  7011. * Representation information objects
  7012. *
  7013. * @param {Object} periodAttributes
  7014. * Contains attributes inherited by the Period
  7015. * @param {Object[]} periodBaseUrls
  7016. * Contains list of objects with resolved base urls and attributes
  7017. * inherited by the Period
  7018. * @param {string[]} periodSegmentInfo
  7019. * Contains Segment Information at the period level
  7020. * @return {toRepresentationsCallback}
  7021. * Callback map function
  7022. */
  7023. const toRepresentations = (periodAttributes, periodBaseUrls, periodSegmentInfo) => adaptationSet => {
  7024. const adaptationSetAttributes = parseAttributes(adaptationSet);
  7025. const adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  7026. const role = findChildren(adaptationSet, 'Role')[0];
  7027. const roleAttributes = {
  7028. role: parseAttributes(role)
  7029. };
  7030. let attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
  7031. const accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  7032. const captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  7033. if (captionServices) {
  7034. attrs = merge(attrs, {
  7035. captionServices
  7036. });
  7037. }
  7038. const label = findChildren(adaptationSet, 'Label')[0];
  7039. if (label && label.childNodes.length) {
  7040. const labelVal = label.childNodes[0].nodeValue.trim();
  7041. attrs = merge(attrs, {
  7042. label: labelVal
  7043. });
  7044. }
  7045. const contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  7046. if (Object.keys(contentProtection).length) {
  7047. attrs = merge(attrs, {
  7048. contentProtection
  7049. });
  7050. }
  7051. const segmentInfo = getSegmentInformation(adaptationSet);
  7052. const representations = findChildren(adaptationSet, 'Representation');
  7053. const adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
  7054. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  7055. };
  7056. /**
  7057. * Contains all period information for mapping nodes onto adaptation sets.
  7058. *
  7059. * @typedef {Object} PeriodInformation
  7060. * @property {Node} period.node
  7061. * Period node from the mpd
  7062. * @property {Object} period.attributes
  7063. * Parsed period attributes from node plus any added
  7064. */
  7065. /**
  7066. * Maps a PeriodInformation object to a list of Representation information objects for all
  7067. * AdaptationSet nodes contained within the Period.
  7068. *
  7069. * @name toAdaptationSetsCallback
  7070. * @function
  7071. * @param {PeriodInformation} period
  7072. * Period object containing necessary period information
  7073. * @param {number} periodStart
  7074. * Start time of the Period within the mpd
  7075. * @return {RepresentationInformation[]}
  7076. * List of objects containing Representaion information
  7077. */
  7078. /**
  7079. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  7080. * Representation information objects
  7081. *
  7082. * @param {Object} mpdAttributes
  7083. * Contains attributes inherited by the mpd
  7084. * @param {Object[]} mpdBaseUrls
  7085. * Contains list of objects with resolved base urls and attributes
  7086. * inherited by the mpd
  7087. * @return {toAdaptationSetsCallback}
  7088. * Callback map function
  7089. */
  7090. const toAdaptationSets = (mpdAttributes, mpdBaseUrls) => (period, index) => {
  7091. const periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  7092. const periodAttributes = merge(mpdAttributes, {
  7093. periodStart: period.attributes.start
  7094. });
  7095. if (typeof period.attributes.duration === 'number') {
  7096. periodAttributes.periodDuration = period.attributes.duration;
  7097. }
  7098. const adaptationSets = findChildren(period.node, 'AdaptationSet');
  7099. const periodSegmentInfo = getSegmentInformation(period.node);
  7100. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  7101. };
  7102. /**
  7103. * Tranforms an array of content steering nodes into an object
  7104. * containing CDN content steering information from the MPD manifest.
  7105. *
  7106. * For more information on the DASH spec for Content Steering parsing, see:
  7107. * https://dashif.org/docs/DASH-IF-CTS-00XX-Content-Steering-Community-Review.pdf
  7108. *
  7109. * @param {Node[]} contentSteeringNodes
  7110. * Content steering nodes
  7111. * @param {Function} eventHandler
  7112. * The event handler passed into the parser options to handle warnings
  7113. * @return {Object}
  7114. * Object containing content steering data
  7115. */
  7116. const generateContentSteeringInformation = (contentSteeringNodes, eventHandler) => {
  7117. // If there are more than one ContentSteering tags, throw an error
  7118. if (contentSteeringNodes.length > 1) {
  7119. eventHandler({
  7120. type: 'warn',
  7121. message: 'The MPD manifest should contain no more than one ContentSteering tag'
  7122. });
  7123. } // Return a null value if there are no ContentSteering tags
  7124. if (!contentSteeringNodes.length) {
  7125. return null;
  7126. }
  7127. const infoFromContentSteeringTag = merge({
  7128. serverURL: getContent(contentSteeringNodes[0])
  7129. }, parseAttributes(contentSteeringNodes[0])); // Converts `queryBeforeStart` to a boolean, as well as setting the default value
  7130. // to `false` if it doesn't exist
  7131. infoFromContentSteeringTag.queryBeforeStart = infoFromContentSteeringTag.queryBeforeStart === 'true';
  7132. return infoFromContentSteeringTag;
  7133. };
  7134. /**
  7135. * Gets Period@start property for a given period.
  7136. *
  7137. * @param {Object} options
  7138. * Options object
  7139. * @param {Object} options.attributes
  7140. * Period attributes
  7141. * @param {Object} [options.priorPeriodAttributes]
  7142. * Prior period attributes (if prior period is available)
  7143. * @param {string} options.mpdType
  7144. * The MPD@type these periods came from
  7145. * @return {number|null}
  7146. * The period start, or null if it's an early available period or error
  7147. */
  7148. const getPeriodStart = ({
  7149. attributes,
  7150. priorPeriodAttributes,
  7151. mpdType
  7152. }) => {
  7153. // Summary of period start time calculation from DASH spec section 5.3.2.1
  7154. //
  7155. // A period's start is the first period's start + time elapsed after playing all
  7156. // prior periods to this one. Periods continue one after the other in time (without
  7157. // gaps) until the end of the presentation.
  7158. //
  7159. // The value of Period@start should be:
  7160. // 1. if Period@start is present: value of Period@start
  7161. // 2. if previous period exists and it has @duration: previous Period@start +
  7162. // previous Period@duration
  7163. // 3. if this is first period and MPD@type is 'static': 0
  7164. // 4. in all other cases, consider the period an "early available period" (note: not
  7165. // currently supported)
  7166. // (1)
  7167. if (typeof attributes.start === 'number') {
  7168. return attributes.start;
  7169. } // (2)
  7170. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  7171. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  7172. } // (3)
  7173. if (!priorPeriodAttributes && mpdType === 'static') {
  7174. return 0;
  7175. } // (4)
  7176. // There is currently no logic for calculating the Period@start value if there is
  7177. // no Period@start or prior Period@start and Period@duration available. This is not made
  7178. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  7179. // nothing about any other resolution strategies, it's implied. Thus, this case should
  7180. // be considered an early available period, or error, and null should suffice for both
  7181. // of those cases.
  7182. return null;
  7183. };
  7184. /**
  7185. * Traverses the mpd xml tree to generate a list of Representation information objects
  7186. * that have inherited attributes from parent nodes
  7187. *
  7188. * @param {Node} mpd
  7189. * The root node of the mpd
  7190. * @param {Object} options
  7191. * Available options for inheritAttributes
  7192. * @param {string} options.manifestUri
  7193. * The uri source of the mpd
  7194. * @param {number} options.NOW
  7195. * Current time per DASH IOP. Default is current time in ms since epoch
  7196. * @param {number} options.clientOffset
  7197. * Client time difference from NOW (in milliseconds)
  7198. * @return {RepresentationInformation[]}
  7199. * List of objects containing Representation information
  7200. */
  7201. const inheritAttributes = (mpd, options = {}) => {
  7202. const {
  7203. manifestUri = '',
  7204. NOW = Date.now(),
  7205. clientOffset = 0,
  7206. // TODO: For now, we are expecting an eventHandler callback function
  7207. // to be passed into the mpd parser as an option.
  7208. // In the future, we should enable stream parsing by using the Stream class from vhs-utils.
  7209. // This will support new features including a standardized event handler.
  7210. // See the m3u8 parser for examples of how stream parsing is currently used for HLS parsing.
  7211. // https://github.com/videojs/vhs-utils/blob/88d6e10c631e57a5af02c5a62bc7376cd456b4f5/src/stream.js#L9
  7212. eventHandler = function () {}
  7213. } = options;
  7214. const periodNodes = findChildren(mpd, 'Period');
  7215. if (!periodNodes.length) {
  7216. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  7217. }
  7218. const locations = findChildren(mpd, 'Location');
  7219. const mpdAttributes = parseAttributes(mpd);
  7220. const mpdBaseUrls = buildBaseUrls([{
  7221. baseUrl: manifestUri
  7222. }], findChildren(mpd, 'BaseURL'));
  7223. const contentSteeringNodes = findChildren(mpd, 'ContentSteering'); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  7224. mpdAttributes.type = mpdAttributes.type || 'static';
  7225. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  7226. mpdAttributes.NOW = NOW;
  7227. mpdAttributes.clientOffset = clientOffset;
  7228. if (locations.length) {
  7229. mpdAttributes.locations = locations.map(getContent);
  7230. }
  7231. const periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  7232. // adding properties that require looking at prior periods is to parse attributes and add
  7233. // missing ones before toAdaptationSets is called. If more such properties are added, it
  7234. // may be better to refactor toAdaptationSets.
  7235. periodNodes.forEach((node, index) => {
  7236. const attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  7237. // for this period.
  7238. const priorPeriod = periods[index - 1];
  7239. attributes.start = getPeriodStart({
  7240. attributes,
  7241. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  7242. mpdType: mpdAttributes.type
  7243. });
  7244. periods.push({
  7245. node,
  7246. attributes
  7247. });
  7248. });
  7249. return {
  7250. locations: mpdAttributes.locations,
  7251. contentSteeringInfo: generateContentSteeringInformation(contentSteeringNodes, eventHandler),
  7252. // TODO: There are occurences where this `representationInfo` array contains undesired
  7253. // duplicates. This generally occurs when there are multiple BaseURL nodes that are
  7254. // direct children of the MPD node. When we attempt to resolve URLs from a combination of the
  7255. // parent BaseURL and a child BaseURL, and the value does not resolve,
  7256. // we end up returning the child BaseURL multiple times.
  7257. // We need to determine a way to remove these duplicates in a safe way.
  7258. // See: https://github.com/videojs/mpd-parser/pull/17#discussion_r162750527
  7259. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls))),
  7260. eventStream: flatten(periods.map(toEventStream))
  7261. };
  7262. };
  7263. const stringToMpdXml = manifestString => {
  7264. if (manifestString === '') {
  7265. throw new Error(errors.DASH_EMPTY_MANIFEST);
  7266. }
  7267. const parser = new xmldom.DOMParser();
  7268. let xml;
  7269. let mpd;
  7270. try {
  7271. xml = parser.parseFromString(manifestString, 'application/xml');
  7272. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  7273. } catch (e) {// ie 11 throws on invalid xml
  7274. }
  7275. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  7276. throw new Error(errors.DASH_INVALID_XML);
  7277. }
  7278. return mpd;
  7279. };
  7280. /**
  7281. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  7282. *
  7283. * @param {string} mpd
  7284. * XML string of the MPD manifest
  7285. * @return {Object|null}
  7286. * Attributes of UTCTiming node specified in the manifest. Null if none found
  7287. */
  7288. const parseUTCTimingScheme = mpd => {
  7289. const UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  7290. if (!UTCTimingNode) {
  7291. return null;
  7292. }
  7293. const attributes = parseAttributes(UTCTimingNode);
  7294. switch (attributes.schemeIdUri) {
  7295. case 'urn:mpeg:dash:utc:http-head:2014':
  7296. case 'urn:mpeg:dash:utc:http-head:2012':
  7297. attributes.method = 'HEAD';
  7298. break;
  7299. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  7300. case 'urn:mpeg:dash:utc:http-iso:2014':
  7301. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  7302. case 'urn:mpeg:dash:utc:http-iso:2012':
  7303. attributes.method = 'GET';
  7304. break;
  7305. case 'urn:mpeg:dash:utc:direct:2014':
  7306. case 'urn:mpeg:dash:utc:direct:2012':
  7307. attributes.method = 'DIRECT';
  7308. attributes.value = Date.parse(attributes.value);
  7309. break;
  7310. case 'urn:mpeg:dash:utc:http-ntp:2014':
  7311. case 'urn:mpeg:dash:utc:ntp:2014':
  7312. case 'urn:mpeg:dash:utc:sntp:2014':
  7313. default:
  7314. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  7315. }
  7316. return attributes;
  7317. };
  7318. /*
  7319. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  7320. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  7321. *
  7322. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  7323. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  7324. * updated to reflect its position relative to the prior manifest.
  7325. *
  7326. * @param {string} manifestString - the DASH manifest as a string
  7327. * @param {options} [options] - any options
  7328. *
  7329. * @return {Object} the manifest object
  7330. */
  7331. const parse = (manifestString, options = {}) => {
  7332. const parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  7333. const playlists = toPlaylists(parsedManifestInfo.representationInfo);
  7334. return toM3u8({
  7335. dashPlaylists: playlists,
  7336. locations: parsedManifestInfo.locations,
  7337. contentSteering: parsedManifestInfo.contentSteeringInfo,
  7338. sidxMapping: options.sidxMapping,
  7339. previousManifest: options.previousManifest,
  7340. eventStream: parsedManifestInfo.eventStream
  7341. });
  7342. };
  7343. /**
  7344. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  7345. *
  7346. * @param {string} manifestString
  7347. * XML string of the MPD manifest
  7348. * @return {Object|null}
  7349. * Attributes of UTCTiming node specified in the manifest. Null if none found
  7350. */
  7351. const parseUTCTiming = manifestString => parseUTCTimingScheme(stringToMpdXml(manifestString));
  7352. var MAX_UINT32 = Math.pow(2, 32);
  7353. var getUint64$1 = function (uint8) {
  7354. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  7355. var value;
  7356. if (dv.getBigUint64) {
  7357. value = dv.getBigUint64(0);
  7358. if (value < Number.MAX_SAFE_INTEGER) {
  7359. return Number(value);
  7360. }
  7361. return value;
  7362. }
  7363. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  7364. };
  7365. var numbers = {
  7366. getUint64: getUint64$1,
  7367. MAX_UINT32: MAX_UINT32
  7368. };
  7369. var getUint64 = numbers.getUint64;
  7370. var parseSidx = function (data) {
  7371. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  7372. result = {
  7373. version: data[0],
  7374. flags: new Uint8Array(data.subarray(1, 4)),
  7375. references: [],
  7376. referenceId: view.getUint32(4),
  7377. timescale: view.getUint32(8)
  7378. },
  7379. i = 12;
  7380. if (result.version === 0) {
  7381. result.earliestPresentationTime = view.getUint32(i);
  7382. result.firstOffset = view.getUint32(i + 4);
  7383. i += 8;
  7384. } else {
  7385. // read 64 bits
  7386. result.earliestPresentationTime = getUint64(data.subarray(i));
  7387. result.firstOffset = getUint64(data.subarray(i + 8));
  7388. i += 16;
  7389. }
  7390. i += 2; // reserved
  7391. var referenceCount = view.getUint16(i);
  7392. i += 2; // start of references
  7393. for (; referenceCount > 0; i += 12, referenceCount--) {
  7394. result.references.push({
  7395. referenceType: (data[i] & 0x80) >>> 7,
  7396. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  7397. subsegmentDuration: view.getUint32(i + 4),
  7398. startsWithSap: !!(data[i + 8] & 0x80),
  7399. sapType: (data[i + 8] & 0x70) >>> 4,
  7400. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  7401. });
  7402. }
  7403. return result;
  7404. };
  7405. var parseSidx_1 = parseSidx;
  7406. var ID3 = toUint8([0x49, 0x44, 0x33]);
  7407. var getId3Size = function getId3Size(bytes, offset) {
  7408. if (offset === void 0) {
  7409. offset = 0;
  7410. }
  7411. bytes = toUint8(bytes);
  7412. var flags = bytes[offset + 5];
  7413. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  7414. var footerPresent = (flags & 16) >> 4;
  7415. if (footerPresent) {
  7416. return returnSize + 20;
  7417. }
  7418. return returnSize + 10;
  7419. };
  7420. var getId3Offset = function getId3Offset(bytes, offset) {
  7421. if (offset === void 0) {
  7422. offset = 0;
  7423. }
  7424. bytes = toUint8(bytes);
  7425. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  7426. offset: offset
  7427. })) {
  7428. return offset;
  7429. }
  7430. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  7431. // have multiple ID3 tag sections even though
  7432. // they should not.
  7433. return getId3Offset(bytes, offset);
  7434. };
  7435. var normalizePath$1 = function normalizePath(path) {
  7436. if (typeof path === 'string') {
  7437. return stringToBytes(path);
  7438. }
  7439. if (typeof path === 'number') {
  7440. return path;
  7441. }
  7442. return path;
  7443. };
  7444. var normalizePaths$1 = function normalizePaths(paths) {
  7445. if (!Array.isArray(paths)) {
  7446. return [normalizePath$1(paths)];
  7447. }
  7448. return paths.map(function (p) {
  7449. return normalizePath$1(p);
  7450. });
  7451. };
  7452. /**
  7453. * find any number of boxes by name given a path to it in an iso bmff
  7454. * such as mp4.
  7455. *
  7456. * @param {TypedArray} bytes
  7457. * bytes for the iso bmff to search for boxes in
  7458. *
  7459. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  7460. * An array of paths or a single path representing the name
  7461. * of boxes to search through in bytes. Paths may be
  7462. * uint8 (character codes) or strings.
  7463. *
  7464. * @param {boolean} [complete=false]
  7465. * Should we search only for complete boxes on the final path.
  7466. * This is very useful when you do not want to get back partial boxes
  7467. * in the case of streaming files.
  7468. *
  7469. * @return {Uint8Array[]}
  7470. * An array of the end paths that we found.
  7471. */
  7472. var findBox = function findBox(bytes, paths, complete) {
  7473. if (complete === void 0) {
  7474. complete = false;
  7475. }
  7476. paths = normalizePaths$1(paths);
  7477. bytes = toUint8(bytes);
  7478. var results = [];
  7479. if (!paths.length) {
  7480. // short-circuit the search for empty paths
  7481. return results;
  7482. }
  7483. var i = 0;
  7484. while (i < bytes.length) {
  7485. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  7486. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  7487. if (size === 0) {
  7488. break;
  7489. }
  7490. var end = i + size;
  7491. if (end > bytes.length) {
  7492. // this box is bigger than the number of bytes we have
  7493. // and complete is set, we cannot find any more boxes.
  7494. if (complete) {
  7495. break;
  7496. }
  7497. end = bytes.length;
  7498. }
  7499. var data = bytes.subarray(i + 8, end);
  7500. if (bytesMatch(type, paths[0])) {
  7501. if (paths.length === 1) {
  7502. // this is the end of the path and we've found the box we were
  7503. // looking for
  7504. results.push(data);
  7505. } else {
  7506. // recursively search for the next box along the path
  7507. results.push.apply(results, findBox(data, paths.slice(1), complete));
  7508. }
  7509. }
  7510. i = end;
  7511. } // we've finished searching all of bytes
  7512. return results;
  7513. };
  7514. // https://matroska-org.github.io/libebml/specs.html
  7515. // https://www.matroska.org/technical/elements.html
  7516. // https://www.webmproject.org/docs/container/
  7517. var EBML_TAGS = {
  7518. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  7519. DocType: toUint8([0x42, 0x82]),
  7520. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  7521. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  7522. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  7523. Track: toUint8([0xAE]),
  7524. TrackNumber: toUint8([0xd7]),
  7525. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  7526. TrackEntry: toUint8([0xAE]),
  7527. TrackType: toUint8([0x83]),
  7528. FlagDefault: toUint8([0x88]),
  7529. CodecID: toUint8([0x86]),
  7530. CodecPrivate: toUint8([0x63, 0xA2]),
  7531. VideoTrack: toUint8([0xe0]),
  7532. AudioTrack: toUint8([0xe1]),
  7533. // Not used yet, but will be used for live webm/mkv
  7534. // see https://www.matroska.org/technical/basics.html#block-structure
  7535. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  7536. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  7537. Timestamp: toUint8([0xE7]),
  7538. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  7539. BlockGroup: toUint8([0xA0]),
  7540. BlockDuration: toUint8([0x9B]),
  7541. Block: toUint8([0xA1]),
  7542. SimpleBlock: toUint8([0xA3])
  7543. };
  7544. /**
  7545. * This is a simple table to determine the length
  7546. * of things in ebml. The length is one based (starts at 1,
  7547. * rather than zero) and for every zero bit before a one bit
  7548. * we add one to length. We also need this table because in some
  7549. * case we have to xor all the length bits from another value.
  7550. */
  7551. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  7552. var getLength = function getLength(byte) {
  7553. var len = 1;
  7554. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  7555. if (byte & LENGTH_TABLE[i]) {
  7556. break;
  7557. }
  7558. len++;
  7559. }
  7560. return len;
  7561. }; // length in ebml is stored in the first 4 to 8 bits
  7562. // of the first byte. 4 for the id length and 8 for the
  7563. // data size length. Length is measured by converting the number to binary
  7564. // then 1 + the number of zeros before a 1 is encountered starting
  7565. // from the left.
  7566. var getvint = function getvint(bytes, offset, removeLength, signed) {
  7567. if (removeLength === void 0) {
  7568. removeLength = true;
  7569. }
  7570. if (signed === void 0) {
  7571. signed = false;
  7572. }
  7573. var length = getLength(bytes[offset]);
  7574. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  7575. // as they will be modified below to remove the dataSizeLen bits and we do not
  7576. // want to modify the original data. normally we could just call slice on
  7577. // uint8array but ie 11 does not support that...
  7578. if (removeLength) {
  7579. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  7580. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  7581. }
  7582. return {
  7583. length: length,
  7584. value: bytesToNumber(valueBytes, {
  7585. signed: signed
  7586. }),
  7587. bytes: valueBytes
  7588. };
  7589. };
  7590. var normalizePath = function normalizePath(path) {
  7591. if (typeof path === 'string') {
  7592. return path.match(/.{1,2}/g).map(function (p) {
  7593. return normalizePath(p);
  7594. });
  7595. }
  7596. if (typeof path === 'number') {
  7597. return numberToBytes(path);
  7598. }
  7599. return path;
  7600. };
  7601. var normalizePaths = function normalizePaths(paths) {
  7602. if (!Array.isArray(paths)) {
  7603. return [normalizePath(paths)];
  7604. }
  7605. return paths.map(function (p) {
  7606. return normalizePath(p);
  7607. });
  7608. };
  7609. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  7610. if (offset >= bytes.length) {
  7611. return bytes.length;
  7612. }
  7613. var innerid = getvint(bytes, offset, false);
  7614. if (bytesMatch(id.bytes, innerid.bytes)) {
  7615. return offset;
  7616. }
  7617. var dataHeader = getvint(bytes, offset + innerid.length);
  7618. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  7619. };
  7620. /**
  7621. * Notes on the EBLM format.
  7622. *
  7623. * EBLM uses "vints" tags. Every vint tag contains
  7624. * two parts
  7625. *
  7626. * 1. The length from the first byte. You get this by
  7627. * converting the byte to binary and counting the zeros
  7628. * before a 1. Then you add 1 to that. Examples
  7629. * 00011111 = length 4 because there are 3 zeros before a 1.
  7630. * 00100000 = length 3 because there are 2 zeros before a 1.
  7631. * 00000011 = length 7 because there are 6 zeros before a 1.
  7632. *
  7633. * 2. The bits used for length are removed from the first byte
  7634. * Then all the bytes are merged into a value. NOTE: this
  7635. * is not the case for id ebml tags as there id includes
  7636. * length bits.
  7637. *
  7638. */
  7639. var findEbml = function findEbml(bytes, paths) {
  7640. paths = normalizePaths(paths);
  7641. bytes = toUint8(bytes);
  7642. var results = [];
  7643. if (!paths.length) {
  7644. return results;
  7645. }
  7646. var i = 0;
  7647. while (i < bytes.length) {
  7648. var id = getvint(bytes, i, false);
  7649. var dataHeader = getvint(bytes, i + id.length);
  7650. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  7651. if (dataHeader.value === 0x7f) {
  7652. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  7653. if (dataHeader.value !== bytes.length) {
  7654. dataHeader.value -= dataStart;
  7655. }
  7656. }
  7657. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  7658. var data = bytes.subarray(dataStart, dataEnd);
  7659. if (bytesMatch(paths[0], id.bytes)) {
  7660. if (paths.length === 1) {
  7661. // this is the end of the paths and we've found the tag we were
  7662. // looking for
  7663. results.push(data);
  7664. } else {
  7665. // recursively search for the next tag inside of the data
  7666. // of this one
  7667. results = results.concat(findEbml(data, paths.slice(1)));
  7668. }
  7669. }
  7670. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  7671. i += totalLength;
  7672. }
  7673. return results;
  7674. }; // see https://www.matroska.org/technical/basics.html#block-structure
  7675. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  7676. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  7677. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  7678. /**
  7679. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  7680. * Sequence Payload"
  7681. *
  7682. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  7683. * unit
  7684. * @return {Uint8Array} the RBSP without any Emulation
  7685. * Prevention Bytes
  7686. */
  7687. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  7688. var positions = [];
  7689. var i = 1; // Find all `Emulation Prevention Bytes`
  7690. while (i < bytes.length - 2) {
  7691. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  7692. positions.push(i + 2);
  7693. i++;
  7694. }
  7695. i++;
  7696. } // If no Emulation Prevention Bytes were found just return the original
  7697. // array
  7698. if (positions.length === 0) {
  7699. return bytes;
  7700. } // Create a new array to hold the NAL unit data
  7701. var newLength = bytes.length - positions.length;
  7702. var newData = new Uint8Array(newLength);
  7703. var sourceIndex = 0;
  7704. for (i = 0; i < newLength; sourceIndex++, i++) {
  7705. if (sourceIndex === positions[0]) {
  7706. // Skip this byte
  7707. sourceIndex++; // Remove this position index
  7708. positions.shift();
  7709. }
  7710. newData[i] = bytes[sourceIndex];
  7711. }
  7712. return newData;
  7713. };
  7714. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  7715. if (nalLimit === void 0) {
  7716. nalLimit = Infinity;
  7717. }
  7718. bytes = toUint8(bytes);
  7719. types = [].concat(types);
  7720. var i = 0;
  7721. var nalStart;
  7722. var nalsFound = 0; // keep searching until:
  7723. // we reach the end of bytes
  7724. // we reach the maximum number of nals they want to seach
  7725. // NOTE: that we disregard nalLimit when we have found the start
  7726. // of the nal we want so that we can find the end of the nal we want.
  7727. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  7728. var nalOffset = void 0;
  7729. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  7730. nalOffset = 4;
  7731. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  7732. nalOffset = 3;
  7733. } // we are unsynced,
  7734. // find the next nal unit
  7735. if (!nalOffset) {
  7736. i++;
  7737. continue;
  7738. }
  7739. nalsFound++;
  7740. if (nalStart) {
  7741. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  7742. }
  7743. var nalType = void 0;
  7744. if (dataType === 'h264') {
  7745. nalType = bytes[i + nalOffset] & 0x1f;
  7746. } else if (dataType === 'h265') {
  7747. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  7748. }
  7749. if (types.indexOf(nalType) !== -1) {
  7750. nalStart = i + nalOffset;
  7751. } // nal header is 1 length for h264, and 2 for h265
  7752. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  7753. }
  7754. return bytes.subarray(0, 0);
  7755. };
  7756. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  7757. return findNal(bytes, 'h264', type, nalLimit);
  7758. };
  7759. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  7760. return findNal(bytes, 'h265', type, nalLimit);
  7761. };
  7762. var CONSTANTS = {
  7763. // "webm" string literal in hex
  7764. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  7765. // "matroska" string literal in hex
  7766. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  7767. // "fLaC" string literal in hex
  7768. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  7769. // "OggS" string literal in hex
  7770. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  7771. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  7772. // of ac-3
  7773. 'ac3': toUint8([0x0b, 0x77]),
  7774. // "RIFF" string literal in hex used for wav and avi
  7775. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  7776. // "AVI" string literal in hex
  7777. 'avi': toUint8([0x41, 0x56, 0x49]),
  7778. // "WAVE" string literal in hex
  7779. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  7780. // "ftyp3g" string literal in hex
  7781. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  7782. // "ftyp" string literal in hex
  7783. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  7784. // "styp" string literal in hex
  7785. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  7786. // "ftypqt" string literal in hex
  7787. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  7788. // moov string literal in hex
  7789. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  7790. // moof string literal in hex
  7791. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  7792. };
  7793. var _isLikely = {
  7794. aac: function aac(bytes) {
  7795. var offset = getId3Offset(bytes);
  7796. return bytesMatch(bytes, [0xFF, 0x10], {
  7797. offset: offset,
  7798. mask: [0xFF, 0x16]
  7799. });
  7800. },
  7801. mp3: function mp3(bytes) {
  7802. var offset = getId3Offset(bytes);
  7803. return bytesMatch(bytes, [0xFF, 0x02], {
  7804. offset: offset,
  7805. mask: [0xFF, 0x06]
  7806. });
  7807. },
  7808. webm: function webm(bytes) {
  7809. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  7810. return bytesMatch(docType, CONSTANTS.webm);
  7811. },
  7812. mkv: function mkv(bytes) {
  7813. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  7814. return bytesMatch(docType, CONSTANTS.matroska);
  7815. },
  7816. mp4: function mp4(bytes) {
  7817. // if this file is another base media file format, it is not mp4
  7818. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  7819. return false;
  7820. } // if this file starts with a ftyp or styp box its mp4
  7821. if (bytesMatch(bytes, CONSTANTS.mp4, {
  7822. offset: 4
  7823. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  7824. offset: 4
  7825. })) {
  7826. return true;
  7827. } // if this file starts with a moof/moov box its mp4
  7828. if (bytesMatch(bytes, CONSTANTS.moof, {
  7829. offset: 4
  7830. }) || bytesMatch(bytes, CONSTANTS.moov, {
  7831. offset: 4
  7832. })) {
  7833. return true;
  7834. }
  7835. },
  7836. mov: function mov(bytes) {
  7837. return bytesMatch(bytes, CONSTANTS.mov, {
  7838. offset: 4
  7839. });
  7840. },
  7841. '3gp': function gp(bytes) {
  7842. return bytesMatch(bytes, CONSTANTS['3gp'], {
  7843. offset: 4
  7844. });
  7845. },
  7846. ac3: function ac3(bytes) {
  7847. var offset = getId3Offset(bytes);
  7848. return bytesMatch(bytes, CONSTANTS.ac3, {
  7849. offset: offset
  7850. });
  7851. },
  7852. ts: function ts(bytes) {
  7853. if (bytes.length < 189 && bytes.length >= 1) {
  7854. return bytes[0] === 0x47;
  7855. }
  7856. var i = 0; // check the first 376 bytes for two matching sync bytes
  7857. while (i + 188 < bytes.length && i < 188) {
  7858. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  7859. return true;
  7860. }
  7861. i += 1;
  7862. }
  7863. return false;
  7864. },
  7865. flac: function flac(bytes) {
  7866. var offset = getId3Offset(bytes);
  7867. return bytesMatch(bytes, CONSTANTS.flac, {
  7868. offset: offset
  7869. });
  7870. },
  7871. ogg: function ogg(bytes) {
  7872. return bytesMatch(bytes, CONSTANTS.ogg);
  7873. },
  7874. avi: function avi(bytes) {
  7875. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  7876. offset: 8
  7877. });
  7878. },
  7879. wav: function wav(bytes) {
  7880. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  7881. offset: 8
  7882. });
  7883. },
  7884. 'h264': function h264(bytes) {
  7885. // find seq_parameter_set_rbsp
  7886. return findH264Nal(bytes, 7, 3).length;
  7887. },
  7888. 'h265': function h265(bytes) {
  7889. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  7890. return findH265Nal(bytes, [32, 33], 3).length;
  7891. }
  7892. }; // get all the isLikely functions
  7893. // but make sure 'ts' is above h264 and h265
  7894. // but below everything else as it is the least specific
  7895. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  7896. .filter(function (t) {
  7897. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  7898. }) // add it back to the bottom
  7899. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  7900. isLikelyTypes.forEach(function (type) {
  7901. var isLikelyFn = _isLikely[type];
  7902. _isLikely[type] = function (bytes) {
  7903. return isLikelyFn(toUint8(bytes));
  7904. };
  7905. }); // export after wrapping
  7906. var isLikely = _isLikely; // A useful list of file signatures can be found here
  7907. // https://en.wikipedia.org/wiki/List_of_file_signatures
  7908. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  7909. bytes = toUint8(bytes);
  7910. for (var i = 0; i < isLikelyTypes.length; i++) {
  7911. var type = isLikelyTypes[i];
  7912. if (isLikely[type](bytes)) {
  7913. return type;
  7914. }
  7915. }
  7916. return '';
  7917. }; // fmp4 is not a container
  7918. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  7919. return findBox(bytes, ['moof']).length > 0;
  7920. };
  7921. // which will only happen if the request is complete.
  7922. const callbackOnCompleted = (request, cb) => {
  7923. if (request.readyState === 4) {
  7924. return cb();
  7925. }
  7926. return;
  7927. };
  7928. const containerRequest = (uri, xhr, cb) => {
  7929. let bytes = [];
  7930. let id3Offset;
  7931. let finished = false;
  7932. const endRequestAndCallback = function (err, req, type, _bytes) {
  7933. req.abort();
  7934. finished = true;
  7935. return cb(err, req, type, _bytes);
  7936. };
  7937. const progressListener = function (error, request) {
  7938. if (finished) {
  7939. return;
  7940. }
  7941. if (error) {
  7942. return endRequestAndCallback(error, request, '', bytes);
  7943. } // grap the new part of content that was just downloaded
  7944. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  7945. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  7946. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  7947. // or we need at least two bytes after an id3Offset
  7948. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  7949. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7950. }
  7951. const type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  7952. // to see the second sync byte, wait until we have enough data
  7953. // before declaring it ts
  7954. if (type === 'ts' && bytes.length < 188) {
  7955. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7956. } // this may be an unsynced ts segment
  7957. // wait for 376 bytes before detecting no container
  7958. if (!type && bytes.length < 376) {
  7959. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  7960. }
  7961. return endRequestAndCallback(null, request, type, bytes);
  7962. };
  7963. const options = {
  7964. uri,
  7965. beforeSend(request) {
  7966. // this forces the browser to pass the bytes to us unprocessed
  7967. request.overrideMimeType('text/plain; charset=x-user-defined');
  7968. request.addEventListener('progress', function ({
  7969. total,
  7970. loaded
  7971. }) {
  7972. return callbackWrapper(request, null, {
  7973. statusCode: request.status
  7974. }, progressListener);
  7975. });
  7976. }
  7977. };
  7978. const request = xhr(options, function (error, response) {
  7979. return callbackWrapper(request, error, response, progressListener);
  7980. });
  7981. return request;
  7982. };
  7983. const {
  7984. EventTarget
  7985. } = videojs__default["default"];
  7986. const dashPlaylistUnchanged = function (a, b) {
  7987. if (!isPlaylistUnchanged(a, b)) {
  7988. return false;
  7989. } // for dash the above check will often return true in scenarios where
  7990. // the playlist actually has changed because mediaSequence isn't a
  7991. // dash thing, and we often set it to 1. So if the playlists have the same amount
  7992. // of segments we return true.
  7993. // So for dash we need to make sure that the underlying segments are different.
  7994. // if sidx changed then the playlists are different.
  7995. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  7996. return false;
  7997. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  7998. return false;
  7999. } // one or the other does not have segments
  8000. // there was a change.
  8001. if (a.segments && !b.segments || !a.segments && b.segments) {
  8002. return false;
  8003. } // neither has segments nothing changed
  8004. if (!a.segments && !b.segments) {
  8005. return true;
  8006. } // check segments themselves
  8007. for (let i = 0; i < a.segments.length; i++) {
  8008. const aSegment = a.segments[i];
  8009. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  8010. if (aSegment.uri !== bSegment.uri) {
  8011. return false;
  8012. } // neither segment has a byterange, there will be no byterange change.
  8013. if (!aSegment.byterange && !bSegment.byterange) {
  8014. continue;
  8015. }
  8016. const aByterange = aSegment.byterange;
  8017. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  8018. if (aByterange && !bByterange || !aByterange && bByterange) {
  8019. return false;
  8020. } // if both segments have byterange with different offsets, there was a change.
  8021. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  8022. return false;
  8023. }
  8024. } // if everything was the same with segments, this is the same playlist.
  8025. return true;
  8026. };
  8027. /**
  8028. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  8029. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  8030. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  8031. * periods without continuous playback this function may need modification as well as the parser.
  8032. */
  8033. const dashGroupId = (type, group, label, playlist) => {
  8034. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  8035. const playlistId = playlist.attributes.NAME || label;
  8036. return `placeholder-uri-${type}-${group}-${playlistId}`;
  8037. };
  8038. /**
  8039. * Parses the main XML string and updates playlist URI references.
  8040. *
  8041. * @param {Object} config
  8042. * Object of arguments
  8043. * @param {string} config.mainXml
  8044. * The mpd XML
  8045. * @param {string} config.srcUrl
  8046. * The mpd URL
  8047. * @param {Date} config.clientOffset
  8048. * A time difference between server and client
  8049. * @param {Object} config.sidxMapping
  8050. * SIDX mappings for moof/mdat URIs and byte ranges
  8051. * @return {Object}
  8052. * The parsed mpd manifest object
  8053. */
  8054. const parseMainXml = ({
  8055. mainXml,
  8056. srcUrl,
  8057. clientOffset,
  8058. sidxMapping,
  8059. previousManifest
  8060. }) => {
  8061. const manifest = parse(mainXml, {
  8062. manifestUri: srcUrl,
  8063. clientOffset,
  8064. sidxMapping,
  8065. previousManifest
  8066. });
  8067. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  8068. return manifest;
  8069. };
  8070. /**
  8071. * Removes any mediaGroup labels that no longer exist in the newMain
  8072. *
  8073. * @param {Object} update
  8074. * The previous mpd object being updated
  8075. * @param {Object} newMain
  8076. * The new mpd object
  8077. */
  8078. const removeOldMediaGroupLabels = (update, newMain) => {
  8079. forEachMediaGroup$1(update, (properties, type, group, label) => {
  8080. if (!(label in newMain.mediaGroups[type][group])) {
  8081. delete update.mediaGroups[type][group][label];
  8082. }
  8083. });
  8084. };
  8085. /**
  8086. * Returns a new main manifest that is the result of merging an updated main manifest
  8087. * into the original version.
  8088. *
  8089. * @param {Object} oldMain
  8090. * The old parsed mpd object
  8091. * @param {Object} newMain
  8092. * The updated parsed mpd object
  8093. * @return {Object}
  8094. * A new object representing the original main manifest with the updated media
  8095. * playlists merged in
  8096. */
  8097. const updateMain = (oldMain, newMain, sidxMapping) => {
  8098. let noChanges = true;
  8099. let update = merge$1(oldMain, {
  8100. // These are top level properties that can be updated
  8101. duration: newMain.duration,
  8102. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  8103. timelineStarts: newMain.timelineStarts
  8104. }); // First update the playlists in playlist list
  8105. for (let i = 0; i < newMain.playlists.length; i++) {
  8106. const playlist = newMain.playlists[i];
  8107. if (playlist.sidx) {
  8108. const sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  8109. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  8110. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  8111. }
  8112. }
  8113. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  8114. if (playlistUpdate) {
  8115. update = playlistUpdate;
  8116. noChanges = false;
  8117. }
  8118. } // Then update media group playlists
  8119. forEachMediaGroup$1(newMain, (properties, type, group, label) => {
  8120. if (properties.playlists && properties.playlists.length) {
  8121. const id = properties.playlists[0].id;
  8122. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  8123. if (playlistUpdate) {
  8124. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  8125. if (!(label in update.mediaGroups[type][group])) {
  8126. update.mediaGroups[type][group][label] = properties;
  8127. } // update the playlist reference within media groups
  8128. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  8129. noChanges = false;
  8130. }
  8131. }
  8132. }); // remove mediaGroup labels and references that no longer exist in the newMain
  8133. removeOldMediaGroupLabels(update, newMain);
  8134. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  8135. noChanges = false;
  8136. }
  8137. if (noChanges) {
  8138. return null;
  8139. }
  8140. return update;
  8141. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  8142. // If the SIDXs have maps, the two maps should match,
  8143. // both `a` and `b` missing SIDXs is considered matching.
  8144. // If `a` or `b` but not both have a map, they aren't matching.
  8145. const equivalentSidx = (a, b) => {
  8146. const neitherMap = Boolean(!a.map && !b.map);
  8147. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  8148. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  8149. }; // exported for testing
  8150. const compareSidxEntry = (playlists, oldSidxMapping) => {
  8151. const newSidxMapping = {};
  8152. for (const id in playlists) {
  8153. const playlist = playlists[id];
  8154. const currentSidxInfo = playlist.sidx;
  8155. if (currentSidxInfo) {
  8156. const key = generateSidxKey(currentSidxInfo);
  8157. if (!oldSidxMapping[key]) {
  8158. break;
  8159. }
  8160. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  8161. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  8162. newSidxMapping[key] = oldSidxMapping[key];
  8163. }
  8164. }
  8165. }
  8166. return newSidxMapping;
  8167. };
  8168. /**
  8169. * A function that filters out changed items as they need to be requested separately.
  8170. *
  8171. * The method is exported for testing
  8172. *
  8173. * @param {Object} main the parsed mpd XML returned via mpd-parser
  8174. * @param {Object} oldSidxMapping the SIDX to compare against
  8175. */
  8176. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  8177. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  8178. let mediaGroupSidx = videoSidx;
  8179. forEachMediaGroup$1(main, (properties, mediaType, groupKey, labelKey) => {
  8180. if (properties.playlists && properties.playlists.length) {
  8181. const playlists = properties.playlists;
  8182. mediaGroupSidx = merge$1(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  8183. }
  8184. });
  8185. return mediaGroupSidx;
  8186. };
  8187. class DashPlaylistLoader extends EventTarget {
  8188. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  8189. // playlist loader setups from media groups will expect to be able to pass a playlist
  8190. // (since there aren't external URLs to media playlists with DASH)
  8191. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  8192. super();
  8193. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  8194. if (!mainPlaylistLoader) {
  8195. this.isMain_ = true;
  8196. }
  8197. const {
  8198. withCredentials = false
  8199. } = options;
  8200. this.vhs_ = vhs;
  8201. this.withCredentials = withCredentials;
  8202. this.addMetadataToTextTrack = options.addMetadataToTextTrack;
  8203. if (!srcUrlOrPlaylist) {
  8204. throw new Error('A non-empty playlist URL or object is required');
  8205. } // event naming?
  8206. this.on('minimumUpdatePeriod', () => {
  8207. this.refreshXml_();
  8208. }); // live playlist staleness timeout
  8209. this.on('mediaupdatetimeout', () => {
  8210. this.refreshMedia_(this.media().id);
  8211. });
  8212. this.state = 'HAVE_NOTHING';
  8213. this.loadedPlaylists_ = {};
  8214. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  8215. // The mainPlaylistLoader will be created with a string
  8216. if (this.isMain_) {
  8217. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  8218. // once multi-period is refactored
  8219. this.mainPlaylistLoader_.sidxMapping_ = {};
  8220. } else {
  8221. this.childPlaylist_ = srcUrlOrPlaylist;
  8222. }
  8223. }
  8224. requestErrored_(err, request, startingState) {
  8225. // disposed
  8226. if (!this.request) {
  8227. return true;
  8228. } // pending request is cleared
  8229. this.request = null;
  8230. if (err) {
  8231. // use the provided error object or create one
  8232. // based on the request/response
  8233. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  8234. status: request.status,
  8235. message: 'DASH request error at URL: ' + request.uri,
  8236. response: request.response,
  8237. // MEDIA_ERR_NETWORK
  8238. code: 2
  8239. };
  8240. if (startingState) {
  8241. this.state = startingState;
  8242. }
  8243. this.trigger('error');
  8244. return true;
  8245. }
  8246. }
  8247. /**
  8248. * Verify that the container of the sidx segment can be parsed
  8249. * and if it can, get and parse that segment.
  8250. */
  8251. addSidxSegments_(playlist, startingState, cb) {
  8252. const sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  8253. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  8254. // keep this function async
  8255. this.mediaRequest_ = window.setTimeout(() => cb(false), 0);
  8256. return;
  8257. } // resolve the segment URL relative to the playlist
  8258. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  8259. const fin = (err, request) => {
  8260. if (this.requestErrored_(err, request, startingState)) {
  8261. return;
  8262. }
  8263. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  8264. let sidx;
  8265. try {
  8266. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  8267. } catch (e) {
  8268. // sidx parsing failed.
  8269. this.requestErrored_(e, request, startingState);
  8270. return;
  8271. }
  8272. sidxMapping[sidxKey] = {
  8273. sidxInfo: playlist.sidx,
  8274. sidx
  8275. };
  8276. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  8277. return cb(true);
  8278. };
  8279. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  8280. if (err) {
  8281. return fin(err, request);
  8282. }
  8283. if (!container || container !== 'mp4') {
  8284. return fin({
  8285. status: request.status,
  8286. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  8287. // response is just bytes in this case
  8288. // but we really don't want to return that.
  8289. response: '',
  8290. playlist,
  8291. internal: true,
  8292. playlistExclusionDuration: Infinity,
  8293. // MEDIA_ERR_NETWORK
  8294. code: 2
  8295. }, request);
  8296. } // if we already downloaded the sidx bytes in the container request, use them
  8297. const {
  8298. offset,
  8299. length
  8300. } = playlist.sidx.byterange;
  8301. if (bytes.length >= length + offset) {
  8302. return fin(err, {
  8303. response: bytes.subarray(offset, offset + length),
  8304. status: request.status,
  8305. uri: request.uri
  8306. });
  8307. } // otherwise request sidx bytes
  8308. this.request = this.vhs_.xhr({
  8309. uri,
  8310. responseType: 'arraybuffer',
  8311. headers: segmentXhrHeaders({
  8312. byterange: playlist.sidx.byterange
  8313. })
  8314. }, fin);
  8315. });
  8316. }
  8317. dispose() {
  8318. this.trigger('dispose');
  8319. this.stopRequest();
  8320. this.loadedPlaylists_ = {};
  8321. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  8322. window.clearTimeout(this.mediaRequest_);
  8323. window.clearTimeout(this.mediaUpdateTimeout);
  8324. this.mediaUpdateTimeout = null;
  8325. this.mediaRequest_ = null;
  8326. this.minimumUpdatePeriodTimeout_ = null;
  8327. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  8328. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  8329. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  8330. }
  8331. this.off();
  8332. }
  8333. hasPendingRequest() {
  8334. return this.request || this.mediaRequest_;
  8335. }
  8336. stopRequest() {
  8337. if (this.request) {
  8338. const oldRequest = this.request;
  8339. this.request = null;
  8340. oldRequest.onreadystatechange = null;
  8341. oldRequest.abort();
  8342. }
  8343. }
  8344. media(playlist) {
  8345. // getter
  8346. if (!playlist) {
  8347. return this.media_;
  8348. } // setter
  8349. if (this.state === 'HAVE_NOTHING') {
  8350. throw new Error('Cannot switch media playlist from ' + this.state);
  8351. }
  8352. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  8353. if (typeof playlist === 'string') {
  8354. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  8355. throw new Error('Unknown playlist URI: ' + playlist);
  8356. }
  8357. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  8358. }
  8359. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  8360. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  8361. this.state = 'HAVE_METADATA';
  8362. this.media_ = playlist; // trigger media change if the active media has been updated
  8363. if (mediaChange) {
  8364. this.trigger('mediachanging');
  8365. this.trigger('mediachange');
  8366. }
  8367. return;
  8368. } // switching to the active playlist is a no-op
  8369. if (!mediaChange) {
  8370. return;
  8371. } // switching from an already loaded playlist
  8372. if (this.media_) {
  8373. this.trigger('mediachanging');
  8374. }
  8375. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  8376. // everything is ready just continue to haveMetadata
  8377. this.haveMetadata({
  8378. startingState,
  8379. playlist
  8380. });
  8381. });
  8382. }
  8383. haveMetadata({
  8384. startingState,
  8385. playlist
  8386. }) {
  8387. this.state = 'HAVE_METADATA';
  8388. this.loadedPlaylists_[playlist.id] = playlist;
  8389. this.mediaRequest_ = null; // This will trigger loadedplaylist
  8390. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  8391. // to resolve setup of media groups
  8392. if (startingState === 'HAVE_MAIN_MANIFEST') {
  8393. this.trigger('loadedmetadata');
  8394. } else {
  8395. // trigger media change if the active media has been updated
  8396. this.trigger('mediachange');
  8397. }
  8398. }
  8399. pause() {
  8400. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  8401. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  8402. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  8403. }
  8404. this.stopRequest();
  8405. window.clearTimeout(this.mediaUpdateTimeout);
  8406. this.mediaUpdateTimeout = null;
  8407. if (this.isMain_) {
  8408. window.clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  8409. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  8410. }
  8411. if (this.state === 'HAVE_NOTHING') {
  8412. // If we pause the loader before any data has been retrieved, its as if we never
  8413. // started, so reset to an unstarted state.
  8414. this.started = false;
  8415. }
  8416. }
  8417. load(isFinalRendition) {
  8418. window.clearTimeout(this.mediaUpdateTimeout);
  8419. this.mediaUpdateTimeout = null;
  8420. const media = this.media();
  8421. if (isFinalRendition) {
  8422. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  8423. this.mediaUpdateTimeout = window.setTimeout(() => this.load(), delay);
  8424. return;
  8425. } // because the playlists are internal to the manifest, load should either load the
  8426. // main manifest, or do nothing but trigger an event
  8427. if (!this.started) {
  8428. this.start();
  8429. return;
  8430. }
  8431. if (media && !media.endList) {
  8432. // Check to see if this is the main loader and the MUP was cleared (this happens
  8433. // when the loader was paused). `media` should be set at this point since one is always
  8434. // set during `start()`.
  8435. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  8436. // Trigger minimumUpdatePeriod to refresh the main manifest
  8437. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  8438. this.updateMinimumUpdatePeriodTimeout_();
  8439. }
  8440. this.trigger('mediaupdatetimeout');
  8441. } else {
  8442. this.trigger('loadedplaylist');
  8443. }
  8444. }
  8445. start() {
  8446. this.started = true; // We don't need to request the main manifest again
  8447. // Call this asynchronously to match the xhr request behavior below
  8448. if (!this.isMain_) {
  8449. this.mediaRequest_ = window.setTimeout(() => this.haveMain_(), 0);
  8450. return;
  8451. }
  8452. this.requestMain_((req, mainChanged) => {
  8453. this.haveMain_();
  8454. if (!this.hasPendingRequest() && !this.media_) {
  8455. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  8456. }
  8457. });
  8458. }
  8459. requestMain_(cb) {
  8460. this.request = this.vhs_.xhr({
  8461. uri: this.mainPlaylistLoader_.srcUrl,
  8462. withCredentials: this.withCredentials
  8463. }, (error, req) => {
  8464. if (this.requestErrored_(error, req)) {
  8465. if (this.state === 'HAVE_NOTHING') {
  8466. this.started = false;
  8467. }
  8468. return;
  8469. }
  8470. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  8471. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  8472. if (req.responseHeaders && req.responseHeaders.date) {
  8473. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  8474. } else {
  8475. this.mainLoaded_ = Date.now();
  8476. }
  8477. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  8478. if (mainChanged) {
  8479. this.handleMain_();
  8480. this.syncClientServerClock_(() => {
  8481. return cb(req, mainChanged);
  8482. });
  8483. return;
  8484. }
  8485. return cb(req, mainChanged);
  8486. });
  8487. }
  8488. /**
  8489. * Parses the main xml for UTCTiming node to sync the client clock to the server
  8490. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  8491. *
  8492. * @param {Function} done
  8493. * Function to call when clock sync has completed
  8494. */
  8495. syncClientServerClock_(done) {
  8496. const utcTiming = parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  8497. // server clock
  8498. if (utcTiming === null) {
  8499. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  8500. return done();
  8501. }
  8502. if (utcTiming.method === 'DIRECT') {
  8503. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  8504. return done();
  8505. }
  8506. this.request = this.vhs_.xhr({
  8507. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  8508. method: utcTiming.method,
  8509. withCredentials: this.withCredentials
  8510. }, (error, req) => {
  8511. // disposed
  8512. if (!this.request) {
  8513. return;
  8514. }
  8515. if (error) {
  8516. // sync request failed, fall back to using date header from mpd
  8517. // TODO: log warning
  8518. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  8519. return done();
  8520. }
  8521. let serverTime;
  8522. if (utcTiming.method === 'HEAD') {
  8523. if (!req.responseHeaders || !req.responseHeaders.date) {
  8524. // expected date header not preset, fall back to using date header from mpd
  8525. // TODO: log warning
  8526. serverTime = this.mainLoaded_;
  8527. } else {
  8528. serverTime = Date.parse(req.responseHeaders.date);
  8529. }
  8530. } else {
  8531. serverTime = Date.parse(req.responseText);
  8532. }
  8533. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  8534. done();
  8535. });
  8536. }
  8537. haveMain_() {
  8538. this.state = 'HAVE_MAIN_MANIFEST';
  8539. if (this.isMain_) {
  8540. // We have the main playlist at this point, so
  8541. // trigger this to allow PlaylistController
  8542. // to make an initial playlist selection
  8543. this.trigger('loadedplaylist');
  8544. } else if (!this.media_) {
  8545. // no media playlist was specifically selected so select
  8546. // the one the child playlist loader was created with
  8547. this.media(this.childPlaylist_);
  8548. }
  8549. }
  8550. handleMain_() {
  8551. // clear media request
  8552. this.mediaRequest_ = null;
  8553. const oldMain = this.mainPlaylistLoader_.main;
  8554. let newMain = parseMainXml({
  8555. mainXml: this.mainPlaylistLoader_.mainXml_,
  8556. srcUrl: this.mainPlaylistLoader_.srcUrl,
  8557. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  8558. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  8559. previousManifest: oldMain
  8560. }); // if we have an old main to compare the new main against
  8561. if (oldMain) {
  8562. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  8563. } // only update main if we have a new main
  8564. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  8565. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  8566. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  8567. this.mainPlaylistLoader_.srcUrl = location;
  8568. }
  8569. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  8570. this.updateMinimumUpdatePeriodTimeout_();
  8571. }
  8572. this.addEventStreamToMetadataTrack_(newMain);
  8573. return Boolean(newMain);
  8574. }
  8575. updateMinimumUpdatePeriodTimeout_() {
  8576. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  8577. // a new one will be added if needed.
  8578. if (mpl.createMupOnMedia_) {
  8579. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  8580. mpl.createMupOnMedia_ = null;
  8581. } // clear any pending timeouts
  8582. if (mpl.minimumUpdatePeriodTimeout_) {
  8583. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  8584. mpl.minimumUpdatePeriodTimeout_ = null;
  8585. }
  8586. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  8587. // MPD has no future validity, so a new one will need to be acquired when new
  8588. // media segments are to be made available. Thus, we use the target duration
  8589. // in this case
  8590. if (mup === 0) {
  8591. if (mpl.media()) {
  8592. mup = mpl.media().targetDuration * 1000;
  8593. } else {
  8594. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  8595. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  8596. }
  8597. } // if minimumUpdatePeriod is invalid or <= zero, which
  8598. // can happen when a live video becomes VOD. skip timeout
  8599. // creation.
  8600. if (typeof mup !== 'number' || mup <= 0) {
  8601. if (mup < 0) {
  8602. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  8603. }
  8604. return;
  8605. }
  8606. this.createMUPTimeout_(mup);
  8607. }
  8608. createMUPTimeout_(mup) {
  8609. const mpl = this.mainPlaylistLoader_;
  8610. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(() => {
  8611. mpl.minimumUpdatePeriodTimeout_ = null;
  8612. mpl.trigger('minimumUpdatePeriod');
  8613. mpl.createMUPTimeout_(mup);
  8614. }, mup);
  8615. }
  8616. /**
  8617. * Sends request to refresh the main xml and updates the parsed main manifest
  8618. */
  8619. refreshXml_() {
  8620. this.requestMain_((req, mainChanged) => {
  8621. if (!mainChanged) {
  8622. return;
  8623. }
  8624. if (this.media_) {
  8625. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  8626. } // This will filter out updated sidx info from the mapping
  8627. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  8628. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  8629. // TODO: do we need to reload the current playlist?
  8630. this.refreshMedia_(this.media().id);
  8631. });
  8632. });
  8633. }
  8634. /**
  8635. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  8636. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  8637. * from the main loader.
  8638. */
  8639. refreshMedia_(mediaID) {
  8640. if (!mediaID) {
  8641. throw new Error('refreshMedia_ must take a media id');
  8642. } // for main we have to reparse the main xml
  8643. // to re-create segments based on current timing values
  8644. // which may change media. We only skip updating the main manifest
  8645. // if this is the first time this.media_ is being set.
  8646. // as main was just parsed in that case.
  8647. if (this.media_ && this.isMain_) {
  8648. this.handleMain_();
  8649. }
  8650. const playlists = this.mainPlaylistLoader_.main.playlists;
  8651. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  8652. if (mediaChanged) {
  8653. this.media_ = playlists[mediaID];
  8654. } else {
  8655. this.trigger('playlistunchanged');
  8656. }
  8657. if (!this.mediaUpdateTimeout) {
  8658. const createMediaUpdateTimeout = () => {
  8659. if (this.media().endList) {
  8660. return;
  8661. }
  8662. this.mediaUpdateTimeout = window.setTimeout(() => {
  8663. this.trigger('mediaupdatetimeout');
  8664. createMediaUpdateTimeout();
  8665. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  8666. };
  8667. createMediaUpdateTimeout();
  8668. }
  8669. this.trigger('loadedplaylist');
  8670. }
  8671. /**
  8672. * Takes eventstream data from a parsed DASH manifest and adds it to the metadata text track.
  8673. *
  8674. * @param {manifest} newMain the newly parsed manifest
  8675. */
  8676. addEventStreamToMetadataTrack_(newMain) {
  8677. // Only add new event stream metadata if we have a new manifest.
  8678. if (newMain && this.mainPlaylistLoader_.main.eventStream) {
  8679. // convert EventStream to ID3-like data.
  8680. const metadataArray = this.mainPlaylistLoader_.main.eventStream.map(eventStreamNode => {
  8681. return {
  8682. cueTime: eventStreamNode.start,
  8683. frames: [{
  8684. data: eventStreamNode.messageData
  8685. }]
  8686. };
  8687. });
  8688. this.addMetadataToTextTrack('EventStream', metadataArray, this.mainPlaylistLoader_.main.duration);
  8689. }
  8690. }
  8691. /**
  8692. * Returns the key ID set from a playlist
  8693. *
  8694. * @param {playlist} playlist to fetch the key ID set from.
  8695. * @return a Set of 32 digit hex strings that represent the unique keyIds for that playlist.
  8696. */
  8697. getKeyIdSet(playlist) {
  8698. if (playlist.contentProtection) {
  8699. const keyIds = new Set();
  8700. for (const keysystem in playlist.contentProtection) {
  8701. const defaultKID = playlist.contentProtection[keysystem].attributes['cenc:default_KID'];
  8702. if (defaultKID) {
  8703. // DASH keyIds are separated by dashes.
  8704. keyIds.add(defaultKID.replace(/-/g, '').toLowerCase());
  8705. }
  8706. }
  8707. return keyIds;
  8708. }
  8709. }
  8710. }
  8711. var Config = {
  8712. GOAL_BUFFER_LENGTH: 30,
  8713. MAX_GOAL_BUFFER_LENGTH: 60,
  8714. BACK_BUFFER_LENGTH: 30,
  8715. GOAL_BUFFER_LENGTH_RATE: 1,
  8716. // 0.5 MB/s
  8717. INITIAL_BANDWIDTH: 4194304,
  8718. // A fudge factor to apply to advertised playlist bitrates to account for
  8719. // temporary flucations in client bandwidth
  8720. BANDWIDTH_VARIANCE: 1.2,
  8721. // How much of the buffer must be filled before we consider upswitching
  8722. BUFFER_LOW_WATER_LINE: 0,
  8723. MAX_BUFFER_LOW_WATER_LINE: 30,
  8724. // TODO: Remove this when experimentalBufferBasedABR is removed
  8725. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  8726. BUFFER_LOW_WATER_LINE_RATE: 1,
  8727. // If the buffer is greater than the high water line, we won't switch down
  8728. BUFFER_HIGH_WATER_LINE: 30
  8729. };
  8730. const stringToArrayBuffer = string => {
  8731. const view = new Uint8Array(new ArrayBuffer(string.length));
  8732. for (let i = 0; i < string.length; i++) {
  8733. view[i] = string.charCodeAt(i);
  8734. }
  8735. return view.buffer;
  8736. };
  8737. class MockWorker {
  8738. constructor() {
  8739. this.listeners_ = [];
  8740. this.onmessage = null;
  8741. this.remote_ = null;
  8742. }
  8743. addEventListener(type, fn) {
  8744. if (type !== 'message') {
  8745. return;
  8746. }
  8747. this.listeners_.push(fn);
  8748. }
  8749. removeEventListener(type, fn) {
  8750. if (type !== 'message') {
  8751. return;
  8752. }
  8753. const i = this.listeners_.indexOf(fn);
  8754. if (i === -1) {
  8755. return;
  8756. }
  8757. this.listeners_.splice(i, 1);
  8758. }
  8759. dispatchEvent(event) {
  8760. if (!event || event.type !== 'message') {
  8761. return;
  8762. }
  8763. if (this.onmessage) {
  8764. this.onmessage(event);
  8765. }
  8766. this.listeners_.forEach(function (fn) {
  8767. fn(event);
  8768. });
  8769. }
  8770. postMessage(data) {
  8771. if (this.remote_) {
  8772. this.remote_.recv_(data);
  8773. }
  8774. }
  8775. recv_(data) {
  8776. // the browser puts the actual message under
  8777. const message = {
  8778. data
  8779. };
  8780. if (this.onmessage) {
  8781. this.onmessage(message);
  8782. }
  8783. this.listeners_.forEach(function (fn) {
  8784. fn(message);
  8785. });
  8786. }
  8787. terminate() {
  8788. if (this.remote_) {
  8789. this.remote_.remote_ = null;
  8790. this.remote_.terminate();
  8791. this.remote_ = null;
  8792. }
  8793. this.onmessage = null;
  8794. this.listeners_.length = 0;
  8795. }
  8796. }
  8797. MockWorker.prototype.on = MockWorker.prototype.addEventListener;
  8798. MockWorker.prototype.off = MockWorker.prototype.removeEventListener;
  8799. const factory = function (fn) {
  8800. return function () {
  8801. const client = new MockWorker();
  8802. const worker = new MockWorker();
  8803. client.type_ = 'window api';
  8804. client.remote_ = worker;
  8805. worker.remote_ = client;
  8806. worker.type_ = 'web worker';
  8807. fn(worker);
  8808. return client;
  8809. };
  8810. };
  8811. const transform = function (fn) {
  8812. // eslint-disable-next-line
  8813. return fn;
  8814. };
  8815. /* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
  8816. const workerCode$1 = transform(function (self) {
  8817. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  8818. /**
  8819. * mux.js
  8820. *
  8821. * Copyright (c) Brightcove
  8822. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8823. *
  8824. * A lightweight readable stream implemention that handles event dispatching.
  8825. * Objects that inherit from streams should call init in their constructors.
  8826. */
  8827. var Stream$8 = function () {
  8828. this.init = function () {
  8829. var listeners = {};
  8830. /**
  8831. * Add a listener for a specified event type.
  8832. * @param type {string} the event name
  8833. * @param listener {function} the callback to be invoked when an event of
  8834. * the specified type occurs
  8835. */
  8836. this.on = function (type, listener) {
  8837. if (!listeners[type]) {
  8838. listeners[type] = [];
  8839. }
  8840. listeners[type] = listeners[type].concat(listener);
  8841. };
  8842. /**
  8843. * Remove a listener for a specified event type.
  8844. * @param type {string} the event name
  8845. * @param listener {function} a function previously registered for this
  8846. * type of event through `on`
  8847. */
  8848. this.off = function (type, listener) {
  8849. var index;
  8850. if (!listeners[type]) {
  8851. return false;
  8852. }
  8853. index = listeners[type].indexOf(listener);
  8854. listeners[type] = listeners[type].slice();
  8855. listeners[type].splice(index, 1);
  8856. return index > -1;
  8857. };
  8858. /**
  8859. * Trigger an event of the specified type on this stream. Any additional
  8860. * arguments to this function are passed as parameters to event listeners.
  8861. * @param type {string} the event name
  8862. */
  8863. this.trigger = function (type) {
  8864. var callbacks, i, length, args;
  8865. callbacks = listeners[type];
  8866. if (!callbacks) {
  8867. return;
  8868. } // Slicing the arguments on every invocation of this method
  8869. // can add a significant amount of overhead. Avoid the
  8870. // intermediate object creation for the common case of a
  8871. // single callback argument
  8872. if (arguments.length === 2) {
  8873. length = callbacks.length;
  8874. for (i = 0; i < length; ++i) {
  8875. callbacks[i].call(this, arguments[1]);
  8876. }
  8877. } else {
  8878. args = [];
  8879. i = arguments.length;
  8880. for (i = 1; i < arguments.length; ++i) {
  8881. args.push(arguments[i]);
  8882. }
  8883. length = callbacks.length;
  8884. for (i = 0; i < length; ++i) {
  8885. callbacks[i].apply(this, args);
  8886. }
  8887. }
  8888. };
  8889. /**
  8890. * Destroys the stream and cleans up.
  8891. */
  8892. this.dispose = function () {
  8893. listeners = {};
  8894. };
  8895. };
  8896. };
  8897. /**
  8898. * Forwards all `data` events on this stream to the destination stream. The
  8899. * destination stream should provide a method `push` to receive the data
  8900. * events as they arrive.
  8901. * @param destination {stream} the stream that will receive all `data` events
  8902. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  8903. * when the current stream emits a 'done' event
  8904. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  8905. */
  8906. Stream$8.prototype.pipe = function (destination) {
  8907. this.on('data', function (data) {
  8908. destination.push(data);
  8909. });
  8910. this.on('done', function (flushSource) {
  8911. destination.flush(flushSource);
  8912. });
  8913. this.on('partialdone', function (flushSource) {
  8914. destination.partialFlush(flushSource);
  8915. });
  8916. this.on('endedtimeline', function (flushSource) {
  8917. destination.endTimeline(flushSource);
  8918. });
  8919. this.on('reset', function (flushSource) {
  8920. destination.reset(flushSource);
  8921. });
  8922. return destination;
  8923. }; // Default stream functions that are expected to be overridden to perform
  8924. // actual work. These are provided by the prototype as a sort of no-op
  8925. // implementation so that we don't have to check for their existence in the
  8926. // `pipe` function above.
  8927. Stream$8.prototype.push = function (data) {
  8928. this.trigger('data', data);
  8929. };
  8930. Stream$8.prototype.flush = function (flushSource) {
  8931. this.trigger('done', flushSource);
  8932. };
  8933. Stream$8.prototype.partialFlush = function (flushSource) {
  8934. this.trigger('partialdone', flushSource);
  8935. };
  8936. Stream$8.prototype.endTimeline = function (flushSource) {
  8937. this.trigger('endedtimeline', flushSource);
  8938. };
  8939. Stream$8.prototype.reset = function (flushSource) {
  8940. this.trigger('reset', flushSource);
  8941. };
  8942. var stream = Stream$8;
  8943. var MAX_UINT32$1 = Math.pow(2, 32);
  8944. var getUint64$3 = function (uint8) {
  8945. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  8946. var value;
  8947. if (dv.getBigUint64) {
  8948. value = dv.getBigUint64(0);
  8949. if (value < Number.MAX_SAFE_INTEGER) {
  8950. return Number(value);
  8951. }
  8952. return value;
  8953. }
  8954. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  8955. };
  8956. var numbers = {
  8957. getUint64: getUint64$3,
  8958. MAX_UINT32: MAX_UINT32$1
  8959. };
  8960. /**
  8961. * mux.js
  8962. *
  8963. * Copyright (c) Brightcove
  8964. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8965. *
  8966. * Functions that generate fragmented MP4s suitable for use with Media
  8967. * Source Extensions.
  8968. */
  8969. var MAX_UINT32 = numbers.MAX_UINT32;
  8970. 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
  8971. (function () {
  8972. var i;
  8973. types = {
  8974. avc1: [],
  8975. // codingname
  8976. avcC: [],
  8977. btrt: [],
  8978. dinf: [],
  8979. dref: [],
  8980. esds: [],
  8981. ftyp: [],
  8982. hdlr: [],
  8983. mdat: [],
  8984. mdhd: [],
  8985. mdia: [],
  8986. mfhd: [],
  8987. minf: [],
  8988. moof: [],
  8989. moov: [],
  8990. mp4a: [],
  8991. // codingname
  8992. mvex: [],
  8993. mvhd: [],
  8994. pasp: [],
  8995. sdtp: [],
  8996. smhd: [],
  8997. stbl: [],
  8998. stco: [],
  8999. stsc: [],
  9000. stsd: [],
  9001. stsz: [],
  9002. stts: [],
  9003. styp: [],
  9004. tfdt: [],
  9005. tfhd: [],
  9006. traf: [],
  9007. trak: [],
  9008. trun: [],
  9009. trex: [],
  9010. tkhd: [],
  9011. vmhd: []
  9012. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  9013. // don't throw an error
  9014. if (typeof Uint8Array === 'undefined') {
  9015. return;
  9016. }
  9017. for (i in types) {
  9018. if (types.hasOwnProperty(i)) {
  9019. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  9020. }
  9021. }
  9022. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  9023. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  9024. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  9025. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  9026. 0x00, 0x00, 0x00, // flags
  9027. 0x00, 0x00, 0x00, 0x00, // pre_defined
  9028. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  9029. 0x00, 0x00, 0x00, 0x00, // reserved
  9030. 0x00, 0x00, 0x00, 0x00, // reserved
  9031. 0x00, 0x00, 0x00, 0x00, // reserved
  9032. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  9033. ]);
  9034. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  9035. 0x00, 0x00, 0x00, // flags
  9036. 0x00, 0x00, 0x00, 0x00, // pre_defined
  9037. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  9038. 0x00, 0x00, 0x00, 0x00, // reserved
  9039. 0x00, 0x00, 0x00, 0x00, // reserved
  9040. 0x00, 0x00, 0x00, 0x00, // reserved
  9041. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  9042. ]);
  9043. HDLR_TYPES = {
  9044. video: VIDEO_HDLR,
  9045. audio: AUDIO_HDLR
  9046. };
  9047. DREF = new Uint8Array([0x00, // version 0
  9048. 0x00, 0x00, 0x00, // flags
  9049. 0x00, 0x00, 0x00, 0x01, // entry_count
  9050. 0x00, 0x00, 0x00, 0x0c, // entry_size
  9051. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  9052. 0x00, // version 0
  9053. 0x00, 0x00, 0x01 // entry_flags
  9054. ]);
  9055. SMHD = new Uint8Array([0x00, // version
  9056. 0x00, 0x00, 0x00, // flags
  9057. 0x00, 0x00, // balance, 0 means centered
  9058. 0x00, 0x00 // reserved
  9059. ]);
  9060. STCO = new Uint8Array([0x00, // version
  9061. 0x00, 0x00, 0x00, // flags
  9062. 0x00, 0x00, 0x00, 0x00 // entry_count
  9063. ]);
  9064. STSC = STCO;
  9065. STSZ = new Uint8Array([0x00, // version
  9066. 0x00, 0x00, 0x00, // flags
  9067. 0x00, 0x00, 0x00, 0x00, // sample_size
  9068. 0x00, 0x00, 0x00, 0x00 // sample_count
  9069. ]);
  9070. STTS = STCO;
  9071. VMHD = new Uint8Array([0x00, // version
  9072. 0x00, 0x00, 0x01, // flags
  9073. 0x00, 0x00, // graphicsmode
  9074. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  9075. ]);
  9076. })();
  9077. box = function (type) {
  9078. var payload = [],
  9079. size = 0,
  9080. i,
  9081. result,
  9082. view;
  9083. for (i = 1; i < arguments.length; i++) {
  9084. payload.push(arguments[i]);
  9085. }
  9086. i = payload.length; // calculate the total size we need to allocate
  9087. while (i--) {
  9088. size += payload[i].byteLength;
  9089. }
  9090. result = new Uint8Array(size + 8);
  9091. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  9092. view.setUint32(0, result.byteLength);
  9093. result.set(type, 4); // copy the payload into the result
  9094. for (i = 0, size = 8; i < payload.length; i++) {
  9095. result.set(payload[i], size);
  9096. size += payload[i].byteLength;
  9097. }
  9098. return result;
  9099. };
  9100. dinf = function () {
  9101. return box(types.dinf, box(types.dref, DREF));
  9102. };
  9103. esds = function (track) {
  9104. return box(types.esds, new Uint8Array([0x00, // version
  9105. 0x00, 0x00, 0x00, // flags
  9106. // ES_Descriptor
  9107. 0x03, // tag, ES_DescrTag
  9108. 0x19, // length
  9109. 0x00, 0x00, // ES_ID
  9110. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  9111. // DecoderConfigDescriptor
  9112. 0x04, // tag, DecoderConfigDescrTag
  9113. 0x11, // length
  9114. 0x40, // object type
  9115. 0x15, // streamType
  9116. 0x00, 0x06, 0x00, // bufferSizeDB
  9117. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  9118. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  9119. // DecoderSpecificInfo
  9120. 0x05, // tag, DecoderSpecificInfoTag
  9121. 0x02, // length
  9122. // ISO/IEC 14496-3, AudioSpecificConfig
  9123. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  9124. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  9125. ]));
  9126. };
  9127. ftyp = function () {
  9128. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  9129. };
  9130. hdlr = function (type) {
  9131. return box(types.hdlr, HDLR_TYPES[type]);
  9132. };
  9133. mdat = function (data) {
  9134. return box(types.mdat, data);
  9135. };
  9136. mdhd = function (track) {
  9137. var result = new Uint8Array([0x00, // version 0
  9138. 0x00, 0x00, 0x00, // flags
  9139. 0x00, 0x00, 0x00, 0x02, // creation_time
  9140. 0x00, 0x00, 0x00, 0x03, // modification_time
  9141. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  9142. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  9143. 0x55, 0xc4, // 'und' language (undetermined)
  9144. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  9145. // defined. The sample rate can be parsed out of an ADTS header, for
  9146. // instance.
  9147. if (track.samplerate) {
  9148. result[12] = track.samplerate >>> 24 & 0xFF;
  9149. result[13] = track.samplerate >>> 16 & 0xFF;
  9150. result[14] = track.samplerate >>> 8 & 0xFF;
  9151. result[15] = track.samplerate & 0xFF;
  9152. }
  9153. return box(types.mdhd, result);
  9154. };
  9155. mdia = function (track) {
  9156. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  9157. };
  9158. mfhd = function (sequenceNumber) {
  9159. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  9160. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  9161. ]));
  9162. };
  9163. minf = function (track) {
  9164. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  9165. };
  9166. moof = function (sequenceNumber, tracks) {
  9167. var trackFragments = [],
  9168. i = tracks.length; // build traf boxes for each track fragment
  9169. while (i--) {
  9170. trackFragments[i] = traf(tracks[i]);
  9171. }
  9172. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  9173. };
  9174. /**
  9175. * Returns a movie box.
  9176. * @param tracks {array} the tracks associated with this movie
  9177. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  9178. */
  9179. moov = function (tracks) {
  9180. var i = tracks.length,
  9181. boxes = [];
  9182. while (i--) {
  9183. boxes[i] = trak(tracks[i]);
  9184. }
  9185. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  9186. };
  9187. mvex = function (tracks) {
  9188. var i = tracks.length,
  9189. boxes = [];
  9190. while (i--) {
  9191. boxes[i] = trex(tracks[i]);
  9192. }
  9193. return box.apply(null, [types.mvex].concat(boxes));
  9194. };
  9195. mvhd = function (duration) {
  9196. var bytes = new Uint8Array([0x00, // version 0
  9197. 0x00, 0x00, 0x00, // flags
  9198. 0x00, 0x00, 0x00, 0x01, // creation_time
  9199. 0x00, 0x00, 0x00, 0x02, // modification_time
  9200. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  9201. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  9202. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  9203. 0x01, 0x00, // 1.0 volume
  9204. 0x00, 0x00, // reserved
  9205. 0x00, 0x00, 0x00, 0x00, // reserved
  9206. 0x00, 0x00, 0x00, 0x00, // reserved
  9207. 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
  9208. 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
  9209. 0xff, 0xff, 0xff, 0xff // next_track_ID
  9210. ]);
  9211. return box(types.mvhd, bytes);
  9212. };
  9213. sdtp = function (track) {
  9214. var samples = track.samples || [],
  9215. bytes = new Uint8Array(4 + samples.length),
  9216. flags,
  9217. i; // leave the full box header (4 bytes) all zero
  9218. // write the sample table
  9219. for (i = 0; i < samples.length; i++) {
  9220. flags = samples[i].flags;
  9221. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  9222. }
  9223. return box(types.sdtp, bytes);
  9224. };
  9225. stbl = function (track) {
  9226. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  9227. };
  9228. (function () {
  9229. var videoSample, audioSample;
  9230. stsd = function (track) {
  9231. return box(types.stsd, new Uint8Array([0x00, // version 0
  9232. 0x00, 0x00, 0x00, // flags
  9233. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  9234. };
  9235. videoSample = function (track) {
  9236. var sps = track.sps || [],
  9237. pps = track.pps || [],
  9238. sequenceParameterSets = [],
  9239. pictureParameterSets = [],
  9240. i,
  9241. avc1Box; // assemble the SPSs
  9242. for (i = 0; i < sps.length; i++) {
  9243. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  9244. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  9245. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  9246. } // assemble the PPSs
  9247. for (i = 0; i < pps.length; i++) {
  9248. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  9249. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  9250. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  9251. }
  9252. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  9253. 0x00, 0x01, // data_reference_index
  9254. 0x00, 0x00, // pre_defined
  9255. 0x00, 0x00, // reserved
  9256. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  9257. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  9258. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  9259. 0x00, 0x48, 0x00, 0x00, // horizresolution
  9260. 0x00, 0x48, 0x00, 0x00, // vertresolution
  9261. 0x00, 0x00, 0x00, 0x00, // reserved
  9262. 0x00, 0x01, // frame_count
  9263. 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
  9264. 0x00, 0x18, // depth = 24
  9265. 0x11, 0x11 // pre_defined = -1
  9266. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  9267. track.profileIdc, // AVCProfileIndication
  9268. track.profileCompatibility, // profile_compatibility
  9269. track.levelIdc, // AVCLevelIndication
  9270. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  9271. ].concat([sps.length], // numOfSequenceParameterSets
  9272. sequenceParameterSets, // "SPS"
  9273. [pps.length], // numOfPictureParameterSets
  9274. pictureParameterSets // "PPS"
  9275. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  9276. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  9277. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  9278. ]))];
  9279. if (track.sarRatio) {
  9280. var hSpacing = track.sarRatio[0],
  9281. vSpacing = track.sarRatio[1];
  9282. 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])));
  9283. }
  9284. return box.apply(null, avc1Box);
  9285. };
  9286. audioSample = function (track) {
  9287. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  9288. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  9289. 0x00, 0x01, // data_reference_index
  9290. // AudioSampleEntry, ISO/IEC 14496-12
  9291. 0x00, 0x00, 0x00, 0x00, // reserved
  9292. 0x00, 0x00, 0x00, 0x00, // reserved
  9293. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  9294. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  9295. 0x00, 0x00, // pre_defined
  9296. 0x00, 0x00, // reserved
  9297. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  9298. // MP4AudioSampleEntry, ISO/IEC 14496-14
  9299. ]), esds(track));
  9300. };
  9301. })();
  9302. tkhd = function (track) {
  9303. var result = new Uint8Array([0x00, // version 0
  9304. 0x00, 0x00, 0x07, // flags
  9305. 0x00, 0x00, 0x00, 0x00, // creation_time
  9306. 0x00, 0x00, 0x00, 0x00, // modification_time
  9307. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  9308. 0x00, 0x00, 0x00, 0x00, // reserved
  9309. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  9310. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  9311. 0x00, 0x00, // layer
  9312. 0x00, 0x00, // alternate_group
  9313. 0x01, 0x00, // non-audio track volume
  9314. 0x00, 0x00, // reserved
  9315. 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
  9316. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  9317. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  9318. ]);
  9319. return box(types.tkhd, result);
  9320. };
  9321. /**
  9322. * Generate a track fragment (traf) box. A traf box collects metadata
  9323. * about tracks in a movie fragment (moof) box.
  9324. */
  9325. traf = function (track) {
  9326. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  9327. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  9328. 0x00, 0x00, 0x3a, // flags
  9329. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  9330. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  9331. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9332. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9333. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  9334. ]));
  9335. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  9336. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  9337. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  9338. 0x00, 0x00, 0x00, // flags
  9339. // baseMediaDecodeTime
  9340. 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
  9341. // the containing moof to the first payload byte of the associated
  9342. // mdat
  9343. dataOffset = 32 + // tfhd
  9344. 20 + // tfdt
  9345. 8 + // traf header
  9346. 16 + // mfhd
  9347. 8 + // moof header
  9348. 8; // mdat header
  9349. // audio tracks require less metadata
  9350. if (track.type === 'audio') {
  9351. trackFragmentRun = trun$1(track, dataOffset);
  9352. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  9353. } // video tracks should contain an independent and disposable samples
  9354. // box (sdtp)
  9355. // generate one and adjust offsets to match
  9356. sampleDependencyTable = sdtp(track);
  9357. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  9358. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  9359. };
  9360. /**
  9361. * Generate a track box.
  9362. * @param track {object} a track definition
  9363. * @return {Uint8Array} the track box
  9364. */
  9365. trak = function (track) {
  9366. track.duration = track.duration || 0xffffffff;
  9367. return box(types.trak, tkhd(track), mdia(track));
  9368. };
  9369. trex = function (track) {
  9370. var result = new Uint8Array([0x00, // version 0
  9371. 0x00, 0x00, 0x00, // flags
  9372. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  9373. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  9374. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  9375. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  9376. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  9377. ]); // the last two bytes of default_sample_flags is the sample
  9378. // degradation priority, a hint about the importance of this sample
  9379. // relative to others. Lower the degradation priority for all sample
  9380. // types other than video.
  9381. if (track.type !== 'video') {
  9382. result[result.length - 1] = 0x00;
  9383. }
  9384. return box(types.trex, result);
  9385. };
  9386. (function () {
  9387. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  9388. // duration is present for the first sample, it will be present for
  9389. // all subsequent samples.
  9390. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  9391. trunHeader = function (samples, offset) {
  9392. var durationPresent = 0,
  9393. sizePresent = 0,
  9394. flagsPresent = 0,
  9395. compositionTimeOffset = 0; // trun flag constants
  9396. if (samples.length) {
  9397. if (samples[0].duration !== undefined) {
  9398. durationPresent = 0x1;
  9399. }
  9400. if (samples[0].size !== undefined) {
  9401. sizePresent = 0x2;
  9402. }
  9403. if (samples[0].flags !== undefined) {
  9404. flagsPresent = 0x4;
  9405. }
  9406. if (samples[0].compositionTimeOffset !== undefined) {
  9407. compositionTimeOffset = 0x8;
  9408. }
  9409. }
  9410. return [0x00, // version 0
  9411. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  9412. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  9413. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  9414. ];
  9415. };
  9416. videoTrun = function (track, offset) {
  9417. var bytesOffest, bytes, header, samples, sample, i;
  9418. samples = track.samples || [];
  9419. offset += 8 + 12 + 16 * samples.length;
  9420. header = trunHeader(samples, offset);
  9421. bytes = new Uint8Array(header.length + samples.length * 16);
  9422. bytes.set(header);
  9423. bytesOffest = header.length;
  9424. for (i = 0; i < samples.length; i++) {
  9425. sample = samples[i];
  9426. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  9427. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  9428. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  9429. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  9430. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  9431. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  9432. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  9433. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  9434. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  9435. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  9436. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  9437. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  9438. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  9439. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  9440. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  9441. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  9442. }
  9443. return box(types.trun, bytes);
  9444. };
  9445. audioTrun = function (track, offset) {
  9446. var bytes, bytesOffest, header, samples, sample, i;
  9447. samples = track.samples || [];
  9448. offset += 8 + 12 + 8 * samples.length;
  9449. header = trunHeader(samples, offset);
  9450. bytes = new Uint8Array(header.length + samples.length * 8);
  9451. bytes.set(header);
  9452. bytesOffest = header.length;
  9453. for (i = 0; i < samples.length; i++) {
  9454. sample = samples[i];
  9455. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  9456. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  9457. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  9458. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  9459. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  9460. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  9461. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  9462. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  9463. }
  9464. return box(types.trun, bytes);
  9465. };
  9466. trun$1 = function (track, offset) {
  9467. if (track.type === 'audio') {
  9468. return audioTrun(track, offset);
  9469. }
  9470. return videoTrun(track, offset);
  9471. };
  9472. })();
  9473. var mp4Generator = {
  9474. ftyp: ftyp,
  9475. mdat: mdat,
  9476. moof: moof,
  9477. moov: moov,
  9478. initSegment: function (tracks) {
  9479. var fileType = ftyp(),
  9480. movie = moov(tracks),
  9481. result;
  9482. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  9483. result.set(fileType);
  9484. result.set(movie, fileType.byteLength);
  9485. return result;
  9486. }
  9487. };
  9488. /**
  9489. * mux.js
  9490. *
  9491. * Copyright (c) Brightcove
  9492. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9493. */
  9494. // composed of the nal units that make up that frame
  9495. // Also keep track of cummulative data about the frame from the nal units such
  9496. // as the frame duration, starting pts, etc.
  9497. var groupNalsIntoFrames = function (nalUnits) {
  9498. var i,
  9499. currentNal,
  9500. currentFrame = [],
  9501. frames = []; // TODO added for LHLS, make sure this is OK
  9502. frames.byteLength = 0;
  9503. frames.nalCount = 0;
  9504. frames.duration = 0;
  9505. currentFrame.byteLength = 0;
  9506. for (i = 0; i < nalUnits.length; i++) {
  9507. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  9508. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  9509. // Since the very first nal unit is expected to be an AUD
  9510. // only push to the frames array when currentFrame is not empty
  9511. if (currentFrame.length) {
  9512. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  9513. frames.byteLength += currentFrame.byteLength;
  9514. frames.nalCount += currentFrame.length;
  9515. frames.duration += currentFrame.duration;
  9516. frames.push(currentFrame);
  9517. }
  9518. currentFrame = [currentNal];
  9519. currentFrame.byteLength = currentNal.data.byteLength;
  9520. currentFrame.pts = currentNal.pts;
  9521. currentFrame.dts = currentNal.dts;
  9522. } else {
  9523. // Specifically flag key frames for ease of use later
  9524. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  9525. currentFrame.keyFrame = true;
  9526. }
  9527. currentFrame.duration = currentNal.dts - currentFrame.dts;
  9528. currentFrame.byteLength += currentNal.data.byteLength;
  9529. currentFrame.push(currentNal);
  9530. }
  9531. } // For the last frame, use the duration of the previous frame if we
  9532. // have nothing better to go on
  9533. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  9534. currentFrame.duration = frames[frames.length - 1].duration;
  9535. } // Push the final frame
  9536. // TODO added for LHLS, make sure this is OK
  9537. frames.byteLength += currentFrame.byteLength;
  9538. frames.nalCount += currentFrame.length;
  9539. frames.duration += currentFrame.duration;
  9540. frames.push(currentFrame);
  9541. return frames;
  9542. }; // Convert an array of frames into an array of Gop with each Gop being composed
  9543. // of the frames that make up that Gop
  9544. // Also keep track of cummulative data about the Gop from the frames such as the
  9545. // Gop duration, starting pts, etc.
  9546. var groupFramesIntoGops = function (frames) {
  9547. var i,
  9548. currentFrame,
  9549. currentGop = [],
  9550. gops = []; // We must pre-set some of the values on the Gop since we
  9551. // keep running totals of these values
  9552. currentGop.byteLength = 0;
  9553. currentGop.nalCount = 0;
  9554. currentGop.duration = 0;
  9555. currentGop.pts = frames[0].pts;
  9556. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  9557. gops.byteLength = 0;
  9558. gops.nalCount = 0;
  9559. gops.duration = 0;
  9560. gops.pts = frames[0].pts;
  9561. gops.dts = frames[0].dts;
  9562. for (i = 0; i < frames.length; i++) {
  9563. currentFrame = frames[i];
  9564. if (currentFrame.keyFrame) {
  9565. // Since the very first frame is expected to be an keyframe
  9566. // only push to the gops array when currentGop is not empty
  9567. if (currentGop.length) {
  9568. gops.push(currentGop);
  9569. gops.byteLength += currentGop.byteLength;
  9570. gops.nalCount += currentGop.nalCount;
  9571. gops.duration += currentGop.duration;
  9572. }
  9573. currentGop = [currentFrame];
  9574. currentGop.nalCount = currentFrame.length;
  9575. currentGop.byteLength = currentFrame.byteLength;
  9576. currentGop.pts = currentFrame.pts;
  9577. currentGop.dts = currentFrame.dts;
  9578. currentGop.duration = currentFrame.duration;
  9579. } else {
  9580. currentGop.duration += currentFrame.duration;
  9581. currentGop.nalCount += currentFrame.length;
  9582. currentGop.byteLength += currentFrame.byteLength;
  9583. currentGop.push(currentFrame);
  9584. }
  9585. }
  9586. if (gops.length && currentGop.duration <= 0) {
  9587. currentGop.duration = gops[gops.length - 1].duration;
  9588. }
  9589. gops.byteLength += currentGop.byteLength;
  9590. gops.nalCount += currentGop.nalCount;
  9591. gops.duration += currentGop.duration; // push the final Gop
  9592. gops.push(currentGop);
  9593. return gops;
  9594. };
  9595. /*
  9596. * Search for the first keyframe in the GOPs and throw away all frames
  9597. * until that keyframe. Then extend the duration of the pulled keyframe
  9598. * and pull the PTS and DTS of the keyframe so that it covers the time
  9599. * range of the frames that were disposed.
  9600. *
  9601. * @param {Array} gops video GOPs
  9602. * @returns {Array} modified video GOPs
  9603. */
  9604. var extendFirstKeyFrame = function (gops) {
  9605. var currentGop;
  9606. if (!gops[0][0].keyFrame && gops.length > 1) {
  9607. // Remove the first GOP
  9608. currentGop = gops.shift();
  9609. gops.byteLength -= currentGop.byteLength;
  9610. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  9611. // first gop to cover the time period of the
  9612. // frames we just removed
  9613. gops[0][0].dts = currentGop.dts;
  9614. gops[0][0].pts = currentGop.pts;
  9615. gops[0][0].duration += currentGop.duration;
  9616. }
  9617. return gops;
  9618. };
  9619. /**
  9620. * Default sample object
  9621. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  9622. */
  9623. var createDefaultSample = function () {
  9624. return {
  9625. size: 0,
  9626. flags: {
  9627. isLeading: 0,
  9628. dependsOn: 1,
  9629. isDependedOn: 0,
  9630. hasRedundancy: 0,
  9631. degradationPriority: 0,
  9632. isNonSyncSample: 1
  9633. }
  9634. };
  9635. };
  9636. /*
  9637. * Collates information from a video frame into an object for eventual
  9638. * entry into an MP4 sample table.
  9639. *
  9640. * @param {Object} frame the video frame
  9641. * @param {Number} dataOffset the byte offset to position the sample
  9642. * @return {Object} object containing sample table info for a frame
  9643. */
  9644. var sampleForFrame = function (frame, dataOffset) {
  9645. var sample = createDefaultSample();
  9646. sample.dataOffset = dataOffset;
  9647. sample.compositionTimeOffset = frame.pts - frame.dts;
  9648. sample.duration = frame.duration;
  9649. sample.size = 4 * frame.length; // Space for nal unit size
  9650. sample.size += frame.byteLength;
  9651. if (frame.keyFrame) {
  9652. sample.flags.dependsOn = 2;
  9653. sample.flags.isNonSyncSample = 0;
  9654. }
  9655. return sample;
  9656. }; // generate the track's sample table from an array of gops
  9657. var generateSampleTable$1 = function (gops, baseDataOffset) {
  9658. var h,
  9659. i,
  9660. sample,
  9661. currentGop,
  9662. currentFrame,
  9663. dataOffset = baseDataOffset || 0,
  9664. samples = [];
  9665. for (h = 0; h < gops.length; h++) {
  9666. currentGop = gops[h];
  9667. for (i = 0; i < currentGop.length; i++) {
  9668. currentFrame = currentGop[i];
  9669. sample = sampleForFrame(currentFrame, dataOffset);
  9670. dataOffset += sample.size;
  9671. samples.push(sample);
  9672. }
  9673. }
  9674. return samples;
  9675. }; // generate the track's raw mdat data from an array of gops
  9676. var concatenateNalData = function (gops) {
  9677. var h,
  9678. i,
  9679. j,
  9680. currentGop,
  9681. currentFrame,
  9682. currentNal,
  9683. dataOffset = 0,
  9684. nalsByteLength = gops.byteLength,
  9685. numberOfNals = gops.nalCount,
  9686. totalByteLength = nalsByteLength + 4 * numberOfNals,
  9687. data = new Uint8Array(totalByteLength),
  9688. view = new DataView(data.buffer); // For each Gop..
  9689. for (h = 0; h < gops.length; h++) {
  9690. currentGop = gops[h]; // For each Frame..
  9691. for (i = 0; i < currentGop.length; i++) {
  9692. currentFrame = currentGop[i]; // For each NAL..
  9693. for (j = 0; j < currentFrame.length; j++) {
  9694. currentNal = currentFrame[j];
  9695. view.setUint32(dataOffset, currentNal.data.byteLength);
  9696. dataOffset += 4;
  9697. data.set(currentNal.data, dataOffset);
  9698. dataOffset += currentNal.data.byteLength;
  9699. }
  9700. }
  9701. }
  9702. return data;
  9703. }; // generate the track's sample table from a frame
  9704. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  9705. var sample,
  9706. dataOffset = baseDataOffset || 0,
  9707. samples = [];
  9708. sample = sampleForFrame(frame, dataOffset);
  9709. samples.push(sample);
  9710. return samples;
  9711. }; // generate the track's raw mdat data from a frame
  9712. var concatenateNalDataForFrame = function (frame) {
  9713. var i,
  9714. currentNal,
  9715. dataOffset = 0,
  9716. nalsByteLength = frame.byteLength,
  9717. numberOfNals = frame.length,
  9718. totalByteLength = nalsByteLength + 4 * numberOfNals,
  9719. data = new Uint8Array(totalByteLength),
  9720. view = new DataView(data.buffer); // For each NAL..
  9721. for (i = 0; i < frame.length; i++) {
  9722. currentNal = frame[i];
  9723. view.setUint32(dataOffset, currentNal.data.byteLength);
  9724. dataOffset += 4;
  9725. data.set(currentNal.data, dataOffset);
  9726. dataOffset += currentNal.data.byteLength;
  9727. }
  9728. return data;
  9729. };
  9730. var frameUtils$1 = {
  9731. groupNalsIntoFrames: groupNalsIntoFrames,
  9732. groupFramesIntoGops: groupFramesIntoGops,
  9733. extendFirstKeyFrame: extendFirstKeyFrame,
  9734. generateSampleTable: generateSampleTable$1,
  9735. concatenateNalData: concatenateNalData,
  9736. generateSampleTableForFrame: generateSampleTableForFrame,
  9737. concatenateNalDataForFrame: concatenateNalDataForFrame
  9738. };
  9739. /**
  9740. * mux.js
  9741. *
  9742. * Copyright (c) Brightcove
  9743. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9744. */
  9745. var highPrefix = [33, 16, 5, 32, 164, 27];
  9746. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  9747. var zeroFill = function (count) {
  9748. var a = [];
  9749. while (count--) {
  9750. a.push(0);
  9751. }
  9752. return a;
  9753. };
  9754. var makeTable = function (metaTable) {
  9755. return Object.keys(metaTable).reduce(function (obj, key) {
  9756. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  9757. return arr.concat(part);
  9758. }, []));
  9759. return obj;
  9760. }, {});
  9761. };
  9762. var silence;
  9763. var silence_1 = function () {
  9764. if (!silence) {
  9765. // Frames-of-silence to use for filling in missing AAC frames
  9766. var coneOfSilence = {
  9767. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  9768. 88200: [highPrefix, [231], zeroFill(170), [56]],
  9769. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  9770. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  9771. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  9772. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  9773. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  9774. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  9775. 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]],
  9776. 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]],
  9777. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  9778. };
  9779. silence = makeTable(coneOfSilence);
  9780. }
  9781. return silence;
  9782. };
  9783. /**
  9784. * mux.js
  9785. *
  9786. * Copyright (c) Brightcove
  9787. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9788. */
  9789. var ONE_SECOND_IN_TS$4 = 90000,
  9790. // 90kHz clock
  9791. secondsToVideoTs,
  9792. secondsToAudioTs,
  9793. videoTsToSeconds,
  9794. audioTsToSeconds,
  9795. audioTsToVideoTs,
  9796. videoTsToAudioTs,
  9797. metadataTsToSeconds;
  9798. secondsToVideoTs = function (seconds) {
  9799. return seconds * ONE_SECOND_IN_TS$4;
  9800. };
  9801. secondsToAudioTs = function (seconds, sampleRate) {
  9802. return seconds * sampleRate;
  9803. };
  9804. videoTsToSeconds = function (timestamp) {
  9805. return timestamp / ONE_SECOND_IN_TS$4;
  9806. };
  9807. audioTsToSeconds = function (timestamp, sampleRate) {
  9808. return timestamp / sampleRate;
  9809. };
  9810. audioTsToVideoTs = function (timestamp, sampleRate) {
  9811. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  9812. };
  9813. videoTsToAudioTs = function (timestamp, sampleRate) {
  9814. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  9815. };
  9816. /**
  9817. * Adjust ID3 tag or caption timing information by the timeline pts values
  9818. * (if keepOriginalTimestamps is false) and convert to seconds
  9819. */
  9820. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  9821. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  9822. };
  9823. var clock$2 = {
  9824. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  9825. secondsToVideoTs: secondsToVideoTs,
  9826. secondsToAudioTs: secondsToAudioTs,
  9827. videoTsToSeconds: videoTsToSeconds,
  9828. audioTsToSeconds: audioTsToSeconds,
  9829. audioTsToVideoTs: audioTsToVideoTs,
  9830. videoTsToAudioTs: videoTsToAudioTs,
  9831. metadataTsToSeconds: metadataTsToSeconds
  9832. };
  9833. /**
  9834. * mux.js
  9835. *
  9836. * Copyright (c) Brightcove
  9837. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9838. */
  9839. var coneOfSilence = silence_1;
  9840. var clock$1 = clock$2;
  9841. /**
  9842. * Sum the `byteLength` properties of the data in each AAC frame
  9843. */
  9844. var sumFrameByteLengths = function (array) {
  9845. var i,
  9846. currentObj,
  9847. sum = 0; // sum the byteLength's all each nal unit in the frame
  9848. for (i = 0; i < array.length; i++) {
  9849. currentObj = array[i];
  9850. sum += currentObj.data.byteLength;
  9851. }
  9852. return sum;
  9853. }; // Possibly pad (prefix) the audio track with silence if appending this track
  9854. // would lead to the introduction of a gap in the audio buffer
  9855. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  9856. var baseMediaDecodeTimeTs,
  9857. frameDuration = 0,
  9858. audioGapDuration = 0,
  9859. audioFillFrameCount = 0,
  9860. audioFillDuration = 0,
  9861. silentFrame,
  9862. i,
  9863. firstFrame;
  9864. if (!frames.length) {
  9865. return;
  9866. }
  9867. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  9868. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  9869. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  9870. // insert the shortest possible amount (audio gap or audio to video gap)
  9871. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  9872. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  9873. audioFillDuration = audioFillFrameCount * frameDuration;
  9874. } // don't attempt to fill gaps smaller than a single frame or larger
  9875. // than a half second
  9876. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  9877. return;
  9878. }
  9879. silentFrame = coneOfSilence()[track.samplerate];
  9880. if (!silentFrame) {
  9881. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  9882. // from the content instead
  9883. silentFrame = frames[0].data;
  9884. }
  9885. for (i = 0; i < audioFillFrameCount; i++) {
  9886. firstFrame = frames[0];
  9887. frames.splice(0, 0, {
  9888. data: silentFrame,
  9889. dts: firstFrame.dts - frameDuration,
  9890. pts: firstFrame.pts - frameDuration
  9891. });
  9892. }
  9893. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  9894. return audioFillDuration;
  9895. }; // If the audio segment extends before the earliest allowed dts
  9896. // value, remove AAC frames until starts at or after the earliest
  9897. // allowed DTS so that we don't end up with a negative baseMedia-
  9898. // DecodeTime for the audio track
  9899. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  9900. if (track.minSegmentDts >= earliestAllowedDts) {
  9901. return adtsFrames;
  9902. } // We will need to recalculate the earliest segment Dts
  9903. track.minSegmentDts = Infinity;
  9904. return adtsFrames.filter(function (currentFrame) {
  9905. // If this is an allowed frame, keep it and record it's Dts
  9906. if (currentFrame.dts >= earliestAllowedDts) {
  9907. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  9908. track.minSegmentPts = track.minSegmentDts;
  9909. return true;
  9910. } // Otherwise, discard it
  9911. return false;
  9912. });
  9913. }; // generate the track's raw mdat data from an array of frames
  9914. var generateSampleTable = function (frames) {
  9915. var i,
  9916. currentFrame,
  9917. samples = [];
  9918. for (i = 0; i < frames.length; i++) {
  9919. currentFrame = frames[i];
  9920. samples.push({
  9921. size: currentFrame.data.byteLength,
  9922. duration: 1024 // For AAC audio, all samples contain 1024 samples
  9923. });
  9924. }
  9925. return samples;
  9926. }; // generate the track's sample table from an array of frames
  9927. var concatenateFrameData = function (frames) {
  9928. var i,
  9929. currentFrame,
  9930. dataOffset = 0,
  9931. data = new Uint8Array(sumFrameByteLengths(frames));
  9932. for (i = 0; i < frames.length; i++) {
  9933. currentFrame = frames[i];
  9934. data.set(currentFrame.data, dataOffset);
  9935. dataOffset += currentFrame.data.byteLength;
  9936. }
  9937. return data;
  9938. };
  9939. var audioFrameUtils$1 = {
  9940. prefixWithSilence: prefixWithSilence,
  9941. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  9942. generateSampleTable: generateSampleTable,
  9943. concatenateFrameData: concatenateFrameData
  9944. };
  9945. /**
  9946. * mux.js
  9947. *
  9948. * Copyright (c) Brightcove
  9949. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9950. */
  9951. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  9952. /**
  9953. * Store information about the start and end of the track and the
  9954. * duration for each frame/sample we process in order to calculate
  9955. * the baseMediaDecodeTime
  9956. */
  9957. var collectDtsInfo = function (track, data) {
  9958. if (typeof data.pts === 'number') {
  9959. if (track.timelineStartInfo.pts === undefined) {
  9960. track.timelineStartInfo.pts = data.pts;
  9961. }
  9962. if (track.minSegmentPts === undefined) {
  9963. track.minSegmentPts = data.pts;
  9964. } else {
  9965. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  9966. }
  9967. if (track.maxSegmentPts === undefined) {
  9968. track.maxSegmentPts = data.pts;
  9969. } else {
  9970. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  9971. }
  9972. }
  9973. if (typeof data.dts === 'number') {
  9974. if (track.timelineStartInfo.dts === undefined) {
  9975. track.timelineStartInfo.dts = data.dts;
  9976. }
  9977. if (track.minSegmentDts === undefined) {
  9978. track.minSegmentDts = data.dts;
  9979. } else {
  9980. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  9981. }
  9982. if (track.maxSegmentDts === undefined) {
  9983. track.maxSegmentDts = data.dts;
  9984. } else {
  9985. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  9986. }
  9987. }
  9988. };
  9989. /**
  9990. * Clear values used to calculate the baseMediaDecodeTime between
  9991. * tracks
  9992. */
  9993. var clearDtsInfo = function (track) {
  9994. delete track.minSegmentDts;
  9995. delete track.maxSegmentDts;
  9996. delete track.minSegmentPts;
  9997. delete track.maxSegmentPts;
  9998. };
  9999. /**
  10000. * Calculate the track's baseMediaDecodeTime based on the earliest
  10001. * DTS the transmuxer has ever seen and the minimum DTS for the
  10002. * current track
  10003. * @param track {object} track metadata configuration
  10004. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  10005. * in the source; false to adjust the first segment to start at 0.
  10006. */
  10007. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  10008. var baseMediaDecodeTime,
  10009. scale,
  10010. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  10011. if (!keepOriginalTimestamps) {
  10012. minSegmentDts -= track.timelineStartInfo.dts;
  10013. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  10014. // we want the start of the first segment to be placed
  10015. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  10016. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  10017. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  10018. if (track.type === 'audio') {
  10019. // Audio has a different clock equal to the sampling_rate so we need to
  10020. // scale the PTS values into the clock rate of the track
  10021. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  10022. baseMediaDecodeTime *= scale;
  10023. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  10024. }
  10025. return baseMediaDecodeTime;
  10026. };
  10027. var trackDecodeInfo$1 = {
  10028. clearDtsInfo: clearDtsInfo,
  10029. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  10030. collectDtsInfo: collectDtsInfo
  10031. };
  10032. /**
  10033. * mux.js
  10034. *
  10035. * Copyright (c) Brightcove
  10036. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10037. *
  10038. * Reads in-band caption information from a video elementary
  10039. * stream. Captions must follow the CEA-708 standard for injection
  10040. * into an MPEG-2 transport streams.
  10041. * @see https://en.wikipedia.org/wiki/CEA-708
  10042. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  10043. */
  10044. // payload type field to indicate how they are to be
  10045. // interpreted. CEAS-708 caption content is always transmitted with
  10046. // payload type 0x04.
  10047. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  10048. RBSP_TRAILING_BITS = 128;
  10049. /**
  10050. * Parse a supplemental enhancement information (SEI) NAL unit.
  10051. * Stops parsing once a message of type ITU T T35 has been found.
  10052. *
  10053. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  10054. * @return {object} the parsed SEI payload
  10055. * @see Rec. ITU-T H.264, 7.3.2.3.1
  10056. */
  10057. var parseSei = function (bytes) {
  10058. var i = 0,
  10059. result = {
  10060. payloadType: -1,
  10061. payloadSize: 0
  10062. },
  10063. payloadType = 0,
  10064. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  10065. while (i < bytes.byteLength) {
  10066. // stop once we have hit the end of the sei_rbsp
  10067. if (bytes[i] === RBSP_TRAILING_BITS) {
  10068. break;
  10069. } // Parse payload type
  10070. while (bytes[i] === 0xFF) {
  10071. payloadType += 255;
  10072. i++;
  10073. }
  10074. payloadType += bytes[i++]; // Parse payload size
  10075. while (bytes[i] === 0xFF) {
  10076. payloadSize += 255;
  10077. i++;
  10078. }
  10079. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  10080. // there can only ever be one caption message in a frame's sei
  10081. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  10082. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  10083. if (userIdentifier === 'GA94') {
  10084. result.payloadType = payloadType;
  10085. result.payloadSize = payloadSize;
  10086. result.payload = bytes.subarray(i, i + payloadSize);
  10087. break;
  10088. } else {
  10089. result.payload = void 0;
  10090. }
  10091. } // skip the payload and parse the next message
  10092. i += payloadSize;
  10093. payloadType = 0;
  10094. payloadSize = 0;
  10095. }
  10096. return result;
  10097. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  10098. var parseUserData = function (sei) {
  10099. // itu_t_t35_contry_code must be 181 (United States) for
  10100. // captions
  10101. if (sei.payload[0] !== 181) {
  10102. return null;
  10103. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  10104. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  10105. return null;
  10106. } // the user_identifier should be "GA94" to indicate ATSC1 data
  10107. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  10108. return null;
  10109. } // finally, user_data_type_code should be 0x03 for caption data
  10110. if (sei.payload[7] !== 0x03) {
  10111. return null;
  10112. } // return the user_data_type_structure and strip the trailing
  10113. // marker bits
  10114. return sei.payload.subarray(8, sei.payload.length - 1);
  10115. }; // see CEA-708-D, section 4.4
  10116. var parseCaptionPackets = function (pts, userData) {
  10117. var results = [],
  10118. i,
  10119. count,
  10120. offset,
  10121. data; // if this is just filler, return immediately
  10122. if (!(userData[0] & 0x40)) {
  10123. return results;
  10124. } // parse out the cc_data_1 and cc_data_2 fields
  10125. count = userData[0] & 0x1f;
  10126. for (i = 0; i < count; i++) {
  10127. offset = i * 3;
  10128. data = {
  10129. type: userData[offset + 2] & 0x03,
  10130. pts: pts
  10131. }; // capture cc data when cc_valid is 1
  10132. if (userData[offset + 2] & 0x04) {
  10133. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  10134. results.push(data);
  10135. }
  10136. }
  10137. return results;
  10138. };
  10139. var discardEmulationPreventionBytes$1 = function (data) {
  10140. var length = data.byteLength,
  10141. emulationPreventionBytesPositions = [],
  10142. i = 1,
  10143. newLength,
  10144. newData; // Find all `Emulation Prevention Bytes`
  10145. while (i < length - 2) {
  10146. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  10147. emulationPreventionBytesPositions.push(i + 2);
  10148. i += 2;
  10149. } else {
  10150. i++;
  10151. }
  10152. } // If no Emulation Prevention Bytes were found just return the original
  10153. // array
  10154. if (emulationPreventionBytesPositions.length === 0) {
  10155. return data;
  10156. } // Create a new array to hold the NAL unit data
  10157. newLength = length - emulationPreventionBytesPositions.length;
  10158. newData = new Uint8Array(newLength);
  10159. var sourceIndex = 0;
  10160. for (i = 0; i < newLength; sourceIndex++, i++) {
  10161. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  10162. // Skip this byte
  10163. sourceIndex++; // Remove this position index
  10164. emulationPreventionBytesPositions.shift();
  10165. }
  10166. newData[i] = data[sourceIndex];
  10167. }
  10168. return newData;
  10169. }; // exports
  10170. var captionPacketParser = {
  10171. parseSei: parseSei,
  10172. parseUserData: parseUserData,
  10173. parseCaptionPackets: parseCaptionPackets,
  10174. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  10175. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  10176. };
  10177. /**
  10178. * mux.js
  10179. *
  10180. * Copyright (c) Brightcove
  10181. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10182. *
  10183. * Reads in-band caption information from a video elementary
  10184. * stream. Captions must follow the CEA-708 standard for injection
  10185. * into an MPEG-2 transport streams.
  10186. * @see https://en.wikipedia.org/wiki/CEA-708
  10187. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  10188. */
  10189. // Link To Transport
  10190. // -----------------
  10191. var Stream$7 = stream;
  10192. var cea708Parser = captionPacketParser;
  10193. var CaptionStream$2 = function (options) {
  10194. options = options || {};
  10195. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  10196. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  10197. this.captionPackets_ = [];
  10198. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  10199. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  10200. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  10201. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  10202. ];
  10203. if (this.parse708captions_) {
  10204. this.cc708Stream_ = new Cea708Stream({
  10205. captionServices: options.captionServices
  10206. }); // eslint-disable-line no-use-before-define
  10207. }
  10208. this.reset(); // forward data and done events from CCs to this CaptionStream
  10209. this.ccStreams_.forEach(function (cc) {
  10210. cc.on('data', this.trigger.bind(this, 'data'));
  10211. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  10212. cc.on('done', this.trigger.bind(this, 'done'));
  10213. }, this);
  10214. if (this.parse708captions_) {
  10215. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  10216. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  10217. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  10218. }
  10219. };
  10220. CaptionStream$2.prototype = new Stream$7();
  10221. CaptionStream$2.prototype.push = function (event) {
  10222. var sei, userData, newCaptionPackets; // only examine SEI NALs
  10223. if (event.nalUnitType !== 'sei_rbsp') {
  10224. return;
  10225. } // parse the sei
  10226. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  10227. if (!sei.payload) {
  10228. return;
  10229. } // ignore everything but user_data_registered_itu_t_t35
  10230. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  10231. return;
  10232. } // parse out the user data payload
  10233. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  10234. if (!userData) {
  10235. return;
  10236. } // Sometimes, the same segment # will be downloaded twice. To stop the
  10237. // caption data from being processed twice, we track the latest dts we've
  10238. // received and ignore everything with a dts before that. However, since
  10239. // data for a specific dts can be split across packets on either side of
  10240. // a segment boundary, we need to make sure we *don't* ignore the packets
  10241. // from the *next* segment that have dts === this.latestDts_. By constantly
  10242. // tracking the number of packets received with dts === this.latestDts_, we
  10243. // know how many should be ignored once we start receiving duplicates.
  10244. if (event.dts < this.latestDts_) {
  10245. // We've started getting older data, so set the flag.
  10246. this.ignoreNextEqualDts_ = true;
  10247. return;
  10248. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  10249. this.numSameDts_--;
  10250. if (!this.numSameDts_) {
  10251. // We've received the last duplicate packet, time to start processing again
  10252. this.ignoreNextEqualDts_ = false;
  10253. }
  10254. return;
  10255. } // parse out CC data packets and save them for later
  10256. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  10257. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  10258. if (this.latestDts_ !== event.dts) {
  10259. this.numSameDts_ = 0;
  10260. }
  10261. this.numSameDts_++;
  10262. this.latestDts_ = event.dts;
  10263. };
  10264. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  10265. this.ccStreams_.forEach(function (cc) {
  10266. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  10267. }, this);
  10268. };
  10269. CaptionStream$2.prototype.flushStream = function (flushType) {
  10270. // make sure we actually parsed captions before proceeding
  10271. if (!this.captionPackets_.length) {
  10272. this.flushCCStreams(flushType);
  10273. return;
  10274. } // In Chrome, the Array#sort function is not stable so add a
  10275. // presortIndex that we can use to ensure we get a stable-sort
  10276. this.captionPackets_.forEach(function (elem, idx) {
  10277. elem.presortIndex = idx;
  10278. }); // sort caption byte-pairs based on their PTS values
  10279. this.captionPackets_.sort(function (a, b) {
  10280. if (a.pts === b.pts) {
  10281. return a.presortIndex - b.presortIndex;
  10282. }
  10283. return a.pts - b.pts;
  10284. });
  10285. this.captionPackets_.forEach(function (packet) {
  10286. if (packet.type < 2) {
  10287. // Dispatch packet to the right Cea608Stream
  10288. this.dispatchCea608Packet(packet);
  10289. } else {
  10290. // Dispatch packet to the Cea708Stream
  10291. this.dispatchCea708Packet(packet);
  10292. }
  10293. }, this);
  10294. this.captionPackets_.length = 0;
  10295. this.flushCCStreams(flushType);
  10296. };
  10297. CaptionStream$2.prototype.flush = function () {
  10298. return this.flushStream('flush');
  10299. }; // Only called if handling partial data
  10300. CaptionStream$2.prototype.partialFlush = function () {
  10301. return this.flushStream('partialFlush');
  10302. };
  10303. CaptionStream$2.prototype.reset = function () {
  10304. this.latestDts_ = null;
  10305. this.ignoreNextEqualDts_ = false;
  10306. this.numSameDts_ = 0;
  10307. this.activeCea608Channel_ = [null, null];
  10308. this.ccStreams_.forEach(function (ccStream) {
  10309. ccStream.reset();
  10310. });
  10311. }; // From the CEA-608 spec:
  10312. /*
  10313. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  10314. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  10315. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  10316. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  10317. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  10318. * to switch to captioning or Text.
  10319. */
  10320. // With that in mind, we ignore any data between an XDS control code and a
  10321. // subsequent closed-captioning control code.
  10322. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  10323. // NOTE: packet.type is the CEA608 field
  10324. if (this.setsTextOrXDSActive(packet)) {
  10325. this.activeCea608Channel_[packet.type] = null;
  10326. } else if (this.setsChannel1Active(packet)) {
  10327. this.activeCea608Channel_[packet.type] = 0;
  10328. } else if (this.setsChannel2Active(packet)) {
  10329. this.activeCea608Channel_[packet.type] = 1;
  10330. }
  10331. if (this.activeCea608Channel_[packet.type] === null) {
  10332. // If we haven't received anything to set the active channel, or the
  10333. // packets are Text/XDS data, discard the data; we don't want jumbled
  10334. // captions
  10335. return;
  10336. }
  10337. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  10338. };
  10339. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  10340. return (packet.ccData & 0x7800) === 0x1000;
  10341. };
  10342. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  10343. return (packet.ccData & 0x7800) === 0x1800;
  10344. };
  10345. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  10346. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  10347. };
  10348. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  10349. if (this.parse708captions_) {
  10350. this.cc708Stream_.push(packet);
  10351. }
  10352. }; // ----------------------
  10353. // Session to Application
  10354. // ----------------------
  10355. // This hash maps special and extended character codes to their
  10356. // proper Unicode equivalent. The first one-byte key is just a
  10357. // non-standard character code. The two-byte keys that follow are
  10358. // the extended CEA708 character codes, along with the preceding
  10359. // 0x10 extended character byte to distinguish these codes from
  10360. // non-extended character codes. Every CEA708 character code that
  10361. // is not in this object maps directly to a standard unicode
  10362. // character code.
  10363. // The transparent space and non-breaking transparent space are
  10364. // technically not fully supported since there is no code to
  10365. // make them transparent, so they have normal non-transparent
  10366. // stand-ins.
  10367. // The special closed caption (CC) character isn't a standard
  10368. // unicode character, so a fairly similar unicode character was
  10369. // chosen in it's place.
  10370. var CHARACTER_TRANSLATION_708 = {
  10371. 0x7f: 0x266a,
  10372. // ♪
  10373. 0x1020: 0x20,
  10374. // Transparent Space
  10375. 0x1021: 0xa0,
  10376. // Nob-breaking Transparent Space
  10377. 0x1025: 0x2026,
  10378. // …
  10379. 0x102a: 0x0160,
  10380. // Š
  10381. 0x102c: 0x0152,
  10382. // Œ
  10383. 0x1030: 0x2588,
  10384. // █
  10385. 0x1031: 0x2018,
  10386. // ‘
  10387. 0x1032: 0x2019,
  10388. // ’
  10389. 0x1033: 0x201c,
  10390. // “
  10391. 0x1034: 0x201d,
  10392. // ”
  10393. 0x1035: 0x2022,
  10394. // •
  10395. 0x1039: 0x2122,
  10396. // ™
  10397. 0x103a: 0x0161,
  10398. // š
  10399. 0x103c: 0x0153,
  10400. // œ
  10401. 0x103d: 0x2120,
  10402. // ℠
  10403. 0x103f: 0x0178,
  10404. // Ÿ
  10405. 0x1076: 0x215b,
  10406. // ⅛
  10407. 0x1077: 0x215c,
  10408. // ⅜
  10409. 0x1078: 0x215d,
  10410. // ⅝
  10411. 0x1079: 0x215e,
  10412. // ⅞
  10413. 0x107a: 0x23d0,
  10414. // ⏐
  10415. 0x107b: 0x23a4,
  10416. // ⎤
  10417. 0x107c: 0x23a3,
  10418. // ⎣
  10419. 0x107d: 0x23af,
  10420. // ⎯
  10421. 0x107e: 0x23a6,
  10422. // ⎦
  10423. 0x107f: 0x23a1,
  10424. // ⎡
  10425. 0x10a0: 0x3138 // ㄸ (CC char)
  10426. };
  10427. var get708CharFromCode = function (code) {
  10428. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  10429. if (code & 0x1000 && code === newCode) {
  10430. // Invalid extended code
  10431. return '';
  10432. }
  10433. return String.fromCharCode(newCode);
  10434. };
  10435. var within708TextBlock = function (b) {
  10436. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  10437. };
  10438. var Cea708Window = function (windowNum) {
  10439. this.windowNum = windowNum;
  10440. this.reset();
  10441. };
  10442. Cea708Window.prototype.reset = function () {
  10443. this.clearText();
  10444. this.pendingNewLine = false;
  10445. this.winAttr = {};
  10446. this.penAttr = {};
  10447. this.penLoc = {};
  10448. this.penColor = {}; // These default values are arbitrary,
  10449. // defineWindow will usually override them
  10450. this.visible = 0;
  10451. this.rowLock = 0;
  10452. this.columnLock = 0;
  10453. this.priority = 0;
  10454. this.relativePositioning = 0;
  10455. this.anchorVertical = 0;
  10456. this.anchorHorizontal = 0;
  10457. this.anchorPoint = 0;
  10458. this.rowCount = 1;
  10459. this.virtualRowCount = this.rowCount + 1;
  10460. this.columnCount = 41;
  10461. this.windowStyle = 0;
  10462. this.penStyle = 0;
  10463. };
  10464. Cea708Window.prototype.getText = function () {
  10465. return this.rows.join('\n');
  10466. };
  10467. Cea708Window.prototype.clearText = function () {
  10468. this.rows = [''];
  10469. this.rowIdx = 0;
  10470. };
  10471. Cea708Window.prototype.newLine = function (pts) {
  10472. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  10473. this.beforeRowOverflow(pts);
  10474. }
  10475. if (this.rows.length > 0) {
  10476. this.rows.push('');
  10477. this.rowIdx++;
  10478. } // Show all virtual rows since there's no visible scrolling
  10479. while (this.rows.length > this.virtualRowCount) {
  10480. this.rows.shift();
  10481. this.rowIdx--;
  10482. }
  10483. };
  10484. Cea708Window.prototype.isEmpty = function () {
  10485. if (this.rows.length === 0) {
  10486. return true;
  10487. } else if (this.rows.length === 1) {
  10488. return this.rows[0] === '';
  10489. }
  10490. return false;
  10491. };
  10492. Cea708Window.prototype.addText = function (text) {
  10493. this.rows[this.rowIdx] += text;
  10494. };
  10495. Cea708Window.prototype.backspace = function () {
  10496. if (!this.isEmpty()) {
  10497. var row = this.rows[this.rowIdx];
  10498. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  10499. }
  10500. };
  10501. var Cea708Service = function (serviceNum, encoding, stream) {
  10502. this.serviceNum = serviceNum;
  10503. this.text = '';
  10504. this.currentWindow = new Cea708Window(-1);
  10505. this.windows = [];
  10506. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  10507. if (typeof encoding === 'string') {
  10508. this.createTextDecoder(encoding);
  10509. }
  10510. };
  10511. /**
  10512. * Initialize service windows
  10513. * Must be run before service use
  10514. *
  10515. * @param {Integer} pts PTS value
  10516. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  10517. */
  10518. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  10519. this.startPts = pts;
  10520. for (var win = 0; win < 8; win++) {
  10521. this.windows[win] = new Cea708Window(win);
  10522. if (typeof beforeRowOverflow === 'function') {
  10523. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  10524. }
  10525. }
  10526. };
  10527. /**
  10528. * Set current window of service to be affected by commands
  10529. *
  10530. * @param {Integer} windowNum Window number
  10531. */
  10532. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  10533. this.currentWindow = this.windows[windowNum];
  10534. };
  10535. /**
  10536. * Try to create a TextDecoder if it is natively supported
  10537. */
  10538. Cea708Service.prototype.createTextDecoder = function (encoding) {
  10539. if (typeof TextDecoder === 'undefined') {
  10540. this.stream.trigger('log', {
  10541. level: 'warn',
  10542. message: 'The `encoding` option is unsupported without TextDecoder support'
  10543. });
  10544. } else {
  10545. try {
  10546. this.textDecoder_ = new TextDecoder(encoding);
  10547. } catch (error) {
  10548. this.stream.trigger('log', {
  10549. level: 'warn',
  10550. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  10551. });
  10552. }
  10553. }
  10554. };
  10555. var Cea708Stream = function (options) {
  10556. options = options || {};
  10557. Cea708Stream.prototype.init.call(this);
  10558. var self = this;
  10559. var captionServices = options.captionServices || {};
  10560. var captionServiceEncodings = {};
  10561. var serviceProps; // Get service encodings from captionServices option block
  10562. Object.keys(captionServices).forEach(serviceName => {
  10563. serviceProps = captionServices[serviceName];
  10564. if (/^SERVICE/.test(serviceName)) {
  10565. captionServiceEncodings[serviceName] = serviceProps.encoding;
  10566. }
  10567. });
  10568. this.serviceEncodings = captionServiceEncodings;
  10569. this.current708Packet = null;
  10570. this.services = {};
  10571. this.push = function (packet) {
  10572. if (packet.type === 3) {
  10573. // 708 packet start
  10574. self.new708Packet();
  10575. self.add708Bytes(packet);
  10576. } else {
  10577. if (self.current708Packet === null) {
  10578. // This should only happen at the start of a file if there's no packet start.
  10579. self.new708Packet();
  10580. }
  10581. self.add708Bytes(packet);
  10582. }
  10583. };
  10584. };
  10585. Cea708Stream.prototype = new Stream$7();
  10586. /**
  10587. * Push current 708 packet, create new 708 packet.
  10588. */
  10589. Cea708Stream.prototype.new708Packet = function () {
  10590. if (this.current708Packet !== null) {
  10591. this.push708Packet();
  10592. }
  10593. this.current708Packet = {
  10594. data: [],
  10595. ptsVals: []
  10596. };
  10597. };
  10598. /**
  10599. * Add pts and both bytes from packet into current 708 packet.
  10600. */
  10601. Cea708Stream.prototype.add708Bytes = function (packet) {
  10602. var data = packet.ccData;
  10603. var byte0 = data >>> 8;
  10604. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  10605. // that service blocks will always line up with byte pairs.
  10606. this.current708Packet.ptsVals.push(packet.pts);
  10607. this.current708Packet.data.push(byte0);
  10608. this.current708Packet.data.push(byte1);
  10609. };
  10610. /**
  10611. * Parse completed 708 packet into service blocks and push each service block.
  10612. */
  10613. Cea708Stream.prototype.push708Packet = function () {
  10614. var packet708 = this.current708Packet;
  10615. var packetData = packet708.data;
  10616. var serviceNum = null;
  10617. var blockSize = null;
  10618. var i = 0;
  10619. var b = packetData[i++];
  10620. packet708.seq = b >> 6;
  10621. packet708.sizeCode = b & 0x3f; // 0b00111111;
  10622. for (; i < packetData.length; i++) {
  10623. b = packetData[i++];
  10624. serviceNum = b >> 5;
  10625. blockSize = b & 0x1f; // 0b00011111
  10626. if (serviceNum === 7 && blockSize > 0) {
  10627. // Extended service num
  10628. b = packetData[i++];
  10629. serviceNum = b;
  10630. }
  10631. this.pushServiceBlock(serviceNum, i, blockSize);
  10632. if (blockSize > 0) {
  10633. i += blockSize - 1;
  10634. }
  10635. }
  10636. };
  10637. /**
  10638. * Parse service block, execute commands, read text.
  10639. *
  10640. * Note: While many of these commands serve important purposes,
  10641. * many others just parse out the parameters or attributes, but
  10642. * nothing is done with them because this is not a full and complete
  10643. * implementation of the entire 708 spec.
  10644. *
  10645. * @param {Integer} serviceNum Service number
  10646. * @param {Integer} start Start index of the 708 packet data
  10647. * @param {Integer} size Block size
  10648. */
  10649. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  10650. var b;
  10651. var i = start;
  10652. var packetData = this.current708Packet.data;
  10653. var service = this.services[serviceNum];
  10654. if (!service) {
  10655. service = this.initService(serviceNum, i);
  10656. }
  10657. for (; i < start + size && i < packetData.length; i++) {
  10658. b = packetData[i];
  10659. if (within708TextBlock(b)) {
  10660. i = this.handleText(i, service);
  10661. } else if (b === 0x18) {
  10662. i = this.multiByteCharacter(i, service);
  10663. } else if (b === 0x10) {
  10664. i = this.extendedCommands(i, service);
  10665. } else if (0x80 <= b && b <= 0x87) {
  10666. i = this.setCurrentWindow(i, service);
  10667. } else if (0x98 <= b && b <= 0x9f) {
  10668. i = this.defineWindow(i, service);
  10669. } else if (b === 0x88) {
  10670. i = this.clearWindows(i, service);
  10671. } else if (b === 0x8c) {
  10672. i = this.deleteWindows(i, service);
  10673. } else if (b === 0x89) {
  10674. i = this.displayWindows(i, service);
  10675. } else if (b === 0x8a) {
  10676. i = this.hideWindows(i, service);
  10677. } else if (b === 0x8b) {
  10678. i = this.toggleWindows(i, service);
  10679. } else if (b === 0x97) {
  10680. i = this.setWindowAttributes(i, service);
  10681. } else if (b === 0x90) {
  10682. i = this.setPenAttributes(i, service);
  10683. } else if (b === 0x91) {
  10684. i = this.setPenColor(i, service);
  10685. } else if (b === 0x92) {
  10686. i = this.setPenLocation(i, service);
  10687. } else if (b === 0x8f) {
  10688. service = this.reset(i, service);
  10689. } else if (b === 0x08) {
  10690. // BS: Backspace
  10691. service.currentWindow.backspace();
  10692. } else if (b === 0x0c) {
  10693. // FF: Form feed
  10694. service.currentWindow.clearText();
  10695. } else if (b === 0x0d) {
  10696. // CR: Carriage return
  10697. service.currentWindow.pendingNewLine = true;
  10698. } else if (b === 0x0e) {
  10699. // HCR: Horizontal carriage return
  10700. service.currentWindow.clearText();
  10701. } else if (b === 0x8d) {
  10702. // DLY: Delay, nothing to do
  10703. i++;
  10704. } else ;
  10705. }
  10706. };
  10707. /**
  10708. * Execute an extended command
  10709. *
  10710. * @param {Integer} i Current index in the 708 packet
  10711. * @param {Service} service The service object to be affected
  10712. * @return {Integer} New index after parsing
  10713. */
  10714. Cea708Stream.prototype.extendedCommands = function (i, service) {
  10715. var packetData = this.current708Packet.data;
  10716. var b = packetData[++i];
  10717. if (within708TextBlock(b)) {
  10718. i = this.handleText(i, service, {
  10719. isExtended: true
  10720. });
  10721. }
  10722. return i;
  10723. };
  10724. /**
  10725. * Get PTS value of a given byte index
  10726. *
  10727. * @param {Integer} byteIndex Index of the byte
  10728. * @return {Integer} PTS
  10729. */
  10730. Cea708Stream.prototype.getPts = function (byteIndex) {
  10731. // There's 1 pts value per 2 bytes
  10732. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  10733. };
  10734. /**
  10735. * Initializes a service
  10736. *
  10737. * @param {Integer} serviceNum Service number
  10738. * @return {Service} Initialized service object
  10739. */
  10740. Cea708Stream.prototype.initService = function (serviceNum, i) {
  10741. var serviceName = 'SERVICE' + serviceNum;
  10742. var self = this;
  10743. var serviceName;
  10744. var encoding;
  10745. if (serviceName in this.serviceEncodings) {
  10746. encoding = this.serviceEncodings[serviceName];
  10747. }
  10748. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  10749. this.services[serviceNum].init(this.getPts(i), function (pts) {
  10750. self.flushDisplayed(pts, self.services[serviceNum]);
  10751. });
  10752. return this.services[serviceNum];
  10753. };
  10754. /**
  10755. * Execute text writing to current window
  10756. *
  10757. * @param {Integer} i Current index in the 708 packet
  10758. * @param {Service} service The service object to be affected
  10759. * @return {Integer} New index after parsing
  10760. */
  10761. Cea708Stream.prototype.handleText = function (i, service, options) {
  10762. var isExtended = options && options.isExtended;
  10763. var isMultiByte = options && options.isMultiByte;
  10764. var packetData = this.current708Packet.data;
  10765. var extended = isExtended ? 0x1000 : 0x0000;
  10766. var currentByte = packetData[i];
  10767. var nextByte = packetData[i + 1];
  10768. var win = service.currentWindow;
  10769. var char;
  10770. var charCodeArray; // Converts an array of bytes to a unicode hex string.
  10771. function toHexString(byteArray) {
  10772. return byteArray.map(byte => {
  10773. return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  10774. }).join('');
  10775. }
  10776. if (isMultiByte) {
  10777. charCodeArray = [currentByte, nextByte];
  10778. i++;
  10779. } else {
  10780. charCodeArray = [currentByte];
  10781. } // Use the TextDecoder if one was created for this service
  10782. if (service.textDecoder_ && !isExtended) {
  10783. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  10784. } else {
  10785. // We assume any multi-byte char without a decoder is unicode.
  10786. if (isMultiByte) {
  10787. const unicode = toHexString(charCodeArray); // Takes a unicode hex string and creates a single character.
  10788. char = String.fromCharCode(parseInt(unicode, 16));
  10789. } else {
  10790. char = get708CharFromCode(extended | currentByte);
  10791. }
  10792. }
  10793. if (win.pendingNewLine && !win.isEmpty()) {
  10794. win.newLine(this.getPts(i));
  10795. }
  10796. win.pendingNewLine = false;
  10797. win.addText(char);
  10798. return i;
  10799. };
  10800. /**
  10801. * Handle decoding of multibyte character
  10802. *
  10803. * @param {Integer} i Current index in the 708 packet
  10804. * @param {Service} service The service object to be affected
  10805. * @return {Integer} New index after parsing
  10806. */
  10807. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  10808. var packetData = this.current708Packet.data;
  10809. var firstByte = packetData[i + 1];
  10810. var secondByte = packetData[i + 2];
  10811. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  10812. i = this.handleText(++i, service, {
  10813. isMultiByte: true
  10814. });
  10815. }
  10816. return i;
  10817. };
  10818. /**
  10819. * Parse and execute the CW# command.
  10820. *
  10821. * Set the current window.
  10822. *
  10823. * @param {Integer} i Current index in the 708 packet
  10824. * @param {Service} service The service object to be affected
  10825. * @return {Integer} New index after parsing
  10826. */
  10827. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  10828. var packetData = this.current708Packet.data;
  10829. var b = packetData[i];
  10830. var windowNum = b & 0x07;
  10831. service.setCurrentWindow(windowNum);
  10832. return i;
  10833. };
  10834. /**
  10835. * Parse and execute the DF# command.
  10836. *
  10837. * Define a window and set it as the current window.
  10838. *
  10839. * @param {Integer} i Current index in the 708 packet
  10840. * @param {Service} service The service object to be affected
  10841. * @return {Integer} New index after parsing
  10842. */
  10843. Cea708Stream.prototype.defineWindow = function (i, service) {
  10844. var packetData = this.current708Packet.data;
  10845. var b = packetData[i];
  10846. var windowNum = b & 0x07;
  10847. service.setCurrentWindow(windowNum);
  10848. var win = service.currentWindow;
  10849. b = packetData[++i];
  10850. win.visible = (b & 0x20) >> 5; // v
  10851. win.rowLock = (b & 0x10) >> 4; // rl
  10852. win.columnLock = (b & 0x08) >> 3; // cl
  10853. win.priority = b & 0x07; // p
  10854. b = packetData[++i];
  10855. win.relativePositioning = (b & 0x80) >> 7; // rp
  10856. win.anchorVertical = b & 0x7f; // av
  10857. b = packetData[++i];
  10858. win.anchorHorizontal = b; // ah
  10859. b = packetData[++i];
  10860. win.anchorPoint = (b & 0xf0) >> 4; // ap
  10861. win.rowCount = b & 0x0f; // rc
  10862. b = packetData[++i];
  10863. win.columnCount = b & 0x3f; // cc
  10864. b = packetData[++i];
  10865. win.windowStyle = (b & 0x38) >> 3; // ws
  10866. win.penStyle = b & 0x07; // ps
  10867. // The spec says there are (rowCount+1) "virtual rows"
  10868. win.virtualRowCount = win.rowCount + 1;
  10869. return i;
  10870. };
  10871. /**
  10872. * Parse and execute the SWA command.
  10873. *
  10874. * Set attributes of the current window.
  10875. *
  10876. * @param {Integer} i Current index in the 708 packet
  10877. * @param {Service} service The service object to be affected
  10878. * @return {Integer} New index after parsing
  10879. */
  10880. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  10881. var packetData = this.current708Packet.data;
  10882. var b = packetData[i];
  10883. var winAttr = service.currentWindow.winAttr;
  10884. b = packetData[++i];
  10885. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  10886. winAttr.fillRed = (b & 0x30) >> 4; // fr
  10887. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  10888. winAttr.fillBlue = b & 0x03; // fb
  10889. b = packetData[++i];
  10890. winAttr.borderType = (b & 0xc0) >> 6; // bt
  10891. winAttr.borderRed = (b & 0x30) >> 4; // br
  10892. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  10893. winAttr.borderBlue = b & 0x03; // bb
  10894. b = packetData[++i];
  10895. winAttr.borderType += (b & 0x80) >> 5; // bt
  10896. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  10897. winAttr.printDirection = (b & 0x30) >> 4; // pd
  10898. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  10899. winAttr.justify = b & 0x03; // j
  10900. b = packetData[++i];
  10901. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  10902. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  10903. winAttr.displayEffect = b & 0x03; // de
  10904. return i;
  10905. };
  10906. /**
  10907. * Gather text from all displayed windows and push a caption to output.
  10908. *
  10909. * @param {Integer} i Current index in the 708 packet
  10910. * @param {Service} service The service object to be affected
  10911. */
  10912. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  10913. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  10914. // display text in the correct order, but sample files so far have not shown any issue.
  10915. for (var winId = 0; winId < 8; winId++) {
  10916. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  10917. displayedText.push(service.windows[winId].getText());
  10918. }
  10919. }
  10920. service.endPts = pts;
  10921. service.text = displayedText.join('\n\n');
  10922. this.pushCaption(service);
  10923. service.startPts = pts;
  10924. };
  10925. /**
  10926. * Push a caption to output if the caption contains text.
  10927. *
  10928. * @param {Service} service The service object to be affected
  10929. */
  10930. Cea708Stream.prototype.pushCaption = function (service) {
  10931. if (service.text !== '') {
  10932. this.trigger('data', {
  10933. startPts: service.startPts,
  10934. endPts: service.endPts,
  10935. text: service.text,
  10936. stream: 'cc708_' + service.serviceNum
  10937. });
  10938. service.text = '';
  10939. service.startPts = service.endPts;
  10940. }
  10941. };
  10942. /**
  10943. * Parse and execute the DSW command.
  10944. *
  10945. * Set visible property of windows based on the parsed bitmask.
  10946. *
  10947. * @param {Integer} i Current index in the 708 packet
  10948. * @param {Service} service The service object to be affected
  10949. * @return {Integer} New index after parsing
  10950. */
  10951. Cea708Stream.prototype.displayWindows = function (i, service) {
  10952. var packetData = this.current708Packet.data;
  10953. var b = packetData[++i];
  10954. var pts = this.getPts(i);
  10955. this.flushDisplayed(pts, service);
  10956. for (var winId = 0; winId < 8; winId++) {
  10957. if (b & 0x01 << winId) {
  10958. service.windows[winId].visible = 1;
  10959. }
  10960. }
  10961. return i;
  10962. };
  10963. /**
  10964. * Parse and execute the HDW command.
  10965. *
  10966. * Set visible property of windows based on the parsed bitmask.
  10967. *
  10968. * @param {Integer} i Current index in the 708 packet
  10969. * @param {Service} service The service object to be affected
  10970. * @return {Integer} New index after parsing
  10971. */
  10972. Cea708Stream.prototype.hideWindows = function (i, service) {
  10973. var packetData = this.current708Packet.data;
  10974. var b = packetData[++i];
  10975. var pts = this.getPts(i);
  10976. this.flushDisplayed(pts, service);
  10977. for (var winId = 0; winId < 8; winId++) {
  10978. if (b & 0x01 << winId) {
  10979. service.windows[winId].visible = 0;
  10980. }
  10981. }
  10982. return i;
  10983. };
  10984. /**
  10985. * Parse and execute the TGW command.
  10986. *
  10987. * Set visible property of windows based on the parsed bitmask.
  10988. *
  10989. * @param {Integer} i Current index in the 708 packet
  10990. * @param {Service} service The service object to be affected
  10991. * @return {Integer} New index after parsing
  10992. */
  10993. Cea708Stream.prototype.toggleWindows = function (i, service) {
  10994. var packetData = this.current708Packet.data;
  10995. var b = packetData[++i];
  10996. var pts = this.getPts(i);
  10997. this.flushDisplayed(pts, service);
  10998. for (var winId = 0; winId < 8; winId++) {
  10999. if (b & 0x01 << winId) {
  11000. service.windows[winId].visible ^= 1;
  11001. }
  11002. }
  11003. return i;
  11004. };
  11005. /**
  11006. * Parse and execute the CLW command.
  11007. *
  11008. * Clear text of windows based on the parsed bitmask.
  11009. *
  11010. * @param {Integer} i Current index in the 708 packet
  11011. * @param {Service} service The service object to be affected
  11012. * @return {Integer} New index after parsing
  11013. */
  11014. Cea708Stream.prototype.clearWindows = function (i, service) {
  11015. var packetData = this.current708Packet.data;
  11016. var b = packetData[++i];
  11017. var pts = this.getPts(i);
  11018. this.flushDisplayed(pts, service);
  11019. for (var winId = 0; winId < 8; winId++) {
  11020. if (b & 0x01 << winId) {
  11021. service.windows[winId].clearText();
  11022. }
  11023. }
  11024. return i;
  11025. };
  11026. /**
  11027. * Parse and execute the DLW command.
  11028. *
  11029. * Re-initialize windows based on the parsed bitmask.
  11030. *
  11031. * @param {Integer} i Current index in the 708 packet
  11032. * @param {Service} service The service object to be affected
  11033. * @return {Integer} New index after parsing
  11034. */
  11035. Cea708Stream.prototype.deleteWindows = function (i, service) {
  11036. var packetData = this.current708Packet.data;
  11037. var b = packetData[++i];
  11038. var pts = this.getPts(i);
  11039. this.flushDisplayed(pts, service);
  11040. for (var winId = 0; winId < 8; winId++) {
  11041. if (b & 0x01 << winId) {
  11042. service.windows[winId].reset();
  11043. }
  11044. }
  11045. return i;
  11046. };
  11047. /**
  11048. * Parse and execute the SPA command.
  11049. *
  11050. * Set pen attributes of the current window.
  11051. *
  11052. * @param {Integer} i Current index in the 708 packet
  11053. * @param {Service} service The service object to be affected
  11054. * @return {Integer} New index after parsing
  11055. */
  11056. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  11057. var packetData = this.current708Packet.data;
  11058. var b = packetData[i];
  11059. var penAttr = service.currentWindow.penAttr;
  11060. b = packetData[++i];
  11061. penAttr.textTag = (b & 0xf0) >> 4; // tt
  11062. penAttr.offset = (b & 0x0c) >> 2; // o
  11063. penAttr.penSize = b & 0x03; // s
  11064. b = packetData[++i];
  11065. penAttr.italics = (b & 0x80) >> 7; // i
  11066. penAttr.underline = (b & 0x40) >> 6; // u
  11067. penAttr.edgeType = (b & 0x38) >> 3; // et
  11068. penAttr.fontStyle = b & 0x07; // fs
  11069. return i;
  11070. };
  11071. /**
  11072. * Parse and execute the SPC command.
  11073. *
  11074. * Set pen color of the current window.
  11075. *
  11076. * @param {Integer} i Current index in the 708 packet
  11077. * @param {Service} service The service object to be affected
  11078. * @return {Integer} New index after parsing
  11079. */
  11080. Cea708Stream.prototype.setPenColor = function (i, service) {
  11081. var packetData = this.current708Packet.data;
  11082. var b = packetData[i];
  11083. var penColor = service.currentWindow.penColor;
  11084. b = packetData[++i];
  11085. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  11086. penColor.fgRed = (b & 0x30) >> 4; // fr
  11087. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  11088. penColor.fgBlue = b & 0x03; // fb
  11089. b = packetData[++i];
  11090. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  11091. penColor.bgRed = (b & 0x30) >> 4; // br
  11092. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  11093. penColor.bgBlue = b & 0x03; // bb
  11094. b = packetData[++i];
  11095. penColor.edgeRed = (b & 0x30) >> 4; // er
  11096. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  11097. penColor.edgeBlue = b & 0x03; // eb
  11098. return i;
  11099. };
  11100. /**
  11101. * Parse and execute the SPL command.
  11102. *
  11103. * Set pen location of the current window.
  11104. *
  11105. * @param {Integer} i Current index in the 708 packet
  11106. * @param {Service} service The service object to be affected
  11107. * @return {Integer} New index after parsing
  11108. */
  11109. Cea708Stream.prototype.setPenLocation = function (i, service) {
  11110. var packetData = this.current708Packet.data;
  11111. var b = packetData[i];
  11112. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  11113. service.currentWindow.pendingNewLine = true;
  11114. b = packetData[++i];
  11115. penLoc.row = b & 0x0f; // r
  11116. b = packetData[++i];
  11117. penLoc.column = b & 0x3f; // c
  11118. return i;
  11119. };
  11120. /**
  11121. * Execute the RST command.
  11122. *
  11123. * Reset service to a clean slate. Re-initialize.
  11124. *
  11125. * @param {Integer} i Current index in the 708 packet
  11126. * @param {Service} service The service object to be affected
  11127. * @return {Service} Re-initialized service
  11128. */
  11129. Cea708Stream.prototype.reset = function (i, service) {
  11130. var pts = this.getPts(i);
  11131. this.flushDisplayed(pts, service);
  11132. return this.initService(service.serviceNum, i);
  11133. }; // This hash maps non-ASCII, special, and extended character codes to their
  11134. // proper Unicode equivalent. The first keys that are only a single byte
  11135. // are the non-standard ASCII characters, which simply map the CEA608 byte
  11136. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  11137. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  11138. // can be performed regardless of the field and data channel on which the
  11139. // character code was received.
  11140. var CHARACTER_TRANSLATION = {
  11141. 0x2a: 0xe1,
  11142. // á
  11143. 0x5c: 0xe9,
  11144. // é
  11145. 0x5e: 0xed,
  11146. // í
  11147. 0x5f: 0xf3,
  11148. // ó
  11149. 0x60: 0xfa,
  11150. // ú
  11151. 0x7b: 0xe7,
  11152. // ç
  11153. 0x7c: 0xf7,
  11154. // ÷
  11155. 0x7d: 0xd1,
  11156. // Ñ
  11157. 0x7e: 0xf1,
  11158. // ñ
  11159. 0x7f: 0x2588,
  11160. // █
  11161. 0x0130: 0xae,
  11162. // ®
  11163. 0x0131: 0xb0,
  11164. // °
  11165. 0x0132: 0xbd,
  11166. // ½
  11167. 0x0133: 0xbf,
  11168. // ¿
  11169. 0x0134: 0x2122,
  11170. // ™
  11171. 0x0135: 0xa2,
  11172. // ¢
  11173. 0x0136: 0xa3,
  11174. // £
  11175. 0x0137: 0x266a,
  11176. // ♪
  11177. 0x0138: 0xe0,
  11178. // à
  11179. 0x0139: 0xa0,
  11180. //
  11181. 0x013a: 0xe8,
  11182. // è
  11183. 0x013b: 0xe2,
  11184. // â
  11185. 0x013c: 0xea,
  11186. // ê
  11187. 0x013d: 0xee,
  11188. // î
  11189. 0x013e: 0xf4,
  11190. // ô
  11191. 0x013f: 0xfb,
  11192. // û
  11193. 0x0220: 0xc1,
  11194. // Á
  11195. 0x0221: 0xc9,
  11196. // É
  11197. 0x0222: 0xd3,
  11198. // Ó
  11199. 0x0223: 0xda,
  11200. // Ú
  11201. 0x0224: 0xdc,
  11202. // Ü
  11203. 0x0225: 0xfc,
  11204. // ü
  11205. 0x0226: 0x2018,
  11206. // ‘
  11207. 0x0227: 0xa1,
  11208. // ¡
  11209. 0x0228: 0x2a,
  11210. // *
  11211. 0x0229: 0x27,
  11212. // '
  11213. 0x022a: 0x2014,
  11214. // —
  11215. 0x022b: 0xa9,
  11216. // ©
  11217. 0x022c: 0x2120,
  11218. // ℠
  11219. 0x022d: 0x2022,
  11220. // •
  11221. 0x022e: 0x201c,
  11222. // “
  11223. 0x022f: 0x201d,
  11224. // ”
  11225. 0x0230: 0xc0,
  11226. // À
  11227. 0x0231: 0xc2,
  11228. // Â
  11229. 0x0232: 0xc7,
  11230. // Ç
  11231. 0x0233: 0xc8,
  11232. // È
  11233. 0x0234: 0xca,
  11234. // Ê
  11235. 0x0235: 0xcb,
  11236. // Ë
  11237. 0x0236: 0xeb,
  11238. // ë
  11239. 0x0237: 0xce,
  11240. // Î
  11241. 0x0238: 0xcf,
  11242. // Ï
  11243. 0x0239: 0xef,
  11244. // ï
  11245. 0x023a: 0xd4,
  11246. // Ô
  11247. 0x023b: 0xd9,
  11248. // Ù
  11249. 0x023c: 0xf9,
  11250. // ù
  11251. 0x023d: 0xdb,
  11252. // Û
  11253. 0x023e: 0xab,
  11254. // «
  11255. 0x023f: 0xbb,
  11256. // »
  11257. 0x0320: 0xc3,
  11258. // Ã
  11259. 0x0321: 0xe3,
  11260. // ã
  11261. 0x0322: 0xcd,
  11262. // Í
  11263. 0x0323: 0xcc,
  11264. // Ì
  11265. 0x0324: 0xec,
  11266. // ì
  11267. 0x0325: 0xd2,
  11268. // Ò
  11269. 0x0326: 0xf2,
  11270. // ò
  11271. 0x0327: 0xd5,
  11272. // Õ
  11273. 0x0328: 0xf5,
  11274. // õ
  11275. 0x0329: 0x7b,
  11276. // {
  11277. 0x032a: 0x7d,
  11278. // }
  11279. 0x032b: 0x5c,
  11280. // \
  11281. 0x032c: 0x5e,
  11282. // ^
  11283. 0x032d: 0x5f,
  11284. // _
  11285. 0x032e: 0x7c,
  11286. // |
  11287. 0x032f: 0x7e,
  11288. // ~
  11289. 0x0330: 0xc4,
  11290. // Ä
  11291. 0x0331: 0xe4,
  11292. // ä
  11293. 0x0332: 0xd6,
  11294. // Ö
  11295. 0x0333: 0xf6,
  11296. // ö
  11297. 0x0334: 0xdf,
  11298. // ß
  11299. 0x0335: 0xa5,
  11300. // ¥
  11301. 0x0336: 0xa4,
  11302. // ¤
  11303. 0x0337: 0x2502,
  11304. // │
  11305. 0x0338: 0xc5,
  11306. // Å
  11307. 0x0339: 0xe5,
  11308. // å
  11309. 0x033a: 0xd8,
  11310. // Ø
  11311. 0x033b: 0xf8,
  11312. // ø
  11313. 0x033c: 0x250c,
  11314. // ┌
  11315. 0x033d: 0x2510,
  11316. // ┐
  11317. 0x033e: 0x2514,
  11318. // └
  11319. 0x033f: 0x2518 // ┘
  11320. };
  11321. var getCharFromCode = function (code) {
  11322. if (code === null) {
  11323. return '';
  11324. }
  11325. code = CHARACTER_TRANSLATION[code] || code;
  11326. return String.fromCharCode(code);
  11327. }; // the index of the last row in a CEA-608 display buffer
  11328. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  11329. // getting it through bit logic.
  11330. 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
  11331. // cells. The "bottom" row is the last element in the outer array.
  11332. // We keep track of positioning information as we go by storing the
  11333. // number of indentations and the tab offset in this buffer.
  11334. var createDisplayBuffer = function () {
  11335. var result = [],
  11336. i = BOTTOM_ROW + 1;
  11337. while (i--) {
  11338. result.push({
  11339. text: '',
  11340. indent: 0,
  11341. offset: 0
  11342. });
  11343. }
  11344. return result;
  11345. };
  11346. var Cea608Stream = function (field, dataChannel) {
  11347. Cea608Stream.prototype.init.call(this);
  11348. this.field_ = field || 0;
  11349. this.dataChannel_ = dataChannel || 0;
  11350. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  11351. this.setConstants();
  11352. this.reset();
  11353. this.push = function (packet) {
  11354. var data, swap, char0, char1, text; // remove the parity bits
  11355. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  11356. if (data === this.lastControlCode_) {
  11357. this.lastControlCode_ = null;
  11358. return;
  11359. } // Store control codes
  11360. if ((data & 0xf000) === 0x1000) {
  11361. this.lastControlCode_ = data;
  11362. } else if (data !== this.PADDING_) {
  11363. this.lastControlCode_ = null;
  11364. }
  11365. char0 = data >>> 8;
  11366. char1 = data & 0xff;
  11367. if (data === this.PADDING_) {
  11368. return;
  11369. } else if (data === this.RESUME_CAPTION_LOADING_) {
  11370. this.mode_ = 'popOn';
  11371. } else if (data === this.END_OF_CAPTION_) {
  11372. // If an EOC is received while in paint-on mode, the displayed caption
  11373. // text should be swapped to non-displayed memory as if it was a pop-on
  11374. // caption. Because of that, we should explicitly switch back to pop-on
  11375. // mode
  11376. this.mode_ = 'popOn';
  11377. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  11378. this.flushDisplayed(packet.pts); // flip memory
  11379. swap = this.displayed_;
  11380. this.displayed_ = this.nonDisplayed_;
  11381. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  11382. this.startPts_ = packet.pts;
  11383. } else if (data === this.ROLL_UP_2_ROWS_) {
  11384. this.rollUpRows_ = 2;
  11385. this.setRollUp(packet.pts);
  11386. } else if (data === this.ROLL_UP_3_ROWS_) {
  11387. this.rollUpRows_ = 3;
  11388. this.setRollUp(packet.pts);
  11389. } else if (data === this.ROLL_UP_4_ROWS_) {
  11390. this.rollUpRows_ = 4;
  11391. this.setRollUp(packet.pts);
  11392. } else if (data === this.CARRIAGE_RETURN_) {
  11393. this.clearFormatting(packet.pts);
  11394. this.flushDisplayed(packet.pts);
  11395. this.shiftRowsUp_();
  11396. this.startPts_ = packet.pts;
  11397. } else if (data === this.BACKSPACE_) {
  11398. if (this.mode_ === 'popOn') {
  11399. this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);
  11400. } else {
  11401. this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);
  11402. }
  11403. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  11404. this.flushDisplayed(packet.pts);
  11405. this.displayed_ = createDisplayBuffer();
  11406. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  11407. this.nonDisplayed_ = createDisplayBuffer();
  11408. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  11409. if (this.mode_ !== 'paintOn') {
  11410. // NOTE: This should be removed when proper caption positioning is
  11411. // implemented
  11412. this.flushDisplayed(packet.pts);
  11413. this.displayed_ = createDisplayBuffer();
  11414. }
  11415. this.mode_ = 'paintOn';
  11416. this.startPts_ = packet.pts; // Append special characters to caption text
  11417. } else if (this.isSpecialCharacter(char0, char1)) {
  11418. // Bitmask char0 so that we can apply character transformations
  11419. // regardless of field and data channel.
  11420. // Then byte-shift to the left and OR with char1 so we can pass the
  11421. // entire character code to `getCharFromCode`.
  11422. char0 = (char0 & 0x03) << 8;
  11423. text = getCharFromCode(char0 | char1);
  11424. this[this.mode_](packet.pts, text);
  11425. this.column_++; // Append extended characters to caption text
  11426. } else if (this.isExtCharacter(char0, char1)) {
  11427. // Extended characters always follow their "non-extended" equivalents.
  11428. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  11429. // decoders are supposed to drop the "è", while compliant decoders
  11430. // backspace the "e" and insert "è".
  11431. // Delete the previous character
  11432. if (this.mode_ === 'popOn') {
  11433. this.nonDisplayed_[this.row_].text = this.nonDisplayed_[this.row_].text.slice(0, -1);
  11434. } else {
  11435. this.displayed_[this.row_].text = this.displayed_[this.row_].text.slice(0, -1);
  11436. } // Bitmask char0 so that we can apply character transformations
  11437. // regardless of field and data channel.
  11438. // Then byte-shift to the left and OR with char1 so we can pass the
  11439. // entire character code to `getCharFromCode`.
  11440. char0 = (char0 & 0x03) << 8;
  11441. text = getCharFromCode(char0 | char1);
  11442. this[this.mode_](packet.pts, text);
  11443. this.column_++; // Process mid-row codes
  11444. } else if (this.isMidRowCode(char0, char1)) {
  11445. // Attributes are not additive, so clear all formatting
  11446. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  11447. // should be replaced with spaces, so add one now
  11448. this[this.mode_](packet.pts, ' ');
  11449. this.column_++;
  11450. if ((char1 & 0xe) === 0xe) {
  11451. this.addFormatting(packet.pts, ['i']);
  11452. }
  11453. if ((char1 & 0x1) === 0x1) {
  11454. this.addFormatting(packet.pts, ['u']);
  11455. } // Detect offset control codes and adjust cursor
  11456. } else if (this.isOffsetControlCode(char0, char1)) {
  11457. // Cursor position is set by indent PAC (see below) in 4-column
  11458. // increments, with an additional offset code of 1-3 to reach any
  11459. // of the 32 columns specified by CEA-608. So all we need to do
  11460. // here is increment the column cursor by the given offset.
  11461. const offset = char1 & 0x03; // For an offest value 1-3, set the offset for that caption
  11462. // in the non-displayed array.
  11463. this.nonDisplayed_[this.row_].offset = offset;
  11464. this.column_ += offset; // Detect PACs (Preamble Address Codes)
  11465. } else if (this.isPAC(char0, char1)) {
  11466. // There's no logic for PAC -> row mapping, so we have to just
  11467. // find the row code in an array and use its index :(
  11468. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  11469. if (this.mode_ === 'rollUp') {
  11470. // This implies that the base row is incorrectly set.
  11471. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  11472. // of roll-up rows set.
  11473. if (row - this.rollUpRows_ + 1 < 0) {
  11474. row = this.rollUpRows_ - 1;
  11475. }
  11476. this.setRollUp(packet.pts, row);
  11477. }
  11478. if (row !== this.row_) {
  11479. // formatting is only persistent for current row
  11480. this.clearFormatting(packet.pts);
  11481. this.row_ = row;
  11482. } // All PACs can apply underline, so detect and apply
  11483. // (All odd-numbered second bytes set underline)
  11484. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  11485. this.addFormatting(packet.pts, ['u']);
  11486. }
  11487. if ((data & 0x10) === 0x10) {
  11488. // We've got an indent level code. Each successive even number
  11489. // increments the column cursor by 4, so we can get the desired
  11490. // column position by bit-shifting to the right (to get n/2)
  11491. // and multiplying by 4.
  11492. const indentations = (data & 0xe) >> 1;
  11493. this.column_ = indentations * 4; // add to the number of indentations for positioning
  11494. this.nonDisplayed_[this.row_].indent += indentations;
  11495. }
  11496. if (this.isColorPAC(char1)) {
  11497. // it's a color code, though we only support white, which
  11498. // can be either normal or italicized. white italics can be
  11499. // either 0x4e or 0x6e depending on the row, so we just
  11500. // bitwise-and with 0xe to see if italics should be turned on
  11501. if ((char1 & 0xe) === 0xe) {
  11502. this.addFormatting(packet.pts, ['i']);
  11503. }
  11504. } // We have a normal character in char0, and possibly one in char1
  11505. } else if (this.isNormalChar(char0)) {
  11506. if (char1 === 0x00) {
  11507. char1 = null;
  11508. }
  11509. text = getCharFromCode(char0);
  11510. text += getCharFromCode(char1);
  11511. this[this.mode_](packet.pts, text);
  11512. this.column_ += text.length;
  11513. } // finish data processing
  11514. };
  11515. };
  11516. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  11517. // display buffer
  11518. Cea608Stream.prototype.flushDisplayed = function (pts) {
  11519. const logWarning = index => {
  11520. this.trigger('log', {
  11521. level: 'warn',
  11522. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  11523. });
  11524. };
  11525. const content = [];
  11526. this.displayed_.forEach((row, i) => {
  11527. if (row && row.text && row.text.length) {
  11528. try {
  11529. // remove spaces from the start and end of the string
  11530. row.text = row.text.trim();
  11531. } catch (e) {
  11532. // Ordinarily, this shouldn't happen. However, caption
  11533. // parsing errors should not throw exceptions and
  11534. // break playback.
  11535. logWarning(i);
  11536. } // See the below link for more details on the following fields:
  11537. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  11538. if (row.text.length) {
  11539. content.push({
  11540. // The text to be displayed in the caption from this specific row, with whitespace removed.
  11541. text: row.text,
  11542. // Value between 1 and 15 representing the PAC row used to calculate line height.
  11543. line: i + 1,
  11544. // A number representing the indent position by percentage (CEA-608 PAC indent code).
  11545. // The value will be a number between 10 and 80. Offset is used to add an aditional
  11546. // value to the position if necessary.
  11547. position: 10 + Math.min(70, row.indent * 10) + row.offset * 2.5
  11548. });
  11549. }
  11550. } else if (row === undefined || row === null) {
  11551. logWarning(i);
  11552. }
  11553. });
  11554. if (content.length) {
  11555. this.trigger('data', {
  11556. startPts: this.startPts_,
  11557. endPts: pts,
  11558. content,
  11559. stream: this.name_
  11560. });
  11561. }
  11562. };
  11563. /**
  11564. * Zero out the data, used for startup and on seek
  11565. */
  11566. Cea608Stream.prototype.reset = function () {
  11567. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  11568. // actually display captions. If a caption is shifted to a row
  11569. // with a lower index than this, it is cleared from the display
  11570. // buffer
  11571. this.topRow_ = 0;
  11572. this.startPts_ = 0;
  11573. this.displayed_ = createDisplayBuffer();
  11574. this.nonDisplayed_ = createDisplayBuffer();
  11575. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  11576. this.column_ = 0;
  11577. this.row_ = BOTTOM_ROW;
  11578. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  11579. this.formatting_ = [];
  11580. };
  11581. /**
  11582. * Sets up control code and related constants for this instance
  11583. */
  11584. Cea608Stream.prototype.setConstants = function () {
  11585. // The following attributes have these uses:
  11586. // ext_ : char0 for mid-row codes, and the base for extended
  11587. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  11588. // extended codes)
  11589. // control_: char0 for control codes, except byte-shifted to the
  11590. // left so that we can do this.control_ | CONTROL_CODE
  11591. // offset_: char0 for tab offset codes
  11592. //
  11593. // It's also worth noting that control codes, and _only_ control codes,
  11594. // differ between field 1 and field2. Field 2 control codes are always
  11595. // their field 1 value plus 1. That's why there's the "| field" on the
  11596. // control value.
  11597. if (this.dataChannel_ === 0) {
  11598. this.BASE_ = 0x10;
  11599. this.EXT_ = 0x11;
  11600. this.CONTROL_ = (0x14 | this.field_) << 8;
  11601. this.OFFSET_ = 0x17;
  11602. } else if (this.dataChannel_ === 1) {
  11603. this.BASE_ = 0x18;
  11604. this.EXT_ = 0x19;
  11605. this.CONTROL_ = (0x1c | this.field_) << 8;
  11606. this.OFFSET_ = 0x1f;
  11607. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  11608. // list is not exhaustive. For a more comprehensive listing and semantics see
  11609. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  11610. // Padding
  11611. this.PADDING_ = 0x0000; // Pop-on Mode
  11612. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  11613. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  11614. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  11615. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  11616. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  11617. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  11618. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  11619. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  11620. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  11621. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  11622. };
  11623. /**
  11624. * Detects if the 2-byte packet data is a special character
  11625. *
  11626. * Special characters have a second byte in the range 0x30 to 0x3f,
  11627. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  11628. * data channel 2).
  11629. *
  11630. * @param {Integer} char0 The first byte
  11631. * @param {Integer} char1 The second byte
  11632. * @return {Boolean} Whether the 2 bytes are an special character
  11633. */
  11634. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  11635. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  11636. };
  11637. /**
  11638. * Detects if the 2-byte packet data is an extended character
  11639. *
  11640. * Extended characters have a second byte in the range 0x20 to 0x3f,
  11641. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  11642. * 0x1a or 0x1b (for data channel 2).
  11643. *
  11644. * @param {Integer} char0 The first byte
  11645. * @param {Integer} char1 The second byte
  11646. * @return {Boolean} Whether the 2 bytes are an extended character
  11647. */
  11648. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  11649. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  11650. };
  11651. /**
  11652. * Detects if the 2-byte packet is a mid-row code
  11653. *
  11654. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  11655. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  11656. * channel 2).
  11657. *
  11658. * @param {Integer} char0 The first byte
  11659. * @param {Integer} char1 The second byte
  11660. * @return {Boolean} Whether the 2 bytes are a mid-row code
  11661. */
  11662. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  11663. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  11664. };
  11665. /**
  11666. * Detects if the 2-byte packet is an offset control code
  11667. *
  11668. * Offset control codes have a second byte in the range 0x21 to 0x23,
  11669. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  11670. * data channel 2).
  11671. *
  11672. * @param {Integer} char0 The first byte
  11673. * @param {Integer} char1 The second byte
  11674. * @return {Boolean} Whether the 2 bytes are an offset control code
  11675. */
  11676. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  11677. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  11678. };
  11679. /**
  11680. * Detects if the 2-byte packet is a Preamble Address Code
  11681. *
  11682. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  11683. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  11684. * range 0x40 to 0x7f.
  11685. *
  11686. * @param {Integer} char0 The first byte
  11687. * @param {Integer} char1 The second byte
  11688. * @return {Boolean} Whether the 2 bytes are a PAC
  11689. */
  11690. Cea608Stream.prototype.isPAC = function (char0, char1) {
  11691. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  11692. };
  11693. /**
  11694. * Detects if a packet's second byte is in the range of a PAC color code
  11695. *
  11696. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  11697. * 0x60 to 0x6f.
  11698. *
  11699. * @param {Integer} char1 The second byte
  11700. * @return {Boolean} Whether the byte is a color PAC
  11701. */
  11702. Cea608Stream.prototype.isColorPAC = function (char1) {
  11703. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  11704. };
  11705. /**
  11706. * Detects if a single byte is in the range of a normal character
  11707. *
  11708. * Normal text bytes are in the range 0x20 to 0x7f.
  11709. *
  11710. * @param {Integer} char The byte
  11711. * @return {Boolean} Whether the byte is a normal character
  11712. */
  11713. Cea608Stream.prototype.isNormalChar = function (char) {
  11714. return char >= 0x20 && char <= 0x7f;
  11715. };
  11716. /**
  11717. * Configures roll-up
  11718. *
  11719. * @param {Integer} pts Current PTS
  11720. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  11721. * a new position
  11722. */
  11723. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  11724. // Reset the base row to the bottom row when switching modes
  11725. if (this.mode_ !== 'rollUp') {
  11726. this.row_ = BOTTOM_ROW;
  11727. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  11728. this.flushDisplayed(pts);
  11729. this.nonDisplayed_ = createDisplayBuffer();
  11730. this.displayed_ = createDisplayBuffer();
  11731. }
  11732. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  11733. // move currently displayed captions (up or down) to the new base row
  11734. for (var i = 0; i < this.rollUpRows_; i++) {
  11735. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  11736. this.displayed_[this.row_ - i] = {
  11737. text: '',
  11738. indent: 0,
  11739. offset: 0
  11740. };
  11741. }
  11742. }
  11743. if (newBaseRow === undefined) {
  11744. newBaseRow = this.row_;
  11745. }
  11746. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  11747. }; // Adds the opening HTML tag for the passed character to the caption text,
  11748. // and keeps track of it for later closing
  11749. Cea608Stream.prototype.addFormatting = function (pts, format) {
  11750. this.formatting_ = this.formatting_.concat(format);
  11751. var text = format.reduce(function (text, format) {
  11752. return text + '<' + format + '>';
  11753. }, '');
  11754. this[this.mode_](pts, text);
  11755. }; // Adds HTML closing tags for current formatting to caption text and
  11756. // clears remembered formatting
  11757. Cea608Stream.prototype.clearFormatting = function (pts) {
  11758. if (!this.formatting_.length) {
  11759. return;
  11760. }
  11761. var text = this.formatting_.reverse().reduce(function (text, format) {
  11762. return text + '</' + format + '>';
  11763. }, '');
  11764. this.formatting_ = [];
  11765. this[this.mode_](pts, text);
  11766. }; // Mode Implementations
  11767. Cea608Stream.prototype.popOn = function (pts, text) {
  11768. var baseRow = this.nonDisplayed_[this.row_].text; // buffer characters
  11769. baseRow += text;
  11770. this.nonDisplayed_[this.row_].text = baseRow;
  11771. };
  11772. Cea608Stream.prototype.rollUp = function (pts, text) {
  11773. var baseRow = this.displayed_[this.row_].text;
  11774. baseRow += text;
  11775. this.displayed_[this.row_].text = baseRow;
  11776. };
  11777. Cea608Stream.prototype.shiftRowsUp_ = function () {
  11778. var i; // clear out inactive rows
  11779. for (i = 0; i < this.topRow_; i++) {
  11780. this.displayed_[i] = {
  11781. text: '',
  11782. indent: 0,
  11783. offset: 0
  11784. };
  11785. }
  11786. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  11787. this.displayed_[i] = {
  11788. text: '',
  11789. indent: 0,
  11790. offset: 0
  11791. };
  11792. } // shift displayed rows up
  11793. for (i = this.topRow_; i < this.row_; i++) {
  11794. this.displayed_[i] = this.displayed_[i + 1];
  11795. } // clear out the bottom row
  11796. this.displayed_[this.row_] = {
  11797. text: '',
  11798. indent: 0,
  11799. offset: 0
  11800. };
  11801. };
  11802. Cea608Stream.prototype.paintOn = function (pts, text) {
  11803. var baseRow = this.displayed_[this.row_].text;
  11804. baseRow += text;
  11805. this.displayed_[this.row_].text = baseRow;
  11806. }; // exports
  11807. var captionStream = {
  11808. CaptionStream: CaptionStream$2,
  11809. Cea608Stream: Cea608Stream,
  11810. Cea708Stream: Cea708Stream
  11811. };
  11812. /**
  11813. * mux.js
  11814. *
  11815. * Copyright (c) Brightcove
  11816. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11817. */
  11818. var streamTypes = {
  11819. H264_STREAM_TYPE: 0x1B,
  11820. ADTS_STREAM_TYPE: 0x0F,
  11821. METADATA_STREAM_TYPE: 0x15
  11822. };
  11823. /**
  11824. * mux.js
  11825. *
  11826. * Copyright (c) Brightcove
  11827. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11828. *
  11829. * Accepts program elementary stream (PES) data events and corrects
  11830. * decode and presentation time stamps to account for a rollover
  11831. * of the 33 bit value.
  11832. */
  11833. var Stream$6 = stream;
  11834. var MAX_TS = 8589934592;
  11835. var RO_THRESH = 4294967296;
  11836. var TYPE_SHARED = 'shared';
  11837. var handleRollover$1 = function (value, reference) {
  11838. var direction = 1;
  11839. if (value > reference) {
  11840. // If the current timestamp value is greater than our reference timestamp and we detect a
  11841. // timestamp rollover, this means the roll over is happening in the opposite direction.
  11842. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  11843. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  11844. // rollover point. In loading this segment, the timestamp values will be very large,
  11845. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  11846. // the time stamp to be `value - 2^33`.
  11847. direction = -1;
  11848. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  11849. // cause an incorrect adjustment.
  11850. while (Math.abs(reference - value) > RO_THRESH) {
  11851. value += direction * MAX_TS;
  11852. }
  11853. return value;
  11854. };
  11855. var TimestampRolloverStream$1 = function (type) {
  11856. var lastDTS, referenceDTS;
  11857. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  11858. // video and audio. We could use `undefined` here, but having a string
  11859. // makes debugging a little clearer.
  11860. this.type_ = type || TYPE_SHARED;
  11861. this.push = function (data) {
  11862. /**
  11863. * Rollover stream expects data from elementary stream.
  11864. * Elementary stream can push forward 2 types of data
  11865. * - Parsed Video/Audio/Timed-metadata PES (packetized elementary stream) packets
  11866. * - Tracks metadata from PMT (Program Map Table)
  11867. * Rollover stream expects pts/dts info to be available, since it stores lastDTS
  11868. * We should ignore non-PES packets since they may override lastDTS to undefined.
  11869. * lastDTS is important to signal the next segments
  11870. * about rollover from the previous segments.
  11871. */
  11872. if (data.type === 'metadata') {
  11873. this.trigger('data', data);
  11874. return;
  11875. } // Any "shared" rollover streams will accept _all_ data. Otherwise,
  11876. // streams will only accept data that matches their type.
  11877. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  11878. return;
  11879. }
  11880. if (referenceDTS === undefined) {
  11881. referenceDTS = data.dts;
  11882. }
  11883. data.dts = handleRollover$1(data.dts, referenceDTS);
  11884. data.pts = handleRollover$1(data.pts, referenceDTS);
  11885. lastDTS = data.dts;
  11886. this.trigger('data', data);
  11887. };
  11888. this.flush = function () {
  11889. referenceDTS = lastDTS;
  11890. this.trigger('done');
  11891. };
  11892. this.endTimeline = function () {
  11893. this.flush();
  11894. this.trigger('endedtimeline');
  11895. };
  11896. this.discontinuity = function () {
  11897. referenceDTS = void 0;
  11898. lastDTS = void 0;
  11899. };
  11900. this.reset = function () {
  11901. this.discontinuity();
  11902. this.trigger('reset');
  11903. };
  11904. };
  11905. TimestampRolloverStream$1.prototype = new Stream$6();
  11906. var timestampRolloverStream = {
  11907. TimestampRolloverStream: TimestampRolloverStream$1,
  11908. handleRollover: handleRollover$1
  11909. }; // Once IE11 support is dropped, this function should be removed.
  11910. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  11911. if (!typedArray) {
  11912. return -1;
  11913. }
  11914. var currentIndex = fromIndex;
  11915. for (; currentIndex < typedArray.length; currentIndex++) {
  11916. if (typedArray[currentIndex] === element) {
  11917. return currentIndex;
  11918. }
  11919. }
  11920. return -1;
  11921. };
  11922. var typedArray = {
  11923. typedArrayIndexOf: typedArrayIndexOf$1
  11924. };
  11925. /**
  11926. * mux.js
  11927. *
  11928. * Copyright (c) Brightcove
  11929. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  11930. *
  11931. * Tools for parsing ID3 frame data
  11932. * @see http://id3.org/id3v2.3.0
  11933. */
  11934. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  11935. // Frames that allow different types of text encoding contain a text
  11936. // encoding description byte [ID3v2.4.0 section 4.]
  11937. textEncodingDescriptionByte = {
  11938. Iso88591: 0x00,
  11939. // ISO-8859-1, terminated with \0.
  11940. Utf16: 0x01,
  11941. // UTF-16 encoded Unicode BOM, terminated with \0\0
  11942. Utf16be: 0x02,
  11943. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  11944. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  11945. },
  11946. // return a percent-encoded representation of the specified byte range
  11947. // @see http://en.wikipedia.org/wiki/Percent-encoding
  11948. percentEncode$1 = function (bytes, start, end) {
  11949. var i,
  11950. result = '';
  11951. for (i = start; i < end; i++) {
  11952. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  11953. }
  11954. return result;
  11955. },
  11956. // return the string representation of the specified byte range,
  11957. // interpreted as UTf-8.
  11958. parseUtf8 = function (bytes, start, end) {
  11959. return decodeURIComponent(percentEncode$1(bytes, start, end));
  11960. },
  11961. // return the string representation of the specified byte range,
  11962. // interpreted as ISO-8859-1.
  11963. parseIso88591$1 = function (bytes, start, end) {
  11964. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  11965. },
  11966. parseSyncSafeInteger$1 = function (data) {
  11967. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  11968. },
  11969. frameParsers = {
  11970. 'APIC': function (frame) {
  11971. var i = 1,
  11972. mimeTypeEndIndex,
  11973. descriptionEndIndex,
  11974. LINK_MIME_TYPE = '-->';
  11975. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  11976. // ignore frames with unrecognized character encodings
  11977. return;
  11978. } // parsing fields [ID3v2.4.0 section 4.14.]
  11979. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11980. if (mimeTypeEndIndex < 0) {
  11981. // malformed frame
  11982. return;
  11983. } // parsing Mime type field (terminated with \0)
  11984. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  11985. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  11986. frame.pictureType = frame.data[i];
  11987. i++;
  11988. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  11989. if (descriptionEndIndex < 0) {
  11990. // malformed frame
  11991. return;
  11992. } // parsing Description field (terminated with \0)
  11993. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  11994. i = descriptionEndIndex + 1;
  11995. if (frame.mimeType === LINK_MIME_TYPE) {
  11996. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  11997. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  11998. } else {
  11999. // parsing Picture Data field as binary data
  12000. frame.pictureData = frame.data.subarray(i, frame.data.length);
  12001. }
  12002. },
  12003. 'T*': function (frame) {
  12004. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  12005. // ignore frames with unrecognized character encodings
  12006. return;
  12007. } // parse text field, do not include null terminator in the frame value
  12008. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  12009. 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.]
  12010. frame.values = frame.value.split('\0');
  12011. },
  12012. 'TXXX': function (frame) {
  12013. var descriptionEndIndex;
  12014. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  12015. // ignore frames with unrecognized character encodings
  12016. return;
  12017. }
  12018. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  12019. if (descriptionEndIndex === -1) {
  12020. return;
  12021. } // parse the text fields
  12022. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  12023. // frames that allow different types of encoding contain terminated text
  12024. // [ID3v2.4.0 section 4.]
  12025. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  12026. frame.data = frame.value;
  12027. },
  12028. 'W*': function (frame) {
  12029. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  12030. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  12031. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  12032. },
  12033. 'WXXX': function (frame) {
  12034. var descriptionEndIndex;
  12035. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  12036. // ignore frames with unrecognized character encodings
  12037. return;
  12038. }
  12039. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  12040. if (descriptionEndIndex === -1) {
  12041. return;
  12042. } // parse the description and URL fields
  12043. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  12044. // if the value is followed by a string termination all the following information
  12045. // should be ignored [ID3v2.4.0 section 4.3]
  12046. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  12047. },
  12048. 'PRIV': function (frame) {
  12049. var i;
  12050. for (i = 0; i < frame.data.length; i++) {
  12051. if (frame.data[i] === 0) {
  12052. // parse the description and URL fields
  12053. frame.owner = parseIso88591$1(frame.data, 0, i);
  12054. break;
  12055. }
  12056. }
  12057. frame.privateData = frame.data.subarray(i + 1);
  12058. frame.data = frame.privateData;
  12059. }
  12060. };
  12061. var parseId3Frames$1 = function (data) {
  12062. var frameSize,
  12063. frameHeader,
  12064. frameStart = 10,
  12065. tagSize = 0,
  12066. frames = []; // If we don't have enough data for a header, 10 bytes,
  12067. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  12068. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  12069. return;
  12070. } // the frame size is transmitted as a 28-bit integer in the
  12071. // last four bytes of the ID3 header.
  12072. // The most significant bit of each byte is dropped and the
  12073. // results concatenated to recover the actual value.
  12074. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  12075. // convenient for our comparisons to include it
  12076. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  12077. var hasExtendedHeader = data[5] & 0x40;
  12078. if (hasExtendedHeader) {
  12079. // advance the frame start past the extended header
  12080. frameStart += 4; // header size field
  12081. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  12082. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  12083. } // parse one or more ID3 frames
  12084. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  12085. do {
  12086. // determine the number of bytes in this frame
  12087. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  12088. if (frameSize < 1) {
  12089. break;
  12090. }
  12091. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  12092. var frame = {
  12093. id: frameHeader,
  12094. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  12095. };
  12096. frame.key = frame.id; // parse frame values
  12097. if (frameParsers[frame.id]) {
  12098. // use frame specific parser
  12099. frameParsers[frame.id](frame);
  12100. } else if (frame.id[0] === 'T') {
  12101. // use text frame generic parser
  12102. frameParsers['T*'](frame);
  12103. } else if (frame.id[0] === 'W') {
  12104. // use URL link frame generic parser
  12105. frameParsers['W*'](frame);
  12106. }
  12107. frames.push(frame);
  12108. frameStart += 10; // advance past the frame header
  12109. frameStart += frameSize; // advance past the frame body
  12110. } while (frameStart < tagSize);
  12111. return frames;
  12112. };
  12113. var parseId3 = {
  12114. parseId3Frames: parseId3Frames$1,
  12115. parseSyncSafeInteger: parseSyncSafeInteger$1,
  12116. frameParsers: frameParsers
  12117. };
  12118. /**
  12119. * mux.js
  12120. *
  12121. * Copyright (c) Brightcove
  12122. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12123. *
  12124. * Accepts program elementary stream (PES) data events and parses out
  12125. * ID3 metadata from them, if present.
  12126. * @see http://id3.org/id3v2.3.0
  12127. */
  12128. var Stream$5 = stream,
  12129. StreamTypes$3 = streamTypes,
  12130. id3 = parseId3,
  12131. MetadataStream;
  12132. MetadataStream = function (options) {
  12133. var settings = {
  12134. // the bytes of the program-level descriptor field in MP2T
  12135. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  12136. // program element descriptors"
  12137. descriptor: options && options.descriptor
  12138. },
  12139. // the total size in bytes of the ID3 tag being parsed
  12140. tagSize = 0,
  12141. // tag data that is not complete enough to be parsed
  12142. buffer = [],
  12143. // the total number of bytes currently in the buffer
  12144. bufferSize = 0,
  12145. i;
  12146. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  12147. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  12148. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  12149. if (settings.descriptor) {
  12150. for (i = 0; i < settings.descriptor.length; i++) {
  12151. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  12152. }
  12153. }
  12154. this.push = function (chunk) {
  12155. var tag, frameStart, frameSize, frame, i, frameHeader;
  12156. if (chunk.type !== 'timed-metadata') {
  12157. return;
  12158. } // if data_alignment_indicator is set in the PES header,
  12159. // we must have the start of a new ID3 tag. Assume anything
  12160. // remaining in the buffer was malformed and throw it out
  12161. if (chunk.dataAlignmentIndicator) {
  12162. bufferSize = 0;
  12163. buffer.length = 0;
  12164. } // ignore events that don't look like ID3 data
  12165. 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))) {
  12166. this.trigger('log', {
  12167. level: 'warn',
  12168. message: 'Skipping unrecognized metadata packet'
  12169. });
  12170. return;
  12171. } // add this chunk to the data we've collected so far
  12172. buffer.push(chunk);
  12173. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  12174. if (buffer.length === 1) {
  12175. // the frame size is transmitted as a 28-bit integer in the
  12176. // last four bytes of the ID3 header.
  12177. // The most significant bit of each byte is dropped and the
  12178. // results concatenated to recover the actual value.
  12179. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  12180. // convenient for our comparisons to include it
  12181. tagSize += 10;
  12182. } // if the entire frame has not arrived, wait for more data
  12183. if (bufferSize < tagSize) {
  12184. return;
  12185. } // collect the entire frame so it can be parsed
  12186. tag = {
  12187. data: new Uint8Array(tagSize),
  12188. frames: [],
  12189. pts: buffer[0].pts,
  12190. dts: buffer[0].dts
  12191. };
  12192. for (i = 0; i < tagSize;) {
  12193. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  12194. i += buffer[0].data.byteLength;
  12195. bufferSize -= buffer[0].data.byteLength;
  12196. buffer.shift();
  12197. } // find the start of the first frame and the end of the tag
  12198. frameStart = 10;
  12199. if (tag.data[5] & 0x40) {
  12200. // advance the frame start past the extended header
  12201. frameStart += 4; // header size field
  12202. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  12203. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  12204. } // parse one or more ID3 frames
  12205. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  12206. do {
  12207. // determine the number of bytes in this frame
  12208. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  12209. if (frameSize < 1) {
  12210. this.trigger('log', {
  12211. level: 'warn',
  12212. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  12213. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  12214. // to be sent along.
  12215. break;
  12216. }
  12217. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  12218. frame = {
  12219. id: frameHeader,
  12220. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  12221. };
  12222. frame.key = frame.id; // parse frame values
  12223. if (id3.frameParsers[frame.id]) {
  12224. // use frame specific parser
  12225. id3.frameParsers[frame.id](frame);
  12226. } else if (frame.id[0] === 'T') {
  12227. // use text frame generic parser
  12228. id3.frameParsers['T*'](frame);
  12229. } else if (frame.id[0] === 'W') {
  12230. // use URL link frame generic parser
  12231. id3.frameParsers['W*'](frame);
  12232. } // handle the special PRIV frame used to indicate the start
  12233. // time for raw AAC data
  12234. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  12235. var d = frame.data,
  12236. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  12237. size *= 4;
  12238. size += d[7] & 0x03;
  12239. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  12240. // on the value of this frame
  12241. // we couldn't have known the appropriate pts and dts before
  12242. // parsing this ID3 tag so set those values now
  12243. if (tag.pts === undefined && tag.dts === undefined) {
  12244. tag.pts = frame.timeStamp;
  12245. tag.dts = frame.timeStamp;
  12246. }
  12247. this.trigger('timestamp', frame);
  12248. }
  12249. tag.frames.push(frame);
  12250. frameStart += 10; // advance past the frame header
  12251. frameStart += frameSize; // advance past the frame body
  12252. } while (frameStart < tagSize);
  12253. this.trigger('data', tag);
  12254. };
  12255. };
  12256. MetadataStream.prototype = new Stream$5();
  12257. var metadataStream = MetadataStream;
  12258. /**
  12259. * mux.js
  12260. *
  12261. * Copyright (c) Brightcove
  12262. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12263. *
  12264. * A stream-based mp2t to mp4 converter. This utility can be used to
  12265. * deliver mp4s to a SourceBuffer on platforms that support native
  12266. * Media Source Extensions.
  12267. */
  12268. var Stream$4 = stream,
  12269. CaptionStream$1 = captionStream,
  12270. StreamTypes$2 = streamTypes,
  12271. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  12272. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  12273. var MP2T_PACKET_LENGTH$1 = 188,
  12274. // bytes
  12275. SYNC_BYTE$1 = 0x47;
  12276. /**
  12277. * Splits an incoming stream of binary data into MPEG-2 Transport
  12278. * Stream packets.
  12279. */
  12280. TransportPacketStream = function () {
  12281. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  12282. bytesInBuffer = 0;
  12283. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  12284. /**
  12285. * Split a stream of data into M2TS packets
  12286. **/
  12287. this.push = function (bytes) {
  12288. var startIndex = 0,
  12289. endIndex = MP2T_PACKET_LENGTH$1,
  12290. everything; // If there are bytes remaining from the last segment, prepend them to the
  12291. // bytes that were pushed in
  12292. if (bytesInBuffer) {
  12293. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  12294. everything.set(buffer.subarray(0, bytesInBuffer));
  12295. everything.set(bytes, bytesInBuffer);
  12296. bytesInBuffer = 0;
  12297. } else {
  12298. everything = bytes;
  12299. } // While we have enough data for a packet
  12300. while (endIndex < everything.byteLength) {
  12301. // Look for a pair of start and end sync bytes in the data..
  12302. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  12303. // We found a packet so emit it and jump one whole packet forward in
  12304. // the stream
  12305. this.trigger('data', everything.subarray(startIndex, endIndex));
  12306. startIndex += MP2T_PACKET_LENGTH$1;
  12307. endIndex += MP2T_PACKET_LENGTH$1;
  12308. continue;
  12309. } // If we get here, we have somehow become de-synchronized and we need to step
  12310. // forward one byte at a time until we find a pair of sync bytes that denote
  12311. // a packet
  12312. startIndex++;
  12313. endIndex++;
  12314. } // If there was some data left over at the end of the segment that couldn't
  12315. // possibly be a whole packet, keep it because it might be the start of a packet
  12316. // that continues in the next segment
  12317. if (startIndex < everything.byteLength) {
  12318. buffer.set(everything.subarray(startIndex), 0);
  12319. bytesInBuffer = everything.byteLength - startIndex;
  12320. }
  12321. };
  12322. /**
  12323. * Passes identified M2TS packets to the TransportParseStream to be parsed
  12324. **/
  12325. this.flush = function () {
  12326. // If the buffer contains a whole packet when we are being flushed, emit it
  12327. // and empty the buffer. Otherwise hold onto the data because it may be
  12328. // important for decoding the next segment
  12329. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  12330. this.trigger('data', buffer);
  12331. bytesInBuffer = 0;
  12332. }
  12333. this.trigger('done');
  12334. };
  12335. this.endTimeline = function () {
  12336. this.flush();
  12337. this.trigger('endedtimeline');
  12338. };
  12339. this.reset = function () {
  12340. bytesInBuffer = 0;
  12341. this.trigger('reset');
  12342. };
  12343. };
  12344. TransportPacketStream.prototype = new Stream$4();
  12345. /**
  12346. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  12347. * forms of the individual transport stream packets.
  12348. */
  12349. TransportParseStream = function () {
  12350. var parsePsi, parsePat, parsePmt, self;
  12351. TransportParseStream.prototype.init.call(this);
  12352. self = this;
  12353. this.packetsWaitingForPmt = [];
  12354. this.programMapTable = undefined;
  12355. parsePsi = function (payload, psi) {
  12356. var offset = 0; // PSI packets may be split into multiple sections and those
  12357. // sections may be split into multiple packets. If a PSI
  12358. // section starts in this packet, the payload_unit_start_indicator
  12359. // will be true and the first byte of the payload will indicate
  12360. // the offset from the current position to the start of the
  12361. // section.
  12362. if (psi.payloadUnitStartIndicator) {
  12363. offset += payload[offset] + 1;
  12364. }
  12365. if (psi.type === 'pat') {
  12366. parsePat(payload.subarray(offset), psi);
  12367. } else {
  12368. parsePmt(payload.subarray(offset), psi);
  12369. }
  12370. };
  12371. parsePat = function (payload, pat) {
  12372. pat.section_number = payload[7]; // eslint-disable-line camelcase
  12373. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  12374. // skip the PSI header and parse the first PMT entry
  12375. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  12376. pat.pmtPid = self.pmtPid;
  12377. };
  12378. /**
  12379. * Parse out the relevant fields of a Program Map Table (PMT).
  12380. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  12381. * packet. The first byte in this array should be the table_id
  12382. * field.
  12383. * @param pmt {object} the object that should be decorated with
  12384. * fields parsed from the PMT.
  12385. */
  12386. parsePmt = function (payload, pmt) {
  12387. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  12388. // take effect. We don't believe this should ever be the case
  12389. // for HLS but we'll ignore "forward" PMT declarations if we see
  12390. // them. Future PMT declarations have the current_next_indicator
  12391. // set to zero.
  12392. if (!(payload[5] & 0x01)) {
  12393. return;
  12394. } // overwrite any existing program map table
  12395. self.programMapTable = {
  12396. video: null,
  12397. audio: null,
  12398. 'timed-metadata': {}
  12399. }; // the mapping table ends at the end of the current section
  12400. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  12401. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  12402. // long the program info descriptors are
  12403. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  12404. offset = 12 + programInfoLength;
  12405. while (offset < tableEnd) {
  12406. var streamType = payload[offset];
  12407. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  12408. // TODO: should this be done for metadata too? for now maintain behavior of
  12409. // multiple metadata streams
  12410. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  12411. self.programMapTable.video = pid;
  12412. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  12413. self.programMapTable.audio = pid;
  12414. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  12415. // map pid to stream type for metadata streams
  12416. self.programMapTable['timed-metadata'][pid] = streamType;
  12417. } // move to the next table entry
  12418. // skip past the elementary stream descriptors, if present
  12419. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  12420. } // record the map on the packet as well
  12421. pmt.programMapTable = self.programMapTable;
  12422. };
  12423. /**
  12424. * Deliver a new MP2T packet to the next stream in the pipeline.
  12425. */
  12426. this.push = function (packet) {
  12427. var result = {},
  12428. offset = 4;
  12429. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  12430. result.pid = packet[1] & 0x1f;
  12431. result.pid <<= 8;
  12432. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  12433. // fifth byte of the TS packet header. The adaptation field is
  12434. // used to add stuffing to PES packets that don't fill a complete
  12435. // TS packet, and to specify some forms of timing and control data
  12436. // that we do not currently use.
  12437. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  12438. offset += packet[offset] + 1;
  12439. } // parse the rest of the packet based on the type
  12440. if (result.pid === 0) {
  12441. result.type = 'pat';
  12442. parsePsi(packet.subarray(offset), result);
  12443. this.trigger('data', result);
  12444. } else if (result.pid === this.pmtPid) {
  12445. result.type = 'pmt';
  12446. parsePsi(packet.subarray(offset), result);
  12447. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  12448. while (this.packetsWaitingForPmt.length) {
  12449. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  12450. }
  12451. } else if (this.programMapTable === undefined) {
  12452. // When we have not seen a PMT yet, defer further processing of
  12453. // PES packets until one has been parsed
  12454. this.packetsWaitingForPmt.push([packet, offset, result]);
  12455. } else {
  12456. this.processPes_(packet, offset, result);
  12457. }
  12458. };
  12459. this.processPes_ = function (packet, offset, result) {
  12460. // set the appropriate stream type
  12461. if (result.pid === this.programMapTable.video) {
  12462. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  12463. } else if (result.pid === this.programMapTable.audio) {
  12464. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  12465. } else {
  12466. // if not video or audio, it is timed-metadata or unknown
  12467. // if unknown, streamType will be undefined
  12468. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  12469. }
  12470. result.type = 'pes';
  12471. result.data = packet.subarray(offset);
  12472. this.trigger('data', result);
  12473. };
  12474. };
  12475. TransportParseStream.prototype = new Stream$4();
  12476. TransportParseStream.STREAM_TYPES = {
  12477. h264: 0x1b,
  12478. adts: 0x0f
  12479. };
  12480. /**
  12481. * Reconsistutes program elementary stream (PES) packets from parsed
  12482. * transport stream packets. That is, if you pipe an
  12483. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  12484. * events will be events which capture the bytes for individual PES
  12485. * packets plus relevant metadata that has been extracted from the
  12486. * container.
  12487. */
  12488. ElementaryStream = function () {
  12489. var self = this,
  12490. segmentHadPmt = false,
  12491. // PES packet fragments
  12492. video = {
  12493. data: [],
  12494. size: 0
  12495. },
  12496. audio = {
  12497. data: [],
  12498. size: 0
  12499. },
  12500. timedMetadata = {
  12501. data: [],
  12502. size: 0
  12503. },
  12504. programMapTable,
  12505. parsePes = function (payload, pes) {
  12506. var ptsDtsFlags;
  12507. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  12508. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  12509. // that are frame data that is continuing from the previous fragment. This
  12510. // is to check that the pes data is the start of a new pes payload
  12511. if (startPrefix !== 1) {
  12512. return;
  12513. } // get the packet length, this will be 0 for video
  12514. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  12515. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  12516. // and a DTS value. Determine what combination of values is
  12517. // available to work with.
  12518. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  12519. // performs all bitwise operations on 32-bit integers but javascript
  12520. // supports a much greater range (52-bits) of integer using standard
  12521. // mathematical operations.
  12522. // We construct a 31-bit value using bitwise operators over the 31
  12523. // most significant bits and then multiply by 4 (equal to a left-shift
  12524. // of 2) before we add the final 2 least significant bits of the
  12525. // timestamp (equal to an OR.)
  12526. if (ptsDtsFlags & 0xC0) {
  12527. // the PTS and DTS are not written out directly. For information
  12528. // on how they are encoded, see
  12529. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  12530. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  12531. pes.pts *= 4; // Left shift by 2
  12532. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  12533. pes.dts = pes.pts;
  12534. if (ptsDtsFlags & 0x40) {
  12535. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  12536. pes.dts *= 4; // Left shift by 2
  12537. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  12538. }
  12539. } // the data section starts immediately after the PES header.
  12540. // pes_header_data_length specifies the number of header bytes
  12541. // that follow the last byte of the field.
  12542. pes.data = payload.subarray(9 + payload[8]);
  12543. },
  12544. /**
  12545. * Pass completely parsed PES packets to the next stream in the pipeline
  12546. **/
  12547. flushStream = function (stream, type, forceFlush) {
  12548. var packetData = new Uint8Array(stream.size),
  12549. event = {
  12550. type: type
  12551. },
  12552. i = 0,
  12553. offset = 0,
  12554. packetFlushable = false,
  12555. fragment; // do nothing if there is not enough buffered data for a complete
  12556. // PES header
  12557. if (!stream.data.length || stream.size < 9) {
  12558. return;
  12559. }
  12560. event.trackId = stream.data[0].pid; // reassemble the packet
  12561. for (i = 0; i < stream.data.length; i++) {
  12562. fragment = stream.data[i];
  12563. packetData.set(fragment.data, offset);
  12564. offset += fragment.data.byteLength;
  12565. } // parse assembled packet's PES header
  12566. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  12567. // check that there is enough stream data to fill the packet
  12568. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  12569. if (forceFlush || packetFlushable) {
  12570. stream.size = 0;
  12571. stream.data.length = 0;
  12572. } // only emit packets that are complete. this is to avoid assembling
  12573. // incomplete PES packets due to poor segmentation
  12574. if (packetFlushable) {
  12575. self.trigger('data', event);
  12576. }
  12577. };
  12578. ElementaryStream.prototype.init.call(this);
  12579. /**
  12580. * Identifies M2TS packet types and parses PES packets using metadata
  12581. * parsed from the PMT
  12582. **/
  12583. this.push = function (data) {
  12584. ({
  12585. pat: function () {// we have to wait for the PMT to arrive as well before we
  12586. // have any meaningful metadata
  12587. },
  12588. pes: function () {
  12589. var stream, streamType;
  12590. switch (data.streamType) {
  12591. case StreamTypes$2.H264_STREAM_TYPE:
  12592. stream = video;
  12593. streamType = 'video';
  12594. break;
  12595. case StreamTypes$2.ADTS_STREAM_TYPE:
  12596. stream = audio;
  12597. streamType = 'audio';
  12598. break;
  12599. case StreamTypes$2.METADATA_STREAM_TYPE:
  12600. stream = timedMetadata;
  12601. streamType = 'timed-metadata';
  12602. break;
  12603. default:
  12604. // ignore unknown stream types
  12605. return;
  12606. } // if a new packet is starting, we can flush the completed
  12607. // packet
  12608. if (data.payloadUnitStartIndicator) {
  12609. flushStream(stream, streamType, true);
  12610. } // buffer this fragment until we are sure we've received the
  12611. // complete payload
  12612. stream.data.push(data);
  12613. stream.size += data.data.byteLength;
  12614. },
  12615. pmt: function () {
  12616. var event = {
  12617. type: 'metadata',
  12618. tracks: []
  12619. };
  12620. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  12621. if (programMapTable.video !== null) {
  12622. event.tracks.push({
  12623. timelineStartInfo: {
  12624. baseMediaDecodeTime: 0
  12625. },
  12626. id: +programMapTable.video,
  12627. codec: 'avc',
  12628. type: 'video'
  12629. });
  12630. }
  12631. if (programMapTable.audio !== null) {
  12632. event.tracks.push({
  12633. timelineStartInfo: {
  12634. baseMediaDecodeTime: 0
  12635. },
  12636. id: +programMapTable.audio,
  12637. codec: 'adts',
  12638. type: 'audio'
  12639. });
  12640. }
  12641. segmentHadPmt = true;
  12642. self.trigger('data', event);
  12643. }
  12644. })[data.type]();
  12645. };
  12646. this.reset = function () {
  12647. video.size = 0;
  12648. video.data.length = 0;
  12649. audio.size = 0;
  12650. audio.data.length = 0;
  12651. this.trigger('reset');
  12652. };
  12653. /**
  12654. * Flush any remaining input. Video PES packets may be of variable
  12655. * length. Normally, the start of a new video packet can trigger the
  12656. * finalization of the previous packet. That is not possible if no
  12657. * more video is forthcoming, however. In that case, some other
  12658. * mechanism (like the end of the file) has to be employed. When it is
  12659. * clear that no additional data is forthcoming, calling this method
  12660. * will flush the buffered packets.
  12661. */
  12662. this.flushStreams_ = function () {
  12663. // !!THIS ORDER IS IMPORTANT!!
  12664. // video first then audio
  12665. flushStream(video, 'video');
  12666. flushStream(audio, 'audio');
  12667. flushStream(timedMetadata, 'timed-metadata');
  12668. };
  12669. this.flush = function () {
  12670. // if on flush we haven't had a pmt emitted
  12671. // and we have a pmt to emit. emit the pmt
  12672. // so that we trigger a trackinfo downstream.
  12673. if (!segmentHadPmt && programMapTable) {
  12674. var pmt = {
  12675. type: 'metadata',
  12676. tracks: []
  12677. }; // translate audio and video streams to tracks
  12678. if (programMapTable.video !== null) {
  12679. pmt.tracks.push({
  12680. timelineStartInfo: {
  12681. baseMediaDecodeTime: 0
  12682. },
  12683. id: +programMapTable.video,
  12684. codec: 'avc',
  12685. type: 'video'
  12686. });
  12687. }
  12688. if (programMapTable.audio !== null) {
  12689. pmt.tracks.push({
  12690. timelineStartInfo: {
  12691. baseMediaDecodeTime: 0
  12692. },
  12693. id: +programMapTable.audio,
  12694. codec: 'adts',
  12695. type: 'audio'
  12696. });
  12697. }
  12698. self.trigger('data', pmt);
  12699. }
  12700. segmentHadPmt = false;
  12701. this.flushStreams_();
  12702. this.trigger('done');
  12703. };
  12704. };
  12705. ElementaryStream.prototype = new Stream$4();
  12706. var m2ts$1 = {
  12707. PAT_PID: 0x0000,
  12708. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  12709. TransportPacketStream: TransportPacketStream,
  12710. TransportParseStream: TransportParseStream,
  12711. ElementaryStream: ElementaryStream,
  12712. TimestampRolloverStream: TimestampRolloverStream,
  12713. CaptionStream: CaptionStream$1.CaptionStream,
  12714. Cea608Stream: CaptionStream$1.Cea608Stream,
  12715. Cea708Stream: CaptionStream$1.Cea708Stream,
  12716. MetadataStream: metadataStream
  12717. };
  12718. for (var type in StreamTypes$2) {
  12719. if (StreamTypes$2.hasOwnProperty(type)) {
  12720. m2ts$1[type] = StreamTypes$2[type];
  12721. }
  12722. }
  12723. var m2ts_1 = m2ts$1;
  12724. /**
  12725. * mux.js
  12726. *
  12727. * Copyright (c) Brightcove
  12728. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12729. */
  12730. var Stream$3 = stream;
  12731. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  12732. var AdtsStream$1;
  12733. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  12734. /*
  12735. * Accepts a ElementaryStream and emits data events with parsed
  12736. * AAC Audio Frames of the individual packets. Input audio in ADTS
  12737. * format is unpacked and re-emitted as AAC frames.
  12738. *
  12739. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  12740. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  12741. */
  12742. AdtsStream$1 = function (handlePartialSegments) {
  12743. var buffer,
  12744. frameNum = 0;
  12745. AdtsStream$1.prototype.init.call(this);
  12746. this.skipWarn_ = function (start, end) {
  12747. this.trigger('log', {
  12748. level: 'warn',
  12749. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  12750. });
  12751. };
  12752. this.push = function (packet) {
  12753. var i = 0,
  12754. frameLength,
  12755. protectionSkipBytes,
  12756. oldBuffer,
  12757. sampleCount,
  12758. adtsFrameDuration;
  12759. if (!handlePartialSegments) {
  12760. frameNum = 0;
  12761. }
  12762. if (packet.type !== 'audio') {
  12763. // ignore non-audio data
  12764. return;
  12765. } // Prepend any data in the buffer to the input data so that we can parse
  12766. // aac frames the cross a PES packet boundary
  12767. if (buffer && buffer.length) {
  12768. oldBuffer = buffer;
  12769. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  12770. buffer.set(oldBuffer);
  12771. buffer.set(packet.data, oldBuffer.byteLength);
  12772. } else {
  12773. buffer = packet.data;
  12774. } // unpack any ADTS frames which have been fully received
  12775. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  12776. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  12777. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  12778. while (i + 7 < buffer.length) {
  12779. // Look for the start of an ADTS header..
  12780. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  12781. if (typeof skip !== 'number') {
  12782. skip = i;
  12783. } // If a valid header was not found, jump one forward and attempt to
  12784. // find a valid ADTS header starting at the next byte
  12785. i++;
  12786. continue;
  12787. }
  12788. if (typeof skip === 'number') {
  12789. this.skipWarn_(skip, i);
  12790. skip = null;
  12791. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  12792. // end of the ADTS header
  12793. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  12794. // end of the sync sequence
  12795. // NOTE: frame length includes the size of the header
  12796. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  12797. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  12798. 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,
  12799. // then we have to wait for more data
  12800. if (buffer.byteLength - i < frameLength) {
  12801. break;
  12802. } // Otherwise, deliver the complete AAC frame
  12803. this.trigger('data', {
  12804. pts: packet.pts + frameNum * adtsFrameDuration,
  12805. dts: packet.dts + frameNum * adtsFrameDuration,
  12806. sampleCount: sampleCount,
  12807. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  12808. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  12809. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  12810. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  12811. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  12812. samplesize: 16,
  12813. // data is the frame without it's header
  12814. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  12815. });
  12816. frameNum++;
  12817. i += frameLength;
  12818. }
  12819. if (typeof skip === 'number') {
  12820. this.skipWarn_(skip, i);
  12821. skip = null;
  12822. } // remove processed bytes from the buffer.
  12823. buffer = buffer.subarray(i);
  12824. };
  12825. this.flush = function () {
  12826. frameNum = 0;
  12827. this.trigger('done');
  12828. };
  12829. this.reset = function () {
  12830. buffer = void 0;
  12831. this.trigger('reset');
  12832. };
  12833. this.endTimeline = function () {
  12834. buffer = void 0;
  12835. this.trigger('endedtimeline');
  12836. };
  12837. };
  12838. AdtsStream$1.prototype = new Stream$3();
  12839. var adts = AdtsStream$1;
  12840. /**
  12841. * mux.js
  12842. *
  12843. * Copyright (c) Brightcove
  12844. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12845. */
  12846. var ExpGolomb$1;
  12847. /**
  12848. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  12849. * scheme used by h264.
  12850. */
  12851. ExpGolomb$1 = function (workingData) {
  12852. var // the number of bytes left to examine in workingData
  12853. workingBytesAvailable = workingData.byteLength,
  12854. // the current word being examined
  12855. workingWord = 0,
  12856. // :uint
  12857. // the number of bits left to examine in the current word
  12858. workingBitsAvailable = 0; // :uint;
  12859. // ():uint
  12860. this.length = function () {
  12861. return 8 * workingBytesAvailable;
  12862. }; // ():uint
  12863. this.bitsAvailable = function () {
  12864. return 8 * workingBytesAvailable + workingBitsAvailable;
  12865. }; // ():void
  12866. this.loadWord = function () {
  12867. var position = workingData.byteLength - workingBytesAvailable,
  12868. workingBytes = new Uint8Array(4),
  12869. availableBytes = Math.min(4, workingBytesAvailable);
  12870. if (availableBytes === 0) {
  12871. throw new Error('no bytes available');
  12872. }
  12873. workingBytes.set(workingData.subarray(position, position + availableBytes));
  12874. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  12875. workingBitsAvailable = availableBytes * 8;
  12876. workingBytesAvailable -= availableBytes;
  12877. }; // (count:int):void
  12878. this.skipBits = function (count) {
  12879. var skipBytes; // :int
  12880. if (workingBitsAvailable > count) {
  12881. workingWord <<= count;
  12882. workingBitsAvailable -= count;
  12883. } else {
  12884. count -= workingBitsAvailable;
  12885. skipBytes = Math.floor(count / 8);
  12886. count -= skipBytes * 8;
  12887. workingBytesAvailable -= skipBytes;
  12888. this.loadWord();
  12889. workingWord <<= count;
  12890. workingBitsAvailable -= count;
  12891. }
  12892. }; // (size:int):uint
  12893. this.readBits = function (size) {
  12894. var bits = Math.min(workingBitsAvailable, size),
  12895. // :uint
  12896. valu = workingWord >>> 32 - bits; // :uint
  12897. // if size > 31, handle error
  12898. workingBitsAvailable -= bits;
  12899. if (workingBitsAvailable > 0) {
  12900. workingWord <<= bits;
  12901. } else if (workingBytesAvailable > 0) {
  12902. this.loadWord();
  12903. }
  12904. bits = size - bits;
  12905. if (bits > 0) {
  12906. return valu << bits | this.readBits(bits);
  12907. }
  12908. return valu;
  12909. }; // ():uint
  12910. this.skipLeadingZeros = function () {
  12911. var leadingZeroCount; // :uint
  12912. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  12913. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  12914. // the first bit of working word is 1
  12915. workingWord <<= leadingZeroCount;
  12916. workingBitsAvailable -= leadingZeroCount;
  12917. return leadingZeroCount;
  12918. }
  12919. } // we exhausted workingWord and still have not found a 1
  12920. this.loadWord();
  12921. return leadingZeroCount + this.skipLeadingZeros();
  12922. }; // ():void
  12923. this.skipUnsignedExpGolomb = function () {
  12924. this.skipBits(1 + this.skipLeadingZeros());
  12925. }; // ():void
  12926. this.skipExpGolomb = function () {
  12927. this.skipBits(1 + this.skipLeadingZeros());
  12928. }; // ():uint
  12929. this.readUnsignedExpGolomb = function () {
  12930. var clz = this.skipLeadingZeros(); // :uint
  12931. return this.readBits(clz + 1) - 1;
  12932. }; // ():int
  12933. this.readExpGolomb = function () {
  12934. var valu = this.readUnsignedExpGolomb(); // :int
  12935. if (0x01 & valu) {
  12936. // the number is odd if the low order bit is set
  12937. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  12938. }
  12939. return -1 * (valu >>> 1); // divide by two then make it negative
  12940. }; // Some convenience functions
  12941. // :Boolean
  12942. this.readBoolean = function () {
  12943. return this.readBits(1) === 1;
  12944. }; // ():int
  12945. this.readUnsignedByte = function () {
  12946. return this.readBits(8);
  12947. };
  12948. this.loadWord();
  12949. };
  12950. var expGolomb = ExpGolomb$1;
  12951. /**
  12952. * mux.js
  12953. *
  12954. * Copyright (c) Brightcove
  12955. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  12956. */
  12957. var Stream$2 = stream;
  12958. var ExpGolomb = expGolomb;
  12959. var H264Stream$1, NalByteStream;
  12960. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  12961. /**
  12962. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  12963. */
  12964. NalByteStream = function () {
  12965. var syncPoint = 0,
  12966. i,
  12967. buffer;
  12968. NalByteStream.prototype.init.call(this);
  12969. /*
  12970. * Scans a byte stream and triggers a data event with the NAL units found.
  12971. * @param {Object} data Event received from H264Stream
  12972. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  12973. *
  12974. * @see H264Stream.push
  12975. */
  12976. this.push = function (data) {
  12977. var swapBuffer;
  12978. if (!buffer) {
  12979. buffer = data.data;
  12980. } else {
  12981. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  12982. swapBuffer.set(buffer);
  12983. swapBuffer.set(data.data, buffer.byteLength);
  12984. buffer = swapBuffer;
  12985. }
  12986. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  12987. // scan for NAL unit boundaries
  12988. // a match looks like this:
  12989. // 0 0 1 .. NAL .. 0 0 1
  12990. // ^ sync point ^ i
  12991. // or this:
  12992. // 0 0 1 .. NAL .. 0 0 0
  12993. // ^ sync point ^ i
  12994. // advance the sync point to a NAL start, if necessary
  12995. for (; syncPoint < len - 3; syncPoint++) {
  12996. if (buffer[syncPoint + 2] === 1) {
  12997. // the sync point is properly aligned
  12998. i = syncPoint + 5;
  12999. break;
  13000. }
  13001. }
  13002. while (i < len) {
  13003. // look at the current byte to determine if we've hit the end of
  13004. // a NAL unit boundary
  13005. switch (buffer[i]) {
  13006. case 0:
  13007. // skip past non-sync sequences
  13008. if (buffer[i - 1] !== 0) {
  13009. i += 2;
  13010. break;
  13011. } else if (buffer[i - 2] !== 0) {
  13012. i++;
  13013. break;
  13014. } // deliver the NAL unit if it isn't empty
  13015. if (syncPoint + 3 !== i - 2) {
  13016. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  13017. } // drop trailing zeroes
  13018. do {
  13019. i++;
  13020. } while (buffer[i] !== 1 && i < len);
  13021. syncPoint = i - 2;
  13022. i += 3;
  13023. break;
  13024. case 1:
  13025. // skip past non-sync sequences
  13026. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  13027. i += 3;
  13028. break;
  13029. } // deliver the NAL unit
  13030. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  13031. syncPoint = i - 2;
  13032. i += 3;
  13033. break;
  13034. default:
  13035. // the current byte isn't a one or zero, so it cannot be part
  13036. // of a sync sequence
  13037. i += 3;
  13038. break;
  13039. }
  13040. } // filter out the NAL units that were delivered
  13041. buffer = buffer.subarray(syncPoint);
  13042. i -= syncPoint;
  13043. syncPoint = 0;
  13044. };
  13045. this.reset = function () {
  13046. buffer = null;
  13047. syncPoint = 0;
  13048. this.trigger('reset');
  13049. };
  13050. this.flush = function () {
  13051. // deliver the last buffered NAL unit
  13052. if (buffer && buffer.byteLength > 3) {
  13053. this.trigger('data', buffer.subarray(syncPoint + 3));
  13054. } // reset the stream state
  13055. buffer = null;
  13056. syncPoint = 0;
  13057. this.trigger('done');
  13058. };
  13059. this.endTimeline = function () {
  13060. this.flush();
  13061. this.trigger('endedtimeline');
  13062. };
  13063. };
  13064. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  13065. // see Recommendation ITU-T H.264 (4/2013),
  13066. // 7.3.2.1.1 Sequence parameter set data syntax
  13067. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  13068. 100: true,
  13069. 110: true,
  13070. 122: true,
  13071. 244: true,
  13072. 44: true,
  13073. 83: true,
  13074. 86: true,
  13075. 118: true,
  13076. 128: true,
  13077. // TODO: the three profiles below don't
  13078. // appear to have sps data in the specificiation anymore?
  13079. 138: true,
  13080. 139: true,
  13081. 134: true
  13082. };
  13083. /**
  13084. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  13085. * events.
  13086. */
  13087. H264Stream$1 = function () {
  13088. var nalByteStream = new NalByteStream(),
  13089. self,
  13090. trackId,
  13091. currentPts,
  13092. currentDts,
  13093. discardEmulationPreventionBytes,
  13094. readSequenceParameterSet,
  13095. skipScalingList;
  13096. H264Stream$1.prototype.init.call(this);
  13097. self = this;
  13098. /*
  13099. * Pushes a packet from a stream onto the NalByteStream
  13100. *
  13101. * @param {Object} packet - A packet received from a stream
  13102. * @param {Uint8Array} packet.data - The raw bytes of the packet
  13103. * @param {Number} packet.dts - Decode timestamp of the packet
  13104. * @param {Number} packet.pts - Presentation timestamp of the packet
  13105. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  13106. * @param {('video'|'audio')} packet.type - The type of packet
  13107. *
  13108. */
  13109. this.push = function (packet) {
  13110. if (packet.type !== 'video') {
  13111. return;
  13112. }
  13113. trackId = packet.trackId;
  13114. currentPts = packet.pts;
  13115. currentDts = packet.dts;
  13116. nalByteStream.push(packet);
  13117. };
  13118. /*
  13119. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  13120. * for the NALUs to the next stream component.
  13121. * Also, preprocess caption and sequence parameter NALUs.
  13122. *
  13123. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  13124. * @see NalByteStream.push
  13125. */
  13126. nalByteStream.on('data', function (data) {
  13127. var event = {
  13128. trackId: trackId,
  13129. pts: currentPts,
  13130. dts: currentDts,
  13131. data: data,
  13132. nalUnitTypeCode: data[0] & 0x1f
  13133. };
  13134. switch (event.nalUnitTypeCode) {
  13135. case 0x05:
  13136. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  13137. break;
  13138. case 0x06:
  13139. event.nalUnitType = 'sei_rbsp';
  13140. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  13141. break;
  13142. case 0x07:
  13143. event.nalUnitType = 'seq_parameter_set_rbsp';
  13144. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  13145. event.config = readSequenceParameterSet(event.escapedRBSP);
  13146. break;
  13147. case 0x08:
  13148. event.nalUnitType = 'pic_parameter_set_rbsp';
  13149. break;
  13150. case 0x09:
  13151. event.nalUnitType = 'access_unit_delimiter_rbsp';
  13152. break;
  13153. } // This triggers data on the H264Stream
  13154. self.trigger('data', event);
  13155. });
  13156. nalByteStream.on('done', function () {
  13157. self.trigger('done');
  13158. });
  13159. nalByteStream.on('partialdone', function () {
  13160. self.trigger('partialdone');
  13161. });
  13162. nalByteStream.on('reset', function () {
  13163. self.trigger('reset');
  13164. });
  13165. nalByteStream.on('endedtimeline', function () {
  13166. self.trigger('endedtimeline');
  13167. });
  13168. this.flush = function () {
  13169. nalByteStream.flush();
  13170. };
  13171. this.partialFlush = function () {
  13172. nalByteStream.partialFlush();
  13173. };
  13174. this.reset = function () {
  13175. nalByteStream.reset();
  13176. };
  13177. this.endTimeline = function () {
  13178. nalByteStream.endTimeline();
  13179. };
  13180. /**
  13181. * Advance the ExpGolomb decoder past a scaling list. The scaling
  13182. * list is optionally transmitted as part of a sequence parameter
  13183. * set and is not relevant to transmuxing.
  13184. * @param count {number} the number of entries in this scaling list
  13185. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  13186. * start of a scaling list
  13187. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  13188. */
  13189. skipScalingList = function (count, expGolombDecoder) {
  13190. var lastScale = 8,
  13191. nextScale = 8,
  13192. j,
  13193. deltaScale;
  13194. for (j = 0; j < count; j++) {
  13195. if (nextScale !== 0) {
  13196. deltaScale = expGolombDecoder.readExpGolomb();
  13197. nextScale = (lastScale + deltaScale + 256) % 256;
  13198. }
  13199. lastScale = nextScale === 0 ? lastScale : nextScale;
  13200. }
  13201. };
  13202. /**
  13203. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  13204. * Sequence Payload"
  13205. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  13206. * unit
  13207. * @return {Uint8Array} the RBSP without any Emulation
  13208. * Prevention Bytes
  13209. */
  13210. discardEmulationPreventionBytes = function (data) {
  13211. var length = data.byteLength,
  13212. emulationPreventionBytesPositions = [],
  13213. i = 1,
  13214. newLength,
  13215. newData; // Find all `Emulation Prevention Bytes`
  13216. while (i < length - 2) {
  13217. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  13218. emulationPreventionBytesPositions.push(i + 2);
  13219. i += 2;
  13220. } else {
  13221. i++;
  13222. }
  13223. } // If no Emulation Prevention Bytes were found just return the original
  13224. // array
  13225. if (emulationPreventionBytesPositions.length === 0) {
  13226. return data;
  13227. } // Create a new array to hold the NAL unit data
  13228. newLength = length - emulationPreventionBytesPositions.length;
  13229. newData = new Uint8Array(newLength);
  13230. var sourceIndex = 0;
  13231. for (i = 0; i < newLength; sourceIndex++, i++) {
  13232. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  13233. // Skip this byte
  13234. sourceIndex++; // Remove this position index
  13235. emulationPreventionBytesPositions.shift();
  13236. }
  13237. newData[i] = data[sourceIndex];
  13238. }
  13239. return newData;
  13240. };
  13241. /**
  13242. * Read a sequence parameter set and return some interesting video
  13243. * properties. A sequence parameter set is the H264 metadata that
  13244. * describes the properties of upcoming video frames.
  13245. * @param data {Uint8Array} the bytes of a sequence parameter set
  13246. * @return {object} an object with configuration parsed from the
  13247. * sequence parameter set, including the dimensions of the
  13248. * associated video frames.
  13249. */
  13250. readSequenceParameterSet = function (data) {
  13251. var frameCropLeftOffset = 0,
  13252. frameCropRightOffset = 0,
  13253. frameCropTopOffset = 0,
  13254. frameCropBottomOffset = 0,
  13255. expGolombDecoder,
  13256. profileIdc,
  13257. levelIdc,
  13258. profileCompatibility,
  13259. chromaFormatIdc,
  13260. picOrderCntType,
  13261. numRefFramesInPicOrderCntCycle,
  13262. picWidthInMbsMinus1,
  13263. picHeightInMapUnitsMinus1,
  13264. frameMbsOnlyFlag,
  13265. scalingListCount,
  13266. sarRatio = [1, 1],
  13267. aspectRatioIdc,
  13268. i;
  13269. expGolombDecoder = new ExpGolomb(data);
  13270. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  13271. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  13272. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  13273. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  13274. // some profiles have more optional data we don't need
  13275. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  13276. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  13277. if (chromaFormatIdc === 3) {
  13278. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  13279. }
  13280. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  13281. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  13282. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  13283. if (expGolombDecoder.readBoolean()) {
  13284. // seq_scaling_matrix_present_flag
  13285. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  13286. for (i = 0; i < scalingListCount; i++) {
  13287. if (expGolombDecoder.readBoolean()) {
  13288. // seq_scaling_list_present_flag[ i ]
  13289. if (i < 6) {
  13290. skipScalingList(16, expGolombDecoder);
  13291. } else {
  13292. skipScalingList(64, expGolombDecoder);
  13293. }
  13294. }
  13295. }
  13296. }
  13297. }
  13298. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  13299. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  13300. if (picOrderCntType === 0) {
  13301. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  13302. } else if (picOrderCntType === 1) {
  13303. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  13304. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  13305. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  13306. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  13307. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  13308. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  13309. }
  13310. }
  13311. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  13312. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  13313. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  13314. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  13315. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  13316. if (frameMbsOnlyFlag === 0) {
  13317. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  13318. }
  13319. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  13320. if (expGolombDecoder.readBoolean()) {
  13321. // frame_cropping_flag
  13322. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  13323. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  13324. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  13325. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  13326. }
  13327. if (expGolombDecoder.readBoolean()) {
  13328. // vui_parameters_present_flag
  13329. if (expGolombDecoder.readBoolean()) {
  13330. // aspect_ratio_info_present_flag
  13331. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  13332. switch (aspectRatioIdc) {
  13333. case 1:
  13334. sarRatio = [1, 1];
  13335. break;
  13336. case 2:
  13337. sarRatio = [12, 11];
  13338. break;
  13339. case 3:
  13340. sarRatio = [10, 11];
  13341. break;
  13342. case 4:
  13343. sarRatio = [16, 11];
  13344. break;
  13345. case 5:
  13346. sarRatio = [40, 33];
  13347. break;
  13348. case 6:
  13349. sarRatio = [24, 11];
  13350. break;
  13351. case 7:
  13352. sarRatio = [20, 11];
  13353. break;
  13354. case 8:
  13355. sarRatio = [32, 11];
  13356. break;
  13357. case 9:
  13358. sarRatio = [80, 33];
  13359. break;
  13360. case 10:
  13361. sarRatio = [18, 11];
  13362. break;
  13363. case 11:
  13364. sarRatio = [15, 11];
  13365. break;
  13366. case 12:
  13367. sarRatio = [64, 33];
  13368. break;
  13369. case 13:
  13370. sarRatio = [160, 99];
  13371. break;
  13372. case 14:
  13373. sarRatio = [4, 3];
  13374. break;
  13375. case 15:
  13376. sarRatio = [3, 2];
  13377. break;
  13378. case 16:
  13379. sarRatio = [2, 1];
  13380. break;
  13381. case 255:
  13382. {
  13383. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  13384. break;
  13385. }
  13386. }
  13387. if (sarRatio) {
  13388. sarRatio[0] / sarRatio[1];
  13389. }
  13390. }
  13391. }
  13392. return {
  13393. profileIdc: profileIdc,
  13394. levelIdc: levelIdc,
  13395. profileCompatibility: profileCompatibility,
  13396. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  13397. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  13398. // sar is sample aspect ratio
  13399. sarRatio: sarRatio
  13400. };
  13401. };
  13402. };
  13403. H264Stream$1.prototype = new Stream$2();
  13404. var h264 = {
  13405. H264Stream: H264Stream$1,
  13406. NalByteStream: NalByteStream
  13407. };
  13408. /**
  13409. * mux.js
  13410. *
  13411. * Copyright (c) Brightcove
  13412. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13413. *
  13414. * Utilities to detect basic properties and metadata about Aac data.
  13415. */
  13416. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  13417. var parseId3TagSize = function (header, byteIndex) {
  13418. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  13419. flags = header[byteIndex + 5],
  13420. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  13421. returnSize = returnSize >= 0 ? returnSize : 0;
  13422. if (footerPresent) {
  13423. return returnSize + 20;
  13424. }
  13425. return returnSize + 10;
  13426. };
  13427. var getId3Offset = function (data, offset) {
  13428. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  13429. return offset;
  13430. }
  13431. offset += parseId3TagSize(data, offset);
  13432. return getId3Offset(data, offset);
  13433. }; // TODO: use vhs-utils
  13434. var isLikelyAacData$1 = function (data) {
  13435. var offset = getId3Offset(data, 0);
  13436. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  13437. // is not mp3 data but aac data.
  13438. (data[offset + 1] & 0x16) === 0x10;
  13439. };
  13440. var parseSyncSafeInteger = function (data) {
  13441. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  13442. }; // return a percent-encoded representation of the specified byte range
  13443. // @see http://en.wikipedia.org/wiki/Percent-encoding
  13444. var percentEncode = function (bytes, start, end) {
  13445. var i,
  13446. result = '';
  13447. for (i = start; i < end; i++) {
  13448. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  13449. }
  13450. return result;
  13451. }; // return the string representation of the specified byte range,
  13452. // interpreted as ISO-8859-1.
  13453. var parseIso88591 = function (bytes, start, end) {
  13454. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  13455. };
  13456. var parseAdtsSize = function (header, byteIndex) {
  13457. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  13458. middle = header[byteIndex + 4] << 3,
  13459. highTwo = header[byteIndex + 3] & 0x3 << 11;
  13460. return highTwo | middle | lowThree;
  13461. };
  13462. var parseType$4 = function (header, byteIndex) {
  13463. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  13464. return 'timed-metadata';
  13465. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  13466. return 'audio';
  13467. }
  13468. return null;
  13469. };
  13470. var parseSampleRate = function (packet) {
  13471. var i = 0;
  13472. while (i + 5 < packet.length) {
  13473. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  13474. // If a valid header was not found, jump one forward and attempt to
  13475. // find a valid ADTS header starting at the next byte
  13476. i++;
  13477. continue;
  13478. }
  13479. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  13480. }
  13481. return null;
  13482. };
  13483. var parseAacTimestamp = function (packet) {
  13484. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  13485. frameStart = 10;
  13486. if (packet[5] & 0x40) {
  13487. // advance the frame start past the extended header
  13488. frameStart += 4; // header size field
  13489. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  13490. } // parse one or more ID3 frames
  13491. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  13492. do {
  13493. // determine the number of bytes in this frame
  13494. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  13495. if (frameSize < 1) {
  13496. return null;
  13497. }
  13498. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  13499. if (frameHeader === 'PRIV') {
  13500. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  13501. for (var i = 0; i < frame.byteLength; i++) {
  13502. if (frame[i] === 0) {
  13503. var owner = parseIso88591(frame, 0, i);
  13504. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  13505. var d = frame.subarray(i + 1);
  13506. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  13507. size *= 4;
  13508. size += d[7] & 0x03;
  13509. return size;
  13510. }
  13511. break;
  13512. }
  13513. }
  13514. }
  13515. frameStart += 10; // advance past the frame header
  13516. frameStart += frameSize; // advance past the frame body
  13517. } while (frameStart < packet.byteLength);
  13518. return null;
  13519. };
  13520. var utils = {
  13521. isLikelyAacData: isLikelyAacData$1,
  13522. parseId3TagSize: parseId3TagSize,
  13523. parseAdtsSize: parseAdtsSize,
  13524. parseType: parseType$4,
  13525. parseSampleRate: parseSampleRate,
  13526. parseAacTimestamp: parseAacTimestamp
  13527. };
  13528. /**
  13529. * mux.js
  13530. *
  13531. * Copyright (c) Brightcove
  13532. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13533. *
  13534. * A stream-based aac to mp4 converter. This utility can be used to
  13535. * deliver mp4s to a SourceBuffer on platforms that support native
  13536. * Media Source Extensions.
  13537. */
  13538. var Stream$1 = stream;
  13539. var aacUtils = utils; // Constants
  13540. var AacStream$1;
  13541. /**
  13542. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  13543. */
  13544. AacStream$1 = function () {
  13545. var everything = new Uint8Array(),
  13546. timeStamp = 0;
  13547. AacStream$1.prototype.init.call(this);
  13548. this.setTimestamp = function (timestamp) {
  13549. timeStamp = timestamp;
  13550. };
  13551. this.push = function (bytes) {
  13552. var frameSize = 0,
  13553. byteIndex = 0,
  13554. bytesLeft,
  13555. chunk,
  13556. packet,
  13557. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  13558. // bytes that were pushed in
  13559. if (everything.length) {
  13560. tempLength = everything.length;
  13561. everything = new Uint8Array(bytes.byteLength + tempLength);
  13562. everything.set(everything.subarray(0, tempLength));
  13563. everything.set(bytes, tempLength);
  13564. } else {
  13565. everything = bytes;
  13566. }
  13567. while (everything.length - byteIndex >= 3) {
  13568. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  13569. // Exit early because we don't have enough to parse
  13570. // the ID3 tag header
  13571. if (everything.length - byteIndex < 10) {
  13572. break;
  13573. } // check framesize
  13574. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  13575. // to emit a full packet
  13576. // Add to byteIndex to support multiple ID3 tags in sequence
  13577. if (byteIndex + frameSize > everything.length) {
  13578. break;
  13579. }
  13580. chunk = {
  13581. type: 'timed-metadata',
  13582. data: everything.subarray(byteIndex, byteIndex + frameSize)
  13583. };
  13584. this.trigger('data', chunk);
  13585. byteIndex += frameSize;
  13586. continue;
  13587. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  13588. // Exit early because we don't have enough to parse
  13589. // the ADTS frame header
  13590. if (everything.length - byteIndex < 7) {
  13591. break;
  13592. }
  13593. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  13594. // to emit a full packet
  13595. if (byteIndex + frameSize > everything.length) {
  13596. break;
  13597. }
  13598. packet = {
  13599. type: 'audio',
  13600. data: everything.subarray(byteIndex, byteIndex + frameSize),
  13601. pts: timeStamp,
  13602. dts: timeStamp
  13603. };
  13604. this.trigger('data', packet);
  13605. byteIndex += frameSize;
  13606. continue;
  13607. }
  13608. byteIndex++;
  13609. }
  13610. bytesLeft = everything.length - byteIndex;
  13611. if (bytesLeft > 0) {
  13612. everything = everything.subarray(byteIndex);
  13613. } else {
  13614. everything = new Uint8Array();
  13615. }
  13616. };
  13617. this.reset = function () {
  13618. everything = new Uint8Array();
  13619. this.trigger('reset');
  13620. };
  13621. this.endTimeline = function () {
  13622. everything = new Uint8Array();
  13623. this.trigger('endedtimeline');
  13624. };
  13625. };
  13626. AacStream$1.prototype = new Stream$1();
  13627. var aac = AacStream$1;
  13628. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  13629. var audioProperties = AUDIO_PROPERTIES$1;
  13630. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  13631. var videoProperties = VIDEO_PROPERTIES$1;
  13632. /**
  13633. * mux.js
  13634. *
  13635. * Copyright (c) Brightcove
  13636. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  13637. *
  13638. * A stream-based mp2t to mp4 converter. This utility can be used to
  13639. * deliver mp4s to a SourceBuffer on platforms that support native
  13640. * Media Source Extensions.
  13641. */
  13642. var Stream = stream;
  13643. var mp4 = mp4Generator;
  13644. var frameUtils = frameUtils$1;
  13645. var audioFrameUtils = audioFrameUtils$1;
  13646. var trackDecodeInfo = trackDecodeInfo$1;
  13647. var m2ts = m2ts_1;
  13648. var clock = clock$2;
  13649. var AdtsStream = adts;
  13650. var H264Stream = h264.H264Stream;
  13651. var AacStream = aac;
  13652. var isLikelyAacData = utils.isLikelyAacData;
  13653. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  13654. var AUDIO_PROPERTIES = audioProperties;
  13655. var VIDEO_PROPERTIES = videoProperties; // object types
  13656. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  13657. var retriggerForStream = function (key, event) {
  13658. event.stream = key;
  13659. this.trigger('log', event);
  13660. };
  13661. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  13662. var keys = Object.keys(pipeline);
  13663. for (var i = 0; i < keys.length; i++) {
  13664. var key = keys[i]; // skip non-stream keys and headOfPipeline
  13665. // which is just a duplicate
  13666. if (key === 'headOfPipeline' || !pipeline[key].on) {
  13667. continue;
  13668. }
  13669. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  13670. }
  13671. };
  13672. /**
  13673. * Compare two arrays (even typed) for same-ness
  13674. */
  13675. var arrayEquals = function (a, b) {
  13676. var i;
  13677. if (a.length !== b.length) {
  13678. return false;
  13679. } // compare the value of each element in the array
  13680. for (i = 0; i < a.length; i++) {
  13681. if (a[i] !== b[i]) {
  13682. return false;
  13683. }
  13684. }
  13685. return true;
  13686. };
  13687. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  13688. var ptsOffsetFromDts = startPts - startDts,
  13689. decodeDuration = endDts - startDts,
  13690. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  13691. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  13692. // In order to provide relevant values for the player times, base timing info on the
  13693. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  13694. return {
  13695. start: {
  13696. dts: baseMediaDecodeTime,
  13697. pts: baseMediaDecodeTime + ptsOffsetFromDts
  13698. },
  13699. end: {
  13700. dts: baseMediaDecodeTime + decodeDuration,
  13701. pts: baseMediaDecodeTime + presentationDuration
  13702. },
  13703. prependedContentDuration: prependedContentDuration,
  13704. baseMediaDecodeTime: baseMediaDecodeTime
  13705. };
  13706. };
  13707. /**
  13708. * Constructs a single-track, ISO BMFF media segment from AAC data
  13709. * events. The output of this stream can be fed to a SourceBuffer
  13710. * configured with a suitable initialization segment.
  13711. * @param track {object} track metadata configuration
  13712. * @param options {object} transmuxer options object
  13713. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  13714. * in the source; false to adjust the first segment to start at 0.
  13715. */
  13716. AudioSegmentStream = function (track, options) {
  13717. var adtsFrames = [],
  13718. sequenceNumber,
  13719. earliestAllowedDts = 0,
  13720. audioAppendStartTs = 0,
  13721. videoBaseMediaDecodeTime = Infinity;
  13722. options = options || {};
  13723. sequenceNumber = options.firstSequenceNumber || 0;
  13724. AudioSegmentStream.prototype.init.call(this);
  13725. this.push = function (data) {
  13726. trackDecodeInfo.collectDtsInfo(track, data);
  13727. if (track) {
  13728. AUDIO_PROPERTIES.forEach(function (prop) {
  13729. track[prop] = data[prop];
  13730. });
  13731. } // buffer audio data until end() is called
  13732. adtsFrames.push(data);
  13733. };
  13734. this.setEarliestDts = function (earliestDts) {
  13735. earliestAllowedDts = earliestDts;
  13736. };
  13737. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  13738. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  13739. };
  13740. this.setAudioAppendStart = function (timestamp) {
  13741. audioAppendStartTs = timestamp;
  13742. };
  13743. this.flush = function () {
  13744. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  13745. if (adtsFrames.length === 0) {
  13746. this.trigger('done', 'AudioSegmentStream');
  13747. return;
  13748. }
  13749. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  13750. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  13751. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  13752. // samples (that is, adts frames) in the audio data
  13753. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  13754. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  13755. adtsFrames = [];
  13756. moof = mp4.moof(sequenceNumber, [track]);
  13757. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  13758. sequenceNumber++;
  13759. boxes.set(moof);
  13760. boxes.set(mdat, moof.byteLength);
  13761. trackDecodeInfo.clearDtsInfo(track);
  13762. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  13763. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  13764. // valid use-case where an init segment/data should be triggered without associated
  13765. // frames. Leaving for now, but should be looked into.
  13766. if (frames.length) {
  13767. segmentDuration = frames.length * frameDuration;
  13768. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  13769. // frame info is in video clock cycles. Convert to match expectation of
  13770. // listeners (that all timestamps will be based on video clock cycles).
  13771. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  13772. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  13773. this.trigger('timingInfo', {
  13774. start: frames[0].pts,
  13775. end: frames[0].pts + segmentDuration
  13776. });
  13777. }
  13778. this.trigger('data', {
  13779. track: track,
  13780. boxes: boxes
  13781. });
  13782. this.trigger('done', 'AudioSegmentStream');
  13783. };
  13784. this.reset = function () {
  13785. trackDecodeInfo.clearDtsInfo(track);
  13786. adtsFrames = [];
  13787. this.trigger('reset');
  13788. };
  13789. };
  13790. AudioSegmentStream.prototype = new Stream();
  13791. /**
  13792. * Constructs a single-track, ISO BMFF media segment from H264 data
  13793. * events. The output of this stream can be fed to a SourceBuffer
  13794. * configured with a suitable initialization segment.
  13795. * @param track {object} track metadata configuration
  13796. * @param options {object} transmuxer options object
  13797. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  13798. * gopsToAlignWith list when attempting to align gop pts
  13799. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  13800. * in the source; false to adjust the first segment to start at 0.
  13801. */
  13802. VideoSegmentStream = function (track, options) {
  13803. var sequenceNumber,
  13804. nalUnits = [],
  13805. gopsToAlignWith = [],
  13806. config,
  13807. pps;
  13808. options = options || {};
  13809. sequenceNumber = options.firstSequenceNumber || 0;
  13810. VideoSegmentStream.prototype.init.call(this);
  13811. delete track.minPTS;
  13812. this.gopCache_ = [];
  13813. /**
  13814. * Constructs a ISO BMFF segment given H264 nalUnits
  13815. * @param {Object} nalUnit A data event representing a nalUnit
  13816. * @param {String} nalUnit.nalUnitType
  13817. * @param {Object} nalUnit.config Properties for a mp4 track
  13818. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  13819. * @see lib/codecs/h264.js
  13820. **/
  13821. this.push = function (nalUnit) {
  13822. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  13823. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  13824. config = nalUnit.config;
  13825. track.sps = [nalUnit.data];
  13826. VIDEO_PROPERTIES.forEach(function (prop) {
  13827. track[prop] = config[prop];
  13828. }, this);
  13829. }
  13830. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  13831. pps = nalUnit.data;
  13832. track.pps = [nalUnit.data];
  13833. } // buffer video until flush() is called
  13834. nalUnits.push(nalUnit);
  13835. };
  13836. /**
  13837. * Pass constructed ISO BMFF track and boxes on to the
  13838. * next stream in the pipeline
  13839. **/
  13840. this.flush = function () {
  13841. var frames,
  13842. gopForFusion,
  13843. gops,
  13844. moof,
  13845. mdat,
  13846. boxes,
  13847. prependedContentDuration = 0,
  13848. firstGop,
  13849. lastGop; // Throw away nalUnits at the start of the byte stream until
  13850. // we find the first AUD
  13851. while (nalUnits.length) {
  13852. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  13853. break;
  13854. }
  13855. nalUnits.shift();
  13856. } // Return early if no video data has been observed
  13857. if (nalUnits.length === 0) {
  13858. this.resetStream_();
  13859. this.trigger('done', 'VideoSegmentStream');
  13860. return;
  13861. } // Organize the raw nal-units into arrays that represent
  13862. // higher-level constructs such as frames and gops
  13863. // (group-of-pictures)
  13864. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  13865. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  13866. // a problem since MSE (on Chrome) requires a leading keyframe.
  13867. //
  13868. // We have two approaches to repairing this situation:
  13869. // 1) GOP-FUSION:
  13870. // This is where we keep track of the GOPS (group-of-pictures)
  13871. // from previous fragments and attempt to find one that we can
  13872. // prepend to the current fragment in order to create a valid
  13873. // fragment.
  13874. // 2) KEYFRAME-PULLING:
  13875. // Here we search for the first keyframe in the fragment and
  13876. // throw away all the frames between the start of the fragment
  13877. // and that keyframe. We then extend the duration and pull the
  13878. // PTS of the keyframe forward so that it covers the time range
  13879. // of the frames that were disposed of.
  13880. //
  13881. // #1 is far prefereable over #2 which can cause "stuttering" but
  13882. // requires more things to be just right.
  13883. if (!gops[0][0].keyFrame) {
  13884. // Search for a gop for fusion from our gopCache
  13885. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  13886. if (gopForFusion) {
  13887. // in order to provide more accurate timing information about the segment, save
  13888. // the number of seconds prepended to the original segment due to GOP fusion
  13889. prependedContentDuration = gopForFusion.duration;
  13890. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  13891. // new gop at the beginning
  13892. gops.byteLength += gopForFusion.byteLength;
  13893. gops.nalCount += gopForFusion.nalCount;
  13894. gops.pts = gopForFusion.pts;
  13895. gops.dts = gopForFusion.dts;
  13896. gops.duration += gopForFusion.duration;
  13897. } else {
  13898. // If we didn't find a candidate gop fall back to keyframe-pulling
  13899. gops = frameUtils.extendFirstKeyFrame(gops);
  13900. }
  13901. } // Trim gops to align with gopsToAlignWith
  13902. if (gopsToAlignWith.length) {
  13903. var alignedGops;
  13904. if (options.alignGopsAtEnd) {
  13905. alignedGops = this.alignGopsAtEnd_(gops);
  13906. } else {
  13907. alignedGops = this.alignGopsAtStart_(gops);
  13908. }
  13909. if (!alignedGops) {
  13910. // save all the nals in the last GOP into the gop cache
  13911. this.gopCache_.unshift({
  13912. gop: gops.pop(),
  13913. pps: track.pps,
  13914. sps: track.sps
  13915. }); // Keep a maximum of 6 GOPs in the cache
  13916. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13917. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  13918. this.resetStream_();
  13919. this.trigger('done', 'VideoSegmentStream');
  13920. return;
  13921. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  13922. // when recalculated before sending off to CoalesceStream
  13923. trackDecodeInfo.clearDtsInfo(track);
  13924. gops = alignedGops;
  13925. }
  13926. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  13927. // samples (that is, frames) in the video data
  13928. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  13929. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  13930. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  13931. this.trigger('processedGopsInfo', gops.map(function (gop) {
  13932. return {
  13933. pts: gop.pts,
  13934. dts: gop.dts,
  13935. byteLength: gop.byteLength
  13936. };
  13937. }));
  13938. firstGop = gops[0];
  13939. lastGop = gops[gops.length - 1];
  13940. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  13941. this.trigger('timingInfo', {
  13942. start: gops[0].pts,
  13943. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  13944. }); // save all the nals in the last GOP into the gop cache
  13945. this.gopCache_.unshift({
  13946. gop: gops.pop(),
  13947. pps: track.pps,
  13948. sps: track.sps
  13949. }); // Keep a maximum of 6 GOPs in the cache
  13950. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  13951. nalUnits = [];
  13952. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  13953. this.trigger('timelineStartInfo', track.timelineStartInfo);
  13954. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  13955. // throwing away hundreds of media segment fragments
  13956. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  13957. sequenceNumber++;
  13958. boxes.set(moof);
  13959. boxes.set(mdat, moof.byteLength);
  13960. this.trigger('data', {
  13961. track: track,
  13962. boxes: boxes
  13963. });
  13964. this.resetStream_(); // Continue with the flush process now
  13965. this.trigger('done', 'VideoSegmentStream');
  13966. };
  13967. this.reset = function () {
  13968. this.resetStream_();
  13969. nalUnits = [];
  13970. this.gopCache_.length = 0;
  13971. gopsToAlignWith.length = 0;
  13972. this.trigger('reset');
  13973. };
  13974. this.resetStream_ = function () {
  13975. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  13976. // for instance, when we are rendition switching
  13977. config = undefined;
  13978. pps = undefined;
  13979. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  13980. // return it or return null if no good candidate was found
  13981. this.getGopForFusion_ = function (nalUnit) {
  13982. var halfSecond = 45000,
  13983. // Half-a-second in a 90khz clock
  13984. allowableOverlap = 10000,
  13985. // About 3 frames @ 30fps
  13986. nearestDistance = Infinity,
  13987. dtsDistance,
  13988. nearestGopObj,
  13989. currentGop,
  13990. currentGopObj,
  13991. i; // Search for the GOP nearest to the beginning of this nal unit
  13992. for (i = 0; i < this.gopCache_.length; i++) {
  13993. currentGopObj = this.gopCache_[i];
  13994. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  13995. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  13996. continue;
  13997. } // Reject Gops that would require a negative baseMediaDecodeTime
  13998. if (currentGop.dts < track.timelineStartInfo.dts) {
  13999. continue;
  14000. } // The distance between the end of the gop and the start of the nalUnit
  14001. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  14002. // a half-second of the nal unit
  14003. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  14004. // Always use the closest GOP we found if there is more than
  14005. // one candidate
  14006. if (!nearestGopObj || nearestDistance > dtsDistance) {
  14007. nearestGopObj = currentGopObj;
  14008. nearestDistance = dtsDistance;
  14009. }
  14010. }
  14011. }
  14012. if (nearestGopObj) {
  14013. return nearestGopObj.gop;
  14014. }
  14015. return null;
  14016. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  14017. // of gopsToAlignWith starting from the START of the list
  14018. this.alignGopsAtStart_ = function (gops) {
  14019. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  14020. byteLength = gops.byteLength;
  14021. nalCount = gops.nalCount;
  14022. duration = gops.duration;
  14023. alignIndex = gopIndex = 0;
  14024. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  14025. align = gopsToAlignWith[alignIndex];
  14026. gop = gops[gopIndex];
  14027. if (align.pts === gop.pts) {
  14028. break;
  14029. }
  14030. if (gop.pts > align.pts) {
  14031. // this current gop starts after the current gop we want to align on, so increment
  14032. // align index
  14033. alignIndex++;
  14034. continue;
  14035. } // current gop starts before the current gop we want to align on. so increment gop
  14036. // index
  14037. gopIndex++;
  14038. byteLength -= gop.byteLength;
  14039. nalCount -= gop.nalCount;
  14040. duration -= gop.duration;
  14041. }
  14042. if (gopIndex === 0) {
  14043. // no gops to trim
  14044. return gops;
  14045. }
  14046. if (gopIndex === gops.length) {
  14047. // all gops trimmed, skip appending all gops
  14048. return null;
  14049. }
  14050. alignedGops = gops.slice(gopIndex);
  14051. alignedGops.byteLength = byteLength;
  14052. alignedGops.duration = duration;
  14053. alignedGops.nalCount = nalCount;
  14054. alignedGops.pts = alignedGops[0].pts;
  14055. alignedGops.dts = alignedGops[0].dts;
  14056. return alignedGops;
  14057. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  14058. // of gopsToAlignWith starting from the END of the list
  14059. this.alignGopsAtEnd_ = function (gops) {
  14060. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  14061. alignIndex = gopsToAlignWith.length - 1;
  14062. gopIndex = gops.length - 1;
  14063. alignEndIndex = null;
  14064. matchFound = false;
  14065. while (alignIndex >= 0 && gopIndex >= 0) {
  14066. align = gopsToAlignWith[alignIndex];
  14067. gop = gops[gopIndex];
  14068. if (align.pts === gop.pts) {
  14069. matchFound = true;
  14070. break;
  14071. }
  14072. if (align.pts > gop.pts) {
  14073. alignIndex--;
  14074. continue;
  14075. }
  14076. if (alignIndex === gopsToAlignWith.length - 1) {
  14077. // gop.pts is greater than the last alignment candidate. If no match is found
  14078. // by the end of this loop, we still want to append gops that come after this
  14079. // point
  14080. alignEndIndex = gopIndex;
  14081. }
  14082. gopIndex--;
  14083. }
  14084. if (!matchFound && alignEndIndex === null) {
  14085. return null;
  14086. }
  14087. var trimIndex;
  14088. if (matchFound) {
  14089. trimIndex = gopIndex;
  14090. } else {
  14091. trimIndex = alignEndIndex;
  14092. }
  14093. if (trimIndex === 0) {
  14094. return gops;
  14095. }
  14096. var alignedGops = gops.slice(trimIndex);
  14097. var metadata = alignedGops.reduce(function (total, gop) {
  14098. total.byteLength += gop.byteLength;
  14099. total.duration += gop.duration;
  14100. total.nalCount += gop.nalCount;
  14101. return total;
  14102. }, {
  14103. byteLength: 0,
  14104. duration: 0,
  14105. nalCount: 0
  14106. });
  14107. alignedGops.byteLength = metadata.byteLength;
  14108. alignedGops.duration = metadata.duration;
  14109. alignedGops.nalCount = metadata.nalCount;
  14110. alignedGops.pts = alignedGops[0].pts;
  14111. alignedGops.dts = alignedGops[0].dts;
  14112. return alignedGops;
  14113. };
  14114. this.alignGopsWith = function (newGopsToAlignWith) {
  14115. gopsToAlignWith = newGopsToAlignWith;
  14116. };
  14117. };
  14118. VideoSegmentStream.prototype = new Stream();
  14119. /**
  14120. * A Stream that can combine multiple streams (ie. audio & video)
  14121. * into a single output segment for MSE. Also supports audio-only
  14122. * and video-only streams.
  14123. * @param options {object} transmuxer options object
  14124. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  14125. * in the source; false to adjust the first segment to start at media timeline start.
  14126. */
  14127. CoalesceStream = function (options, metadataStream) {
  14128. // Number of Tracks per output segment
  14129. // If greater than 1, we combine multiple
  14130. // tracks into a single segment
  14131. this.numberOfTracks = 0;
  14132. this.metadataStream = metadataStream;
  14133. options = options || {};
  14134. if (typeof options.remux !== 'undefined') {
  14135. this.remuxTracks = !!options.remux;
  14136. } else {
  14137. this.remuxTracks = true;
  14138. }
  14139. if (typeof options.keepOriginalTimestamps === 'boolean') {
  14140. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  14141. } else {
  14142. this.keepOriginalTimestamps = false;
  14143. }
  14144. this.pendingTracks = [];
  14145. this.videoTrack = null;
  14146. this.pendingBoxes = [];
  14147. this.pendingCaptions = [];
  14148. this.pendingMetadata = [];
  14149. this.pendingBytes = 0;
  14150. this.emittedTracks = 0;
  14151. CoalesceStream.prototype.init.call(this); // Take output from multiple
  14152. this.push = function (output) {
  14153. // buffer incoming captions until the associated video segment
  14154. // finishes
  14155. if (output.content || output.text) {
  14156. return this.pendingCaptions.push(output);
  14157. } // buffer incoming id3 tags until the final flush
  14158. if (output.frames) {
  14159. return this.pendingMetadata.push(output);
  14160. } // Add this track to the list of pending tracks and store
  14161. // important information required for the construction of
  14162. // the final segment
  14163. this.pendingTracks.push(output.track);
  14164. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  14165. // We unshift audio and push video because
  14166. // as of Chrome 75 when switching from
  14167. // one init segment to another if the video
  14168. // mdat does not appear after the audio mdat
  14169. // only audio will play for the duration of our transmux.
  14170. if (output.track.type === 'video') {
  14171. this.videoTrack = output.track;
  14172. this.pendingBoxes.push(output.boxes);
  14173. }
  14174. if (output.track.type === 'audio') {
  14175. this.audioTrack = output.track;
  14176. this.pendingBoxes.unshift(output.boxes);
  14177. }
  14178. };
  14179. };
  14180. CoalesceStream.prototype = new Stream();
  14181. CoalesceStream.prototype.flush = function (flushSource) {
  14182. var offset = 0,
  14183. event = {
  14184. captions: [],
  14185. captionStreams: {},
  14186. metadata: [],
  14187. info: {}
  14188. },
  14189. caption,
  14190. id3,
  14191. initSegment,
  14192. timelineStartPts = 0,
  14193. i;
  14194. if (this.pendingTracks.length < this.numberOfTracks) {
  14195. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  14196. // Return because we haven't received a flush from a data-generating
  14197. // portion of the segment (meaning that we have only recieved meta-data
  14198. // or captions.)
  14199. return;
  14200. } else if (this.remuxTracks) {
  14201. // Return until we have enough tracks from the pipeline to remux (if we
  14202. // are remuxing audio and video into a single MP4)
  14203. return;
  14204. } else if (this.pendingTracks.length === 0) {
  14205. // In the case where we receive a flush without any data having been
  14206. // received we consider it an emitted track for the purposes of coalescing
  14207. // `done` events.
  14208. // We do this for the case where there is an audio and video track in the
  14209. // segment but no audio data. (seen in several playlists with alternate
  14210. // audio tracks and no audio present in the main TS segments.)
  14211. this.emittedTracks++;
  14212. if (this.emittedTracks >= this.numberOfTracks) {
  14213. this.trigger('done');
  14214. this.emittedTracks = 0;
  14215. }
  14216. return;
  14217. }
  14218. }
  14219. if (this.videoTrack) {
  14220. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  14221. VIDEO_PROPERTIES.forEach(function (prop) {
  14222. event.info[prop] = this.videoTrack[prop];
  14223. }, this);
  14224. } else if (this.audioTrack) {
  14225. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  14226. AUDIO_PROPERTIES.forEach(function (prop) {
  14227. event.info[prop] = this.audioTrack[prop];
  14228. }, this);
  14229. }
  14230. if (this.videoTrack || this.audioTrack) {
  14231. if (this.pendingTracks.length === 1) {
  14232. event.type = this.pendingTracks[0].type;
  14233. } else {
  14234. event.type = 'combined';
  14235. }
  14236. this.emittedTracks += this.pendingTracks.length;
  14237. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  14238. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  14239. // and track definitions
  14240. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  14241. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  14242. for (i = 0; i < this.pendingBoxes.length; i++) {
  14243. event.data.set(this.pendingBoxes[i], offset);
  14244. offset += this.pendingBoxes[i].byteLength;
  14245. } // Translate caption PTS times into second offsets to match the
  14246. // video timeline for the segment, and add track info
  14247. for (i = 0; i < this.pendingCaptions.length; i++) {
  14248. caption = this.pendingCaptions[i];
  14249. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  14250. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  14251. event.captionStreams[caption.stream] = true;
  14252. event.captions.push(caption);
  14253. } // Translate ID3 frame PTS times into second offsets to match the
  14254. // video timeline for the segment
  14255. for (i = 0; i < this.pendingMetadata.length; i++) {
  14256. id3 = this.pendingMetadata[i];
  14257. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  14258. event.metadata.push(id3);
  14259. } // We add this to every single emitted segment even though we only need
  14260. // it for the first
  14261. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  14262. this.pendingTracks.length = 0;
  14263. this.videoTrack = null;
  14264. this.pendingBoxes.length = 0;
  14265. this.pendingCaptions.length = 0;
  14266. this.pendingBytes = 0;
  14267. this.pendingMetadata.length = 0; // Emit the built segment
  14268. // We include captions and ID3 tags for backwards compatibility,
  14269. // ideally we should send only video and audio in the data event
  14270. this.trigger('data', event); // Emit each caption to the outside world
  14271. // Ideally, this would happen immediately on parsing captions,
  14272. // but we need to ensure that video data is sent back first
  14273. // so that caption timing can be adjusted to match video timing
  14274. for (i = 0; i < event.captions.length; i++) {
  14275. caption = event.captions[i];
  14276. this.trigger('caption', caption);
  14277. } // Emit each id3 tag to the outside world
  14278. // Ideally, this would happen immediately on parsing the tag,
  14279. // but we need to ensure that video data is sent back first
  14280. // so that ID3 frame timing can be adjusted to match video timing
  14281. for (i = 0; i < event.metadata.length; i++) {
  14282. id3 = event.metadata[i];
  14283. this.trigger('id3Frame', id3);
  14284. }
  14285. } // Only emit `done` if all tracks have been flushed and emitted
  14286. if (this.emittedTracks >= this.numberOfTracks) {
  14287. this.trigger('done');
  14288. this.emittedTracks = 0;
  14289. }
  14290. };
  14291. CoalesceStream.prototype.setRemux = function (val) {
  14292. this.remuxTracks = val;
  14293. };
  14294. /**
  14295. * A Stream that expects MP2T binary data as input and produces
  14296. * corresponding media segments, suitable for use with Media Source
  14297. * Extension (MSE) implementations that support the ISO BMFF byte
  14298. * stream format, like Chrome.
  14299. */
  14300. Transmuxer = function (options) {
  14301. var self = this,
  14302. hasFlushed = true,
  14303. videoTrack,
  14304. audioTrack;
  14305. Transmuxer.prototype.init.call(this);
  14306. options = options || {};
  14307. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  14308. this.transmuxPipeline_ = {};
  14309. this.setupAacPipeline = function () {
  14310. var pipeline = {};
  14311. this.transmuxPipeline_ = pipeline;
  14312. pipeline.type = 'aac';
  14313. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  14314. pipeline.aacStream = new AacStream();
  14315. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  14316. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  14317. pipeline.adtsStream = new AdtsStream();
  14318. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  14319. pipeline.headOfPipeline = pipeline.aacStream;
  14320. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  14321. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  14322. pipeline.metadataStream.on('timestamp', function (frame) {
  14323. pipeline.aacStream.setTimestamp(frame.timeStamp);
  14324. });
  14325. pipeline.aacStream.on('data', function (data) {
  14326. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  14327. return;
  14328. }
  14329. audioTrack = audioTrack || {
  14330. timelineStartInfo: {
  14331. baseMediaDecodeTime: self.baseMediaDecodeTime
  14332. },
  14333. codec: 'adts',
  14334. type: 'audio'
  14335. }; // hook up the audio segment stream to the first track with aac data
  14336. pipeline.coalesceStream.numberOfTracks++;
  14337. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  14338. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  14339. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  14340. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  14341. self.trigger('trackinfo', {
  14342. hasAudio: !!audioTrack,
  14343. hasVideo: !!videoTrack
  14344. });
  14345. }); // Re-emit any data coming from the coalesce stream to the outside world
  14346. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  14347. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  14348. addPipelineLogRetriggers(this, pipeline);
  14349. };
  14350. this.setupTsPipeline = function () {
  14351. var pipeline = {};
  14352. this.transmuxPipeline_ = pipeline;
  14353. pipeline.type = 'ts';
  14354. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  14355. pipeline.packetStream = new m2ts.TransportPacketStream();
  14356. pipeline.parseStream = new m2ts.TransportParseStream();
  14357. pipeline.elementaryStream = new m2ts.ElementaryStream();
  14358. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  14359. pipeline.adtsStream = new AdtsStream();
  14360. pipeline.h264Stream = new H264Stream();
  14361. pipeline.captionStream = new m2ts.CaptionStream(options);
  14362. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  14363. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  14364. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  14365. // demux the streams
  14366. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  14367. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  14368. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  14369. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  14370. pipeline.elementaryStream.on('data', function (data) {
  14371. var i;
  14372. if (data.type === 'metadata') {
  14373. i = data.tracks.length; // scan the tracks listed in the metadata
  14374. while (i--) {
  14375. if (!videoTrack && data.tracks[i].type === 'video') {
  14376. videoTrack = data.tracks[i];
  14377. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  14378. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  14379. audioTrack = data.tracks[i];
  14380. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  14381. }
  14382. } // hook up the video segment stream to the first track with h264 data
  14383. if (videoTrack && !pipeline.videoSegmentStream) {
  14384. pipeline.coalesceStream.numberOfTracks++;
  14385. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  14386. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  14387. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  14388. // When video emits timelineStartInfo data after a flush, we forward that
  14389. // info to the AudioSegmentStream, if it exists, because video timeline
  14390. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  14391. // because this is a particularly subtle form of timestamp alteration.
  14392. if (audioTrack && !options.keepOriginalTimestamps) {
  14393. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  14394. // very earliest DTS we have seen in video because Chrome will
  14395. // interpret any video track with a baseMediaDecodeTime that is
  14396. // non-zero as a gap.
  14397. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  14398. }
  14399. });
  14400. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  14401. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  14402. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  14403. if (audioTrack) {
  14404. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  14405. }
  14406. });
  14407. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  14408. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  14409. }
  14410. if (audioTrack && !pipeline.audioSegmentStream) {
  14411. // hook up the audio segment stream to the first track with aac data
  14412. pipeline.coalesceStream.numberOfTracks++;
  14413. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  14414. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  14415. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  14416. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  14417. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  14418. } // emit pmt info
  14419. self.trigger('trackinfo', {
  14420. hasAudio: !!audioTrack,
  14421. hasVideo: !!videoTrack
  14422. });
  14423. }
  14424. }); // Re-emit any data coming from the coalesce stream to the outside world
  14425. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  14426. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  14427. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  14428. self.trigger('id3Frame', id3Frame);
  14429. });
  14430. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  14431. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  14432. addPipelineLogRetriggers(this, pipeline);
  14433. }; // hook up the segment streams once track metadata is delivered
  14434. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  14435. var pipeline = this.transmuxPipeline_;
  14436. if (!options.keepOriginalTimestamps) {
  14437. this.baseMediaDecodeTime = baseMediaDecodeTime;
  14438. }
  14439. if (audioTrack) {
  14440. audioTrack.timelineStartInfo.dts = undefined;
  14441. audioTrack.timelineStartInfo.pts = undefined;
  14442. trackDecodeInfo.clearDtsInfo(audioTrack);
  14443. if (pipeline.audioTimestampRolloverStream) {
  14444. pipeline.audioTimestampRolloverStream.discontinuity();
  14445. }
  14446. }
  14447. if (videoTrack) {
  14448. if (pipeline.videoSegmentStream) {
  14449. pipeline.videoSegmentStream.gopCache_ = [];
  14450. }
  14451. videoTrack.timelineStartInfo.dts = undefined;
  14452. videoTrack.timelineStartInfo.pts = undefined;
  14453. trackDecodeInfo.clearDtsInfo(videoTrack);
  14454. pipeline.captionStream.reset();
  14455. }
  14456. if (pipeline.timestampRolloverStream) {
  14457. pipeline.timestampRolloverStream.discontinuity();
  14458. }
  14459. };
  14460. this.setAudioAppendStart = function (timestamp) {
  14461. if (audioTrack) {
  14462. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  14463. }
  14464. };
  14465. this.setRemux = function (val) {
  14466. var pipeline = this.transmuxPipeline_;
  14467. options.remux = val;
  14468. if (pipeline && pipeline.coalesceStream) {
  14469. pipeline.coalesceStream.setRemux(val);
  14470. }
  14471. };
  14472. this.alignGopsWith = function (gopsToAlignWith) {
  14473. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  14474. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  14475. }
  14476. };
  14477. this.getLogTrigger_ = function (key) {
  14478. var self = this;
  14479. return function (event) {
  14480. event.stream = key;
  14481. self.trigger('log', event);
  14482. };
  14483. }; // feed incoming data to the front of the parsing pipeline
  14484. this.push = function (data) {
  14485. if (hasFlushed) {
  14486. var isAac = isLikelyAacData(data);
  14487. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  14488. this.setupAacPipeline();
  14489. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  14490. this.setupTsPipeline();
  14491. }
  14492. hasFlushed = false;
  14493. }
  14494. this.transmuxPipeline_.headOfPipeline.push(data);
  14495. }; // flush any buffered data
  14496. this.flush = function () {
  14497. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  14498. this.transmuxPipeline_.headOfPipeline.flush();
  14499. };
  14500. this.endTimeline = function () {
  14501. this.transmuxPipeline_.headOfPipeline.endTimeline();
  14502. };
  14503. this.reset = function () {
  14504. if (this.transmuxPipeline_.headOfPipeline) {
  14505. this.transmuxPipeline_.headOfPipeline.reset();
  14506. }
  14507. }; // Caption data has to be reset when seeking outside buffered range
  14508. this.resetCaptions = function () {
  14509. if (this.transmuxPipeline_.captionStream) {
  14510. this.transmuxPipeline_.captionStream.reset();
  14511. }
  14512. };
  14513. };
  14514. Transmuxer.prototype = new Stream();
  14515. var transmuxer = {
  14516. Transmuxer: Transmuxer,
  14517. VideoSegmentStream: VideoSegmentStream,
  14518. AudioSegmentStream: AudioSegmentStream,
  14519. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  14520. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  14521. // exported for testing
  14522. generateSegmentTimingInfo: generateSegmentTimingInfo
  14523. };
  14524. /**
  14525. * mux.js
  14526. *
  14527. * Copyright (c) Brightcove
  14528. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14529. */
  14530. var toUnsigned$3 = function (value) {
  14531. return value >>> 0;
  14532. };
  14533. var toHexString$1 = function (value) {
  14534. return ('00' + value.toString(16)).slice(-2);
  14535. };
  14536. var bin = {
  14537. toUnsigned: toUnsigned$3,
  14538. toHexString: toHexString$1
  14539. };
  14540. var parseType$3 = function (buffer) {
  14541. var result = '';
  14542. result += String.fromCharCode(buffer[0]);
  14543. result += String.fromCharCode(buffer[1]);
  14544. result += String.fromCharCode(buffer[2]);
  14545. result += String.fromCharCode(buffer[3]);
  14546. return result;
  14547. };
  14548. var parseType_1 = parseType$3;
  14549. var toUnsigned$2 = bin.toUnsigned;
  14550. var parseType$2 = parseType_1;
  14551. var findBox$2 = function (data, path) {
  14552. var results = [],
  14553. i,
  14554. size,
  14555. type,
  14556. end,
  14557. subresults;
  14558. if (!path.length) {
  14559. // short-circuit the search for empty paths
  14560. return null;
  14561. }
  14562. for (i = 0; i < data.byteLength;) {
  14563. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  14564. type = parseType$2(data.subarray(i + 4, i + 8));
  14565. end = size > 1 ? i + size : data.byteLength;
  14566. if (type === path[0]) {
  14567. if (path.length === 1) {
  14568. // this is the end of the path and we've found the box we were
  14569. // looking for
  14570. results.push(data.subarray(i + 8, end));
  14571. } else {
  14572. // recursively search for the next box along the path
  14573. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  14574. if (subresults.length) {
  14575. results = results.concat(subresults);
  14576. }
  14577. }
  14578. }
  14579. i = end;
  14580. } // we've finished searching all of data
  14581. return results;
  14582. };
  14583. var findBox_1 = findBox$2;
  14584. var toUnsigned$1 = bin.toUnsigned;
  14585. var getUint64$2 = numbers.getUint64;
  14586. var tfdt = function (data) {
  14587. var result = {
  14588. version: data[0],
  14589. flags: new Uint8Array(data.subarray(1, 4))
  14590. };
  14591. if (result.version === 1) {
  14592. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  14593. } else {
  14594. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  14595. }
  14596. return result;
  14597. };
  14598. var parseTfdt$2 = tfdt;
  14599. var parseSampleFlags$1 = function (flags) {
  14600. return {
  14601. isLeading: (flags[0] & 0x0c) >>> 2,
  14602. dependsOn: flags[0] & 0x03,
  14603. isDependedOn: (flags[1] & 0xc0) >>> 6,
  14604. hasRedundancy: (flags[1] & 0x30) >>> 4,
  14605. paddingValue: (flags[1] & 0x0e) >>> 1,
  14606. isNonSyncSample: flags[1] & 0x01,
  14607. degradationPriority: flags[2] << 8 | flags[3]
  14608. };
  14609. };
  14610. var parseSampleFlags_1 = parseSampleFlags$1;
  14611. var parseSampleFlags = parseSampleFlags_1;
  14612. var trun = function (data) {
  14613. var result = {
  14614. version: data[0],
  14615. flags: new Uint8Array(data.subarray(1, 4)),
  14616. samples: []
  14617. },
  14618. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  14619. // Flag interpretation
  14620. dataOffsetPresent = result.flags[2] & 0x01,
  14621. // compare with 2nd byte of 0x1
  14622. firstSampleFlagsPresent = result.flags[2] & 0x04,
  14623. // compare with 2nd byte of 0x4
  14624. sampleDurationPresent = result.flags[1] & 0x01,
  14625. // compare with 2nd byte of 0x100
  14626. sampleSizePresent = result.flags[1] & 0x02,
  14627. // compare with 2nd byte of 0x200
  14628. sampleFlagsPresent = result.flags[1] & 0x04,
  14629. // compare with 2nd byte of 0x400
  14630. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  14631. // compare with 2nd byte of 0x800
  14632. sampleCount = view.getUint32(4),
  14633. offset = 8,
  14634. sample;
  14635. if (dataOffsetPresent) {
  14636. // 32 bit signed integer
  14637. result.dataOffset = view.getInt32(offset);
  14638. offset += 4;
  14639. } // Overrides the flags for the first sample only. The order of
  14640. // optional values will be: duration, size, compositionTimeOffset
  14641. if (firstSampleFlagsPresent && sampleCount) {
  14642. sample = {
  14643. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  14644. };
  14645. offset += 4;
  14646. if (sampleDurationPresent) {
  14647. sample.duration = view.getUint32(offset);
  14648. offset += 4;
  14649. }
  14650. if (sampleSizePresent) {
  14651. sample.size = view.getUint32(offset);
  14652. offset += 4;
  14653. }
  14654. if (sampleCompositionTimeOffsetPresent) {
  14655. if (result.version === 1) {
  14656. sample.compositionTimeOffset = view.getInt32(offset);
  14657. } else {
  14658. sample.compositionTimeOffset = view.getUint32(offset);
  14659. }
  14660. offset += 4;
  14661. }
  14662. result.samples.push(sample);
  14663. sampleCount--;
  14664. }
  14665. while (sampleCount--) {
  14666. sample = {};
  14667. if (sampleDurationPresent) {
  14668. sample.duration = view.getUint32(offset);
  14669. offset += 4;
  14670. }
  14671. if (sampleSizePresent) {
  14672. sample.size = view.getUint32(offset);
  14673. offset += 4;
  14674. }
  14675. if (sampleFlagsPresent) {
  14676. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  14677. offset += 4;
  14678. }
  14679. if (sampleCompositionTimeOffsetPresent) {
  14680. if (result.version === 1) {
  14681. sample.compositionTimeOffset = view.getInt32(offset);
  14682. } else {
  14683. sample.compositionTimeOffset = view.getUint32(offset);
  14684. }
  14685. offset += 4;
  14686. }
  14687. result.samples.push(sample);
  14688. }
  14689. return result;
  14690. };
  14691. var parseTrun$2 = trun;
  14692. var tfhd = function (data) {
  14693. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  14694. result = {
  14695. version: data[0],
  14696. flags: new Uint8Array(data.subarray(1, 4)),
  14697. trackId: view.getUint32(4)
  14698. },
  14699. baseDataOffsetPresent = result.flags[2] & 0x01,
  14700. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  14701. defaultSampleDurationPresent = result.flags[2] & 0x08,
  14702. defaultSampleSizePresent = result.flags[2] & 0x10,
  14703. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  14704. durationIsEmpty = result.flags[0] & 0x010000,
  14705. defaultBaseIsMoof = result.flags[0] & 0x020000,
  14706. i;
  14707. i = 8;
  14708. if (baseDataOffsetPresent) {
  14709. i += 4; // truncate top 4 bytes
  14710. // FIXME: should we read the full 64 bits?
  14711. result.baseDataOffset = view.getUint32(12);
  14712. i += 4;
  14713. }
  14714. if (sampleDescriptionIndexPresent) {
  14715. result.sampleDescriptionIndex = view.getUint32(i);
  14716. i += 4;
  14717. }
  14718. if (defaultSampleDurationPresent) {
  14719. result.defaultSampleDuration = view.getUint32(i);
  14720. i += 4;
  14721. }
  14722. if (defaultSampleSizePresent) {
  14723. result.defaultSampleSize = view.getUint32(i);
  14724. i += 4;
  14725. }
  14726. if (defaultSampleFlagsPresent) {
  14727. result.defaultSampleFlags = view.getUint32(i);
  14728. }
  14729. if (durationIsEmpty) {
  14730. result.durationIsEmpty = true;
  14731. }
  14732. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  14733. result.baseDataOffsetIsMoof = true;
  14734. }
  14735. return result;
  14736. };
  14737. var parseTfhd$2 = tfhd;
  14738. var win;
  14739. if (typeof window !== "undefined") {
  14740. win = window;
  14741. } else if (typeof commonjsGlobal !== "undefined") {
  14742. win = commonjsGlobal;
  14743. } else if (typeof self !== "undefined") {
  14744. win = self;
  14745. } else {
  14746. win = {};
  14747. }
  14748. var window_1 = win;
  14749. /**
  14750. * mux.js
  14751. *
  14752. * Copyright (c) Brightcove
  14753. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  14754. *
  14755. * Reads in-band CEA-708 captions out of FMP4 segments.
  14756. * @see https://en.wikipedia.org/wiki/CEA-708
  14757. */
  14758. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  14759. var CaptionStream = captionStream.CaptionStream;
  14760. var findBox$1 = findBox_1;
  14761. var parseTfdt$1 = parseTfdt$2;
  14762. var parseTrun$1 = parseTrun$2;
  14763. var parseTfhd$1 = parseTfhd$2;
  14764. var window$2 = window_1;
  14765. /**
  14766. * Maps an offset in the mdat to a sample based on the the size of the samples.
  14767. * Assumes that `parseSamples` has been called first.
  14768. *
  14769. * @param {Number} offset - The offset into the mdat
  14770. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  14771. * @return {?Object} The matching sample, or null if no match was found.
  14772. *
  14773. * @see ISO-BMFF-12/2015, Section 8.8.8
  14774. **/
  14775. var mapToSample = function (offset, samples) {
  14776. var approximateOffset = offset;
  14777. for (var i = 0; i < samples.length; i++) {
  14778. var sample = samples[i];
  14779. if (approximateOffset < sample.size) {
  14780. return sample;
  14781. }
  14782. approximateOffset -= sample.size;
  14783. }
  14784. return null;
  14785. };
  14786. /**
  14787. * Finds SEI nal units contained in a Media Data Box.
  14788. * Assumes that `parseSamples` has been called first.
  14789. *
  14790. * @param {Uint8Array} avcStream - The bytes of the mdat
  14791. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  14792. * @param {Number} trackId - The trackId of this video track
  14793. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  14794. * The contents of the seiNal should match what is expected by
  14795. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  14796. *
  14797. * @see ISO-BMFF-12/2015, Section 8.1.1
  14798. * @see Rec. ITU-T H.264, 7.3.2.3.1
  14799. **/
  14800. var findSeiNals = function (avcStream, samples, trackId) {
  14801. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  14802. result = {
  14803. logs: [],
  14804. seiNals: []
  14805. },
  14806. seiNal,
  14807. i,
  14808. length,
  14809. lastMatchedSample;
  14810. for (i = 0; i + 4 < avcStream.length; i += length) {
  14811. length = avcView.getUint32(i);
  14812. i += 4; // Bail if this doesn't appear to be an H264 stream
  14813. if (length <= 0) {
  14814. continue;
  14815. }
  14816. switch (avcStream[i] & 0x1F) {
  14817. case 0x06:
  14818. var data = avcStream.subarray(i + 1, i + 1 + length);
  14819. var matchingSample = mapToSample(i, samples);
  14820. seiNal = {
  14821. nalUnitType: 'sei_rbsp',
  14822. size: length,
  14823. data: data,
  14824. escapedRBSP: discardEmulationPreventionBytes(data),
  14825. trackId: trackId
  14826. };
  14827. if (matchingSample) {
  14828. seiNal.pts = matchingSample.pts;
  14829. seiNal.dts = matchingSample.dts;
  14830. lastMatchedSample = matchingSample;
  14831. } else if (lastMatchedSample) {
  14832. // If a matching sample cannot be found, use the last
  14833. // sample's values as they should be as close as possible
  14834. seiNal.pts = lastMatchedSample.pts;
  14835. seiNal.dts = lastMatchedSample.dts;
  14836. } else {
  14837. result.logs.push({
  14838. level: 'warn',
  14839. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  14840. });
  14841. break;
  14842. }
  14843. result.seiNals.push(seiNal);
  14844. break;
  14845. }
  14846. }
  14847. return result;
  14848. };
  14849. /**
  14850. * Parses sample information out of Track Run Boxes and calculates
  14851. * the absolute presentation and decode timestamps of each sample.
  14852. *
  14853. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  14854. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  14855. @see ISO-BMFF-12/2015, Section 8.8.12
  14856. * @param {Object} tfhd - The parsed Track Fragment Header
  14857. * @see inspect.parseTfhd
  14858. * @return {Object[]} the parsed samples
  14859. *
  14860. * @see ISO-BMFF-12/2015, Section 8.8.8
  14861. **/
  14862. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  14863. var currentDts = baseMediaDecodeTime;
  14864. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  14865. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  14866. var trackId = tfhd.trackId;
  14867. var allSamples = [];
  14868. truns.forEach(function (trun) {
  14869. // Note: We currently do not parse the sample table as well
  14870. // as the trun. It's possible some sources will require this.
  14871. // moov > trak > mdia > minf > stbl
  14872. var trackRun = parseTrun$1(trun);
  14873. var samples = trackRun.samples;
  14874. samples.forEach(function (sample) {
  14875. if (sample.duration === undefined) {
  14876. sample.duration = defaultSampleDuration;
  14877. }
  14878. if (sample.size === undefined) {
  14879. sample.size = defaultSampleSize;
  14880. }
  14881. sample.trackId = trackId;
  14882. sample.dts = currentDts;
  14883. if (sample.compositionTimeOffset === undefined) {
  14884. sample.compositionTimeOffset = 0;
  14885. }
  14886. if (typeof currentDts === 'bigint') {
  14887. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  14888. currentDts += window$2.BigInt(sample.duration);
  14889. } else {
  14890. sample.pts = currentDts + sample.compositionTimeOffset;
  14891. currentDts += sample.duration;
  14892. }
  14893. });
  14894. allSamples = allSamples.concat(samples);
  14895. });
  14896. return allSamples;
  14897. };
  14898. /**
  14899. * Parses out caption nals from an FMP4 segment's video tracks.
  14900. *
  14901. * @param {Uint8Array} segment - The bytes of a single segment
  14902. * @param {Number} videoTrackId - The trackId of a video track in the segment
  14903. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  14904. * a list of seiNals found in that track
  14905. **/
  14906. var parseCaptionNals = function (segment, videoTrackId) {
  14907. // To get the samples
  14908. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  14909. var mdats = findBox$1(segment, ['mdat']);
  14910. var captionNals = {};
  14911. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  14912. mdats.forEach(function (mdat, index) {
  14913. var matchingTraf = trafs[index];
  14914. mdatTrafPairs.push({
  14915. mdat: mdat,
  14916. traf: matchingTraf
  14917. });
  14918. });
  14919. mdatTrafPairs.forEach(function (pair) {
  14920. var mdat = pair.mdat;
  14921. var traf = pair.traf;
  14922. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  14923. var headerInfo = parseTfhd$1(tfhd[0]);
  14924. var trackId = headerInfo.trackId;
  14925. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  14926. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  14927. var truns = findBox$1(traf, ['trun']);
  14928. var samples;
  14929. var result; // Only parse video data for the chosen video track
  14930. if (videoTrackId === trackId && truns.length > 0) {
  14931. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  14932. result = findSeiNals(mdat, samples, trackId);
  14933. if (!captionNals[trackId]) {
  14934. captionNals[trackId] = {
  14935. seiNals: [],
  14936. logs: []
  14937. };
  14938. }
  14939. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  14940. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  14941. }
  14942. });
  14943. return captionNals;
  14944. };
  14945. /**
  14946. * Parses out inband captions from an MP4 container and returns
  14947. * caption objects that can be used by WebVTT and the TextTrack API.
  14948. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  14949. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  14950. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  14951. *
  14952. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  14953. * @param {Number} trackId - The id of the video track to parse
  14954. * @param {Number} timescale - The timescale for the video track from the init segment
  14955. *
  14956. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  14957. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  14958. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  14959. * @return {Object[]} parsedCaptions[].content - A list of individual caption segments
  14960. * @return {String} parsedCaptions[].content.text - The visible content of the caption segment
  14961. * @return {Number} parsedCaptions[].content.line - The line height from 1-15 for positioning of the caption segment
  14962. * @return {Number} parsedCaptions[].content.position - The column indent percentage for cue positioning from 10-80
  14963. **/
  14964. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  14965. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  14966. if (trackId === null) {
  14967. return null;
  14968. }
  14969. captionNals = parseCaptionNals(segment, trackId);
  14970. var trackNals = captionNals[trackId] || {};
  14971. return {
  14972. seiNals: trackNals.seiNals,
  14973. logs: trackNals.logs,
  14974. timescale: timescale
  14975. };
  14976. };
  14977. /**
  14978. * Converts SEI NALUs into captions that can be used by video.js
  14979. **/
  14980. var CaptionParser = function () {
  14981. var isInitialized = false;
  14982. var captionStream; // Stores segments seen before trackId and timescale are set
  14983. var segmentCache; // Stores video track ID of the track being parsed
  14984. var trackId; // Stores the timescale of the track being parsed
  14985. var timescale; // Stores captions parsed so far
  14986. var parsedCaptions; // Stores whether we are receiving partial data or not
  14987. var parsingPartial;
  14988. /**
  14989. * A method to indicate whether a CaptionParser has been initalized
  14990. * @returns {Boolean}
  14991. **/
  14992. this.isInitialized = function () {
  14993. return isInitialized;
  14994. };
  14995. /**
  14996. * Initializes the underlying CaptionStream, SEI NAL parsing
  14997. * and management, and caption collection
  14998. **/
  14999. this.init = function (options) {
  15000. captionStream = new CaptionStream();
  15001. isInitialized = true;
  15002. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  15003. captionStream.on('data', function (event) {
  15004. // Convert to seconds in the source's timescale
  15005. event.startTime = event.startPts / timescale;
  15006. event.endTime = event.endPts / timescale;
  15007. parsedCaptions.captions.push(event);
  15008. parsedCaptions.captionStreams[event.stream] = true;
  15009. });
  15010. captionStream.on('log', function (log) {
  15011. parsedCaptions.logs.push(log);
  15012. });
  15013. };
  15014. /**
  15015. * Determines if a new video track will be selected
  15016. * or if the timescale changed
  15017. * @return {Boolean}
  15018. **/
  15019. this.isNewInit = function (videoTrackIds, timescales) {
  15020. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  15021. return false;
  15022. }
  15023. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  15024. };
  15025. /**
  15026. * Parses out SEI captions and interacts with underlying
  15027. * CaptionStream to return dispatched captions
  15028. *
  15029. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  15030. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  15031. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  15032. * @see parseEmbeddedCaptions
  15033. * @see m2ts/caption-stream.js
  15034. **/
  15035. this.parse = function (segment, videoTrackIds, timescales) {
  15036. var parsedData;
  15037. if (!this.isInitialized()) {
  15038. return null; // This is not likely to be a video segment
  15039. } else if (!videoTrackIds || !timescales) {
  15040. return null;
  15041. } else if (this.isNewInit(videoTrackIds, timescales)) {
  15042. // Use the first video track only as there is no
  15043. // mechanism to switch to other video tracks
  15044. trackId = videoTrackIds[0];
  15045. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  15046. // data until we have one.
  15047. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  15048. } else if (trackId === null || !timescale) {
  15049. segmentCache.push(segment);
  15050. return null;
  15051. } // Now that a timescale and trackId is set, parse cached segments
  15052. while (segmentCache.length > 0) {
  15053. var cachedSegment = segmentCache.shift();
  15054. this.parse(cachedSegment, videoTrackIds, timescales);
  15055. }
  15056. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  15057. if (parsedData && parsedData.logs) {
  15058. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  15059. }
  15060. if (parsedData === null || !parsedData.seiNals) {
  15061. if (parsedCaptions.logs.length) {
  15062. return {
  15063. logs: parsedCaptions.logs,
  15064. captions: [],
  15065. captionStreams: []
  15066. };
  15067. }
  15068. return null;
  15069. }
  15070. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  15071. this.flushStream();
  15072. return parsedCaptions;
  15073. };
  15074. /**
  15075. * Pushes SEI NALUs onto CaptionStream
  15076. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  15077. * Assumes that `parseCaptionNals` has been called first
  15078. * @see m2ts/caption-stream.js
  15079. **/
  15080. this.pushNals = function (nals) {
  15081. if (!this.isInitialized() || !nals || nals.length === 0) {
  15082. return null;
  15083. }
  15084. nals.forEach(function (nal) {
  15085. captionStream.push(nal);
  15086. });
  15087. };
  15088. /**
  15089. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  15090. * @see m2ts/caption-stream.js
  15091. **/
  15092. this.flushStream = function () {
  15093. if (!this.isInitialized()) {
  15094. return null;
  15095. }
  15096. if (!parsingPartial) {
  15097. captionStream.flush();
  15098. } else {
  15099. captionStream.partialFlush();
  15100. }
  15101. };
  15102. /**
  15103. * Reset caption buckets for new data
  15104. **/
  15105. this.clearParsedCaptions = function () {
  15106. parsedCaptions.captions = [];
  15107. parsedCaptions.captionStreams = {};
  15108. parsedCaptions.logs = [];
  15109. };
  15110. /**
  15111. * Resets underlying CaptionStream
  15112. * @see m2ts/caption-stream.js
  15113. **/
  15114. this.resetCaptionStream = function () {
  15115. if (!this.isInitialized()) {
  15116. return null;
  15117. }
  15118. captionStream.reset();
  15119. };
  15120. /**
  15121. * Convenience method to clear all captions flushed from the
  15122. * CaptionStream and still being parsed
  15123. * @see m2ts/caption-stream.js
  15124. **/
  15125. this.clearAllCaptions = function () {
  15126. this.clearParsedCaptions();
  15127. this.resetCaptionStream();
  15128. };
  15129. /**
  15130. * Reset caption parser
  15131. **/
  15132. this.reset = function () {
  15133. segmentCache = [];
  15134. trackId = null;
  15135. timescale = null;
  15136. if (!parsedCaptions) {
  15137. parsedCaptions = {
  15138. captions: [],
  15139. // CC1, CC2, CC3, CC4
  15140. captionStreams: {},
  15141. logs: []
  15142. };
  15143. } else {
  15144. this.clearParsedCaptions();
  15145. }
  15146. this.resetCaptionStream();
  15147. };
  15148. this.reset();
  15149. };
  15150. var captionParser = CaptionParser;
  15151. /**
  15152. * Returns the first string in the data array ending with a null char '\0'
  15153. * @param {UInt8} data
  15154. * @returns the string with the null char
  15155. */
  15156. var uint8ToCString$1 = function (data) {
  15157. var index = 0;
  15158. var curChar = String.fromCharCode(data[index]);
  15159. var retString = '';
  15160. while (curChar !== '\0') {
  15161. retString += curChar;
  15162. index++;
  15163. curChar = String.fromCharCode(data[index]);
  15164. } // Add nullChar
  15165. retString += curChar;
  15166. return retString;
  15167. };
  15168. var string = {
  15169. uint8ToCString: uint8ToCString$1
  15170. };
  15171. var uint8ToCString = string.uint8ToCString;
  15172. var getUint64$1 = numbers.getUint64;
  15173. /**
  15174. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  15175. * References:
  15176. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  15177. * https://aomediacodec.github.io/id3-emsg/
  15178. *
  15179. * Takes emsg box data as a uint8 array and returns a emsg box object
  15180. * @param {UInt8Array} boxData data from emsg box
  15181. * @returns A parsed emsg box object
  15182. */
  15183. var parseEmsgBox = function (boxData) {
  15184. // version + flags
  15185. var offset = 4;
  15186. var version = boxData[0];
  15187. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  15188. if (version === 0) {
  15189. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  15190. offset += scheme_id_uri.length;
  15191. value = uint8ToCString(boxData.subarray(offset));
  15192. offset += value.length;
  15193. var dv = new DataView(boxData.buffer);
  15194. timescale = dv.getUint32(offset);
  15195. offset += 4;
  15196. presentation_time_delta = dv.getUint32(offset);
  15197. offset += 4;
  15198. event_duration = dv.getUint32(offset);
  15199. offset += 4;
  15200. id = dv.getUint32(offset);
  15201. offset += 4;
  15202. } else if (version === 1) {
  15203. var dv = new DataView(boxData.buffer);
  15204. timescale = dv.getUint32(offset);
  15205. offset += 4;
  15206. presentation_time = getUint64$1(boxData.subarray(offset));
  15207. offset += 8;
  15208. event_duration = dv.getUint32(offset);
  15209. offset += 4;
  15210. id = dv.getUint32(offset);
  15211. offset += 4;
  15212. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  15213. offset += scheme_id_uri.length;
  15214. value = uint8ToCString(boxData.subarray(offset));
  15215. offset += value.length;
  15216. }
  15217. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  15218. var emsgBox = {
  15219. scheme_id_uri,
  15220. value,
  15221. // if timescale is undefined or 0 set to 1
  15222. timescale: timescale ? timescale : 1,
  15223. presentation_time,
  15224. presentation_time_delta,
  15225. event_duration,
  15226. id,
  15227. message_data
  15228. };
  15229. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  15230. };
  15231. /**
  15232. * Scales a presentation time or time delta with an offset with a provided timescale
  15233. * @param {number} presentationTime
  15234. * @param {number} timescale
  15235. * @param {number} timeDelta
  15236. * @param {number} offset
  15237. * @returns the scaled time as a number
  15238. */
  15239. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  15240. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  15241. };
  15242. /**
  15243. * Checks the emsg box data for validity based on the version
  15244. * @param {number} version of the emsg box to validate
  15245. * @param {Object} emsg the emsg data to validate
  15246. * @returns if the box is valid as a boolean
  15247. */
  15248. var isValidEmsgBox = function (version, emsg) {
  15249. var hasScheme = emsg.scheme_id_uri !== '\0';
  15250. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  15251. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  15252. return !(version > 1) && isValidV0Box || isValidV1Box;
  15253. }; // Utility function to check if an object is defined
  15254. var isDefined = function (data) {
  15255. return data !== undefined || data !== null;
  15256. };
  15257. var emsg$1 = {
  15258. parseEmsgBox: parseEmsgBox,
  15259. scaleTime: scaleTime
  15260. };
  15261. /**
  15262. * mux.js
  15263. *
  15264. * Copyright (c) Brightcove
  15265. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  15266. *
  15267. * Utilities to detect basic properties and metadata about MP4s.
  15268. */
  15269. var toUnsigned = bin.toUnsigned;
  15270. var toHexString = bin.toHexString;
  15271. var findBox = findBox_1;
  15272. var parseType$1 = parseType_1;
  15273. var emsg = emsg$1;
  15274. var parseTfhd = parseTfhd$2;
  15275. var parseTrun = parseTrun$2;
  15276. var parseTfdt = parseTfdt$2;
  15277. var getUint64 = numbers.getUint64;
  15278. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  15279. var window$1 = window_1;
  15280. var parseId3Frames = parseId3.parseId3Frames;
  15281. /**
  15282. * Parses an MP4 initialization segment and extracts the timescale
  15283. * values for any declared tracks. Timescale values indicate the
  15284. * number of clock ticks per second to assume for time-based values
  15285. * elsewhere in the MP4.
  15286. *
  15287. * To determine the start time of an MP4, you need two pieces of
  15288. * information: the timescale unit and the earliest base media decode
  15289. * time. Multiple timescales can be specified within an MP4 but the
  15290. * base media decode time is always expressed in the timescale from
  15291. * the media header box for the track:
  15292. * ```
  15293. * moov > trak > mdia > mdhd.timescale
  15294. * ```
  15295. * @param init {Uint8Array} the bytes of the init segment
  15296. * @return {object} a hash of track ids to timescale values or null if
  15297. * the init segment is malformed.
  15298. */
  15299. timescale = function (init) {
  15300. var result = {},
  15301. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  15302. return traks.reduce(function (result, trak) {
  15303. var tkhd, version, index, id, mdhd;
  15304. tkhd = findBox(trak, ['tkhd'])[0];
  15305. if (!tkhd) {
  15306. return null;
  15307. }
  15308. version = tkhd[0];
  15309. index = version === 0 ? 12 : 20;
  15310. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  15311. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  15312. if (!mdhd) {
  15313. return null;
  15314. }
  15315. version = mdhd[0];
  15316. index = version === 0 ? 12 : 20;
  15317. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  15318. return result;
  15319. }, result);
  15320. };
  15321. /**
  15322. * Determine the base media decode start time, in seconds, for an MP4
  15323. * fragment. If multiple fragments are specified, the earliest time is
  15324. * returned.
  15325. *
  15326. * The base media decode time can be parsed from track fragment
  15327. * metadata:
  15328. * ```
  15329. * moof > traf > tfdt.baseMediaDecodeTime
  15330. * ```
  15331. * It requires the timescale value from the mdhd to interpret.
  15332. *
  15333. * @param timescale {object} a hash of track ids to timescale values.
  15334. * @return {number} the earliest base media decode start time for the
  15335. * fragment, in seconds
  15336. */
  15337. startTime = function (timescale, fragment) {
  15338. var trafs; // we need info from two childrend of each track fragment box
  15339. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  15340. var lowestTime = trafs.reduce(function (acc, traf) {
  15341. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  15342. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  15343. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  15344. var tfdt = findBox(traf, ['tfdt'])[0];
  15345. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  15346. var baseTime; // version 1 is 64 bit
  15347. if (tfdt[0] === 1) {
  15348. baseTime = getUint64(tfdt.subarray(4, 12));
  15349. } else {
  15350. baseTime = dv.getUint32(4);
  15351. } // convert base time to seconds if it is a valid number.
  15352. let seconds;
  15353. if (typeof baseTime === 'bigint') {
  15354. seconds = baseTime / window$1.BigInt(scale);
  15355. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  15356. seconds = baseTime / scale;
  15357. }
  15358. if (seconds < Number.MAX_SAFE_INTEGER) {
  15359. seconds = Number(seconds);
  15360. }
  15361. if (seconds < acc) {
  15362. acc = seconds;
  15363. }
  15364. return acc;
  15365. }, Infinity);
  15366. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  15367. };
  15368. /**
  15369. * Determine the composition start, in seconds, for an MP4
  15370. * fragment.
  15371. *
  15372. * The composition start time of a fragment can be calculated using the base
  15373. * media decode time, composition time offset, and timescale, as follows:
  15374. *
  15375. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  15376. *
  15377. * All of the aforementioned information is contained within a media fragment's
  15378. * `traf` box, except for timescale info, which comes from the initialization
  15379. * segment, so a track id (also contained within a `traf`) is also necessary to
  15380. * associate it with a timescale
  15381. *
  15382. *
  15383. * @param timescales {object} - a hash of track ids to timescale values.
  15384. * @param fragment {Unit8Array} - the bytes of a media segment
  15385. * @return {number} the composition start time for the fragment, in seconds
  15386. **/
  15387. compositionStartTime = function (timescales, fragment) {
  15388. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  15389. var baseMediaDecodeTime = 0;
  15390. var compositionTimeOffset = 0;
  15391. var trackId;
  15392. if (trafBoxes && trafBoxes.length) {
  15393. // The spec states that track run samples contained within a `traf` box are contiguous, but
  15394. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  15395. // We will assume that they are, so we only need the first to calculate start time.
  15396. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  15397. var trun = findBox(trafBoxes[0], ['trun'])[0];
  15398. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  15399. if (tfhd) {
  15400. var parsedTfhd = parseTfhd(tfhd);
  15401. trackId = parsedTfhd.trackId;
  15402. }
  15403. if (tfdt) {
  15404. var parsedTfdt = parseTfdt(tfdt);
  15405. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  15406. }
  15407. if (trun) {
  15408. var parsedTrun = parseTrun(trun);
  15409. if (parsedTrun.samples && parsedTrun.samples.length) {
  15410. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  15411. }
  15412. }
  15413. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  15414. // specified.
  15415. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  15416. if (typeof baseMediaDecodeTime === 'bigint') {
  15417. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  15418. timescale = window$1.BigInt(timescale);
  15419. }
  15420. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  15421. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  15422. result = Number(result);
  15423. }
  15424. return result;
  15425. };
  15426. /**
  15427. * Find the trackIds of the video tracks in this source.
  15428. * Found by parsing the Handler Reference and Track Header Boxes:
  15429. * moov > trak > mdia > hdlr
  15430. * moov > trak > tkhd
  15431. *
  15432. * @param {Uint8Array} init - The bytes of the init segment for this source
  15433. * @return {Number[]} A list of trackIds
  15434. *
  15435. * @see ISO-BMFF-12/2015, Section 8.4.3
  15436. **/
  15437. getVideoTrackIds = function (init) {
  15438. var traks = findBox(init, ['moov', 'trak']);
  15439. var videoTrackIds = [];
  15440. traks.forEach(function (trak) {
  15441. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  15442. var tkhds = findBox(trak, ['tkhd']);
  15443. hdlrs.forEach(function (hdlr, index) {
  15444. var handlerType = parseType$1(hdlr.subarray(8, 12));
  15445. var tkhd = tkhds[index];
  15446. var view;
  15447. var version;
  15448. var trackId;
  15449. if (handlerType === 'vide') {
  15450. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  15451. version = view.getUint8(0);
  15452. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  15453. videoTrackIds.push(trackId);
  15454. }
  15455. });
  15456. });
  15457. return videoTrackIds;
  15458. };
  15459. getTimescaleFromMediaHeader = function (mdhd) {
  15460. // mdhd is a FullBox, meaning it will have its own version as the first byte
  15461. var version = mdhd[0];
  15462. var index = version === 0 ? 12 : 20;
  15463. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  15464. };
  15465. /**
  15466. * Get all the video, audio, and hint tracks from a non fragmented
  15467. * mp4 segment
  15468. */
  15469. getTracks = function (init) {
  15470. var traks = findBox(init, ['moov', 'trak']);
  15471. var tracks = [];
  15472. traks.forEach(function (trak) {
  15473. var track = {};
  15474. var tkhd = findBox(trak, ['tkhd'])[0];
  15475. var view, tkhdVersion; // id
  15476. if (tkhd) {
  15477. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  15478. tkhdVersion = view.getUint8(0);
  15479. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  15480. }
  15481. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  15482. if (hdlr) {
  15483. var type = parseType$1(hdlr.subarray(8, 12));
  15484. if (type === 'vide') {
  15485. track.type = 'video';
  15486. } else if (type === 'soun') {
  15487. track.type = 'audio';
  15488. } else {
  15489. track.type = type;
  15490. }
  15491. } // codec
  15492. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  15493. if (stsd) {
  15494. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  15495. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  15496. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  15497. var codecConfig, codecConfigType;
  15498. if (codecBox) {
  15499. // https://tools.ietf.org/html/rfc6381#section-3.3
  15500. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  15501. // we don't need anything but the "config" parameter of the
  15502. // avc1 codecBox
  15503. codecConfig = codecBox.subarray(78);
  15504. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  15505. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  15506. track.codec += '.'; // left padded with zeroes for single digit hex
  15507. // profile idc
  15508. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  15509. track.codec += toHexString(codecConfig[10]); // level idc
  15510. track.codec += toHexString(codecConfig[11]);
  15511. } else {
  15512. // TODO: show a warning that we couldn't parse the codec
  15513. // and are using the default
  15514. track.codec = 'avc1.4d400d';
  15515. }
  15516. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  15517. // we do not need anything but the streamDescriptor of the mp4a codecBox
  15518. codecConfig = codecBox.subarray(28);
  15519. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  15520. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  15521. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  15522. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  15523. } else {
  15524. // TODO: show a warning that we couldn't parse the codec
  15525. // and are using the default
  15526. track.codec = 'mp4a.40.2';
  15527. }
  15528. } else {
  15529. // flac, opus, etc
  15530. track.codec = track.codec.toLowerCase();
  15531. }
  15532. }
  15533. }
  15534. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  15535. if (mdhd) {
  15536. track.timescale = getTimescaleFromMediaHeader(mdhd);
  15537. }
  15538. tracks.push(track);
  15539. });
  15540. return tracks;
  15541. };
  15542. /**
  15543. * Returns an array of emsg ID3 data from the provided segmentData.
  15544. * An offset can also be provided as the Latest Arrival Time to calculate
  15545. * the Event Start Time of v0 EMSG boxes.
  15546. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  15547. *
  15548. * @param {Uint8Array} segmentData the segment byte array.
  15549. * @param {number} offset the segment start time or Latest Arrival Time,
  15550. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  15551. */
  15552. getEmsgID3 = function (segmentData, offset = 0) {
  15553. var emsgBoxes = findBox(segmentData, ['emsg']);
  15554. return emsgBoxes.map(data => {
  15555. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  15556. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  15557. return {
  15558. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  15559. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  15560. frames: parsedId3Frames
  15561. };
  15562. });
  15563. };
  15564. var probe$2 = {
  15565. // export mp4 inspector's findBox and parseType for backwards compatibility
  15566. findBox: findBox,
  15567. parseType: parseType$1,
  15568. timescale: timescale,
  15569. startTime: startTime,
  15570. compositionStartTime: compositionStartTime,
  15571. videoTrackIds: getVideoTrackIds,
  15572. tracks: getTracks,
  15573. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  15574. getEmsgID3: getEmsgID3
  15575. };
  15576. /**
  15577. * mux.js
  15578. *
  15579. * Copyright (c) Brightcove
  15580. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  15581. *
  15582. * Utilities to detect basic properties and metadata about TS Segments.
  15583. */
  15584. var StreamTypes$1 = streamTypes;
  15585. var parsePid = function (packet) {
  15586. var pid = packet[1] & 0x1f;
  15587. pid <<= 8;
  15588. pid |= packet[2];
  15589. return pid;
  15590. };
  15591. var parsePayloadUnitStartIndicator = function (packet) {
  15592. return !!(packet[1] & 0x40);
  15593. };
  15594. var parseAdaptionField = function (packet) {
  15595. var offset = 0; // if an adaption field is present, its length is specified by the
  15596. // fifth byte of the TS packet header. The adaptation field is
  15597. // used to add stuffing to PES packets that don't fill a complete
  15598. // TS packet, and to specify some forms of timing and control data
  15599. // that we do not currently use.
  15600. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  15601. offset += packet[4] + 1;
  15602. }
  15603. return offset;
  15604. };
  15605. var parseType = function (packet, pmtPid) {
  15606. var pid = parsePid(packet);
  15607. if (pid === 0) {
  15608. return 'pat';
  15609. } else if (pid === pmtPid) {
  15610. return 'pmt';
  15611. } else if (pmtPid) {
  15612. return 'pes';
  15613. }
  15614. return null;
  15615. };
  15616. var parsePat = function (packet) {
  15617. var pusi = parsePayloadUnitStartIndicator(packet);
  15618. var offset = 4 + parseAdaptionField(packet);
  15619. if (pusi) {
  15620. offset += packet[offset] + 1;
  15621. }
  15622. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  15623. };
  15624. var parsePmt = function (packet) {
  15625. var programMapTable = {};
  15626. var pusi = parsePayloadUnitStartIndicator(packet);
  15627. var payloadOffset = 4 + parseAdaptionField(packet);
  15628. if (pusi) {
  15629. payloadOffset += packet[payloadOffset] + 1;
  15630. } // PMTs can be sent ahead of the time when they should actually
  15631. // take effect. We don't believe this should ever be the case
  15632. // for HLS but we'll ignore "forward" PMT declarations if we see
  15633. // them. Future PMT declarations have the current_next_indicator
  15634. // set to zero.
  15635. if (!(packet[payloadOffset + 5] & 0x01)) {
  15636. return;
  15637. }
  15638. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  15639. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  15640. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  15641. // long the program info descriptors are
  15642. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  15643. var offset = 12 + programInfoLength;
  15644. while (offset < tableEnd) {
  15645. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  15646. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  15647. // skip past the elementary stream descriptors, if present
  15648. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  15649. }
  15650. return programMapTable;
  15651. };
  15652. var parsePesType = function (packet, programMapTable) {
  15653. var pid = parsePid(packet);
  15654. var type = programMapTable[pid];
  15655. switch (type) {
  15656. case StreamTypes$1.H264_STREAM_TYPE:
  15657. return 'video';
  15658. case StreamTypes$1.ADTS_STREAM_TYPE:
  15659. return 'audio';
  15660. case StreamTypes$1.METADATA_STREAM_TYPE:
  15661. return 'timed-metadata';
  15662. default:
  15663. return null;
  15664. }
  15665. };
  15666. var parsePesTime = function (packet) {
  15667. var pusi = parsePayloadUnitStartIndicator(packet);
  15668. if (!pusi) {
  15669. return null;
  15670. }
  15671. var offset = 4 + parseAdaptionField(packet);
  15672. if (offset >= packet.byteLength) {
  15673. // From the H 222.0 MPEG-TS spec
  15674. // "For transport stream packets carrying PES packets, stuffing is needed when there
  15675. // is insufficient PES packet data to completely fill the transport stream packet
  15676. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  15677. // the sum of the lengths of the data elements in it, so that the payload bytes
  15678. // remaining after the adaptation field exactly accommodates the available PES packet
  15679. // data."
  15680. //
  15681. // If the offset is >= the length of the packet, then the packet contains no data
  15682. // and instead is just adaption field stuffing bytes
  15683. return null;
  15684. }
  15685. var pes = null;
  15686. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  15687. // and a DTS value. Determine what combination of values is
  15688. // available to work with.
  15689. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  15690. // performs all bitwise operations on 32-bit integers but javascript
  15691. // supports a much greater range (52-bits) of integer using standard
  15692. // mathematical operations.
  15693. // We construct a 31-bit value using bitwise operators over the 31
  15694. // most significant bits and then multiply by 4 (equal to a left-shift
  15695. // of 2) before we add the final 2 least significant bits of the
  15696. // timestamp (equal to an OR.)
  15697. if (ptsDtsFlags & 0xC0) {
  15698. pes = {}; // the PTS and DTS are not written out directly. For information
  15699. // on how they are encoded, see
  15700. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  15701. 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;
  15702. pes.pts *= 4; // Left shift by 2
  15703. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  15704. pes.dts = pes.pts;
  15705. if (ptsDtsFlags & 0x40) {
  15706. 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;
  15707. pes.dts *= 4; // Left shift by 2
  15708. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  15709. }
  15710. }
  15711. return pes;
  15712. };
  15713. var parseNalUnitType = function (type) {
  15714. switch (type) {
  15715. case 0x05:
  15716. return 'slice_layer_without_partitioning_rbsp_idr';
  15717. case 0x06:
  15718. return 'sei_rbsp';
  15719. case 0x07:
  15720. return 'seq_parameter_set_rbsp';
  15721. case 0x08:
  15722. return 'pic_parameter_set_rbsp';
  15723. case 0x09:
  15724. return 'access_unit_delimiter_rbsp';
  15725. default:
  15726. return null;
  15727. }
  15728. };
  15729. var videoPacketContainsKeyFrame = function (packet) {
  15730. var offset = 4 + parseAdaptionField(packet);
  15731. var frameBuffer = packet.subarray(offset);
  15732. var frameI = 0;
  15733. var frameSyncPoint = 0;
  15734. var foundKeyFrame = false;
  15735. var nalType; // advance the sync point to a NAL start, if necessary
  15736. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  15737. if (frameBuffer[frameSyncPoint + 2] === 1) {
  15738. // the sync point is properly aligned
  15739. frameI = frameSyncPoint + 5;
  15740. break;
  15741. }
  15742. }
  15743. while (frameI < frameBuffer.byteLength) {
  15744. // look at the current byte to determine if we've hit the end of
  15745. // a NAL unit boundary
  15746. switch (frameBuffer[frameI]) {
  15747. case 0:
  15748. // skip past non-sync sequences
  15749. if (frameBuffer[frameI - 1] !== 0) {
  15750. frameI += 2;
  15751. break;
  15752. } else if (frameBuffer[frameI - 2] !== 0) {
  15753. frameI++;
  15754. break;
  15755. }
  15756. if (frameSyncPoint + 3 !== frameI - 2) {
  15757. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  15758. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  15759. foundKeyFrame = true;
  15760. }
  15761. } // drop trailing zeroes
  15762. do {
  15763. frameI++;
  15764. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  15765. frameSyncPoint = frameI - 2;
  15766. frameI += 3;
  15767. break;
  15768. case 1:
  15769. // skip past non-sync sequences
  15770. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  15771. frameI += 3;
  15772. break;
  15773. }
  15774. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  15775. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  15776. foundKeyFrame = true;
  15777. }
  15778. frameSyncPoint = frameI - 2;
  15779. frameI += 3;
  15780. break;
  15781. default:
  15782. // the current byte isn't a one or zero, so it cannot be part
  15783. // of a sync sequence
  15784. frameI += 3;
  15785. break;
  15786. }
  15787. }
  15788. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  15789. frameI -= frameSyncPoint;
  15790. frameSyncPoint = 0; // parse the final nal
  15791. if (frameBuffer && frameBuffer.byteLength > 3) {
  15792. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  15793. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  15794. foundKeyFrame = true;
  15795. }
  15796. }
  15797. return foundKeyFrame;
  15798. };
  15799. var probe$1 = {
  15800. parseType: parseType,
  15801. parsePat: parsePat,
  15802. parsePmt: parsePmt,
  15803. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  15804. parsePesType: parsePesType,
  15805. parsePesTime: parsePesTime,
  15806. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  15807. };
  15808. /**
  15809. * mux.js
  15810. *
  15811. * Copyright (c) Brightcove
  15812. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  15813. *
  15814. * Parse mpeg2 transport stream packets to extract basic timing information
  15815. */
  15816. var StreamTypes = streamTypes;
  15817. var handleRollover = timestampRolloverStream.handleRollover;
  15818. var probe = {};
  15819. probe.ts = probe$1;
  15820. probe.aac = utils;
  15821. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  15822. var MP2T_PACKET_LENGTH = 188,
  15823. // bytes
  15824. SYNC_BYTE = 0x47;
  15825. /**
  15826. * walks through segment data looking for pat and pmt packets to parse out
  15827. * program map table information
  15828. */
  15829. var parsePsi_ = function (bytes, pmt) {
  15830. var startIndex = 0,
  15831. endIndex = MP2T_PACKET_LENGTH,
  15832. packet,
  15833. type;
  15834. while (endIndex < bytes.byteLength) {
  15835. // Look for a pair of start and end sync bytes in the data..
  15836. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15837. // We found a packet
  15838. packet = bytes.subarray(startIndex, endIndex);
  15839. type = probe.ts.parseType(packet, pmt.pid);
  15840. switch (type) {
  15841. case 'pat':
  15842. pmt.pid = probe.ts.parsePat(packet);
  15843. break;
  15844. case 'pmt':
  15845. var table = probe.ts.parsePmt(packet);
  15846. pmt.table = pmt.table || {};
  15847. Object.keys(table).forEach(function (key) {
  15848. pmt.table[key] = table[key];
  15849. });
  15850. break;
  15851. }
  15852. startIndex += MP2T_PACKET_LENGTH;
  15853. endIndex += MP2T_PACKET_LENGTH;
  15854. continue;
  15855. } // If we get here, we have somehow become de-synchronized and we need to step
  15856. // forward one byte at a time until we find a pair of sync bytes that denote
  15857. // a packet
  15858. startIndex++;
  15859. endIndex++;
  15860. }
  15861. };
  15862. /**
  15863. * walks through the segment data from the start and end to get timing information
  15864. * for the first and last audio pes packets
  15865. */
  15866. var parseAudioPes_ = function (bytes, pmt, result) {
  15867. var startIndex = 0,
  15868. endIndex = MP2T_PACKET_LENGTH,
  15869. packet,
  15870. type,
  15871. pesType,
  15872. pusi,
  15873. parsed;
  15874. var endLoop = false; // Start walking from start of segment to get first audio packet
  15875. while (endIndex <= bytes.byteLength) {
  15876. // Look for a pair of start and end sync bytes in the data..
  15877. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15878. // We found a packet
  15879. packet = bytes.subarray(startIndex, endIndex);
  15880. type = probe.ts.parseType(packet, pmt.pid);
  15881. switch (type) {
  15882. case 'pes':
  15883. pesType = probe.ts.parsePesType(packet, pmt.table);
  15884. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15885. if (pesType === 'audio' && pusi) {
  15886. parsed = probe.ts.parsePesTime(packet);
  15887. if (parsed) {
  15888. parsed.type = 'audio';
  15889. result.audio.push(parsed);
  15890. endLoop = true;
  15891. }
  15892. }
  15893. break;
  15894. }
  15895. if (endLoop) {
  15896. break;
  15897. }
  15898. startIndex += MP2T_PACKET_LENGTH;
  15899. endIndex += MP2T_PACKET_LENGTH;
  15900. continue;
  15901. } // If we get here, we have somehow become de-synchronized and we need to step
  15902. // forward one byte at a time until we find a pair of sync bytes that denote
  15903. // a packet
  15904. startIndex++;
  15905. endIndex++;
  15906. } // Start walking from end of segment to get last audio packet
  15907. endIndex = bytes.byteLength;
  15908. startIndex = endIndex - MP2T_PACKET_LENGTH;
  15909. endLoop = false;
  15910. while (startIndex >= 0) {
  15911. // Look for a pair of start and end sync bytes in the data..
  15912. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  15913. // We found a packet
  15914. packet = bytes.subarray(startIndex, endIndex);
  15915. type = probe.ts.parseType(packet, pmt.pid);
  15916. switch (type) {
  15917. case 'pes':
  15918. pesType = probe.ts.parsePesType(packet, pmt.table);
  15919. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15920. if (pesType === 'audio' && pusi) {
  15921. parsed = probe.ts.parsePesTime(packet);
  15922. if (parsed) {
  15923. parsed.type = 'audio';
  15924. result.audio.push(parsed);
  15925. endLoop = true;
  15926. }
  15927. }
  15928. break;
  15929. }
  15930. if (endLoop) {
  15931. break;
  15932. }
  15933. startIndex -= MP2T_PACKET_LENGTH;
  15934. endIndex -= MP2T_PACKET_LENGTH;
  15935. continue;
  15936. } // If we get here, we have somehow become de-synchronized and we need to step
  15937. // forward one byte at a time until we find a pair of sync bytes that denote
  15938. // a packet
  15939. startIndex--;
  15940. endIndex--;
  15941. }
  15942. };
  15943. /**
  15944. * walks through the segment data from the start and end to get timing information
  15945. * for the first and last video pes packets as well as timing information for the first
  15946. * key frame.
  15947. */
  15948. var parseVideoPes_ = function (bytes, pmt, result) {
  15949. var startIndex = 0,
  15950. endIndex = MP2T_PACKET_LENGTH,
  15951. packet,
  15952. type,
  15953. pesType,
  15954. pusi,
  15955. parsed,
  15956. frame,
  15957. i,
  15958. pes;
  15959. var endLoop = false;
  15960. var currentFrame = {
  15961. data: [],
  15962. size: 0
  15963. }; // Start walking from start of segment to get first video packet
  15964. while (endIndex < bytes.byteLength) {
  15965. // Look for a pair of start and end sync bytes in the data..
  15966. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  15967. // We found a packet
  15968. packet = bytes.subarray(startIndex, endIndex);
  15969. type = probe.ts.parseType(packet, pmt.pid);
  15970. switch (type) {
  15971. case 'pes':
  15972. pesType = probe.ts.parsePesType(packet, pmt.table);
  15973. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  15974. if (pesType === 'video') {
  15975. if (pusi && !endLoop) {
  15976. parsed = probe.ts.parsePesTime(packet);
  15977. if (parsed) {
  15978. parsed.type = 'video';
  15979. result.video.push(parsed);
  15980. endLoop = true;
  15981. }
  15982. }
  15983. if (!result.firstKeyFrame) {
  15984. if (pusi) {
  15985. if (currentFrame.size !== 0) {
  15986. frame = new Uint8Array(currentFrame.size);
  15987. i = 0;
  15988. while (currentFrame.data.length) {
  15989. pes = currentFrame.data.shift();
  15990. frame.set(pes, i);
  15991. i += pes.byteLength;
  15992. }
  15993. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  15994. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  15995. // the keyframe seems to work fine with HLS playback
  15996. // and definitely preferable to a crash with TypeError...
  15997. if (firstKeyFrame) {
  15998. result.firstKeyFrame = firstKeyFrame;
  15999. result.firstKeyFrame.type = 'video';
  16000. } else {
  16001. // eslint-disable-next-line
  16002. 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.');
  16003. }
  16004. }
  16005. currentFrame.size = 0;
  16006. }
  16007. }
  16008. currentFrame.data.push(packet);
  16009. currentFrame.size += packet.byteLength;
  16010. }
  16011. }
  16012. break;
  16013. }
  16014. if (endLoop && result.firstKeyFrame) {
  16015. break;
  16016. }
  16017. startIndex += MP2T_PACKET_LENGTH;
  16018. endIndex += MP2T_PACKET_LENGTH;
  16019. continue;
  16020. } // If we get here, we have somehow become de-synchronized and we need to step
  16021. // forward one byte at a time until we find a pair of sync bytes that denote
  16022. // a packet
  16023. startIndex++;
  16024. endIndex++;
  16025. } // Start walking from end of segment to get last video packet
  16026. endIndex = bytes.byteLength;
  16027. startIndex = endIndex - MP2T_PACKET_LENGTH;
  16028. endLoop = false;
  16029. while (startIndex >= 0) {
  16030. // Look for a pair of start and end sync bytes in the data..
  16031. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  16032. // We found a packet
  16033. packet = bytes.subarray(startIndex, endIndex);
  16034. type = probe.ts.parseType(packet, pmt.pid);
  16035. switch (type) {
  16036. case 'pes':
  16037. pesType = probe.ts.parsePesType(packet, pmt.table);
  16038. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  16039. if (pesType === 'video' && pusi) {
  16040. parsed = probe.ts.parsePesTime(packet);
  16041. if (parsed) {
  16042. parsed.type = 'video';
  16043. result.video.push(parsed);
  16044. endLoop = true;
  16045. }
  16046. }
  16047. break;
  16048. }
  16049. if (endLoop) {
  16050. break;
  16051. }
  16052. startIndex -= MP2T_PACKET_LENGTH;
  16053. endIndex -= MP2T_PACKET_LENGTH;
  16054. continue;
  16055. } // If we get here, we have somehow become de-synchronized and we need to step
  16056. // forward one byte at a time until we find a pair of sync bytes that denote
  16057. // a packet
  16058. startIndex--;
  16059. endIndex--;
  16060. }
  16061. };
  16062. /**
  16063. * Adjusts the timestamp information for the segment to account for
  16064. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  16065. */
  16066. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  16067. if (segmentInfo.audio && segmentInfo.audio.length) {
  16068. var audioBaseTimestamp = baseTimestamp;
  16069. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  16070. audioBaseTimestamp = segmentInfo.audio[0].dts;
  16071. }
  16072. segmentInfo.audio.forEach(function (info) {
  16073. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  16074. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  16075. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  16076. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  16077. });
  16078. }
  16079. if (segmentInfo.video && segmentInfo.video.length) {
  16080. var videoBaseTimestamp = baseTimestamp;
  16081. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  16082. videoBaseTimestamp = segmentInfo.video[0].dts;
  16083. }
  16084. segmentInfo.video.forEach(function (info) {
  16085. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  16086. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  16087. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  16088. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  16089. });
  16090. if (segmentInfo.firstKeyFrame) {
  16091. var frame = segmentInfo.firstKeyFrame;
  16092. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  16093. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  16094. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  16095. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  16096. }
  16097. }
  16098. };
  16099. /**
  16100. * inspects the aac data stream for start and end time information
  16101. */
  16102. var inspectAac_ = function (bytes) {
  16103. var endLoop = false,
  16104. audioCount = 0,
  16105. sampleRate = null,
  16106. timestamp = null,
  16107. frameSize = 0,
  16108. byteIndex = 0,
  16109. packet;
  16110. while (bytes.length - byteIndex >= 3) {
  16111. var type = probe.aac.parseType(bytes, byteIndex);
  16112. switch (type) {
  16113. case 'timed-metadata':
  16114. // Exit early because we don't have enough to parse
  16115. // the ID3 tag header
  16116. if (bytes.length - byteIndex < 10) {
  16117. endLoop = true;
  16118. break;
  16119. }
  16120. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  16121. // to emit a full packet
  16122. if (frameSize > bytes.length) {
  16123. endLoop = true;
  16124. break;
  16125. }
  16126. if (timestamp === null) {
  16127. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  16128. timestamp = probe.aac.parseAacTimestamp(packet);
  16129. }
  16130. byteIndex += frameSize;
  16131. break;
  16132. case 'audio':
  16133. // Exit early because we don't have enough to parse
  16134. // the ADTS frame header
  16135. if (bytes.length - byteIndex < 7) {
  16136. endLoop = true;
  16137. break;
  16138. }
  16139. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  16140. // to emit a full packet
  16141. if (frameSize > bytes.length) {
  16142. endLoop = true;
  16143. break;
  16144. }
  16145. if (sampleRate === null) {
  16146. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  16147. sampleRate = probe.aac.parseSampleRate(packet);
  16148. }
  16149. audioCount++;
  16150. byteIndex += frameSize;
  16151. break;
  16152. default:
  16153. byteIndex++;
  16154. break;
  16155. }
  16156. if (endLoop) {
  16157. return null;
  16158. }
  16159. }
  16160. if (sampleRate === null || timestamp === null) {
  16161. return null;
  16162. }
  16163. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  16164. var result = {
  16165. audio: [{
  16166. type: 'audio',
  16167. dts: timestamp,
  16168. pts: timestamp
  16169. }, {
  16170. type: 'audio',
  16171. dts: timestamp + audioCount * 1024 * audioTimescale,
  16172. pts: timestamp + audioCount * 1024 * audioTimescale
  16173. }]
  16174. };
  16175. return result;
  16176. };
  16177. /**
  16178. * inspects the transport stream segment data for start and end time information
  16179. * of the audio and video tracks (when present) as well as the first key frame's
  16180. * start time.
  16181. */
  16182. var inspectTs_ = function (bytes) {
  16183. var pmt = {
  16184. pid: null,
  16185. table: null
  16186. };
  16187. var result = {};
  16188. parsePsi_(bytes, pmt);
  16189. for (var pid in pmt.table) {
  16190. if (pmt.table.hasOwnProperty(pid)) {
  16191. var type = pmt.table[pid];
  16192. switch (type) {
  16193. case StreamTypes.H264_STREAM_TYPE:
  16194. result.video = [];
  16195. parseVideoPes_(bytes, pmt, result);
  16196. if (result.video.length === 0) {
  16197. delete result.video;
  16198. }
  16199. break;
  16200. case StreamTypes.ADTS_STREAM_TYPE:
  16201. result.audio = [];
  16202. parseAudioPes_(bytes, pmt, result);
  16203. if (result.audio.length === 0) {
  16204. delete result.audio;
  16205. }
  16206. break;
  16207. }
  16208. }
  16209. }
  16210. return result;
  16211. };
  16212. /**
  16213. * Inspects segment byte data and returns an object with start and end timing information
  16214. *
  16215. * @param {Uint8Array} bytes The segment byte data
  16216. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  16217. * timestamps for rollover. This value must be in 90khz clock.
  16218. * @return {Object} Object containing start and end frame timing info of segment.
  16219. */
  16220. var inspect = function (bytes, baseTimestamp) {
  16221. var isAacData = probe.aac.isLikelyAacData(bytes);
  16222. var result;
  16223. if (isAacData) {
  16224. result = inspectAac_(bytes);
  16225. } else {
  16226. result = inspectTs_(bytes);
  16227. }
  16228. if (!result || !result.audio && !result.video) {
  16229. return null;
  16230. }
  16231. adjustTimestamp_(result, baseTimestamp);
  16232. return result;
  16233. };
  16234. var tsInspector = {
  16235. inspect: inspect,
  16236. parseAudioPes_: parseAudioPes_
  16237. };
  16238. /* global self */
  16239. /**
  16240. * Re-emits transmuxer events by converting them into messages to the
  16241. * world outside the worker.
  16242. *
  16243. * @param {Object} transmuxer the transmuxer to wire events on
  16244. * @private
  16245. */
  16246. const wireTransmuxerEvents = function (self, transmuxer) {
  16247. transmuxer.on('data', function (segment) {
  16248. // transfer ownership of the underlying ArrayBuffer
  16249. // instead of doing a copy to save memory
  16250. // ArrayBuffers are transferable but generic TypedArrays are not
  16251. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  16252. const initArray = segment.initSegment;
  16253. segment.initSegment = {
  16254. data: initArray.buffer,
  16255. byteOffset: initArray.byteOffset,
  16256. byteLength: initArray.byteLength
  16257. };
  16258. const typedArray = segment.data;
  16259. segment.data = typedArray.buffer;
  16260. self.postMessage({
  16261. action: 'data',
  16262. segment,
  16263. byteOffset: typedArray.byteOffset,
  16264. byteLength: typedArray.byteLength
  16265. }, [segment.data]);
  16266. });
  16267. transmuxer.on('done', function (data) {
  16268. self.postMessage({
  16269. action: 'done'
  16270. });
  16271. });
  16272. transmuxer.on('gopInfo', function (gopInfo) {
  16273. self.postMessage({
  16274. action: 'gopInfo',
  16275. gopInfo
  16276. });
  16277. });
  16278. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  16279. const videoSegmentTimingInfo = {
  16280. start: {
  16281. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  16282. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  16283. },
  16284. end: {
  16285. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  16286. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  16287. },
  16288. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  16289. };
  16290. if (timingInfo.prependedContentDuration) {
  16291. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  16292. }
  16293. self.postMessage({
  16294. action: 'videoSegmentTimingInfo',
  16295. videoSegmentTimingInfo
  16296. });
  16297. });
  16298. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  16299. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  16300. const audioSegmentTimingInfo = {
  16301. start: {
  16302. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  16303. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  16304. },
  16305. end: {
  16306. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  16307. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  16308. },
  16309. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  16310. };
  16311. if (timingInfo.prependedContentDuration) {
  16312. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  16313. }
  16314. self.postMessage({
  16315. action: 'audioSegmentTimingInfo',
  16316. audioSegmentTimingInfo
  16317. });
  16318. });
  16319. transmuxer.on('id3Frame', function (id3Frame) {
  16320. self.postMessage({
  16321. action: 'id3Frame',
  16322. id3Frame
  16323. });
  16324. });
  16325. transmuxer.on('caption', function (caption) {
  16326. self.postMessage({
  16327. action: 'caption',
  16328. caption
  16329. });
  16330. });
  16331. transmuxer.on('trackinfo', function (trackInfo) {
  16332. self.postMessage({
  16333. action: 'trackinfo',
  16334. trackInfo
  16335. });
  16336. });
  16337. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  16338. // convert to video TS since we prioritize video time over audio
  16339. self.postMessage({
  16340. action: 'audioTimingInfo',
  16341. audioTimingInfo: {
  16342. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  16343. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  16344. }
  16345. });
  16346. });
  16347. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  16348. self.postMessage({
  16349. action: 'videoTimingInfo',
  16350. videoTimingInfo: {
  16351. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  16352. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  16353. }
  16354. });
  16355. });
  16356. transmuxer.on('log', function (log) {
  16357. self.postMessage({
  16358. action: 'log',
  16359. log
  16360. });
  16361. });
  16362. };
  16363. /**
  16364. * All incoming messages route through this hash. If no function exists
  16365. * to handle an incoming message, then we ignore the message.
  16366. *
  16367. * @class MessageHandlers
  16368. * @param {Object} options the options to initialize with
  16369. */
  16370. class MessageHandlers {
  16371. constructor(self, options) {
  16372. this.options = options || {};
  16373. this.self = self;
  16374. this.init();
  16375. }
  16376. /**
  16377. * initialize our web worker and wire all the events.
  16378. */
  16379. init() {
  16380. if (this.transmuxer) {
  16381. this.transmuxer.dispose();
  16382. }
  16383. this.transmuxer = new transmuxer.Transmuxer(this.options);
  16384. wireTransmuxerEvents(this.self, this.transmuxer);
  16385. }
  16386. pushMp4Captions(data) {
  16387. if (!this.captionParser) {
  16388. this.captionParser = new captionParser();
  16389. this.captionParser.init();
  16390. }
  16391. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  16392. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  16393. this.self.postMessage({
  16394. action: 'mp4Captions',
  16395. captions: parsed && parsed.captions || [],
  16396. logs: parsed && parsed.logs || [],
  16397. data: segment.buffer
  16398. }, [segment.buffer]);
  16399. }
  16400. probeMp4StartTime({
  16401. timescales,
  16402. data
  16403. }) {
  16404. const startTime = probe$2.startTime(timescales, data);
  16405. this.self.postMessage({
  16406. action: 'probeMp4StartTime',
  16407. startTime,
  16408. data
  16409. }, [data.buffer]);
  16410. }
  16411. probeMp4Tracks({
  16412. data
  16413. }) {
  16414. const tracks = probe$2.tracks(data);
  16415. this.self.postMessage({
  16416. action: 'probeMp4Tracks',
  16417. tracks,
  16418. data
  16419. }, [data.buffer]);
  16420. }
  16421. /**
  16422. * Probes an mp4 segment for EMSG boxes containing ID3 data.
  16423. * https://aomediacodec.github.io/id3-emsg/
  16424. *
  16425. * @param {Uint8Array} data segment data
  16426. * @param {number} offset segment start time
  16427. * @return {Object[]} an array of ID3 frames
  16428. */
  16429. probeEmsgID3({
  16430. data,
  16431. offset
  16432. }) {
  16433. const id3Frames = probe$2.getEmsgID3(data, offset);
  16434. this.self.postMessage({
  16435. action: 'probeEmsgID3',
  16436. id3Frames,
  16437. emsgData: data
  16438. }, [data.buffer]);
  16439. }
  16440. /**
  16441. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  16442. * internal "media time," as well as whether it contains video and/or audio.
  16443. *
  16444. * @private
  16445. * @param {Uint8Array} bytes - segment bytes
  16446. * @param {number} baseStartTime
  16447. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  16448. * This value should be in seconds, as it's converted to a 90khz clock within the
  16449. * function body.
  16450. * @return {Object} The start time of the current segment in "media time" as well as
  16451. * whether it contains video and/or audio
  16452. */
  16453. probeTs({
  16454. data,
  16455. baseStartTime
  16456. }) {
  16457. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  16458. const timeInfo = tsInspector.inspect(data, tsStartTime);
  16459. let result = null;
  16460. if (timeInfo) {
  16461. result = {
  16462. // each type's time info comes back as an array of 2 times, start and end
  16463. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  16464. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  16465. };
  16466. if (result.hasVideo) {
  16467. result.videoStart = timeInfo.video[0].ptsTime;
  16468. }
  16469. if (result.hasAudio) {
  16470. result.audioStart = timeInfo.audio[0].ptsTime;
  16471. }
  16472. }
  16473. this.self.postMessage({
  16474. action: 'probeTs',
  16475. result,
  16476. data
  16477. }, [data.buffer]);
  16478. }
  16479. clearAllMp4Captions() {
  16480. if (this.captionParser) {
  16481. this.captionParser.clearAllCaptions();
  16482. }
  16483. }
  16484. clearParsedMp4Captions() {
  16485. if (this.captionParser) {
  16486. this.captionParser.clearParsedCaptions();
  16487. }
  16488. }
  16489. /**
  16490. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  16491. * processing.
  16492. *
  16493. * @param {ArrayBuffer} data data to push into the muxer
  16494. */
  16495. push(data) {
  16496. // Cast array buffer to correct type for transmuxer
  16497. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  16498. this.transmuxer.push(segment);
  16499. }
  16500. /**
  16501. * Recreate the transmuxer so that the next segment added via `push`
  16502. * start with a fresh transmuxer.
  16503. */
  16504. reset() {
  16505. this.transmuxer.reset();
  16506. }
  16507. /**
  16508. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  16509. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  16510. * set relative to the first based on the PTS values.
  16511. *
  16512. * @param {Object} data used to set the timestamp offset in the muxer
  16513. */
  16514. setTimestampOffset(data) {
  16515. const timestampOffset = data.timestampOffset || 0;
  16516. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  16517. }
  16518. setAudioAppendStart(data) {
  16519. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  16520. }
  16521. setRemux(data) {
  16522. this.transmuxer.setRemux(data.remux);
  16523. }
  16524. /**
  16525. * Forces the pipeline to finish processing the last segment and emit it's
  16526. * results.
  16527. *
  16528. * @param {Object} data event data, not really used
  16529. */
  16530. flush(data) {
  16531. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  16532. self.postMessage({
  16533. action: 'done',
  16534. type: 'transmuxed'
  16535. });
  16536. }
  16537. endTimeline() {
  16538. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  16539. // timelines
  16540. self.postMessage({
  16541. action: 'endedtimeline',
  16542. type: 'transmuxed'
  16543. });
  16544. }
  16545. alignGopsWith(data) {
  16546. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  16547. }
  16548. }
  16549. /**
  16550. * Our web worker interface so that things can talk to mux.js
  16551. * that will be running in a web worker. the scope is passed to this by
  16552. * webworkify.
  16553. *
  16554. * @param {Object} self the scope for the web worker
  16555. */
  16556. self.onmessage = function (event) {
  16557. if (event.data.action === 'init' && event.data.options) {
  16558. this.messageHandlers = new MessageHandlers(self, event.data.options);
  16559. return;
  16560. }
  16561. if (!this.messageHandlers) {
  16562. this.messageHandlers = new MessageHandlers(self);
  16563. }
  16564. if (event.data && event.data.action && event.data.action !== 'init') {
  16565. if (this.messageHandlers[event.data.action]) {
  16566. this.messageHandlers[event.data.action](event.data);
  16567. }
  16568. }
  16569. };
  16570. });
  16571. var TransmuxWorker = factory(workerCode$1);
  16572. /* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
  16573. const handleData_ = (event, transmuxedData, callback) => {
  16574. const {
  16575. type,
  16576. initSegment,
  16577. captions,
  16578. captionStreams,
  16579. metadata,
  16580. videoFrameDtsTime,
  16581. videoFramePtsTime
  16582. } = event.data.segment;
  16583. transmuxedData.buffer.push({
  16584. captions,
  16585. captionStreams,
  16586. metadata
  16587. });
  16588. const boxes = event.data.segment.boxes || {
  16589. data: event.data.segment.data
  16590. };
  16591. const result = {
  16592. type,
  16593. // cast ArrayBuffer to TypedArray
  16594. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  16595. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  16596. };
  16597. if (typeof videoFrameDtsTime !== 'undefined') {
  16598. result.videoFrameDtsTime = videoFrameDtsTime;
  16599. }
  16600. if (typeof videoFramePtsTime !== 'undefined') {
  16601. result.videoFramePtsTime = videoFramePtsTime;
  16602. }
  16603. callback(result);
  16604. };
  16605. const handleDone_ = ({
  16606. transmuxedData,
  16607. callback
  16608. }) => {
  16609. // Previously we only returned data on data events,
  16610. // not on done events. Clear out the buffer to keep that consistent.
  16611. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  16612. // have received
  16613. callback(transmuxedData);
  16614. };
  16615. const handleGopInfo_ = (event, transmuxedData) => {
  16616. transmuxedData.gopInfo = event.data.gopInfo;
  16617. };
  16618. const processTransmux = options => {
  16619. const {
  16620. transmuxer,
  16621. bytes,
  16622. audioAppendStart,
  16623. gopsToAlignWith,
  16624. remux,
  16625. onData,
  16626. onTrackInfo,
  16627. onAudioTimingInfo,
  16628. onVideoTimingInfo,
  16629. onVideoSegmentTimingInfo,
  16630. onAudioSegmentTimingInfo,
  16631. onId3,
  16632. onCaptions,
  16633. onDone,
  16634. onEndedTimeline,
  16635. onTransmuxerLog,
  16636. isEndOfTimeline
  16637. } = options;
  16638. const transmuxedData = {
  16639. buffer: []
  16640. };
  16641. let waitForEndedTimelineEvent = isEndOfTimeline;
  16642. const handleMessage = event => {
  16643. if (transmuxer.currentTransmux !== options) {
  16644. // disposed
  16645. return;
  16646. }
  16647. if (event.data.action === 'data') {
  16648. handleData_(event, transmuxedData, onData);
  16649. }
  16650. if (event.data.action === 'trackinfo') {
  16651. onTrackInfo(event.data.trackInfo);
  16652. }
  16653. if (event.data.action === 'gopInfo') {
  16654. handleGopInfo_(event, transmuxedData);
  16655. }
  16656. if (event.data.action === 'audioTimingInfo') {
  16657. onAudioTimingInfo(event.data.audioTimingInfo);
  16658. }
  16659. if (event.data.action === 'videoTimingInfo') {
  16660. onVideoTimingInfo(event.data.videoTimingInfo);
  16661. }
  16662. if (event.data.action === 'videoSegmentTimingInfo') {
  16663. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  16664. }
  16665. if (event.data.action === 'audioSegmentTimingInfo') {
  16666. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  16667. }
  16668. if (event.data.action === 'id3Frame') {
  16669. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  16670. }
  16671. if (event.data.action === 'caption') {
  16672. onCaptions(event.data.caption);
  16673. }
  16674. if (event.data.action === 'endedtimeline') {
  16675. waitForEndedTimelineEvent = false;
  16676. onEndedTimeline();
  16677. }
  16678. if (event.data.action === 'log') {
  16679. onTransmuxerLog(event.data.log);
  16680. } // wait for the transmuxed event since we may have audio and video
  16681. if (event.data.type !== 'transmuxed') {
  16682. return;
  16683. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  16684. // of a timeline, that means there may still be data events before the segment
  16685. // processing can be considerred complete. In that case, the final event should be
  16686. // an "endedtimeline" event with the type "transmuxed."
  16687. if (waitForEndedTimelineEvent) {
  16688. return;
  16689. }
  16690. transmuxer.onmessage = null;
  16691. handleDone_({
  16692. transmuxedData,
  16693. callback: onDone
  16694. });
  16695. /* eslint-disable no-use-before-define */
  16696. dequeue(transmuxer);
  16697. /* eslint-enable */
  16698. };
  16699. transmuxer.onmessage = handleMessage;
  16700. if (audioAppendStart) {
  16701. transmuxer.postMessage({
  16702. action: 'setAudioAppendStart',
  16703. appendStart: audioAppendStart
  16704. });
  16705. } // allow empty arrays to be passed to clear out GOPs
  16706. if (Array.isArray(gopsToAlignWith)) {
  16707. transmuxer.postMessage({
  16708. action: 'alignGopsWith',
  16709. gopsToAlignWith
  16710. });
  16711. }
  16712. if (typeof remux !== 'undefined') {
  16713. transmuxer.postMessage({
  16714. action: 'setRemux',
  16715. remux
  16716. });
  16717. }
  16718. if (bytes.byteLength) {
  16719. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  16720. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  16721. transmuxer.postMessage({
  16722. action: 'push',
  16723. // Send the typed-array of data as an ArrayBuffer so that
  16724. // it can be sent as a "Transferable" and avoid the costly
  16725. // memory copy
  16726. data: buffer,
  16727. // To recreate the original typed-array, we need information
  16728. // about what portion of the ArrayBuffer it was a view into
  16729. byteOffset,
  16730. byteLength: bytes.byteLength
  16731. }, [buffer]);
  16732. }
  16733. if (isEndOfTimeline) {
  16734. transmuxer.postMessage({
  16735. action: 'endTimeline'
  16736. });
  16737. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  16738. // the end of the segment
  16739. transmuxer.postMessage({
  16740. action: 'flush'
  16741. });
  16742. };
  16743. const dequeue = transmuxer => {
  16744. transmuxer.currentTransmux = null;
  16745. if (transmuxer.transmuxQueue.length) {
  16746. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  16747. if (typeof transmuxer.currentTransmux === 'function') {
  16748. transmuxer.currentTransmux();
  16749. } else {
  16750. processTransmux(transmuxer.currentTransmux);
  16751. }
  16752. }
  16753. };
  16754. const processAction = (transmuxer, action) => {
  16755. transmuxer.postMessage({
  16756. action
  16757. });
  16758. dequeue(transmuxer);
  16759. };
  16760. const enqueueAction = (action, transmuxer) => {
  16761. if (!transmuxer.currentTransmux) {
  16762. transmuxer.currentTransmux = action;
  16763. processAction(transmuxer, action);
  16764. return;
  16765. }
  16766. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  16767. };
  16768. const reset = transmuxer => {
  16769. enqueueAction('reset', transmuxer);
  16770. };
  16771. const endTimeline = transmuxer => {
  16772. enqueueAction('endTimeline', transmuxer);
  16773. };
  16774. const transmux = options => {
  16775. if (!options.transmuxer.currentTransmux) {
  16776. options.transmuxer.currentTransmux = options;
  16777. processTransmux(options);
  16778. return;
  16779. }
  16780. options.transmuxer.transmuxQueue.push(options);
  16781. };
  16782. const createTransmuxer = options => {
  16783. const transmuxer = new TransmuxWorker();
  16784. transmuxer.currentTransmux = null;
  16785. transmuxer.transmuxQueue = [];
  16786. const term = transmuxer.terminate;
  16787. transmuxer.terminate = () => {
  16788. transmuxer.currentTransmux = null;
  16789. transmuxer.transmuxQueue.length = 0;
  16790. return term.call(transmuxer);
  16791. };
  16792. transmuxer.postMessage({
  16793. action: 'init',
  16794. options
  16795. });
  16796. return transmuxer;
  16797. };
  16798. var segmentTransmuxer = {
  16799. reset,
  16800. endTimeline,
  16801. transmux,
  16802. createTransmuxer
  16803. };
  16804. const workerCallback = function (options) {
  16805. const transmuxer = options.transmuxer;
  16806. const endAction = options.endAction || options.action;
  16807. const callback = options.callback;
  16808. const message = _extends({}, options, {
  16809. endAction: null,
  16810. transmuxer: null,
  16811. callback: null
  16812. });
  16813. const listenForEndEvent = event => {
  16814. if (event.data.action !== endAction) {
  16815. return;
  16816. }
  16817. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  16818. if (event.data.data) {
  16819. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  16820. if (options.data) {
  16821. options.data = event.data.data;
  16822. }
  16823. }
  16824. callback(event.data);
  16825. };
  16826. transmuxer.addEventListener('message', listenForEndEvent);
  16827. if (options.data) {
  16828. const isArrayBuffer = options.data instanceof ArrayBuffer;
  16829. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  16830. message.byteLength = options.data.byteLength;
  16831. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  16832. transmuxer.postMessage(message, transfers);
  16833. } else {
  16834. transmuxer.postMessage(message);
  16835. }
  16836. };
  16837. const REQUEST_ERRORS = {
  16838. FAILURE: 2,
  16839. TIMEOUT: -101,
  16840. ABORTED: -102
  16841. };
  16842. /**
  16843. * Abort all requests
  16844. *
  16845. * @param {Object} activeXhrs - an object that tracks all XHR requests
  16846. */
  16847. const abortAll = activeXhrs => {
  16848. activeXhrs.forEach(xhr => {
  16849. xhr.abort();
  16850. });
  16851. };
  16852. /**
  16853. * Gather important bandwidth stats once a request has completed
  16854. *
  16855. * @param {Object} request - the XHR request from which to gather stats
  16856. */
  16857. const getRequestStats = request => {
  16858. return {
  16859. bandwidth: request.bandwidth,
  16860. bytesReceived: request.bytesReceived || 0,
  16861. roundTripTime: request.roundTripTime || 0
  16862. };
  16863. };
  16864. /**
  16865. * If possible gather bandwidth stats as a request is in
  16866. * progress
  16867. *
  16868. * @param {Event} progressEvent - an event object from an XHR's progress event
  16869. */
  16870. const getProgressStats = progressEvent => {
  16871. const request = progressEvent.target;
  16872. const roundTripTime = Date.now() - request.requestTime;
  16873. const stats = {
  16874. bandwidth: Infinity,
  16875. bytesReceived: 0,
  16876. roundTripTime: roundTripTime || 0
  16877. };
  16878. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  16879. // because we should only use bandwidth stats on progress to determine when
  16880. // abort a request early due to insufficient bandwidth
  16881. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  16882. return stats;
  16883. };
  16884. /**
  16885. * Handle all error conditions in one place and return an object
  16886. * with all the information
  16887. *
  16888. * @param {Error|null} error - if non-null signals an error occured with the XHR
  16889. * @param {Object} request - the XHR request that possibly generated the error
  16890. */
  16891. const handleErrors = (error, request) => {
  16892. if (request.timedout) {
  16893. return {
  16894. status: request.status,
  16895. message: 'HLS request timed-out at URL: ' + request.uri,
  16896. code: REQUEST_ERRORS.TIMEOUT,
  16897. xhr: request
  16898. };
  16899. }
  16900. if (request.aborted) {
  16901. return {
  16902. status: request.status,
  16903. message: 'HLS request aborted at URL: ' + request.uri,
  16904. code: REQUEST_ERRORS.ABORTED,
  16905. xhr: request
  16906. };
  16907. }
  16908. if (error) {
  16909. return {
  16910. status: request.status,
  16911. message: 'HLS request errored at URL: ' + request.uri,
  16912. code: REQUEST_ERRORS.FAILURE,
  16913. xhr: request
  16914. };
  16915. }
  16916. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  16917. return {
  16918. status: request.status,
  16919. message: 'Empty HLS response at URL: ' + request.uri,
  16920. code: REQUEST_ERRORS.FAILURE,
  16921. xhr: request
  16922. };
  16923. }
  16924. return null;
  16925. };
  16926. /**
  16927. * Handle responses for key data and convert the key data to the correct format
  16928. * for the decryption step later
  16929. *
  16930. * @param {Object} segment - a simplified copy of the segmentInfo object
  16931. * from SegmentLoader
  16932. * @param {Array} objects - objects to add the key bytes to.
  16933. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16934. * this request
  16935. */
  16936. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  16937. const response = request.response;
  16938. const errorObj = handleErrors(error, request);
  16939. if (errorObj) {
  16940. return finishProcessingFn(errorObj, segment);
  16941. }
  16942. if (response.byteLength !== 16) {
  16943. return finishProcessingFn({
  16944. status: request.status,
  16945. message: 'Invalid HLS key at URL: ' + request.uri,
  16946. code: REQUEST_ERRORS.FAILURE,
  16947. xhr: request
  16948. }, segment);
  16949. }
  16950. const view = new DataView(response);
  16951. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  16952. for (let i = 0; i < objects.length; i++) {
  16953. objects[i].bytes = bytes;
  16954. }
  16955. return finishProcessingFn(null, segment);
  16956. };
  16957. const parseInitSegment = (segment, callback) => {
  16958. const type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  16959. // only know how to parse mp4 init segments at the moment
  16960. if (type !== 'mp4') {
  16961. const uri = segment.map.resolvedUri || segment.map.uri;
  16962. return callback({
  16963. internal: true,
  16964. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  16965. code: REQUEST_ERRORS.FAILURE
  16966. });
  16967. }
  16968. workerCallback({
  16969. action: 'probeMp4Tracks',
  16970. data: segment.map.bytes,
  16971. transmuxer: segment.transmuxer,
  16972. callback: ({
  16973. tracks,
  16974. data
  16975. }) => {
  16976. // transfer bytes back to us
  16977. segment.map.bytes = data;
  16978. tracks.forEach(function (track) {
  16979. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  16980. if (segment.map.tracks[track.type]) {
  16981. return;
  16982. }
  16983. segment.map.tracks[track.type] = track;
  16984. if (typeof track.id === 'number' && track.timescale) {
  16985. segment.map.timescales = segment.map.timescales || {};
  16986. segment.map.timescales[track.id] = track.timescale;
  16987. }
  16988. });
  16989. return callback(null);
  16990. }
  16991. });
  16992. };
  16993. /**
  16994. * Handle init-segment responses
  16995. *
  16996. * @param {Object} segment - a simplified copy of the segmentInfo object
  16997. * from SegmentLoader
  16998. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  16999. * this request
  17000. */
  17001. const handleInitSegmentResponse = ({
  17002. segment,
  17003. finishProcessingFn
  17004. }) => (error, request) => {
  17005. const errorObj = handleErrors(error, request);
  17006. if (errorObj) {
  17007. return finishProcessingFn(errorObj, segment);
  17008. }
  17009. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  17010. // until the key request is done to decrypt.
  17011. if (segment.map.key) {
  17012. segment.map.encryptedBytes = bytes;
  17013. return finishProcessingFn(null, segment);
  17014. }
  17015. segment.map.bytes = bytes;
  17016. parseInitSegment(segment, function (parseError) {
  17017. if (parseError) {
  17018. parseError.xhr = request;
  17019. parseError.status = request.status;
  17020. return finishProcessingFn(parseError, segment);
  17021. }
  17022. finishProcessingFn(null, segment);
  17023. });
  17024. };
  17025. /**
  17026. * Response handler for segment-requests being sure to set the correct
  17027. * property depending on whether the segment is encryped or not
  17028. * Also records and keeps track of stats that are used for ABR purposes
  17029. *
  17030. * @param {Object} segment - a simplified copy of the segmentInfo object
  17031. * from SegmentLoader
  17032. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  17033. * this request
  17034. */
  17035. const handleSegmentResponse = ({
  17036. segment,
  17037. finishProcessingFn,
  17038. responseType
  17039. }) => (error, request) => {
  17040. const errorObj = handleErrors(error, request);
  17041. if (errorObj) {
  17042. return finishProcessingFn(errorObj, segment);
  17043. }
  17044. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  17045. // thrown for two primary cases:
  17046. // 1. the mime type override stops working, or is not implemented for a specific
  17047. // browser
  17048. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  17049. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  17050. segment.stats = getRequestStats(request);
  17051. if (segment.key) {
  17052. segment.encryptedBytes = new Uint8Array(newBytes);
  17053. } else {
  17054. segment.bytes = new Uint8Array(newBytes);
  17055. }
  17056. return finishProcessingFn(null, segment);
  17057. };
  17058. const transmuxAndNotify = ({
  17059. segment,
  17060. bytes,
  17061. trackInfoFn,
  17062. timingInfoFn,
  17063. videoSegmentTimingInfoFn,
  17064. audioSegmentTimingInfoFn,
  17065. id3Fn,
  17066. captionsFn,
  17067. isEndOfTimeline,
  17068. endedTimelineFn,
  17069. dataFn,
  17070. doneFn,
  17071. onTransmuxerLog
  17072. }) => {
  17073. const fmp4Tracks = segment.map && segment.map.tracks || {};
  17074. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  17075. // One reason for this is that in the case of full segments, we want to trust start
  17076. // times from the probe, rather than the transmuxer.
  17077. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  17078. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  17079. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  17080. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  17081. const finish = () => transmux({
  17082. bytes,
  17083. transmuxer: segment.transmuxer,
  17084. audioAppendStart: segment.audioAppendStart,
  17085. gopsToAlignWith: segment.gopsToAlignWith,
  17086. remux: isMuxed,
  17087. onData: result => {
  17088. result.type = result.type === 'combined' ? 'video' : result.type;
  17089. dataFn(segment, result);
  17090. },
  17091. onTrackInfo: trackInfo => {
  17092. if (trackInfoFn) {
  17093. if (isMuxed) {
  17094. trackInfo.isMuxed = true;
  17095. }
  17096. trackInfoFn(segment, trackInfo);
  17097. }
  17098. },
  17099. onAudioTimingInfo: audioTimingInfo => {
  17100. // we only want the first start value we encounter
  17101. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  17102. audioStartFn(audioTimingInfo.start);
  17103. audioStartFn = null;
  17104. } // we want to continually update the end time
  17105. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  17106. audioEndFn(audioTimingInfo.end);
  17107. }
  17108. },
  17109. onVideoTimingInfo: videoTimingInfo => {
  17110. // we only want the first start value we encounter
  17111. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  17112. videoStartFn(videoTimingInfo.start);
  17113. videoStartFn = null;
  17114. } // we want to continually update the end time
  17115. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  17116. videoEndFn(videoTimingInfo.end);
  17117. }
  17118. },
  17119. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  17120. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  17121. },
  17122. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  17123. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  17124. },
  17125. onId3: (id3Frames, dispatchType) => {
  17126. id3Fn(segment, id3Frames, dispatchType);
  17127. },
  17128. onCaptions: captions => {
  17129. captionsFn(segment, [captions]);
  17130. },
  17131. isEndOfTimeline,
  17132. onEndedTimeline: () => {
  17133. endedTimelineFn();
  17134. },
  17135. onTransmuxerLog,
  17136. onDone: result => {
  17137. if (!doneFn) {
  17138. return;
  17139. }
  17140. result.type = result.type === 'combined' ? 'video' : result.type;
  17141. doneFn(null, segment, result);
  17142. }
  17143. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  17144. // Meaning cached frame data may corrupt our notion of where this segment
  17145. // really starts. To get around this, probe for the info needed.
  17146. workerCallback({
  17147. action: 'probeTs',
  17148. transmuxer: segment.transmuxer,
  17149. data: bytes,
  17150. baseStartTime: segment.baseStartTime,
  17151. callback: data => {
  17152. segment.bytes = bytes = data.data;
  17153. const probeResult = data.result;
  17154. if (probeResult) {
  17155. trackInfoFn(segment, {
  17156. hasAudio: probeResult.hasAudio,
  17157. hasVideo: probeResult.hasVideo,
  17158. isMuxed
  17159. });
  17160. trackInfoFn = null;
  17161. }
  17162. finish();
  17163. }
  17164. });
  17165. };
  17166. const handleSegmentBytes = ({
  17167. segment,
  17168. bytes,
  17169. trackInfoFn,
  17170. timingInfoFn,
  17171. videoSegmentTimingInfoFn,
  17172. audioSegmentTimingInfoFn,
  17173. id3Fn,
  17174. captionsFn,
  17175. isEndOfTimeline,
  17176. endedTimelineFn,
  17177. dataFn,
  17178. doneFn,
  17179. onTransmuxerLog
  17180. }) => {
  17181. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  17182. // We should have a handler that fetches the number of bytes required
  17183. // to check if something is fmp4. This will allow us to save bandwidth
  17184. // because we can only exclude a playlist and abort requests
  17185. // by codec after trackinfo triggers.
  17186. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  17187. segment.isFmp4 = true;
  17188. const {
  17189. tracks
  17190. } = segment.map;
  17191. const trackInfo = {
  17192. isFmp4: true,
  17193. hasVideo: !!tracks.video,
  17194. hasAudio: !!tracks.audio
  17195. }; // if we have a audio track, with a codec that is not set to
  17196. // encrypted audio
  17197. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  17198. trackInfo.audioCodec = tracks.audio.codec;
  17199. } // if we have a video track, with a codec that is not set to
  17200. // encrypted video
  17201. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  17202. trackInfo.videoCodec = tracks.video.codec;
  17203. }
  17204. if (tracks.video && tracks.audio) {
  17205. trackInfo.isMuxed = true;
  17206. } // since we don't support appending fmp4 data on progress, we know we have the full
  17207. // segment here
  17208. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  17209. // time. The end time can be roughly calculated by the receiver using the duration.
  17210. //
  17211. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  17212. // that is the true start of the segment (where the playback engine should begin
  17213. // decoding).
  17214. const finishLoading = (captions, id3Frames) => {
  17215. // if the track still has audio at this point it is only possible
  17216. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  17217. // above.
  17218. // we make sure to use segment.bytes here as that
  17219. dataFn(segment, {
  17220. data: bytesAsUint8Array,
  17221. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  17222. });
  17223. if (id3Frames && id3Frames.length) {
  17224. id3Fn(segment, id3Frames);
  17225. }
  17226. if (captions && captions.length) {
  17227. captionsFn(segment, captions);
  17228. }
  17229. doneFn(null, segment, {});
  17230. };
  17231. workerCallback({
  17232. action: 'probeMp4StartTime',
  17233. timescales: segment.map.timescales,
  17234. data: bytesAsUint8Array,
  17235. transmuxer: segment.transmuxer,
  17236. callback: ({
  17237. data,
  17238. startTime
  17239. }) => {
  17240. // transfer bytes back to us
  17241. bytes = data.buffer;
  17242. segment.bytes = bytesAsUint8Array = data;
  17243. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  17244. timingInfoFn(segment, 'audio', 'start', startTime);
  17245. }
  17246. if (trackInfo.hasVideo) {
  17247. timingInfoFn(segment, 'video', 'start', startTime);
  17248. }
  17249. workerCallback({
  17250. action: 'probeEmsgID3',
  17251. data: bytesAsUint8Array,
  17252. transmuxer: segment.transmuxer,
  17253. offset: startTime,
  17254. callback: ({
  17255. emsgData,
  17256. id3Frames
  17257. }) => {
  17258. // transfer bytes back to us
  17259. bytes = emsgData.buffer;
  17260. segment.bytes = bytesAsUint8Array = emsgData; // Run through the CaptionParser in case there are captions.
  17261. // Initialize CaptionParser if it hasn't been yet
  17262. if (!tracks.video || !emsgData.byteLength || !segment.transmuxer) {
  17263. finishLoading(undefined, id3Frames);
  17264. return;
  17265. }
  17266. workerCallback({
  17267. action: 'pushMp4Captions',
  17268. endAction: 'mp4Captions',
  17269. transmuxer: segment.transmuxer,
  17270. data: bytesAsUint8Array,
  17271. timescales: segment.map.timescales,
  17272. trackIds: [tracks.video.id],
  17273. callback: message => {
  17274. // transfer bytes back to us
  17275. bytes = message.data.buffer;
  17276. segment.bytes = bytesAsUint8Array = message.data;
  17277. message.logs.forEach(function (log) {
  17278. onTransmuxerLog(merge$1(log, {
  17279. stream: 'mp4CaptionParser'
  17280. }));
  17281. });
  17282. finishLoading(message.captions, id3Frames);
  17283. }
  17284. });
  17285. }
  17286. });
  17287. }
  17288. });
  17289. return;
  17290. } // VTT or other segments that don't need processing
  17291. if (!segment.transmuxer) {
  17292. doneFn(null, segment, {});
  17293. return;
  17294. }
  17295. if (typeof segment.container === 'undefined') {
  17296. segment.container = detectContainerForBytes(bytesAsUint8Array);
  17297. }
  17298. if (segment.container !== 'ts' && segment.container !== 'aac') {
  17299. trackInfoFn(segment, {
  17300. hasAudio: false,
  17301. hasVideo: false
  17302. });
  17303. doneFn(null, segment, {});
  17304. return;
  17305. } // ts or aac
  17306. transmuxAndNotify({
  17307. segment,
  17308. bytes,
  17309. trackInfoFn,
  17310. timingInfoFn,
  17311. videoSegmentTimingInfoFn,
  17312. audioSegmentTimingInfoFn,
  17313. id3Fn,
  17314. captionsFn,
  17315. isEndOfTimeline,
  17316. endedTimelineFn,
  17317. dataFn,
  17318. doneFn,
  17319. onTransmuxerLog
  17320. });
  17321. };
  17322. const decrypt = function ({
  17323. id,
  17324. key,
  17325. encryptedBytes,
  17326. decryptionWorker
  17327. }, callback) {
  17328. const decryptionHandler = event => {
  17329. if (event.data.source === id) {
  17330. decryptionWorker.removeEventListener('message', decryptionHandler);
  17331. const decrypted = event.data.decrypted;
  17332. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  17333. }
  17334. };
  17335. decryptionWorker.addEventListener('message', decryptionHandler);
  17336. let keyBytes;
  17337. if (key.bytes.slice) {
  17338. keyBytes = key.bytes.slice();
  17339. } else {
  17340. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  17341. } // incrementally decrypt the bytes
  17342. decryptionWorker.postMessage(createTransferableMessage({
  17343. source: id,
  17344. encrypted: encryptedBytes,
  17345. key: keyBytes,
  17346. iv: key.iv
  17347. }), [encryptedBytes.buffer, keyBytes.buffer]);
  17348. };
  17349. /**
  17350. * Decrypt the segment via the decryption web worker
  17351. *
  17352. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  17353. * routines
  17354. * @param {Object} segment - a simplified copy of the segmentInfo object
  17355. * from SegmentLoader
  17356. * @param {Function} trackInfoFn - a callback that receives track info
  17357. * @param {Function} timingInfoFn - a callback that receives timing info
  17358. * @param {Function} videoSegmentTimingInfoFn
  17359. * a callback that receives video timing info based on media times and
  17360. * any adjustments made by the transmuxer
  17361. * @param {Function} audioSegmentTimingInfoFn
  17362. * a callback that receives audio timing info based on media times and
  17363. * any adjustments made by the transmuxer
  17364. * @param {boolean} isEndOfTimeline
  17365. * true if this segment represents the last segment in a timeline
  17366. * @param {Function} endedTimelineFn
  17367. * a callback made when a timeline is ended, will only be called if
  17368. * isEndOfTimeline is true
  17369. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  17370. * and ready to use
  17371. * @param {Function} doneFn - a callback that is executed after decryption has completed
  17372. */
  17373. const decryptSegment = ({
  17374. decryptionWorker,
  17375. segment,
  17376. trackInfoFn,
  17377. timingInfoFn,
  17378. videoSegmentTimingInfoFn,
  17379. audioSegmentTimingInfoFn,
  17380. id3Fn,
  17381. captionsFn,
  17382. isEndOfTimeline,
  17383. endedTimelineFn,
  17384. dataFn,
  17385. doneFn,
  17386. onTransmuxerLog
  17387. }) => {
  17388. decrypt({
  17389. id: segment.requestId,
  17390. key: segment.key,
  17391. encryptedBytes: segment.encryptedBytes,
  17392. decryptionWorker
  17393. }, decryptedBytes => {
  17394. segment.bytes = decryptedBytes;
  17395. handleSegmentBytes({
  17396. segment,
  17397. bytes: segment.bytes,
  17398. trackInfoFn,
  17399. timingInfoFn,
  17400. videoSegmentTimingInfoFn,
  17401. audioSegmentTimingInfoFn,
  17402. id3Fn,
  17403. captionsFn,
  17404. isEndOfTimeline,
  17405. endedTimelineFn,
  17406. dataFn,
  17407. doneFn,
  17408. onTransmuxerLog
  17409. });
  17410. });
  17411. };
  17412. /**
  17413. * This function waits for all XHRs to finish (with either success or failure)
  17414. * before continueing processing via it's callback. The function gathers errors
  17415. * from each request into a single errors array so that the error status for
  17416. * each request can be examined later.
  17417. *
  17418. * @param {Object} activeXhrs - an object that tracks all XHR requests
  17419. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  17420. * routines
  17421. * @param {Function} trackInfoFn - a callback that receives track info
  17422. * @param {Function} timingInfoFn - a callback that receives timing info
  17423. * @param {Function} videoSegmentTimingInfoFn
  17424. * a callback that receives video timing info based on media times and
  17425. * any adjustments made by the transmuxer
  17426. * @param {Function} audioSegmentTimingInfoFn
  17427. * a callback that receives audio timing info based on media times and
  17428. * any adjustments made by the transmuxer
  17429. * @param {Function} id3Fn - a callback that receives ID3 metadata
  17430. * @param {Function} captionsFn - a callback that receives captions
  17431. * @param {boolean} isEndOfTimeline
  17432. * true if this segment represents the last segment in a timeline
  17433. * @param {Function} endedTimelineFn
  17434. * a callback made when a timeline is ended, will only be called if
  17435. * isEndOfTimeline is true
  17436. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  17437. * and ready to use
  17438. * @param {Function} doneFn - a callback that is executed after all resources have been
  17439. * downloaded and any decryption completed
  17440. */
  17441. const waitForCompletion = ({
  17442. activeXhrs,
  17443. decryptionWorker,
  17444. trackInfoFn,
  17445. timingInfoFn,
  17446. videoSegmentTimingInfoFn,
  17447. audioSegmentTimingInfoFn,
  17448. id3Fn,
  17449. captionsFn,
  17450. isEndOfTimeline,
  17451. endedTimelineFn,
  17452. dataFn,
  17453. doneFn,
  17454. onTransmuxerLog
  17455. }) => {
  17456. let count = 0;
  17457. let didError = false;
  17458. return (error, segment) => {
  17459. if (didError) {
  17460. return;
  17461. }
  17462. if (error) {
  17463. didError = true; // If there are errors, we have to abort any outstanding requests
  17464. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  17465. // handle the aborted events from those requests, there are some cases where we may
  17466. // never get an aborted event. For instance, if the network connection is lost and
  17467. // there were two requests, the first may have triggered an error immediately, while
  17468. // the second request remains unsent. In that case, the aborted algorithm will not
  17469. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  17470. //
  17471. // We also can't rely on the ready state of the XHR, since the request that
  17472. // triggered the connection error may also show as a ready state of 0 (unsent).
  17473. // Therefore, we have to finish this group of requests immediately after the first
  17474. // seen error.
  17475. return doneFn(error, segment);
  17476. }
  17477. count += 1;
  17478. if (count === activeXhrs.length) {
  17479. const segmentFinish = function () {
  17480. if (segment.encryptedBytes) {
  17481. return decryptSegment({
  17482. decryptionWorker,
  17483. segment,
  17484. trackInfoFn,
  17485. timingInfoFn,
  17486. videoSegmentTimingInfoFn,
  17487. audioSegmentTimingInfoFn,
  17488. id3Fn,
  17489. captionsFn,
  17490. isEndOfTimeline,
  17491. endedTimelineFn,
  17492. dataFn,
  17493. doneFn,
  17494. onTransmuxerLog
  17495. });
  17496. } // Otherwise, everything is ready just continue
  17497. handleSegmentBytes({
  17498. segment,
  17499. bytes: segment.bytes,
  17500. trackInfoFn,
  17501. timingInfoFn,
  17502. videoSegmentTimingInfoFn,
  17503. audioSegmentTimingInfoFn,
  17504. id3Fn,
  17505. captionsFn,
  17506. isEndOfTimeline,
  17507. endedTimelineFn,
  17508. dataFn,
  17509. doneFn,
  17510. onTransmuxerLog
  17511. });
  17512. }; // Keep track of when *all* of the requests have completed
  17513. segment.endOfAllRequests = Date.now();
  17514. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  17515. return decrypt({
  17516. decryptionWorker,
  17517. // add -init to the "id" to differentiate between segment
  17518. // and init segment decryption, just in case they happen
  17519. // at the same time at some point in the future.
  17520. id: segment.requestId + '-init',
  17521. encryptedBytes: segment.map.encryptedBytes,
  17522. key: segment.map.key
  17523. }, decryptedBytes => {
  17524. segment.map.bytes = decryptedBytes;
  17525. parseInitSegment(segment, parseError => {
  17526. if (parseError) {
  17527. abortAll(activeXhrs);
  17528. return doneFn(parseError, segment);
  17529. }
  17530. segmentFinish();
  17531. });
  17532. });
  17533. }
  17534. segmentFinish();
  17535. }
  17536. };
  17537. };
  17538. /**
  17539. * Calls the abort callback if any request within the batch was aborted. Will only call
  17540. * the callback once per batch of requests, even if multiple were aborted.
  17541. *
  17542. * @param {Object} loadendState - state to check to see if the abort function was called
  17543. * @param {Function} abortFn - callback to call for abort
  17544. */
  17545. const handleLoadEnd = ({
  17546. loadendState,
  17547. abortFn
  17548. }) => event => {
  17549. const request = event.target;
  17550. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  17551. abortFn();
  17552. loadendState.calledAbortFn = true;
  17553. }
  17554. };
  17555. /**
  17556. * Simple progress event callback handler that gathers some stats before
  17557. * executing a provided callback with the `segment` object
  17558. *
  17559. * @param {Object} segment - a simplified copy of the segmentInfo object
  17560. * from SegmentLoader
  17561. * @param {Function} progressFn - a callback that is executed each time a progress event
  17562. * is received
  17563. * @param {Function} trackInfoFn - a callback that receives track info
  17564. * @param {Function} timingInfoFn - a callback that receives timing info
  17565. * @param {Function} videoSegmentTimingInfoFn
  17566. * a callback that receives video timing info based on media times and
  17567. * any adjustments made by the transmuxer
  17568. * @param {Function} audioSegmentTimingInfoFn
  17569. * a callback that receives audio timing info based on media times and
  17570. * any adjustments made by the transmuxer
  17571. * @param {boolean} isEndOfTimeline
  17572. * true if this segment represents the last segment in a timeline
  17573. * @param {Function} endedTimelineFn
  17574. * a callback made when a timeline is ended, will only be called if
  17575. * isEndOfTimeline is true
  17576. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  17577. * and ready to use
  17578. * @param {Event} event - the progress event object from XMLHttpRequest
  17579. */
  17580. const handleProgress = ({
  17581. segment,
  17582. progressFn,
  17583. trackInfoFn,
  17584. timingInfoFn,
  17585. videoSegmentTimingInfoFn,
  17586. audioSegmentTimingInfoFn,
  17587. id3Fn,
  17588. captionsFn,
  17589. isEndOfTimeline,
  17590. endedTimelineFn,
  17591. dataFn
  17592. }) => event => {
  17593. const request = event.target;
  17594. if (request.aborted) {
  17595. return;
  17596. }
  17597. segment.stats = merge$1(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  17598. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  17599. segment.stats.firstBytesReceivedAt = Date.now();
  17600. }
  17601. return progressFn(event, segment);
  17602. };
  17603. /**
  17604. * Load all resources and does any processing necessary for a media-segment
  17605. *
  17606. * Features:
  17607. * decrypts the media-segment if it has a key uri and an iv
  17608. * aborts *all* requests if *any* one request fails
  17609. *
  17610. * The segment object, at minimum, has the following format:
  17611. * {
  17612. * resolvedUri: String,
  17613. * [transmuxer]: Object,
  17614. * [byterange]: {
  17615. * offset: Number,
  17616. * length: Number
  17617. * },
  17618. * [key]: {
  17619. * resolvedUri: String
  17620. * [byterange]: {
  17621. * offset: Number,
  17622. * length: Number
  17623. * },
  17624. * iv: {
  17625. * bytes: Uint32Array
  17626. * }
  17627. * },
  17628. * [map]: {
  17629. * resolvedUri: String,
  17630. * [byterange]: {
  17631. * offset: Number,
  17632. * length: Number
  17633. * },
  17634. * [bytes]: Uint8Array
  17635. * }
  17636. * }
  17637. * ...where [name] denotes optional properties
  17638. *
  17639. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  17640. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  17641. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  17642. * decryption routines
  17643. * @param {Object} segment - a simplified copy of the segmentInfo object
  17644. * from SegmentLoader
  17645. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  17646. * aborted
  17647. * @param {Function} progressFn - a callback that receives progress events from the main
  17648. * segment's xhr request
  17649. * @param {Function} trackInfoFn - a callback that receives track info
  17650. * @param {Function} timingInfoFn - a callback that receives timing info
  17651. * @param {Function} videoSegmentTimingInfoFn
  17652. * a callback that receives video timing info based on media times and
  17653. * any adjustments made by the transmuxer
  17654. * @param {Function} audioSegmentTimingInfoFn
  17655. * a callback that receives audio timing info based on media times and
  17656. * any adjustments made by the transmuxer
  17657. * @param {Function} id3Fn - a callback that receives ID3 metadata
  17658. * @param {Function} captionsFn - a callback that receives captions
  17659. * @param {boolean} isEndOfTimeline
  17660. * true if this segment represents the last segment in a timeline
  17661. * @param {Function} endedTimelineFn
  17662. * a callback made when a timeline is ended, will only be called if
  17663. * isEndOfTimeline is true
  17664. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  17665. * request, transmuxed if needed
  17666. * @param {Function} doneFn - a callback that is executed only once all requests have
  17667. * succeeded or failed
  17668. * @return {Function} a function that, when invoked, immediately aborts all
  17669. * outstanding requests
  17670. */
  17671. const mediaSegmentRequest = ({
  17672. xhr,
  17673. xhrOptions,
  17674. decryptionWorker,
  17675. segment,
  17676. abortFn,
  17677. progressFn,
  17678. trackInfoFn,
  17679. timingInfoFn,
  17680. videoSegmentTimingInfoFn,
  17681. audioSegmentTimingInfoFn,
  17682. id3Fn,
  17683. captionsFn,
  17684. isEndOfTimeline,
  17685. endedTimelineFn,
  17686. dataFn,
  17687. doneFn,
  17688. onTransmuxerLog
  17689. }) => {
  17690. const activeXhrs = [];
  17691. const finishProcessingFn = waitForCompletion({
  17692. activeXhrs,
  17693. decryptionWorker,
  17694. trackInfoFn,
  17695. timingInfoFn,
  17696. videoSegmentTimingInfoFn,
  17697. audioSegmentTimingInfoFn,
  17698. id3Fn,
  17699. captionsFn,
  17700. isEndOfTimeline,
  17701. endedTimelineFn,
  17702. dataFn,
  17703. doneFn,
  17704. onTransmuxerLog
  17705. }); // optionally, request the decryption key
  17706. if (segment.key && !segment.key.bytes) {
  17707. const objects = [segment.key];
  17708. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  17709. objects.push(segment.map.key);
  17710. }
  17711. const keyRequestOptions = merge$1(xhrOptions, {
  17712. uri: segment.key.resolvedUri,
  17713. responseType: 'arraybuffer'
  17714. });
  17715. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  17716. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  17717. activeXhrs.push(keyXhr);
  17718. } // optionally, request the associated media init segment
  17719. if (segment.map && !segment.map.bytes) {
  17720. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  17721. if (differentMapKey) {
  17722. const mapKeyRequestOptions = merge$1(xhrOptions, {
  17723. uri: segment.map.key.resolvedUri,
  17724. responseType: 'arraybuffer'
  17725. });
  17726. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  17727. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  17728. activeXhrs.push(mapKeyXhr);
  17729. }
  17730. const initSegmentOptions = merge$1(xhrOptions, {
  17731. uri: segment.map.resolvedUri,
  17732. responseType: 'arraybuffer',
  17733. headers: segmentXhrHeaders(segment.map)
  17734. });
  17735. const initSegmentRequestCallback = handleInitSegmentResponse({
  17736. segment,
  17737. finishProcessingFn
  17738. });
  17739. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  17740. activeXhrs.push(initSegmentXhr);
  17741. }
  17742. const segmentRequestOptions = merge$1(xhrOptions, {
  17743. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  17744. responseType: 'arraybuffer',
  17745. headers: segmentXhrHeaders(segment)
  17746. });
  17747. const segmentRequestCallback = handleSegmentResponse({
  17748. segment,
  17749. finishProcessingFn,
  17750. responseType: segmentRequestOptions.responseType
  17751. });
  17752. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  17753. segmentXhr.addEventListener('progress', handleProgress({
  17754. segment,
  17755. progressFn,
  17756. trackInfoFn,
  17757. timingInfoFn,
  17758. videoSegmentTimingInfoFn,
  17759. audioSegmentTimingInfoFn,
  17760. id3Fn,
  17761. captionsFn,
  17762. isEndOfTimeline,
  17763. endedTimelineFn,
  17764. dataFn
  17765. }));
  17766. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  17767. // multiple times, provide a shared state object
  17768. const loadendState = {};
  17769. activeXhrs.forEach(activeXhr => {
  17770. activeXhr.addEventListener('loadend', handleLoadEnd({
  17771. loadendState,
  17772. abortFn
  17773. }));
  17774. });
  17775. return () => abortAll(activeXhrs);
  17776. };
  17777. /**
  17778. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  17779. * codec strings, or translating codec strings into objects that can be examined.
  17780. */
  17781. const logFn$1 = logger('CodecUtils');
  17782. /**
  17783. * Returns a set of codec strings parsed from the playlist or the default
  17784. * codec strings if no codecs were specified in the playlist
  17785. *
  17786. * @param {Playlist} media the current media playlist
  17787. * @return {Object} an object with the video and audio codecs
  17788. */
  17789. const getCodecs = function (media) {
  17790. // if the codecs were explicitly specified, use them instead of the
  17791. // defaults
  17792. const mediaAttributes = media.attributes || {};
  17793. if (mediaAttributes.CODECS) {
  17794. return parseCodecs(mediaAttributes.CODECS);
  17795. }
  17796. };
  17797. const isMaat = (main, media) => {
  17798. const mediaAttributes = media.attributes || {};
  17799. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  17800. };
  17801. const isMuxed = (main, media) => {
  17802. if (!isMaat(main, media)) {
  17803. return true;
  17804. }
  17805. const mediaAttributes = media.attributes || {};
  17806. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  17807. for (const groupId in audioGroup) {
  17808. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  17809. // or there are listed playlists (the case for DASH, as the manifest will have already
  17810. // provided all of the details necessary to generate the audio playlist, as opposed to
  17811. // HLS' externally requested playlists), then the content is demuxed.
  17812. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  17813. return true;
  17814. }
  17815. }
  17816. return false;
  17817. };
  17818. const unwrapCodecList = function (codecList) {
  17819. const codecs = {};
  17820. codecList.forEach(({
  17821. mediaType,
  17822. type,
  17823. details
  17824. }) => {
  17825. codecs[mediaType] = codecs[mediaType] || [];
  17826. codecs[mediaType].push(translateLegacyCodec(`${type}${details}`));
  17827. });
  17828. Object.keys(codecs).forEach(function (mediaType) {
  17829. if (codecs[mediaType].length > 1) {
  17830. 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.`);
  17831. codecs[mediaType] = null;
  17832. return;
  17833. }
  17834. codecs[mediaType] = codecs[mediaType][0];
  17835. });
  17836. return codecs;
  17837. };
  17838. const codecCount = function (codecObj) {
  17839. let count = 0;
  17840. if (codecObj.audio) {
  17841. count++;
  17842. }
  17843. if (codecObj.video) {
  17844. count++;
  17845. }
  17846. return count;
  17847. };
  17848. /**
  17849. * Calculates the codec strings for a working configuration of
  17850. * SourceBuffers to play variant streams in a main playlist. If
  17851. * there is no possible working configuration, an empty object will be
  17852. * returned.
  17853. *
  17854. * @param main {Object} the m3u8 object for the main playlist
  17855. * @param media {Object} the m3u8 object for the variant playlist
  17856. * @return {Object} the codec strings.
  17857. *
  17858. * @private
  17859. */
  17860. const codecsForPlaylist = function (main, media) {
  17861. const mediaAttributes = media.attributes || {};
  17862. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  17863. // Put another way, there is no way to have a video-only multiple-audio HLS!
  17864. if (isMaat(main, media) && !codecInfo.audio) {
  17865. if (!isMuxed(main, media)) {
  17866. // It is possible for codecs to be specified on the audio media group playlist but
  17867. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  17868. // video are always separate (and separately specified).
  17869. const defaultCodecs = unwrapCodecList(codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  17870. if (defaultCodecs.audio) {
  17871. codecInfo.audio = defaultCodecs.audio;
  17872. }
  17873. }
  17874. }
  17875. return codecInfo;
  17876. };
  17877. const logFn = logger('PlaylistSelector');
  17878. const representationToString = function (representation) {
  17879. if (!representation || !representation.playlist) {
  17880. return;
  17881. }
  17882. const playlist = representation.playlist;
  17883. return JSON.stringify({
  17884. id: playlist.id,
  17885. bandwidth: representation.bandwidth,
  17886. width: representation.width,
  17887. height: representation.height,
  17888. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  17889. });
  17890. }; // Utilities
  17891. /**
  17892. * Returns the CSS value for the specified property on an element
  17893. * using `getComputedStyle`. Firefox has a long-standing issue where
  17894. * getComputedStyle() may return null when running in an iframe with
  17895. * `display: none`.
  17896. *
  17897. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  17898. * @param {HTMLElement} el the htmlelement to work on
  17899. * @param {string} the proprety to get the style for
  17900. */
  17901. const safeGetComputedStyle = function (el, property) {
  17902. if (!el) {
  17903. return '';
  17904. }
  17905. const result = window.getComputedStyle(el);
  17906. if (!result) {
  17907. return '';
  17908. }
  17909. return result[property];
  17910. };
  17911. /**
  17912. * Resuable stable sort function
  17913. *
  17914. * @param {Playlists} array
  17915. * @param {Function} sortFn Different comparators
  17916. * @function stableSort
  17917. */
  17918. const stableSort = function (array, sortFn) {
  17919. const newArray = array.slice();
  17920. array.sort(function (left, right) {
  17921. const cmp = sortFn(left, right);
  17922. if (cmp === 0) {
  17923. return newArray.indexOf(left) - newArray.indexOf(right);
  17924. }
  17925. return cmp;
  17926. });
  17927. };
  17928. /**
  17929. * A comparator function to sort two playlist object by bandwidth.
  17930. *
  17931. * @param {Object} left a media playlist object
  17932. * @param {Object} right a media playlist object
  17933. * @return {number} Greater than zero if the bandwidth attribute of
  17934. * left is greater than the corresponding attribute of right. Less
  17935. * than zero if the bandwidth of right is greater than left and
  17936. * exactly zero if the two are equal.
  17937. */
  17938. const comparePlaylistBandwidth = function (left, right) {
  17939. let leftBandwidth;
  17940. let rightBandwidth;
  17941. if (left.attributes.BANDWIDTH) {
  17942. leftBandwidth = left.attributes.BANDWIDTH;
  17943. }
  17944. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  17945. if (right.attributes.BANDWIDTH) {
  17946. rightBandwidth = right.attributes.BANDWIDTH;
  17947. }
  17948. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  17949. return leftBandwidth - rightBandwidth;
  17950. };
  17951. /**
  17952. * A comparator function to sort two playlist object by resolution (width).
  17953. *
  17954. * @param {Object} left a media playlist object
  17955. * @param {Object} right a media playlist object
  17956. * @return {number} Greater than zero if the resolution.width attribute of
  17957. * left is greater than the corresponding attribute of right. Less
  17958. * than zero if the resolution.width of right is greater than left and
  17959. * exactly zero if the two are equal.
  17960. */
  17961. const comparePlaylistResolution = function (left, right) {
  17962. let leftWidth;
  17963. let rightWidth;
  17964. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  17965. leftWidth = left.attributes.RESOLUTION.width;
  17966. }
  17967. leftWidth = leftWidth || window.Number.MAX_VALUE;
  17968. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  17969. rightWidth = right.attributes.RESOLUTION.width;
  17970. }
  17971. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  17972. // have the same media dimensions/ resolution
  17973. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  17974. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  17975. }
  17976. return leftWidth - rightWidth;
  17977. };
  17978. /**
  17979. * Chooses the appropriate media playlist based on bandwidth and player size
  17980. *
  17981. * @param {Object} main
  17982. * Object representation of the main manifest
  17983. * @param {number} playerBandwidth
  17984. * Current calculated bandwidth of the player
  17985. * @param {number} playerWidth
  17986. * Current width of the player element (should account for the device pixel ratio)
  17987. * @param {number} playerHeight
  17988. * Current height of the player element (should account for the device pixel ratio)
  17989. * @param {boolean} limitRenditionByPlayerDimensions
  17990. * True if the player width and height should be used during the selection, false otherwise
  17991. * @param {Object} playlistController
  17992. * the current playlistController object
  17993. * @return {Playlist} the highest bitrate playlist less than the
  17994. * currently detected bandwidth, accounting for some amount of
  17995. * bandwidth variance
  17996. */
  17997. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  17998. // If we end up getting called before `main` is available, exit early
  17999. if (!main) {
  18000. return;
  18001. }
  18002. const options = {
  18003. bandwidth: playerBandwidth,
  18004. width: playerWidth,
  18005. height: playerHeight,
  18006. limitRenditionByPlayerDimensions
  18007. };
  18008. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  18009. if (Playlist.isAudioOnly(main)) {
  18010. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  18011. // at the buttom of this function for debugging.
  18012. options.audioOnly = true;
  18013. } // convert the playlists to an intermediary representation to make comparisons easier
  18014. let sortedPlaylistReps = playlists.map(playlist => {
  18015. let bandwidth;
  18016. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  18017. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  18018. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  18019. bandwidth = bandwidth || window.Number.MAX_VALUE;
  18020. return {
  18021. bandwidth,
  18022. width,
  18023. height,
  18024. playlist
  18025. };
  18026. });
  18027. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  18028. // incompatible configurations
  18029. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  18030. // api or excluded temporarily due to playback errors.
  18031. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  18032. if (!enabledPlaylistReps.length) {
  18033. // if there are no enabled playlists, then they have all been excluded or disabled
  18034. // by the user through the representations api. In this case, ignore exclusion and
  18035. // fallback to what the user wants by using playlists the user has not disabled.
  18036. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  18037. } // filter out any variant that has greater effective bitrate
  18038. // than the current estimated bandwidth
  18039. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  18040. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  18041. // and then taking the very first element
  18042. 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.
  18043. if (limitRenditionByPlayerDimensions === false) {
  18044. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  18045. if (chosenRep && chosenRep.playlist) {
  18046. let type = 'sortedPlaylistReps';
  18047. if (bandwidthBestRep) {
  18048. type = 'bandwidthBestRep';
  18049. }
  18050. if (enabledPlaylistReps[0]) {
  18051. type = 'enabledPlaylistReps';
  18052. }
  18053. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  18054. return chosenRep.playlist;
  18055. }
  18056. logFn('could not choose a playlist with options', options);
  18057. return null;
  18058. } // filter out playlists without resolution information
  18059. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  18060. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  18061. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  18062. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  18063. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  18064. let resolutionPlusOneList;
  18065. let resolutionPlusOneSmallest;
  18066. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  18067. // if there is no match of exact resolution
  18068. if (!resolutionBestRep) {
  18069. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  18070. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  18071. // is just-larger-than the video player
  18072. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  18073. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  18074. }
  18075. let leastPixelDiffRep; // If this selector proves to be better than others,
  18076. // resolutionPlusOneRep and resolutionBestRep and all
  18077. // the code involving them should be removed.
  18078. if (playlistController.leastPixelDiffSelector) {
  18079. // find the variant that is closest to the player's pixel size
  18080. const leastPixelDiffList = haveResolution.map(rep => {
  18081. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  18082. return rep;
  18083. }); // get the highest bandwidth, closest resolution playlist
  18084. stableSort(leastPixelDiffList, (left, right) => {
  18085. // sort by highest bandwidth if pixelDiff is the same
  18086. if (left.pixelDiff === right.pixelDiff) {
  18087. return right.bandwidth - left.bandwidth;
  18088. }
  18089. return left.pixelDiff - right.pixelDiff;
  18090. });
  18091. leastPixelDiffRep = leastPixelDiffList[0];
  18092. } // fallback chain of variants
  18093. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  18094. if (chosenRep && chosenRep.playlist) {
  18095. let type = 'sortedPlaylistReps';
  18096. if (leastPixelDiffRep) {
  18097. type = 'leastPixelDiffRep';
  18098. } else if (resolutionPlusOneRep) {
  18099. type = 'resolutionPlusOneRep';
  18100. } else if (resolutionBestRep) {
  18101. type = 'resolutionBestRep';
  18102. } else if (bandwidthBestRep) {
  18103. type = 'bandwidthBestRep';
  18104. } else if (enabledPlaylistReps[0]) {
  18105. type = 'enabledPlaylistReps';
  18106. }
  18107. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  18108. return chosenRep.playlist;
  18109. }
  18110. logFn('could not choose a playlist with options', options);
  18111. return null;
  18112. };
  18113. /**
  18114. * Chooses the appropriate media playlist based on the most recent
  18115. * bandwidth estimate and the player size.
  18116. *
  18117. * Expects to be called within the context of an instance of VhsHandler
  18118. *
  18119. * @return {Playlist} the highest bitrate playlist less than the
  18120. * currently detected bandwidth, accounting for some amount of
  18121. * bandwidth variance
  18122. */
  18123. const lastBandwidthSelector = function () {
  18124. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  18125. 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_);
  18126. };
  18127. /**
  18128. * Chooses the appropriate media playlist based on an
  18129. * exponential-weighted moving average of the bandwidth after
  18130. * filtering for player size.
  18131. *
  18132. * Expects to be called within the context of an instance of VhsHandler
  18133. *
  18134. * @param {number} decay - a number between 0 and 1. Higher values of
  18135. * this parameter will cause previous bandwidth estimates to lose
  18136. * significance more quickly.
  18137. * @return {Function} a function which can be invoked to create a new
  18138. * playlist selector function.
  18139. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  18140. */
  18141. const movingAverageBandwidthSelector = function (decay) {
  18142. let average = -1;
  18143. let lastSystemBandwidth = -1;
  18144. if (decay < 0 || decay > 1) {
  18145. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  18146. }
  18147. return function () {
  18148. const pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  18149. if (average < 0) {
  18150. average = this.systemBandwidth;
  18151. lastSystemBandwidth = this.systemBandwidth;
  18152. } // stop the average value from decaying for every 250ms
  18153. // when the systemBandwidth is constant
  18154. // and
  18155. // stop average from setting to a very low value when the
  18156. // systemBandwidth becomes 0 in case of chunk cancellation
  18157. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  18158. average = decay * this.systemBandwidth + (1 - decay) * average;
  18159. lastSystemBandwidth = this.systemBandwidth;
  18160. }
  18161. 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_);
  18162. };
  18163. };
  18164. /**
  18165. * Chooses the appropriate media playlist based on the potential to rebuffer
  18166. *
  18167. * @param {Object} settings
  18168. * Object of information required to use this selector
  18169. * @param {Object} settings.main
  18170. * Object representation of the main manifest
  18171. * @param {number} settings.currentTime
  18172. * The current time of the player
  18173. * @param {number} settings.bandwidth
  18174. * Current measured bandwidth
  18175. * @param {number} settings.duration
  18176. * Duration of the media
  18177. * @param {number} settings.segmentDuration
  18178. * Segment duration to be used in round trip time calculations
  18179. * @param {number} settings.timeUntilRebuffer
  18180. * Time left in seconds until the player has to rebuffer
  18181. * @param {number} settings.currentTimeline
  18182. * The current timeline segments are being loaded from
  18183. * @param {SyncController} settings.syncController
  18184. * SyncController for determining if we have a sync point for a given playlist
  18185. * @return {Object|null}
  18186. * {Object} return.playlist
  18187. * The highest bandwidth playlist with the least amount of rebuffering
  18188. * {Number} return.rebufferingImpact
  18189. * The amount of time in seconds switching to this playlist will rebuffer. A
  18190. * negative value means that switching will cause zero rebuffering.
  18191. */
  18192. const minRebufferMaxBandwidthSelector = function (settings) {
  18193. const {
  18194. main,
  18195. currentTime,
  18196. bandwidth,
  18197. duration,
  18198. segmentDuration,
  18199. timeUntilRebuffer,
  18200. currentTimeline,
  18201. syncController
  18202. } = settings; // filter out any playlists that have been excluded due to
  18203. // incompatible configurations
  18204. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  18205. // api or excluded temporarily due to playback errors.
  18206. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  18207. if (!enabledPlaylists.length) {
  18208. // if there are no enabled playlists, then they have all been excluded or disabled
  18209. // by the user through the representations api. In this case, ignore exclusion and
  18210. // fallback to what the user wants by using playlists the user has not disabled.
  18211. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  18212. }
  18213. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  18214. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  18215. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  18216. // sync request first. This will double the request time
  18217. const numRequests = syncPoint ? 1 : 2;
  18218. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  18219. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  18220. return {
  18221. playlist,
  18222. rebufferingImpact
  18223. };
  18224. });
  18225. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  18226. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  18227. if (noRebufferingPlaylists.length) {
  18228. return noRebufferingPlaylists[0];
  18229. }
  18230. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  18231. return rebufferingEstimates[0] || null;
  18232. };
  18233. /**
  18234. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  18235. * one with video. If no renditions with video exist, return the lowest audio rendition.
  18236. *
  18237. * Expects to be called within the context of an instance of VhsHandler
  18238. *
  18239. * @return {Object|null}
  18240. * {Object} return.playlist
  18241. * The lowest bitrate playlist that contains a video codec. If no such rendition
  18242. * exists pick the lowest audio rendition.
  18243. */
  18244. const lowestBitrateCompatibleVariantSelector = function () {
  18245. // filter out any playlists that have been excluded due to
  18246. // incompatible configurations or playback errors
  18247. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  18248. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  18249. // (this is not necessarily true, although it is generally true).
  18250. //
  18251. // If an entire manifest has no valid videos everything will get filtered
  18252. // out.
  18253. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  18254. return playlistsWithVideo[0] || null;
  18255. };
  18256. /**
  18257. * Combine all segments into a single Uint8Array
  18258. *
  18259. * @param {Object} segmentObj
  18260. * @return {Uint8Array} concatenated bytes
  18261. * @private
  18262. */
  18263. const concatSegments = segmentObj => {
  18264. let offset = 0;
  18265. let tempBuffer;
  18266. if (segmentObj.bytes) {
  18267. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  18268. segmentObj.segments.forEach(segment => {
  18269. tempBuffer.set(segment, offset);
  18270. offset += segment.byteLength;
  18271. });
  18272. }
  18273. return tempBuffer;
  18274. };
  18275. /**
  18276. * @file text-tracks.js
  18277. */
  18278. /**
  18279. * Create captions text tracks on video.js if they do not exist
  18280. *
  18281. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  18282. * @param {Object} tech the video.js tech
  18283. * @param {Object} captionStream the caption stream to create
  18284. * @private
  18285. */
  18286. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  18287. if (!inbandTextTracks[captionStream]) {
  18288. tech.trigger({
  18289. type: 'usage',
  18290. name: 'vhs-608'
  18291. });
  18292. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  18293. if (/^cc708_/.test(captionStream)) {
  18294. instreamId = 'SERVICE' + captionStream.split('_')[1];
  18295. }
  18296. const track = tech.textTracks().getTrackById(instreamId);
  18297. if (track) {
  18298. // Resuse an existing track with a CC# id because this was
  18299. // very likely created by videojs-contrib-hls from information
  18300. // in the m3u8 for us to use
  18301. inbandTextTracks[captionStream] = track;
  18302. } else {
  18303. // This section gets called when we have caption services that aren't specified in the manifest.
  18304. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  18305. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  18306. let label = captionStream;
  18307. let language = captionStream;
  18308. let def = false;
  18309. const captionService = captionServices[instreamId];
  18310. if (captionService) {
  18311. label = captionService.label;
  18312. language = captionService.language;
  18313. def = captionService.default;
  18314. } // Otherwise, create a track with the default `CC#` label and
  18315. // without a language
  18316. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  18317. kind: 'captions',
  18318. id: instreamId,
  18319. // TODO: investigate why this doesn't seem to turn the caption on by default
  18320. default: def,
  18321. label,
  18322. language
  18323. }, false).track;
  18324. }
  18325. }
  18326. };
  18327. /**
  18328. * Add caption text track data to a source handler given an array of captions
  18329. *
  18330. * @param {Object}
  18331. * @param {Object} inbandTextTracks the inband text tracks
  18332. * @param {number} timestampOffset the timestamp offset of the source buffer
  18333. * @param {Array} captionArray an array of caption data
  18334. * @private
  18335. */
  18336. const addCaptionData = function ({
  18337. inbandTextTracks,
  18338. captionArray,
  18339. timestampOffset
  18340. }) {
  18341. if (!captionArray) {
  18342. return;
  18343. }
  18344. const Cue = window.WebKitDataCue || window.VTTCue;
  18345. captionArray.forEach(caption => {
  18346. const track = caption.stream; // in CEA 608 captions, video.js/mux.js sends a content array
  18347. // with positioning data
  18348. if (caption.content) {
  18349. caption.content.forEach(value => {
  18350. const cue = new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, value.text);
  18351. cue.line = value.line;
  18352. cue.align = 'left';
  18353. cue.position = value.position;
  18354. cue.positionAlign = 'line-left';
  18355. inbandTextTracks[track].addCue(cue);
  18356. });
  18357. } else {
  18358. // otherwise, a text value with combined captions is sent
  18359. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  18360. }
  18361. });
  18362. };
  18363. /**
  18364. * Define properties on a cue for backwards compatability,
  18365. * but warn the user that the way that they are using it
  18366. * is depricated and will be removed at a later date.
  18367. *
  18368. * @param {Cue} cue the cue to add the properties on
  18369. * @private
  18370. */
  18371. const deprecateOldCue = function (cue) {
  18372. Object.defineProperties(cue.frame, {
  18373. id: {
  18374. get() {
  18375. videojs__default["default"].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  18376. return cue.value.key;
  18377. }
  18378. },
  18379. value: {
  18380. get() {
  18381. videojs__default["default"].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  18382. return cue.value.data;
  18383. }
  18384. },
  18385. privateData: {
  18386. get() {
  18387. videojs__default["default"].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  18388. return cue.value.data;
  18389. }
  18390. }
  18391. });
  18392. };
  18393. /**
  18394. * Add metadata text track data to a source handler given an array of metadata
  18395. *
  18396. * @param {Object}
  18397. * @param {Object} inbandTextTracks the inband text tracks
  18398. * @param {Array} metadataArray an array of meta data
  18399. * @param {number} timestampOffset the timestamp offset of the source buffer
  18400. * @param {number} videoDuration the duration of the video
  18401. * @private
  18402. */
  18403. const addMetadata = ({
  18404. inbandTextTracks,
  18405. metadataArray,
  18406. timestampOffset,
  18407. videoDuration
  18408. }) => {
  18409. if (!metadataArray) {
  18410. return;
  18411. }
  18412. const Cue = window.WebKitDataCue || window.VTTCue;
  18413. const metadataTrack = inbandTextTracks.metadataTrack_;
  18414. if (!metadataTrack) {
  18415. return;
  18416. }
  18417. metadataArray.forEach(metadata => {
  18418. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  18419. // ignore this bit of metadata.
  18420. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  18421. // which is the "Title/Songname/Content description" frame
  18422. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  18423. return;
  18424. } // If we have no frames, we can't create a cue.
  18425. if (!metadata.frames || !metadata.frames.length) {
  18426. return;
  18427. }
  18428. metadata.frames.forEach(frame => {
  18429. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  18430. cue.frame = frame;
  18431. cue.value = frame;
  18432. deprecateOldCue(cue);
  18433. metadataTrack.addCue(cue);
  18434. });
  18435. });
  18436. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  18437. return;
  18438. } // Updating the metadeta cues so that
  18439. // the endTime of each cue is the startTime of the next cue
  18440. // the endTime of last cue is the duration of the video
  18441. const cues = metadataTrack.cues;
  18442. const cuesArray = []; // Create a copy of the TextTrackCueList...
  18443. // ...disregarding cues with a falsey value
  18444. for (let i = 0; i < cues.length; i++) {
  18445. if (cues[i]) {
  18446. cuesArray.push(cues[i]);
  18447. }
  18448. } // Group cues by their startTime value
  18449. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  18450. const timeSlot = obj[cue.startTime] || [];
  18451. timeSlot.push(cue);
  18452. obj[cue.startTime] = timeSlot;
  18453. return obj;
  18454. }, {}); // Sort startTimes by ascending order
  18455. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  18456. sortedStartTimes.forEach((startTime, idx) => {
  18457. const cueGroup = cuesGroupedByStartTime[startTime];
  18458. const finiteDuration = isFinite(videoDuration) ? videoDuration : startTime;
  18459. const nextTime = Number(sortedStartTimes[idx + 1]) || finiteDuration; // Map each cue's endTime the next group's startTime
  18460. cueGroup.forEach(cue => {
  18461. cue.endTime = nextTime;
  18462. });
  18463. });
  18464. }; // object for mapping daterange attributes
  18465. const dateRangeAttr = {
  18466. id: 'ID',
  18467. class: 'CLASS',
  18468. startDate: 'START-DATE',
  18469. duration: 'DURATION',
  18470. endDate: 'END-DATE',
  18471. endOnNext: 'END-ON-NEXT',
  18472. plannedDuration: 'PLANNED-DURATION',
  18473. scte35Out: 'SCTE35-OUT',
  18474. scte35In: 'SCTE35-IN'
  18475. };
  18476. const dateRangeKeysToOmit = new Set(['id', 'class', 'startDate', 'duration', 'endDate', 'endOnNext', 'startTime', 'endTime', 'processDateRange']);
  18477. /**
  18478. * Add DateRange metadata text track to a source handler given an array of metadata
  18479. *
  18480. * @param {Object}
  18481. * @param {Object} inbandTextTracks the inband text tracks
  18482. * @param {Array} dateRanges parsed media playlist
  18483. * @private
  18484. */
  18485. const addDateRangeMetadata = ({
  18486. inbandTextTracks,
  18487. dateRanges
  18488. }) => {
  18489. const metadataTrack = inbandTextTracks.metadataTrack_;
  18490. if (!metadataTrack) {
  18491. return;
  18492. }
  18493. const Cue = window.WebKitDataCue || window.VTTCue;
  18494. dateRanges.forEach(dateRange => {
  18495. // we generate multiple cues for each date range with different attributes
  18496. for (const key of Object.keys(dateRange)) {
  18497. if (dateRangeKeysToOmit.has(key)) {
  18498. continue;
  18499. }
  18500. const cue = new Cue(dateRange.startTime, dateRange.endTime, '');
  18501. cue.id = dateRange.id;
  18502. cue.type = 'com.apple.quicktime.HLS';
  18503. cue.value = {
  18504. key: dateRangeAttr[key],
  18505. data: dateRange[key]
  18506. };
  18507. if (key === 'scte35Out' || key === 'scte35In') {
  18508. cue.value.data = new Uint8Array(cue.value.data.match(/[\da-f]{2}/gi)).buffer;
  18509. }
  18510. metadataTrack.addCue(cue);
  18511. }
  18512. dateRange.processDateRange();
  18513. });
  18514. };
  18515. /**
  18516. * Create metadata text track on video.js if it does not exist
  18517. *
  18518. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  18519. * @param {string} dispatchType the inband metadata track dispatch type
  18520. * @param {Object} tech the video.js tech
  18521. * @private
  18522. */
  18523. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  18524. if (inbandTextTracks.metadataTrack_) {
  18525. return;
  18526. }
  18527. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  18528. kind: 'metadata',
  18529. label: 'Timed Metadata'
  18530. }, false).track;
  18531. if (!videojs__default["default"].browser.IS_ANY_SAFARI) {
  18532. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  18533. }
  18534. };
  18535. /**
  18536. * Remove cues from a track on video.js.
  18537. *
  18538. * @param {Double} start start of where we should remove the cue
  18539. * @param {Double} end end of where the we should remove the cue
  18540. * @param {Object} track the text track to remove the cues from
  18541. * @private
  18542. */
  18543. const removeCuesFromTrack = function (start, end, track) {
  18544. let i;
  18545. let cue;
  18546. if (!track) {
  18547. return;
  18548. }
  18549. if (!track.cues) {
  18550. return;
  18551. }
  18552. i = track.cues.length;
  18553. while (i--) {
  18554. cue = track.cues[i]; // Remove any cue within the provided start and end time
  18555. if (cue.startTime >= start && cue.endTime <= end) {
  18556. track.removeCue(cue);
  18557. }
  18558. }
  18559. };
  18560. /**
  18561. * Remove duplicate cues from a track on video.js (a cue is considered a
  18562. * duplicate if it has the same time interval and text as another)
  18563. *
  18564. * @param {Object} track the text track to remove the duplicate cues from
  18565. * @private
  18566. */
  18567. const removeDuplicateCuesFromTrack = function (track) {
  18568. const cues = track.cues;
  18569. if (!cues) {
  18570. return;
  18571. }
  18572. const uniqueCues = {};
  18573. for (let i = cues.length - 1; i >= 0; i--) {
  18574. const cue = cues[i];
  18575. const cueKey = `${cue.startTime}-${cue.endTime}-${cue.text}`;
  18576. if (uniqueCues[cueKey]) {
  18577. track.removeCue(cue);
  18578. } else {
  18579. uniqueCues[cueKey] = cue;
  18580. }
  18581. }
  18582. };
  18583. /**
  18584. * mux.js
  18585. *
  18586. * Copyright (c) Brightcove
  18587. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  18588. */
  18589. var ONE_SECOND_IN_TS = 90000,
  18590. // 90kHz clock
  18591. secondsToVideoTs,
  18592. secondsToAudioTs,
  18593. videoTsToSeconds,
  18594. audioTsToSeconds,
  18595. audioTsToVideoTs,
  18596. videoTsToAudioTs,
  18597. metadataTsToSeconds;
  18598. secondsToVideoTs = function (seconds) {
  18599. return seconds * ONE_SECOND_IN_TS;
  18600. };
  18601. secondsToAudioTs = function (seconds, sampleRate) {
  18602. return seconds * sampleRate;
  18603. };
  18604. videoTsToSeconds = function (timestamp) {
  18605. return timestamp / ONE_SECOND_IN_TS;
  18606. };
  18607. audioTsToSeconds = function (timestamp, sampleRate) {
  18608. return timestamp / sampleRate;
  18609. };
  18610. audioTsToVideoTs = function (timestamp, sampleRate) {
  18611. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  18612. };
  18613. videoTsToAudioTs = function (timestamp, sampleRate) {
  18614. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  18615. };
  18616. /**
  18617. * Adjust ID3 tag or caption timing information by the timeline pts values
  18618. * (if keepOriginalTimestamps is false) and convert to seconds
  18619. */
  18620. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  18621. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  18622. };
  18623. var clock = {
  18624. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  18625. secondsToVideoTs: secondsToVideoTs,
  18626. secondsToAudioTs: secondsToAudioTs,
  18627. videoTsToSeconds: videoTsToSeconds,
  18628. audioTsToSeconds: audioTsToSeconds,
  18629. audioTsToVideoTs: audioTsToVideoTs,
  18630. videoTsToAudioTs: videoTsToAudioTs,
  18631. metadataTsToSeconds: metadataTsToSeconds
  18632. };
  18633. /**
  18634. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  18635. * front of current time.
  18636. *
  18637. * @param {Array} buffer
  18638. * The current buffer of gop information
  18639. * @param {number} currentTime
  18640. * The current time
  18641. * @param {Double} mapping
  18642. * Offset to map display time to stream presentation time
  18643. * @return {Array}
  18644. * List of gops considered safe to append over
  18645. */
  18646. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  18647. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  18648. return [];
  18649. } // pts value for current time + 3 seconds to give a bit more wiggle room
  18650. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  18651. let i;
  18652. for (i = 0; i < buffer.length; i++) {
  18653. if (buffer[i].pts > currentTimePts) {
  18654. break;
  18655. }
  18656. }
  18657. return buffer.slice(i);
  18658. };
  18659. /**
  18660. * Appends gop information (timing and byteLength) received by the transmuxer for the
  18661. * gops appended in the last call to appendBuffer
  18662. *
  18663. * @param {Array} buffer
  18664. * The current buffer of gop information
  18665. * @param {Array} gops
  18666. * List of new gop information
  18667. * @param {boolean} replace
  18668. * If true, replace the buffer with the new gop information. If false, append the
  18669. * new gop information to the buffer in the right location of time.
  18670. * @return {Array}
  18671. * Updated list of gop information
  18672. */
  18673. const updateGopBuffer = (buffer, gops, replace) => {
  18674. if (!gops.length) {
  18675. return buffer;
  18676. }
  18677. if (replace) {
  18678. // If we are in safe append mode, then completely overwrite the gop buffer
  18679. // with the most recent appeneded data. This will make sure that when appending
  18680. // future segments, we only try to align with gops that are both ahead of current
  18681. // time and in the last segment appended.
  18682. return gops.slice();
  18683. }
  18684. const start = gops[0].pts;
  18685. let i = 0;
  18686. for (i; i < buffer.length; i++) {
  18687. if (buffer[i].pts >= start) {
  18688. break;
  18689. }
  18690. }
  18691. return buffer.slice(0, i).concat(gops);
  18692. };
  18693. /**
  18694. * Removes gop information in buffer that overlaps with provided start and end
  18695. *
  18696. * @param {Array} buffer
  18697. * The current buffer of gop information
  18698. * @param {Double} start
  18699. * position to start the remove at
  18700. * @param {Double} end
  18701. * position to end the remove at
  18702. * @param {Double} mapping
  18703. * Offset to map display time to stream presentation time
  18704. */
  18705. const removeGopBuffer = (buffer, start, end, mapping) => {
  18706. const startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  18707. const endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  18708. const updatedBuffer = buffer.slice();
  18709. let i = buffer.length;
  18710. while (i--) {
  18711. if (buffer[i].pts <= endPts) {
  18712. break;
  18713. }
  18714. }
  18715. if (i === -1) {
  18716. // no removal because end of remove range is before start of buffer
  18717. return updatedBuffer;
  18718. }
  18719. let j = i + 1;
  18720. while (j--) {
  18721. if (buffer[j].pts <= startPts) {
  18722. break;
  18723. }
  18724. } // clamp remove range start to 0 index
  18725. j = Math.max(j, 0);
  18726. updatedBuffer.splice(j, i - j + 1);
  18727. return updatedBuffer;
  18728. };
  18729. const shallowEqual = function (a, b) {
  18730. // if both are undefined
  18731. // or one or the other is undefined
  18732. // they are not equal
  18733. if (!a && !b || !a && b || a && !b) {
  18734. return false;
  18735. } // they are the same object and thus, equal
  18736. if (a === b) {
  18737. return true;
  18738. } // sort keys so we can make sure they have
  18739. // all the same keys later.
  18740. const akeys = Object.keys(a).sort();
  18741. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  18742. if (akeys.length !== bkeys.length) {
  18743. return false;
  18744. }
  18745. for (let i = 0; i < akeys.length; i++) {
  18746. const key = akeys[i]; // different sorted keys, not equal
  18747. if (key !== bkeys[i]) {
  18748. return false;
  18749. } // different values, not equal
  18750. if (a[key] !== b[key]) {
  18751. return false;
  18752. }
  18753. }
  18754. return true;
  18755. };
  18756. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  18757. const QUOTA_EXCEEDED_ERR = 22;
  18758. /**
  18759. * The segment loader has no recourse except to fetch a segment in the
  18760. * current playlist and use the internal timestamps in that segment to
  18761. * generate a syncPoint. This function returns a good candidate index
  18762. * for that process.
  18763. *
  18764. * @param {Array} segments - the segments array from a playlist.
  18765. * @return {number} An index of a segment from the playlist to load
  18766. */
  18767. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  18768. segments = segments || [];
  18769. const timelineSegments = [];
  18770. let time = 0;
  18771. for (let i = 0; i < segments.length; i++) {
  18772. const segment = segments[i];
  18773. if (currentTimeline === segment.timeline) {
  18774. timelineSegments.push(i);
  18775. time += segment.duration;
  18776. if (time > targetTime) {
  18777. return i;
  18778. }
  18779. }
  18780. }
  18781. if (timelineSegments.length === 0) {
  18782. return 0;
  18783. } // default to the last timeline segment
  18784. return timelineSegments[timelineSegments.length - 1];
  18785. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  18786. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  18787. // as a start to prevent any potential issues with removing content too close to the
  18788. // playhead.
  18789. const MIN_BACK_BUFFER = 1; // in ms
  18790. const CHECK_BUFFER_DELAY = 500;
  18791. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  18792. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  18793. // not accurately reflect the rest of the content.
  18794. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  18795. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  18796. // Although these checks should most likely cover non 'main' types, for now it narrows
  18797. // the scope of our checks.
  18798. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  18799. return null;
  18800. }
  18801. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  18802. return 'Neither audio nor video found in segment.';
  18803. }
  18804. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  18805. 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.';
  18806. }
  18807. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  18808. 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.';
  18809. }
  18810. return null;
  18811. };
  18812. /**
  18813. * Calculates a time value that is safe to remove from the back buffer without interrupting
  18814. * playback.
  18815. *
  18816. * @param {TimeRange} seekable
  18817. * The current seekable range
  18818. * @param {number} currentTime
  18819. * The current time of the player
  18820. * @param {number} targetDuration
  18821. * The target duration of the current playlist
  18822. * @return {number}
  18823. * Time that is safe to remove from the back buffer without interrupting playback
  18824. */
  18825. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  18826. // 30 seconds before the playhead provides a safe default for trimming.
  18827. //
  18828. // Choosing a reasonable default is particularly important for high bitrate content and
  18829. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  18830. // throw an APPEND_BUFFER_ERR.
  18831. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  18832. if (seekable.length) {
  18833. // Some live playlists may have a shorter window of content than the full allowed back
  18834. // buffer. For these playlists, don't save content that's no longer within the window.
  18835. trimTime = Math.max(trimTime, seekable.start(0));
  18836. } // Don't remove within target duration of the current time to avoid the possibility of
  18837. // removing the GOP currently being played, as removing it can cause playback stalls.
  18838. const maxTrimTime = currentTime - targetDuration;
  18839. return Math.min(maxTrimTime, trimTime);
  18840. };
  18841. const segmentInfoString = segmentInfo => {
  18842. const {
  18843. startOfSegment,
  18844. duration,
  18845. segment,
  18846. part,
  18847. playlist: {
  18848. mediaSequence: seq,
  18849. id,
  18850. segments = []
  18851. },
  18852. mediaIndex: index,
  18853. partIndex,
  18854. timeline
  18855. } = segmentInfo;
  18856. const segmentLen = segments.length - 1;
  18857. let selection = 'mediaIndex/partIndex increment';
  18858. if (segmentInfo.getMediaInfoForTime) {
  18859. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  18860. } else if (segmentInfo.isSyncRequest) {
  18861. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  18862. }
  18863. if (segmentInfo.independent) {
  18864. selection += ` with independent ${segmentInfo.independent}`;
  18865. }
  18866. const hasPartIndex = typeof partIndex === 'number';
  18867. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  18868. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  18869. preloadSegment: segment
  18870. }) - 1 : 0;
  18871. 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}]`;
  18872. };
  18873. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  18874. /**
  18875. * Returns the timestamp offset to use for the segment.
  18876. *
  18877. * @param {number} segmentTimeline
  18878. * The timeline of the segment
  18879. * @param {number} currentTimeline
  18880. * The timeline currently being followed by the loader
  18881. * @param {number} startOfSegment
  18882. * The estimated segment start
  18883. * @param {TimeRange[]} buffered
  18884. * The loader's buffer
  18885. * @param {boolean} overrideCheck
  18886. * If true, no checks are made to see if the timestamp offset value should be set,
  18887. * but sets it directly to a value.
  18888. *
  18889. * @return {number|null}
  18890. * Either a number representing a new timestamp offset, or null if the segment is
  18891. * part of the same timeline
  18892. */
  18893. const timestampOffsetForSegment = ({
  18894. segmentTimeline,
  18895. currentTimeline,
  18896. startOfSegment,
  18897. buffered,
  18898. overrideCheck
  18899. }) => {
  18900. // Check to see if we are crossing a discontinuity to see if we need to set the
  18901. // timestamp offset on the transmuxer and source buffer.
  18902. //
  18903. // Previously, we changed the timestampOffset if the start of this segment was less than
  18904. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  18905. // behavior, especially around long running live streams.
  18906. if (!overrideCheck && segmentTimeline === currentTimeline) {
  18907. return null;
  18908. } // When changing renditions, it's possible to request a segment on an older timeline. For
  18909. // instance, given two renditions with the following:
  18910. //
  18911. // #EXTINF:10
  18912. // segment1
  18913. // #EXT-X-DISCONTINUITY
  18914. // #EXTINF:10
  18915. // segment2
  18916. // #EXTINF:10
  18917. // segment3
  18918. //
  18919. // And the current player state:
  18920. //
  18921. // current time: 8
  18922. // buffer: 0 => 20
  18923. //
  18924. // The next segment on the current rendition would be segment3, filling the buffer from
  18925. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  18926. // then the next segment to be requested will be segment1 from the new rendition in
  18927. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  18928. // content (since it would position segment1 of the new rendition starting at 20s). This
  18929. // case can be identified when the new segment's timeline is a prior value. Instead of
  18930. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  18931. // more accurate to the actual start time of the segment.
  18932. if (segmentTimeline < currentTimeline) {
  18933. return startOfSegment;
  18934. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  18935. // value uses the end of the last segment if it is available. While this value
  18936. // should often be correct, it's better to rely on the buffered end, as the new
  18937. // content post discontinuity should line up with the buffered end as if it were
  18938. // time 0 for the new content.
  18939. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  18940. };
  18941. /**
  18942. * Returns whether or not the loader should wait for a timeline change from the timeline
  18943. * change controller before processing the segment.
  18944. *
  18945. * Primary timing in VHS goes by video. This is different from most media players, as
  18946. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  18947. * will continue to use video as the primary timing source, due to the current logic and
  18948. * expectations built around it.
  18949. * Since the timing follows video, in order to maintain sync, the video loader is
  18950. * responsible for setting both audio and video source buffer timestamp offsets.
  18951. *
  18952. * Setting different values for audio and video source buffers could lead to
  18953. * desyncing. The following examples demonstrate some of the situations where this
  18954. * distinction is important. Note that all of these cases involve demuxed content. When
  18955. * content is muxed, the audio and video are packaged together, therefore syncing
  18956. * separate media playlists is not an issue.
  18957. *
  18958. * CASE 1: Audio prepares to load a new timeline before video:
  18959. *
  18960. * Timeline: 0 1
  18961. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18962. * Audio Loader: ^
  18963. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18964. * Video Loader ^
  18965. *
  18966. * In the above example, the audio loader is preparing to load the 6th segment, the first
  18967. * after a discontinuity, while the video loader is still loading the 5th segment, before
  18968. * the discontinuity.
  18969. *
  18970. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  18971. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  18972. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  18973. * the audio loader must provide the audioAppendStart value to trim the content in the
  18974. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  18975. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  18976. * segment until that value is provided.
  18977. *
  18978. * CASE 2: Video prepares to load a new timeline before audio:
  18979. *
  18980. * Timeline: 0 1
  18981. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18982. * Audio Loader: ^
  18983. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  18984. * Video Loader ^
  18985. *
  18986. * In the above example, the video loader is preparing to load the 6th segment, the first
  18987. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  18988. * the discontinuity.
  18989. *
  18990. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  18991. * segment is loaded and processed, both the video and audio timestamp offsets will be
  18992. * set, since video is used as the primary timing source. This is to ensure content lines
  18993. * up appropriately, as any modifications to the video timing are reflected by audio when
  18994. * the video loader sets the audio and video timestamp offsets to the same value. However,
  18995. * setting the timestamp offset for audio before audio has had a chance to change
  18996. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  18997. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  18998. *
  18999. * CASE 3: When seeking, audio prepares to load a new timeline before video
  19000. *
  19001. * Timeline: 0 1
  19002. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  19003. * Audio Loader: ^
  19004. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  19005. * Video Loader ^
  19006. *
  19007. * In the above example, both audio and video loaders are loading segments from timeline
  19008. * 0, but imagine that the seek originated from timeline 1.
  19009. *
  19010. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  19011. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  19012. * must wait for the video loader to load its segment and update both the audio and video
  19013. * timestamp offsets before it may load and append its own segment. This is the case
  19014. * whether the seek results in a mismatched segment request (e.g., the audio loader
  19015. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  19016. * loaders choose to load the same segment index from each playlist, as the segments may
  19017. * not be aligned perfectly, even for matching segment indexes.
  19018. *
  19019. * @param {Object} timelinechangeController
  19020. * @param {number} currentTimeline
  19021. * The timeline currently being followed by the loader
  19022. * @param {number} segmentTimeline
  19023. * The timeline of the segment being loaded
  19024. * @param {('main'|'audio')} loaderType
  19025. * The loader type
  19026. * @param {boolean} audioDisabled
  19027. * Whether the audio is disabled for the loader. This should only be true when the
  19028. * loader may have muxed audio in its segment, but should not append it, e.g., for
  19029. * the main loader when an alternate audio playlist is active.
  19030. *
  19031. * @return {boolean}
  19032. * Whether the loader should wait for a timeline change from the timeline change
  19033. * controller before processing the segment
  19034. */
  19035. const shouldWaitForTimelineChange = ({
  19036. timelineChangeController,
  19037. currentTimeline,
  19038. segmentTimeline,
  19039. loaderType,
  19040. audioDisabled
  19041. }) => {
  19042. if (currentTimeline === segmentTimeline) {
  19043. return false;
  19044. }
  19045. if (loaderType === 'audio') {
  19046. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  19047. type: 'main'
  19048. }); // Audio loader should wait if:
  19049. //
  19050. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  19051. // * main hasn't yet changed to the timeline audio is looking to load
  19052. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  19053. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  19054. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  19055. // loader's segments (or the content is audio/video only and handled by the main
  19056. // loader).
  19057. if (loaderType === 'main' && audioDisabled) {
  19058. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  19059. type: 'audio'
  19060. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  19061. // change to the current timeline.
  19062. //
  19063. // Since the main loader is responsible for setting the timestamp offset for both
  19064. // audio and video, the main loader must wait for audio to be about to change to its
  19065. // timeline before setting the offset, otherwise, if audio is behind in loading,
  19066. // segments from the previous timeline would be adjusted by the new timestamp offset.
  19067. //
  19068. // This requirement means that video will not cross a timeline until the audio is
  19069. // about to cross to it, so that way audio and video will always cross the timeline
  19070. // together.
  19071. //
  19072. // In addition to normal timeline changes, these rules also apply to the start of a
  19073. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  19074. // that these rules apply to the first timeline change because if they did not, it's
  19075. // possible that the main loader will cross two timelines before the audio loader has
  19076. // crossed one. Logic may be implemented to handle the startup as a special case, but
  19077. // it's easier to simply treat all timeline changes the same.
  19078. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  19079. return false;
  19080. }
  19081. return true;
  19082. }
  19083. return false;
  19084. };
  19085. const mediaDuration = timingInfos => {
  19086. let maxDuration = 0;
  19087. ['video', 'audio'].forEach(function (type) {
  19088. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  19089. if (!typeTimingInfo) {
  19090. return;
  19091. }
  19092. const {
  19093. start,
  19094. end
  19095. } = typeTimingInfo;
  19096. let duration;
  19097. if (typeof start === 'bigint' || typeof end === 'bigint') {
  19098. duration = window.BigInt(end) - window.BigInt(start);
  19099. } else if (typeof start === 'number' && typeof end === 'number') {
  19100. duration = end - start;
  19101. }
  19102. if (typeof duration !== 'undefined' && duration > maxDuration) {
  19103. maxDuration = duration;
  19104. }
  19105. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  19106. // as we only need BigInt when we are above that.
  19107. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  19108. maxDuration = Number(maxDuration);
  19109. }
  19110. return maxDuration;
  19111. };
  19112. const segmentTooLong = ({
  19113. segmentDuration,
  19114. maxDuration
  19115. }) => {
  19116. // 0 duration segments are most likely due to metadata only segments or a lack of
  19117. // information.
  19118. if (!segmentDuration) {
  19119. return false;
  19120. } // For HLS:
  19121. //
  19122. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  19123. // The EXTINF duration of each Media Segment in the Playlist
  19124. // file, when rounded to the nearest integer, MUST be less than or equal
  19125. // to the target duration; longer segments can trigger playback stalls
  19126. // or other errors.
  19127. //
  19128. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  19129. // duration. Although that reported duration is occasionally approximate (i.e., not
  19130. // exact), a strict check may report that a segment is too long more often in DASH.
  19131. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  19132. };
  19133. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  19134. // Right now we aren't following DASH's timing model exactly, so only perform
  19135. // this check for HLS content.
  19136. if (sourceType !== 'hls') {
  19137. return null;
  19138. }
  19139. const segmentDuration = mediaDuration({
  19140. audioTimingInfo: segmentInfo.audioTimingInfo,
  19141. videoTimingInfo: segmentInfo.videoTimingInfo
  19142. }); // Don't report if we lack information.
  19143. //
  19144. // If the segment has a duration of 0 it is either a lack of information or a
  19145. // metadata only segment and shouldn't be reported here.
  19146. if (!segmentDuration) {
  19147. return null;
  19148. }
  19149. const targetDuration = segmentInfo.playlist.targetDuration;
  19150. const isSegmentWayTooLong = segmentTooLong({
  19151. segmentDuration,
  19152. maxDuration: targetDuration * 2
  19153. });
  19154. const isSegmentSlightlyTooLong = segmentTooLong({
  19155. segmentDuration,
  19156. maxDuration: targetDuration
  19157. });
  19158. 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';
  19159. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  19160. return {
  19161. severity: isSegmentWayTooLong ? 'warn' : 'info',
  19162. message: segmentTooLongMessage
  19163. };
  19164. }
  19165. return null;
  19166. };
  19167. /**
  19168. * An object that manages segment loading and appending.
  19169. *
  19170. * @class SegmentLoader
  19171. * @param {Object} options required and optional options
  19172. * @extends videojs.EventTarget
  19173. */
  19174. class SegmentLoader extends videojs__default["default"].EventTarget {
  19175. constructor(settings, options = {}) {
  19176. super(); // check pre-conditions
  19177. if (!settings) {
  19178. throw new TypeError('Initialization settings are required');
  19179. }
  19180. if (typeof settings.currentTime !== 'function') {
  19181. throw new TypeError('No currentTime getter specified');
  19182. }
  19183. if (!settings.mediaSource) {
  19184. throw new TypeError('No MediaSource specified');
  19185. } // public properties
  19186. this.bandwidth = settings.bandwidth;
  19187. this.throughput = {
  19188. rate: 0,
  19189. count: 0
  19190. };
  19191. this.roundTrip = NaN;
  19192. this.resetStats_();
  19193. this.mediaIndex = null;
  19194. this.partIndex = null; // private settings
  19195. this.hasPlayed_ = settings.hasPlayed;
  19196. this.currentTime_ = settings.currentTime;
  19197. this.seekable_ = settings.seekable;
  19198. this.seeking_ = settings.seeking;
  19199. this.duration_ = settings.duration;
  19200. this.mediaSource_ = settings.mediaSource;
  19201. this.vhs_ = settings.vhs;
  19202. this.loaderType_ = settings.loaderType;
  19203. this.currentMediaInfo_ = void 0;
  19204. this.startingMediaInfo_ = void 0;
  19205. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  19206. this.goalBufferLength_ = settings.goalBufferLength;
  19207. this.sourceType_ = settings.sourceType;
  19208. this.sourceUpdater_ = settings.sourceUpdater;
  19209. this.inbandTextTracks_ = settings.inbandTextTracks;
  19210. this.state_ = 'INIT';
  19211. this.timelineChangeController_ = settings.timelineChangeController;
  19212. this.shouldSaveSegmentTimingInfo_ = true;
  19213. this.parse708captions_ = settings.parse708captions;
  19214. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  19215. this.captionServices_ = settings.captionServices;
  19216. this.exactManifestTimings = settings.exactManifestTimings;
  19217. this.addMetadataToTextTrack = settings.addMetadataToTextTrack; // private instance variables
  19218. this.checkBufferTimeout_ = null;
  19219. this.error_ = void 0;
  19220. this.currentTimeline_ = -1;
  19221. this.shouldForceTimestampOffsetAfterResync_ = false;
  19222. this.pendingSegment_ = null;
  19223. this.xhrOptions_ = null;
  19224. this.pendingSegments_ = [];
  19225. this.audioDisabled_ = false;
  19226. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  19227. this.gopBuffer_ = [];
  19228. this.timeMapping_ = 0;
  19229. this.safeAppend_ = false;
  19230. this.appendInitSegment_ = {
  19231. audio: true,
  19232. video: true
  19233. };
  19234. this.playlistOfLastInitSegment_ = {
  19235. audio: null,
  19236. video: null
  19237. };
  19238. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  19239. // information yet to start the loading process (e.g., if the audio loader wants to
  19240. // load a segment from the next timeline but the main loader hasn't yet crossed that
  19241. // timeline), then the load call will be added to the queue until it is ready to be
  19242. // processed.
  19243. this.loadQueue_ = [];
  19244. this.metadataQueue_ = {
  19245. id3: [],
  19246. caption: []
  19247. };
  19248. this.waitingOnRemove_ = false;
  19249. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  19250. this.activeInitSegmentId_ = null;
  19251. this.initSegments_ = {}; // HLSe playback
  19252. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  19253. this.keyCache_ = {};
  19254. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  19255. // between a time in the display time and a segment index within
  19256. // a playlist
  19257. this.syncController_ = settings.syncController;
  19258. this.syncPoint_ = {
  19259. segmentIndex: 0,
  19260. time: 0
  19261. };
  19262. this.transmuxer_ = this.createTransmuxer_();
  19263. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  19264. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  19265. this.mediaSource_.addEventListener('sourceopen', () => {
  19266. if (!this.isEndOfStream_()) {
  19267. this.ended_ = false;
  19268. }
  19269. }); // ...for determining the fetch location
  19270. this.fetchAtBuffer_ = false;
  19271. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  19272. Object.defineProperty(this, 'state', {
  19273. get() {
  19274. return this.state_;
  19275. },
  19276. set(newState) {
  19277. if (newState !== this.state_) {
  19278. this.logger_(`${this.state_} -> ${newState}`);
  19279. this.state_ = newState;
  19280. this.trigger('statechange');
  19281. }
  19282. }
  19283. });
  19284. this.sourceUpdater_.on('ready', () => {
  19285. if (this.hasEnoughInfoToAppend_()) {
  19286. this.processCallQueue_();
  19287. }
  19288. }); // Only the main loader needs to listen for pending timeline changes, as the main
  19289. // loader should wait for audio to be ready to change its timeline so that both main
  19290. // and audio timelines change together. For more details, see the
  19291. // shouldWaitForTimelineChange function.
  19292. if (this.loaderType_ === 'main') {
  19293. this.timelineChangeController_.on('pendingtimelinechange', () => {
  19294. if (this.hasEnoughInfoToAppend_()) {
  19295. this.processCallQueue_();
  19296. }
  19297. });
  19298. } // The main loader only listens on pending timeline changes, but the audio loader,
  19299. // since its loads follow main, needs to listen on timeline changes. For more details,
  19300. // see the shouldWaitForTimelineChange function.
  19301. if (this.loaderType_ === 'audio') {
  19302. this.timelineChangeController_.on('timelinechange', () => {
  19303. if (this.hasEnoughInfoToLoad_()) {
  19304. this.processLoadQueue_();
  19305. }
  19306. if (this.hasEnoughInfoToAppend_()) {
  19307. this.processCallQueue_();
  19308. }
  19309. });
  19310. }
  19311. }
  19312. createTransmuxer_() {
  19313. return segmentTransmuxer.createTransmuxer({
  19314. remux: false,
  19315. alignGopsAtEnd: this.safeAppend_,
  19316. keepOriginalTimestamps: true,
  19317. parse708captions: this.parse708captions_,
  19318. captionServices: this.captionServices_
  19319. });
  19320. }
  19321. /**
  19322. * reset all of our media stats
  19323. *
  19324. * @private
  19325. */
  19326. resetStats_() {
  19327. this.mediaBytesTransferred = 0;
  19328. this.mediaRequests = 0;
  19329. this.mediaRequestsAborted = 0;
  19330. this.mediaRequestsTimedout = 0;
  19331. this.mediaRequestsErrored = 0;
  19332. this.mediaTransferDuration = 0;
  19333. this.mediaSecondsLoaded = 0;
  19334. this.mediaAppends = 0;
  19335. }
  19336. /**
  19337. * dispose of the SegmentLoader and reset to the default state
  19338. */
  19339. dispose() {
  19340. this.trigger('dispose');
  19341. this.state = 'DISPOSED';
  19342. this.pause();
  19343. this.abort_();
  19344. if (this.transmuxer_) {
  19345. this.transmuxer_.terminate();
  19346. }
  19347. this.resetStats_();
  19348. if (this.checkBufferTimeout_) {
  19349. window.clearTimeout(this.checkBufferTimeout_);
  19350. }
  19351. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  19352. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  19353. }
  19354. this.off();
  19355. }
  19356. setAudio(enable) {
  19357. this.audioDisabled_ = !enable;
  19358. if (enable) {
  19359. this.appendInitSegment_.audio = true;
  19360. } else {
  19361. // remove current track audio if it gets disabled
  19362. this.sourceUpdater_.removeAudio(0, this.duration_());
  19363. }
  19364. }
  19365. /**
  19366. * abort anything that is currently doing on with the SegmentLoader
  19367. * and reset to a default state
  19368. */
  19369. abort() {
  19370. if (this.state !== 'WAITING') {
  19371. if (this.pendingSegment_) {
  19372. this.pendingSegment_ = null;
  19373. }
  19374. return;
  19375. }
  19376. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  19377. // since we are no longer "waiting" on any requests. XHR callback is not always run
  19378. // when the request is aborted. This will prevent the loader from being stuck in the
  19379. // WAITING state indefinitely.
  19380. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  19381. // next segment
  19382. if (!this.paused()) {
  19383. this.monitorBuffer_();
  19384. }
  19385. }
  19386. /**
  19387. * abort all pending xhr requests and null any pending segements
  19388. *
  19389. * @private
  19390. */
  19391. abort_() {
  19392. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  19393. this.pendingSegment_.abortRequests();
  19394. } // clear out the segment being processed
  19395. this.pendingSegment_ = null;
  19396. this.callQueue_ = [];
  19397. this.loadQueue_ = [];
  19398. this.metadataQueue_.id3 = [];
  19399. this.metadataQueue_.caption = [];
  19400. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  19401. this.waitingOnRemove_ = false;
  19402. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  19403. this.quotaExceededErrorRetryTimeout_ = null;
  19404. }
  19405. checkForAbort_(requestId) {
  19406. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  19407. // callback that happens should reset the state to READY so that loading can continue.
  19408. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  19409. this.state = 'READY';
  19410. return true;
  19411. }
  19412. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  19413. return true;
  19414. }
  19415. return false;
  19416. }
  19417. /**
  19418. * set an error on the segment loader and null out any pending segements
  19419. *
  19420. * @param {Error} error the error to set on the SegmentLoader
  19421. * @return {Error} the error that was set or that is currently set
  19422. */
  19423. error(error) {
  19424. if (typeof error !== 'undefined') {
  19425. this.logger_('error occurred:', error);
  19426. this.error_ = error;
  19427. }
  19428. this.pendingSegment_ = null;
  19429. return this.error_;
  19430. }
  19431. endOfStream() {
  19432. this.ended_ = true;
  19433. if (this.transmuxer_) {
  19434. // need to clear out any cached data to prepare for the new segment
  19435. segmentTransmuxer.reset(this.transmuxer_);
  19436. }
  19437. this.gopBuffer_.length = 0;
  19438. this.pause();
  19439. this.trigger('ended');
  19440. }
  19441. /**
  19442. * Indicates which time ranges are buffered
  19443. *
  19444. * @return {TimeRange}
  19445. * TimeRange object representing the current buffered ranges
  19446. */
  19447. buffered_() {
  19448. const trackInfo = this.getMediaInfo_();
  19449. if (!this.sourceUpdater_ || !trackInfo) {
  19450. return createTimeRanges();
  19451. }
  19452. if (this.loaderType_ === 'main') {
  19453. const {
  19454. hasAudio,
  19455. hasVideo,
  19456. isMuxed
  19457. } = trackInfo;
  19458. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  19459. return this.sourceUpdater_.buffered();
  19460. }
  19461. if (hasVideo) {
  19462. return this.sourceUpdater_.videoBuffered();
  19463. }
  19464. } // One case that can be ignored for now is audio only with alt audio,
  19465. // as we don't yet have proper support for that.
  19466. return this.sourceUpdater_.audioBuffered();
  19467. }
  19468. /**
  19469. * Gets and sets init segment for the provided map
  19470. *
  19471. * @param {Object} map
  19472. * The map object representing the init segment to get or set
  19473. * @param {boolean=} set
  19474. * If true, the init segment for the provided map should be saved
  19475. * @return {Object}
  19476. * map object for desired init segment
  19477. */
  19478. initSegmentForMap(map, set = false) {
  19479. if (!map) {
  19480. return null;
  19481. }
  19482. const id = initSegmentId(map);
  19483. let storedMap = this.initSegments_[id];
  19484. if (set && !storedMap && map.bytes) {
  19485. this.initSegments_[id] = storedMap = {
  19486. resolvedUri: map.resolvedUri,
  19487. byterange: map.byterange,
  19488. bytes: map.bytes,
  19489. tracks: map.tracks,
  19490. timescales: map.timescales
  19491. };
  19492. }
  19493. return storedMap || map;
  19494. }
  19495. /**
  19496. * Gets and sets key for the provided key
  19497. *
  19498. * @param {Object} key
  19499. * The key object representing the key to get or set
  19500. * @param {boolean=} set
  19501. * If true, the key for the provided key should be saved
  19502. * @return {Object}
  19503. * Key object for desired key
  19504. */
  19505. segmentKey(key, set = false) {
  19506. if (!key) {
  19507. return null;
  19508. }
  19509. const id = segmentKeyId(key);
  19510. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  19511. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  19512. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  19513. this.keyCache_[id] = storedKey = {
  19514. resolvedUri: key.resolvedUri,
  19515. bytes: key.bytes
  19516. };
  19517. }
  19518. const result = {
  19519. resolvedUri: (storedKey || key).resolvedUri
  19520. };
  19521. if (storedKey) {
  19522. result.bytes = storedKey.bytes;
  19523. }
  19524. return result;
  19525. }
  19526. /**
  19527. * Returns true if all configuration required for loading is present, otherwise false.
  19528. *
  19529. * @return {boolean} True if the all configuration is ready for loading
  19530. * @private
  19531. */
  19532. couldBeginLoading_() {
  19533. return this.playlist_ && !this.paused();
  19534. }
  19535. /**
  19536. * load a playlist and start to fill the buffer
  19537. */
  19538. load() {
  19539. // un-pause
  19540. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  19541. // specified
  19542. if (!this.playlist_) {
  19543. return;
  19544. } // if all the configuration is ready, initialize and begin loading
  19545. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  19546. return this.init_();
  19547. } // if we're in the middle of processing a segment already, don't
  19548. // kick off an additional segment request
  19549. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  19550. return;
  19551. }
  19552. this.state = 'READY';
  19553. }
  19554. /**
  19555. * Once all the starting parameters have been specified, begin
  19556. * operation. This method should only be invoked from the INIT
  19557. * state.
  19558. *
  19559. * @private
  19560. */
  19561. init_() {
  19562. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  19563. // audio data from the muxed content should be removed
  19564. this.resetEverything();
  19565. return this.monitorBuffer_();
  19566. }
  19567. /**
  19568. * set a playlist on the segment loader
  19569. *
  19570. * @param {PlaylistLoader} media the playlist to set on the segment loader
  19571. */
  19572. playlist(newPlaylist, options = {}) {
  19573. if (!newPlaylist) {
  19574. return;
  19575. }
  19576. const oldPlaylist = this.playlist_;
  19577. const segmentInfo = this.pendingSegment_;
  19578. this.playlist_ = newPlaylist;
  19579. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  19580. // is always our zero-time so force a sync update each time the playlist
  19581. // is refreshed from the server
  19582. //
  19583. // Use the INIT state to determine if playback has started, as the playlist sync info
  19584. // should be fixed once requests begin (as sync points are generated based on sync
  19585. // info), but not before then.
  19586. if (this.state === 'INIT') {
  19587. newPlaylist.syncInfo = {
  19588. mediaSequence: newPlaylist.mediaSequence,
  19589. time: 0
  19590. }; // Setting the date time mapping means mapping the program date time (if available)
  19591. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  19592. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  19593. // be updated as the playlist is refreshed before the loader starts loading, the
  19594. // program date time mapping needs to be updated as well.
  19595. //
  19596. // This mapping is only done for the main loader because a program date time should
  19597. // map equivalently between playlists.
  19598. if (this.loaderType_ === 'main') {
  19599. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  19600. }
  19601. }
  19602. let oldId = null;
  19603. if (oldPlaylist) {
  19604. if (oldPlaylist.id) {
  19605. oldId = oldPlaylist.id;
  19606. } else if (oldPlaylist.uri) {
  19607. oldId = oldPlaylist.uri;
  19608. }
  19609. }
  19610. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`);
  19611. this.syncController_.updateMediaSequenceMap(newPlaylist, this.currentTime_(), this.loaderType_); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  19612. // in LIVE, we always want to update with new playlists (including refreshes)
  19613. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  19614. // buffering now
  19615. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  19616. return this.init_();
  19617. }
  19618. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  19619. if (this.mediaIndex !== null) {
  19620. // we must reset/resync the segment loader when we switch renditions and
  19621. // the segment loader is already synced to the previous rendition
  19622. // We only want to reset the loader here for LLHLS playback, as resetLoader sets fetchAtBuffer_
  19623. // to false, resulting in fetching segments at currentTime and causing repeated
  19624. // same-segment requests on playlist change. This erroneously drives up the playback watcher
  19625. // stalled segment count, as re-requesting segments at the currentTime or browser cached segments
  19626. // will not change the buffer.
  19627. // Reference for LLHLS fixes: https://github.com/videojs/http-streaming/pull/1201
  19628. const isLLHLS = !newPlaylist.endList && typeof newPlaylist.partTargetDuration === 'number';
  19629. if (isLLHLS) {
  19630. this.resetLoader();
  19631. } else {
  19632. this.resyncLoader();
  19633. }
  19634. }
  19635. this.currentMediaInfo_ = void 0;
  19636. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  19637. return;
  19638. } // we reloaded the same playlist so we are in a live scenario
  19639. // and we will likely need to adjust the mediaIndex
  19640. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  19641. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  19642. // this is important because we can abort a request and this value must be
  19643. // equal to the last appended mediaIndex
  19644. if (this.mediaIndex !== null) {
  19645. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  19646. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  19647. // new playlist was incremented by 1.
  19648. if (this.mediaIndex < 0) {
  19649. this.mediaIndex = null;
  19650. this.partIndex = null;
  19651. } else {
  19652. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  19653. // unless parts fell off of the playlist for this segment.
  19654. // In that case we need to reset partIndex and resync
  19655. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  19656. const mediaIndex = this.mediaIndex;
  19657. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  19658. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  19659. // as the part was dropped from our current playlists segment.
  19660. // The mediaIndex will still be valid so keep that around.
  19661. this.mediaIndex = mediaIndex;
  19662. }
  19663. }
  19664. } // update the mediaIndex on the SegmentInfo object
  19665. // this is important because we will update this.mediaIndex with this value
  19666. // in `handleAppendsDone_` after the segment has been successfully appended
  19667. if (segmentInfo) {
  19668. segmentInfo.mediaIndex -= mediaSequenceDiff;
  19669. if (segmentInfo.mediaIndex < 0) {
  19670. segmentInfo.mediaIndex = null;
  19671. segmentInfo.partIndex = null;
  19672. } else {
  19673. // we need to update the referenced segment so that timing information is
  19674. // saved for the new playlist's segment, however, if the segment fell off the
  19675. // playlist, we can leave the old reference and just lose the timing info
  19676. if (segmentInfo.mediaIndex >= 0) {
  19677. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  19678. }
  19679. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  19680. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  19681. }
  19682. }
  19683. }
  19684. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  19685. }
  19686. /**
  19687. * Prevent the loader from fetching additional segments. If there
  19688. * is a segment request outstanding, it will finish processing
  19689. * before the loader halts. A segment loader can be unpaused by
  19690. * calling load().
  19691. */
  19692. pause() {
  19693. if (this.checkBufferTimeout_) {
  19694. window.clearTimeout(this.checkBufferTimeout_);
  19695. this.checkBufferTimeout_ = null;
  19696. }
  19697. }
  19698. /**
  19699. * Returns whether the segment loader is fetching additional
  19700. * segments when given the opportunity. This property can be
  19701. * modified through calls to pause() and load().
  19702. */
  19703. paused() {
  19704. return this.checkBufferTimeout_ === null;
  19705. }
  19706. /**
  19707. * Delete all the buffered data and reset the SegmentLoader
  19708. *
  19709. * @param {Function} [done] an optional callback to be executed when the remove
  19710. * operation is complete
  19711. */
  19712. resetEverything(done) {
  19713. this.ended_ = false;
  19714. this.activeInitSegmentId_ = null;
  19715. this.appendInitSegment_ = {
  19716. audio: true,
  19717. video: true
  19718. };
  19719. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  19720. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  19721. // we then clamp the value to duration if necessary.
  19722. this.remove(0, Infinity, done); // clears fmp4 captions
  19723. if (this.transmuxer_) {
  19724. this.transmuxer_.postMessage({
  19725. action: 'clearAllMp4Captions'
  19726. }); // reset the cache in the transmuxer
  19727. this.transmuxer_.postMessage({
  19728. action: 'reset'
  19729. });
  19730. }
  19731. }
  19732. /**
  19733. * Force the SegmentLoader to resync and start loading around the currentTime instead
  19734. * of starting at the end of the buffer
  19735. *
  19736. * Useful for fast quality changes
  19737. */
  19738. resetLoader() {
  19739. this.fetchAtBuffer_ = false;
  19740. this.resyncLoader();
  19741. }
  19742. /**
  19743. * Force the SegmentLoader to restart synchronization and make a conservative guess
  19744. * before returning to the simple walk-forward method
  19745. */
  19746. resyncLoader() {
  19747. if (this.transmuxer_) {
  19748. // need to clear out any cached data to prepare for the new segment
  19749. segmentTransmuxer.reset(this.transmuxer_);
  19750. }
  19751. this.mediaIndex = null;
  19752. this.partIndex = null;
  19753. this.syncPoint_ = null;
  19754. this.isPendingTimestampOffset_ = false;
  19755. this.shouldForceTimestampOffsetAfterResync_ = true;
  19756. this.callQueue_ = [];
  19757. this.loadQueue_ = [];
  19758. this.metadataQueue_.id3 = [];
  19759. this.metadataQueue_.caption = [];
  19760. this.abort();
  19761. if (this.transmuxer_) {
  19762. this.transmuxer_.postMessage({
  19763. action: 'clearParsedMp4Captions'
  19764. });
  19765. }
  19766. }
  19767. /**
  19768. * Remove any data in the source buffer between start and end times
  19769. *
  19770. * @param {number} start - the start time of the region to remove from the buffer
  19771. * @param {number} end - the end time of the region to remove from the buffer
  19772. * @param {Function} [done] - an optional callback to be executed when the remove
  19773. * @param {boolean} force - force all remove operations to happen
  19774. * operation is complete
  19775. */
  19776. remove(start, end, done = () => {}, force = false) {
  19777. // clamp end to duration if we need to remove everything.
  19778. // This is due to a browser bug that causes issues if we remove to Infinity.
  19779. // videojs/videojs-contrib-hls#1225
  19780. if (end === Infinity) {
  19781. end = this.duration_();
  19782. } // skip removes that would throw an error
  19783. // commonly happens during a rendition switch at the start of a video
  19784. // from start 0 to end 0
  19785. if (end <= start) {
  19786. this.logger_('skipping remove because end ${end} is <= start ${start}');
  19787. return;
  19788. }
  19789. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  19790. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  19791. return;
  19792. } // set it to one to complete this function's removes
  19793. let removesRemaining = 1;
  19794. const removeFinished = () => {
  19795. removesRemaining--;
  19796. if (removesRemaining === 0) {
  19797. done();
  19798. }
  19799. };
  19800. if (force || !this.audioDisabled_) {
  19801. removesRemaining++;
  19802. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  19803. } // While it would be better to only remove video if the main loader has video, this
  19804. // should be safe with audio only as removeVideo will call back even if there's no
  19805. // video buffer.
  19806. //
  19807. // In theory we can check to see if there's video before calling the remove, but in
  19808. // the event that we're switching between renditions and from video to audio only
  19809. // (when we add support for that), we may need to clear the video contents despite
  19810. // what the new media will contain.
  19811. if (force || this.loaderType_ === 'main') {
  19812. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  19813. removesRemaining++;
  19814. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  19815. } // remove any captions and ID3 tags
  19816. for (const track in this.inbandTextTracks_) {
  19817. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  19818. }
  19819. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  19820. removeFinished();
  19821. }
  19822. /**
  19823. * (re-)schedule monitorBufferTick_ to run as soon as possible
  19824. *
  19825. * @private
  19826. */
  19827. monitorBuffer_() {
  19828. if (this.checkBufferTimeout_) {
  19829. window.clearTimeout(this.checkBufferTimeout_);
  19830. }
  19831. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  19832. }
  19833. /**
  19834. * As long as the SegmentLoader is in the READY state, periodically
  19835. * invoke fillBuffer_().
  19836. *
  19837. * @private
  19838. */
  19839. monitorBufferTick_() {
  19840. if (this.state === 'READY') {
  19841. this.fillBuffer_();
  19842. }
  19843. if (this.checkBufferTimeout_) {
  19844. window.clearTimeout(this.checkBufferTimeout_);
  19845. }
  19846. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  19847. }
  19848. /**
  19849. * fill the buffer with segements unless the sourceBuffers are
  19850. * currently updating
  19851. *
  19852. * Note: this function should only ever be called by monitorBuffer_
  19853. * and never directly
  19854. *
  19855. * @private
  19856. */
  19857. fillBuffer_() {
  19858. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  19859. // except when we're ready for the next segment, this check can most likely be removed
  19860. if (this.sourceUpdater_.updating()) {
  19861. return;
  19862. } // see if we need to begin loading immediately
  19863. const segmentInfo = this.chooseNextRequest_();
  19864. if (!segmentInfo) {
  19865. return;
  19866. }
  19867. if (typeof segmentInfo.timestampOffset === 'number') {
  19868. this.isPendingTimestampOffset_ = false;
  19869. this.timelineChangeController_.pendingTimelineChange({
  19870. type: this.loaderType_,
  19871. from: this.currentTimeline_,
  19872. to: segmentInfo.timeline
  19873. });
  19874. }
  19875. this.loadSegment_(segmentInfo);
  19876. }
  19877. /**
  19878. * Determines if we should call endOfStream on the media source based
  19879. * on the state of the buffer or if appened segment was the final
  19880. * segment in the playlist.
  19881. *
  19882. * @param {number} [mediaIndex] the media index of segment we last appended
  19883. * @param {Object} [playlist] a media playlist object
  19884. * @return {boolean} do we need to call endOfStream on the MediaSource
  19885. */
  19886. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  19887. if (!playlist || !this.mediaSource_) {
  19888. return false;
  19889. }
  19890. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  19891. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  19892. 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
  19893. // so that MediaSources can trigger the `ended` event when it runs out of
  19894. // buffered data instead of waiting for me
  19895. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  19896. }
  19897. /**
  19898. * Determines what request should be made given current segment loader state.
  19899. *
  19900. * @return {Object} a request object that describes the segment/part to load
  19901. */
  19902. chooseNextRequest_() {
  19903. const buffered = this.buffered_();
  19904. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  19905. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  19906. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  19907. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  19908. const segments = this.playlist_.segments; // return no segment if:
  19909. // 1. we don't have segments
  19910. // 2. The video has not yet played and we already downloaded a segment
  19911. // 3. we already have enough buffered time
  19912. if (!segments.length || preloaded || haveEnoughBuffer) {
  19913. return null;
  19914. }
  19915. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_(), this.loaderType_);
  19916. const next = {
  19917. partIndex: null,
  19918. mediaIndex: null,
  19919. startOfSegment: null,
  19920. playlist: this.playlist_,
  19921. isSyncRequest: Boolean(!this.syncPoint_)
  19922. };
  19923. if (next.isSyncRequest) {
  19924. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  19925. this.logger_(`choose next request. Can not find sync point. Fallback to media Index: ${next.mediaIndex}`);
  19926. } else if (this.mediaIndex !== null) {
  19927. const segment = segments[this.mediaIndex];
  19928. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  19929. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  19930. if (segment.parts && segment.parts[partIndex + 1]) {
  19931. next.mediaIndex = this.mediaIndex;
  19932. next.partIndex = partIndex + 1;
  19933. } else {
  19934. next.mediaIndex = this.mediaIndex + 1;
  19935. }
  19936. } else {
  19937. // Find the segment containing the end of the buffer or current time.
  19938. const {
  19939. segmentIndex,
  19940. startTime,
  19941. partIndex
  19942. } = Playlist.getMediaInfoForTime({
  19943. exactManifestTimings: this.exactManifestTimings,
  19944. playlist: this.playlist_,
  19945. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  19946. startingPartIndex: this.syncPoint_.partIndex,
  19947. startingSegmentIndex: this.syncPoint_.segmentIndex,
  19948. startTime: this.syncPoint_.time
  19949. });
  19950. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  19951. next.mediaIndex = segmentIndex;
  19952. next.startOfSegment = startTime;
  19953. next.partIndex = partIndex;
  19954. this.logger_(`choose next request. Playlist switched and we have a sync point. Media Index: ${next.mediaIndex} `);
  19955. }
  19956. const nextSegment = segments[next.mediaIndex];
  19957. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  19958. // the next partIndex is invalid do not choose a next segment.
  19959. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  19960. return null;
  19961. } // if the next segment has parts, and we don't have a partIndex.
  19962. // Set partIndex to 0
  19963. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  19964. next.partIndex = 0;
  19965. nextPart = nextSegment.parts[0];
  19966. } // independentSegments applies to every segment in a playlist. If independentSegments appears in a main playlist,
  19967. // it applies to each segment in each media playlist.
  19968. // https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-23#section-4.3.5.1
  19969. const hasIndependentSegments = this.vhs_.playlists && this.vhs_.playlists.main && this.vhs_.playlists.main.independentSegments || this.playlist_.independentSegments; // if we have no buffered data then we need to make sure
  19970. // that the next part we append is "independent" if possible.
  19971. // So we check if the previous part is independent, and request
  19972. // it if it is.
  19973. if (!bufferedTime && nextPart && !hasIndependentSegments && !nextPart.independent) {
  19974. if (next.partIndex === 0) {
  19975. const lastSegment = segments[next.mediaIndex - 1];
  19976. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  19977. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  19978. next.mediaIndex -= 1;
  19979. next.partIndex = lastSegment.parts.length - 1;
  19980. next.independent = 'previous segment';
  19981. }
  19982. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  19983. next.partIndex -= 1;
  19984. next.independent = 'previous part';
  19985. }
  19986. }
  19987. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  19988. // 1. this is the last segment in the playlist
  19989. // 2. end of stream has been called on the media source already
  19990. // 3. the player is not seeking
  19991. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  19992. return null;
  19993. }
  19994. if (this.shouldForceTimestampOffsetAfterResync_) {
  19995. this.shouldForceTimestampOffsetAfterResync_ = false;
  19996. next.forceTimestampOffset = true;
  19997. this.logger_('choose next request. Force timestamp offset after loader resync');
  19998. }
  19999. return this.generateSegmentInfo_(next);
  20000. }
  20001. generateSegmentInfo_(options) {
  20002. const {
  20003. independent,
  20004. playlist,
  20005. mediaIndex,
  20006. startOfSegment,
  20007. isSyncRequest,
  20008. partIndex,
  20009. forceTimestampOffset,
  20010. getMediaInfoForTime
  20011. } = options;
  20012. const segment = playlist.segments[mediaIndex];
  20013. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  20014. const segmentInfo = {
  20015. requestId: 'segment-loader-' + Math.random(),
  20016. // resolve the segment URL relative to the playlist
  20017. uri: part && part.resolvedUri || segment.resolvedUri,
  20018. // the segment's mediaIndex at the time it was requested
  20019. mediaIndex,
  20020. partIndex: part ? partIndex : null,
  20021. // whether or not to update the SegmentLoader's state with this
  20022. // segment's mediaIndex
  20023. isSyncRequest,
  20024. startOfSegment,
  20025. // the segment's playlist
  20026. playlist,
  20027. // unencrypted bytes of the segment
  20028. bytes: null,
  20029. // when a key is defined for this segment, the encrypted bytes
  20030. encryptedBytes: null,
  20031. // The target timestampOffset for this segment when we append it
  20032. // to the source buffer
  20033. timestampOffset: null,
  20034. // The timeline that the segment is in
  20035. timeline: segment.timeline,
  20036. // The expected duration of the segment in seconds
  20037. duration: part && part.duration || segment.duration,
  20038. // retain the segment in case the playlist updates while doing an async process
  20039. segment,
  20040. part,
  20041. byteLength: 0,
  20042. transmuxer: this.transmuxer_,
  20043. // type of getMediaInfoForTime that was used to get this segment
  20044. getMediaInfoForTime,
  20045. independent
  20046. };
  20047. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  20048. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  20049. segmentTimeline: segment.timeline,
  20050. currentTimeline: this.currentTimeline_,
  20051. startOfSegment,
  20052. buffered: this.buffered_(),
  20053. overrideCheck
  20054. });
  20055. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  20056. if (typeof audioBufferedEnd === 'number') {
  20057. // since the transmuxer is using the actual timing values, but the buffer is
  20058. // adjusted by the timestamp offset, we must adjust the value here
  20059. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  20060. }
  20061. if (this.sourceUpdater_.videoBuffered().length) {
  20062. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  20063. // adjusted by the timestmap offset, we must adjust the value here
  20064. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  20065. }
  20066. return segmentInfo;
  20067. } // get the timestampoffset for a segment,
  20068. // added so that vtt segment loader can override and prevent
  20069. // adding timestamp offsets.
  20070. timestampOffsetForSegment_(options) {
  20071. return timestampOffsetForSegment(options);
  20072. }
  20073. /**
  20074. * Determines if the network has enough bandwidth to complete the current segment
  20075. * request in a timely manner. If not, the request will be aborted early and bandwidth
  20076. * updated to trigger a playlist switch.
  20077. *
  20078. * @param {Object} stats
  20079. * Object containing stats about the request timing and size
  20080. * @private
  20081. */
  20082. earlyAbortWhenNeeded_(stats) {
  20083. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  20084. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  20085. // the lowestEnabledRendition.
  20086. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  20087. !this.playlist_.attributes.BANDWIDTH) {
  20088. return;
  20089. } // Wait at least 1 second since the first byte of data has been received before
  20090. // using the calculated bandwidth from the progress event to allow the bitrate
  20091. // to stabilize
  20092. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  20093. return;
  20094. }
  20095. const currentTime = this.currentTime_();
  20096. const measuredBandwidth = stats.bandwidth;
  20097. const segmentDuration = this.pendingSegment_.duration;
  20098. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  20099. // if we are only left with less than 1 second when the request completes.
  20100. // A negative timeUntilRebuffering indicates we are already rebuffering
  20101. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  20102. // is larger than the estimated time until the player runs out of forward buffer
  20103. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  20104. return;
  20105. }
  20106. const switchCandidate = minRebufferMaxBandwidthSelector({
  20107. main: this.vhs_.playlists.main,
  20108. currentTime,
  20109. bandwidth: measuredBandwidth,
  20110. duration: this.duration_(),
  20111. segmentDuration,
  20112. timeUntilRebuffer: timeUntilRebuffer$1,
  20113. currentTimeline: this.currentTimeline_,
  20114. syncController: this.syncController_
  20115. });
  20116. if (!switchCandidate) {
  20117. return;
  20118. }
  20119. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  20120. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  20121. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  20122. // potential round trip time of the new request so that we are not too aggressive
  20123. // with switching to a playlist that might save us a fraction of a second.
  20124. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  20125. minimumTimeSaving = 1;
  20126. }
  20127. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  20128. return;
  20129. } // set the bandwidth to that of the desired playlist being sure to scale by
  20130. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  20131. // don't trigger a bandwidthupdate as the bandwidth is artifial
  20132. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  20133. this.trigger('earlyabort');
  20134. }
  20135. handleAbort_(segmentInfo) {
  20136. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  20137. this.mediaRequestsAborted += 1;
  20138. }
  20139. /**
  20140. * XHR `progress` event handler
  20141. *
  20142. * @param {Event}
  20143. * The XHR `progress` event
  20144. * @param {Object} simpleSegment
  20145. * A simplified segment object copy
  20146. * @private
  20147. */
  20148. handleProgress_(event, simpleSegment) {
  20149. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20150. if (this.checkForAbort_(simpleSegment.requestId)) {
  20151. return;
  20152. }
  20153. this.trigger('progress');
  20154. }
  20155. handleTrackInfo_(simpleSegment, trackInfo) {
  20156. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20157. if (this.checkForAbort_(simpleSegment.requestId)) {
  20158. return;
  20159. }
  20160. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  20161. return;
  20162. }
  20163. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  20164. // Guard against cases where we're not getting track info at all until we are
  20165. // certain that all streams will provide it.
  20166. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  20167. this.appendInitSegment_ = {
  20168. audio: true,
  20169. video: true
  20170. };
  20171. this.startingMediaInfo_ = trackInfo;
  20172. this.currentMediaInfo_ = trackInfo;
  20173. this.logger_('trackinfo update', trackInfo);
  20174. this.trigger('trackinfo');
  20175. } // trackinfo may cause an abort if the trackinfo
  20176. // causes a codec change to an unsupported codec.
  20177. if (this.checkForAbort_(simpleSegment.requestId)) {
  20178. return;
  20179. } // set trackinfo on the pending segment so that
  20180. // it can append.
  20181. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  20182. if (this.hasEnoughInfoToAppend_()) {
  20183. this.processCallQueue_();
  20184. }
  20185. }
  20186. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  20187. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20188. if (this.checkForAbort_(simpleSegment.requestId)) {
  20189. return;
  20190. }
  20191. const segmentInfo = this.pendingSegment_;
  20192. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  20193. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  20194. segmentInfo[timingInfoProperty][timeType] = time;
  20195. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  20196. if (this.hasEnoughInfoToAppend_()) {
  20197. this.processCallQueue_();
  20198. }
  20199. }
  20200. handleCaptions_(simpleSegment, captionData) {
  20201. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20202. if (this.checkForAbort_(simpleSegment.requestId)) {
  20203. return;
  20204. } // This could only happen with fmp4 segments, but
  20205. // should still not happen in general
  20206. if (captionData.length === 0) {
  20207. this.logger_('SegmentLoader received no captions from a caption event');
  20208. return;
  20209. }
  20210. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  20211. // can be adjusted by the timestamp offset
  20212. if (!segmentInfo.hasAppendedData_) {
  20213. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  20214. return;
  20215. }
  20216. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  20217. const captionTracks = {}; // get total start/end and captions for each track/stream
  20218. captionData.forEach(caption => {
  20219. // caption.stream is actually a track name...
  20220. // set to the existing values in tracks or default values
  20221. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  20222. // Infinity, as any other value will be less than this
  20223. startTime: Infinity,
  20224. captions: [],
  20225. // 0 as an other value will be more than this
  20226. endTime: 0
  20227. };
  20228. const captionTrack = captionTracks[caption.stream];
  20229. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  20230. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  20231. captionTrack.captions.push(caption);
  20232. });
  20233. Object.keys(captionTracks).forEach(trackName => {
  20234. const {
  20235. startTime,
  20236. endTime,
  20237. captions
  20238. } = captionTracks[trackName];
  20239. const inbandTextTracks = this.inbandTextTracks_;
  20240. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  20241. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  20242. // We do this because a rendition change that also changes the timescale for captions
  20243. // will result in captions being re-parsed for certain segments. If we add them again
  20244. // without clearing we will have two of the same captions visible.
  20245. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  20246. addCaptionData({
  20247. captionArray: captions,
  20248. inbandTextTracks,
  20249. timestampOffset
  20250. });
  20251. }); // Reset stored captions since we added parsed
  20252. // captions to a text track at this point
  20253. if (this.transmuxer_) {
  20254. this.transmuxer_.postMessage({
  20255. action: 'clearParsedMp4Captions'
  20256. });
  20257. }
  20258. }
  20259. handleId3_(simpleSegment, id3Frames, dispatchType) {
  20260. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20261. if (this.checkForAbort_(simpleSegment.requestId)) {
  20262. return;
  20263. }
  20264. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  20265. if (!segmentInfo.hasAppendedData_) {
  20266. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  20267. return;
  20268. }
  20269. this.addMetadataToTextTrack(dispatchType, id3Frames, this.duration_());
  20270. }
  20271. processMetadataQueue_() {
  20272. this.metadataQueue_.id3.forEach(fn => fn());
  20273. this.metadataQueue_.caption.forEach(fn => fn());
  20274. this.metadataQueue_.id3 = [];
  20275. this.metadataQueue_.caption = [];
  20276. }
  20277. processCallQueue_() {
  20278. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  20279. // functions may check the length of the load queue and default to pushing themselves
  20280. // back onto the queue.
  20281. this.callQueue_ = [];
  20282. callQueue.forEach(fun => fun());
  20283. }
  20284. processLoadQueue_() {
  20285. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  20286. // functions may check the length of the load queue and default to pushing themselves
  20287. // back onto the queue.
  20288. this.loadQueue_ = [];
  20289. loadQueue.forEach(fun => fun());
  20290. }
  20291. /**
  20292. * Determines whether the loader has enough info to load the next segment.
  20293. *
  20294. * @return {boolean}
  20295. * Whether or not the loader has enough info to load the next segment
  20296. */
  20297. hasEnoughInfoToLoad_() {
  20298. // Since primary timing goes by video, only the audio loader potentially needs to wait
  20299. // to load.
  20300. if (this.loaderType_ !== 'audio') {
  20301. return true;
  20302. }
  20303. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  20304. // enough info to load.
  20305. if (!segmentInfo) {
  20306. return false;
  20307. } // The first segment can and should be loaded immediately so that source buffers are
  20308. // created together (before appending). Source buffer creation uses the presence of
  20309. // audio and video data to determine whether to create audio/video source buffers, and
  20310. // uses processed (transmuxed or parsed) media to determine the types required.
  20311. if (!this.getCurrentMediaInfo_()) {
  20312. return true;
  20313. }
  20314. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  20315. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  20316. // But in practice, there are a few reasons why it is better to wait until a loader
  20317. // is ready to append that segment before requesting and downloading:
  20318. //
  20319. // 1. Because audio and main loaders cross discontinuities together, if this loader
  20320. // is waiting for the other to catch up, then instead of requesting another
  20321. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  20322. // allotted to the loader currently behind.
  20323. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  20324. // is ready to be processed or not, isolating the queueing behavior to the loader.
  20325. // 3. The audio loader bases some of its segment properties on timing information
  20326. // provided by the main loader, meaning that, if the logic for waiting on
  20327. // processing was in media-segment-request, then it would also need to know how
  20328. // to re-generate the segment information after the main loader caught up.
  20329. shouldWaitForTimelineChange({
  20330. timelineChangeController: this.timelineChangeController_,
  20331. currentTimeline: this.currentTimeline_,
  20332. segmentTimeline: segmentInfo.timeline,
  20333. loaderType: this.loaderType_,
  20334. audioDisabled: this.audioDisabled_
  20335. })) {
  20336. return false;
  20337. }
  20338. return true;
  20339. }
  20340. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  20341. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  20342. }
  20343. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  20344. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  20345. }
  20346. getPendingSegmentPlaylist() {
  20347. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  20348. }
  20349. hasEnoughInfoToAppend_() {
  20350. if (!this.sourceUpdater_.ready()) {
  20351. return false;
  20352. } // If content needs to be removed or the loader is waiting on an append reattempt,
  20353. // then no additional content should be appended until the prior append is resolved.
  20354. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  20355. return false;
  20356. }
  20357. const segmentInfo = this.pendingSegment_;
  20358. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  20359. // we do not have information on this specific
  20360. // segment yet
  20361. if (!segmentInfo || !trackInfo) {
  20362. return false;
  20363. }
  20364. const {
  20365. hasAudio,
  20366. hasVideo,
  20367. isMuxed
  20368. } = trackInfo;
  20369. if (hasVideo && !segmentInfo.videoTimingInfo) {
  20370. return false;
  20371. } // muxed content only relies on video timing information for now.
  20372. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  20373. return false;
  20374. }
  20375. if (shouldWaitForTimelineChange({
  20376. timelineChangeController: this.timelineChangeController_,
  20377. currentTimeline: this.currentTimeline_,
  20378. segmentTimeline: segmentInfo.timeline,
  20379. loaderType: this.loaderType_,
  20380. audioDisabled: this.audioDisabled_
  20381. })) {
  20382. return false;
  20383. }
  20384. return true;
  20385. }
  20386. handleData_(simpleSegment, result) {
  20387. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  20388. if (this.checkForAbort_(simpleSegment.requestId)) {
  20389. return;
  20390. } // If there's anything in the call queue, then this data came later and should be
  20391. // executed after the calls currently queued.
  20392. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  20393. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  20394. return;
  20395. }
  20396. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  20397. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  20398. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  20399. // logic may change behavior depending on the state, and changing state too early may
  20400. // inflate our estimates of bandwidth. In the future this should be re-examined to
  20401. // note more granular states.
  20402. // don't process and append data if the mediaSource is closed
  20403. if (this.mediaSource_.readyState === 'closed') {
  20404. return;
  20405. } // if this request included an initialization segment, save that data
  20406. // to the initSegment cache
  20407. if (simpleSegment.map) {
  20408. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  20409. segmentInfo.segment.map = simpleSegment.map;
  20410. } // if this request included a segment key, save that data in the cache
  20411. if (simpleSegment.key) {
  20412. this.segmentKey(simpleSegment.key, true);
  20413. }
  20414. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  20415. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  20416. if (segmentInfo.isFmp4) {
  20417. this.trigger('fmp4');
  20418. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  20419. } else {
  20420. const trackInfo = this.getCurrentMediaInfo_();
  20421. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  20422. let firstVideoFrameTimeForData;
  20423. if (useVideoTimingInfo) {
  20424. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  20425. } // Segment loader knows more about segment timing than the transmuxer (in certain
  20426. // aspects), so make any changes required for a more accurate start time.
  20427. // Don't set the end time yet, as the segment may not be finished processing.
  20428. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  20429. currentStart: segmentInfo.timingInfo.start,
  20430. playlist: segmentInfo.playlist,
  20431. mediaIndex: segmentInfo.mediaIndex,
  20432. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  20433. useVideoTimingInfo,
  20434. firstVideoFrameTimeForData,
  20435. videoTimingInfo: segmentInfo.videoTimingInfo,
  20436. audioTimingInfo: segmentInfo.audioTimingInfo
  20437. });
  20438. } // Init segments for audio and video only need to be appended in certain cases. Now
  20439. // that data is about to be appended, we can check the final cases to determine
  20440. // whether we should append an init segment.
  20441. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  20442. // as we use the start of the segment to offset the best guess (playlist provided)
  20443. // timestamp offset.
  20444. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  20445. // be appended or not.
  20446. if (segmentInfo.isSyncRequest) {
  20447. // first save/update our timing info for this segment.
  20448. // this is what allows us to choose an accurate segment
  20449. // and the main reason we make a sync request.
  20450. this.updateTimingInfoEnd_(segmentInfo);
  20451. this.syncController_.saveSegmentTimingInfo({
  20452. segmentInfo,
  20453. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  20454. });
  20455. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  20456. // after taking into account its timing info, do not append it.
  20457. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  20458. this.logger_('sync segment was incorrect, not appending');
  20459. return;
  20460. } // otherwise append it like any other segment as our guess was correct.
  20461. this.logger_('sync segment was correct, appending');
  20462. } // Save some state so that in the future anything waiting on first append (and/or
  20463. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  20464. // we need some notion of whether the timestamp offset or other relevant information
  20465. // has had a chance to be set.
  20466. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  20467. this.processMetadataQueue_();
  20468. this.appendData_(segmentInfo, result);
  20469. }
  20470. updateAppendInitSegmentStatus(segmentInfo, type) {
  20471. // alt audio doesn't manage timestamp offset
  20472. 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
  20473. // segment for each chunk
  20474. !segmentInfo.changedTimestampOffset) {
  20475. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  20476. // append init segments
  20477. this.appendInitSegment_ = {
  20478. audio: true,
  20479. video: true
  20480. };
  20481. }
  20482. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  20483. // make sure we append init segment on playlist changes, in case the media config
  20484. // changed
  20485. this.appendInitSegment_[type] = true;
  20486. }
  20487. }
  20488. getInitSegmentAndUpdateState_({
  20489. type,
  20490. initSegment,
  20491. map,
  20492. playlist
  20493. }) {
  20494. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  20495. // (Section 3) required to parse the applicable Media Segments. It applies to every
  20496. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  20497. // or until the end of the playlist."
  20498. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  20499. if (map) {
  20500. const id = initSegmentId(map);
  20501. if (this.activeInitSegmentId_ === id) {
  20502. // don't need to re-append the init segment if the ID matches
  20503. return null;
  20504. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  20505. // obtained) init segment
  20506. //
  20507. // this also caches the init segment for later use
  20508. initSegment = this.initSegmentForMap(map, true).bytes;
  20509. this.activeInitSegmentId_ = id;
  20510. } // We used to always prepend init segments for video, however, that shouldn't be
  20511. // necessary. Instead, we should only append on changes, similar to what we've always
  20512. // done for audio. This is more important (though may not be that important) for
  20513. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  20514. // appends.
  20515. if (initSegment && this.appendInitSegment_[type]) {
  20516. // Make sure we track the playlist that we last used for the init segment, so that
  20517. // we can re-append the init segment in the event that we get data from a new
  20518. // playlist. Discontinuities and track changes are handled in other sections.
  20519. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  20520. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  20521. // we are appending the muxer init segment
  20522. this.activeInitSegmentId_ = null;
  20523. return initSegment;
  20524. }
  20525. return null;
  20526. }
  20527. handleQuotaExceededError_({
  20528. segmentInfo,
  20529. type,
  20530. bytes
  20531. }, error) {
  20532. const audioBuffered = this.sourceUpdater_.audioBuffered();
  20533. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  20534. // should be cleared out during the buffer removals. However, log in case it helps
  20535. // debug.
  20536. if (audioBuffered.length > 1) {
  20537. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  20538. }
  20539. if (videoBuffered.length > 1) {
  20540. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  20541. }
  20542. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  20543. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  20544. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  20545. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  20546. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  20547. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  20548. // allow for appends of segments this size). In the future, it may be possible to
  20549. // split up the segment and append in pieces, but for now, error out this playlist
  20550. // in an attempt to switch to a more manageable rendition.
  20551. 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(', ')}, `);
  20552. this.error({
  20553. message: 'Quota exceeded error with append of a single segment of content',
  20554. excludeUntil: Infinity
  20555. });
  20556. this.trigger('error');
  20557. return;
  20558. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  20559. // that the segment-loader should block on future events until this one is handled, so
  20560. // that it doesn't keep moving onto further segments. Adding the call to the call
  20561. // queue will prevent further appends until waitingOnRemove_ and
  20562. // quotaExceededErrorRetryTimeout_ are cleared.
  20563. //
  20564. // Note that this will only block the current loader. In the case of demuxed content,
  20565. // the other load may keep filling as fast as possible. In practice, this should be
  20566. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  20567. // source buffer, or video fills without enough room for audio to append (and without
  20568. // the availability of clearing out seconds of back buffer to make room for audio).
  20569. // But it might still be good to handle this case in the future as a TODO.
  20570. this.waitingOnRemove_ = true;
  20571. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  20572. segmentInfo,
  20573. type,
  20574. bytes
  20575. }));
  20576. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  20577. // before retrying.
  20578. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  20579. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  20580. this.remove(0, timeToRemoveUntil, () => {
  20581. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  20582. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  20583. // attempts (since we can't clear less than the minimum)
  20584. this.quotaExceededErrorRetryTimeout_ = window.setTimeout(() => {
  20585. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  20586. this.quotaExceededErrorRetryTimeout_ = null;
  20587. this.processCallQueue_();
  20588. }, MIN_BACK_BUFFER * 1000);
  20589. }, true);
  20590. }
  20591. handleAppendError_({
  20592. segmentInfo,
  20593. type,
  20594. bytes
  20595. }, error) {
  20596. // if there's no error, nothing to do
  20597. if (!error) {
  20598. return;
  20599. }
  20600. if (error.code === QUOTA_EXCEEDED_ERR) {
  20601. this.handleQuotaExceededError_({
  20602. segmentInfo,
  20603. type,
  20604. bytes
  20605. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  20606. // to trigger an append error.
  20607. return;
  20608. }
  20609. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  20610. 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.
  20611. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  20612. //
  20613. // Trigger a special error so that it can be handled separately from normal,
  20614. // recoverable errors.
  20615. this.trigger('appenderror');
  20616. }
  20617. appendToSourceBuffer_({
  20618. segmentInfo,
  20619. type,
  20620. initSegment,
  20621. data,
  20622. bytes
  20623. }) {
  20624. // If this is a re-append, bytes were already created and don't need to be recreated
  20625. if (!bytes) {
  20626. const segments = [data];
  20627. let byteLength = data.byteLength;
  20628. if (initSegment) {
  20629. // if the media initialization segment is changing, append it before the content
  20630. // segment
  20631. segments.unshift(initSegment);
  20632. byteLength += initSegment.byteLength;
  20633. } // Technically we should be OK appending the init segment separately, however, we
  20634. // haven't yet tested that, and prepending is how we have always done things.
  20635. bytes = concatSegments({
  20636. bytes: byteLength,
  20637. segments
  20638. });
  20639. }
  20640. this.sourceUpdater_.appendBuffer({
  20641. segmentInfo,
  20642. type,
  20643. bytes
  20644. }, this.handleAppendError_.bind(this, {
  20645. segmentInfo,
  20646. type,
  20647. bytes
  20648. }));
  20649. }
  20650. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  20651. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  20652. return;
  20653. }
  20654. const segment = this.pendingSegment_.segment;
  20655. const timingInfoProperty = `${type}TimingInfo`;
  20656. if (!segment[timingInfoProperty]) {
  20657. segment[timingInfoProperty] = {};
  20658. }
  20659. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  20660. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  20661. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  20662. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  20663. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  20664. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  20665. }
  20666. appendData_(segmentInfo, result) {
  20667. const {
  20668. type,
  20669. data
  20670. } = result;
  20671. if (!data || !data.byteLength) {
  20672. return;
  20673. }
  20674. if (type === 'audio' && this.audioDisabled_) {
  20675. return;
  20676. }
  20677. const initSegment = this.getInitSegmentAndUpdateState_({
  20678. type,
  20679. initSegment: result.initSegment,
  20680. playlist: segmentInfo.playlist,
  20681. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  20682. });
  20683. this.appendToSourceBuffer_({
  20684. segmentInfo,
  20685. type,
  20686. initSegment,
  20687. data
  20688. });
  20689. }
  20690. /**
  20691. * load a specific segment from a request into the buffer
  20692. *
  20693. * @private
  20694. */
  20695. loadSegment_(segmentInfo) {
  20696. this.state = 'WAITING';
  20697. this.pendingSegment_ = segmentInfo;
  20698. this.trimBackBuffer_(segmentInfo);
  20699. if (typeof segmentInfo.timestampOffset === 'number') {
  20700. if (this.transmuxer_) {
  20701. this.transmuxer_.postMessage({
  20702. action: 'clearAllMp4Captions'
  20703. });
  20704. }
  20705. }
  20706. if (!this.hasEnoughInfoToLoad_()) {
  20707. this.loadQueue_.push(() => {
  20708. // regenerate the audioAppendStart, timestampOffset, etc as they
  20709. // may have changed since this function was added to the queue.
  20710. const options = _extends({}, segmentInfo, {
  20711. forceTimestampOffset: true
  20712. });
  20713. _extends(segmentInfo, this.generateSegmentInfo_(options));
  20714. this.isPendingTimestampOffset_ = false;
  20715. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  20716. });
  20717. return;
  20718. }
  20719. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  20720. }
  20721. updateTransmuxerAndRequestSegment_(segmentInfo) {
  20722. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  20723. // the transmuxer still needs to be updated before then.
  20724. //
  20725. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  20726. // offset must be passed to the transmuxer for stream correcting adjustments.
  20727. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  20728. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  20729. segmentInfo.gopsToAlignWith = [];
  20730. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  20731. this.transmuxer_.postMessage({
  20732. action: 'reset'
  20733. });
  20734. this.transmuxer_.postMessage({
  20735. action: 'setTimestampOffset',
  20736. timestampOffset: segmentInfo.timestampOffset
  20737. });
  20738. }
  20739. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  20740. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  20741. const isWalkingForward = this.mediaIndex !== null;
  20742. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  20743. // the first timeline
  20744. segmentInfo.timeline > 0;
  20745. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  20746. 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),
  20747. // then this init segment has never been seen before and should be appended.
  20748. //
  20749. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  20750. // both to true and leave the decision of whether to append the init segment to append time.
  20751. if (simpleSegment.map && !simpleSegment.map.bytes) {
  20752. this.logger_('going to request init segment.');
  20753. this.appendInitSegment_ = {
  20754. video: true,
  20755. audio: true
  20756. };
  20757. }
  20758. segmentInfo.abortRequests = mediaSegmentRequest({
  20759. xhr: this.vhs_.xhr,
  20760. xhrOptions: this.xhrOptions_,
  20761. decryptionWorker: this.decrypter_,
  20762. segment: simpleSegment,
  20763. abortFn: this.handleAbort_.bind(this, segmentInfo),
  20764. progressFn: this.handleProgress_.bind(this),
  20765. trackInfoFn: this.handleTrackInfo_.bind(this),
  20766. timingInfoFn: this.handleTimingInfo_.bind(this),
  20767. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  20768. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  20769. captionsFn: this.handleCaptions_.bind(this),
  20770. isEndOfTimeline,
  20771. endedTimelineFn: () => {
  20772. this.logger_('received endedtimeline callback');
  20773. },
  20774. id3Fn: this.handleId3_.bind(this),
  20775. dataFn: this.handleData_.bind(this),
  20776. doneFn: this.segmentRequestFinished_.bind(this),
  20777. onTransmuxerLog: ({
  20778. message,
  20779. level,
  20780. stream
  20781. }) => {
  20782. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  20783. }
  20784. });
  20785. }
  20786. /**
  20787. * trim the back buffer so that we don't have too much data
  20788. * in the source buffer
  20789. *
  20790. * @private
  20791. *
  20792. * @param {Object} segmentInfo - the current segment
  20793. */
  20794. trimBackBuffer_(segmentInfo) {
  20795. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  20796. // buffer and a very conservative "garbage collector"
  20797. // We manually clear out the old buffer to ensure
  20798. // we don't trigger the QuotaExceeded error
  20799. // on the source buffer during subsequent appends
  20800. if (removeToTime > 0) {
  20801. this.remove(0, removeToTime);
  20802. }
  20803. }
  20804. /**
  20805. * created a simplified copy of the segment object with just the
  20806. * information necessary to perform the XHR and decryption
  20807. *
  20808. * @private
  20809. *
  20810. * @param {Object} segmentInfo - the current segment
  20811. * @return {Object} a simplified segment object copy
  20812. */
  20813. createSimplifiedSegmentObj_(segmentInfo) {
  20814. const segment = segmentInfo.segment;
  20815. const part = segmentInfo.part;
  20816. const simpleSegment = {
  20817. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  20818. byterange: part ? part.byterange : segment.byterange,
  20819. requestId: segmentInfo.requestId,
  20820. transmuxer: segmentInfo.transmuxer,
  20821. audioAppendStart: segmentInfo.audioAppendStart,
  20822. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  20823. part: segmentInfo.part
  20824. };
  20825. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  20826. if (previousSegment && previousSegment.timeline === segment.timeline) {
  20827. // The baseStartTime of a segment is used to handle rollover when probing the TS
  20828. // segment to retrieve timing information. Since the probe only looks at the media's
  20829. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  20830. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  20831. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  20832. // seconds of media time, so should be used here. The previous segment is used since
  20833. // the end of the previous segment should represent the beginning of the current
  20834. // segment, so long as they are on the same timeline.
  20835. if (previousSegment.videoTimingInfo) {
  20836. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  20837. } else if (previousSegment.audioTimingInfo) {
  20838. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  20839. }
  20840. }
  20841. if (segment.key) {
  20842. // if the media sequence is greater than 2^32, the IV will be incorrect
  20843. // assuming 10s segments, that would be about 1300 years
  20844. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  20845. simpleSegment.key = this.segmentKey(segment.key);
  20846. simpleSegment.key.iv = iv;
  20847. }
  20848. if (segment.map) {
  20849. simpleSegment.map = this.initSegmentForMap(segment.map);
  20850. }
  20851. return simpleSegment;
  20852. }
  20853. saveTransferStats_(stats) {
  20854. // every request counts as a media request even if it has been aborted
  20855. // or canceled due to a timeout
  20856. this.mediaRequests += 1;
  20857. if (stats) {
  20858. this.mediaBytesTransferred += stats.bytesReceived;
  20859. this.mediaTransferDuration += stats.roundTripTime;
  20860. }
  20861. }
  20862. saveBandwidthRelatedStats_(duration, stats) {
  20863. // byteLength will be used for throughput, and should be based on bytes receieved,
  20864. // which we only know at the end of the request and should reflect total bytes
  20865. // downloaded rather than just bytes processed from components of the segment
  20866. this.pendingSegment_.byteLength = stats.bytesReceived;
  20867. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  20868. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  20869. return;
  20870. }
  20871. this.bandwidth = stats.bandwidth;
  20872. this.roundTrip = stats.roundTripTime;
  20873. }
  20874. handleTimeout_() {
  20875. // although the VTT segment loader bandwidth isn't really used, it's good to
  20876. // maintain functinality between segment loaders
  20877. this.mediaRequestsTimedout += 1;
  20878. this.bandwidth = 1;
  20879. this.roundTrip = NaN;
  20880. this.trigger('bandwidthupdate');
  20881. this.trigger('timeout');
  20882. }
  20883. /**
  20884. * Handle the callback from the segmentRequest function and set the
  20885. * associated SegmentLoader state and errors if necessary
  20886. *
  20887. * @private
  20888. */
  20889. segmentRequestFinished_(error, simpleSegment, result) {
  20890. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  20891. // check the call queue directly since this function doesn't need to deal with any
  20892. // data, and can continue even if the source buffers are not set up and we didn't get
  20893. // any data from the segment
  20894. if (this.callQueue_.length) {
  20895. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  20896. return;
  20897. }
  20898. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  20899. if (!this.pendingSegment_) {
  20900. return;
  20901. } // the request was aborted and the SegmentLoader has already started
  20902. // another request. this can happen when the timeout for an aborted
  20903. // request triggers due to a limitation in the XHR library
  20904. // do not count this as any sort of request or we risk double-counting
  20905. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  20906. return;
  20907. } // an error occurred from the active pendingSegment_ so reset everything
  20908. if (error) {
  20909. this.pendingSegment_ = null;
  20910. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  20911. if (error.code === REQUEST_ERRORS.ABORTED) {
  20912. return;
  20913. }
  20914. this.pause(); // the error is really just that at least one of the requests timed-out
  20915. // set the bandwidth to a very low value and trigger an ABR switch to
  20916. // take emergency action
  20917. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  20918. this.handleTimeout_();
  20919. return;
  20920. } // if control-flow has arrived here, then the error is real
  20921. // emit an error event to exclude the current playlist
  20922. this.mediaRequestsErrored += 1;
  20923. this.error(error);
  20924. this.trigger('error');
  20925. return;
  20926. }
  20927. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  20928. // generated for ABR purposes
  20929. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  20930. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  20931. if (result.gopInfo) {
  20932. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  20933. } // Although we may have already started appending on progress, we shouldn't switch the
  20934. // state away from loading until we are officially done loading the segment data.
  20935. this.state = 'APPENDING'; // used for testing
  20936. this.trigger('appending');
  20937. this.waitForAppendsToComplete_(segmentInfo);
  20938. }
  20939. setTimeMapping_(timeline) {
  20940. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  20941. if (timelineMapping !== null) {
  20942. this.timeMapping_ = timelineMapping;
  20943. }
  20944. }
  20945. updateMediaSecondsLoaded_(segment) {
  20946. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  20947. this.mediaSecondsLoaded += segment.end - segment.start;
  20948. } else {
  20949. this.mediaSecondsLoaded += segment.duration;
  20950. }
  20951. }
  20952. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  20953. if (timestampOffset === null) {
  20954. return false;
  20955. } // note that we're potentially using the same timestamp offset for both video and
  20956. // audio
  20957. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  20958. return true;
  20959. }
  20960. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  20961. return true;
  20962. }
  20963. return false;
  20964. }
  20965. trueSegmentStart_({
  20966. currentStart,
  20967. playlist,
  20968. mediaIndex,
  20969. firstVideoFrameTimeForData,
  20970. currentVideoTimestampOffset,
  20971. useVideoTimingInfo,
  20972. videoTimingInfo,
  20973. audioTimingInfo
  20974. }) {
  20975. if (typeof currentStart !== 'undefined') {
  20976. // if start was set once, keep using it
  20977. return currentStart;
  20978. }
  20979. if (!useVideoTimingInfo) {
  20980. return audioTimingInfo.start;
  20981. }
  20982. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  20983. // within that segment. Since the transmuxer maintains a cache of incomplete data
  20984. // from and/or the last frame seen, the start time may reflect a frame that starts
  20985. // in the previous segment. Check for that case and ensure the start time is
  20986. // accurate for the segment.
  20987. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  20988. return firstVideoFrameTimeForData;
  20989. }
  20990. return videoTimingInfo.start;
  20991. }
  20992. waitForAppendsToComplete_(segmentInfo) {
  20993. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  20994. if (!trackInfo) {
  20995. this.error({
  20996. message: 'No starting media returned, likely due to an unsupported media format.',
  20997. playlistExclusionDuration: Infinity
  20998. });
  20999. this.trigger('error');
  21000. return;
  21001. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  21002. // on each queue this loader is responsible for to ensure that the appends are
  21003. // complete.
  21004. const {
  21005. hasAudio,
  21006. hasVideo,
  21007. isMuxed
  21008. } = trackInfo;
  21009. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  21010. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  21011. segmentInfo.waitingOnAppends = 0; // segments with no data
  21012. if (!segmentInfo.hasAppendedData_) {
  21013. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  21014. // When there's no audio or video data in the segment, there's no audio or video
  21015. // timing information.
  21016. //
  21017. // If there's no audio or video timing information, then the timestamp offset
  21018. // can't be adjusted to the appropriate value for the transmuxer and source
  21019. // buffers.
  21020. //
  21021. // Therefore, the next segment should be used to set the timestamp offset.
  21022. this.isPendingTimestampOffset_ = true;
  21023. } // override settings for metadata only segments
  21024. segmentInfo.timingInfo = {
  21025. start: 0
  21026. };
  21027. segmentInfo.waitingOnAppends++;
  21028. if (!this.isPendingTimestampOffset_) {
  21029. // update the timestampoffset
  21030. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  21031. // no video/audio data.
  21032. this.processMetadataQueue_();
  21033. } // append is "done" instantly with no data.
  21034. this.checkAppendsDone_(segmentInfo);
  21035. return;
  21036. } // Since source updater could call back synchronously, do the increments first.
  21037. if (waitForVideo) {
  21038. segmentInfo.waitingOnAppends++;
  21039. }
  21040. if (waitForAudio) {
  21041. segmentInfo.waitingOnAppends++;
  21042. }
  21043. if (waitForVideo) {
  21044. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  21045. }
  21046. if (waitForAudio) {
  21047. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  21048. }
  21049. }
  21050. checkAppendsDone_(segmentInfo) {
  21051. if (this.checkForAbort_(segmentInfo.requestId)) {
  21052. return;
  21053. }
  21054. segmentInfo.waitingOnAppends--;
  21055. if (segmentInfo.waitingOnAppends === 0) {
  21056. this.handleAppendsDone_();
  21057. }
  21058. }
  21059. checkForIllegalMediaSwitch(trackInfo) {
  21060. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  21061. if (illegalMediaSwitchError) {
  21062. this.error({
  21063. message: illegalMediaSwitchError,
  21064. playlistExclusionDuration: Infinity
  21065. });
  21066. this.trigger('error');
  21067. return true;
  21068. }
  21069. return false;
  21070. }
  21071. updateSourceBufferTimestampOffset_(segmentInfo) {
  21072. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  21073. // priority, timing-wise, so we must wait
  21074. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  21075. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  21076. this.loaderType_ !== 'main') {
  21077. return;
  21078. }
  21079. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  21080. // the timing info here comes from video. In the event that the audio is longer than
  21081. // the video, this will trim the start of the audio.
  21082. // This also trims any offset from 0 at the beginning of the media
  21083. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  21084. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  21085. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  21086. timingInfo: segmentInfo.timingInfo
  21087. }); // In the event that there are part segment downloads, each will try to update the
  21088. // timestamp offset. Retaining this bit of state prevents us from updating in the
  21089. // future (within the same segment), however, there may be a better way to handle it.
  21090. segmentInfo.changedTimestampOffset = true;
  21091. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  21092. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  21093. didChange = true;
  21094. }
  21095. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  21096. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  21097. didChange = true;
  21098. }
  21099. if (didChange) {
  21100. this.trigger('timestampoffset');
  21101. }
  21102. }
  21103. getSegmentStartTimeForTimestampOffsetCalculation_({
  21104. videoTimingInfo,
  21105. audioTimingInfo,
  21106. timingInfo
  21107. }) {
  21108. if (!this.useDtsForTimestampOffset_) {
  21109. return timingInfo.start;
  21110. }
  21111. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  21112. return videoTimingInfo.transmuxedDecodeStart;
  21113. } // handle audio only
  21114. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  21115. return audioTimingInfo.transmuxedDecodeStart;
  21116. } // handle content not transmuxed (e.g., MP4)
  21117. return timingInfo.start;
  21118. }
  21119. updateTimingInfoEnd_(segmentInfo) {
  21120. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  21121. const trackInfo = this.getMediaInfo_();
  21122. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  21123. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  21124. if (!prioritizedTimingInfo) {
  21125. return;
  21126. }
  21127. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  21128. // current example is the case of fmp4), so use the rough duration to calculate an
  21129. // end time.
  21130. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  21131. }
  21132. /**
  21133. * callback to run when appendBuffer is finished. detects if we are
  21134. * in a good state to do things with the data we got, or if we need
  21135. * to wait for more
  21136. *
  21137. * @private
  21138. */
  21139. handleAppendsDone_() {
  21140. // appendsdone can cause an abort
  21141. if (this.pendingSegment_) {
  21142. this.trigger('appendsdone');
  21143. }
  21144. if (!this.pendingSegment_) {
  21145. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  21146. // all appending cases?
  21147. if (!this.paused()) {
  21148. this.monitorBuffer_();
  21149. }
  21150. return;
  21151. }
  21152. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  21153. // best to wait until all appends are done so we're sure that the primary media is
  21154. // finished (and we have its end time).
  21155. this.updateTimingInfoEnd_(segmentInfo);
  21156. if (this.shouldSaveSegmentTimingInfo_) {
  21157. // Timeline mappings should only be saved for the main loader. This is for multiple
  21158. // reasons:
  21159. //
  21160. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  21161. // and the main loader try to save the timeline mapping, whichever comes later
  21162. // will overwrite the first. In theory this is OK, as the mappings should be the
  21163. // same, however, it breaks for (2)
  21164. // 2) In the event of a live stream, the initial live point will make for a somewhat
  21165. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  21166. // the mapping will be off for one of the streams, dependent on which one was
  21167. // first saved (see (1)).
  21168. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  21169. //
  21170. // Since the audio loader will wait for the main loader to load the first segment,
  21171. // the main loader will save the first timeline mapping, and ensure that there won't
  21172. // be a case where audio loads two segments without saving a mapping (thus leading
  21173. // to missing segment timing info).
  21174. this.syncController_.saveSegmentTimingInfo({
  21175. segmentInfo,
  21176. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  21177. });
  21178. }
  21179. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  21180. if (segmentDurationMessage) {
  21181. if (segmentDurationMessage.severity === 'warn') {
  21182. videojs__default["default"].log.warn(segmentDurationMessage.message);
  21183. } else {
  21184. this.logger_(segmentDurationMessage.message);
  21185. }
  21186. }
  21187. this.recordThroughput_(segmentInfo);
  21188. this.pendingSegment_ = null;
  21189. this.state = 'READY';
  21190. if (segmentInfo.isSyncRequest) {
  21191. this.trigger('syncinfoupdate'); // if the sync request was not appended
  21192. // then it was not the correct segment.
  21193. // throw it away and use the data it gave us
  21194. // to get the correct one.
  21195. if (!segmentInfo.hasAppendedData_) {
  21196. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  21197. return;
  21198. }
  21199. }
  21200. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  21201. this.addSegmentMetadataCue_(segmentInfo);
  21202. this.fetchAtBuffer_ = true;
  21203. if (this.currentTimeline_ !== segmentInfo.timeline) {
  21204. this.timelineChangeController_.lastTimelineChange({
  21205. type: this.loaderType_,
  21206. from: this.currentTimeline_,
  21207. to: segmentInfo.timeline
  21208. }); // If audio is not disabled, the main segment loader is responsible for updating
  21209. // the audio timeline as well. If the content is video only, this won't have any
  21210. // impact.
  21211. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  21212. this.timelineChangeController_.lastTimelineChange({
  21213. type: 'audio',
  21214. from: this.currentTimeline_,
  21215. to: segmentInfo.timeline
  21216. });
  21217. }
  21218. }
  21219. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  21220. // the following conditional otherwise it may consider this a bad "guess"
  21221. // and attempt to resync when the post-update seekable window and live
  21222. // point would mean that this was the perfect segment to fetch
  21223. this.trigger('syncinfoupdate');
  21224. const segment = segmentInfo.segment;
  21225. const part = segmentInfo.part;
  21226. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  21227. 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
  21228. // the currentTime_ that means that our conservative guess was too conservative.
  21229. // In that case, reset the loader state so that we try to use any information gained
  21230. // from the previous request to create a new, more accurate, sync-point.
  21231. if (badSegmentGuess || badPartGuess) {
  21232. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  21233. this.resetEverything();
  21234. return;
  21235. }
  21236. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  21237. // and conservatively guess
  21238. if (isWalkingForward) {
  21239. this.trigger('bandwidthupdate');
  21240. }
  21241. this.trigger('progress');
  21242. this.mediaIndex = segmentInfo.mediaIndex;
  21243. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  21244. // buffer, end the stream. this ensures the "ended" event will
  21245. // fire if playback reaches that point.
  21246. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  21247. this.endOfStream();
  21248. } // used for testing
  21249. this.trigger('appended');
  21250. if (segmentInfo.hasAppendedData_) {
  21251. this.mediaAppends++;
  21252. }
  21253. if (!this.paused()) {
  21254. this.monitorBuffer_();
  21255. }
  21256. }
  21257. /**
  21258. * Records the current throughput of the decrypt, transmux, and append
  21259. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  21260. * moving average of the throughput. `throughput.count` is the number of
  21261. * data points in the average.
  21262. *
  21263. * @private
  21264. * @param {Object} segmentInfo the object returned by loadSegment
  21265. */
  21266. recordThroughput_(segmentInfo) {
  21267. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  21268. 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}`);
  21269. return;
  21270. }
  21271. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  21272. // by zero in the case where the throughput is ridiculously high
  21273. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  21274. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  21275. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  21276. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  21277. }
  21278. /**
  21279. * Adds a cue to the segment-metadata track with some metadata information about the
  21280. * segment
  21281. *
  21282. * @private
  21283. * @param {Object} segmentInfo
  21284. * the object returned by loadSegment
  21285. * @method addSegmentMetadataCue_
  21286. */
  21287. addSegmentMetadataCue_(segmentInfo) {
  21288. if (!this.segmentMetadataTrack_) {
  21289. return;
  21290. }
  21291. const segment = segmentInfo.segment;
  21292. const start = segment.start;
  21293. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  21294. if (!finite(start) || !finite(end)) {
  21295. return;
  21296. }
  21297. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  21298. const Cue = window.WebKitDataCue || window.VTTCue;
  21299. const value = {
  21300. custom: segment.custom,
  21301. dateTimeObject: segment.dateTimeObject,
  21302. dateTimeString: segment.dateTimeString,
  21303. programDateTime: segment.programDateTime,
  21304. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  21305. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  21306. codecs: segmentInfo.playlist.attributes.CODECS,
  21307. byteLength: segmentInfo.byteLength,
  21308. uri: segmentInfo.uri,
  21309. timeline: segmentInfo.timeline,
  21310. playlist: segmentInfo.playlist.id,
  21311. start,
  21312. end
  21313. };
  21314. const data = JSON.stringify(value);
  21315. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  21316. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  21317. cue.value = value;
  21318. this.segmentMetadataTrack_.addCue(cue);
  21319. }
  21320. }
  21321. function noop() {}
  21322. const toTitleCase = function (string) {
  21323. if (typeof string !== 'string') {
  21324. return string;
  21325. }
  21326. return string.replace(/./, w => w.toUpperCase());
  21327. };
  21328. /**
  21329. * @file source-updater.js
  21330. */
  21331. const bufferTypes = ['video', 'audio'];
  21332. const updating = (type, sourceUpdater) => {
  21333. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  21334. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  21335. };
  21336. const nextQueueIndexOfType = (type, queue) => {
  21337. for (let i = 0; i < queue.length; i++) {
  21338. const queueEntry = queue[i];
  21339. if (queueEntry.type === 'mediaSource') {
  21340. // If the next entry is a media source entry (uses multiple source buffers), block
  21341. // processing to allow it to go through first.
  21342. return null;
  21343. }
  21344. if (queueEntry.type === type) {
  21345. return i;
  21346. }
  21347. }
  21348. return null;
  21349. };
  21350. const shiftQueue = (type, sourceUpdater) => {
  21351. if (sourceUpdater.queue.length === 0) {
  21352. return;
  21353. }
  21354. let queueIndex = 0;
  21355. let queueEntry = sourceUpdater.queue[queueIndex];
  21356. if (queueEntry.type === 'mediaSource') {
  21357. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  21358. sourceUpdater.queue.shift();
  21359. queueEntry.action(sourceUpdater);
  21360. if (queueEntry.doneFn) {
  21361. queueEntry.doneFn();
  21362. } // Only specific source buffer actions must wait for async updateend events. Media
  21363. // Source actions process synchronously. Therefore, both audio and video source
  21364. // buffers are now clear to process the next queue entries.
  21365. shiftQueue('audio', sourceUpdater);
  21366. shiftQueue('video', sourceUpdater);
  21367. } // Media Source actions require both source buffers, so if the media source action
  21368. // couldn't process yet (because one or both source buffers are busy), block other
  21369. // queue actions until both are available and the media source action can process.
  21370. return;
  21371. }
  21372. if (type === 'mediaSource') {
  21373. // If the queue was shifted by a media source action (this happens when pushing a
  21374. // media source action onto the queue), then it wasn't from an updateend event from an
  21375. // audio or video source buffer, so there's no change from previous state, and no
  21376. // processing should be done.
  21377. return;
  21378. } // Media source queue entries don't need to consider whether the source updater is
  21379. // started (i.e., source buffers are created) as they don't need the source buffers, but
  21380. // source buffer queue entries do.
  21381. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  21382. return;
  21383. }
  21384. if (queueEntry.type !== type) {
  21385. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  21386. if (queueIndex === null) {
  21387. // Either there's no queue entry that uses this source buffer type in the queue, or
  21388. // there's a media source queue entry before the next entry of this type, in which
  21389. // case wait for that action to process first.
  21390. return;
  21391. }
  21392. queueEntry = sourceUpdater.queue[queueIndex];
  21393. }
  21394. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  21395. //
  21396. // The queue pending operation must be set before the action is performed in the event
  21397. // that the action results in a synchronous event that is acted upon. For instance, if
  21398. // an exception is thrown that can be handled, it's possible that new actions will be
  21399. // appended to an empty queue and immediately executed, but would not have the correct
  21400. // pending information if this property was set after the action was performed.
  21401. sourceUpdater.queuePending[type] = queueEntry;
  21402. queueEntry.action(type, sourceUpdater);
  21403. if (!queueEntry.doneFn) {
  21404. // synchronous operation, process next entry
  21405. sourceUpdater.queuePending[type] = null;
  21406. shiftQueue(type, sourceUpdater);
  21407. return;
  21408. }
  21409. };
  21410. const cleanupBuffer = (type, sourceUpdater) => {
  21411. const buffer = sourceUpdater[`${type}Buffer`];
  21412. const titleType = toTitleCase(type);
  21413. if (!buffer) {
  21414. return;
  21415. }
  21416. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  21417. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  21418. sourceUpdater.codecs[type] = null;
  21419. sourceUpdater[`${type}Buffer`] = null;
  21420. };
  21421. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  21422. const actions = {
  21423. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  21424. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  21425. // or the media source does not contain this source buffer.
  21426. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21427. return;
  21428. }
  21429. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  21430. try {
  21431. sourceBuffer.appendBuffer(bytes);
  21432. } catch (e) {
  21433. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  21434. sourceUpdater.queuePending[type] = null;
  21435. onError(e);
  21436. }
  21437. },
  21438. remove: (start, end) => (type, sourceUpdater) => {
  21439. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  21440. // or the media source does not contain this source buffer.
  21441. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21442. return;
  21443. }
  21444. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  21445. try {
  21446. sourceBuffer.remove(start, end);
  21447. } catch (e) {
  21448. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  21449. }
  21450. },
  21451. timestampOffset: offset => (type, sourceUpdater) => {
  21452. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  21453. // or the media source does not contain this source buffer.
  21454. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21455. return;
  21456. }
  21457. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  21458. sourceBuffer.timestampOffset = offset;
  21459. },
  21460. callback: callback => (type, sourceUpdater) => {
  21461. callback();
  21462. },
  21463. endOfStream: error => sourceUpdater => {
  21464. if (sourceUpdater.mediaSource.readyState !== 'open') {
  21465. return;
  21466. }
  21467. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  21468. try {
  21469. sourceUpdater.mediaSource.endOfStream(error);
  21470. } catch (e) {
  21471. videojs__default["default"].log.warn('Failed to call media source endOfStream', e);
  21472. }
  21473. },
  21474. duration: duration => sourceUpdater => {
  21475. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  21476. try {
  21477. sourceUpdater.mediaSource.duration = duration;
  21478. } catch (e) {
  21479. videojs__default["default"].log.warn('Failed to set media source duration', e);
  21480. }
  21481. },
  21482. abort: () => (type, sourceUpdater) => {
  21483. if (sourceUpdater.mediaSource.readyState !== 'open') {
  21484. return;
  21485. }
  21486. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  21487. // or the media source does not contain this source buffer.
  21488. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21489. return;
  21490. }
  21491. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  21492. try {
  21493. sourceBuffer.abort();
  21494. } catch (e) {
  21495. videojs__default["default"].log.warn(`Failed to abort on ${type}Buffer`, e);
  21496. }
  21497. },
  21498. addSourceBuffer: (type, codec) => sourceUpdater => {
  21499. const titleType = toTitleCase(type);
  21500. const mime = getMimeForCodec(codec);
  21501. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  21502. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  21503. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  21504. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  21505. sourceUpdater.codecs[type] = codec;
  21506. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  21507. },
  21508. removeSourceBuffer: type => sourceUpdater => {
  21509. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  21510. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  21511. // or the media source does not contain this source buffer.
  21512. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21513. return;
  21514. }
  21515. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  21516. try {
  21517. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  21518. } catch (e) {
  21519. videojs__default["default"].log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  21520. }
  21521. },
  21522. changeType: codec => (type, sourceUpdater) => {
  21523. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  21524. const mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  21525. // or the media source does not contain this source buffer.
  21526. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  21527. return;
  21528. } // do not update codec if we don't need to.
  21529. if (sourceUpdater.codecs[type] === codec) {
  21530. return;
  21531. }
  21532. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`); // check if change to the provided type is supported
  21533. try {
  21534. sourceBuffer.changeType(mime);
  21535. sourceUpdater.codecs[type] = codec;
  21536. } catch (e) {
  21537. videojs__default["default"].log.warn(`Failed to changeType on ${type}Buffer`, e);
  21538. }
  21539. }
  21540. };
  21541. const pushQueue = ({
  21542. type,
  21543. sourceUpdater,
  21544. action,
  21545. doneFn,
  21546. name
  21547. }) => {
  21548. sourceUpdater.queue.push({
  21549. type,
  21550. action,
  21551. doneFn,
  21552. name
  21553. });
  21554. shiftQueue(type, sourceUpdater);
  21555. };
  21556. const onUpdateend = (type, sourceUpdater) => e => {
  21557. // Although there should, in theory, be a pending action for any updateend receieved,
  21558. // there are some actions that may trigger updateend events without set definitions in
  21559. // the w3c spec. For instance, setting the duration on the media source may trigger
  21560. // updateend events on source buffers. This does not appear to be in the spec. As such,
  21561. // if we encounter an updateend without a corresponding pending action from our queue
  21562. // for that source buffer type, process the next action.
  21563. if (sourceUpdater.queuePending[type]) {
  21564. const doneFn = sourceUpdater.queuePending[type].doneFn;
  21565. sourceUpdater.queuePending[type] = null;
  21566. if (doneFn) {
  21567. // if there's an error, report it
  21568. doneFn(sourceUpdater[`${type}Error_`]);
  21569. }
  21570. }
  21571. shiftQueue(type, sourceUpdater);
  21572. };
  21573. /**
  21574. * A queue of callbacks to be serialized and applied when a
  21575. * MediaSource and its associated SourceBuffers are not in the
  21576. * updating state. It is used by the segment loader to update the
  21577. * underlying SourceBuffers when new data is loaded, for instance.
  21578. *
  21579. * @class SourceUpdater
  21580. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  21581. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  21582. */
  21583. class SourceUpdater extends videojs__default["default"].EventTarget {
  21584. constructor(mediaSource) {
  21585. super();
  21586. this.mediaSource = mediaSource;
  21587. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  21588. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  21589. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  21590. this.audioTimestampOffset_ = 0;
  21591. this.videoTimestampOffset_ = 0;
  21592. this.queue = [];
  21593. this.queuePending = {
  21594. audio: null,
  21595. video: null
  21596. };
  21597. this.delayedAudioAppendQueue_ = [];
  21598. this.videoAppendQueued_ = false;
  21599. this.codecs = {};
  21600. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  21601. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  21602. this.onVideoError_ = e => {
  21603. // used for debugging
  21604. this.videoError_ = e;
  21605. };
  21606. this.onAudioError_ = e => {
  21607. // used for debugging
  21608. this.audioError_ = e;
  21609. };
  21610. this.createdSourceBuffers_ = false;
  21611. this.initializedEme_ = false;
  21612. this.triggeredReady_ = false;
  21613. }
  21614. initializedEme() {
  21615. this.initializedEme_ = true;
  21616. this.triggerReady();
  21617. }
  21618. hasCreatedSourceBuffers() {
  21619. // if false, likely waiting on one of the segment loaders to get enough data to create
  21620. // source buffers
  21621. return this.createdSourceBuffers_;
  21622. }
  21623. hasInitializedAnyEme() {
  21624. return this.initializedEme_;
  21625. }
  21626. ready() {
  21627. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  21628. }
  21629. createSourceBuffers(codecs) {
  21630. if (this.hasCreatedSourceBuffers()) {
  21631. // already created them before
  21632. return;
  21633. } // the intial addOrChangeSourceBuffers will always be
  21634. // two add buffers.
  21635. this.addOrChangeSourceBuffers(codecs);
  21636. this.createdSourceBuffers_ = true;
  21637. this.trigger('createdsourcebuffers');
  21638. this.triggerReady();
  21639. }
  21640. triggerReady() {
  21641. // only allow ready to be triggered once, this prevents the case
  21642. // where:
  21643. // 1. we trigger createdsourcebuffers
  21644. // 2. ie 11 synchronously initializates eme
  21645. // 3. the synchronous initialization causes us to trigger ready
  21646. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  21647. if (this.ready() && !this.triggeredReady_) {
  21648. this.triggeredReady_ = true;
  21649. this.trigger('ready');
  21650. }
  21651. }
  21652. /**
  21653. * Add a type of source buffer to the media source.
  21654. *
  21655. * @param {string} type
  21656. * The type of source buffer to add.
  21657. *
  21658. * @param {string} codec
  21659. * The codec to add the source buffer with.
  21660. */
  21661. addSourceBuffer(type, codec) {
  21662. pushQueue({
  21663. type: 'mediaSource',
  21664. sourceUpdater: this,
  21665. action: actions.addSourceBuffer(type, codec),
  21666. name: 'addSourceBuffer'
  21667. });
  21668. }
  21669. /**
  21670. * call abort on a source buffer.
  21671. *
  21672. * @param {string} type
  21673. * The type of source buffer to call abort on.
  21674. */
  21675. abort(type) {
  21676. pushQueue({
  21677. type,
  21678. sourceUpdater: this,
  21679. action: actions.abort(type),
  21680. name: 'abort'
  21681. });
  21682. }
  21683. /**
  21684. * Call removeSourceBuffer and remove a specific type
  21685. * of source buffer on the mediaSource.
  21686. *
  21687. * @param {string} type
  21688. * The type of source buffer to remove.
  21689. */
  21690. removeSourceBuffer(type) {
  21691. if (!this.canRemoveSourceBuffer()) {
  21692. videojs__default["default"].log.error('removeSourceBuffer is not supported!');
  21693. return;
  21694. }
  21695. pushQueue({
  21696. type: 'mediaSource',
  21697. sourceUpdater: this,
  21698. action: actions.removeSourceBuffer(type),
  21699. name: 'removeSourceBuffer'
  21700. });
  21701. }
  21702. /**
  21703. * Whether or not the removeSourceBuffer function is supported
  21704. * on the mediaSource.
  21705. *
  21706. * @return {boolean}
  21707. * if removeSourceBuffer can be called.
  21708. */
  21709. canRemoveSourceBuffer() {
  21710. // As of Firefox 83 removeSourceBuffer
  21711. // throws errors, so we report that it does not support this.
  21712. return !videojs__default["default"].browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  21713. }
  21714. /**
  21715. * Whether or not the changeType function is supported
  21716. * on our SourceBuffers.
  21717. *
  21718. * @return {boolean}
  21719. * if changeType can be called.
  21720. */
  21721. static canChangeType() {
  21722. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  21723. }
  21724. /**
  21725. * Whether or not the changeType function is supported
  21726. * on our SourceBuffers.
  21727. *
  21728. * @return {boolean}
  21729. * if changeType can be called.
  21730. */
  21731. canChangeType() {
  21732. return this.constructor.canChangeType();
  21733. }
  21734. /**
  21735. * Call the changeType function on a source buffer, given the code and type.
  21736. *
  21737. * @param {string} type
  21738. * The type of source buffer to call changeType on.
  21739. *
  21740. * @param {string} codec
  21741. * The codec string to change type with on the source buffer.
  21742. */
  21743. changeType(type, codec) {
  21744. if (!this.canChangeType()) {
  21745. videojs__default["default"].log.error('changeType is not supported!');
  21746. return;
  21747. }
  21748. pushQueue({
  21749. type,
  21750. sourceUpdater: this,
  21751. action: actions.changeType(codec),
  21752. name: 'changeType'
  21753. });
  21754. }
  21755. /**
  21756. * Add source buffers with a codec or, if they are already created,
  21757. * call changeType on source buffers using changeType.
  21758. *
  21759. * @param {Object} codecs
  21760. * Codecs to switch to
  21761. */
  21762. addOrChangeSourceBuffers(codecs) {
  21763. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  21764. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  21765. }
  21766. Object.keys(codecs).forEach(type => {
  21767. const codec = codecs[type];
  21768. if (!this.hasCreatedSourceBuffers()) {
  21769. return this.addSourceBuffer(type, codec);
  21770. }
  21771. if (this.canChangeType()) {
  21772. this.changeType(type, codec);
  21773. }
  21774. });
  21775. }
  21776. /**
  21777. * Queue an update to append an ArrayBuffer.
  21778. *
  21779. * @param {MediaObject} object containing audioBytes and/or videoBytes
  21780. * @param {Function} done the function to call when done
  21781. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  21782. */
  21783. appendBuffer(options, doneFn) {
  21784. const {
  21785. segmentInfo,
  21786. type,
  21787. bytes
  21788. } = options;
  21789. this.processedAppend_ = true;
  21790. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  21791. this.delayedAudioAppendQueue_.push([options, doneFn]);
  21792. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  21793. return;
  21794. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  21795. // not be fired. This means that the queue will be blocked until the next action
  21796. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  21797. // these errors by calling the doneFn with the specific error.
  21798. const onError = doneFn;
  21799. pushQueue({
  21800. type,
  21801. sourceUpdater: this,
  21802. action: actions.appendBuffer(bytes, segmentInfo || {
  21803. mediaIndex: -1
  21804. }, onError),
  21805. doneFn,
  21806. name: 'appendBuffer'
  21807. });
  21808. if (type === 'video') {
  21809. this.videoAppendQueued_ = true;
  21810. if (!this.delayedAudioAppendQueue_.length) {
  21811. return;
  21812. }
  21813. const queue = this.delayedAudioAppendQueue_.slice();
  21814. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  21815. this.delayedAudioAppendQueue_.length = 0;
  21816. queue.forEach(que => {
  21817. this.appendBuffer.apply(this, que);
  21818. });
  21819. }
  21820. }
  21821. /**
  21822. * Get the audio buffer's buffered timerange.
  21823. *
  21824. * @return {TimeRange}
  21825. * The audio buffer's buffered time range
  21826. */
  21827. audioBuffered() {
  21828. // no media source/source buffer or it isn't in the media sources
  21829. // source buffer list
  21830. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  21831. return createTimeRanges();
  21832. }
  21833. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  21834. }
  21835. /**
  21836. * Get the video buffer's buffered timerange.
  21837. *
  21838. * @return {TimeRange}
  21839. * The video buffer's buffered time range
  21840. */
  21841. videoBuffered() {
  21842. // no media source/source buffer or it isn't in the media sources
  21843. // source buffer list
  21844. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  21845. return createTimeRanges();
  21846. }
  21847. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  21848. }
  21849. /**
  21850. * Get a combined video/audio buffer's buffered timerange.
  21851. *
  21852. * @return {TimeRange}
  21853. * the combined time range
  21854. */
  21855. buffered() {
  21856. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  21857. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  21858. if (audio && !video) {
  21859. return this.audioBuffered();
  21860. }
  21861. if (video && !audio) {
  21862. return this.videoBuffered();
  21863. }
  21864. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  21865. }
  21866. /**
  21867. * Add a callback to the queue that will set duration on the mediaSource.
  21868. *
  21869. * @param {number} duration
  21870. * The duration to set
  21871. *
  21872. * @param {Function} [doneFn]
  21873. * function to run after duration has been set.
  21874. */
  21875. setDuration(duration, doneFn = noop) {
  21876. // In order to set the duration on the media source, it's necessary to wait for all
  21877. // source buffers to no longer be updating. "If the updating attribute equals true on
  21878. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  21879. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  21880. pushQueue({
  21881. type: 'mediaSource',
  21882. sourceUpdater: this,
  21883. action: actions.duration(duration),
  21884. name: 'duration',
  21885. doneFn
  21886. });
  21887. }
  21888. /**
  21889. * Add a mediaSource endOfStream call to the queue
  21890. *
  21891. * @param {Error} [error]
  21892. * Call endOfStream with an error
  21893. *
  21894. * @param {Function} [doneFn]
  21895. * A function that should be called when the
  21896. * endOfStream call has finished.
  21897. */
  21898. endOfStream(error = null, doneFn = noop) {
  21899. if (typeof error !== 'string') {
  21900. error = undefined;
  21901. } // In order to set the duration on the media source, it's necessary to wait for all
  21902. // source buffers to no longer be updating. "If the updating attribute equals true on
  21903. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  21904. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  21905. pushQueue({
  21906. type: 'mediaSource',
  21907. sourceUpdater: this,
  21908. action: actions.endOfStream(error),
  21909. name: 'endOfStream',
  21910. doneFn
  21911. });
  21912. }
  21913. /**
  21914. * Queue an update to remove a time range from the buffer.
  21915. *
  21916. * @param {number} start where to start the removal
  21917. * @param {number} end where to end the removal
  21918. * @param {Function} [done=noop] optional callback to be executed when the remove
  21919. * operation is complete
  21920. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  21921. */
  21922. removeAudio(start, end, done = noop) {
  21923. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  21924. done();
  21925. return;
  21926. }
  21927. pushQueue({
  21928. type: 'audio',
  21929. sourceUpdater: this,
  21930. action: actions.remove(start, end),
  21931. doneFn: done,
  21932. name: 'remove'
  21933. });
  21934. }
  21935. /**
  21936. * Queue an update to remove a time range from the buffer.
  21937. *
  21938. * @param {number} start where to start the removal
  21939. * @param {number} end where to end the removal
  21940. * @param {Function} [done=noop] optional callback to be executed when the remove
  21941. * operation is complete
  21942. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  21943. */
  21944. removeVideo(start, end, done = noop) {
  21945. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  21946. done();
  21947. return;
  21948. }
  21949. pushQueue({
  21950. type: 'video',
  21951. sourceUpdater: this,
  21952. action: actions.remove(start, end),
  21953. doneFn: done,
  21954. name: 'remove'
  21955. });
  21956. }
  21957. /**
  21958. * Whether the underlying sourceBuffer is updating or not
  21959. *
  21960. * @return {boolean} the updating status of the SourceBuffer
  21961. */
  21962. updating() {
  21963. // the audio/video source buffer is updating
  21964. if (updating('audio', this) || updating('video', this)) {
  21965. return true;
  21966. }
  21967. return false;
  21968. }
  21969. /**
  21970. * Set/get the timestampoffset on the audio SourceBuffer
  21971. *
  21972. * @return {number} the timestamp offset
  21973. */
  21974. audioTimestampOffset(offset) {
  21975. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  21976. this.audioTimestampOffset_ !== offset) {
  21977. pushQueue({
  21978. type: 'audio',
  21979. sourceUpdater: this,
  21980. action: actions.timestampOffset(offset),
  21981. name: 'timestampOffset'
  21982. });
  21983. this.audioTimestampOffset_ = offset;
  21984. }
  21985. return this.audioTimestampOffset_;
  21986. }
  21987. /**
  21988. * Set/get the timestampoffset on the video SourceBuffer
  21989. *
  21990. * @return {number} the timestamp offset
  21991. */
  21992. videoTimestampOffset(offset) {
  21993. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  21994. this.videoTimestampOffset !== offset) {
  21995. pushQueue({
  21996. type: 'video',
  21997. sourceUpdater: this,
  21998. action: actions.timestampOffset(offset),
  21999. name: 'timestampOffset'
  22000. });
  22001. this.videoTimestampOffset_ = offset;
  22002. }
  22003. return this.videoTimestampOffset_;
  22004. }
  22005. /**
  22006. * Add a function to the queue that will be called
  22007. * when it is its turn to run in the audio queue.
  22008. *
  22009. * @param {Function} callback
  22010. * The callback to queue.
  22011. */
  22012. audioQueueCallback(callback) {
  22013. if (!this.audioBuffer) {
  22014. return;
  22015. }
  22016. pushQueue({
  22017. type: 'audio',
  22018. sourceUpdater: this,
  22019. action: actions.callback(callback),
  22020. name: 'callback'
  22021. });
  22022. }
  22023. /**
  22024. * Add a function to the queue that will be called
  22025. * when it is its turn to run in the video queue.
  22026. *
  22027. * @param {Function} callback
  22028. * The callback to queue.
  22029. */
  22030. videoQueueCallback(callback) {
  22031. if (!this.videoBuffer) {
  22032. return;
  22033. }
  22034. pushQueue({
  22035. type: 'video',
  22036. sourceUpdater: this,
  22037. action: actions.callback(callback),
  22038. name: 'callback'
  22039. });
  22040. }
  22041. /**
  22042. * dispose of the source updater and the underlying sourceBuffer
  22043. */
  22044. dispose() {
  22045. this.trigger('dispose');
  22046. bufferTypes.forEach(type => {
  22047. this.abort(type);
  22048. if (this.canRemoveSourceBuffer()) {
  22049. this.removeSourceBuffer(type);
  22050. } else {
  22051. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  22052. }
  22053. });
  22054. this.videoAppendQueued_ = false;
  22055. this.delayedAudioAppendQueue_.length = 0;
  22056. if (this.sourceopenListener_) {
  22057. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  22058. }
  22059. this.off();
  22060. }
  22061. }
  22062. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  22063. const bufferToHexString = buffer => {
  22064. const uInt8Buffer = new Uint8Array(buffer);
  22065. return Array.from(uInt8Buffer).map(byte => byte.toString(16).padStart(2, '0')).join('');
  22066. };
  22067. /**
  22068. * @file vtt-segment-loader.js
  22069. */
  22070. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  22071. class NoVttJsError extends Error {
  22072. constructor() {
  22073. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  22074. }
  22075. }
  22076. /**
  22077. * An object that manages segment loading and appending.
  22078. *
  22079. * @class VTTSegmentLoader
  22080. * @param {Object} options required and optional options
  22081. * @extends videojs.EventTarget
  22082. */
  22083. class VTTSegmentLoader extends SegmentLoader {
  22084. constructor(settings, options = {}) {
  22085. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  22086. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  22087. this.mediaSource_ = null;
  22088. this.subtitlesTrack_ = null;
  22089. this.loaderType_ = 'subtitle';
  22090. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  22091. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  22092. // the sync controller leads to improper behavior.
  22093. this.shouldSaveSegmentTimingInfo_ = false;
  22094. }
  22095. createTransmuxer_() {
  22096. // don't need to transmux any subtitles
  22097. return null;
  22098. }
  22099. /**
  22100. * Indicates which time ranges are buffered
  22101. *
  22102. * @return {TimeRange}
  22103. * TimeRange object representing the current buffered ranges
  22104. */
  22105. buffered_() {
  22106. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  22107. return createTimeRanges();
  22108. }
  22109. const cues = this.subtitlesTrack_.cues;
  22110. const start = cues[0].startTime;
  22111. const end = cues[cues.length - 1].startTime;
  22112. return createTimeRanges([[start, end]]);
  22113. }
  22114. /**
  22115. * Gets and sets init segment for the provided map
  22116. *
  22117. * @param {Object} map
  22118. * The map object representing the init segment to get or set
  22119. * @param {boolean=} set
  22120. * If true, the init segment for the provided map should be saved
  22121. * @return {Object}
  22122. * map object for desired init segment
  22123. */
  22124. initSegmentForMap(map, set = false) {
  22125. if (!map) {
  22126. return null;
  22127. }
  22128. const id = initSegmentId(map);
  22129. let storedMap = this.initSegments_[id];
  22130. if (set && !storedMap && map.bytes) {
  22131. // append WebVTT line terminators to the media initialization segment if it exists
  22132. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  22133. // requires two or more WebVTT line terminators between the WebVTT header and the
  22134. // rest of the file
  22135. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  22136. const combinedSegment = new Uint8Array(combinedByteLength);
  22137. combinedSegment.set(map.bytes);
  22138. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  22139. this.initSegments_[id] = storedMap = {
  22140. resolvedUri: map.resolvedUri,
  22141. byterange: map.byterange,
  22142. bytes: combinedSegment
  22143. };
  22144. }
  22145. return storedMap || map;
  22146. }
  22147. /**
  22148. * Returns true if all configuration required for loading is present, otherwise false.
  22149. *
  22150. * @return {boolean} True if the all configuration is ready for loading
  22151. * @private
  22152. */
  22153. couldBeginLoading_() {
  22154. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  22155. }
  22156. /**
  22157. * Once all the starting parameters have been specified, begin
  22158. * operation. This method should only be invoked from the INIT
  22159. * state.
  22160. *
  22161. * @private
  22162. */
  22163. init_() {
  22164. this.state = 'READY';
  22165. this.resetEverything();
  22166. return this.monitorBuffer_();
  22167. }
  22168. /**
  22169. * Set a subtitle track on the segment loader to add subtitles to
  22170. *
  22171. * @param {TextTrack=} track
  22172. * The text track to add loaded subtitles to
  22173. * @return {TextTrack}
  22174. * Returns the subtitles track
  22175. */
  22176. track(track) {
  22177. if (typeof track === 'undefined') {
  22178. return this.subtitlesTrack_;
  22179. }
  22180. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  22181. // buffering now
  22182. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  22183. this.init_();
  22184. }
  22185. return this.subtitlesTrack_;
  22186. }
  22187. /**
  22188. * Remove any data in the source buffer between start and end times
  22189. *
  22190. * @param {number} start - the start time of the region to remove from the buffer
  22191. * @param {number} end - the end time of the region to remove from the buffer
  22192. */
  22193. remove(start, end) {
  22194. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  22195. }
  22196. /**
  22197. * fill the buffer with segements unless the sourceBuffers are
  22198. * currently updating
  22199. *
  22200. * Note: this function should only ever be called by monitorBuffer_
  22201. * and never directly
  22202. *
  22203. * @private
  22204. */
  22205. fillBuffer_() {
  22206. // see if we need to begin loading immediately
  22207. const segmentInfo = this.chooseNextRequest_();
  22208. if (!segmentInfo) {
  22209. return;
  22210. }
  22211. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  22212. // We don't have the timestamp offset that we need to sync subtitles.
  22213. // Rerun on a timestamp offset or user interaction.
  22214. const checkTimestampOffset = () => {
  22215. this.state = 'READY';
  22216. if (!this.paused()) {
  22217. // if not paused, queue a buffer check as soon as possible
  22218. this.monitorBuffer_();
  22219. }
  22220. };
  22221. this.syncController_.one('timestampoffset', checkTimestampOffset);
  22222. this.state = 'WAITING_ON_TIMELINE';
  22223. return;
  22224. }
  22225. this.loadSegment_(segmentInfo);
  22226. } // never set a timestamp offset for vtt segments.
  22227. timestampOffsetForSegment_() {
  22228. return null;
  22229. }
  22230. chooseNextRequest_() {
  22231. return this.skipEmptySegments_(super.chooseNextRequest_());
  22232. }
  22233. /**
  22234. * Prevents the segment loader from requesting segments we know contain no subtitles
  22235. * by walking forward until we find the next segment that we don't know whether it is
  22236. * empty or not.
  22237. *
  22238. * @param {Object} segmentInfo
  22239. * a segment info object that describes the current segment
  22240. * @return {Object}
  22241. * a segment info object that describes the current segment
  22242. */
  22243. skipEmptySegments_(segmentInfo) {
  22244. while (segmentInfo && segmentInfo.segment.empty) {
  22245. // stop at the last possible segmentInfo
  22246. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  22247. segmentInfo = null;
  22248. break;
  22249. }
  22250. segmentInfo = this.generateSegmentInfo_({
  22251. playlist: segmentInfo.playlist,
  22252. mediaIndex: segmentInfo.mediaIndex + 1,
  22253. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  22254. isSyncRequest: segmentInfo.isSyncRequest
  22255. });
  22256. }
  22257. return segmentInfo;
  22258. }
  22259. stopForError(error) {
  22260. this.error(error);
  22261. this.state = 'READY';
  22262. this.pause();
  22263. this.trigger('error');
  22264. }
  22265. /**
  22266. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  22267. *
  22268. * @private
  22269. */
  22270. segmentRequestFinished_(error, simpleSegment, result) {
  22271. if (!this.subtitlesTrack_) {
  22272. this.state = 'READY';
  22273. return;
  22274. }
  22275. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  22276. if (!this.pendingSegment_) {
  22277. this.state = 'READY';
  22278. this.mediaRequestsAborted += 1;
  22279. return;
  22280. }
  22281. if (error) {
  22282. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  22283. this.handleTimeout_();
  22284. }
  22285. if (error.code === REQUEST_ERRORS.ABORTED) {
  22286. this.mediaRequestsAborted += 1;
  22287. } else {
  22288. this.mediaRequestsErrored += 1;
  22289. }
  22290. this.stopForError(error);
  22291. return;
  22292. }
  22293. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  22294. // maintain functionality between segment loaders
  22295. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  22296. if (simpleSegment.key) {
  22297. this.segmentKey(simpleSegment.key, true);
  22298. }
  22299. this.state = 'APPENDING'; // used for tests
  22300. this.trigger('appending');
  22301. const segment = segmentInfo.segment;
  22302. if (segment.map) {
  22303. segment.map.bytes = simpleSegment.map.bytes;
  22304. }
  22305. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  22306. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  22307. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  22308. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  22309. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  22310. message: 'Error loading vtt.js'
  22311. }));
  22312. return;
  22313. }
  22314. segment.requested = true;
  22315. try {
  22316. this.parseVTTCues_(segmentInfo);
  22317. } catch (e) {
  22318. this.stopForError({
  22319. message: e.message
  22320. });
  22321. return;
  22322. }
  22323. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  22324. if (segmentInfo.cues.length) {
  22325. segmentInfo.timingInfo = {
  22326. start: segmentInfo.cues[0].startTime,
  22327. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  22328. };
  22329. } else {
  22330. segmentInfo.timingInfo = {
  22331. start: segmentInfo.startOfSegment,
  22332. end: segmentInfo.startOfSegment + segmentInfo.duration
  22333. };
  22334. }
  22335. if (segmentInfo.isSyncRequest) {
  22336. this.trigger('syncinfoupdate');
  22337. this.pendingSegment_ = null;
  22338. this.state = 'READY';
  22339. return;
  22340. }
  22341. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  22342. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  22343. // the subtitle track
  22344. segmentInfo.cues.forEach(cue => {
  22345. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  22346. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  22347. // cues to have identical time-intervals, but if the text is also identical
  22348. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  22349. // "overlaps" VTT segments)
  22350. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  22351. this.handleAppendsDone_();
  22352. }
  22353. handleData_() {// noop as we shouldn't be getting video/audio data captions
  22354. // that we do not support here.
  22355. }
  22356. updateTimingInfoEnd_() {// noop
  22357. }
  22358. /**
  22359. * Uses the WebVTT parser to parse the segment response
  22360. *
  22361. * @throws NoVttJsError
  22362. *
  22363. * @param {Object} segmentInfo
  22364. * a segment info object that describes the current segment
  22365. * @private
  22366. */
  22367. parseVTTCues_(segmentInfo) {
  22368. let decoder;
  22369. let decodeBytesToString = false;
  22370. if (typeof window.WebVTT !== 'function') {
  22371. // caller is responsible for exception handling.
  22372. throw new NoVttJsError();
  22373. }
  22374. if (typeof window.TextDecoder === 'function') {
  22375. decoder = new window.TextDecoder('utf8');
  22376. } else {
  22377. decoder = window.WebVTT.StringDecoder();
  22378. decodeBytesToString = true;
  22379. }
  22380. const parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  22381. segmentInfo.cues = [];
  22382. segmentInfo.timestampmap = {
  22383. MPEGTS: 0,
  22384. LOCAL: 0
  22385. };
  22386. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  22387. parser.ontimestampmap = map => {
  22388. segmentInfo.timestampmap = map;
  22389. };
  22390. parser.onparsingerror = error => {
  22391. videojs__default["default"].log.warn('Error encountered when parsing cues: ' + error.message);
  22392. };
  22393. if (segmentInfo.segment.map) {
  22394. let mapData = segmentInfo.segment.map.bytes;
  22395. if (decodeBytesToString) {
  22396. mapData = uint8ToUtf8(mapData);
  22397. }
  22398. parser.parse(mapData);
  22399. }
  22400. let segmentData = segmentInfo.bytes;
  22401. if (decodeBytesToString) {
  22402. segmentData = uint8ToUtf8(segmentData);
  22403. }
  22404. parser.parse(segmentData);
  22405. parser.flush();
  22406. }
  22407. /**
  22408. * Updates the start and end times of any cues parsed by the WebVTT parser using
  22409. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  22410. * from the SyncController
  22411. *
  22412. * @param {Object} segmentInfo
  22413. * a segment info object that describes the current segment
  22414. * @param {Object} mappingObj
  22415. * object containing a mapping from TS to media time
  22416. * @param {Object} playlist
  22417. * the playlist object containing the segment
  22418. * @private
  22419. */
  22420. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  22421. const segment = segmentInfo.segment;
  22422. if (!mappingObj) {
  22423. // If the sync controller does not have a mapping of TS to Media Time for the
  22424. // timeline, then we don't have enough information to update the cue
  22425. // start/end times
  22426. return;
  22427. }
  22428. if (!segmentInfo.cues.length) {
  22429. // If there are no cues, we also do not have enough information to figure out
  22430. // segment timing. Mark that the segment contains no cues so we don't re-request
  22431. // an empty segment.
  22432. segment.empty = true;
  22433. return;
  22434. }
  22435. const {
  22436. MPEGTS,
  22437. LOCAL
  22438. } = segmentInfo.timestampmap;
  22439. /**
  22440. * From the spec:
  22441. * The MPEGTS media timestamp MUST use a 90KHz timescale,
  22442. * even when non-WebVTT Media Segments use a different timescale.
  22443. */
  22444. const mpegTsInSeconds = MPEGTS / clock.ONE_SECOND_IN_TS;
  22445. const diff = mpegTsInSeconds - LOCAL + mappingObj.mapping;
  22446. segmentInfo.cues.forEach(cue => {
  22447. const duration = cue.endTime - cue.startTime;
  22448. const startTime = MPEGTS === 0 ? cue.startTime + diff : this.handleRollover_(cue.startTime + diff, mappingObj.time);
  22449. cue.startTime = Math.max(startTime, 0);
  22450. cue.endTime = Math.max(startTime + duration, 0);
  22451. });
  22452. if (!playlist.syncInfo) {
  22453. const firstStart = segmentInfo.cues[0].startTime;
  22454. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  22455. playlist.syncInfo = {
  22456. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  22457. time: Math.min(firstStart, lastStart - segment.duration)
  22458. };
  22459. }
  22460. }
  22461. /**
  22462. * MPEG-TS PES timestamps are limited to 2^33.
  22463. * Once they reach 2^33, they roll over to 0.
  22464. * mux.js handles PES timestamp rollover for the following scenarios:
  22465. * [forward rollover(right)] ->
  22466. * PES timestamps monotonically increase, and once they reach 2^33, they roll over to 0
  22467. * [backward rollover(left)] -->
  22468. * we seek back to position before rollover.
  22469. *
  22470. * According to the HLS SPEC:
  22471. * When synchronizing WebVTT with PES timestamps, clients SHOULD account
  22472. * for cases where the 33-bit PES timestamps have wrapped and the WebVTT
  22473. * cue times have not. When the PES timestamp wraps, the WebVTT Segment
  22474. * SHOULD have a X-TIMESTAMP-MAP header that maps the current WebVTT
  22475. * time to the new (low valued) PES timestamp.
  22476. *
  22477. * So we want to handle rollover here and align VTT Cue start/end time to the player's time.
  22478. */
  22479. handleRollover_(value, reference) {
  22480. if (reference === null) {
  22481. return value;
  22482. }
  22483. let valueIn90khz = value * clock.ONE_SECOND_IN_TS;
  22484. const referenceIn90khz = reference * clock.ONE_SECOND_IN_TS;
  22485. let offset;
  22486. if (referenceIn90khz < valueIn90khz) {
  22487. // - 2^33
  22488. offset = -8589934592;
  22489. } else {
  22490. // + 2^33
  22491. offset = 8589934592;
  22492. } // distance(value - reference) > 2^32
  22493. while (Math.abs(valueIn90khz - referenceIn90khz) > 4294967296) {
  22494. valueIn90khz += offset;
  22495. }
  22496. return valueIn90khz / clock.ONE_SECOND_IN_TS;
  22497. }
  22498. }
  22499. /**
  22500. * @file ad-cue-tags.js
  22501. */
  22502. /**
  22503. * Searches for an ad cue that overlaps with the given mediaTime
  22504. *
  22505. * @param {Object} track
  22506. * the track to find the cue for
  22507. *
  22508. * @param {number} mediaTime
  22509. * the time to find the cue at
  22510. *
  22511. * @return {Object|null}
  22512. * the found cue or null
  22513. */
  22514. const findAdCue = function (track, mediaTime) {
  22515. const cues = track.cues;
  22516. for (let i = 0; i < cues.length; i++) {
  22517. const cue = cues[i];
  22518. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  22519. return cue;
  22520. }
  22521. }
  22522. return null;
  22523. };
  22524. const updateAdCues = function (media, track, offset = 0) {
  22525. if (!media.segments) {
  22526. return;
  22527. }
  22528. let mediaTime = offset;
  22529. let cue;
  22530. for (let i = 0; i < media.segments.length; i++) {
  22531. const segment = media.segments[i];
  22532. if (!cue) {
  22533. // Since the cues will span for at least the segment duration, adding a fudge
  22534. // factor of half segment duration will prevent duplicate cues from being
  22535. // created when timing info is not exact (e.g. cue start time initialized
  22536. // at 10.006677, but next call mediaTime is 10.003332 )
  22537. cue = findAdCue(track, mediaTime + segment.duration / 2);
  22538. }
  22539. if (cue) {
  22540. if ('cueIn' in segment) {
  22541. // Found a CUE-IN so end the cue
  22542. cue.endTime = mediaTime;
  22543. cue.adEndTime = mediaTime;
  22544. mediaTime += segment.duration;
  22545. cue = null;
  22546. continue;
  22547. }
  22548. if (mediaTime < cue.endTime) {
  22549. // Already processed this mediaTime for this cue
  22550. mediaTime += segment.duration;
  22551. continue;
  22552. } // otherwise extend cue until a CUE-IN is found
  22553. cue.endTime += segment.duration;
  22554. } else {
  22555. if ('cueOut' in segment) {
  22556. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  22557. cue.adStartTime = mediaTime; // Assumes tag format to be
  22558. // #EXT-X-CUE-OUT:30
  22559. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  22560. track.addCue(cue);
  22561. }
  22562. if ('cueOutCont' in segment) {
  22563. // Entered into the middle of an ad cue
  22564. // Assumes tag formate to be
  22565. // #EXT-X-CUE-OUT-CONT:10/30
  22566. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  22567. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  22568. cue.adStartTime = mediaTime - adOffset;
  22569. cue.adEndTime = cue.adStartTime + adTotal;
  22570. track.addCue(cue);
  22571. }
  22572. }
  22573. mediaTime += segment.duration;
  22574. }
  22575. };
  22576. /**
  22577. * @file sync-controller.js
  22578. */
  22579. // synchronize expired playlist segments.
  22580. // the max media sequence diff is 48 hours of live stream
  22581. // content with two second segments. Anything larger than that
  22582. // will likely be invalid.
  22583. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  22584. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  22585. // the equivalence display-time 0 === segment-index 0
  22586. {
  22587. name: 'VOD',
  22588. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  22589. if (duration !== Infinity) {
  22590. const syncPoint = {
  22591. time: 0,
  22592. segmentIndex: 0,
  22593. partIndex: null
  22594. };
  22595. return syncPoint;
  22596. }
  22597. return null;
  22598. }
  22599. }, {
  22600. name: 'MediaSequence',
  22601. /**
  22602. * run media sequence strategy
  22603. *
  22604. * @param {SyncController} syncController
  22605. * @param {Object} playlist
  22606. * @param {number} duration
  22607. * @param {number} currentTimeline
  22608. * @param {number} currentTime
  22609. * @param {string} type
  22610. */
  22611. run: (syncController, playlist, duration, currentTimeline, currentTime, type) => {
  22612. if (!type) {
  22613. return null;
  22614. }
  22615. const mediaSequenceMap = syncController.getMediaSequenceMap(type);
  22616. if (!mediaSequenceMap || mediaSequenceMap.size === 0) {
  22617. return null;
  22618. }
  22619. if (playlist.mediaSequence === undefined || !Array.isArray(playlist.segments) || !playlist.segments.length) {
  22620. return null;
  22621. }
  22622. let currentMediaSequence = playlist.mediaSequence;
  22623. let segmentIndex = 0;
  22624. for (const segment of playlist.segments) {
  22625. const range = mediaSequenceMap.get(currentMediaSequence);
  22626. if (!range) {
  22627. // unexpected case
  22628. // we expect this playlist to be the same playlist in the map
  22629. // just break from the loop and move forward to the next strategy
  22630. break;
  22631. }
  22632. if (currentTime >= range.start && currentTime < range.end) {
  22633. // we found segment
  22634. if (Array.isArray(segment.parts) && segment.parts.length) {
  22635. let currentPartStart = range.start;
  22636. let partIndex = 0;
  22637. for (const part of segment.parts) {
  22638. const start = currentPartStart;
  22639. const end = start + part.duration;
  22640. if (currentTime >= start && currentTime < end) {
  22641. return {
  22642. time: range.start,
  22643. segmentIndex,
  22644. partIndex
  22645. };
  22646. }
  22647. partIndex++;
  22648. currentPartStart = end;
  22649. }
  22650. } // no parts found, return sync point for segment
  22651. return {
  22652. time: range.start,
  22653. segmentIndex,
  22654. partIndex: null
  22655. };
  22656. }
  22657. segmentIndex++;
  22658. currentMediaSequence++;
  22659. } // we didn't find any segments for provided current time
  22660. return null;
  22661. }
  22662. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  22663. {
  22664. name: 'ProgramDateTime',
  22665. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  22666. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  22667. return null;
  22668. }
  22669. let syncPoint = null;
  22670. let lastDistance = null;
  22671. const partsAndSegments = getPartsAndSegments(playlist);
  22672. currentTime = currentTime || 0;
  22673. for (let i = 0; i < partsAndSegments.length; i++) {
  22674. // start from the end and loop backwards for live
  22675. // or start from the front and loop forwards for non-live
  22676. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  22677. const partAndSegment = partsAndSegments[index];
  22678. const segment = partAndSegment.segment;
  22679. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  22680. if (!datetimeMapping || !segment.dateTimeObject) {
  22681. continue;
  22682. }
  22683. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  22684. let start = segmentTime + datetimeMapping; // take part duration into account.
  22685. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  22686. for (let z = 0; z < partAndSegment.partIndex; z++) {
  22687. start += segment.parts[z].duration;
  22688. }
  22689. }
  22690. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  22691. // currentTime and can stop looking for better candidates
  22692. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  22693. break;
  22694. }
  22695. lastDistance = distance;
  22696. syncPoint = {
  22697. time: start,
  22698. segmentIndex: partAndSegment.segmentIndex,
  22699. partIndex: partAndSegment.partIndex
  22700. };
  22701. }
  22702. return syncPoint;
  22703. }
  22704. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  22705. // segment in the current timeline with timing data
  22706. {
  22707. name: 'Segment',
  22708. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  22709. let syncPoint = null;
  22710. let lastDistance = null;
  22711. currentTime = currentTime || 0;
  22712. const partsAndSegments = getPartsAndSegments(playlist);
  22713. for (let i = 0; i < partsAndSegments.length; i++) {
  22714. // start from the end and loop backwards for live
  22715. // or start from the front and loop forwards for non-live
  22716. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  22717. const partAndSegment = partsAndSegments[index];
  22718. const segment = partAndSegment.segment;
  22719. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  22720. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  22721. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  22722. // currentTime and can stop looking for better candidates
  22723. if (lastDistance !== null && lastDistance < distance) {
  22724. break;
  22725. }
  22726. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  22727. lastDistance = distance;
  22728. syncPoint = {
  22729. time: start,
  22730. segmentIndex: partAndSegment.segmentIndex,
  22731. partIndex: partAndSegment.partIndex
  22732. };
  22733. }
  22734. }
  22735. }
  22736. return syncPoint;
  22737. }
  22738. }, // Stategy "Discontinuity": We have a discontinuity with a known
  22739. // display-time
  22740. {
  22741. name: 'Discontinuity',
  22742. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  22743. let syncPoint = null;
  22744. currentTime = currentTime || 0;
  22745. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  22746. let lastDistance = null;
  22747. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  22748. const segmentIndex = playlist.discontinuityStarts[i];
  22749. const discontinuity = playlist.discontinuitySequence + i + 1;
  22750. const discontinuitySync = syncController.discontinuities[discontinuity];
  22751. if (discontinuitySync) {
  22752. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  22753. // currentTime and can stop looking for better candidates
  22754. if (lastDistance !== null && lastDistance < distance) {
  22755. break;
  22756. }
  22757. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  22758. lastDistance = distance;
  22759. syncPoint = {
  22760. time: discontinuitySync.time,
  22761. segmentIndex,
  22762. partIndex: null
  22763. };
  22764. }
  22765. }
  22766. }
  22767. }
  22768. return syncPoint;
  22769. }
  22770. }, // Stategy "Playlist": We have a playlist with a known mapping of
  22771. // segment index to display time
  22772. {
  22773. name: 'Playlist',
  22774. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  22775. if (playlist.syncInfo) {
  22776. const syncPoint = {
  22777. time: playlist.syncInfo.time,
  22778. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  22779. partIndex: null
  22780. };
  22781. return syncPoint;
  22782. }
  22783. return null;
  22784. }
  22785. }];
  22786. class SyncController extends videojs__default["default"].EventTarget {
  22787. constructor(options = {}) {
  22788. super(); // ...for synching across variants
  22789. this.timelines = [];
  22790. this.discontinuities = [];
  22791. this.timelineToDatetimeMappings = {};
  22792. /**
  22793. * @type {Map<string, Map<number, { start: number, end: number }>>}
  22794. * @private
  22795. */
  22796. this.mediaSequenceStorage_ = new Map();
  22797. this.logger_ = logger('SyncController');
  22798. }
  22799. /**
  22800. * Get media sequence map by type
  22801. *
  22802. * @param {string} type - segment loader type
  22803. * @return {Map<number, { start: number, end: number }> | undefined}
  22804. */
  22805. getMediaSequenceMap(type) {
  22806. return this.mediaSequenceStorage_.get(type);
  22807. }
  22808. /**
  22809. * Update Media Sequence Map -> <MediaSequence, Range>
  22810. *
  22811. * @param {Object} playlist - parsed playlist
  22812. * @param {number} currentTime - current player's time
  22813. * @param {string} type - segment loader type
  22814. * @return {void}
  22815. */
  22816. updateMediaSequenceMap(playlist, currentTime, type) {
  22817. // we should not process this playlist if it does not have mediaSequence or segments
  22818. if (playlist.mediaSequence === undefined || !Array.isArray(playlist.segments) || !playlist.segments.length) {
  22819. return;
  22820. }
  22821. const currentMap = this.getMediaSequenceMap(type);
  22822. const result = new Map();
  22823. let currentMediaSequence = playlist.mediaSequence;
  22824. let currentBaseTime;
  22825. if (!currentMap) {
  22826. // first playlist setup:
  22827. currentBaseTime = 0;
  22828. } else if (currentMap.has(playlist.mediaSequence)) {
  22829. // further playlists setup:
  22830. currentBaseTime = currentMap.get(playlist.mediaSequence).start;
  22831. } else {
  22832. // it seems like we have a gap between playlists, use current time as a fallback:
  22833. this.logger_(`MediaSequence sync for ${type} segment loader - received a gap between playlists.
  22834. Fallback base time to: ${currentTime}.
  22835. Received media sequence: ${currentMediaSequence}.
  22836. Current map: `, currentMap);
  22837. currentBaseTime = currentTime;
  22838. }
  22839. this.logger_(`MediaSequence sync for ${type} segment loader.
  22840. Received media sequence: ${currentMediaSequence}.
  22841. base time is ${currentBaseTime}
  22842. Current map: `, currentMap);
  22843. playlist.segments.forEach(segment => {
  22844. const start = currentBaseTime;
  22845. const end = start + segment.duration;
  22846. const range = {
  22847. start,
  22848. end
  22849. };
  22850. result.set(currentMediaSequence, range);
  22851. currentMediaSequence++;
  22852. currentBaseTime = end;
  22853. });
  22854. this.mediaSequenceStorage_.set(type, result);
  22855. }
  22856. /**
  22857. * Find a sync-point for the playlist specified
  22858. *
  22859. * A sync-point is defined as a known mapping from display-time to
  22860. * a segment-index in the current playlist.
  22861. *
  22862. * @param {Playlist} playlist
  22863. * The playlist that needs a sync-point
  22864. * @param {number} duration
  22865. * Duration of the MediaSource (Infinite if playing a live source)
  22866. * @param {number} currentTimeline
  22867. * The last timeline from which a segment was loaded
  22868. * @param {number} currentTime
  22869. * Current player's time
  22870. * @param {string} type
  22871. * Segment loader type
  22872. * @return {Object}
  22873. * A sync-point object
  22874. */
  22875. getSyncPoint(playlist, duration, currentTimeline, currentTime, type) {
  22876. // Always use VOD sync point for VOD
  22877. if (duration !== Infinity) {
  22878. const vodSyncPointStrategy = syncPointStrategies.find(({
  22879. name
  22880. }) => name === 'VOD');
  22881. return vodSyncPointStrategy.run(this, playlist, duration);
  22882. }
  22883. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime, type);
  22884. if (!syncPoints.length) {
  22885. // Signal that we need to attempt to get a sync-point manually
  22886. // by fetching a segment in the playlist and constructing
  22887. // a sync-point from that information
  22888. return null;
  22889. } // If we have exact match just return it instead of finding the nearest distance
  22890. for (const syncPointInfo of syncPoints) {
  22891. const {
  22892. syncPoint,
  22893. strategy
  22894. } = syncPointInfo;
  22895. const {
  22896. segmentIndex,
  22897. time
  22898. } = syncPoint;
  22899. if (segmentIndex < 0) {
  22900. continue;
  22901. }
  22902. const selectedSegment = playlist.segments[segmentIndex];
  22903. const start = time;
  22904. const end = start + selectedSegment.duration;
  22905. this.logger_(`Strategy: ${strategy}. Current time: ${currentTime}. selected segment: ${segmentIndex}. Time: [${start} -> ${end}]}`);
  22906. if (currentTime >= start && currentTime < end) {
  22907. this.logger_('Found sync point with exact match: ', syncPoint);
  22908. return syncPoint;
  22909. }
  22910. } // Now find the sync-point that is closest to the currentTime because
  22911. // that should result in the most accurate guess about which segment
  22912. // to fetch
  22913. return this.selectSyncPoint_(syncPoints, {
  22914. key: 'time',
  22915. value: currentTime
  22916. });
  22917. }
  22918. /**
  22919. * Calculate the amount of time that has expired off the playlist during playback
  22920. *
  22921. * @param {Playlist} playlist
  22922. * Playlist object to calculate expired from
  22923. * @param {number} duration
  22924. * Duration of the MediaSource (Infinity if playling a live source)
  22925. * @return {number|null}
  22926. * The amount of time that has expired off the playlist during playback. Null
  22927. * if no sync-points for the playlist can be found.
  22928. */
  22929. getExpiredTime(playlist, duration) {
  22930. if (!playlist || !playlist.segments) {
  22931. return null;
  22932. }
  22933. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0, 'main'); // Without sync-points, there is not enough information to determine the expired time
  22934. if (!syncPoints.length) {
  22935. return null;
  22936. }
  22937. const syncPoint = this.selectSyncPoint_(syncPoints, {
  22938. key: 'segmentIndex',
  22939. value: 0
  22940. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  22941. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  22942. if (syncPoint.segmentIndex > 0) {
  22943. syncPoint.time *= -1;
  22944. }
  22945. return Math.abs(syncPoint.time + sumDurations({
  22946. defaultDuration: playlist.targetDuration,
  22947. durationList: playlist.segments,
  22948. startIndex: syncPoint.segmentIndex,
  22949. endIndex: 0
  22950. }));
  22951. }
  22952. /**
  22953. * Runs each sync-point strategy and returns a list of sync-points returned by the
  22954. * strategies
  22955. *
  22956. * @private
  22957. * @param {Playlist} playlist
  22958. * The playlist that needs a sync-point
  22959. * @param {number} duration
  22960. * Duration of the MediaSource (Infinity if playing a live source)
  22961. * @param {number} currentTimeline
  22962. * The last timeline from which a segment was loaded
  22963. * @param {number} currentTime
  22964. * Current player's time
  22965. * @param {string} type
  22966. * Segment loader type
  22967. * @return {Array}
  22968. * A list of sync-point objects
  22969. */
  22970. runStrategies_(playlist, duration, currentTimeline, currentTime, type) {
  22971. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  22972. for (let i = 0; i < syncPointStrategies.length; i++) {
  22973. const strategy = syncPointStrategies[i];
  22974. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime, type);
  22975. if (syncPoint) {
  22976. syncPoint.strategy = strategy.name;
  22977. syncPoints.push({
  22978. strategy: strategy.name,
  22979. syncPoint
  22980. });
  22981. }
  22982. }
  22983. return syncPoints;
  22984. }
  22985. /**
  22986. * Selects the sync-point nearest the specified target
  22987. *
  22988. * @private
  22989. * @param {Array} syncPoints
  22990. * List of sync-points to select from
  22991. * @param {Object} target
  22992. * Object specifying the property and value we are targeting
  22993. * @param {string} target.key
  22994. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  22995. * @param {number} target.value
  22996. * The value to target for the specified key.
  22997. * @return {Object}
  22998. * The sync-point nearest the target
  22999. */
  23000. selectSyncPoint_(syncPoints, target) {
  23001. let bestSyncPoint = syncPoints[0].syncPoint;
  23002. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  23003. let bestStrategy = syncPoints[0].strategy;
  23004. for (let i = 1; i < syncPoints.length; i++) {
  23005. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  23006. if (newDistance < bestDistance) {
  23007. bestDistance = newDistance;
  23008. bestSyncPoint = syncPoints[i].syncPoint;
  23009. bestStrategy = syncPoints[i].strategy;
  23010. }
  23011. }
  23012. 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}` : '') + ']');
  23013. return bestSyncPoint;
  23014. }
  23015. /**
  23016. * Save any meta-data present on the segments when segments leave
  23017. * the live window to the playlist to allow for synchronization at the
  23018. * playlist level later.
  23019. *
  23020. * @param {Playlist} oldPlaylist - The previous active playlist
  23021. * @param {Playlist} newPlaylist - The updated and most current playlist
  23022. */
  23023. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  23024. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  23025. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  23026. videojs__default["default"].log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  23027. return;
  23028. } // When a segment expires from the playlist and it has a start time
  23029. // save that information as a possible sync-point reference in future
  23030. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  23031. const lastRemovedSegment = oldPlaylist.segments[i];
  23032. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  23033. newPlaylist.syncInfo = {
  23034. mediaSequence: oldPlaylist.mediaSequence + i,
  23035. time: lastRemovedSegment.start
  23036. };
  23037. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  23038. this.trigger('syncinfoupdate');
  23039. break;
  23040. }
  23041. }
  23042. }
  23043. /**
  23044. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  23045. * before segments start to load.
  23046. *
  23047. * @param {Playlist} playlist - The currently active playlist
  23048. */
  23049. setDateTimeMappingForStart(playlist) {
  23050. // It's possible for the playlist to be updated before playback starts, meaning time
  23051. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  23052. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  23053. // unless the mappings are cleared.
  23054. this.timelineToDatetimeMappings = {};
  23055. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  23056. const firstSegment = playlist.segments[0];
  23057. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  23058. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  23059. }
  23060. }
  23061. /**
  23062. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  23063. * based on the latest timing information.
  23064. *
  23065. * @param {Object} options
  23066. * Options object
  23067. * @param {SegmentInfo} options.segmentInfo
  23068. * The current active request information
  23069. * @param {boolean} options.shouldSaveTimelineMapping
  23070. * If there's a timeline change, determines if the timeline mapping should be
  23071. * saved for timeline mapping and program date time mappings.
  23072. */
  23073. saveSegmentTimingInfo({
  23074. segmentInfo,
  23075. shouldSaveTimelineMapping
  23076. }) {
  23077. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  23078. const segment = segmentInfo.segment;
  23079. if (didCalculateSegmentTimeMapping) {
  23080. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  23081. // now with segment timing information
  23082. if (!segmentInfo.playlist.syncInfo) {
  23083. segmentInfo.playlist.syncInfo = {
  23084. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  23085. time: segment.start
  23086. };
  23087. }
  23088. }
  23089. const dateTime = segment.dateTimeObject;
  23090. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  23091. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  23092. }
  23093. }
  23094. timestampOffsetForTimeline(timeline) {
  23095. if (typeof this.timelines[timeline] === 'undefined') {
  23096. return null;
  23097. }
  23098. return this.timelines[timeline].time;
  23099. }
  23100. mappingForTimeline(timeline) {
  23101. if (typeof this.timelines[timeline] === 'undefined') {
  23102. return null;
  23103. }
  23104. return this.timelines[timeline].mapping;
  23105. }
  23106. /**
  23107. * Use the "media time" for a segment to generate a mapping to "display time" and
  23108. * save that display time to the segment.
  23109. *
  23110. * @private
  23111. * @param {SegmentInfo} segmentInfo
  23112. * The current active request information
  23113. * @param {Object} timingInfo
  23114. * The start and end time of the current segment in "media time"
  23115. * @param {boolean} shouldSaveTimelineMapping
  23116. * If there's a timeline change, determines if the timeline mapping should be
  23117. * saved in timelines.
  23118. * @return {boolean}
  23119. * Returns false if segment time mapping could not be calculated
  23120. */
  23121. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  23122. // TODO: remove side effects
  23123. const segment = segmentInfo.segment;
  23124. const part = segmentInfo.part;
  23125. let mappingObj = this.timelines[segmentInfo.timeline];
  23126. let start;
  23127. let end;
  23128. if (typeof segmentInfo.timestampOffset === 'number') {
  23129. mappingObj = {
  23130. time: segmentInfo.startOfSegment,
  23131. mapping: segmentInfo.startOfSegment - timingInfo.start
  23132. };
  23133. if (shouldSaveTimelineMapping) {
  23134. this.timelines[segmentInfo.timeline] = mappingObj;
  23135. this.trigger('timestampoffset');
  23136. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  23137. }
  23138. start = segmentInfo.startOfSegment;
  23139. end = timingInfo.end + mappingObj.mapping;
  23140. } else if (mappingObj) {
  23141. start = timingInfo.start + mappingObj.mapping;
  23142. end = timingInfo.end + mappingObj.mapping;
  23143. } else {
  23144. return false;
  23145. }
  23146. if (part) {
  23147. part.start = start;
  23148. part.end = end;
  23149. } // If we don't have a segment start yet or the start value we got
  23150. // is less than our current segment.start value, save a new start value.
  23151. // We have to do this because parts will have segment timing info saved
  23152. // multiple times and we want segment start to be the earliest part start
  23153. // value for that segment.
  23154. if (!segment.start || start < segment.start) {
  23155. segment.start = start;
  23156. }
  23157. segment.end = end;
  23158. return true;
  23159. }
  23160. /**
  23161. * Each time we have discontinuity in the playlist, attempt to calculate the location
  23162. * in display of the start of the discontinuity and save that. We also save an accuracy
  23163. * value so that we save values with the most accuracy (closest to 0.)
  23164. *
  23165. * @private
  23166. * @param {SegmentInfo} segmentInfo - The current active request information
  23167. */
  23168. saveDiscontinuitySyncInfo_(segmentInfo) {
  23169. const playlist = segmentInfo.playlist;
  23170. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  23171. // the start of the range and it's accuracy is 0 (greater accuracy values
  23172. // mean more approximation)
  23173. if (segment.discontinuity) {
  23174. this.discontinuities[segment.timeline] = {
  23175. time: segment.start,
  23176. accuracy: 0
  23177. };
  23178. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  23179. // Search for future discontinuities that we can provide better timing
  23180. // information for and save that information for sync purposes
  23181. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  23182. const segmentIndex = playlist.discontinuityStarts[i];
  23183. const discontinuity = playlist.discontinuitySequence + i + 1;
  23184. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  23185. const accuracy = Math.abs(mediaIndexDiff);
  23186. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  23187. let time;
  23188. if (mediaIndexDiff < 0) {
  23189. time = segment.start - sumDurations({
  23190. defaultDuration: playlist.targetDuration,
  23191. durationList: playlist.segments,
  23192. startIndex: segmentInfo.mediaIndex,
  23193. endIndex: segmentIndex
  23194. });
  23195. } else {
  23196. time = segment.end + sumDurations({
  23197. defaultDuration: playlist.targetDuration,
  23198. durationList: playlist.segments,
  23199. startIndex: segmentInfo.mediaIndex + 1,
  23200. endIndex: segmentIndex
  23201. });
  23202. }
  23203. this.discontinuities[discontinuity] = {
  23204. time,
  23205. accuracy
  23206. };
  23207. }
  23208. }
  23209. }
  23210. }
  23211. dispose() {
  23212. this.trigger('dispose');
  23213. this.off();
  23214. }
  23215. }
  23216. /**
  23217. * The TimelineChangeController acts as a source for segment loaders to listen for and
  23218. * keep track of latest and pending timeline changes. This is useful to ensure proper
  23219. * sync, as each loader may need to make a consideration for what timeline the other
  23220. * loader is on before making changes which could impact the other loader's media.
  23221. *
  23222. * @class TimelineChangeController
  23223. * @extends videojs.EventTarget
  23224. */
  23225. class TimelineChangeController extends videojs__default["default"].EventTarget {
  23226. constructor() {
  23227. super();
  23228. this.pendingTimelineChanges_ = {};
  23229. this.lastTimelineChanges_ = {};
  23230. }
  23231. clearPendingTimelineChange(type) {
  23232. this.pendingTimelineChanges_[type] = null;
  23233. this.trigger('pendingtimelinechange');
  23234. }
  23235. pendingTimelineChange({
  23236. type,
  23237. from,
  23238. to
  23239. }) {
  23240. if (typeof from === 'number' && typeof to === 'number') {
  23241. this.pendingTimelineChanges_[type] = {
  23242. type,
  23243. from,
  23244. to
  23245. };
  23246. this.trigger('pendingtimelinechange');
  23247. }
  23248. return this.pendingTimelineChanges_[type];
  23249. }
  23250. lastTimelineChange({
  23251. type,
  23252. from,
  23253. to
  23254. }) {
  23255. if (typeof from === 'number' && typeof to === 'number') {
  23256. this.lastTimelineChanges_[type] = {
  23257. type,
  23258. from,
  23259. to
  23260. };
  23261. delete this.pendingTimelineChanges_[type];
  23262. this.trigger('timelinechange');
  23263. }
  23264. return this.lastTimelineChanges_[type];
  23265. }
  23266. dispose() {
  23267. this.trigger('dispose');
  23268. this.pendingTimelineChanges_ = {};
  23269. this.lastTimelineChanges_ = {};
  23270. this.off();
  23271. }
  23272. }
  23273. /* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
  23274. const workerCode = transform(function (self) {
  23275. /**
  23276. * @file stream.js
  23277. */
  23278. /**
  23279. * A lightweight readable stream implemention that handles event dispatching.
  23280. *
  23281. * @class Stream
  23282. */
  23283. var Stream = /*#__PURE__*/function () {
  23284. function Stream() {
  23285. this.listeners = {};
  23286. }
  23287. /**
  23288. * Add a listener for a specified event type.
  23289. *
  23290. * @param {string} type the event name
  23291. * @param {Function} listener the callback to be invoked when an event of
  23292. * the specified type occurs
  23293. */
  23294. var _proto = Stream.prototype;
  23295. _proto.on = function on(type, listener) {
  23296. if (!this.listeners[type]) {
  23297. this.listeners[type] = [];
  23298. }
  23299. this.listeners[type].push(listener);
  23300. }
  23301. /**
  23302. * Remove a listener for a specified event type.
  23303. *
  23304. * @param {string} type the event name
  23305. * @param {Function} listener a function previously registered for this
  23306. * type of event through `on`
  23307. * @return {boolean} if we could turn it off or not
  23308. */
  23309. ;
  23310. _proto.off = function off(type, listener) {
  23311. if (!this.listeners[type]) {
  23312. return false;
  23313. }
  23314. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  23315. // In Video.js we slice listener functions
  23316. // on trigger so that it does not mess up the order
  23317. // while we loop through.
  23318. //
  23319. // Here we slice on off so that the loop in trigger
  23320. // can continue using it's old reference to loop without
  23321. // messing up the order.
  23322. this.listeners[type] = this.listeners[type].slice(0);
  23323. this.listeners[type].splice(index, 1);
  23324. return index > -1;
  23325. }
  23326. /**
  23327. * Trigger an event of the specified type on this stream. Any additional
  23328. * arguments to this function are passed as parameters to event listeners.
  23329. *
  23330. * @param {string} type the event name
  23331. */
  23332. ;
  23333. _proto.trigger = function trigger(type) {
  23334. var callbacks = this.listeners[type];
  23335. if (!callbacks) {
  23336. return;
  23337. } // Slicing the arguments on every invocation of this method
  23338. // can add a significant amount of overhead. Avoid the
  23339. // intermediate object creation for the common case of a
  23340. // single callback argument
  23341. if (arguments.length === 2) {
  23342. var length = callbacks.length;
  23343. for (var i = 0; i < length; ++i) {
  23344. callbacks[i].call(this, arguments[1]);
  23345. }
  23346. } else {
  23347. var args = Array.prototype.slice.call(arguments, 1);
  23348. var _length = callbacks.length;
  23349. for (var _i = 0; _i < _length; ++_i) {
  23350. callbacks[_i].apply(this, args);
  23351. }
  23352. }
  23353. }
  23354. /**
  23355. * Destroys the stream and cleans up.
  23356. */
  23357. ;
  23358. _proto.dispose = function dispose() {
  23359. this.listeners = {};
  23360. }
  23361. /**
  23362. * Forwards all `data` events on this stream to the destination stream. The
  23363. * destination stream should provide a method `push` to receive the data
  23364. * events as they arrive.
  23365. *
  23366. * @param {Stream} destination the stream that will receive all `data` events
  23367. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  23368. */
  23369. ;
  23370. _proto.pipe = function pipe(destination) {
  23371. this.on('data', function (data) {
  23372. destination.push(data);
  23373. });
  23374. };
  23375. return Stream;
  23376. }();
  23377. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  23378. /**
  23379. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  23380. *
  23381. * @param padded {Uint8Array} unencrypted bytes that have been padded
  23382. * @return {Uint8Array} the unpadded bytes
  23383. * @see http://tools.ietf.org/html/rfc5652
  23384. */
  23385. function unpad(padded) {
  23386. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  23387. }
  23388. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  23389. /**
  23390. * @file aes.js
  23391. *
  23392. * This file contains an adaptation of the AES decryption algorithm
  23393. * from the Standford Javascript Cryptography Library. That work is
  23394. * covered by the following copyright and permissions notice:
  23395. *
  23396. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  23397. * All rights reserved.
  23398. *
  23399. * Redistribution and use in source and binary forms, with or without
  23400. * modification, are permitted provided that the following conditions are
  23401. * met:
  23402. *
  23403. * 1. Redistributions of source code must retain the above copyright
  23404. * notice, this list of conditions and the following disclaimer.
  23405. *
  23406. * 2. Redistributions in binary form must reproduce the above
  23407. * copyright notice, this list of conditions and the following
  23408. * disclaimer in the documentation and/or other materials provided
  23409. * with the distribution.
  23410. *
  23411. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  23412. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  23413. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23414. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  23415. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  23416. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23417. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  23418. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23419. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  23420. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  23421. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23422. *
  23423. * The views and conclusions contained in the software and documentation
  23424. * are those of the authors and should not be interpreted as representing
  23425. * official policies, either expressed or implied, of the authors.
  23426. */
  23427. /**
  23428. * Expand the S-box tables.
  23429. *
  23430. * @private
  23431. */
  23432. const precompute = function () {
  23433. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  23434. const encTable = tables[0];
  23435. const decTable = tables[1];
  23436. const sbox = encTable[4];
  23437. const sboxInv = decTable[4];
  23438. let i;
  23439. let x;
  23440. let xInv;
  23441. const d = [];
  23442. const th = [];
  23443. let x2;
  23444. let x4;
  23445. let x8;
  23446. let s;
  23447. let tEnc;
  23448. let tDec; // Compute double and third tables
  23449. for (i = 0; i < 256; i++) {
  23450. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  23451. }
  23452. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  23453. // Compute sbox
  23454. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  23455. s = s >> 8 ^ s & 255 ^ 99;
  23456. sbox[x] = s;
  23457. sboxInv[s] = x; // Compute MixColumns
  23458. x8 = d[x4 = d[x2 = d[x]]];
  23459. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  23460. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  23461. for (i = 0; i < 4; i++) {
  23462. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  23463. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  23464. }
  23465. } // Compactify. Considerable speedup on Firefox.
  23466. for (i = 0; i < 5; i++) {
  23467. encTable[i] = encTable[i].slice(0);
  23468. decTable[i] = decTable[i].slice(0);
  23469. }
  23470. return tables;
  23471. };
  23472. let aesTables = null;
  23473. /**
  23474. * Schedule out an AES key for both encryption and decryption. This
  23475. * is a low-level class. Use a cipher mode to do bulk encryption.
  23476. *
  23477. * @class AES
  23478. * @param key {Array} The key as an array of 4, 6 or 8 words.
  23479. */
  23480. class AES {
  23481. constructor(key) {
  23482. /**
  23483. * The expanded S-box and inverse S-box tables. These will be computed
  23484. * on the client so that we don't have to send them down the wire.
  23485. *
  23486. * There are two tables, _tables[0] is for encryption and
  23487. * _tables[1] is for decryption.
  23488. *
  23489. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  23490. * last (_tables[01][4]) is the S-box itself.
  23491. *
  23492. * @private
  23493. */
  23494. // if we have yet to precompute the S-box tables
  23495. // do so now
  23496. if (!aesTables) {
  23497. aesTables = precompute();
  23498. } // then make a copy of that object for use
  23499. 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()]];
  23500. let i;
  23501. let j;
  23502. let tmp;
  23503. const sbox = this._tables[0][4];
  23504. const decTable = this._tables[1];
  23505. const keyLen = key.length;
  23506. let rcon = 1;
  23507. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  23508. throw new Error('Invalid aes key size');
  23509. }
  23510. const encKey = key.slice(0);
  23511. const decKey = [];
  23512. this._key = [encKey, decKey]; // schedule encryption keys
  23513. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  23514. tmp = encKey[i - 1]; // apply sbox
  23515. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  23516. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  23517. if (i % keyLen === 0) {
  23518. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  23519. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  23520. }
  23521. }
  23522. encKey[i] = encKey[i - keyLen] ^ tmp;
  23523. } // schedule decryption keys
  23524. for (j = 0; i; j++, i--) {
  23525. tmp = encKey[j & 3 ? i : i - 4];
  23526. if (i <= 4 || j < 4) {
  23527. decKey[j] = tmp;
  23528. } else {
  23529. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  23530. }
  23531. }
  23532. }
  23533. /**
  23534. * Decrypt 16 bytes, specified as four 32-bit words.
  23535. *
  23536. * @param {number} encrypted0 the first word to decrypt
  23537. * @param {number} encrypted1 the second word to decrypt
  23538. * @param {number} encrypted2 the third word to decrypt
  23539. * @param {number} encrypted3 the fourth word to decrypt
  23540. * @param {Int32Array} out the array to write the decrypted words
  23541. * into
  23542. * @param {number} offset the offset into the output array to start
  23543. * writing results
  23544. * @return {Array} The plaintext.
  23545. */
  23546. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  23547. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  23548. let a = encrypted0 ^ key[0];
  23549. let b = encrypted3 ^ key[1];
  23550. let c = encrypted2 ^ key[2];
  23551. let d = encrypted1 ^ key[3];
  23552. let a2;
  23553. let b2;
  23554. let c2; // key.length === 2 ?
  23555. const nInnerRounds = key.length / 4 - 2;
  23556. let i;
  23557. let kIndex = 4;
  23558. const table = this._tables[1]; // load up the tables
  23559. const table0 = table[0];
  23560. const table1 = table[1];
  23561. const table2 = table[2];
  23562. const table3 = table[3];
  23563. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  23564. for (i = 0; i < nInnerRounds; i++) {
  23565. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  23566. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  23567. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  23568. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  23569. kIndex += 4;
  23570. a = a2;
  23571. b = b2;
  23572. c = c2;
  23573. } // Last round.
  23574. for (i = 0; i < 4; i++) {
  23575. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  23576. a2 = a;
  23577. a = b;
  23578. b = c;
  23579. c = d;
  23580. d = a2;
  23581. }
  23582. }
  23583. }
  23584. /**
  23585. * @file async-stream.js
  23586. */
  23587. /**
  23588. * A wrapper around the Stream class to use setTimeout
  23589. * and run stream "jobs" Asynchronously
  23590. *
  23591. * @class AsyncStream
  23592. * @extends Stream
  23593. */
  23594. class AsyncStream extends Stream {
  23595. constructor() {
  23596. super(Stream);
  23597. this.jobs = [];
  23598. this.delay = 1;
  23599. this.timeout_ = null;
  23600. }
  23601. /**
  23602. * process an async job
  23603. *
  23604. * @private
  23605. */
  23606. processJob_() {
  23607. this.jobs.shift()();
  23608. if (this.jobs.length) {
  23609. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  23610. } else {
  23611. this.timeout_ = null;
  23612. }
  23613. }
  23614. /**
  23615. * push a job into the stream
  23616. *
  23617. * @param {Function} job the job to push into the stream
  23618. */
  23619. push(job) {
  23620. this.jobs.push(job);
  23621. if (!this.timeout_) {
  23622. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  23623. }
  23624. }
  23625. }
  23626. /**
  23627. * @file decrypter.js
  23628. *
  23629. * An asynchronous implementation of AES-128 CBC decryption with
  23630. * PKCS#7 padding.
  23631. */
  23632. /**
  23633. * Convert network-order (big-endian) bytes into their little-endian
  23634. * representation.
  23635. */
  23636. const ntoh = function (word) {
  23637. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  23638. };
  23639. /**
  23640. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  23641. *
  23642. * @param {Uint8Array} encrypted the encrypted bytes
  23643. * @param {Uint32Array} key the bytes of the decryption key
  23644. * @param {Uint32Array} initVector the initialization vector (IV) to
  23645. * use for the first round of CBC.
  23646. * @return {Uint8Array} the decrypted bytes
  23647. *
  23648. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  23649. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  23650. * @see https://tools.ietf.org/html/rfc2315
  23651. */
  23652. const decrypt = function (encrypted, key, initVector) {
  23653. // word-level access to the encrypted bytes
  23654. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  23655. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  23656. const decrypted = new Uint8Array(encrypted.byteLength);
  23657. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  23658. // decrypted data
  23659. let init0;
  23660. let init1;
  23661. let init2;
  23662. let init3;
  23663. let encrypted0;
  23664. let encrypted1;
  23665. let encrypted2;
  23666. let encrypted3; // iteration variable
  23667. let wordIx; // pull out the words of the IV to ensure we don't modify the
  23668. // passed-in reference and easier access
  23669. init0 = initVector[0];
  23670. init1 = initVector[1];
  23671. init2 = initVector[2];
  23672. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  23673. // to each decrypted block
  23674. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  23675. // convert big-endian (network order) words into little-endian
  23676. // (javascript order)
  23677. encrypted0 = ntoh(encrypted32[wordIx]);
  23678. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  23679. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  23680. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  23681. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  23682. // plaintext
  23683. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  23684. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  23685. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  23686. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  23687. init0 = encrypted0;
  23688. init1 = encrypted1;
  23689. init2 = encrypted2;
  23690. init3 = encrypted3;
  23691. }
  23692. return decrypted;
  23693. };
  23694. /**
  23695. * The `Decrypter` class that manages decryption of AES
  23696. * data through `AsyncStream` objects and the `decrypt`
  23697. * function
  23698. *
  23699. * @param {Uint8Array} encrypted the encrypted bytes
  23700. * @param {Uint32Array} key the bytes of the decryption key
  23701. * @param {Uint32Array} initVector the initialization vector (IV) to
  23702. * @param {Function} done the function to run when done
  23703. * @class Decrypter
  23704. */
  23705. class Decrypter {
  23706. constructor(encrypted, key, initVector, done) {
  23707. const step = Decrypter.STEP;
  23708. const encrypted32 = new Int32Array(encrypted.buffer);
  23709. const decrypted = new Uint8Array(encrypted.byteLength);
  23710. let i = 0;
  23711. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  23712. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  23713. for (i = step; i < encrypted32.length; i += step) {
  23714. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  23715. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  23716. } // invoke the done() callback when everything is finished
  23717. this.asyncStream_.push(function () {
  23718. // remove pkcs#7 padding from the decrypted bytes
  23719. done(null, unpad(decrypted));
  23720. });
  23721. }
  23722. /**
  23723. * a getter for step the maximum number of bytes to process at one time
  23724. *
  23725. * @return {number} the value of step 32000
  23726. */
  23727. static get STEP() {
  23728. // 4 * 8000;
  23729. return 32000;
  23730. }
  23731. /**
  23732. * @private
  23733. */
  23734. decryptChunk_(encrypted, key, initVector, decrypted) {
  23735. return function () {
  23736. const bytes = decrypt(encrypted, key, initVector);
  23737. decrypted.set(bytes, encrypted.byteOffset);
  23738. };
  23739. }
  23740. }
  23741. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  23742. var win;
  23743. if (typeof window !== "undefined") {
  23744. win = window;
  23745. } else if (typeof commonjsGlobal !== "undefined") {
  23746. win = commonjsGlobal;
  23747. } else if (typeof self !== "undefined") {
  23748. win = self;
  23749. } else {
  23750. win = {};
  23751. }
  23752. var window_1 = win;
  23753. var isArrayBufferView = function isArrayBufferView(obj) {
  23754. if (ArrayBuffer.isView === 'function') {
  23755. return ArrayBuffer.isView(obj);
  23756. }
  23757. return obj && obj.buffer instanceof ArrayBuffer;
  23758. };
  23759. var BigInt = window_1.BigInt || Number;
  23760. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  23761. (function () {
  23762. var a = new Uint16Array([0xFFCC]);
  23763. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  23764. if (b[0] === 0xFF) {
  23765. return 'big';
  23766. }
  23767. if (b[0] === 0xCC) {
  23768. return 'little';
  23769. }
  23770. return 'unknown';
  23771. })();
  23772. /**
  23773. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  23774. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  23775. *
  23776. * @param {Object} message
  23777. * Object of properties and values to send to the web worker
  23778. * @return {Object}
  23779. * Modified message with TypedArray values expanded
  23780. * @function createTransferableMessage
  23781. */
  23782. const createTransferableMessage = function (message) {
  23783. const transferable = {};
  23784. Object.keys(message).forEach(key => {
  23785. const value = message[key];
  23786. if (isArrayBufferView(value)) {
  23787. transferable[key] = {
  23788. bytes: value.buffer,
  23789. byteOffset: value.byteOffset,
  23790. byteLength: value.byteLength
  23791. };
  23792. } else {
  23793. transferable[key] = value;
  23794. }
  23795. });
  23796. return transferable;
  23797. };
  23798. /* global self */
  23799. /**
  23800. * Our web worker interface so that things can talk to aes-decrypter
  23801. * that will be running in a web worker. the scope is passed to this by
  23802. * webworkify.
  23803. */
  23804. self.onmessage = function (event) {
  23805. const data = event.data;
  23806. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  23807. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  23808. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  23809. /* eslint-disable no-new, handle-callback-err */
  23810. new Decrypter(encrypted, key, iv, function (err, bytes) {
  23811. self.postMessage(createTransferableMessage({
  23812. source: data.source,
  23813. decrypted: bytes
  23814. }), [bytes.buffer]);
  23815. });
  23816. /* eslint-enable */
  23817. };
  23818. });
  23819. var Decrypter = factory(workerCode);
  23820. /* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
  23821. /**
  23822. * Convert the properties of an HLS track into an audioTrackKind.
  23823. *
  23824. * @private
  23825. */
  23826. const audioTrackKind_ = properties => {
  23827. let kind = properties.default ? 'main' : 'alternative';
  23828. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  23829. kind = 'main-desc';
  23830. }
  23831. return kind;
  23832. };
  23833. /**
  23834. * Pause provided segment loader and playlist loader if active
  23835. *
  23836. * @param {SegmentLoader} segmentLoader
  23837. * SegmentLoader to pause
  23838. * @param {Object} mediaType
  23839. * Active media type
  23840. * @function stopLoaders
  23841. */
  23842. const stopLoaders = (segmentLoader, mediaType) => {
  23843. segmentLoader.abort();
  23844. segmentLoader.pause();
  23845. if (mediaType && mediaType.activePlaylistLoader) {
  23846. mediaType.activePlaylistLoader.pause();
  23847. mediaType.activePlaylistLoader = null;
  23848. }
  23849. };
  23850. /**
  23851. * Start loading provided segment loader and playlist loader
  23852. *
  23853. * @param {PlaylistLoader} playlistLoader
  23854. * PlaylistLoader to start loading
  23855. * @param {Object} mediaType
  23856. * Active media type
  23857. * @function startLoaders
  23858. */
  23859. const startLoaders = (playlistLoader, mediaType) => {
  23860. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  23861. // playlist loader
  23862. mediaType.activePlaylistLoader = playlistLoader;
  23863. playlistLoader.load();
  23864. };
  23865. /**
  23866. * Returns a function to be called when the media group changes. It performs a
  23867. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  23868. * change of group is merely a rendition switch of the same content at another encoding,
  23869. * rather than a change of content, such as switching audio from English to Spanish.
  23870. *
  23871. * @param {string} type
  23872. * MediaGroup type
  23873. * @param {Object} settings
  23874. * Object containing required information for media groups
  23875. * @return {Function}
  23876. * Handler for a non-destructive resync of SegmentLoader when the active media
  23877. * group changes.
  23878. * @function onGroupChanged
  23879. */
  23880. const onGroupChanged = (type, settings) => () => {
  23881. const {
  23882. segmentLoaders: {
  23883. [type]: segmentLoader,
  23884. main: mainSegmentLoader
  23885. },
  23886. mediaTypes: {
  23887. [type]: mediaType
  23888. }
  23889. } = settings;
  23890. const activeTrack = mediaType.activeTrack();
  23891. const activeGroup = mediaType.getActiveGroup();
  23892. const previousActiveLoader = mediaType.activePlaylistLoader;
  23893. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  23894. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  23895. return;
  23896. }
  23897. mediaType.lastGroup_ = activeGroup;
  23898. mediaType.lastTrack_ = activeTrack;
  23899. stopLoaders(segmentLoader, mediaType);
  23900. if (!activeGroup || activeGroup.isMainPlaylist) {
  23901. // there is no group active or active group is a main playlist and won't change
  23902. return;
  23903. }
  23904. if (!activeGroup.playlistLoader) {
  23905. if (previousActiveLoader) {
  23906. // The previous group had a playlist loader but the new active group does not
  23907. // this means we are switching from demuxed to muxed audio. In this case we want to
  23908. // do a destructive reset of the main segment loader and not restart the audio
  23909. // loaders.
  23910. mainSegmentLoader.resetEverything();
  23911. }
  23912. return;
  23913. } // Non-destructive resync
  23914. segmentLoader.resyncLoader();
  23915. startLoaders(activeGroup.playlistLoader, mediaType);
  23916. };
  23917. const onGroupChanging = (type, settings) => () => {
  23918. const {
  23919. segmentLoaders: {
  23920. [type]: segmentLoader
  23921. },
  23922. mediaTypes: {
  23923. [type]: mediaType
  23924. }
  23925. } = settings;
  23926. mediaType.lastGroup_ = null;
  23927. segmentLoader.abort();
  23928. segmentLoader.pause();
  23929. };
  23930. /**
  23931. * Returns a function to be called when the media track changes. It performs a
  23932. * destructive reset of the SegmentLoader to ensure we start loading as close to
  23933. * currentTime as possible.
  23934. *
  23935. * @param {string} type
  23936. * MediaGroup type
  23937. * @param {Object} settings
  23938. * Object containing required information for media groups
  23939. * @return {Function}
  23940. * Handler for a destructive reset of SegmentLoader when the active media
  23941. * track changes.
  23942. * @function onTrackChanged
  23943. */
  23944. const onTrackChanged = (type, settings) => () => {
  23945. const {
  23946. mainPlaylistLoader,
  23947. segmentLoaders: {
  23948. [type]: segmentLoader,
  23949. main: mainSegmentLoader
  23950. },
  23951. mediaTypes: {
  23952. [type]: mediaType
  23953. }
  23954. } = settings;
  23955. const activeTrack = mediaType.activeTrack();
  23956. const activeGroup = mediaType.getActiveGroup();
  23957. const previousActiveLoader = mediaType.activePlaylistLoader;
  23958. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  23959. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  23960. return;
  23961. }
  23962. mediaType.lastGroup_ = activeGroup;
  23963. mediaType.lastTrack_ = activeTrack;
  23964. stopLoaders(segmentLoader, mediaType);
  23965. if (!activeGroup) {
  23966. // there is no group active so we do not want to restart loaders
  23967. return;
  23968. }
  23969. if (activeGroup.isMainPlaylist) {
  23970. // track did not change, do nothing
  23971. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  23972. return;
  23973. }
  23974. const pc = settings.vhs.playlistController_;
  23975. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  23976. if (pc.media() === newPlaylist) {
  23977. return;
  23978. }
  23979. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  23980. mainPlaylistLoader.pause();
  23981. mainSegmentLoader.resetEverything();
  23982. pc.fastQualityChange_(newPlaylist);
  23983. return;
  23984. }
  23985. if (type === 'AUDIO') {
  23986. if (!activeGroup.playlistLoader) {
  23987. // when switching from demuxed audio/video to muxed audio/video (noted by no
  23988. // playlist loader for the audio group), we want to do a destructive reset of the
  23989. // main segment loader and not restart the audio loaders
  23990. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  23991. // it should be stopped
  23992. mainSegmentLoader.resetEverything();
  23993. return;
  23994. } // although the segment loader is an audio segment loader, call the setAudio
  23995. // function to ensure it is prepared to re-append the init segment (or handle other
  23996. // config changes)
  23997. segmentLoader.setAudio(true);
  23998. mainSegmentLoader.setAudio(false);
  23999. }
  24000. if (previousActiveLoader === activeGroup.playlistLoader) {
  24001. // Nothing has actually changed. This can happen because track change events can fire
  24002. // multiple times for a "single" change. One for enabling the new active track, and
  24003. // one for disabling the track that was active
  24004. startLoaders(activeGroup.playlistLoader, mediaType);
  24005. return;
  24006. }
  24007. if (segmentLoader.track) {
  24008. // For WebVTT, set the new text track in the segmentloader
  24009. segmentLoader.track(activeTrack);
  24010. } // destructive reset
  24011. segmentLoader.resetEverything();
  24012. startLoaders(activeGroup.playlistLoader, mediaType);
  24013. };
  24014. const onError = {
  24015. /**
  24016. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  24017. * an error.
  24018. *
  24019. * @param {string} type
  24020. * MediaGroup type
  24021. * @param {Object} settings
  24022. * Object containing required information for media groups
  24023. * @return {Function}
  24024. * Error handler. Logs warning (or error if the playlist is excluded) to
  24025. * console and switches back to default audio track.
  24026. * @function onError.AUDIO
  24027. */
  24028. AUDIO: (type, settings) => () => {
  24029. const {
  24030. mediaTypes: {
  24031. [type]: mediaType
  24032. },
  24033. excludePlaylist
  24034. } = settings; // switch back to default audio track
  24035. const activeTrack = mediaType.activeTrack();
  24036. const activeGroup = mediaType.activeGroup();
  24037. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  24038. const defaultTrack = mediaType.tracks[id];
  24039. if (activeTrack === defaultTrack) {
  24040. // Default track encountered an error. All we can do now is exclude the current
  24041. // rendition and hope another will switch audio groups
  24042. excludePlaylist({
  24043. error: {
  24044. message: 'Problem encountered loading the default audio track.'
  24045. }
  24046. });
  24047. return;
  24048. }
  24049. videojs__default["default"].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  24050. for (const trackId in mediaType.tracks) {
  24051. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  24052. }
  24053. mediaType.onTrackChanged();
  24054. },
  24055. /**
  24056. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  24057. * an error.
  24058. *
  24059. * @param {string} type
  24060. * MediaGroup type
  24061. * @param {Object} settings
  24062. * Object containing required information for media groups
  24063. * @return {Function}
  24064. * Error handler. Logs warning to console and disables the active subtitle track
  24065. * @function onError.SUBTITLES
  24066. */
  24067. SUBTITLES: (type, settings) => () => {
  24068. const {
  24069. mediaTypes: {
  24070. [type]: mediaType
  24071. }
  24072. } = settings;
  24073. videojs__default["default"].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  24074. const track = mediaType.activeTrack();
  24075. if (track) {
  24076. track.mode = 'disabled';
  24077. }
  24078. mediaType.onTrackChanged();
  24079. }
  24080. };
  24081. const setupListeners = {
  24082. /**
  24083. * Setup event listeners for audio playlist loader
  24084. *
  24085. * @param {string} type
  24086. * MediaGroup type
  24087. * @param {PlaylistLoader|null} playlistLoader
  24088. * PlaylistLoader to register listeners on
  24089. * @param {Object} settings
  24090. * Object containing required information for media groups
  24091. * @function setupListeners.AUDIO
  24092. */
  24093. AUDIO: (type, playlistLoader, settings) => {
  24094. if (!playlistLoader) {
  24095. // no playlist loader means audio will be muxed with the video
  24096. return;
  24097. }
  24098. const {
  24099. tech,
  24100. requestOptions,
  24101. segmentLoaders: {
  24102. [type]: segmentLoader
  24103. }
  24104. } = settings;
  24105. playlistLoader.on('loadedmetadata', () => {
  24106. const media = playlistLoader.media();
  24107. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  24108. // permits, start downloading segments
  24109. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  24110. segmentLoader.load();
  24111. }
  24112. });
  24113. playlistLoader.on('loadedplaylist', () => {
  24114. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  24115. if (!tech.paused()) {
  24116. segmentLoader.load();
  24117. }
  24118. });
  24119. playlistLoader.on('error', onError[type](type, settings));
  24120. },
  24121. /**
  24122. * Setup event listeners for subtitle playlist loader
  24123. *
  24124. * @param {string} type
  24125. * MediaGroup type
  24126. * @param {PlaylistLoader|null} playlistLoader
  24127. * PlaylistLoader to register listeners on
  24128. * @param {Object} settings
  24129. * Object containing required information for media groups
  24130. * @function setupListeners.SUBTITLES
  24131. */
  24132. SUBTITLES: (type, playlistLoader, settings) => {
  24133. const {
  24134. tech,
  24135. requestOptions,
  24136. segmentLoaders: {
  24137. [type]: segmentLoader
  24138. },
  24139. mediaTypes: {
  24140. [type]: mediaType
  24141. }
  24142. } = settings;
  24143. playlistLoader.on('loadedmetadata', () => {
  24144. const media = playlistLoader.media();
  24145. segmentLoader.playlist(media, requestOptions);
  24146. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  24147. // permits, start downloading segments
  24148. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  24149. segmentLoader.load();
  24150. }
  24151. });
  24152. playlistLoader.on('loadedplaylist', () => {
  24153. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  24154. if (!tech.paused()) {
  24155. segmentLoader.load();
  24156. }
  24157. });
  24158. playlistLoader.on('error', onError[type](type, settings));
  24159. }
  24160. };
  24161. const initialize = {
  24162. /**
  24163. * Setup PlaylistLoaders and AudioTracks for the audio groups
  24164. *
  24165. * @param {string} type
  24166. * MediaGroup type
  24167. * @param {Object} settings
  24168. * Object containing required information for media groups
  24169. * @function initialize.AUDIO
  24170. */
  24171. 'AUDIO': (type, settings) => {
  24172. const {
  24173. vhs,
  24174. sourceType,
  24175. segmentLoaders: {
  24176. [type]: segmentLoader
  24177. },
  24178. requestOptions,
  24179. main: {
  24180. mediaGroups
  24181. },
  24182. mediaTypes: {
  24183. [type]: {
  24184. groups,
  24185. tracks,
  24186. logger_
  24187. }
  24188. },
  24189. mainPlaylistLoader
  24190. } = settings;
  24191. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  24192. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  24193. mediaGroups[type] = {
  24194. main: {
  24195. default: {
  24196. default: true
  24197. }
  24198. }
  24199. };
  24200. if (audioOnlyMain) {
  24201. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  24202. }
  24203. }
  24204. for (const groupId in mediaGroups[type]) {
  24205. if (!groups[groupId]) {
  24206. groups[groupId] = [];
  24207. }
  24208. for (const variantLabel in mediaGroups[type][groupId]) {
  24209. let properties = mediaGroups[type][groupId][variantLabel];
  24210. let playlistLoader;
  24211. if (audioOnlyMain) {
  24212. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  24213. properties.isMainPlaylist = true;
  24214. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  24215. // use the resolved media playlist object
  24216. } else if (sourceType === 'vhs-json' && properties.playlists) {
  24217. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  24218. } else if (properties.resolvedUri) {
  24219. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  24220. // should we even have properties.playlists in this check.
  24221. } else if (properties.playlists && sourceType === 'dash') {
  24222. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  24223. } else {
  24224. // no resolvedUri means the audio is muxed with the video when using this
  24225. // audio track
  24226. playlistLoader = null;
  24227. }
  24228. properties = merge$1({
  24229. id: variantLabel,
  24230. playlistLoader
  24231. }, properties);
  24232. setupListeners[type](type, properties.playlistLoader, settings);
  24233. groups[groupId].push(properties);
  24234. if (typeof tracks[variantLabel] === 'undefined') {
  24235. const track = new videojs__default["default"].AudioTrack({
  24236. id: variantLabel,
  24237. kind: audioTrackKind_(properties),
  24238. enabled: false,
  24239. language: properties.language,
  24240. default: properties.default,
  24241. label: variantLabel
  24242. });
  24243. tracks[variantLabel] = track;
  24244. }
  24245. }
  24246. } // setup single error event handler for the segment loader
  24247. segmentLoader.on('error', onError[type](type, settings));
  24248. },
  24249. /**
  24250. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  24251. *
  24252. * @param {string} type
  24253. * MediaGroup type
  24254. * @param {Object} settings
  24255. * Object containing required information for media groups
  24256. * @function initialize.SUBTITLES
  24257. */
  24258. 'SUBTITLES': (type, settings) => {
  24259. const {
  24260. tech,
  24261. vhs,
  24262. sourceType,
  24263. segmentLoaders: {
  24264. [type]: segmentLoader
  24265. },
  24266. requestOptions,
  24267. main: {
  24268. mediaGroups
  24269. },
  24270. mediaTypes: {
  24271. [type]: {
  24272. groups,
  24273. tracks
  24274. }
  24275. },
  24276. mainPlaylistLoader
  24277. } = settings;
  24278. for (const groupId in mediaGroups[type]) {
  24279. if (!groups[groupId]) {
  24280. groups[groupId] = [];
  24281. }
  24282. for (const variantLabel in mediaGroups[type][groupId]) {
  24283. if (!vhs.options_.useForcedSubtitles && mediaGroups[type][groupId][variantLabel].forced) {
  24284. // Subtitle playlists with the forced attribute are not selectable in Safari.
  24285. // According to Apple's HLS Authoring Specification:
  24286. // If content has forced subtitles and regular subtitles in a given language,
  24287. // the regular subtitles track in that language MUST contain both the forced
  24288. // subtitles and the regular subtitles for that language.
  24289. // Because of this requirement and that Safari does not add forced subtitles,
  24290. // forced subtitles are skipped here to maintain consistent experience across
  24291. // all platforms
  24292. continue;
  24293. }
  24294. let properties = mediaGroups[type][groupId][variantLabel];
  24295. let playlistLoader;
  24296. if (sourceType === 'hls') {
  24297. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  24298. } else if (sourceType === 'dash') {
  24299. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  24300. if (!playlists.length) {
  24301. return;
  24302. }
  24303. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  24304. } else if (sourceType === 'vhs-json') {
  24305. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  24306. // as provided, otherwise use the resolved URI to load the playlist
  24307. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  24308. }
  24309. properties = merge$1({
  24310. id: variantLabel,
  24311. playlistLoader
  24312. }, properties);
  24313. setupListeners[type](type, properties.playlistLoader, settings);
  24314. groups[groupId].push(properties);
  24315. if (typeof tracks[variantLabel] === 'undefined') {
  24316. const track = tech.addRemoteTextTrack({
  24317. id: variantLabel,
  24318. kind: 'subtitles',
  24319. default: properties.default && properties.autoselect,
  24320. language: properties.language,
  24321. label: variantLabel
  24322. }, false).track;
  24323. tracks[variantLabel] = track;
  24324. }
  24325. }
  24326. } // setup single error event handler for the segment loader
  24327. segmentLoader.on('error', onError[type](type, settings));
  24328. },
  24329. /**
  24330. * Setup TextTracks for the closed-caption groups
  24331. *
  24332. * @param {String} type
  24333. * MediaGroup type
  24334. * @param {Object} settings
  24335. * Object containing required information for media groups
  24336. * @function initialize['CLOSED-CAPTIONS']
  24337. */
  24338. 'CLOSED-CAPTIONS': (type, settings) => {
  24339. const {
  24340. tech,
  24341. main: {
  24342. mediaGroups
  24343. },
  24344. mediaTypes: {
  24345. [type]: {
  24346. groups,
  24347. tracks
  24348. }
  24349. }
  24350. } = settings;
  24351. for (const groupId in mediaGroups[type]) {
  24352. if (!groups[groupId]) {
  24353. groups[groupId] = [];
  24354. }
  24355. for (const variantLabel in mediaGroups[type][groupId]) {
  24356. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  24357. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  24358. continue;
  24359. }
  24360. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  24361. let newProps = {
  24362. label: variantLabel,
  24363. language: properties.language,
  24364. instreamId: properties.instreamId,
  24365. default: properties.default && properties.autoselect
  24366. };
  24367. if (captionServices[newProps.instreamId]) {
  24368. newProps = merge$1(newProps, captionServices[newProps.instreamId]);
  24369. }
  24370. if (newProps.default === undefined) {
  24371. delete newProps.default;
  24372. } // No PlaylistLoader is required for Closed-Captions because the captions are
  24373. // embedded within the video stream
  24374. groups[groupId].push(merge$1({
  24375. id: variantLabel
  24376. }, properties));
  24377. if (typeof tracks[variantLabel] === 'undefined') {
  24378. const track = tech.addRemoteTextTrack({
  24379. id: newProps.instreamId,
  24380. kind: 'captions',
  24381. default: newProps.default,
  24382. language: newProps.language,
  24383. label: newProps.label
  24384. }, false).track;
  24385. tracks[variantLabel] = track;
  24386. }
  24387. }
  24388. }
  24389. }
  24390. };
  24391. const groupMatch = (list, media) => {
  24392. for (let i = 0; i < list.length; i++) {
  24393. if (playlistMatch(media, list[i])) {
  24394. return true;
  24395. }
  24396. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  24397. return true;
  24398. }
  24399. }
  24400. return false;
  24401. };
  24402. /**
  24403. * Returns a function used to get the active group of the provided type
  24404. *
  24405. * @param {string} type
  24406. * MediaGroup type
  24407. * @param {Object} settings
  24408. * Object containing required information for media groups
  24409. * @return {Function}
  24410. * Function that returns the active media group for the provided type. Takes an
  24411. * optional parameter {TextTrack} track. If no track is provided, a list of all
  24412. * variants in the group, otherwise the variant corresponding to the provided
  24413. * track is returned.
  24414. * @function activeGroup
  24415. */
  24416. const activeGroup = (type, settings) => track => {
  24417. const {
  24418. mainPlaylistLoader,
  24419. mediaTypes: {
  24420. [type]: {
  24421. groups
  24422. }
  24423. }
  24424. } = settings;
  24425. const media = mainPlaylistLoader.media();
  24426. if (!media) {
  24427. return null;
  24428. }
  24429. let variants = null; // set to variants to main media active group
  24430. if (media.attributes[type]) {
  24431. variants = groups[media.attributes[type]];
  24432. }
  24433. const groupKeys = Object.keys(groups);
  24434. if (!variants) {
  24435. // find the mainPlaylistLoader media
  24436. // that is in a media group if we are dealing
  24437. // with audio only
  24438. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  24439. for (let i = 0; i < groupKeys.length; i++) {
  24440. const groupPropertyList = groups[groupKeys[i]];
  24441. if (groupMatch(groupPropertyList, media)) {
  24442. variants = groupPropertyList;
  24443. break;
  24444. }
  24445. } // use the main group if it exists
  24446. } else if (groups.main) {
  24447. variants = groups.main; // only one group, use that one
  24448. } else if (groupKeys.length === 1) {
  24449. variants = groups[groupKeys[0]];
  24450. }
  24451. }
  24452. if (typeof track === 'undefined') {
  24453. return variants;
  24454. }
  24455. if (track === null || !variants) {
  24456. // An active track was specified so a corresponding group is expected. track === null
  24457. // means no track is currently active so there is no corresponding group
  24458. return null;
  24459. }
  24460. return variants.filter(props => props.id === track.id)[0] || null;
  24461. };
  24462. const activeTrack = {
  24463. /**
  24464. * Returns a function used to get the active track of type provided
  24465. *
  24466. * @param {string} type
  24467. * MediaGroup type
  24468. * @param {Object} settings
  24469. * Object containing required information for media groups
  24470. * @return {Function}
  24471. * Function that returns the active media track for the provided type. Returns
  24472. * null if no track is active
  24473. * @function activeTrack.AUDIO
  24474. */
  24475. AUDIO: (type, settings) => () => {
  24476. const {
  24477. mediaTypes: {
  24478. [type]: {
  24479. tracks
  24480. }
  24481. }
  24482. } = settings;
  24483. for (const id in tracks) {
  24484. if (tracks[id].enabled) {
  24485. return tracks[id];
  24486. }
  24487. }
  24488. return null;
  24489. },
  24490. /**
  24491. * Returns a function used to get the active track of type provided
  24492. *
  24493. * @param {string} type
  24494. * MediaGroup type
  24495. * @param {Object} settings
  24496. * Object containing required information for media groups
  24497. * @return {Function}
  24498. * Function that returns the active media track for the provided type. Returns
  24499. * null if no track is active
  24500. * @function activeTrack.SUBTITLES
  24501. */
  24502. SUBTITLES: (type, settings) => () => {
  24503. const {
  24504. mediaTypes: {
  24505. [type]: {
  24506. tracks
  24507. }
  24508. }
  24509. } = settings;
  24510. for (const id in tracks) {
  24511. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  24512. return tracks[id];
  24513. }
  24514. }
  24515. return null;
  24516. }
  24517. };
  24518. const getActiveGroup = (type, {
  24519. mediaTypes
  24520. }) => () => {
  24521. const activeTrack_ = mediaTypes[type].activeTrack();
  24522. if (!activeTrack_) {
  24523. return null;
  24524. }
  24525. return mediaTypes[type].activeGroup(activeTrack_);
  24526. };
  24527. /**
  24528. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  24529. * Closed-Captions) specified in the main manifest.
  24530. *
  24531. * @param {Object} settings
  24532. * Object containing required information for setting up the media groups
  24533. * @param {Tech} settings.tech
  24534. * The tech of the player
  24535. * @param {Object} settings.requestOptions
  24536. * XHR request options used by the segment loaders
  24537. * @param {PlaylistLoader} settings.mainPlaylistLoader
  24538. * PlaylistLoader for the main source
  24539. * @param {VhsHandler} settings.vhs
  24540. * VHS SourceHandler
  24541. * @param {Object} settings.main
  24542. * The parsed main manifest
  24543. * @param {Object} settings.mediaTypes
  24544. * Object to store the loaders, tracks, and utility methods for each media type
  24545. * @param {Function} settings.excludePlaylist
  24546. * Excludes the current rendition and forces a rendition switch.
  24547. * @function setupMediaGroups
  24548. */
  24549. const setupMediaGroups = settings => {
  24550. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  24551. initialize[type](type, settings);
  24552. });
  24553. const {
  24554. mediaTypes,
  24555. mainPlaylistLoader,
  24556. tech,
  24557. vhs,
  24558. segmentLoaders: {
  24559. ['AUDIO']: audioSegmentLoader,
  24560. main: mainSegmentLoader
  24561. }
  24562. } = settings; // setup active group and track getters and change event handlers
  24563. ['AUDIO', 'SUBTITLES'].forEach(type => {
  24564. mediaTypes[type].activeGroup = activeGroup(type, settings);
  24565. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  24566. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  24567. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  24568. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  24569. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  24570. }); // DO NOT enable the default subtitle or caption track.
  24571. // DO enable the default audio track
  24572. const audioGroup = mediaTypes.AUDIO.activeGroup();
  24573. if (audioGroup) {
  24574. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  24575. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  24576. mediaTypes.AUDIO.onGroupChanged();
  24577. mediaTypes.AUDIO.onTrackChanged();
  24578. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  24579. // track is changed, but needs to be handled here since the track may not be considered
  24580. // changed on the first call to onTrackChanged
  24581. if (!activeAudioGroup.playlistLoader) {
  24582. // either audio is muxed with video or the stream is audio only
  24583. mainSegmentLoader.setAudio(true);
  24584. } else {
  24585. // audio is demuxed
  24586. mainSegmentLoader.setAudio(false);
  24587. audioSegmentLoader.setAudio(true);
  24588. }
  24589. }
  24590. mainPlaylistLoader.on('mediachange', () => {
  24591. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  24592. });
  24593. mainPlaylistLoader.on('mediachanging', () => {
  24594. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  24595. }); // custom audio track change event handler for usage event
  24596. const onAudioTrackChanged = () => {
  24597. mediaTypes.AUDIO.onTrackChanged();
  24598. tech.trigger({
  24599. type: 'usage',
  24600. name: 'vhs-audio-change'
  24601. });
  24602. };
  24603. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  24604. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  24605. vhs.on('dispose', () => {
  24606. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  24607. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  24608. }); // clear existing audio tracks and add the ones we just created
  24609. tech.clearTracks('audio');
  24610. for (const id in mediaTypes.AUDIO.tracks) {
  24611. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  24612. }
  24613. };
  24614. /**
  24615. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  24616. * media type
  24617. *
  24618. * @return {Object}
  24619. * Object to store the loaders, tracks, and utility methods for each media type
  24620. * @function createMediaTypes
  24621. */
  24622. const createMediaTypes = () => {
  24623. const mediaTypes = {};
  24624. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  24625. mediaTypes[type] = {
  24626. groups: {},
  24627. tracks: {},
  24628. activePlaylistLoader: null,
  24629. activeGroup: noop,
  24630. activeTrack: noop,
  24631. getActiveGroup: noop,
  24632. onGroupChanged: noop,
  24633. onTrackChanged: noop,
  24634. lastTrack_: null,
  24635. logger_: logger(`MediaGroups[${type}]`)
  24636. };
  24637. });
  24638. return mediaTypes;
  24639. };
  24640. /**
  24641. * A utility class for setting properties and maintaining the state of the content steering manifest.
  24642. *
  24643. * Content Steering manifest format:
  24644. * VERSION: number (required) currently only version 1 is supported.
  24645. * TTL: number in seconds (optional) until the next content steering manifest reload.
  24646. * RELOAD-URI: string (optional) uri to fetch the next content steering manifest.
  24647. * SERVICE-LOCATION-PRIORITY or PATHWAY-PRIORITY a non empty array of unique string values.
  24648. * PATHWAY-CLONES: array (optional) (HLS only) pathway clone objects to copy from other playlists.
  24649. */
  24650. class SteeringManifest {
  24651. constructor() {
  24652. this.priority_ = [];
  24653. this.pathwayClones_ = new Map();
  24654. }
  24655. set version(number) {
  24656. // Only version 1 is currently supported for both DASH and HLS.
  24657. if (number === 1) {
  24658. this.version_ = number;
  24659. }
  24660. }
  24661. set ttl(seconds) {
  24662. // TTL = time-to-live, default = 300 seconds.
  24663. this.ttl_ = seconds || 300;
  24664. }
  24665. set reloadUri(uri) {
  24666. if (uri) {
  24667. // reload URI can be relative to the previous reloadUri.
  24668. this.reloadUri_ = resolveUrl(this.reloadUri_, uri);
  24669. }
  24670. }
  24671. set priority(array) {
  24672. // priority must be non-empty and unique values.
  24673. if (array && array.length) {
  24674. this.priority_ = array;
  24675. }
  24676. }
  24677. set pathwayClones(array) {
  24678. // pathwayClones must be non-empty.
  24679. if (array && array.length) {
  24680. this.pathwayClones_ = new Map(array.map(clone => [clone.ID, clone]));
  24681. }
  24682. }
  24683. get version() {
  24684. return this.version_;
  24685. }
  24686. get ttl() {
  24687. return this.ttl_;
  24688. }
  24689. get reloadUri() {
  24690. return this.reloadUri_;
  24691. }
  24692. get priority() {
  24693. return this.priority_;
  24694. }
  24695. get pathwayClones() {
  24696. return this.pathwayClones_;
  24697. }
  24698. }
  24699. /**
  24700. * This class represents a content steering manifest and associated state. See both HLS and DASH specifications.
  24701. * HLS: https://developer.apple.com/streaming/HLSContentSteeringSpecification.pdf and
  24702. * https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/ section 4.4.6.6.
  24703. * DASH: https://dashif.org/docs/DASH-IF-CTS-00XX-Content-Steering-Community-Review.pdf
  24704. *
  24705. * @param {function} xhr for making a network request from the browser.
  24706. * @param {function} bandwidth for fetching the current bandwidth from the main segment loader.
  24707. */
  24708. class ContentSteeringController extends videojs__default["default"].EventTarget {
  24709. constructor(xhr, bandwidth) {
  24710. super();
  24711. this.currentPathway = null;
  24712. this.defaultPathway = null;
  24713. this.queryBeforeStart = false;
  24714. this.availablePathways_ = new Set();
  24715. this.steeringManifest = new SteeringManifest();
  24716. this.proxyServerUrl_ = null;
  24717. this.manifestType_ = null;
  24718. this.ttlTimeout_ = null;
  24719. this.request_ = null;
  24720. this.currentPathwayClones = new Map();
  24721. this.nextPathwayClones = new Map();
  24722. this.excludedSteeringManifestURLs = new Set();
  24723. this.logger_ = logger('Content Steering');
  24724. this.xhr_ = xhr;
  24725. this.getBandwidth_ = bandwidth;
  24726. }
  24727. /**
  24728. * Assigns the content steering tag properties to the steering controller
  24729. *
  24730. * @param {string} baseUrl the baseURL from the main manifest for resolving the steering manifest url
  24731. * @param {Object} steeringTag the content steering tag from the main manifest
  24732. */
  24733. assignTagProperties(baseUrl, steeringTag) {
  24734. this.manifestType_ = steeringTag.serverUri ? 'HLS' : 'DASH'; // serverUri is HLS serverURL is DASH
  24735. const steeringUri = steeringTag.serverUri || steeringTag.serverURL;
  24736. if (!steeringUri) {
  24737. this.logger_(`steering manifest URL is ${steeringUri}, cannot request steering manifest.`);
  24738. this.trigger('error');
  24739. return;
  24740. } // Content steering manifests can be encoded as a data URI. We can decode, parse and return early if that's the case.
  24741. if (steeringUri.startsWith('data:')) {
  24742. this.decodeDataUriManifest_(steeringUri.substring(steeringUri.indexOf(',') + 1));
  24743. return;
  24744. } // reloadUri is the resolution of the main manifest URL and steering URL.
  24745. this.steeringManifest.reloadUri = resolveUrl(baseUrl, steeringUri); // pathwayId is HLS defaultServiceLocation is DASH
  24746. this.defaultPathway = steeringTag.pathwayId || steeringTag.defaultServiceLocation; // currently only DASH supports the following properties on <ContentSteering> tags.
  24747. this.queryBeforeStart = steeringTag.queryBeforeStart;
  24748. this.proxyServerUrl_ = steeringTag.proxyServerURL; // trigger a steering event if we have a pathway from the content steering tag.
  24749. // this tells VHS which segment pathway to start with.
  24750. // If queryBeforeStart is true we need to wait for the steering manifest response.
  24751. if (this.defaultPathway && !this.queryBeforeStart) {
  24752. this.trigger('content-steering');
  24753. }
  24754. }
  24755. /**
  24756. * Requests the content steering manifest and parse the response. This should only be called after
  24757. * assignTagProperties was called with a content steering tag.
  24758. *
  24759. * @param {string} initialUri The optional uri to make the request with.
  24760. * If set, the request should be made with exactly what is passed in this variable.
  24761. * This scenario should only happen once on initalization.
  24762. */
  24763. requestSteeringManifest(initial) {
  24764. const reloadUri = this.steeringManifest.reloadUri;
  24765. if (!reloadUri) {
  24766. return;
  24767. } // We currently don't support passing MPD query parameters directly to the content steering URL as this requires
  24768. // ExtUrlQueryInfo tag support. See the DASH content steering spec section 8.1.
  24769. // This request URI accounts for manifest URIs that have been excluded.
  24770. const uri = initial ? reloadUri : this.getRequestURI(reloadUri); // If there are no valid manifest URIs, we should stop content steering.
  24771. if (!uri) {
  24772. this.logger_('No valid content steering manifest URIs. Stopping content steering.');
  24773. this.trigger('error');
  24774. this.dispose();
  24775. return;
  24776. }
  24777. this.request_ = this.xhr_({
  24778. uri
  24779. }, (error, errorInfo) => {
  24780. if (error) {
  24781. // If the client receives HTTP 410 Gone in response to a manifest request,
  24782. // it MUST NOT issue another request for that URI for the remainder of the
  24783. // playback session. It MAY continue to use the most-recently obtained set
  24784. // of Pathways.
  24785. if (errorInfo.status === 410) {
  24786. this.logger_(`manifest request 410 ${error}.`);
  24787. this.logger_(`There will be no more content steering requests to ${uri} this session.`);
  24788. this.excludedSteeringManifestURLs.add(uri);
  24789. return;
  24790. } // If the client receives HTTP 429 Too Many Requests with a Retry-After
  24791. // header in response to a manifest request, it SHOULD wait until the time
  24792. // specified by the Retry-After header to reissue the request.
  24793. if (errorInfo.status === 429) {
  24794. const retrySeconds = errorInfo.responseHeaders['retry-after'];
  24795. this.logger_(`manifest request 429 ${error}.`);
  24796. this.logger_(`content steering will retry in ${retrySeconds} seconds.`);
  24797. this.startTTLTimeout_(parseInt(retrySeconds, 10));
  24798. return;
  24799. } // If the Steering Manifest cannot be loaded and parsed correctly, the
  24800. // client SHOULD continue to use the previous values and attempt to reload
  24801. // it after waiting for the previously-specified TTL (or 5 minutes if
  24802. // none).
  24803. this.logger_(`manifest failed to load ${error}.`);
  24804. this.startTTLTimeout_();
  24805. return;
  24806. }
  24807. const steeringManifestJson = JSON.parse(this.request_.responseText);
  24808. this.assignSteeringProperties_(steeringManifestJson);
  24809. this.startTTLTimeout_();
  24810. });
  24811. }
  24812. /**
  24813. * Set the proxy server URL and add the steering manifest url as a URI encoded parameter.
  24814. *
  24815. * @param {string} steeringUrl the steering manifest url
  24816. * @return the steering manifest url to a proxy server with all parameters set
  24817. */
  24818. setProxyServerUrl_(steeringUrl) {
  24819. const steeringUrlObject = new window.URL(steeringUrl);
  24820. const proxyServerUrlObject = new window.URL(this.proxyServerUrl_);
  24821. proxyServerUrlObject.searchParams.set('url', encodeURI(steeringUrlObject.toString()));
  24822. return this.setSteeringParams_(proxyServerUrlObject.toString());
  24823. }
  24824. /**
  24825. * Decodes and parses the data uri encoded steering manifest
  24826. *
  24827. * @param {string} dataUri the data uri to be decoded and parsed.
  24828. */
  24829. decodeDataUriManifest_(dataUri) {
  24830. const steeringManifestJson = JSON.parse(window.atob(dataUri));
  24831. this.assignSteeringProperties_(steeringManifestJson);
  24832. }
  24833. /**
  24834. * Set the HLS or DASH content steering manifest request query parameters. For example:
  24835. * _HLS_pathway="<CURRENT-PATHWAY-ID>" and _HLS_throughput=<THROUGHPUT>
  24836. * _DASH_pathway and _DASH_throughput
  24837. *
  24838. * @param {string} uri to add content steering server parameters to.
  24839. * @return a new uri as a string with the added steering query parameters.
  24840. */
  24841. setSteeringParams_(url) {
  24842. const urlObject = new window.URL(url);
  24843. const path = this.getPathway();
  24844. const networkThroughput = this.getBandwidth_();
  24845. if (path) {
  24846. const pathwayKey = `_${this.manifestType_}_pathway`;
  24847. urlObject.searchParams.set(pathwayKey, path);
  24848. }
  24849. if (networkThroughput) {
  24850. const throughputKey = `_${this.manifestType_}_throughput`;
  24851. urlObject.searchParams.set(throughputKey, networkThroughput);
  24852. }
  24853. return urlObject.toString();
  24854. }
  24855. /**
  24856. * Assigns the current steering manifest properties and to the SteeringManifest object
  24857. *
  24858. * @param {Object} steeringJson the raw JSON steering manifest
  24859. */
  24860. assignSteeringProperties_(steeringJson) {
  24861. this.steeringManifest.version = steeringJson.VERSION;
  24862. if (!this.steeringManifest.version) {
  24863. this.logger_(`manifest version is ${steeringJson.VERSION}, which is not supported.`);
  24864. this.trigger('error');
  24865. return;
  24866. }
  24867. this.steeringManifest.ttl = steeringJson.TTL;
  24868. this.steeringManifest.reloadUri = steeringJson['RELOAD-URI']; // HLS = PATHWAY-PRIORITY required. DASH = SERVICE-LOCATION-PRIORITY optional
  24869. this.steeringManifest.priority = steeringJson['PATHWAY-PRIORITY'] || steeringJson['SERVICE-LOCATION-PRIORITY']; // Pathway clones to be created/updated in HLS.
  24870. // See section 7.2 https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/
  24871. this.steeringManifest.pathwayClones = steeringJson['PATHWAY-CLONES'];
  24872. this.nextPathwayClones = this.steeringManifest.pathwayClones; // 1. apply first pathway from the array.
  24873. // 2. if first pathway doesn't exist in manifest, try next pathway.
  24874. // a. if all pathways are exhausted, ignore the steering manifest priority.
  24875. // 3. if segments fail from an established pathway, try all variants/renditions, then exclude the failed pathway.
  24876. // a. exclude a pathway for a minimum of the last TTL duration. Meaning, from the next steering response,
  24877. // the excluded pathway will be ignored.
  24878. // See excludePathway usage in excludePlaylist().
  24879. // If there are no available pathways, we need to stop content steering.
  24880. if (!this.availablePathways_.size) {
  24881. this.logger_('There are no available pathways for content steering. Ending content steering.');
  24882. this.trigger('error');
  24883. this.dispose();
  24884. }
  24885. const chooseNextPathway = pathwaysByPriority => {
  24886. for (const path of pathwaysByPriority) {
  24887. if (this.availablePathways_.has(path)) {
  24888. return path;
  24889. }
  24890. } // If no pathway matches, ignore the manifest and choose the first available.
  24891. return [...this.availablePathways_][0];
  24892. };
  24893. const nextPathway = chooseNextPathway(this.steeringManifest.priority);
  24894. if (this.currentPathway !== nextPathway) {
  24895. this.currentPathway = nextPathway;
  24896. this.trigger('content-steering');
  24897. }
  24898. }
  24899. /**
  24900. * Returns the pathway to use for steering decisions
  24901. *
  24902. * @return {string} returns the current pathway or the default
  24903. */
  24904. getPathway() {
  24905. return this.currentPathway || this.defaultPathway;
  24906. }
  24907. /**
  24908. * Chooses the manifest request URI based on proxy URIs and server URLs.
  24909. * Also accounts for exclusion on certain manifest URIs.
  24910. *
  24911. * @param {string} reloadUri the base uri before parameters
  24912. *
  24913. * @return {string} the final URI for the request to the manifest server.
  24914. */
  24915. getRequestURI(reloadUri) {
  24916. if (!reloadUri) {
  24917. return null;
  24918. }
  24919. const isExcluded = uri => this.excludedSteeringManifestURLs.has(uri);
  24920. if (this.proxyServerUrl_) {
  24921. const proxyURI = this.setProxyServerUrl_(reloadUri);
  24922. if (!isExcluded(proxyURI)) {
  24923. return proxyURI;
  24924. }
  24925. }
  24926. const steeringURI = this.setSteeringParams_(reloadUri);
  24927. if (!isExcluded(steeringURI)) {
  24928. return steeringURI;
  24929. } // Return nothing if all valid manifest URIs are excluded.
  24930. return null;
  24931. }
  24932. /**
  24933. * Start the timeout for re-requesting the steering manifest at the TTL interval.
  24934. *
  24935. * @param {number} ttl time in seconds of the timeout. Defaults to the
  24936. * ttl interval in the steering manifest
  24937. */
  24938. startTTLTimeout_(ttl = this.steeringManifest.ttl) {
  24939. // 300 (5 minutes) is the default value.
  24940. const ttlMS = ttl * 1000;
  24941. this.ttlTimeout_ = window.setTimeout(() => {
  24942. this.requestSteeringManifest();
  24943. }, ttlMS);
  24944. }
  24945. /**
  24946. * Clear the TTL timeout if necessary.
  24947. */
  24948. clearTTLTimeout_() {
  24949. window.clearTimeout(this.ttlTimeout_);
  24950. this.ttlTimeout_ = null;
  24951. }
  24952. /**
  24953. * aborts any current steering xhr and sets the current request object to null
  24954. */
  24955. abort() {
  24956. if (this.request_) {
  24957. this.request_.abort();
  24958. }
  24959. this.request_ = null;
  24960. }
  24961. /**
  24962. * aborts steering requests clears the ttl timeout and resets all properties.
  24963. */
  24964. dispose() {
  24965. this.off('content-steering');
  24966. this.off('error');
  24967. this.abort();
  24968. this.clearTTLTimeout_();
  24969. this.currentPathway = null;
  24970. this.defaultPathway = null;
  24971. this.queryBeforeStart = null;
  24972. this.proxyServerUrl_ = null;
  24973. this.manifestType_ = null;
  24974. this.ttlTimeout_ = null;
  24975. this.request_ = null;
  24976. this.excludedSteeringManifestURLs = new Set();
  24977. this.availablePathways_ = new Set();
  24978. this.steeringManifest = new SteeringManifest();
  24979. }
  24980. /**
  24981. * adds a pathway to the available pathways set
  24982. *
  24983. * @param {string} pathway the pathway string to add
  24984. */
  24985. addAvailablePathway(pathway) {
  24986. if (pathway) {
  24987. this.availablePathways_.add(pathway);
  24988. }
  24989. }
  24990. /**
  24991. * Clears all pathways from the available pathways set
  24992. */
  24993. clearAvailablePathways() {
  24994. this.availablePathways_.clear();
  24995. }
  24996. /**
  24997. * Removes a pathway from the available pathways set.
  24998. */
  24999. excludePathway(pathway) {
  25000. return this.availablePathways_.delete(pathway);
  25001. }
  25002. /**
  25003. * Checks the refreshed DASH manifest content steering tag for changes.
  25004. *
  25005. * @param {string} baseURL new steering tag on DASH manifest refresh
  25006. * @param {Object} newTag the new tag to check for changes
  25007. * @return a true or false whether the new tag has different values
  25008. */
  25009. didDASHTagChange(baseURL, newTag) {
  25010. return !newTag && this.steeringManifest.reloadUri || newTag && (resolveUrl(baseURL, newTag.serverURL) !== this.steeringManifest.reloadUri || newTag.defaultServiceLocation !== this.defaultPathway || newTag.queryBeforeStart !== this.queryBeforeStart || newTag.proxyServerURL !== this.proxyServerUrl_);
  25011. }
  25012. getAvailablePathways() {
  25013. return this.availablePathways_;
  25014. }
  25015. }
  25016. /**
  25017. * @file playlist-controller.js
  25018. */
  25019. const ABORT_EARLY_EXCLUSION_SECONDS = 10;
  25020. let Vhs$1; // SegmentLoader stats that need to have each loader's
  25021. // values summed to calculate the final value
  25022. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  25023. const sumLoaderStat = function (stat) {
  25024. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  25025. };
  25026. const shouldSwitchToMedia = function ({
  25027. currentPlaylist,
  25028. buffered,
  25029. currentTime,
  25030. nextPlaylist,
  25031. bufferLowWaterLine,
  25032. bufferHighWaterLine,
  25033. duration,
  25034. bufferBasedABR,
  25035. log
  25036. }) {
  25037. // we have no other playlist to switch to
  25038. if (!nextPlaylist) {
  25039. videojs__default["default"].log.warn('We received no playlist to switch to. Please check your stream.');
  25040. return false;
  25041. }
  25042. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  25043. if (!currentPlaylist) {
  25044. log(`${sharedLogLine} as current playlist is not set`);
  25045. return true;
  25046. } // no need to switch if playlist is the same
  25047. if (nextPlaylist.id === currentPlaylist.id) {
  25048. return false;
  25049. } // determine if current time is in a buffered range.
  25050. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  25051. // This is because in LIVE, the player plays 3 segments from the end of the
  25052. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  25053. // in those segments, a viewer will never experience a rendition upswitch.
  25054. if (!currentPlaylist.endList) {
  25055. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  25056. // doubles the time to first playback.
  25057. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  25058. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  25059. return false;
  25060. }
  25061. log(`${sharedLogLine} as current playlist is live`);
  25062. return true;
  25063. }
  25064. const forwardBuffer = timeAheadOf(buffered, currentTime);
  25065. 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
  25066. // duration is below the max potential low water line
  25067. if (duration < maxBufferLowWaterLine) {
  25068. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  25069. return true;
  25070. }
  25071. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  25072. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  25073. // we can switch down
  25074. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  25075. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  25076. if (bufferBasedABR) {
  25077. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  25078. }
  25079. log(logLine);
  25080. return true;
  25081. } // and if our buffer is higher than the low water line,
  25082. // we can switch up
  25083. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  25084. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  25085. if (bufferBasedABR) {
  25086. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  25087. }
  25088. log(logLine);
  25089. return true;
  25090. }
  25091. log(`not ${sharedLogLine} as no switching criteria met`);
  25092. return false;
  25093. };
  25094. /**
  25095. * the main playlist controller controller all interactons
  25096. * between playlists and segmentloaders. At this time this mainly
  25097. * involves a main playlist and a series of audio playlists
  25098. * if they are available
  25099. *
  25100. * @class PlaylistController
  25101. * @extends videojs.EventTarget
  25102. */
  25103. class PlaylistController extends videojs__default["default"].EventTarget {
  25104. constructor(options) {
  25105. super();
  25106. const {
  25107. src,
  25108. withCredentials,
  25109. tech,
  25110. bandwidth,
  25111. externVhs,
  25112. useCueTags,
  25113. playlistExclusionDuration,
  25114. enableLowInitialPlaylist,
  25115. sourceType,
  25116. cacheEncryptionKeys,
  25117. bufferBasedABR,
  25118. leastPixelDiffSelector,
  25119. captionServices
  25120. } = options;
  25121. if (!src) {
  25122. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  25123. }
  25124. let {
  25125. maxPlaylistRetries
  25126. } = options;
  25127. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  25128. maxPlaylistRetries = Infinity;
  25129. }
  25130. Vhs$1 = externVhs;
  25131. this.bufferBasedABR = Boolean(bufferBasedABR);
  25132. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  25133. this.withCredentials = withCredentials;
  25134. this.tech_ = tech;
  25135. this.vhs_ = tech.vhs;
  25136. this.sourceType_ = sourceType;
  25137. this.useCueTags_ = useCueTags;
  25138. this.playlistExclusionDuration = playlistExclusionDuration;
  25139. this.maxPlaylistRetries = maxPlaylistRetries;
  25140. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  25141. if (this.useCueTags_) {
  25142. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  25143. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  25144. }
  25145. this.requestOptions_ = {
  25146. withCredentials,
  25147. maxPlaylistRetries,
  25148. timeout: null
  25149. };
  25150. this.on('error', this.pauseLoading);
  25151. this.mediaTypes_ = createMediaTypes();
  25152. this.mediaSource = new window.MediaSource();
  25153. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  25154. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  25155. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  25156. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  25157. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  25158. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  25159. // everything, and the MediaSource should not be detached without a proper disposal
  25160. this.seekable_ = createTimeRanges();
  25161. this.hasPlayed_ = false;
  25162. this.syncController_ = new SyncController(options);
  25163. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  25164. kind: 'metadata',
  25165. label: 'segment-metadata'
  25166. }, false).track;
  25167. this.decrypter_ = new Decrypter();
  25168. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  25169. this.inbandTextTracks_ = {};
  25170. this.timelineChangeController_ = new TimelineChangeController();
  25171. this.keyStatusMap_ = new Map();
  25172. const segmentLoaderSettings = {
  25173. vhs: this.vhs_,
  25174. parse708captions: options.parse708captions,
  25175. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  25176. captionServices,
  25177. mediaSource: this.mediaSource,
  25178. currentTime: this.tech_.currentTime.bind(this.tech_),
  25179. seekable: () => this.seekable(),
  25180. seeking: () => this.tech_.seeking(),
  25181. duration: () => this.duration(),
  25182. hasPlayed: () => this.hasPlayed_,
  25183. goalBufferLength: () => this.goalBufferLength(),
  25184. bandwidth,
  25185. syncController: this.syncController_,
  25186. decrypter: this.decrypter_,
  25187. sourceType: this.sourceType_,
  25188. inbandTextTracks: this.inbandTextTracks_,
  25189. cacheEncryptionKeys,
  25190. sourceUpdater: this.sourceUpdater_,
  25191. timelineChangeController: this.timelineChangeController_,
  25192. exactManifestTimings: options.exactManifestTimings,
  25193. addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)
  25194. }; // The source type check not only determines whether a special DASH playlist loader
  25195. // should be used, but also covers the case where the provided src is a vhs-json
  25196. // manifest object (instead of a URL). In the case of vhs-json, the default
  25197. // PlaylistLoader should be used.
  25198. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, merge$1(this.requestOptions_, {
  25199. addMetadataToTextTrack: this.addMetadataToTextTrack.bind(this)
  25200. })) : new PlaylistLoader(src, this.vhs_, merge$1(this.requestOptions_, {
  25201. addDateRangesToTextTrack: this.addDateRangesToTextTrack_.bind(this)
  25202. }));
  25203. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  25204. // combined audio/video or just video when alternate audio track is selected
  25205. this.mainSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  25206. segmentMetadataTrack: this.segmentMetadataTrack_,
  25207. loaderType: 'main'
  25208. }), options); // alternate audio track
  25209. this.audioSegmentLoader_ = new SegmentLoader(merge$1(segmentLoaderSettings, {
  25210. loaderType: 'audio'
  25211. }), options);
  25212. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge$1(segmentLoaderSettings, {
  25213. loaderType: 'vtt',
  25214. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  25215. loadVttJs: () => new Promise((resolve, reject) => {
  25216. function onLoad() {
  25217. tech.off('vttjserror', onError);
  25218. resolve();
  25219. }
  25220. function onError() {
  25221. tech.off('vttjsloaded', onLoad);
  25222. reject();
  25223. }
  25224. tech.one('vttjsloaded', onLoad);
  25225. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  25226. tech.addWebVttScript_();
  25227. })
  25228. }), options);
  25229. const getBandwidth = () => {
  25230. return this.mainSegmentLoader_.bandwidth;
  25231. };
  25232. this.contentSteeringController_ = new ContentSteeringController(this.vhs_.xhr, getBandwidth);
  25233. this.setupSegmentLoaderListeners_();
  25234. if (this.bufferBasedABR) {
  25235. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  25236. this.tech_.on('pause', () => this.stopABRTimer_());
  25237. this.tech_.on('play', () => this.startABRTimer_());
  25238. } // Create SegmentLoader stat-getters
  25239. // mediaRequests_
  25240. // mediaRequestsAborted_
  25241. // mediaRequestsTimedout_
  25242. // mediaRequestsErrored_
  25243. // mediaTransferDuration_
  25244. // mediaBytesTransferred_
  25245. // mediaAppends_
  25246. loaderStats.forEach(stat => {
  25247. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  25248. });
  25249. this.logger_ = logger('pc');
  25250. this.triggeredFmp4Usage = false;
  25251. if (this.tech_.preload() === 'none') {
  25252. this.loadOnPlay_ = () => {
  25253. this.loadOnPlay_ = null;
  25254. this.mainPlaylistLoader_.load();
  25255. };
  25256. this.tech_.one('play', this.loadOnPlay_);
  25257. } else {
  25258. this.mainPlaylistLoader_.load();
  25259. }
  25260. this.timeToLoadedData__ = -1;
  25261. this.mainAppendsToLoadedData__ = -1;
  25262. this.audioAppendsToLoadedData__ = -1;
  25263. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  25264. this.tech_.one(event, () => {
  25265. const timeToLoadedDataStart = Date.now();
  25266. this.tech_.one('loadeddata', () => {
  25267. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  25268. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  25269. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  25270. });
  25271. });
  25272. }
  25273. mainAppendsToLoadedData_() {
  25274. return this.mainAppendsToLoadedData__;
  25275. }
  25276. audioAppendsToLoadedData_() {
  25277. return this.audioAppendsToLoadedData__;
  25278. }
  25279. appendsToLoadedData_() {
  25280. const main = this.mainAppendsToLoadedData_();
  25281. const audio = this.audioAppendsToLoadedData_();
  25282. if (main === -1 || audio === -1) {
  25283. return -1;
  25284. }
  25285. return main + audio;
  25286. }
  25287. timeToLoadedData_() {
  25288. return this.timeToLoadedData__;
  25289. }
  25290. /**
  25291. * Run selectPlaylist and switch to the new playlist if we should
  25292. *
  25293. * @param {string} [reason=abr] a reason for why the ABR check is made
  25294. * @private
  25295. */
  25296. checkABR_(reason = 'abr') {
  25297. const nextPlaylist = this.selectPlaylist();
  25298. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  25299. this.switchMedia_(nextPlaylist, reason);
  25300. }
  25301. }
  25302. switchMedia_(playlist, cause, delay) {
  25303. const oldMedia = this.media();
  25304. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  25305. const newId = playlist && (playlist.id || playlist.uri);
  25306. if (oldId && oldId !== newId) {
  25307. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  25308. this.tech_.trigger({
  25309. type: 'usage',
  25310. name: `vhs-rendition-change-${cause}`
  25311. });
  25312. }
  25313. this.mainPlaylistLoader_.media(playlist, delay);
  25314. }
  25315. /**
  25316. * A function that ensures we switch our playlists inside of `mediaTypes`
  25317. * to match the current `serviceLocation` provided by the contentSteering controller.
  25318. * We want to check media types of `AUDIO`, `SUBTITLES`, and `CLOSED-CAPTIONS`.
  25319. *
  25320. * This should only be called on a DASH playback scenario while using content steering.
  25321. * This is necessary due to differences in how media in HLS manifests are generally tied to
  25322. * a video playlist, where in DASH that is not always the case.
  25323. */
  25324. switchMediaForDASHContentSteering_() {
  25325. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  25326. const mediaType = this.mediaTypes_[type];
  25327. const activeGroup = mediaType ? mediaType.activeGroup() : null;
  25328. const pathway = this.contentSteeringController_.getPathway();
  25329. if (activeGroup && pathway) {
  25330. // activeGroup can be an array or a single group
  25331. const mediaPlaylists = activeGroup.length ? activeGroup[0].playlists : activeGroup.playlists;
  25332. const dashMediaPlaylists = mediaPlaylists.filter(p => p.attributes.serviceLocation === pathway); // Switch the current active playlist to the correct CDN
  25333. if (dashMediaPlaylists.length) {
  25334. this.mediaTypes_[type].activePlaylistLoader.media(dashMediaPlaylists[0]);
  25335. }
  25336. }
  25337. });
  25338. }
  25339. /**
  25340. * Start a timer that periodically calls checkABR_
  25341. *
  25342. * @private
  25343. */
  25344. startABRTimer_() {
  25345. this.stopABRTimer_();
  25346. this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
  25347. }
  25348. /**
  25349. * Stop the timer that periodically calls checkABR_
  25350. *
  25351. * @private
  25352. */
  25353. stopABRTimer_() {
  25354. // if we're scrubbing, we don't need to pause.
  25355. // This getter will be added to Video.js in version 7.11.
  25356. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  25357. return;
  25358. }
  25359. window.clearInterval(this.abrTimer_);
  25360. this.abrTimer_ = null;
  25361. }
  25362. /**
  25363. * Get a list of playlists for the currently selected audio playlist
  25364. *
  25365. * @return {Array} the array of audio playlists
  25366. */
  25367. getAudioTrackPlaylists_() {
  25368. const main = this.main();
  25369. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  25370. // assume that the audio tracks are contained in main
  25371. // playlist array, use that or an empty array.
  25372. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  25373. return defaultPlaylists;
  25374. }
  25375. const AUDIO = main.mediaGroups.AUDIO;
  25376. const groupKeys = Object.keys(AUDIO);
  25377. let track; // get the current active track
  25378. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  25379. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  25380. } else {
  25381. // default group is `main` or just the first group.
  25382. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  25383. for (const label in defaultGroup) {
  25384. if (defaultGroup[label].default) {
  25385. track = {
  25386. label
  25387. };
  25388. break;
  25389. }
  25390. }
  25391. } // no active track no playlists.
  25392. if (!track) {
  25393. return defaultPlaylists;
  25394. }
  25395. const playlists = []; // get all of the playlists that are possible for the
  25396. // active track.
  25397. for (const group in AUDIO) {
  25398. if (AUDIO[group][track.label]) {
  25399. const properties = AUDIO[group][track.label];
  25400. if (properties.playlists && properties.playlists.length) {
  25401. playlists.push.apply(playlists, properties.playlists);
  25402. } else if (properties.uri) {
  25403. playlists.push(properties);
  25404. } else if (main.playlists.length) {
  25405. // if an audio group does not have a uri
  25406. // see if we have main playlists that use it as a group.
  25407. // if we do then add those to the playlists list.
  25408. for (let i = 0; i < main.playlists.length; i++) {
  25409. const playlist = main.playlists[i];
  25410. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  25411. playlists.push(playlist);
  25412. }
  25413. }
  25414. }
  25415. }
  25416. }
  25417. if (!playlists.length) {
  25418. return defaultPlaylists;
  25419. }
  25420. return playlists;
  25421. }
  25422. /**
  25423. * Register event handlers on the main playlist loader. A helper
  25424. * function for construction time.
  25425. *
  25426. * @private
  25427. */
  25428. setupMainPlaylistLoaderListeners_() {
  25429. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  25430. const media = this.mainPlaylistLoader_.media();
  25431. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  25432. // timeout the request.
  25433. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  25434. this.requestOptions_.timeout = 0;
  25435. } else {
  25436. this.requestOptions_.timeout = requestTimeout;
  25437. } // if this isn't a live video and preload permits, start
  25438. // downloading segments
  25439. if (media.endList && this.tech_.preload() !== 'none') {
  25440. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  25441. this.mainSegmentLoader_.load();
  25442. }
  25443. setupMediaGroups({
  25444. sourceType: this.sourceType_,
  25445. segmentLoaders: {
  25446. AUDIO: this.audioSegmentLoader_,
  25447. SUBTITLES: this.subtitleSegmentLoader_,
  25448. main: this.mainSegmentLoader_
  25449. },
  25450. tech: this.tech_,
  25451. requestOptions: this.requestOptions_,
  25452. mainPlaylistLoader: this.mainPlaylistLoader_,
  25453. vhs: this.vhs_,
  25454. main: this.main(),
  25455. mediaTypes: this.mediaTypes_,
  25456. excludePlaylist: this.excludePlaylist.bind(this)
  25457. });
  25458. this.triggerPresenceUsage_(this.main(), media);
  25459. this.setupFirstPlay();
  25460. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  25461. this.trigger('selectedinitialmedia');
  25462. } else {
  25463. // We must wait for the active audio playlist loader to
  25464. // finish setting up before triggering this event so the
  25465. // representations API and EME setup is correct
  25466. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  25467. this.trigger('selectedinitialmedia');
  25468. });
  25469. }
  25470. });
  25471. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  25472. if (this.loadOnPlay_) {
  25473. this.tech_.off('play', this.loadOnPlay_);
  25474. }
  25475. let updatedPlaylist = this.mainPlaylistLoader_.media();
  25476. if (!updatedPlaylist) {
  25477. // Add content steering listeners on first load and init.
  25478. this.attachContentSteeringListeners_();
  25479. this.initContentSteeringController_(); // exclude any variants that are not supported by the browser before selecting
  25480. // an initial media as the playlist selectors do not consider browser support
  25481. this.excludeUnsupportedVariants_();
  25482. let selectedMedia;
  25483. if (this.enableLowInitialPlaylist) {
  25484. selectedMedia = this.selectInitialPlaylist();
  25485. }
  25486. if (!selectedMedia) {
  25487. selectedMedia = this.selectPlaylist();
  25488. }
  25489. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  25490. return;
  25491. }
  25492. this.initialMedia_ = selectedMedia;
  25493. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  25494. // fire again since the playlist will be requested. In the case of vhs-json
  25495. // (where the manifest object is provided as the source), when the media
  25496. // playlist's `segments` list is already available, a media playlist won't be
  25497. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  25498. // called on its own here.
  25499. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  25500. if (!haveJsonSource) {
  25501. return;
  25502. }
  25503. updatedPlaylist = this.initialMedia_;
  25504. }
  25505. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  25506. });
  25507. this.mainPlaylistLoader_.on('error', () => {
  25508. const error = this.mainPlaylistLoader_.error;
  25509. this.excludePlaylist({
  25510. playlistToExclude: error.playlist,
  25511. error
  25512. });
  25513. });
  25514. this.mainPlaylistLoader_.on('mediachanging', () => {
  25515. this.mainSegmentLoader_.abort();
  25516. this.mainSegmentLoader_.pause();
  25517. });
  25518. this.mainPlaylistLoader_.on('mediachange', () => {
  25519. const media = this.mainPlaylistLoader_.media();
  25520. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  25521. // timeout the request.
  25522. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  25523. this.requestOptions_.timeout = 0;
  25524. } else {
  25525. this.requestOptions_.timeout = requestTimeout;
  25526. }
  25527. if (this.sourceType_ === 'dash') {
  25528. // we don't want to re-request the same hls playlist right after it was changed
  25529. this.mainPlaylistLoader_.load();
  25530. } // TODO: Create a new event on the PlaylistLoader that signals
  25531. // that the segments have changed in some way and use that to
  25532. // update the SegmentLoader instead of doing it twice here and
  25533. // on `loadedplaylist`
  25534. this.mainSegmentLoader_.pause();
  25535. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  25536. if (this.waitingForFastQualityPlaylistReceived_) {
  25537. this.runFastQualitySwitch_();
  25538. } else {
  25539. this.mainSegmentLoader_.load();
  25540. }
  25541. this.tech_.trigger({
  25542. type: 'mediachange',
  25543. bubbles: true
  25544. });
  25545. });
  25546. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  25547. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  25548. // excluded for not-changing. We likely just have a really slowly updating
  25549. // playlist.
  25550. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  25551. return;
  25552. }
  25553. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  25554. if (playlistOutdated) {
  25555. // Playlist has stopped updating and we're stuck at its end. Try to
  25556. // exclude it and switch to another playlist in the hope that that
  25557. // one is updating (and give the player a chance to re-adjust to the
  25558. // safe live point).
  25559. this.excludePlaylist({
  25560. error: {
  25561. message: 'Playlist no longer updating.',
  25562. reason: 'playlist-unchanged'
  25563. }
  25564. }); // useful for monitoring QoS
  25565. this.tech_.trigger('playliststuck');
  25566. }
  25567. });
  25568. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  25569. this.tech_.trigger({
  25570. type: 'usage',
  25571. name: 'vhs-rendition-disabled'
  25572. });
  25573. });
  25574. this.mainPlaylistLoader_.on('renditionenabled', () => {
  25575. this.tech_.trigger({
  25576. type: 'usage',
  25577. name: 'vhs-rendition-enabled'
  25578. });
  25579. });
  25580. }
  25581. /**
  25582. * Given an updated media playlist (whether it was loaded for the first time, or
  25583. * refreshed for live playlists), update any relevant properties and state to reflect
  25584. * changes in the media that should be accounted for (e.g., cues and duration).
  25585. *
  25586. * @param {Object} updatedPlaylist the updated media playlist object
  25587. *
  25588. * @private
  25589. */
  25590. handleUpdatedMediaPlaylist(updatedPlaylist) {
  25591. if (this.useCueTags_) {
  25592. this.updateAdCues_(updatedPlaylist);
  25593. } // TODO: Create a new event on the PlaylistLoader that signals
  25594. // that the segments have changed in some way and use that to
  25595. // update the SegmentLoader instead of doing it twice here and
  25596. // on `mediachange`
  25597. this.mainSegmentLoader_.pause();
  25598. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  25599. if (this.waitingForFastQualityPlaylistReceived_) {
  25600. this.runFastQualitySwitch_();
  25601. }
  25602. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  25603. // as it is possible that it was temporarily stopped while waiting for
  25604. // a playlist (e.g., in case the playlist errored and we re-requested it).
  25605. if (!this.tech_.paused()) {
  25606. this.mainSegmentLoader_.load();
  25607. if (this.audioSegmentLoader_) {
  25608. this.audioSegmentLoader_.load();
  25609. }
  25610. }
  25611. }
  25612. /**
  25613. * A helper function for triggerring presence usage events once per source
  25614. *
  25615. * @private
  25616. */
  25617. triggerPresenceUsage_(main, media) {
  25618. const mediaGroups = main.mediaGroups || {};
  25619. let defaultDemuxed = true;
  25620. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  25621. for (const mediaGroup in mediaGroups.AUDIO) {
  25622. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  25623. const properties = mediaGroups.AUDIO[mediaGroup][label];
  25624. if (!properties.uri) {
  25625. defaultDemuxed = false;
  25626. }
  25627. }
  25628. }
  25629. if (defaultDemuxed) {
  25630. this.tech_.trigger({
  25631. type: 'usage',
  25632. name: 'vhs-demuxed'
  25633. });
  25634. }
  25635. if (Object.keys(mediaGroups.SUBTITLES).length) {
  25636. this.tech_.trigger({
  25637. type: 'usage',
  25638. name: 'vhs-webvtt'
  25639. });
  25640. }
  25641. if (Vhs$1.Playlist.isAes(media)) {
  25642. this.tech_.trigger({
  25643. type: 'usage',
  25644. name: 'vhs-aes'
  25645. });
  25646. }
  25647. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  25648. this.tech_.trigger({
  25649. type: 'usage',
  25650. name: 'vhs-alternate-audio'
  25651. });
  25652. }
  25653. if (this.useCueTags_) {
  25654. this.tech_.trigger({
  25655. type: 'usage',
  25656. name: 'vhs-playlist-cue-tags'
  25657. });
  25658. }
  25659. }
  25660. shouldSwitchToMedia_(nextPlaylist) {
  25661. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  25662. const currentTime = this.tech_.currentTime();
  25663. const bufferLowWaterLine = this.bufferLowWaterLine();
  25664. const bufferHighWaterLine = this.bufferHighWaterLine();
  25665. const buffered = this.tech_.buffered();
  25666. return shouldSwitchToMedia({
  25667. buffered,
  25668. currentTime,
  25669. currentPlaylist,
  25670. nextPlaylist,
  25671. bufferLowWaterLine,
  25672. bufferHighWaterLine,
  25673. duration: this.duration(),
  25674. bufferBasedABR: this.bufferBasedABR,
  25675. log: this.logger_
  25676. });
  25677. }
  25678. /**
  25679. * Register event handlers on the segment loaders. A helper function
  25680. * for construction time.
  25681. *
  25682. * @private
  25683. */
  25684. setupSegmentLoaderListeners_() {
  25685. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  25686. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  25687. // useful to check to see if a rendition switch should be made.
  25688. this.checkABR_('bandwidthupdate');
  25689. this.tech_.trigger('bandwidthupdate');
  25690. });
  25691. this.mainSegmentLoader_.on('timeout', () => {
  25692. if (this.bufferBasedABR) {
  25693. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  25694. // Here the only consideration is that for buffer based ABR there's no guarantee
  25695. // of an immediate switch (since the bandwidth is averaged with a timeout
  25696. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  25697. this.mainSegmentLoader_.load();
  25698. }
  25699. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  25700. // based ABR.
  25701. if (!this.bufferBasedABR) {
  25702. this.mainSegmentLoader_.on('progress', () => {
  25703. this.trigger('progress');
  25704. });
  25705. }
  25706. this.mainSegmentLoader_.on('error', () => {
  25707. const error = this.mainSegmentLoader_.error();
  25708. this.excludePlaylist({
  25709. playlistToExclude: error.playlist,
  25710. error
  25711. });
  25712. });
  25713. this.mainSegmentLoader_.on('appenderror', () => {
  25714. this.error = this.mainSegmentLoader_.error_;
  25715. this.trigger('error');
  25716. });
  25717. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  25718. this.onSyncInfoUpdate_();
  25719. });
  25720. this.mainSegmentLoader_.on('timestampoffset', () => {
  25721. this.tech_.trigger({
  25722. type: 'usage',
  25723. name: 'vhs-timestamp-offset'
  25724. });
  25725. });
  25726. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  25727. this.onSyncInfoUpdate_();
  25728. });
  25729. this.audioSegmentLoader_.on('appenderror', () => {
  25730. this.error = this.audioSegmentLoader_.error_;
  25731. this.trigger('error');
  25732. });
  25733. this.mainSegmentLoader_.on('ended', () => {
  25734. this.logger_('main segment loader ended');
  25735. this.onEndOfStream();
  25736. });
  25737. this.mainSegmentLoader_.on('earlyabort', event => {
  25738. // never try to early abort with the new ABR algorithm
  25739. if (this.bufferBasedABR) {
  25740. return;
  25741. }
  25742. this.delegateLoaders_('all', ['abort']);
  25743. this.excludePlaylist({
  25744. error: {
  25745. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  25746. },
  25747. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  25748. });
  25749. });
  25750. const updateCodecs = () => {
  25751. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  25752. return this.tryToCreateSourceBuffers_();
  25753. }
  25754. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  25755. if (!codecs) {
  25756. return;
  25757. }
  25758. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  25759. };
  25760. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  25761. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  25762. this.mainSegmentLoader_.on('fmp4', () => {
  25763. if (!this.triggeredFmp4Usage) {
  25764. this.tech_.trigger({
  25765. type: 'usage',
  25766. name: 'vhs-fmp4'
  25767. });
  25768. this.triggeredFmp4Usage = true;
  25769. }
  25770. });
  25771. this.audioSegmentLoader_.on('fmp4', () => {
  25772. if (!this.triggeredFmp4Usage) {
  25773. this.tech_.trigger({
  25774. type: 'usage',
  25775. name: 'vhs-fmp4'
  25776. });
  25777. this.triggeredFmp4Usage = true;
  25778. }
  25779. });
  25780. this.audioSegmentLoader_.on('ended', () => {
  25781. this.logger_('audioSegmentLoader ended');
  25782. this.onEndOfStream();
  25783. });
  25784. }
  25785. mediaSecondsLoaded_() {
  25786. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  25787. }
  25788. /**
  25789. * Call load on our SegmentLoaders
  25790. */
  25791. load() {
  25792. this.mainSegmentLoader_.load();
  25793. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  25794. this.audioSegmentLoader_.load();
  25795. }
  25796. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  25797. this.subtitleSegmentLoader_.load();
  25798. }
  25799. }
  25800. /**
  25801. * Re-tune playback quality level for the current player
  25802. * conditions. This method will perform destructive actions like removing
  25803. * already buffered content in order to readjust the currently active
  25804. * playlist quickly. This is good for manual quality changes
  25805. *
  25806. * @private
  25807. */
  25808. fastQualityChange_(media = this.selectPlaylist()) {
  25809. if (media && media === this.mainPlaylistLoader_.media()) {
  25810. this.logger_('skipping fastQualityChange because new media is same as old');
  25811. return;
  25812. }
  25813. this.switchMedia_(media, 'fast-quality'); // we would like to avoid race condition when we call fastQuality,
  25814. // reset everything and start loading segments from prev segments instead of new because new playlist is not received yet
  25815. this.waitingForFastQualityPlaylistReceived_ = true;
  25816. }
  25817. runFastQualitySwitch_() {
  25818. this.waitingForFastQualityPlaylistReceived_ = false; // Delete all buffered data to allow an immediate quality switch, then seek to give
  25819. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  25820. // ahead was roughly the minimum that will accomplish this across a variety of content
  25821. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  25822. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  25823. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  25824. this.mainSegmentLoader_.pause();
  25825. this.mainSegmentLoader_.resetEverything(() => {
  25826. this.tech_.setCurrentTime(this.tech_.currentTime());
  25827. }); // don't need to reset audio as it is reset when media changes
  25828. }
  25829. /**
  25830. * Begin playback.
  25831. */
  25832. play() {
  25833. if (this.setupFirstPlay()) {
  25834. return;
  25835. }
  25836. if (this.tech_.ended()) {
  25837. this.tech_.setCurrentTime(0);
  25838. }
  25839. if (this.hasPlayed_) {
  25840. this.load();
  25841. }
  25842. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  25843. // seek forward to the live point
  25844. if (this.tech_.duration() === Infinity) {
  25845. if (this.tech_.currentTime() < seekable.start(0)) {
  25846. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  25847. }
  25848. }
  25849. }
  25850. /**
  25851. * Seek to the latest media position if this is a live video and the
  25852. * player and video are loaded and initialized.
  25853. */
  25854. setupFirstPlay() {
  25855. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  25856. // If 1) there is no active media
  25857. // 2) the player is paused
  25858. // 3) the first play has already been setup
  25859. // then exit early
  25860. if (!media || this.tech_.paused() || this.hasPlayed_) {
  25861. return false;
  25862. } // when the video is a live stream and/or has a start time
  25863. if (!media.endList || media.start) {
  25864. const seekable = this.seekable();
  25865. if (!seekable.length) {
  25866. // without a seekable range, the player cannot seek to begin buffering at the
  25867. // live or start point
  25868. return false;
  25869. }
  25870. const seekableEnd = seekable.end(0);
  25871. let startPoint = seekableEnd;
  25872. if (media.start) {
  25873. const offset = media.start.timeOffset;
  25874. if (offset < 0) {
  25875. startPoint = Math.max(seekableEnd + offset, seekable.start(0));
  25876. } else {
  25877. startPoint = Math.min(seekableEnd, offset);
  25878. }
  25879. } // trigger firstplay to inform the source handler to ignore the next seek event
  25880. this.trigger('firstplay'); // seek to the live point
  25881. this.tech_.setCurrentTime(startPoint);
  25882. }
  25883. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  25884. this.load();
  25885. return true;
  25886. }
  25887. /**
  25888. * handle the sourceopen event on the MediaSource
  25889. *
  25890. * @private
  25891. */
  25892. handleSourceOpen_() {
  25893. // Only attempt to create the source buffer if none already exist.
  25894. // handleSourceOpen is also called when we are "re-opening" a source buffer
  25895. // after `endOfStream` has been called (in response to a seek for instance)
  25896. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  25897. // code in video.js but is required because play() must be invoked
  25898. // *after* the media source has opened.
  25899. if (this.tech_.autoplay()) {
  25900. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  25901. // on browsers which return a promise
  25902. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  25903. playPromise.then(null, e => {});
  25904. }
  25905. }
  25906. this.trigger('sourceopen');
  25907. }
  25908. /**
  25909. * handle the sourceended event on the MediaSource
  25910. *
  25911. * @private
  25912. */
  25913. handleSourceEnded_() {
  25914. if (!this.inbandTextTracks_.metadataTrack_) {
  25915. return;
  25916. }
  25917. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  25918. if (!cues || !cues.length) {
  25919. return;
  25920. }
  25921. const duration = this.duration();
  25922. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  25923. }
  25924. /**
  25925. * handle the durationchange event on the MediaSource
  25926. *
  25927. * @private
  25928. */
  25929. handleDurationChange_() {
  25930. this.tech_.trigger('durationchange');
  25931. }
  25932. /**
  25933. * Calls endOfStream on the media source when all active stream types have called
  25934. * endOfStream
  25935. *
  25936. * @param {string} streamType
  25937. * Stream type of the segment loader that called endOfStream
  25938. * @private
  25939. */
  25940. onEndOfStream() {
  25941. let isEndOfStream = this.mainSegmentLoader_.ended_;
  25942. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  25943. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  25944. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  25945. // if we do not know if the main segment loader contains video yet or if we
  25946. // definitively know the main segment loader contains video, then we need to wait
  25947. // for both main and audio segment loaders to call endOfStream
  25948. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  25949. } else {
  25950. // otherwise just rely on the audio loader
  25951. isEndOfStream = this.audioSegmentLoader_.ended_;
  25952. }
  25953. }
  25954. if (!isEndOfStream) {
  25955. return;
  25956. }
  25957. this.stopABRTimer_();
  25958. this.sourceUpdater_.endOfStream();
  25959. }
  25960. /**
  25961. * Check if a playlist has stopped being updated
  25962. *
  25963. * @param {Object} playlist the media playlist object
  25964. * @return {boolean} whether the playlist has stopped being updated or not
  25965. */
  25966. stuckAtPlaylistEnd_(playlist) {
  25967. const seekable = this.seekable();
  25968. if (!seekable.length) {
  25969. // playlist doesn't have enough information to determine whether we are stuck
  25970. return false;
  25971. }
  25972. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  25973. if (expired === null) {
  25974. return false;
  25975. } // does not use the safe live end to calculate playlist end, since we
  25976. // don't want to say we are stuck while there is still content
  25977. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  25978. const currentTime = this.tech_.currentTime();
  25979. const buffered = this.tech_.buffered();
  25980. if (!buffered.length) {
  25981. // return true if the playhead reached the absolute end of the playlist
  25982. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  25983. }
  25984. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  25985. // end of playlist
  25986. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  25987. }
  25988. /**
  25989. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  25990. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  25991. *
  25992. * @param {Object=} playlistToExclude
  25993. * the playlist to exclude, defaults to the currently selected playlist
  25994. * @param {Object=} error
  25995. * an optional error
  25996. * @param {number=} playlistExclusionDuration
  25997. * an optional number of seconds to exclude the playlist
  25998. */
  25999. excludePlaylist({
  26000. playlistToExclude = this.mainPlaylistLoader_.media(),
  26001. error = {},
  26002. playlistExclusionDuration
  26003. }) {
  26004. // If the `error` was generated by the playlist loader, it will contain
  26005. // the playlist we were trying to load (but failed) and that should be
  26006. // excluded instead of the currently selected playlist which is likely
  26007. // out-of-date in this scenario
  26008. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  26009. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  26010. // trying to load the main OR while we were disposing of the tech
  26011. if (!playlistToExclude) {
  26012. this.error = error;
  26013. if (this.mediaSource.readyState !== 'open') {
  26014. this.trigger('error');
  26015. } else {
  26016. this.sourceUpdater_.endOfStream('network');
  26017. }
  26018. return;
  26019. }
  26020. playlistToExclude.playlistErrors_++;
  26021. const playlists = this.mainPlaylistLoader_.main.playlists;
  26022. const enabledPlaylists = playlists.filter(isEnabled);
  26023. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  26024. // forever
  26025. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  26026. videojs__default["default"].log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  26027. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  26028. return this.mainPlaylistLoader_.load(isFinalRendition);
  26029. }
  26030. if (isFinalRendition) {
  26031. // If we're content steering, try other pathways.
  26032. if (this.main().contentSteering) {
  26033. const pathway = this.pathwayAttribute_(playlistToExclude); // Ignore at least 1 steering manifest refresh.
  26034. const reIncludeDelay = this.contentSteeringController_.steeringManifest.ttl * 1000;
  26035. this.contentSteeringController_.excludePathway(pathway);
  26036. this.excludeThenChangePathway_();
  26037. setTimeout(() => {
  26038. this.contentSteeringController_.addAvailablePathway(pathway);
  26039. }, reIncludeDelay);
  26040. return;
  26041. } // Since we're on the final non-excluded playlist, and we're about to exclude
  26042. // it, instead of erring the player or retrying this playlist, clear out the current
  26043. // exclusion list. This allows other playlists to be attempted in case any have been
  26044. // fixed.
  26045. let reincluded = false;
  26046. playlists.forEach(playlist => {
  26047. // skip current playlist which is about to be excluded
  26048. if (playlist === playlistToExclude) {
  26049. return;
  26050. }
  26051. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  26052. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  26053. reincluded = true;
  26054. delete playlist.excludeUntil;
  26055. }
  26056. });
  26057. if (reincluded) {
  26058. 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
  26059. // playlist. This is needed for users relying on the retryplaylist event to catch a
  26060. // case where the player might be stuck and looping through "dead" playlists.
  26061. this.tech_.trigger('retryplaylist');
  26062. }
  26063. } // Exclude this playlist
  26064. let excludeUntil;
  26065. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  26066. excludeUntil = Infinity;
  26067. } else {
  26068. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  26069. }
  26070. playlistToExclude.excludeUntil = excludeUntil;
  26071. if (error.reason) {
  26072. playlistToExclude.lastExcludeReason_ = error.reason;
  26073. }
  26074. this.tech_.trigger('excludeplaylist');
  26075. this.tech_.trigger({
  26076. type: 'usage',
  26077. name: 'vhs-rendition-excluded'
  26078. }); // TODO: only load a new playlist if we're excluding the current playlist
  26079. // If this function was called with a playlist that's not the current active playlist
  26080. // (e.g., media().id !== playlistToExclude.id),
  26081. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  26082. const nextPlaylist = this.selectPlaylist();
  26083. if (!nextPlaylist) {
  26084. this.error = 'Playback cannot continue. No available working or supported playlists.';
  26085. this.trigger('error');
  26086. return;
  26087. }
  26088. const logFn = error.internal ? this.logger_ : videojs__default["default"].log.warn;
  26089. const errorMessage = error.message ? ' ' + error.message : '';
  26090. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  26091. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  26092. this.delegateLoaders_('audio', ['abort', 'pause']);
  26093. } // if subtitle group changed reset subtitle loaders
  26094. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  26095. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  26096. }
  26097. this.delegateLoaders_('main', ['abort', 'pause']);
  26098. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  26099. 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
  26100. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  26101. }
  26102. /**
  26103. * Pause all segment/playlist loaders
  26104. */
  26105. pauseLoading() {
  26106. this.delegateLoaders_('all', ['abort', 'pause']);
  26107. this.stopABRTimer_();
  26108. }
  26109. /**
  26110. * Call a set of functions in order on playlist loaders, segment loaders,
  26111. * or both types of loaders.
  26112. *
  26113. * @param {string} filter
  26114. * Filter loaders that should call fnNames using a string. Can be:
  26115. * * all - run on all loaders
  26116. * * audio - run on all audio loaders
  26117. * * subtitle - run on all subtitle loaders
  26118. * * main - run on the main loaders
  26119. *
  26120. * @param {Array|string} fnNames
  26121. * A string or array of function names to call.
  26122. */
  26123. delegateLoaders_(filter, fnNames) {
  26124. const loaders = [];
  26125. const dontFilterPlaylist = filter === 'all';
  26126. if (dontFilterPlaylist || filter === 'main') {
  26127. loaders.push(this.mainPlaylistLoader_);
  26128. }
  26129. const mediaTypes = [];
  26130. if (dontFilterPlaylist || filter === 'audio') {
  26131. mediaTypes.push('AUDIO');
  26132. }
  26133. if (dontFilterPlaylist || filter === 'subtitle') {
  26134. mediaTypes.push('CLOSED-CAPTIONS');
  26135. mediaTypes.push('SUBTITLES');
  26136. }
  26137. mediaTypes.forEach(mediaType => {
  26138. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  26139. if (loader) {
  26140. loaders.push(loader);
  26141. }
  26142. });
  26143. ['main', 'audio', 'subtitle'].forEach(name => {
  26144. const loader = this[`${name}SegmentLoader_`];
  26145. if (loader && (filter === name || filter === 'all')) {
  26146. loaders.push(loader);
  26147. }
  26148. });
  26149. loaders.forEach(loader => fnNames.forEach(fnName => {
  26150. if (typeof loader[fnName] === 'function') {
  26151. loader[fnName]();
  26152. }
  26153. }));
  26154. }
  26155. /**
  26156. * set the current time on all segment loaders
  26157. *
  26158. * @param {TimeRange} currentTime the current time to set
  26159. * @return {TimeRange} the current time
  26160. */
  26161. setCurrentTime(currentTime) {
  26162. const buffered = findRange(this.tech_.buffered(), currentTime);
  26163. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  26164. // return immediately if the metadata is not ready yet
  26165. return 0;
  26166. } // it's clearly an edge-case but don't thrown an error if asked to
  26167. // seek within an empty playlist
  26168. if (!this.mainPlaylistLoader_.media().segments) {
  26169. return 0;
  26170. } // if the seek location is already buffered, continue buffering as usual
  26171. if (buffered && buffered.length) {
  26172. return currentTime;
  26173. } // cancel outstanding requests so we begin buffering at the new
  26174. // location
  26175. this.mainSegmentLoader_.pause();
  26176. this.mainSegmentLoader_.resetEverything();
  26177. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  26178. this.audioSegmentLoader_.pause();
  26179. this.audioSegmentLoader_.resetEverything();
  26180. }
  26181. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  26182. this.subtitleSegmentLoader_.pause();
  26183. this.subtitleSegmentLoader_.resetEverything();
  26184. } // start segment loader loading in case they are paused
  26185. this.load();
  26186. }
  26187. /**
  26188. * get the current duration
  26189. *
  26190. * @return {TimeRange} the duration
  26191. */
  26192. duration() {
  26193. if (!this.mainPlaylistLoader_) {
  26194. return 0;
  26195. }
  26196. const media = this.mainPlaylistLoader_.media();
  26197. if (!media) {
  26198. // no playlists loaded yet, so can't determine a duration
  26199. return 0;
  26200. } // Don't rely on the media source for duration in the case of a live playlist since
  26201. // setting the native MediaSource's duration to infinity ends up with consequences to
  26202. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  26203. //
  26204. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  26205. // however, few browsers have support for setLiveSeekableRange()
  26206. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  26207. //
  26208. // Until a time when the duration of the media source can be set to infinity, and a
  26209. // seekable range specified across browsers, just return Infinity.
  26210. if (!media.endList) {
  26211. return Infinity;
  26212. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  26213. // available). If it's not available, fall back to a playlist-calculated estimate.
  26214. if (this.mediaSource) {
  26215. return this.mediaSource.duration;
  26216. }
  26217. return Vhs$1.Playlist.duration(media);
  26218. }
  26219. /**
  26220. * check the seekable range
  26221. *
  26222. * @return {TimeRange} the seekable range
  26223. */
  26224. seekable() {
  26225. return this.seekable_;
  26226. }
  26227. onSyncInfoUpdate_() {
  26228. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  26229. //
  26230. // A fix was made to this function where a check for
  26231. // this.sourceUpdater_.hasCreatedSourceBuffers
  26232. // was added to ensure that both source buffers were created before seekable was
  26233. // updated. However, it originally had a bug where it was checking for a true and
  26234. // returning early instead of checking for false. Setting it to check for false to
  26235. // return early though created other issues. A call to play() would check for seekable
  26236. // end without verifying that a seekable range was present. In addition, even checking
  26237. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  26238. // due to a media update calling load on the segment loaders, skipping a seek to live,
  26239. // thereby starting live streams at the beginning of the stream rather than at the end.
  26240. //
  26241. // This conditional should be fixed to wait for the creation of two source buffers at
  26242. // the same time as the other sections of code are fixed to properly seek to live and
  26243. // not throw an error due to checking for a seekable end when no seekable range exists.
  26244. //
  26245. // For now, fall back to the older behavior, with the understanding that the seekable
  26246. // range may not be completely correct, leading to a suboptimal initial live point.
  26247. if (!this.mainPlaylistLoader_) {
  26248. return;
  26249. }
  26250. let media = this.mainPlaylistLoader_.media();
  26251. if (!media) {
  26252. return;
  26253. }
  26254. let expired = this.syncController_.getExpiredTime(media, this.duration());
  26255. if (expired === null) {
  26256. // not enough information to update seekable
  26257. return;
  26258. }
  26259. const main = this.mainPlaylistLoader_.main;
  26260. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  26261. if (mainSeekable.length === 0) {
  26262. return;
  26263. }
  26264. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  26265. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  26266. expired = this.syncController_.getExpiredTime(media, this.duration());
  26267. if (expired === null) {
  26268. return;
  26269. }
  26270. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  26271. if (audioSeekable.length === 0) {
  26272. return;
  26273. }
  26274. }
  26275. let oldEnd;
  26276. let oldStart;
  26277. if (this.seekable_ && this.seekable_.length) {
  26278. oldEnd = this.seekable_.end(0);
  26279. oldStart = this.seekable_.start(0);
  26280. }
  26281. if (!audioSeekable) {
  26282. // seekable has been calculated based on buffering video data so it
  26283. // can be returned directly
  26284. this.seekable_ = mainSeekable;
  26285. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  26286. // seekables are pretty far off, rely on main
  26287. this.seekable_ = mainSeekable;
  26288. } else {
  26289. 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)]]);
  26290. } // seekable is the same as last time
  26291. if (this.seekable_ && this.seekable_.length) {
  26292. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  26293. return;
  26294. }
  26295. }
  26296. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  26297. this.tech_.trigger('seekablechanged');
  26298. }
  26299. /**
  26300. * Update the player duration
  26301. */
  26302. updateDuration(isLive) {
  26303. if (this.updateDuration_) {
  26304. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  26305. this.updateDuration_ = null;
  26306. }
  26307. if (this.mediaSource.readyState !== 'open') {
  26308. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  26309. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  26310. return;
  26311. }
  26312. if (isLive) {
  26313. const seekable = this.seekable();
  26314. if (!seekable.length) {
  26315. return;
  26316. } // Even in the case of a live playlist, the native MediaSource's duration should not
  26317. // be set to Infinity (even though this would be expected for a live playlist), since
  26318. // setting the native MediaSource's duration to infinity ends up with consequences to
  26319. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  26320. //
  26321. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  26322. // however, few browsers have support for setLiveSeekableRange()
  26323. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  26324. //
  26325. // Until a time when the duration of the media source can be set to infinity, and a
  26326. // seekable range specified across browsers, the duration should be greater than or
  26327. // equal to the last possible seekable value.
  26328. // MediaSource duration starts as NaN
  26329. // It is possible (and probable) that this case will never be reached for many
  26330. // sources, since the MediaSource reports duration as the highest value without
  26331. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  26332. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  26333. // time will be between 0 and 100, the native media source may report the duration
  26334. // as 200. However, since we report duration separate from the media source (as
  26335. // Infinity), and as long as the native media source duration value is greater than
  26336. // our reported seekable range, seeks will work as expected. The large number as
  26337. // duration for live is actually a strategy used by some players to work around the
  26338. // issue of live seekable ranges cited above.
  26339. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  26340. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  26341. }
  26342. return;
  26343. }
  26344. const buffered = this.tech_.buffered();
  26345. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  26346. if (buffered.length > 0) {
  26347. duration = Math.max(duration, buffered.end(buffered.length - 1));
  26348. }
  26349. if (this.mediaSource.duration !== duration) {
  26350. this.sourceUpdater_.setDuration(duration);
  26351. }
  26352. }
  26353. /**
  26354. * dispose of the PlaylistController and everything
  26355. * that it controls
  26356. */
  26357. dispose() {
  26358. this.trigger('dispose');
  26359. this.decrypter_.terminate();
  26360. this.mainPlaylistLoader_.dispose();
  26361. this.mainSegmentLoader_.dispose();
  26362. this.contentSteeringController_.dispose();
  26363. this.keyStatusMap_.clear();
  26364. if (this.loadOnPlay_) {
  26365. this.tech_.off('play', this.loadOnPlay_);
  26366. }
  26367. ['AUDIO', 'SUBTITLES'].forEach(type => {
  26368. const groups = this.mediaTypes_[type].groups;
  26369. for (const id in groups) {
  26370. groups[id].forEach(group => {
  26371. if (group.playlistLoader) {
  26372. group.playlistLoader.dispose();
  26373. }
  26374. });
  26375. }
  26376. });
  26377. this.audioSegmentLoader_.dispose();
  26378. this.subtitleSegmentLoader_.dispose();
  26379. this.sourceUpdater_.dispose();
  26380. this.timelineChangeController_.dispose();
  26381. this.stopABRTimer_();
  26382. if (this.updateDuration_) {
  26383. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  26384. }
  26385. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  26386. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  26387. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  26388. this.off();
  26389. }
  26390. /**
  26391. * return the main playlist object if we have one
  26392. *
  26393. * @return {Object} the main playlist object that we parsed
  26394. */
  26395. main() {
  26396. return this.mainPlaylistLoader_.main;
  26397. }
  26398. /**
  26399. * return the currently selected playlist
  26400. *
  26401. * @return {Object} the currently selected playlist object that we parsed
  26402. */
  26403. media() {
  26404. // playlist loader will not return media if it has not been fully loaded
  26405. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  26406. }
  26407. areMediaTypesKnown_() {
  26408. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  26409. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  26410. // otherwise check on the segment loader.
  26411. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  26412. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  26413. return false;
  26414. }
  26415. return true;
  26416. }
  26417. getCodecsOrExclude_() {
  26418. const media = {
  26419. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  26420. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  26421. };
  26422. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  26423. media.video = media.main;
  26424. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  26425. const codecs = {};
  26426. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  26427. if (media.main.hasVideo) {
  26428. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  26429. }
  26430. if (media.main.isMuxed) {
  26431. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC}`;
  26432. }
  26433. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  26434. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  26435. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  26436. } // no codecs, no playback.
  26437. if (!codecs.audio && !codecs.video) {
  26438. this.excludePlaylist({
  26439. playlistToExclude: playlist,
  26440. error: {
  26441. message: 'Could not determine codecs for playlist.'
  26442. },
  26443. playlistExclusionDuration: Infinity
  26444. });
  26445. return;
  26446. } // fmp4 relies on browser support, while ts relies on muxer support
  26447. const supportFunction = (isFmp4, codec) => isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  26448. const unsupportedCodecs = {};
  26449. let unsupportedAudio;
  26450. ['video', 'audio'].forEach(function (type) {
  26451. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  26452. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  26453. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  26454. unsupportedCodecs[supporter].push(codecs[type]);
  26455. if (type === 'audio') {
  26456. unsupportedAudio = supporter;
  26457. }
  26458. }
  26459. });
  26460. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  26461. const audioGroup = playlist.attributes.AUDIO;
  26462. this.main().playlists.forEach(variant => {
  26463. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  26464. if (variantAudioGroup === audioGroup && variant !== playlist) {
  26465. variant.excludeUntil = Infinity;
  26466. }
  26467. });
  26468. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  26469. } // if we have any unsupported codecs exclude this playlist.
  26470. if (Object.keys(unsupportedCodecs).length) {
  26471. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  26472. if (acc) {
  26473. acc += ', ';
  26474. }
  26475. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  26476. return acc;
  26477. }, '') + '.';
  26478. this.excludePlaylist({
  26479. playlistToExclude: playlist,
  26480. error: {
  26481. internal: true,
  26482. message
  26483. },
  26484. playlistExclusionDuration: Infinity
  26485. });
  26486. return;
  26487. } // check if codec switching is happening
  26488. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  26489. const switchMessages = [];
  26490. ['video', 'audio'].forEach(type => {
  26491. const newCodec = (parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  26492. const oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  26493. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  26494. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  26495. }
  26496. });
  26497. if (switchMessages.length) {
  26498. this.excludePlaylist({
  26499. playlistToExclude: playlist,
  26500. error: {
  26501. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  26502. internal: true
  26503. },
  26504. playlistExclusionDuration: Infinity
  26505. });
  26506. return;
  26507. }
  26508. } // TODO: when using the muxer shouldn't we just return
  26509. // the codecs that the muxer outputs?
  26510. return codecs;
  26511. }
  26512. /**
  26513. * Create source buffers and exlude any incompatible renditions.
  26514. *
  26515. * @private
  26516. */
  26517. tryToCreateSourceBuffers_() {
  26518. // media source is not ready yet or sourceBuffers are already
  26519. // created.
  26520. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  26521. return;
  26522. }
  26523. if (!this.areMediaTypesKnown_()) {
  26524. return;
  26525. }
  26526. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  26527. if (!codecs) {
  26528. return;
  26529. }
  26530. this.sourceUpdater_.createSourceBuffers(codecs);
  26531. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  26532. this.excludeIncompatibleVariants_(codecString);
  26533. }
  26534. /**
  26535. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  26536. */
  26537. excludeUnsupportedVariants_() {
  26538. const playlists = this.main().playlists;
  26539. const ids = []; // TODO: why don't we have a property to loop through all
  26540. // playlist? Why did we ever mix indexes and keys?
  26541. Object.keys(playlists).forEach(key => {
  26542. const variant = playlists[key]; // check if we already processed this playlist.
  26543. if (ids.indexOf(variant.id) !== -1) {
  26544. return;
  26545. }
  26546. ids.push(variant.id);
  26547. const codecs = codecsForPlaylist(this.main, variant);
  26548. const unsupported = [];
  26549. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  26550. unsupported.push(`audio codec ${codecs.audio}`);
  26551. }
  26552. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  26553. unsupported.push(`video codec ${codecs.video}`);
  26554. }
  26555. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  26556. unsupported.push(`text codec ${codecs.text}`);
  26557. }
  26558. if (unsupported.length) {
  26559. variant.excludeUntil = Infinity;
  26560. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  26561. }
  26562. });
  26563. }
  26564. /**
  26565. * Exclude playlists that are known to be codec or
  26566. * stream-incompatible with the SourceBuffer configuration. For
  26567. * instance, Media Source Extensions would cause the video element to
  26568. * stall waiting for video data if you switched from a variant with
  26569. * video and audio to an audio-only one.
  26570. *
  26571. * @param {Object} media a media playlist compatible with the current
  26572. * set of SourceBuffers. Variants in the current main playlist that
  26573. * do not appear to have compatible codec or stream configurations
  26574. * will be excluded from the default playlist selection algorithm
  26575. * indefinitely.
  26576. * @private
  26577. */
  26578. excludeIncompatibleVariants_(codecString) {
  26579. const ids = [];
  26580. const playlists = this.main().playlists;
  26581. const codecs = unwrapCodecList(parseCodecs(codecString));
  26582. const codecCount_ = codecCount(codecs);
  26583. const videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  26584. const audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  26585. Object.keys(playlists).forEach(key => {
  26586. const variant = playlists[key]; // check if we already processed this playlist.
  26587. // or it if it is already excluded forever.
  26588. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  26589. return;
  26590. }
  26591. ids.push(variant.id);
  26592. const exclusionReasons = []; // get codecs from the playlist for this variant
  26593. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  26594. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  26595. // variant is incompatible. Wait for mux.js to probe
  26596. if (!variantCodecs.audio && !variantCodecs.video) {
  26597. return;
  26598. } // TODO: we can support this by removing the
  26599. // old media source and creating a new one, but it will take some work.
  26600. // The number of streams cannot change
  26601. if (variantCodecCount !== codecCount_) {
  26602. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  26603. } // only exclude playlists by codec change, if codecs cannot switch
  26604. // during playback.
  26605. if (!this.sourceUpdater_.canChangeType()) {
  26606. const variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  26607. const variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  26608. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  26609. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  26610. } // the audio codec cannot change
  26611. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  26612. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  26613. }
  26614. }
  26615. if (exclusionReasons.length) {
  26616. variant.excludeUntil = Infinity;
  26617. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  26618. }
  26619. });
  26620. }
  26621. updateAdCues_(media) {
  26622. let offset = 0;
  26623. const seekable = this.seekable();
  26624. if (seekable.length) {
  26625. offset = seekable.start(0);
  26626. }
  26627. updateAdCues(media, this.cueTagsTrack_, offset);
  26628. }
  26629. /**
  26630. * Calculates the desired forward buffer length based on current time
  26631. *
  26632. * @return {number} Desired forward buffer length in seconds
  26633. */
  26634. goalBufferLength() {
  26635. const currentTime = this.tech_.currentTime();
  26636. const initial = Config.GOAL_BUFFER_LENGTH;
  26637. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  26638. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  26639. return Math.min(initial + currentTime * rate, max);
  26640. }
  26641. /**
  26642. * Calculates the desired buffer low water line based on current time
  26643. *
  26644. * @return {number} Desired buffer low water line in seconds
  26645. */
  26646. bufferLowWaterLine() {
  26647. const currentTime = this.tech_.currentTime();
  26648. const initial = Config.BUFFER_LOW_WATER_LINE;
  26649. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  26650. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  26651. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  26652. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  26653. }
  26654. bufferHighWaterLine() {
  26655. return Config.BUFFER_HIGH_WATER_LINE;
  26656. }
  26657. addDateRangesToTextTrack_(dateRanges) {
  26658. createMetadataTrackIfNotExists(this.inbandTextTracks_, 'com.apple.streaming', this.tech_);
  26659. addDateRangeMetadata({
  26660. inbandTextTracks: this.inbandTextTracks_,
  26661. dateRanges
  26662. });
  26663. }
  26664. addMetadataToTextTrack(dispatchType, metadataArray, videoDuration) {
  26665. const timestampOffset = this.sourceUpdater_.videoBuffer ? this.sourceUpdater_.videoTimestampOffset() : this.sourceUpdater_.audioTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  26666. // audio/video source with a metadata track, and an alt audio with a metadata track.
  26667. // However, this probably won't happen, and if it does it can be handled then.
  26668. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.tech_);
  26669. addMetadata({
  26670. inbandTextTracks: this.inbandTextTracks_,
  26671. metadataArray,
  26672. timestampOffset,
  26673. videoDuration
  26674. });
  26675. }
  26676. /**
  26677. * Utility for getting the pathway or service location from an HLS or DASH playlist.
  26678. *
  26679. * @param {Object} playlist for getting pathway from.
  26680. * @return the pathway attribute of a playlist
  26681. */
  26682. pathwayAttribute_(playlist) {
  26683. return playlist.attributes['PATHWAY-ID'] || playlist.attributes.serviceLocation;
  26684. }
  26685. /**
  26686. * Initialize available pathways and apply the tag properties.
  26687. */
  26688. initContentSteeringController_() {
  26689. const main = this.main();
  26690. if (!main.contentSteering) {
  26691. return;
  26692. }
  26693. for (const playlist of main.playlists) {
  26694. this.contentSteeringController_.addAvailablePathway(this.pathwayAttribute_(playlist));
  26695. }
  26696. this.contentSteeringController_.assignTagProperties(main.uri, main.contentSteering); // request the steering manifest immediately if queryBeforeStart is set.
  26697. if (this.contentSteeringController_.queryBeforeStart) {
  26698. // When queryBeforeStart is true, initial request should omit steering parameters.
  26699. this.contentSteeringController_.requestSteeringManifest(true);
  26700. return;
  26701. } // otherwise start content steering after playback starts
  26702. this.tech_.one('canplay', () => {
  26703. this.contentSteeringController_.requestSteeringManifest();
  26704. });
  26705. }
  26706. /**
  26707. * Reset the content steering controller and re-init.
  26708. */
  26709. resetContentSteeringController_() {
  26710. this.contentSteeringController_.clearAvailablePathways();
  26711. this.contentSteeringController_.dispose();
  26712. this.initContentSteeringController_();
  26713. }
  26714. /**
  26715. * Attaches the listeners for content steering.
  26716. */
  26717. attachContentSteeringListeners_() {
  26718. this.contentSteeringController_.on('content-steering', this.excludeThenChangePathway_.bind(this));
  26719. if (this.sourceType_ === 'dash') {
  26720. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  26721. const main = this.main(); // check if steering tag or pathways changed.
  26722. const didDashTagChange = this.contentSteeringController_.didDASHTagChange(main.uri, main.contentSteering);
  26723. const didPathwaysChange = () => {
  26724. const availablePathways = this.contentSteeringController_.getAvailablePathways();
  26725. const newPathways = [];
  26726. for (const playlist of main.playlists) {
  26727. const serviceLocation = playlist.attributes.serviceLocation;
  26728. if (serviceLocation) {
  26729. newPathways.push(serviceLocation);
  26730. if (!availablePathways.has(serviceLocation)) {
  26731. return true;
  26732. }
  26733. }
  26734. } // If we have no new serviceLocations and previously had availablePathways
  26735. if (!newPathways.length && availablePathways.size) {
  26736. return true;
  26737. }
  26738. return false;
  26739. };
  26740. if (didDashTagChange || didPathwaysChange()) {
  26741. this.resetContentSteeringController_();
  26742. }
  26743. });
  26744. }
  26745. }
  26746. /**
  26747. * Simple exclude and change playlist logic for content steering.
  26748. */
  26749. excludeThenChangePathway_() {
  26750. const currentPathway = this.contentSteeringController_.getPathway();
  26751. if (!currentPathway) {
  26752. return;
  26753. }
  26754. this.handlePathwayClones_();
  26755. const main = this.main();
  26756. const playlists = main.playlists;
  26757. const ids = new Set();
  26758. let didEnablePlaylists = false;
  26759. Object.keys(playlists).forEach(key => {
  26760. const variant = playlists[key];
  26761. const pathwayId = this.pathwayAttribute_(variant);
  26762. const differentPathwayId = pathwayId && currentPathway !== pathwayId;
  26763. const steeringExclusion = variant.excludeUntil === Infinity && variant.lastExcludeReason_ === 'content-steering';
  26764. if (steeringExclusion && !differentPathwayId) {
  26765. delete variant.excludeUntil;
  26766. delete variant.lastExcludeReason_;
  26767. didEnablePlaylists = true;
  26768. }
  26769. const noExcludeUntil = !variant.excludeUntil && variant.excludeUntil !== Infinity;
  26770. const shouldExclude = !ids.has(variant.id) && differentPathwayId && noExcludeUntil;
  26771. if (!shouldExclude) {
  26772. return;
  26773. }
  26774. ids.add(variant.id);
  26775. variant.excludeUntil = Infinity;
  26776. variant.lastExcludeReason_ = 'content-steering'; // TODO: kind of spammy, maybe move this.
  26777. this.logger_(`excluding ${variant.id} for ${variant.lastExcludeReason_}`);
  26778. });
  26779. if (this.contentSteeringController_.manifestType_ === 'DASH') {
  26780. Object.keys(this.mediaTypes_).forEach(key => {
  26781. const type = this.mediaTypes_[key];
  26782. if (type.activePlaylistLoader) {
  26783. const currentPlaylist = type.activePlaylistLoader.media_; // Check if the current media playlist matches the current CDN
  26784. if (currentPlaylist && currentPlaylist.attributes.serviceLocation !== currentPathway) {
  26785. didEnablePlaylists = true;
  26786. }
  26787. }
  26788. });
  26789. }
  26790. if (didEnablePlaylists) {
  26791. this.changeSegmentPathway_();
  26792. }
  26793. }
  26794. /**
  26795. * Add, update, or delete playlists and media groups for
  26796. * the pathway clones for HLS Content Steering.
  26797. *
  26798. * See https://datatracker.ietf.org/doc/draft-pantos-hls-rfc8216bis/
  26799. *
  26800. * NOTE: Pathway cloning does not currently support the `PER_VARIANT_URIS` and
  26801. * `PER_RENDITION_URIS` as we do not handle `STABLE-VARIANT-ID` or
  26802. * `STABLE-RENDITION-ID` values.
  26803. */
  26804. handlePathwayClones_() {
  26805. const main = this.main();
  26806. const playlists = main.playlists;
  26807. const currentPathwayClones = this.contentSteeringController_.currentPathwayClones;
  26808. const nextPathwayClones = this.contentSteeringController_.nextPathwayClones;
  26809. const hasClones = currentPathwayClones && currentPathwayClones.size || nextPathwayClones && nextPathwayClones.size;
  26810. if (!hasClones) {
  26811. return;
  26812. }
  26813. for (const [id, clone] of currentPathwayClones.entries()) {
  26814. const newClone = nextPathwayClones.get(id); // Delete the old pathway clone.
  26815. if (!newClone) {
  26816. this.mainPlaylistLoader_.updateOrDeleteClone(clone);
  26817. this.contentSteeringController_.excludePathway(id);
  26818. }
  26819. }
  26820. for (const [id, clone] of nextPathwayClones.entries()) {
  26821. const oldClone = currentPathwayClones.get(id); // Create a new pathway if it is a new pathway clone object.
  26822. if (!oldClone) {
  26823. const playlistsToClone = playlists.filter(p => {
  26824. return p.attributes['PATHWAY-ID'] === clone['BASE-ID'];
  26825. });
  26826. playlistsToClone.forEach(p => {
  26827. this.mainPlaylistLoader_.addClonePathway(clone, p);
  26828. });
  26829. this.contentSteeringController_.addAvailablePathway(id);
  26830. continue;
  26831. } // There have not been changes to the pathway clone object, so skip.
  26832. if (this.equalPathwayClones_(oldClone, clone)) {
  26833. continue;
  26834. } // Update a preexisting cloned pathway.
  26835. // True is set for the update flag.
  26836. this.mainPlaylistLoader_.updateOrDeleteClone(clone, true);
  26837. this.contentSteeringController_.addAvailablePathway(id);
  26838. } // Deep copy contents of next to current pathways.
  26839. this.contentSteeringController_.currentPathwayClones = new Map(JSON.parse(JSON.stringify([...nextPathwayClones])));
  26840. }
  26841. /**
  26842. * Determines whether two pathway clone objects are equivalent.
  26843. *
  26844. * @param {Object} a The first pathway clone object.
  26845. * @param {Object} b The second pathway clone object.
  26846. * @return {boolean} True if the pathway clone objects are equal, false otherwise.
  26847. */
  26848. equalPathwayClones_(a, b) {
  26849. if (a['BASE-ID'] !== b['BASE-ID'] || a.ID !== b.ID || a['URI-REPLACEMENT'].HOST !== b['URI-REPLACEMENT'].HOST) {
  26850. return false;
  26851. }
  26852. const aParams = a['URI-REPLACEMENT'].PARAMS;
  26853. const bParams = b['URI-REPLACEMENT'].PARAMS; // We need to iterate through both lists of params because one could be
  26854. // missing a parameter that the other has.
  26855. for (const p in aParams) {
  26856. if (aParams[p] !== bParams[p]) {
  26857. return false;
  26858. }
  26859. }
  26860. for (const p in bParams) {
  26861. if (aParams[p] !== bParams[p]) {
  26862. return false;
  26863. }
  26864. }
  26865. return true;
  26866. }
  26867. /**
  26868. * Changes the current playlists for audio, video and subtitles after a new pathway
  26869. * is chosen from content steering.
  26870. */
  26871. changeSegmentPathway_() {
  26872. const nextPlaylist = this.selectPlaylist();
  26873. this.pauseLoading(); // Switch audio and text track playlists if necessary in DASH
  26874. if (this.contentSteeringController_.manifestType_ === 'DASH') {
  26875. this.switchMediaForDASHContentSteering_();
  26876. }
  26877. this.switchMedia_(nextPlaylist, 'content-steering');
  26878. }
  26879. /**
  26880. * Iterates through playlists and check their keyId set and compare with the
  26881. * keyStatusMap, only enable playlists that have a usable key. If the playlist
  26882. * has no keyId leave it enabled by default.
  26883. */
  26884. excludeNonUsablePlaylistsByKeyId_() {
  26885. if (!this.mainPlaylistLoader_ || !this.mainPlaylistLoader_.main) {
  26886. return;
  26887. }
  26888. let nonUsableKeyStatusCount = 0;
  26889. const NON_USABLE = 'non-usable';
  26890. this.mainPlaylistLoader_.main.playlists.forEach(playlist => {
  26891. const keyIdSet = this.mainPlaylistLoader_.getKeyIdSet(playlist); // If the playlist doesn't have keyIDs lets not exclude it.
  26892. if (!keyIdSet || !keyIdSet.size) {
  26893. return;
  26894. }
  26895. keyIdSet.forEach(key => {
  26896. const USABLE = 'usable';
  26897. const hasUsableKeyStatus = this.keyStatusMap_.has(key) && this.keyStatusMap_.get(key) === USABLE;
  26898. const nonUsableExclusion = playlist.lastExcludeReason_ === NON_USABLE && playlist.excludeUntil === Infinity;
  26899. if (!hasUsableKeyStatus) {
  26900. // Only exclude playlists that haven't already been excluded as non-usable.
  26901. if (playlist.excludeUntil !== Infinity && playlist.lastExcludeReason_ !== NON_USABLE) {
  26902. playlist.excludeUntil = Infinity;
  26903. playlist.lastExcludeReason_ = NON_USABLE;
  26904. this.logger_(`excluding playlist ${playlist.id} because the key ID ${key} doesn't exist in the keyStatusMap or is not ${USABLE}`);
  26905. } // count all nonUsableKeyStatus
  26906. nonUsableKeyStatusCount++;
  26907. } else if (hasUsableKeyStatus && nonUsableExclusion) {
  26908. delete playlist.excludeUntil;
  26909. delete playlist.lastExcludeReason_;
  26910. this.logger_(`enabling playlist ${playlist.id} because key ID ${key} is ${USABLE}`);
  26911. }
  26912. });
  26913. }); // If for whatever reason every playlist has a non usable key status. Lets try re-including the SD renditions as a failsafe.
  26914. if (nonUsableKeyStatusCount >= this.mainPlaylistLoader_.main.playlists.length) {
  26915. this.mainPlaylistLoader_.main.playlists.forEach(playlist => {
  26916. const isNonHD = playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height < 720;
  26917. const excludedForNonUsableKey = playlist.excludeUntil === Infinity && playlist.lastExcludeReason_ === NON_USABLE;
  26918. if (isNonHD && excludedForNonUsableKey) {
  26919. // Only delete the excludeUntil so we don't try and re-exclude these playlists.
  26920. delete playlist.excludeUntil;
  26921. videojs__default["default"].log.warn(`enabling non-HD playlist ${playlist.id} because all playlists were excluded due to ${NON_USABLE} key IDs`);
  26922. }
  26923. });
  26924. }
  26925. }
  26926. /**
  26927. * Adds a keystatus to the keystatus map, tries to convert to string if necessary.
  26928. *
  26929. * @param {any} keyId the keyId to add a status for
  26930. * @param {string} status the status of the keyId
  26931. */
  26932. addKeyStatus_(keyId, status) {
  26933. const isString = typeof keyId === 'string';
  26934. const keyIdHexString = isString ? keyId : bufferToHexString(keyId);
  26935. const formattedKeyIdString = keyIdHexString.slice(0, 32).toLowerCase();
  26936. this.logger_(`KeyStatus '${status}' with key ID ${formattedKeyIdString} added to the keyStatusMap`);
  26937. this.keyStatusMap_.set(formattedKeyIdString, status);
  26938. }
  26939. /**
  26940. * Utility function for adding key status to the keyStatusMap and filtering usable encrypted playlists.
  26941. *
  26942. * @param {any} keyId the keyId from the keystatuschange event
  26943. * @param {string} status the key status string
  26944. */
  26945. updatePlaylistByKeyStatus(keyId, status) {
  26946. this.addKeyStatus_(keyId, status);
  26947. if (!this.waitingForFastQualityPlaylistReceived_) {
  26948. this.excludeNonUsableThenChangePlaylist_();
  26949. } // Listen to loadedplaylist with a single listener and check for new contentProtection elements when a playlist is updated.
  26950. this.mainPlaylistLoader_.off('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));
  26951. this.mainPlaylistLoader_.on('loadedplaylist', this.excludeNonUsableThenChangePlaylist_.bind(this));
  26952. }
  26953. excludeNonUsableThenChangePlaylist_() {
  26954. this.excludeNonUsablePlaylistsByKeyId_();
  26955. this.fastQualityChange_();
  26956. }
  26957. }
  26958. /**
  26959. * Returns a function that acts as the Enable/disable playlist function.
  26960. *
  26961. * @param {PlaylistLoader} loader - The main playlist loader
  26962. * @param {string} playlistID - id of the playlist
  26963. * @param {Function} changePlaylistFn - A function to be called after a
  26964. * playlist's enabled-state has been changed. Will NOT be called if a
  26965. * playlist's enabled-state is unchanged
  26966. * @param {boolean=} enable - Value to set the playlist enabled-state to
  26967. * or if undefined returns the current enabled-state for the playlist
  26968. * @return {Function} Function for setting/getting enabled
  26969. */
  26970. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  26971. const playlist = loader.main.playlists[playlistID];
  26972. const incompatible = isIncompatible(playlist);
  26973. const currentlyEnabled = isEnabled(playlist);
  26974. if (typeof enable === 'undefined') {
  26975. return currentlyEnabled;
  26976. }
  26977. if (enable) {
  26978. delete playlist.disabled;
  26979. } else {
  26980. playlist.disabled = true;
  26981. }
  26982. if (enable !== currentlyEnabled && !incompatible) {
  26983. // Ensure the outside world knows about our changes
  26984. changePlaylistFn();
  26985. if (enable) {
  26986. loader.trigger('renditionenabled');
  26987. } else {
  26988. loader.trigger('renditiondisabled');
  26989. }
  26990. }
  26991. return enable;
  26992. };
  26993. /**
  26994. * The representation object encapsulates the publicly visible information
  26995. * in a media playlist along with a setter/getter-type function (enabled)
  26996. * for changing the enabled-state of a particular playlist entry
  26997. *
  26998. * @class Representation
  26999. */
  27000. class Representation {
  27001. constructor(vhsHandler, playlist, id) {
  27002. const {
  27003. playlistController_: pc
  27004. } = vhsHandler;
  27005. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  27006. if (playlist.attributes) {
  27007. const resolution = playlist.attributes.RESOLUTION;
  27008. this.width = resolution && resolution.width;
  27009. this.height = resolution && resolution.height;
  27010. this.bandwidth = playlist.attributes.BANDWIDTH;
  27011. this.frameRate = playlist.attributes['FRAME-RATE'];
  27012. }
  27013. this.codecs = codecsForPlaylist(pc.main(), playlist);
  27014. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  27015. // within the main playlist
  27016. this.id = id; // Partially-apply the enableFunction to create a playlist-
  27017. // specific variant
  27018. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  27019. }
  27020. }
  27021. /**
  27022. * A mixin function that adds the `representations` api to an instance
  27023. * of the VhsHandler class
  27024. *
  27025. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  27026. * representation API into
  27027. */
  27028. const renditionSelectionMixin = function (vhsHandler) {
  27029. // Add a single API-specific function to the VhsHandler instance
  27030. vhsHandler.representations = () => {
  27031. const main = vhsHandler.playlistController_.main();
  27032. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  27033. if (!playlists) {
  27034. return [];
  27035. }
  27036. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  27037. };
  27038. };
  27039. /**
  27040. * @file playback-watcher.js
  27041. *
  27042. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  27043. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  27044. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  27045. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  27046. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  27047. */
  27048. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  27049. /**
  27050. * @class PlaybackWatcher
  27051. */
  27052. class PlaybackWatcher {
  27053. /**
  27054. * Represents an PlaybackWatcher object.
  27055. *
  27056. * @class
  27057. * @param {Object} options an object that includes the tech and settings
  27058. */
  27059. constructor(options) {
  27060. this.playlistController_ = options.playlistController;
  27061. this.tech_ = options.tech;
  27062. this.seekable = options.seekable;
  27063. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  27064. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  27065. this.media = options.media;
  27066. this.consecutiveUpdates = 0;
  27067. this.lastRecordedTime = null;
  27068. this.checkCurrentTimeTimeout_ = null;
  27069. this.logger_ = logger('PlaybackWatcher');
  27070. this.logger_('initialize');
  27071. const playHandler = () => this.monitorCurrentTime_();
  27072. const canPlayHandler = () => this.monitorCurrentTime_();
  27073. const waitingHandler = () => this.techWaiting_();
  27074. const cancelTimerHandler = () => this.resetTimeUpdate_();
  27075. const pc = this.playlistController_;
  27076. const loaderTypes = ['main', 'subtitle', 'audio'];
  27077. const loaderChecks = {};
  27078. loaderTypes.forEach(type => {
  27079. loaderChecks[type] = {
  27080. reset: () => this.resetSegmentDownloads_(type),
  27081. updateend: () => this.checkSegmentDownloads_(type)
  27082. };
  27083. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  27084. // isn't changing we want to reset. We cannot assume that the new rendition
  27085. // will also be stalled, until after new appends.
  27086. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  27087. // This prevents one segment playlists (single vtt or single segment content)
  27088. // from being detected as stalling. As the buffer will not change in those cases, since
  27089. // the buffer is the entire video duration.
  27090. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  27091. });
  27092. /**
  27093. * We check if a seek was into a gap through the following steps:
  27094. * 1. We get a seeking event and we do not get a seeked event. This means that
  27095. * a seek was attempted but not completed.
  27096. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  27097. * removed everything from our buffer and appended a segment, and should be ready
  27098. * to check for gaps.
  27099. */
  27100. const setSeekingHandlers = fn => {
  27101. ['main', 'audio'].forEach(type => {
  27102. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  27103. });
  27104. };
  27105. this.seekingAppendCheck_ = () => {
  27106. if (this.fixesBadSeeks_()) {
  27107. this.consecutiveUpdates = 0;
  27108. this.lastRecordedTime = this.tech_.currentTime();
  27109. setSeekingHandlers('off');
  27110. }
  27111. };
  27112. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  27113. this.watchForBadSeeking_ = () => {
  27114. this.clearSeekingAppendCheck_();
  27115. setSeekingHandlers('on');
  27116. };
  27117. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  27118. this.tech_.on('seeking', this.watchForBadSeeking_);
  27119. this.tech_.on('waiting', waitingHandler);
  27120. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  27121. this.tech_.on('canplay', canPlayHandler);
  27122. /*
  27123. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  27124. is surfaced in one of two ways:
  27125. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  27126. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  27127. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  27128. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  27129. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  27130. even if the player is in a playing state
  27131. */
  27132. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  27133. this.dispose = () => {
  27134. this.clearSeekingAppendCheck_();
  27135. this.logger_('dispose');
  27136. this.tech_.off('waiting', waitingHandler);
  27137. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  27138. this.tech_.off('canplay', canPlayHandler);
  27139. this.tech_.off('play', playHandler);
  27140. this.tech_.off('seeking', this.watchForBadSeeking_);
  27141. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  27142. loaderTypes.forEach(type => {
  27143. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  27144. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  27145. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  27146. });
  27147. if (this.checkCurrentTimeTimeout_) {
  27148. window.clearTimeout(this.checkCurrentTimeTimeout_);
  27149. }
  27150. this.resetTimeUpdate_();
  27151. };
  27152. }
  27153. /**
  27154. * Periodically check current time to see if playback stopped
  27155. *
  27156. * @private
  27157. */
  27158. monitorCurrentTime_() {
  27159. this.checkCurrentTime_();
  27160. if (this.checkCurrentTimeTimeout_) {
  27161. window.clearTimeout(this.checkCurrentTimeTimeout_);
  27162. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  27163. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  27164. }
  27165. /**
  27166. * Reset stalled download stats for a specific type of loader
  27167. *
  27168. * @param {string} type
  27169. * The segment loader type to check.
  27170. *
  27171. * @listens SegmentLoader#playlistupdate
  27172. * @listens Tech#seeking
  27173. * @listens Tech#seeked
  27174. */
  27175. resetSegmentDownloads_(type) {
  27176. const loader = this.playlistController_[`${type}SegmentLoader_`];
  27177. if (this[`${type}StalledDownloads_`] > 0) {
  27178. this.logger_(`resetting possible stalled download count for ${type} loader`);
  27179. }
  27180. this[`${type}StalledDownloads_`] = 0;
  27181. this[`${type}Buffered_`] = loader.buffered_();
  27182. }
  27183. /**
  27184. * Checks on every segment `appendsdone` to see
  27185. * if segment appends are making progress. If they are not
  27186. * and we are still downloading bytes. We exclude the playlist.
  27187. *
  27188. * @param {string} type
  27189. * The segment loader type to check.
  27190. *
  27191. * @listens SegmentLoader#appendsdone
  27192. */
  27193. checkSegmentDownloads_(type) {
  27194. const pc = this.playlistController_;
  27195. const loader = pc[`${type}SegmentLoader_`];
  27196. const buffered = loader.buffered_();
  27197. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  27198. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  27199. // the buffered value for this loader changed
  27200. // appends are working
  27201. if (isBufferedDifferent) {
  27202. this.resetSegmentDownloads_(type);
  27203. return;
  27204. }
  27205. this[`${type}StalledDownloads_`]++;
  27206. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  27207. playlistId: loader.playlist_ && loader.playlist_.id,
  27208. buffered: timeRangesToArray(buffered)
  27209. }); // after 10 possibly stalled appends with no reset, exclude
  27210. if (this[`${type}StalledDownloads_`] < 10) {
  27211. return;
  27212. }
  27213. this.logger_(`${type} loader stalled download exclusion`);
  27214. this.resetSegmentDownloads_(type);
  27215. this.tech_.trigger({
  27216. type: 'usage',
  27217. name: `vhs-${type}-download-exclusion`
  27218. });
  27219. if (type === 'subtitle') {
  27220. return;
  27221. } // TODO: should we exclude audio tracks rather than main tracks
  27222. // when type is audio?
  27223. pc.excludePlaylist({
  27224. error: {
  27225. message: `Excessive ${type} segment downloading detected.`
  27226. },
  27227. playlistExclusionDuration: Infinity
  27228. });
  27229. }
  27230. /**
  27231. * The purpose of this function is to emulate the "waiting" event on
  27232. * browsers that do not emit it when they are waiting for more
  27233. * data to continue playback
  27234. *
  27235. * @private
  27236. */
  27237. checkCurrentTime_() {
  27238. if (this.tech_.paused() || this.tech_.seeking()) {
  27239. return;
  27240. }
  27241. const currentTime = this.tech_.currentTime();
  27242. const buffered = this.tech_.buffered();
  27243. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  27244. // If current time is at the end of the final buffered region, then any playback
  27245. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  27246. // should fire a `waiting` event in this scenario, but due to browser and tech
  27247. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  27248. // responding to a native `waiting` event when the tech fails to emit one.
  27249. return this.techWaiting_();
  27250. }
  27251. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  27252. this.consecutiveUpdates++;
  27253. this.waiting_();
  27254. } else if (currentTime === this.lastRecordedTime) {
  27255. this.consecutiveUpdates++;
  27256. } else {
  27257. this.consecutiveUpdates = 0;
  27258. this.lastRecordedTime = currentTime;
  27259. }
  27260. }
  27261. /**
  27262. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  27263. *
  27264. * @private
  27265. */
  27266. resetTimeUpdate_() {
  27267. this.consecutiveUpdates = 0;
  27268. }
  27269. /**
  27270. * Fixes situations where there's a bad seek
  27271. *
  27272. * @return {boolean} whether an action was taken to fix the seek
  27273. * @private
  27274. */
  27275. fixesBadSeeks_() {
  27276. const seeking = this.tech_.seeking();
  27277. if (!seeking) {
  27278. return false;
  27279. } // TODO: It's possible that these seekable checks should be moved out of this function
  27280. // and into a function that runs on seekablechange. It's also possible that we only need
  27281. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  27282. // seekable range.
  27283. const seekable = this.seekable();
  27284. const currentTime = this.tech_.currentTime();
  27285. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  27286. let seekTo;
  27287. if (isAfterSeekableRange) {
  27288. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  27289. seekTo = seekableEnd;
  27290. }
  27291. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  27292. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  27293. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  27294. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  27295. // happen in live with a 3 segment playlist), then don't use a time delta
  27296. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  27297. }
  27298. if (typeof seekTo !== 'undefined') {
  27299. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  27300. this.tech_.setCurrentTime(seekTo);
  27301. return true;
  27302. }
  27303. const sourceUpdater = this.playlistController_.sourceUpdater_;
  27304. const buffered = this.tech_.buffered();
  27305. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  27306. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  27307. const media = this.media(); // verify that at least two segment durations or one part duration have been
  27308. // appended before checking for a gap.
  27309. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  27310. // appended before checking for a gap.
  27311. const bufferedToCheck = [audioBuffered, videoBuffered];
  27312. for (let i = 0; i < bufferedToCheck.length; i++) {
  27313. // skip null buffered
  27314. if (!bufferedToCheck[i]) {
  27315. continue;
  27316. }
  27317. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  27318. // duration behind we haven't appended enough to call this a bad seek.
  27319. if (timeAhead < minAppendedDuration) {
  27320. return false;
  27321. }
  27322. }
  27323. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  27324. // to seek over the gap
  27325. if (nextRange.length === 0) {
  27326. return false;
  27327. }
  27328. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  27329. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  27330. this.tech_.setCurrentTime(seekTo);
  27331. return true;
  27332. }
  27333. /**
  27334. * Handler for situations when we determine the player is waiting.
  27335. *
  27336. * @private
  27337. */
  27338. waiting_() {
  27339. if (this.techWaiting_()) {
  27340. return;
  27341. } // All tech waiting checks failed. Use last resort correction
  27342. const currentTime = this.tech_.currentTime();
  27343. const buffered = this.tech_.buffered();
  27344. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  27345. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  27346. // currentTime is usually enough to kickstart the player. This checks that the player
  27347. // is currently within a buffered region before attempting a corrective seek.
  27348. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  27349. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  27350. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  27351. // to avoid triggering an `unknownwaiting` event when the network is slow.
  27352. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  27353. this.resetTimeUpdate_();
  27354. this.tech_.setCurrentTime(currentTime);
  27355. 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
  27356. this.tech_.trigger({
  27357. type: 'usage',
  27358. name: 'vhs-unknown-waiting'
  27359. });
  27360. return;
  27361. }
  27362. }
  27363. /**
  27364. * Handler for situations when the tech fires a `waiting` event
  27365. *
  27366. * @return {boolean}
  27367. * True if an action (or none) was needed to correct the waiting. False if no
  27368. * checks passed
  27369. * @private
  27370. */
  27371. techWaiting_() {
  27372. const seekable = this.seekable();
  27373. const currentTime = this.tech_.currentTime();
  27374. if (this.tech_.seeking()) {
  27375. // Tech is seeking or already waiting on another action, no action needed
  27376. return true;
  27377. }
  27378. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  27379. const livePoint = seekable.end(seekable.length - 1);
  27380. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  27381. this.resetTimeUpdate_();
  27382. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  27383. this.tech_.trigger({
  27384. type: 'usage',
  27385. name: 'vhs-live-resync'
  27386. });
  27387. return true;
  27388. }
  27389. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  27390. const buffered = this.tech_.buffered();
  27391. const videoUnderflow = this.videoUnderflow_({
  27392. audioBuffered: sourceUpdater.audioBuffered(),
  27393. videoBuffered: sourceUpdater.videoBuffered(),
  27394. currentTime
  27395. });
  27396. if (videoUnderflow) {
  27397. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  27398. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  27399. // allows the video to catch up to the audio position without losing any audio
  27400. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  27401. this.resetTimeUpdate_();
  27402. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  27403. this.tech_.trigger({
  27404. type: 'usage',
  27405. name: 'vhs-video-underflow'
  27406. });
  27407. return true;
  27408. }
  27409. const nextRange = findNextRange(buffered, currentTime); // check for gap
  27410. if (nextRange.length > 0) {
  27411. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  27412. this.resetTimeUpdate_();
  27413. this.skipTheGap_(currentTime);
  27414. return true;
  27415. } // All checks failed. Returning false to indicate failure to correct waiting
  27416. return false;
  27417. }
  27418. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  27419. if (!seekable.length) {
  27420. // we can't make a solid case if there's no seekable, default to false
  27421. return false;
  27422. }
  27423. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  27424. const isLive = !playlist.endList;
  27425. const isLLHLS = typeof playlist.partTargetDuration === 'number';
  27426. if (isLive && (isLLHLS || allowSeeksWithinUnsafeLiveWindow)) {
  27427. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  27428. }
  27429. if (currentTime > allowedEnd) {
  27430. return true;
  27431. }
  27432. return false;
  27433. }
  27434. beforeSeekableWindow_(seekable, currentTime) {
  27435. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  27436. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  27437. return true;
  27438. }
  27439. return false;
  27440. }
  27441. videoUnderflow_({
  27442. videoBuffered,
  27443. audioBuffered,
  27444. currentTime
  27445. }) {
  27446. // audio only content will not have video underflow :)
  27447. if (!videoBuffered) {
  27448. return;
  27449. }
  27450. let gap; // find a gap in demuxed content.
  27451. if (videoBuffered.length && audioBuffered.length) {
  27452. // in Chrome audio will continue to play for ~3s when we run out of video
  27453. // so we have to check that the video buffer did have some buffer in the
  27454. // past.
  27455. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  27456. const videoRange = findRange(videoBuffered, currentTime);
  27457. const audioRange = findRange(audioBuffered, currentTime);
  27458. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  27459. gap = {
  27460. start: lastVideoRange.end(0),
  27461. end: audioRange.end(0)
  27462. };
  27463. } // find a gap in muxed content.
  27464. } else {
  27465. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  27466. // stuck in a gap due to video underflow.
  27467. if (!nextRange.length) {
  27468. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  27469. }
  27470. }
  27471. if (gap) {
  27472. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  27473. return true;
  27474. }
  27475. return false;
  27476. }
  27477. /**
  27478. * Timer callback. If playback still has not proceeded, then we seek
  27479. * to the start of the next buffered region.
  27480. *
  27481. * @private
  27482. */
  27483. skipTheGap_(scheduledCurrentTime) {
  27484. const buffered = this.tech_.buffered();
  27485. const currentTime = this.tech_.currentTime();
  27486. const nextRange = findNextRange(buffered, currentTime);
  27487. this.resetTimeUpdate_();
  27488. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  27489. return;
  27490. }
  27491. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  27492. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  27493. this.tech_.trigger({
  27494. type: 'usage',
  27495. name: 'vhs-gap-skip'
  27496. });
  27497. }
  27498. gapFromVideoUnderflow_(buffered, currentTime) {
  27499. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  27500. // playing for ~3 seconds after the video gap starts. This is done to account for
  27501. // video buffer underflow/underrun (note that this is not done when there is audio
  27502. // buffer underflow/underrun -- in that case the video will stop as soon as it
  27503. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  27504. // video stalls). The player's time will reflect the playthrough of audio, so the
  27505. // time will appear as if we are in a buffered region, even if we are stuck in a
  27506. // "gap."
  27507. //
  27508. // Example:
  27509. // video buffer: 0 => 10.1, 10.2 => 20
  27510. // audio buffer: 0 => 20
  27511. // overall buffer: 0 => 10.1, 10.2 => 20
  27512. // current time: 13
  27513. //
  27514. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  27515. // however, the audio continued playing until it reached ~3 seconds past the gap
  27516. // (13 seconds), at which point it stops as well. Since current time is past the
  27517. // gap, findNextRange will return no ranges.
  27518. //
  27519. // To check for this issue, we see if there is a gap that starts somewhere within
  27520. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  27521. const gaps = findGaps(buffered);
  27522. for (let i = 0; i < gaps.length; i++) {
  27523. const start = gaps.start(i);
  27524. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  27525. if (currentTime - start < 4 && currentTime - start > 2) {
  27526. return {
  27527. start,
  27528. end
  27529. };
  27530. }
  27531. }
  27532. return null;
  27533. }
  27534. }
  27535. const defaultOptions = {
  27536. errorInterval: 30,
  27537. getSource(next) {
  27538. const tech = this.tech({
  27539. IWillNotUseThisInPlugins: true
  27540. });
  27541. const sourceObj = tech.currentSource_ || this.currentSource();
  27542. return next(sourceObj);
  27543. }
  27544. };
  27545. /**
  27546. * Main entry point for the plugin
  27547. *
  27548. * @param {Player} player a reference to a videojs Player instance
  27549. * @param {Object} [options] an object with plugin options
  27550. * @private
  27551. */
  27552. const initPlugin = function (player, options) {
  27553. let lastCalled = 0;
  27554. let seekTo = 0;
  27555. const localOptions = merge$1(defaultOptions, options);
  27556. player.ready(() => {
  27557. player.trigger({
  27558. type: 'usage',
  27559. name: 'vhs-error-reload-initialized'
  27560. });
  27561. });
  27562. /**
  27563. * Player modifications to perform that must wait until `loadedmetadata`
  27564. * has been triggered
  27565. *
  27566. * @private
  27567. */
  27568. const loadedMetadataHandler = function () {
  27569. if (seekTo) {
  27570. player.currentTime(seekTo);
  27571. }
  27572. };
  27573. /**
  27574. * Set the source on the player element, play, and seek if necessary
  27575. *
  27576. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  27577. * @private
  27578. */
  27579. const setSource = function (sourceObj) {
  27580. if (sourceObj === null || sourceObj === undefined) {
  27581. return;
  27582. }
  27583. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  27584. player.one('loadedmetadata', loadedMetadataHandler);
  27585. player.src(sourceObj);
  27586. player.trigger({
  27587. type: 'usage',
  27588. name: 'vhs-error-reload'
  27589. });
  27590. player.play();
  27591. };
  27592. /**
  27593. * Attempt to get a source from either the built-in getSource function
  27594. * or a custom function provided via the options
  27595. *
  27596. * @private
  27597. */
  27598. const errorHandler = function () {
  27599. // Do not attempt to reload the source if a source-reload occurred before
  27600. // 'errorInterval' time has elapsed since the last source-reload
  27601. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  27602. player.trigger({
  27603. type: 'usage',
  27604. name: 'vhs-error-reload-canceled'
  27605. });
  27606. return;
  27607. }
  27608. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  27609. videojs__default["default"].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  27610. return;
  27611. }
  27612. lastCalled = Date.now();
  27613. return localOptions.getSource.call(player, setSource);
  27614. };
  27615. /**
  27616. * Unbind any event handlers that were bound by the plugin
  27617. *
  27618. * @private
  27619. */
  27620. const cleanupEvents = function () {
  27621. player.off('loadedmetadata', loadedMetadataHandler);
  27622. player.off('error', errorHandler);
  27623. player.off('dispose', cleanupEvents);
  27624. };
  27625. /**
  27626. * Cleanup before re-initializing the plugin
  27627. *
  27628. * @param {Object} [newOptions] an object with plugin options
  27629. * @private
  27630. */
  27631. const reinitPlugin = function (newOptions) {
  27632. cleanupEvents();
  27633. initPlugin(player, newOptions);
  27634. };
  27635. player.on('error', errorHandler);
  27636. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  27637. // initializing the plugin
  27638. player.reloadSourceOnError = reinitPlugin;
  27639. };
  27640. /**
  27641. * Reload the source when an error is detected as long as there
  27642. * wasn't an error previously within the last 30 seconds
  27643. *
  27644. * @param {Object} [options] an object with plugin options
  27645. */
  27646. const reloadSourceOnError = function (options) {
  27647. initPlugin(this, options);
  27648. };
  27649. var version$4 = "3.10.0";
  27650. var version$3 = "7.0.2";
  27651. var version$2 = "1.3.0";
  27652. var version$1 = "7.1.0";
  27653. var version = "4.0.1";
  27654. /**
  27655. * @file videojs-http-streaming.js
  27656. *
  27657. * The main file for the VHS project.
  27658. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  27659. */
  27660. const Vhs = {
  27661. PlaylistLoader,
  27662. Playlist,
  27663. utils,
  27664. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  27665. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  27666. lastBandwidthSelector,
  27667. movingAverageBandwidthSelector,
  27668. comparePlaylistBandwidth,
  27669. comparePlaylistResolution,
  27670. xhr: xhrFactory()
  27671. }; // Define getter/setters for config properties
  27672. Object.keys(Config).forEach(prop => {
  27673. Object.defineProperty(Vhs, prop, {
  27674. get() {
  27675. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  27676. return Config[prop];
  27677. },
  27678. set(value) {
  27679. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  27680. if (typeof value !== 'number' || value < 0) {
  27681. videojs__default["default"].log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  27682. return;
  27683. }
  27684. Config[prop] = value;
  27685. }
  27686. });
  27687. });
  27688. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  27689. /**
  27690. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  27691. *
  27692. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  27693. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  27694. * @function handleVhsMediaChange
  27695. */
  27696. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  27697. const newPlaylist = playlistLoader.media();
  27698. let selectedIndex = -1;
  27699. for (let i = 0; i < qualityLevels.length; i++) {
  27700. if (qualityLevels[i].id === newPlaylist.id) {
  27701. selectedIndex = i;
  27702. break;
  27703. }
  27704. }
  27705. qualityLevels.selectedIndex_ = selectedIndex;
  27706. qualityLevels.trigger({
  27707. selectedIndex,
  27708. type: 'change'
  27709. });
  27710. };
  27711. /**
  27712. * Adds quality levels to list once playlist metadata is available
  27713. *
  27714. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  27715. * @param {Object} vhs Vhs object to listen to for media events.
  27716. * @function handleVhsLoadedMetadata
  27717. */
  27718. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  27719. vhs.representations().forEach(rep => {
  27720. qualityLevels.addQualityLevel(rep);
  27721. });
  27722. handleVhsMediaChange(qualityLevels, vhs.playlists);
  27723. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  27724. // as one do not cause exceptions.
  27725. Vhs.canPlaySource = function () {
  27726. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  27727. };
  27728. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  27729. if (!keySystemOptions) {
  27730. return keySystemOptions;
  27731. }
  27732. let codecs = {};
  27733. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  27734. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  27735. }
  27736. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  27737. codecs.audio = audioPlaylist.attributes.CODECS;
  27738. }
  27739. const videoContentType = getMimeForCodec(codecs.video);
  27740. const audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  27741. const keySystemContentTypes = {};
  27742. for (const keySystem in keySystemOptions) {
  27743. keySystemContentTypes[keySystem] = {};
  27744. if (audioContentType) {
  27745. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  27746. }
  27747. if (videoContentType) {
  27748. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  27749. } // Default to using the video playlist's PSSH even though they may be different, as
  27750. // videojs-contrib-eme will only accept one in the options.
  27751. //
  27752. // This shouldn't be an issue for most cases as early intialization will handle all
  27753. // unique PSSH values, and if they aren't, then encrypted events should have the
  27754. // specific information needed for the unique license.
  27755. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  27756. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  27757. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  27758. // so we need to prevent overwriting the URL entirely
  27759. if (typeof keySystemOptions[keySystem] === 'string') {
  27760. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  27761. }
  27762. }
  27763. return merge$1(keySystemOptions, keySystemContentTypes);
  27764. };
  27765. /**
  27766. * @typedef {Object} KeySystems
  27767. *
  27768. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  27769. * Note: not all options are listed here.
  27770. *
  27771. * @property {Uint8Array} [pssh]
  27772. * Protection System Specific Header
  27773. */
  27774. /**
  27775. * Goes through all the playlists and collects an array of KeySystems options objects
  27776. * containing each playlist's keySystems and their pssh values, if available.
  27777. *
  27778. * @param {Object[]} playlists
  27779. * The playlists to look through
  27780. * @param {string[]} keySystems
  27781. * The keySystems to collect pssh values for
  27782. *
  27783. * @return {KeySystems[]}
  27784. * An array of KeySystems objects containing available key systems and their
  27785. * pssh values
  27786. */
  27787. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  27788. return playlists.reduce((keySystemsArr, playlist) => {
  27789. if (!playlist.contentProtection) {
  27790. return keySystemsArr;
  27791. }
  27792. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  27793. const keySystemOptions = playlist.contentProtection[keySystem];
  27794. if (keySystemOptions && keySystemOptions.pssh) {
  27795. keySystemsObj[keySystem] = {
  27796. pssh: keySystemOptions.pssh
  27797. };
  27798. }
  27799. return keySystemsObj;
  27800. }, {});
  27801. if (Object.keys(keySystemsOptions).length) {
  27802. keySystemsArr.push(keySystemsOptions);
  27803. }
  27804. return keySystemsArr;
  27805. }, []);
  27806. };
  27807. /**
  27808. * Returns a promise that waits for the
  27809. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  27810. *
  27811. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  27812. * browsers.
  27813. *
  27814. * As per the above ticket, this is particularly important for Chrome, where, if
  27815. * unencrypted content is appended before encrypted content and the key session has not
  27816. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  27817. * during playback.
  27818. *
  27819. * @param {Object} player
  27820. * The player instance
  27821. * @param {Object[]} sourceKeySystems
  27822. * The key systems options from the player source
  27823. * @param {Object} [audioMedia]
  27824. * The active audio media playlist (optional)
  27825. * @param {Object[]} mainPlaylists
  27826. * The playlists found on the main playlist object
  27827. *
  27828. * @return {Object}
  27829. * Promise that resolves when the key session has been created
  27830. */
  27831. const waitForKeySessionCreation = ({
  27832. player,
  27833. sourceKeySystems,
  27834. audioMedia,
  27835. mainPlaylists
  27836. }) => {
  27837. if (!player.eme.initializeMediaKeys) {
  27838. return Promise.resolve();
  27839. } // TODO should all audio PSSH values be initialized for DRM?
  27840. //
  27841. // All unique video rendition pssh values are initialized for DRM, but here only
  27842. // the initial audio playlist license is initialized. In theory, an encrypted
  27843. // event should be fired if the user switches to an alternative audio playlist
  27844. // where a license is required, but this case hasn't yet been tested. In addition, there
  27845. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  27846. // languages).
  27847. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  27848. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  27849. const initializationFinishedPromises = [];
  27850. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  27851. // only place where it should not be deduped is for ms-prefixed APIs, but
  27852. // the existence of modern EME APIs in addition to
  27853. // ms-prefixed APIs on Edge should prevent this from being a concern.
  27854. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  27855. keySystemsOptionsArr.forEach(keySystemsOptions => {
  27856. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  27857. player.tech_.one('keysessioncreated', resolve);
  27858. }));
  27859. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  27860. player.eme.initializeMediaKeys({
  27861. keySystems: keySystemsOptions
  27862. }, err => {
  27863. if (err) {
  27864. reject(err);
  27865. return;
  27866. }
  27867. resolve();
  27868. });
  27869. }));
  27870. }); // The reasons Promise.race is chosen over Promise.any:
  27871. //
  27872. // * Promise.any is only available in Safari 14+.
  27873. // * None of these promises are expected to reject. If they do reject, it might be
  27874. // better here for the race to surface the rejection, rather than mask it by using
  27875. // Promise.any.
  27876. return Promise.race([// If a session was previously created, these will all finish resolving without
  27877. // creating a new session, otherwise it will take until the end of all license
  27878. // requests, which is why the key session check is used (to make setup much faster).
  27879. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  27880. Promise.race(keySessionCreatedPromises)]);
  27881. };
  27882. /**
  27883. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  27884. * there are keySystems on the source, sets up source options to prepare the source for
  27885. * eme.
  27886. *
  27887. * @param {Object} player
  27888. * The player instance
  27889. * @param {Object[]} sourceKeySystems
  27890. * The key systems options from the player source
  27891. * @param {Object} media
  27892. * The active media playlist
  27893. * @param {Object} [audioMedia]
  27894. * The active audio media playlist (optional)
  27895. *
  27896. * @return {boolean}
  27897. * Whether or not options were configured and EME is available
  27898. */
  27899. const setupEmeOptions = ({
  27900. player,
  27901. sourceKeySystems,
  27902. media,
  27903. audioMedia
  27904. }) => {
  27905. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  27906. if (!sourceOptions) {
  27907. return false;
  27908. }
  27909. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  27910. // do nothing.
  27911. if (sourceOptions && !player.eme) {
  27912. videojs__default["default"].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  27913. return false;
  27914. }
  27915. return true;
  27916. };
  27917. const getVhsLocalStorage = () => {
  27918. if (!window.localStorage) {
  27919. return null;
  27920. }
  27921. const storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  27922. if (!storedObject) {
  27923. return null;
  27924. }
  27925. try {
  27926. return JSON.parse(storedObject);
  27927. } catch (e) {
  27928. // someone may have tampered with the value
  27929. return null;
  27930. }
  27931. };
  27932. const updateVhsLocalStorage = options => {
  27933. if (!window.localStorage) {
  27934. return false;
  27935. }
  27936. let objectToStore = getVhsLocalStorage();
  27937. objectToStore = objectToStore ? merge$1(objectToStore, options) : options;
  27938. try {
  27939. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  27940. } catch (e) {
  27941. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  27942. // storage is set to 0).
  27943. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  27944. // No need to perform any operation.
  27945. return false;
  27946. }
  27947. return objectToStore;
  27948. };
  27949. /**
  27950. * Parses VHS-supported media types from data URIs. See
  27951. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  27952. * for information on data URIs.
  27953. *
  27954. * @param {string} dataUri
  27955. * The data URI
  27956. *
  27957. * @return {string|Object}
  27958. * The parsed object/string, or the original string if no supported media type
  27959. * was found
  27960. */
  27961. const expandDataUri = dataUri => {
  27962. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  27963. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  27964. } // no known case for this data URI, return the string as-is
  27965. return dataUri;
  27966. };
  27967. /**
  27968. * Adds a request hook to an xhr object
  27969. *
  27970. * @param {Object} xhr object to add the onRequest hook to
  27971. * @param {function} callback hook function for an xhr request
  27972. */
  27973. const addOnRequestHook = (xhr, callback) => {
  27974. if (!xhr._requestCallbackSet) {
  27975. xhr._requestCallbackSet = new Set();
  27976. }
  27977. xhr._requestCallbackSet.add(callback);
  27978. };
  27979. /**
  27980. * Adds a response hook to an xhr object
  27981. *
  27982. * @param {Object} xhr object to add the onResponse hook to
  27983. * @param {function} callback hook function for an xhr response
  27984. */
  27985. const addOnResponseHook = (xhr, callback) => {
  27986. if (!xhr._responseCallbackSet) {
  27987. xhr._responseCallbackSet = new Set();
  27988. }
  27989. xhr._responseCallbackSet.add(callback);
  27990. };
  27991. /**
  27992. * Removes a request hook on an xhr object, deletes the onRequest set if empty.
  27993. *
  27994. * @param {Object} xhr object to remove the onRequest hook from
  27995. * @param {function} callback hook function to remove
  27996. */
  27997. const removeOnRequestHook = (xhr, callback) => {
  27998. if (!xhr._requestCallbackSet) {
  27999. return;
  28000. }
  28001. xhr._requestCallbackSet.delete(callback);
  28002. if (!xhr._requestCallbackSet.size) {
  28003. delete xhr._requestCallbackSet;
  28004. }
  28005. };
  28006. /**
  28007. * Removes a response hook on an xhr object, deletes the onResponse set if empty.
  28008. *
  28009. * @param {Object} xhr object to remove the onResponse hook from
  28010. * @param {function} callback hook function to remove
  28011. */
  28012. const removeOnResponseHook = (xhr, callback) => {
  28013. if (!xhr._responseCallbackSet) {
  28014. return;
  28015. }
  28016. xhr._responseCallbackSet.delete(callback);
  28017. if (!xhr._responseCallbackSet.size) {
  28018. delete xhr._responseCallbackSet;
  28019. }
  28020. };
  28021. /**
  28022. * Whether the browser has built-in HLS support.
  28023. */
  28024. Vhs.supportsNativeHls = function () {
  28025. if (!document || !document.createElement) {
  28026. return false;
  28027. }
  28028. const video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  28029. if (!videojs__default["default"].getTech('Html5').isSupported()) {
  28030. return false;
  28031. } // HLS manifests can go by many mime-types
  28032. const canPlay = [// Apple santioned
  28033. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  28034. 'audio/mpegurl', // Very common
  28035. 'audio/x-mpegurl', // Very common
  28036. 'application/x-mpegurl', // Included for completeness
  28037. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  28038. return canPlay.some(function (canItPlay) {
  28039. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  28040. });
  28041. }();
  28042. Vhs.supportsNativeDash = function () {
  28043. if (!document || !document.createElement || !videojs__default["default"].getTech('Html5').isSupported()) {
  28044. return false;
  28045. }
  28046. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  28047. }();
  28048. Vhs.supportsTypeNatively = type => {
  28049. if (type === 'hls') {
  28050. return Vhs.supportsNativeHls;
  28051. }
  28052. if (type === 'dash') {
  28053. return Vhs.supportsNativeDash;
  28054. }
  28055. return false;
  28056. };
  28057. /**
  28058. * VHS is a source handler, not a tech. Make sure attempts to use it
  28059. * as one do not cause exceptions.
  28060. */
  28061. Vhs.isSupported = function () {
  28062. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  28063. };
  28064. /**
  28065. * A global function for setting an onRequest hook
  28066. *
  28067. * @param {function} callback for request modifiction
  28068. */
  28069. Vhs.xhr.onRequest = function (callback) {
  28070. addOnRequestHook(Vhs.xhr, callback);
  28071. };
  28072. /**
  28073. * A global function for setting an onResponse hook
  28074. *
  28075. * @param {callback} callback for response data retrieval
  28076. */
  28077. Vhs.xhr.onResponse = function (callback) {
  28078. addOnResponseHook(Vhs.xhr, callback);
  28079. };
  28080. /**
  28081. * Deletes a global onRequest callback if it exists
  28082. *
  28083. * @param {function} callback to delete from the global set
  28084. */
  28085. Vhs.xhr.offRequest = function (callback) {
  28086. removeOnRequestHook(Vhs.xhr, callback);
  28087. };
  28088. /**
  28089. * Deletes a global onResponse callback if it exists
  28090. *
  28091. * @param {function} callback to delete from the global set
  28092. */
  28093. Vhs.xhr.offResponse = function (callback) {
  28094. removeOnResponseHook(Vhs.xhr, callback);
  28095. };
  28096. const Component = videojs__default["default"].getComponent('Component');
  28097. /**
  28098. * The Vhs Handler object, where we orchestrate all of the parts
  28099. * of VHS to interact with video.js
  28100. *
  28101. * @class VhsHandler
  28102. * @extends videojs.Component
  28103. * @param {Object} source the soruce object
  28104. * @param {Tech} tech the parent tech object
  28105. * @param {Object} options optional and required options
  28106. */
  28107. class VhsHandler extends Component {
  28108. constructor(source, tech, options) {
  28109. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  28110. // use that over the VHS level `bandwidth` option
  28111. if (typeof options.initialBandwidth === 'number') {
  28112. this.options_.bandwidth = options.initialBandwidth;
  28113. }
  28114. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  28115. // so, get it from Video.js via the `playerId`
  28116. if (tech.options_ && tech.options_.playerId) {
  28117. const _player = videojs__default["default"].getPlayer(tech.options_.playerId);
  28118. this.player_ = _player;
  28119. }
  28120. this.tech_ = tech;
  28121. this.source_ = source;
  28122. this.stats = {};
  28123. this.ignoreNextSeekingEvent_ = false;
  28124. this.setOptions_();
  28125. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  28126. tech.overrideNativeAudioTracks(true);
  28127. tech.overrideNativeVideoTracks(true);
  28128. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  28129. // overriding native VHS only works if audio tracks have been emulated
  28130. // error early if we're misconfigured
  28131. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  28132. } // listen for fullscreenchange events for this player so that we
  28133. // can adjust our quality selection quickly
  28134. this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  28135. const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  28136. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  28137. this.playlistController_.fastQualityChange_();
  28138. } else {
  28139. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  28140. // than full screen, see if there should be a rendition switch down to preserve
  28141. // bandwidth.
  28142. this.playlistController_.checkABR_();
  28143. }
  28144. });
  28145. this.on(this.tech_, 'seeking', function () {
  28146. if (this.ignoreNextSeekingEvent_) {
  28147. this.ignoreNextSeekingEvent_ = false;
  28148. return;
  28149. }
  28150. this.setCurrentTime(this.tech_.currentTime());
  28151. });
  28152. this.on(this.tech_, 'error', function () {
  28153. // verify that the error was real and we are loaded
  28154. // enough to have pc loaded.
  28155. if (this.tech_.error() && this.playlistController_) {
  28156. this.playlistController_.pauseLoading();
  28157. }
  28158. });
  28159. this.on(this.tech_, 'play', this.play);
  28160. }
  28161. /**
  28162. * Set VHS options based on options from configuration, as well as partial
  28163. * options to be passed at a later time.
  28164. *
  28165. * @param {Object} options A partial chunk of config options
  28166. */
  28167. setOptions_(options = {}) {
  28168. this.options_ = merge$1(this.options_, options); // defaults
  28169. this.options_.withCredentials = this.options_.withCredentials || false;
  28170. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  28171. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  28172. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  28173. this.options_.useForcedSubtitles = this.options_.useForcedSubtitles || false;
  28174. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  28175. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  28176. this.options_.customTagParsers = this.options_.customTagParsers || [];
  28177. this.options_.customTagMappers = this.options_.customTagMappers || [];
  28178. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  28179. this.options_.llhls = this.options_.llhls === false ? false : true;
  28180. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  28181. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  28182. this.options_.playlistExclusionDuration = 60;
  28183. }
  28184. if (typeof this.options_.bandwidth !== 'number') {
  28185. if (this.options_.useBandwidthFromLocalStorage) {
  28186. const storedObject = getVhsLocalStorage();
  28187. if (storedObject && storedObject.bandwidth) {
  28188. this.options_.bandwidth = storedObject.bandwidth;
  28189. this.tech_.trigger({
  28190. type: 'usage',
  28191. name: 'vhs-bandwidth-from-local-storage'
  28192. });
  28193. }
  28194. if (storedObject && storedObject.throughput) {
  28195. this.options_.throughput = storedObject.throughput;
  28196. this.tech_.trigger({
  28197. type: 'usage',
  28198. name: 'vhs-throughput-from-local-storage'
  28199. });
  28200. }
  28201. }
  28202. } // if bandwidth was not set by options or pulled from local storage, start playlist
  28203. // selection at a reasonable bandwidth
  28204. if (typeof this.options_.bandwidth !== 'number') {
  28205. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  28206. } // If the bandwidth number is unchanged from the initial setting
  28207. // then this takes precedence over the enableLowInitialPlaylist option
  28208. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  28209. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useForcedSubtitles', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  28210. if (typeof this.source_[option] !== 'undefined') {
  28211. this.options_[option] = this.source_[option];
  28212. }
  28213. });
  28214. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  28215. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  28216. } // alias for public method to set options
  28217. setOptions(options = {}) {
  28218. this.setOptions_(options);
  28219. }
  28220. /**
  28221. * called when player.src gets called, handle a new source
  28222. *
  28223. * @param {Object} src the source object to handle
  28224. */
  28225. src(src, type) {
  28226. // do nothing if the src is falsey
  28227. if (!src) {
  28228. return;
  28229. }
  28230. this.setOptions_(); // add main playlist controller options
  28231. this.options_.src = expandDataUri(this.source_.src);
  28232. this.options_.tech = this.tech_;
  28233. this.options_.externVhs = Vhs;
  28234. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  28235. this.options_.seekTo = time => {
  28236. this.tech_.setCurrentTime(time);
  28237. };
  28238. this.playlistController_ = new PlaylistController(this.options_);
  28239. const playbackWatcherOptions = merge$1({
  28240. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  28241. }, this.options_, {
  28242. seekable: () => this.seekable(),
  28243. media: () => this.playlistController_.media(),
  28244. playlistController: this.playlistController_
  28245. });
  28246. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  28247. this.playlistController_.on('error', () => {
  28248. const player = videojs__default["default"].players[this.tech_.options_.playerId];
  28249. let error = this.playlistController_.error;
  28250. if (typeof error === 'object' && !error.code) {
  28251. error.code = 3;
  28252. } else if (typeof error === 'string') {
  28253. error = {
  28254. message: error,
  28255. code: 3
  28256. };
  28257. }
  28258. player.error(error);
  28259. });
  28260. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  28261. // compatibility with < v2
  28262. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  28263. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  28264. this.playlists = this.playlistController_.mainPlaylistLoader_;
  28265. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  28266. // controller. Using a custom property for backwards compatibility
  28267. // with < v2
  28268. Object.defineProperties(this, {
  28269. selectPlaylist: {
  28270. get() {
  28271. return this.playlistController_.selectPlaylist;
  28272. },
  28273. set(selectPlaylist) {
  28274. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  28275. }
  28276. },
  28277. throughput: {
  28278. get() {
  28279. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  28280. },
  28281. set(throughput) {
  28282. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  28283. // for the cumulative average
  28284. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  28285. }
  28286. },
  28287. bandwidth: {
  28288. get() {
  28289. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  28290. const networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  28291. const tenMbpsAsBitsPerSecond = 10e6;
  28292. if (this.options_.useNetworkInformationApi && networkInformation) {
  28293. // downlink returns Mbps
  28294. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  28295. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  28296. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  28297. // high quality streams are not filtered out.
  28298. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  28299. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  28300. } else {
  28301. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  28302. }
  28303. }
  28304. return playerBandwidthEst;
  28305. },
  28306. set(bandwidth) {
  28307. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  28308. // `count` is set to zero that current value of `rate` isn't included
  28309. // in the cumulative average
  28310. this.playlistController_.mainSegmentLoader_.throughput = {
  28311. rate: 0,
  28312. count: 0
  28313. };
  28314. }
  28315. },
  28316. /**
  28317. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  28318. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  28319. * the entire process after that - decryption, transmuxing, and appending - provided
  28320. * by `throughput`.
  28321. *
  28322. * Since the two process are serial, the overall system bandwidth is given by:
  28323. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  28324. */
  28325. systemBandwidth: {
  28326. get() {
  28327. const invBandwidth = 1 / (this.bandwidth || 1);
  28328. let invThroughput;
  28329. if (this.throughput > 0) {
  28330. invThroughput = 1 / this.throughput;
  28331. } else {
  28332. invThroughput = 0;
  28333. }
  28334. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  28335. return systemBitrate;
  28336. },
  28337. set() {
  28338. videojs__default["default"].log.error('The "systemBandwidth" property is read-only');
  28339. }
  28340. }
  28341. });
  28342. if (this.options_.bandwidth) {
  28343. this.bandwidth = this.options_.bandwidth;
  28344. }
  28345. if (this.options_.throughput) {
  28346. this.throughput = this.options_.throughput;
  28347. }
  28348. Object.defineProperties(this.stats, {
  28349. bandwidth: {
  28350. get: () => this.bandwidth || 0,
  28351. enumerable: true
  28352. },
  28353. mediaRequests: {
  28354. get: () => this.playlistController_.mediaRequests_() || 0,
  28355. enumerable: true
  28356. },
  28357. mediaRequestsAborted: {
  28358. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  28359. enumerable: true
  28360. },
  28361. mediaRequestsTimedout: {
  28362. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  28363. enumerable: true
  28364. },
  28365. mediaRequestsErrored: {
  28366. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  28367. enumerable: true
  28368. },
  28369. mediaTransferDuration: {
  28370. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  28371. enumerable: true
  28372. },
  28373. mediaBytesTransferred: {
  28374. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  28375. enumerable: true
  28376. },
  28377. mediaSecondsLoaded: {
  28378. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  28379. enumerable: true
  28380. },
  28381. mediaAppends: {
  28382. get: () => this.playlistController_.mediaAppends_() || 0,
  28383. enumerable: true
  28384. },
  28385. mainAppendsToLoadedData: {
  28386. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  28387. enumerable: true
  28388. },
  28389. audioAppendsToLoadedData: {
  28390. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  28391. enumerable: true
  28392. },
  28393. appendsToLoadedData: {
  28394. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  28395. enumerable: true
  28396. },
  28397. timeToLoadedData: {
  28398. get: () => this.playlistController_.timeToLoadedData_() || 0,
  28399. enumerable: true
  28400. },
  28401. buffered: {
  28402. get: () => timeRangesToArray(this.tech_.buffered()),
  28403. enumerable: true
  28404. },
  28405. currentTime: {
  28406. get: () => this.tech_.currentTime(),
  28407. enumerable: true
  28408. },
  28409. currentSource: {
  28410. get: () => this.tech_.currentSource_,
  28411. enumerable: true
  28412. },
  28413. currentTech: {
  28414. get: () => this.tech_.name_,
  28415. enumerable: true
  28416. },
  28417. duration: {
  28418. get: () => this.tech_.duration(),
  28419. enumerable: true
  28420. },
  28421. main: {
  28422. get: () => this.playlists.main,
  28423. enumerable: true
  28424. },
  28425. playerDimensions: {
  28426. get: () => this.tech_.currentDimensions(),
  28427. enumerable: true
  28428. },
  28429. seekable: {
  28430. get: () => timeRangesToArray(this.tech_.seekable()),
  28431. enumerable: true
  28432. },
  28433. timestamp: {
  28434. get: () => Date.now(),
  28435. enumerable: true
  28436. },
  28437. videoPlaybackQuality: {
  28438. get: () => this.tech_.getVideoPlaybackQuality(),
  28439. enumerable: true
  28440. }
  28441. });
  28442. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  28443. this.tech_.on('bandwidthupdate', () => {
  28444. if (this.options_.useBandwidthFromLocalStorage) {
  28445. updateVhsLocalStorage({
  28446. bandwidth: this.bandwidth,
  28447. throughput: Math.round(this.throughput)
  28448. });
  28449. }
  28450. });
  28451. this.playlistController_.on('selectedinitialmedia', () => {
  28452. // Add the manual rendition mix-in to VhsHandler
  28453. renditionSelectionMixin(this);
  28454. });
  28455. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  28456. this.setupEme_();
  28457. }); // the bandwidth of the primary segment loader is our best
  28458. // estimate of overall bandwidth
  28459. this.on(this.playlistController_, 'progress', function () {
  28460. this.tech_.trigger('progress');
  28461. }); // In the live case, we need to ignore the very first `seeking` event since
  28462. // that will be the result of the seek-to-live behavior
  28463. this.on(this.playlistController_, 'firstplay', function () {
  28464. this.ignoreNextSeekingEvent_ = true;
  28465. });
  28466. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  28467. // this can occur if someone sets the src in player.ready(), for instance
  28468. if (!this.tech_.el()) {
  28469. return;
  28470. }
  28471. this.mediaSourceUrl_ = window.URL.createObjectURL(this.playlistController_.mediaSource);
  28472. this.tech_.src(this.mediaSourceUrl_);
  28473. }
  28474. createKeySessions_() {
  28475. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  28476. this.logger_('waiting for EME key session creation');
  28477. waitForKeySessionCreation({
  28478. player: this.player_,
  28479. sourceKeySystems: this.source_.keySystems,
  28480. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  28481. mainPlaylists: this.playlists.main.playlists
  28482. }).then(() => {
  28483. this.logger_('created EME key session');
  28484. this.playlistController_.sourceUpdater_.initializedEme();
  28485. }).catch(err => {
  28486. this.logger_('error while creating EME key session', err);
  28487. this.player_.error({
  28488. message: 'Failed to initialize media keys for EME',
  28489. code: 3
  28490. });
  28491. });
  28492. }
  28493. handleWaitingForKey_() {
  28494. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  28495. // the key is in the manifest. While this should've happened on initial source load, it
  28496. // may happen again in live streams where the keys change, and the manifest info
  28497. // reflects the update.
  28498. //
  28499. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  28500. // already requested keys for, we don't have to worry about this generating extraneous
  28501. // requests.
  28502. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  28503. this.createKeySessions_();
  28504. }
  28505. /**
  28506. * If necessary and EME is available, sets up EME options and waits for key session
  28507. * creation.
  28508. *
  28509. * This function also updates the source updater so taht it can be used, as for some
  28510. * browsers, EME must be configured before content is appended (if appending unencrypted
  28511. * content before encrypted content).
  28512. */
  28513. setupEme_() {
  28514. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  28515. const didSetupEmeOptions = setupEmeOptions({
  28516. player: this.player_,
  28517. sourceKeySystems: this.source_.keySystems,
  28518. media: this.playlists.media(),
  28519. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  28520. });
  28521. this.player_.tech_.on('keystatuschange', e => {
  28522. this.playlistController_.updatePlaylistByKeyStatus(e.keyId, e.status);
  28523. });
  28524. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  28525. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_);
  28526. if (!didSetupEmeOptions) {
  28527. // If EME options were not set up, we've done all we could to initialize EME.
  28528. this.playlistController_.sourceUpdater_.initializedEme();
  28529. return;
  28530. }
  28531. this.createKeySessions_();
  28532. }
  28533. /**
  28534. * Initializes the quality levels and sets listeners to update them.
  28535. *
  28536. * @method setupQualityLevels_
  28537. * @private
  28538. */
  28539. setupQualityLevels_() {
  28540. const player = videojs__default["default"].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  28541. // or qualityLevels_ listeners have already been setup, do nothing.
  28542. if (!player || !player.qualityLevels || this.qualityLevels_) {
  28543. return;
  28544. }
  28545. this.qualityLevels_ = player.qualityLevels();
  28546. this.playlistController_.on('selectedinitialmedia', () => {
  28547. handleVhsLoadedMetadata(this.qualityLevels_, this);
  28548. });
  28549. this.playlists.on('mediachange', () => {
  28550. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  28551. });
  28552. }
  28553. /**
  28554. * return the version
  28555. */
  28556. static version() {
  28557. return {
  28558. '@videojs/http-streaming': version$4,
  28559. 'mux.js': version$3,
  28560. 'mpd-parser': version$2,
  28561. 'm3u8-parser': version$1,
  28562. 'aes-decrypter': version
  28563. };
  28564. }
  28565. /**
  28566. * return the version
  28567. */
  28568. version() {
  28569. return this.constructor.version();
  28570. }
  28571. canChangeType() {
  28572. return SourceUpdater.canChangeType();
  28573. }
  28574. /**
  28575. * Begin playing the video.
  28576. */
  28577. play() {
  28578. this.playlistController_.play();
  28579. }
  28580. /**
  28581. * a wrapper around the function in PlaylistController
  28582. */
  28583. setCurrentTime(currentTime) {
  28584. this.playlistController_.setCurrentTime(currentTime);
  28585. }
  28586. /**
  28587. * a wrapper around the function in PlaylistController
  28588. */
  28589. duration() {
  28590. return this.playlistController_.duration();
  28591. }
  28592. /**
  28593. * a wrapper around the function in PlaylistController
  28594. */
  28595. seekable() {
  28596. return this.playlistController_.seekable();
  28597. }
  28598. /**
  28599. * Abort all outstanding work and cleanup.
  28600. */
  28601. dispose() {
  28602. if (this.playbackWatcher_) {
  28603. this.playbackWatcher_.dispose();
  28604. }
  28605. if (this.playlistController_) {
  28606. this.playlistController_.dispose();
  28607. }
  28608. if (this.qualityLevels_) {
  28609. this.qualityLevels_.dispose();
  28610. }
  28611. if (this.tech_ && this.tech_.vhs) {
  28612. delete this.tech_.vhs;
  28613. }
  28614. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  28615. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  28616. this.mediaSourceUrl_ = null;
  28617. }
  28618. if (this.tech_) {
  28619. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  28620. }
  28621. super.dispose();
  28622. }
  28623. convertToProgramTime(time, callback) {
  28624. return getProgramTime({
  28625. playlist: this.playlistController_.media(),
  28626. time,
  28627. callback
  28628. });
  28629. } // the player must be playing before calling this
  28630. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  28631. return seekToProgramTime({
  28632. programTime,
  28633. playlist: this.playlistController_.media(),
  28634. retryCount,
  28635. pauseAfterSeek,
  28636. seekTo: this.options_.seekTo,
  28637. tech: this.options_.tech,
  28638. callback
  28639. });
  28640. }
  28641. /**
  28642. * Adds the onRequest, onResponse, offRequest and offResponse functions
  28643. * to the VhsHandler xhr Object.
  28644. */
  28645. setupXhrHooks_() {
  28646. /**
  28647. * A player function for setting an onRequest hook
  28648. *
  28649. * @param {function} callback for request modifiction
  28650. */
  28651. this.xhr.onRequest = callback => {
  28652. addOnRequestHook(this.xhr, callback);
  28653. };
  28654. /**
  28655. * A player function for setting an onResponse hook
  28656. *
  28657. * @param {callback} callback for response data retrieval
  28658. */
  28659. this.xhr.onResponse = callback => {
  28660. addOnResponseHook(this.xhr, callback);
  28661. };
  28662. /**
  28663. * Deletes a player onRequest callback if it exists
  28664. *
  28665. * @param {function} callback to delete from the player set
  28666. */
  28667. this.xhr.offRequest = callback => {
  28668. removeOnRequestHook(this.xhr, callback);
  28669. };
  28670. /**
  28671. * Deletes a player onResponse callback if it exists
  28672. *
  28673. * @param {function} callback to delete from the player set
  28674. */
  28675. this.xhr.offResponse = callback => {
  28676. removeOnResponseHook(this.xhr, callback);
  28677. }; // Trigger an event on the player to notify the user that vhs is ready to set xhr hooks.
  28678. // This allows hooks to be set before the source is set to vhs when handleSource is called.
  28679. this.player_.trigger('xhr-hooks-ready');
  28680. }
  28681. }
  28682. /**
  28683. * The Source Handler object, which informs video.js what additional
  28684. * MIME types are supported and sets up playback. It is registered
  28685. * automatically to the appropriate tech based on the capabilities of
  28686. * the browser it is running in. It is not necessary to use or modify
  28687. * this object in normal usage.
  28688. */
  28689. const VhsSourceHandler = {
  28690. name: 'videojs-http-streaming',
  28691. VERSION: version$4,
  28692. canHandleSource(srcObj, options = {}) {
  28693. const localOptions = merge$1(videojs__default["default"].options, options);
  28694. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  28695. },
  28696. handleSource(source, tech, options = {}) {
  28697. const localOptions = merge$1(videojs__default["default"].options, options);
  28698. tech.vhs = new VhsHandler(source, tech, localOptions);
  28699. tech.vhs.xhr = xhrFactory();
  28700. tech.vhs.setupXhrHooks_();
  28701. tech.vhs.src(source.src, source.type);
  28702. return tech.vhs;
  28703. },
  28704. canPlayType(type, options) {
  28705. const simpleType = simpleTypeFromSourceType(type);
  28706. if (!simpleType) {
  28707. return '';
  28708. }
  28709. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  28710. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  28711. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  28712. return canUseMsePlayback ? 'maybe' : '';
  28713. },
  28714. getOverrideNative(options = {}) {
  28715. const {
  28716. vhs = {}
  28717. } = options;
  28718. const defaultOverrideNative = !(videojs__default["default"].browser.IS_ANY_SAFARI || videojs__default["default"].browser.IS_IOS);
  28719. const {
  28720. overrideNative = defaultOverrideNative
  28721. } = vhs;
  28722. return overrideNative;
  28723. }
  28724. };
  28725. /**
  28726. * Check to see if the native MediaSource object exists and supports
  28727. * an MP4 container with both H.264 video and AAC-LC audio.
  28728. *
  28729. * @return {boolean} if native media sources are supported
  28730. */
  28731. const supportsNativeMediaSources = () => {
  28732. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  28733. }; // register source handlers with the appropriate techs
  28734. if (supportsNativeMediaSources()) {
  28735. videojs__default["default"].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  28736. }
  28737. videojs__default["default"].VhsHandler = VhsHandler;
  28738. videojs__default["default"].VhsSourceHandler = VhsSourceHandler;
  28739. videojs__default["default"].Vhs = Vhs;
  28740. if (!videojs__default["default"].use) {
  28741. videojs__default["default"].registerComponent('Vhs', Vhs);
  28742. }
  28743. videojs__default["default"].options.vhs = videojs__default["default"].options.vhs || {};
  28744. if (!videojs__default["default"].getPlugin || !videojs__default["default"].getPlugin('reloadSourceOnError')) {
  28745. videojs__default["default"].registerPlugin('reloadSourceOnError', reloadSourceOnError);
  28746. }
  28747. exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
  28748. exports.Vhs = Vhs;
  28749. exports.VhsHandler = VhsHandler;
  28750. exports.VhsSourceHandler = VhsSourceHandler;
  28751. exports.emeKeySystems = emeKeySystems;
  28752. exports.expandDataUri = expandDataUri;
  28753. exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
  28754. exports.setupEmeOptions = setupEmeOptions;
  28755. exports.simpleTypeFromSourceType = simpleTypeFromSourceType;
  28756. exports.waitForKeySessionCreation = waitForKeySessionCreation;
  28757. Object.defineProperty(exports, '__esModule', { value: true });
  28758. }));