videojs-http-streaming.cjs.js 843 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432
  1. /*! @name @videojs/http-streaming @version 3.0.2 @license Apache-2.0 */
  2. 'use strict';
  3. Object.defineProperty(exports, '__esModule', { value: true });
  4. var document = require('global/document');
  5. var window$1 = require('global/window');
  6. var _resolveUrl = require('@videojs/vhs-utils/cjs/resolve-url.js');
  7. var videojs = require('video.js');
  8. var _extends = require('@babel/runtime/helpers/extends');
  9. var m3u8Parser = require('m3u8-parser');
  10. var codecs_js = require('@videojs/vhs-utils/cjs/codecs.js');
  11. var mediaTypes_js = require('@videojs/vhs-utils/cjs/media-types.js');
  12. var byteHelpers = require('@videojs/vhs-utils/cjs/byte-helpers');
  13. var mpdParser = require('mpd-parser');
  14. var parseSidx = require('mux.js/lib/tools/parse-sidx');
  15. var id3Helpers = require('@videojs/vhs-utils/cjs/id3-helpers');
  16. var containers = require('@videojs/vhs-utils/cjs/containers');
  17. var clock = require('mux.js/lib/utils/clock');
  18. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  19. var document__default = /*#__PURE__*/_interopDefaultLegacy(document);
  20. var window__default = /*#__PURE__*/_interopDefaultLegacy(window$1);
  21. var _resolveUrl__default = /*#__PURE__*/_interopDefaultLegacy(_resolveUrl);
  22. var videojs__default = /*#__PURE__*/_interopDefaultLegacy(videojs);
  23. var _extends__default = /*#__PURE__*/_interopDefaultLegacy(_extends);
  24. var parseSidx__default = /*#__PURE__*/_interopDefaultLegacy(parseSidx);
  25. /**
  26. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  27. */
  28. const resolveUrl = _resolveUrl__default["default"];
  29. /**
  30. * If the xhr request was redirected, return the responseURL, otherwise,
  31. * return the original url.
  32. *
  33. * @api private
  34. *
  35. * @param {string} url - an url being requested
  36. * @param {XMLHttpRequest} req - xhr request result
  37. *
  38. * @return {string}
  39. */
  40. const resolveManifestRedirect = (url, req) => {
  41. // To understand how the responseURL below is set and generated:
  42. // - https://fetch.spec.whatwg.org/#concept-response-url
  43. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  44. if (req && req.responseURL && url !== req.responseURL) {
  45. return req.responseURL;
  46. }
  47. return url;
  48. };
  49. const logger = source => {
  50. if (videojs__default["default"].log.debug) {
  51. return videojs__default["default"].log.debug.bind(videojs__default["default"], 'VHS:', `${source} >`);
  52. }
  53. return function () {};
  54. };
  55. /**
  56. * Provides a compatibility layer between Video.js 7 and 8 API changes for VHS.
  57. */
  58. /**
  59. * Delegates to videojs.obj.merge (Video.js 8) or
  60. * videojs.mergeOptions (Video.js 7).
  61. */
  62. function merge(...args) {
  63. const context = videojs__default["default"].obj || videojs__default["default"];
  64. const fn = context.merge || context.mergeOptions;
  65. return fn.apply(context, args);
  66. }
  67. /**
  68. * Delegates to videojs.time.createTimeRanges (Video.js 8) or
  69. * videojs.createTimeRanges (Video.js 7).
  70. */
  71. function createTimeRanges(...args) {
  72. const context = videojs__default["default"].time || videojs__default["default"];
  73. const fn = context.createTimeRanges || context.createTimeRanges;
  74. return fn.apply(context, args);
  75. }
  76. /**
  77. * ranges
  78. *
  79. * Utilities for working with TimeRanges.
  80. *
  81. */
  82. const TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  83. // can be misleading because of precision differences or when the current media has poorly
  84. // aligned audio and video, which can cause values to be slightly off from what you would
  85. // expect. This value is what we consider to be safe to use in such comparisons to account
  86. // for these scenarios.
  87. const SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  88. const filterRanges = function (timeRanges, predicate) {
  89. const results = [];
  90. let i;
  91. if (timeRanges && timeRanges.length) {
  92. // Search for ranges that match the predicate
  93. for (i = 0; i < timeRanges.length; i++) {
  94. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  95. results.push([timeRanges.start(i), timeRanges.end(i)]);
  96. }
  97. }
  98. }
  99. return createTimeRanges(results);
  100. };
  101. /**
  102. * Attempts to find the buffered TimeRange that contains the specified
  103. * time.
  104. *
  105. * @param {TimeRanges} buffered - the TimeRanges object to query
  106. * @param {number} time - the time to filter on.
  107. * @return {TimeRanges} a new TimeRanges object
  108. */
  109. const findRange = function (buffered, time) {
  110. return filterRanges(buffered, function (start, end) {
  111. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  112. });
  113. };
  114. /**
  115. * Returns the TimeRanges that begin later than the specified time.
  116. *
  117. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  118. * @param {number} time - the time to filter on.
  119. * @return {TimeRanges} a new TimeRanges object.
  120. */
  121. const findNextRange = function (timeRanges, time) {
  122. return filterRanges(timeRanges, function (start) {
  123. return start - TIME_FUDGE_FACTOR >= time;
  124. });
  125. };
  126. /**
  127. * Returns gaps within a list of TimeRanges
  128. *
  129. * @param {TimeRanges} buffered - the TimeRanges object
  130. * @return {TimeRanges} a TimeRanges object of gaps
  131. */
  132. const findGaps = function (buffered) {
  133. if (buffered.length < 2) {
  134. return createTimeRanges();
  135. }
  136. const ranges = [];
  137. for (let i = 1; i < buffered.length; i++) {
  138. const start = buffered.end(i - 1);
  139. const end = buffered.start(i);
  140. ranges.push([start, end]);
  141. }
  142. return createTimeRanges(ranges);
  143. };
  144. /**
  145. * Calculate the intersection of two TimeRanges
  146. *
  147. * @param {TimeRanges} bufferA
  148. * @param {TimeRanges} bufferB
  149. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  150. */
  151. const bufferIntersection = function (bufferA, bufferB) {
  152. let start = null;
  153. let end = null;
  154. let arity = 0;
  155. const extents = [];
  156. const ranges = [];
  157. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  158. return createTimeRanges();
  159. } // Handle the case where we have both buffers and create an
  160. // intersection of the two
  161. let count = bufferA.length; // A) Gather up all start and end times
  162. while (count--) {
  163. extents.push({
  164. time: bufferA.start(count),
  165. type: 'start'
  166. });
  167. extents.push({
  168. time: bufferA.end(count),
  169. type: 'end'
  170. });
  171. }
  172. count = bufferB.length;
  173. while (count--) {
  174. extents.push({
  175. time: bufferB.start(count),
  176. type: 'start'
  177. });
  178. extents.push({
  179. time: bufferB.end(count),
  180. type: 'end'
  181. });
  182. } // B) Sort them by time
  183. extents.sort(function (a, b) {
  184. return a.time - b.time;
  185. }); // C) Go along one by one incrementing arity for start and decrementing
  186. // arity for ends
  187. for (count = 0; count < extents.length; count++) {
  188. if (extents[count].type === 'start') {
  189. arity++; // D) If arity is ever incremented to 2 we are entering an
  190. // overlapping range
  191. if (arity === 2) {
  192. start = extents[count].time;
  193. }
  194. } else if (extents[count].type === 'end') {
  195. arity--; // E) If arity is ever decremented to 1 we leaving an
  196. // overlapping range
  197. if (arity === 1) {
  198. end = extents[count].time;
  199. }
  200. } // F) Record overlapping ranges
  201. if (start !== null && end !== null) {
  202. ranges.push([start, end]);
  203. start = null;
  204. end = null;
  205. }
  206. }
  207. return createTimeRanges(ranges);
  208. };
  209. /**
  210. * Gets a human readable string for a TimeRange
  211. *
  212. * @param {TimeRange} range
  213. * @return {string} a human readable string
  214. */
  215. const printableRange = range => {
  216. const strArr = [];
  217. if (!range || !range.length) {
  218. return '';
  219. }
  220. for (let i = 0; i < range.length; i++) {
  221. strArr.push(range.start(i) + ' => ' + range.end(i));
  222. }
  223. return strArr.join(', ');
  224. };
  225. /**
  226. * Calculates the amount of time left in seconds until the player hits the end of the
  227. * buffer and causes a rebuffer
  228. *
  229. * @param {TimeRange} buffered
  230. * The state of the buffer
  231. * @param {Numnber} currentTime
  232. * The current time of the player
  233. * @param {number} playbackRate
  234. * The current playback rate of the player. Defaults to 1.
  235. * @return {number}
  236. * Time until the player has to start rebuffering in seconds.
  237. * @function timeUntilRebuffer
  238. */
  239. const timeUntilRebuffer = function (buffered, currentTime, playbackRate = 1) {
  240. const bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  241. return (bufferedEnd - currentTime) / playbackRate;
  242. };
  243. /**
  244. * Converts a TimeRanges object into an array representation
  245. *
  246. * @param {TimeRanges} timeRanges
  247. * @return {Array}
  248. */
  249. const timeRangesToArray = timeRanges => {
  250. const timeRangesList = [];
  251. for (let i = 0; i < timeRanges.length; i++) {
  252. timeRangesList.push({
  253. start: timeRanges.start(i),
  254. end: timeRanges.end(i)
  255. });
  256. }
  257. return timeRangesList;
  258. };
  259. /**
  260. * Determines if two time range objects are different.
  261. *
  262. * @param {TimeRange} a
  263. * the first time range object to check
  264. *
  265. * @param {TimeRange} b
  266. * the second time range object to check
  267. *
  268. * @return {Boolean}
  269. * Whether the time range objects differ
  270. */
  271. const isRangeDifferent = function (a, b) {
  272. // same object
  273. if (a === b) {
  274. return false;
  275. } // one or the other is undefined
  276. if (!a && b || !b && a) {
  277. return true;
  278. } // length is different
  279. if (a.length !== b.length) {
  280. return true;
  281. } // see if any start/end pair is different
  282. for (let i = 0; i < a.length; i++) {
  283. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  284. return true;
  285. }
  286. } // if the length and every pair is the same
  287. // this is the same time range
  288. return false;
  289. };
  290. const lastBufferedEnd = function (a) {
  291. if (!a || !a.length || !a.end) {
  292. return;
  293. }
  294. return a.end(a.length - 1);
  295. };
  296. /**
  297. * A utility function to add up the amount of time in a timeRange
  298. * after a specified startTime.
  299. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  300. * would return 40 as there are 40s seconds after 0 in the timeRange
  301. *
  302. * @param {TimeRange} range
  303. * The range to check against
  304. * @param {number} startTime
  305. * The time in the time range that you should start counting from
  306. *
  307. * @return {number}
  308. * The number of seconds in the buffer passed the specified time.
  309. */
  310. const timeAheadOf = function (range, startTime) {
  311. let time = 0;
  312. if (!range || !range.length) {
  313. return time;
  314. }
  315. for (let i = 0; i < range.length; i++) {
  316. const start = range.start(i);
  317. const end = range.end(i); // startTime is after this range entirely
  318. if (startTime > end) {
  319. continue;
  320. } // startTime is within this range
  321. if (startTime > start && startTime <= end) {
  322. time += end - startTime;
  323. continue;
  324. } // startTime is before this range.
  325. time += end - start;
  326. }
  327. return time;
  328. };
  329. /**
  330. * @file playlist.js
  331. *
  332. * Playlist related utilities.
  333. */
  334. /**
  335. * Get the duration of a segment, with special cases for
  336. * llhls segments that do not have a duration yet.
  337. *
  338. * @param {Object} playlist
  339. * the playlist that the segment belongs to.
  340. * @param {Object} segment
  341. * the segment to get a duration for.
  342. *
  343. * @return {number}
  344. * the segment duration
  345. */
  346. const segmentDurationWithParts = (playlist, segment) => {
  347. // if this isn't a preload segment
  348. // then we will have a segment duration that is accurate.
  349. if (!segment.preload) {
  350. return segment.duration;
  351. } // otherwise we have to add up parts and preload hints
  352. // to get an up to date duration.
  353. let result = 0;
  354. (segment.parts || []).forEach(function (p) {
  355. result += p.duration;
  356. }); // for preload hints we have to use partTargetDuration
  357. // as they won't even have a duration yet.
  358. (segment.preloadHints || []).forEach(function (p) {
  359. if (p.type === 'PART') {
  360. result += playlist.partTargetDuration;
  361. }
  362. });
  363. return result;
  364. };
  365. /**
  366. * A function to get a combined list of parts and segments with durations
  367. * and indexes.
  368. *
  369. * @param {Playlist} playlist the playlist to get the list for.
  370. *
  371. * @return {Array} The part/segment list.
  372. */
  373. const getPartsAndSegments = playlist => (playlist.segments || []).reduce((acc, segment, si) => {
  374. if (segment.parts) {
  375. segment.parts.forEach(function (part, pi) {
  376. acc.push({
  377. duration: part.duration,
  378. segmentIndex: si,
  379. partIndex: pi,
  380. part,
  381. segment
  382. });
  383. });
  384. } else {
  385. acc.push({
  386. duration: segment.duration,
  387. segmentIndex: si,
  388. partIndex: null,
  389. segment,
  390. part: null
  391. });
  392. }
  393. return acc;
  394. }, []);
  395. const getLastParts = media => {
  396. const lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  397. return lastSegment && lastSegment.parts || [];
  398. };
  399. const getKnownPartCount = ({
  400. preloadSegment
  401. }) => {
  402. if (!preloadSegment) {
  403. return;
  404. }
  405. const {
  406. parts,
  407. preloadHints
  408. } = preloadSegment;
  409. let partCount = (preloadHints || []).reduce((count, hint) => count + (hint.type === 'PART' ? 1 : 0), 0);
  410. partCount += parts && parts.length ? parts.length : 0;
  411. return partCount;
  412. };
  413. /**
  414. * Get the number of seconds to delay from the end of a
  415. * live playlist.
  416. *
  417. * @param {Playlist} main the main playlist
  418. * @param {Playlist} media the media playlist
  419. * @return {number} the hold back in seconds.
  420. */
  421. const liveEdgeDelay = (main, media) => {
  422. if (media.endList) {
  423. return 0;
  424. } // dash suggestedPresentationDelay trumps everything
  425. if (main && main.suggestedPresentationDelay) {
  426. return main.suggestedPresentationDelay;
  427. }
  428. const hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  429. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  430. return media.serverControl.partHoldBack;
  431. } else if (hasParts && media.partTargetDuration) {
  432. return media.partTargetDuration * 3; // finally look for full segment delays
  433. } else if (media.serverControl && media.serverControl.holdBack) {
  434. return media.serverControl.holdBack;
  435. } else if (media.targetDuration) {
  436. return media.targetDuration * 3;
  437. }
  438. return 0;
  439. };
  440. /**
  441. * walk backward until we find a duration we can use
  442. * or return a failure
  443. *
  444. * @param {Playlist} playlist the playlist to walk through
  445. * @param {Number} endSequence the mediaSequence to stop walking on
  446. */
  447. const backwardDuration = function (playlist, endSequence) {
  448. let result = 0;
  449. let i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  450. // the interval, use it
  451. let segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  452. // information that is earlier than endSequence
  453. if (segment) {
  454. if (typeof segment.start !== 'undefined') {
  455. return {
  456. result: segment.start,
  457. precise: true
  458. };
  459. }
  460. if (typeof segment.end !== 'undefined') {
  461. return {
  462. result: segment.end - segment.duration,
  463. precise: true
  464. };
  465. }
  466. }
  467. while (i--) {
  468. segment = playlist.segments[i];
  469. if (typeof segment.end !== 'undefined') {
  470. return {
  471. result: result + segment.end,
  472. precise: true
  473. };
  474. }
  475. result += segmentDurationWithParts(playlist, segment);
  476. if (typeof segment.start !== 'undefined') {
  477. return {
  478. result: result + segment.start,
  479. precise: true
  480. };
  481. }
  482. }
  483. return {
  484. result,
  485. precise: false
  486. };
  487. };
  488. /**
  489. * walk forward until we find a duration we can use
  490. * or return a failure
  491. *
  492. * @param {Playlist} playlist the playlist to walk through
  493. * @param {number} endSequence the mediaSequence to stop walking on
  494. */
  495. const forwardDuration = function (playlist, endSequence) {
  496. let result = 0;
  497. let segment;
  498. let i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  499. // information
  500. for (; i < playlist.segments.length; i++) {
  501. segment = playlist.segments[i];
  502. if (typeof segment.start !== 'undefined') {
  503. return {
  504. result: segment.start - result,
  505. precise: true
  506. };
  507. }
  508. result += segmentDurationWithParts(playlist, segment);
  509. if (typeof segment.end !== 'undefined') {
  510. return {
  511. result: segment.end - result,
  512. precise: true
  513. };
  514. }
  515. } // indicate we didn't find a useful duration estimate
  516. return {
  517. result: -1,
  518. precise: false
  519. };
  520. };
  521. /**
  522. * Calculate the media duration from the segments associated with a
  523. * playlist. The duration of a subinterval of the available segments
  524. * may be calculated by specifying an end index.
  525. *
  526. * @param {Object} playlist a media playlist object
  527. * @param {number=} endSequence an exclusive upper boundary
  528. * for the playlist. Defaults to playlist length.
  529. * @param {number} expired the amount of time that has dropped
  530. * off the front of the playlist in a live scenario
  531. * @return {number} the duration between the first available segment
  532. * and end index.
  533. */
  534. const intervalDuration = function (playlist, endSequence, expired) {
  535. if (typeof endSequence === 'undefined') {
  536. endSequence = playlist.mediaSequence + playlist.segments.length;
  537. }
  538. if (endSequence < playlist.mediaSequence) {
  539. return 0;
  540. } // do a backward walk to estimate the duration
  541. const backward = backwardDuration(playlist, endSequence);
  542. if (backward.precise) {
  543. // if we were able to base our duration estimate on timing
  544. // information provided directly from the Media Source, return
  545. // it
  546. return backward.result;
  547. } // walk forward to see if a precise duration estimate can be made
  548. // that way
  549. const forward = forwardDuration(playlist, endSequence);
  550. if (forward.precise) {
  551. // we found a segment that has been buffered and so it's
  552. // position is known precisely
  553. return forward.result;
  554. } // return the less-precise, playlist-based duration estimate
  555. return backward.result + expired;
  556. };
  557. /**
  558. * Calculates the duration of a playlist. If a start and end index
  559. * are specified, the duration will be for the subset of the media
  560. * timeline between those two indices. The total duration for live
  561. * playlists is always Infinity.
  562. *
  563. * @param {Object} playlist a media playlist object
  564. * @param {number=} endSequence an exclusive upper
  565. * boundary for the playlist. Defaults to the playlist media
  566. * sequence number plus its length.
  567. * @param {number=} expired the amount of time that has
  568. * dropped off the front of the playlist in a live scenario
  569. * @return {number} the duration between the start index and end
  570. * index.
  571. */
  572. const duration = function (playlist, endSequence, expired) {
  573. if (!playlist) {
  574. return 0;
  575. }
  576. if (typeof expired !== 'number') {
  577. expired = 0;
  578. } // if a slice of the total duration is not requested, use
  579. // playlist-level duration indicators when they're present
  580. if (typeof endSequence === 'undefined') {
  581. // if present, use the duration specified in the playlist
  582. if (playlist.totalDuration) {
  583. return playlist.totalDuration;
  584. } // duration should be Infinity for live playlists
  585. if (!playlist.endList) {
  586. return window__default["default"].Infinity;
  587. }
  588. } // calculate the total duration based on the segment durations
  589. return intervalDuration(playlist, endSequence, expired);
  590. };
  591. /**
  592. * Calculate the time between two indexes in the current playlist
  593. * neight the start- nor the end-index need to be within the current
  594. * playlist in which case, the targetDuration of the playlist is used
  595. * to approximate the durations of the segments
  596. *
  597. * @param {Array} options.durationList list to iterate over for durations.
  598. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  599. * @param {number} options.startIndex partsAndSegments index to start
  600. * @param {number} options.endIndex partsAndSegments index to end.
  601. * @return {number} the number of seconds between startIndex and endIndex
  602. */
  603. const sumDurations = function ({
  604. defaultDuration,
  605. durationList,
  606. startIndex,
  607. endIndex
  608. }) {
  609. let durations = 0;
  610. if (startIndex > endIndex) {
  611. [startIndex, endIndex] = [endIndex, startIndex];
  612. }
  613. if (startIndex < 0) {
  614. for (let i = startIndex; i < Math.min(0, endIndex); i++) {
  615. durations += defaultDuration;
  616. }
  617. startIndex = 0;
  618. }
  619. for (let i = startIndex; i < endIndex; i++) {
  620. durations += durationList[i].duration;
  621. }
  622. return durations;
  623. };
  624. /**
  625. * Calculates the playlist end time
  626. *
  627. * @param {Object} playlist a media playlist object
  628. * @param {number=} expired the amount of time that has
  629. * dropped off the front of the playlist in a live scenario
  630. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  631. * playlist end calculation should consider the safe live end
  632. * (truncate the playlist end by three segments). This is normally
  633. * used for calculating the end of the playlist's seekable range.
  634. * This takes into account the value of liveEdgePadding.
  635. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  636. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  637. * If this is provided, it is used in the safe live end calculation.
  638. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  639. * Corresponds to suggestedPresentationDelay in DASH manifests.
  640. * @return {number} the end time of playlist
  641. * @function playlistEnd
  642. */
  643. const playlistEnd = function (playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  644. if (!playlist || !playlist.segments) {
  645. return null;
  646. }
  647. if (playlist.endList) {
  648. return duration(playlist);
  649. }
  650. if (expired === null) {
  651. return null;
  652. }
  653. expired = expired || 0;
  654. let lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  655. if (useSafeLiveEnd) {
  656. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  657. lastSegmentEndTime -= liveEdgePadding;
  658. } // don't return a time less than zero
  659. return Math.max(0, lastSegmentEndTime);
  660. };
  661. /**
  662. * Calculates the interval of time that is currently seekable in a
  663. * playlist. The returned time ranges are relative to the earliest
  664. * moment in the specified playlist that is still available. A full
  665. * seekable implementation for live streams would need to offset
  666. * these values by the duration of content that has expired from the
  667. * stream.
  668. *
  669. * @param {Object} playlist a media playlist object
  670. * dropped off the front of the playlist in a live scenario
  671. * @param {number=} expired the amount of time that has
  672. * dropped off the front of the playlist in a live scenario
  673. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  674. * Corresponds to suggestedPresentationDelay in DASH manifests.
  675. * @return {TimeRanges} the periods of time that are valid targets
  676. * for seeking
  677. */
  678. const seekable = function (playlist, expired, liveEdgePadding) {
  679. const useSafeLiveEnd = true;
  680. const seekableStart = expired || 0;
  681. const seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  682. if (seekableEnd === null) {
  683. return createTimeRanges();
  684. }
  685. return createTimeRanges(seekableStart, seekableEnd);
  686. };
  687. /**
  688. * Determine the index and estimated starting time of the segment that
  689. * contains a specified playback position in a media playlist.
  690. *
  691. * @param {Object} options.playlist the media playlist to query
  692. * @param {number} options.currentTime The number of seconds since the earliest
  693. * possible position to determine the containing segment for
  694. * @param {number} options.startTime the time when the segment/part starts
  695. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  696. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  697. *
  698. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  699. */
  700. const getMediaInfoForTime = function ({
  701. playlist,
  702. currentTime,
  703. startingSegmentIndex,
  704. startingPartIndex,
  705. startTime,
  706. exactManifestTimings
  707. }) {
  708. let time = currentTime - startTime;
  709. const partsAndSegments = getPartsAndSegments(playlist);
  710. let startIndex = 0;
  711. for (let i = 0; i < partsAndSegments.length; i++) {
  712. const partAndSegment = partsAndSegments[i];
  713. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  714. continue;
  715. } // skip this if part index does not match.
  716. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  717. continue;
  718. }
  719. startIndex = i;
  720. break;
  721. }
  722. if (time < 0) {
  723. // Walk backward from startIndex in the playlist, adding durations
  724. // until we find a segment that contains `time` and return it
  725. if (startIndex > 0) {
  726. for (let i = startIndex - 1; i >= 0; i--) {
  727. const partAndSegment = partsAndSegments[i];
  728. time += partAndSegment.duration;
  729. if (exactManifestTimings) {
  730. if (time < 0) {
  731. continue;
  732. }
  733. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  734. continue;
  735. }
  736. return {
  737. partIndex: partAndSegment.partIndex,
  738. segmentIndex: partAndSegment.segmentIndex,
  739. startTime: startTime - sumDurations({
  740. defaultDuration: playlist.targetDuration,
  741. durationList: partsAndSegments,
  742. startIndex,
  743. endIndex: i
  744. })
  745. };
  746. }
  747. } // We were unable to find a good segment within the playlist
  748. // so select the first segment
  749. return {
  750. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  751. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  752. startTime: currentTime
  753. };
  754. } // When startIndex is negative, we first walk forward to first segment
  755. // adding target durations. If we "run out of time" before getting to
  756. // the first segment, return the first segment
  757. if (startIndex < 0) {
  758. for (let i = startIndex; i < 0; i++) {
  759. time -= playlist.targetDuration;
  760. if (time < 0) {
  761. return {
  762. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  763. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  764. startTime: currentTime
  765. };
  766. }
  767. }
  768. startIndex = 0;
  769. } // Walk forward from startIndex in the playlist, subtracting durations
  770. // until we find a segment that contains `time` and return it
  771. for (let i = startIndex; i < partsAndSegments.length; i++) {
  772. const partAndSegment = partsAndSegments[i];
  773. time -= partAndSegment.duration;
  774. if (exactManifestTimings) {
  775. if (time > 0) {
  776. continue;
  777. }
  778. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  779. continue;
  780. }
  781. return {
  782. partIndex: partAndSegment.partIndex,
  783. segmentIndex: partAndSegment.segmentIndex,
  784. startTime: startTime + sumDurations({
  785. defaultDuration: playlist.targetDuration,
  786. durationList: partsAndSegments,
  787. startIndex,
  788. endIndex: i
  789. })
  790. };
  791. } // We are out of possible candidates so load the last one...
  792. return {
  793. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  794. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  795. startTime: currentTime
  796. };
  797. };
  798. /**
  799. * Check whether the playlist is excluded or not.
  800. *
  801. * @param {Object} playlist the media playlist object
  802. * @return {boolean} whether the playlist is excluded or not
  803. * @function isExcluded
  804. */
  805. const isExcluded = function (playlist) {
  806. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  807. };
  808. /**
  809. * Check whether the playlist is compatible with current playback configuration or has
  810. * been excluded permanently for being incompatible.
  811. *
  812. * @param {Object} playlist the media playlist object
  813. * @return {boolean} whether the playlist is incompatible or not
  814. * @function isIncompatible
  815. */
  816. const isIncompatible = function (playlist) {
  817. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  818. };
  819. /**
  820. * Check whether the playlist is enabled or not.
  821. *
  822. * @param {Object} playlist the media playlist object
  823. * @return {boolean} whether the playlist is enabled or not
  824. * @function isEnabled
  825. */
  826. const isEnabled = function (playlist) {
  827. const excluded = isExcluded(playlist);
  828. return !playlist.disabled && !excluded;
  829. };
  830. /**
  831. * Check whether the playlist has been manually disabled through the representations api.
  832. *
  833. * @param {Object} playlist the media playlist object
  834. * @return {boolean} whether the playlist is disabled manually or not
  835. * @function isDisabled
  836. */
  837. const isDisabled = function (playlist) {
  838. return playlist.disabled;
  839. };
  840. /**
  841. * Returns whether the current playlist is an AES encrypted HLS stream
  842. *
  843. * @return {boolean} true if it's an AES encrypted HLS stream
  844. */
  845. const isAes = function (media) {
  846. for (let i = 0; i < media.segments.length; i++) {
  847. if (media.segments[i].key) {
  848. return true;
  849. }
  850. }
  851. return false;
  852. };
  853. /**
  854. * Checks if the playlist has a value for the specified attribute
  855. *
  856. * @param {string} attr
  857. * Attribute to check for
  858. * @param {Object} playlist
  859. * The media playlist object
  860. * @return {boolean}
  861. * Whether the playlist contains a value for the attribute or not
  862. * @function hasAttribute
  863. */
  864. const hasAttribute = function (attr, playlist) {
  865. return playlist.attributes && playlist.attributes[attr];
  866. };
  867. /**
  868. * Estimates the time required to complete a segment download from the specified playlist
  869. *
  870. * @param {number} segmentDuration
  871. * Duration of requested segment
  872. * @param {number} bandwidth
  873. * Current measured bandwidth of the player
  874. * @param {Object} playlist
  875. * The media playlist object
  876. * @param {number=} bytesReceived
  877. * Number of bytes already received for the request. Defaults to 0
  878. * @return {number|NaN}
  879. * The estimated time to request the segment. NaN if bandwidth information for
  880. * the given playlist is unavailable
  881. * @function estimateSegmentRequestTime
  882. */
  883. const estimateSegmentRequestTime = function (segmentDuration, bandwidth, playlist, bytesReceived = 0) {
  884. if (!hasAttribute('BANDWIDTH', playlist)) {
  885. return NaN;
  886. }
  887. const size = segmentDuration * playlist.attributes.BANDWIDTH;
  888. return (size - bytesReceived * 8) / bandwidth;
  889. };
  890. /*
  891. * Returns whether the current playlist is the lowest rendition
  892. *
  893. * @return {Boolean} true if on lowest rendition
  894. */
  895. const isLowestEnabledRendition = (main, media) => {
  896. if (main.playlists.length === 1) {
  897. return true;
  898. }
  899. const currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  900. return main.playlists.filter(playlist => {
  901. if (!isEnabled(playlist)) {
  902. return false;
  903. }
  904. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  905. }).length === 0;
  906. };
  907. const playlistMatch = (a, b) => {
  908. // both playlits are null
  909. // or only one playlist is non-null
  910. // no match
  911. if (!a && !b || !a && b || a && !b) {
  912. return false;
  913. } // playlist objects are the same, match
  914. if (a === b) {
  915. return true;
  916. } // first try to use id as it should be the most
  917. // accurate
  918. if (a.id && b.id && a.id === b.id) {
  919. return true;
  920. } // next try to use reslovedUri as it should be the
  921. // second most accurate.
  922. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  923. return true;
  924. } // finally try to use uri as it should be accurate
  925. // but might miss a few cases for relative uris
  926. if (a.uri && b.uri && a.uri === b.uri) {
  927. return true;
  928. }
  929. return false;
  930. };
  931. const someAudioVariant = function (main, callback) {
  932. const AUDIO = main && main.mediaGroups && main.mediaGroups.AUDIO || {};
  933. let found = false;
  934. for (const groupName in AUDIO) {
  935. for (const label in AUDIO[groupName]) {
  936. found = callback(AUDIO[groupName][label]);
  937. if (found) {
  938. break;
  939. }
  940. }
  941. if (found) {
  942. break;
  943. }
  944. }
  945. return !!found;
  946. };
  947. const isAudioOnly = main => {
  948. // we are audio only if we have no main playlists but do
  949. // have media group playlists.
  950. if (!main || !main.playlists || !main.playlists.length) {
  951. // without audio variants or playlists this
  952. // is not an audio only main.
  953. const found = someAudioVariant(main, variant => variant.playlists && variant.playlists.length || variant.uri);
  954. return found;
  955. } // if every playlist has only an audio codec it is audio only
  956. for (let i = 0; i < main.playlists.length; i++) {
  957. const playlist = main.playlists[i];
  958. const CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  959. if (CODECS && CODECS.split(',').every(c => codecs_js.isAudioCodec(c))) {
  960. continue;
  961. } // playlist is in an audio group it is audio only
  962. const found = someAudioVariant(main, variant => playlistMatch(playlist, variant));
  963. if (found) {
  964. continue;
  965. } // if we make it here this playlist isn't audio and we
  966. // are not audio only
  967. return false;
  968. } // if we make it past every playlist without returning, then
  969. // this is an audio only playlist.
  970. return true;
  971. }; // exports
  972. var Playlist = {
  973. liveEdgeDelay,
  974. duration,
  975. seekable,
  976. getMediaInfoForTime,
  977. isEnabled,
  978. isDisabled,
  979. isExcluded,
  980. isIncompatible,
  981. playlistEnd,
  982. isAes,
  983. hasAttribute,
  984. estimateSegmentRequestTime,
  985. isLowestEnabledRendition,
  986. isAudioOnly,
  987. playlistMatch,
  988. segmentDurationWithParts
  989. };
  990. const {
  991. log
  992. } = videojs__default["default"];
  993. const createPlaylistID = (index, uri) => {
  994. return `${index}-${uri}`;
  995. }; // default function for creating a group id
  996. const groupID = (type, group, label) => {
  997. return `placeholder-uri-${type}-${group}-${label}`;
  998. };
  999. /**
  1000. * Parses a given m3u8 playlist
  1001. *
  1002. * @param {Function} [onwarn]
  1003. * a function to call when the parser triggers a warning event.
  1004. * @param {Function} [oninfo]
  1005. * a function to call when the parser triggers an info event.
  1006. * @param {string} manifestString
  1007. * The downloaded manifest string
  1008. * @param {Object[]} [customTagParsers]
  1009. * An array of custom tag parsers for the m3u8-parser instance
  1010. * @param {Object[]} [customTagMappers]
  1011. * An array of custom tag mappers for the m3u8-parser instance
  1012. * @param {boolean} [llhls]
  1013. * Whether to keep ll-hls features in the manifest after parsing.
  1014. * @return {Object}
  1015. * The manifest object
  1016. */
  1017. const parseManifest = ({
  1018. onwarn,
  1019. oninfo,
  1020. manifestString,
  1021. customTagParsers = [],
  1022. customTagMappers = [],
  1023. llhls
  1024. }) => {
  1025. const parser = new m3u8Parser.Parser();
  1026. if (onwarn) {
  1027. parser.on('warn', onwarn);
  1028. }
  1029. if (oninfo) {
  1030. parser.on('info', oninfo);
  1031. }
  1032. customTagParsers.forEach(customParser => parser.addParser(customParser));
  1033. customTagMappers.forEach(mapper => parser.addTagMapper(mapper));
  1034. parser.push(manifestString);
  1035. parser.end();
  1036. const manifest = parser.manifest; // remove llhls features from the parsed manifest
  1037. // if we don't want llhls support.
  1038. if (!llhls) {
  1039. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  1040. if (manifest.hasOwnProperty(k)) {
  1041. delete manifest[k];
  1042. }
  1043. });
  1044. if (manifest.segments) {
  1045. manifest.segments.forEach(function (segment) {
  1046. ['parts', 'preloadHints'].forEach(function (k) {
  1047. if (segment.hasOwnProperty(k)) {
  1048. delete segment[k];
  1049. }
  1050. });
  1051. });
  1052. }
  1053. }
  1054. if (!manifest.targetDuration) {
  1055. let targetDuration = 10;
  1056. if (manifest.segments && manifest.segments.length) {
  1057. targetDuration = manifest.segments.reduce((acc, s) => Math.max(acc, s.duration), 0);
  1058. }
  1059. if (onwarn) {
  1060. onwarn(`manifest has no targetDuration defaulting to ${targetDuration}`);
  1061. }
  1062. manifest.targetDuration = targetDuration;
  1063. }
  1064. const parts = getLastParts(manifest);
  1065. if (parts.length && !manifest.partTargetDuration) {
  1066. const partTargetDuration = parts.reduce((acc, p) => Math.max(acc, p.duration), 0);
  1067. if (onwarn) {
  1068. onwarn(`manifest has no partTargetDuration defaulting to ${partTargetDuration}`);
  1069. 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.');
  1070. }
  1071. manifest.partTargetDuration = partTargetDuration;
  1072. }
  1073. return manifest;
  1074. };
  1075. /**
  1076. * Loops through all supported media groups in main and calls the provided
  1077. * callback for each group
  1078. *
  1079. * @param {Object} main
  1080. * The parsed main manifest object
  1081. * @param {Function} callback
  1082. * Callback to call for each media group
  1083. */
  1084. const forEachMediaGroup = (main, callback) => {
  1085. if (!main.mediaGroups) {
  1086. return;
  1087. }
  1088. ['AUDIO', 'SUBTITLES'].forEach(mediaType => {
  1089. if (!main.mediaGroups[mediaType]) {
  1090. return;
  1091. }
  1092. for (const groupKey in main.mediaGroups[mediaType]) {
  1093. for (const labelKey in main.mediaGroups[mediaType][groupKey]) {
  1094. const mediaProperties = main.mediaGroups[mediaType][groupKey][labelKey];
  1095. callback(mediaProperties, mediaType, groupKey, labelKey);
  1096. }
  1097. }
  1098. });
  1099. };
  1100. /**
  1101. * Adds properties and attributes to the playlist to keep consistent functionality for
  1102. * playlists throughout VHS.
  1103. *
  1104. * @param {Object} config
  1105. * Arguments object
  1106. * @param {Object} config.playlist
  1107. * The media playlist
  1108. * @param {string} [config.uri]
  1109. * The uri to the media playlist (if media playlist is not from within a main
  1110. * playlist)
  1111. * @param {string} id
  1112. * ID to use for the playlist
  1113. */
  1114. const setupMediaPlaylist = ({
  1115. playlist,
  1116. uri,
  1117. id
  1118. }) => {
  1119. playlist.id = id;
  1120. playlist.playlistErrors_ = 0;
  1121. if (uri) {
  1122. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  1123. // playlists do not contain their own source URI, but one is needed for consistency in
  1124. // VHS.
  1125. playlist.uri = uri;
  1126. } // For HLS main playlists, even though certain attributes MUST be defined, the
  1127. // stream may still be played without them.
  1128. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  1129. // manifest.
  1130. //
  1131. // To avoid undefined reference errors through the project, and make the code easier
  1132. // to write/read, add an empty attributes object for these cases.
  1133. playlist.attributes = playlist.attributes || {};
  1134. };
  1135. /**
  1136. * Adds ID, resolvedUri, and attributes properties to each playlist of the main, where
  1137. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  1138. * playlist references to the playlists array.
  1139. *
  1140. * @param {Object} main
  1141. * The main playlist
  1142. */
  1143. const setupMediaPlaylists = main => {
  1144. let i = main.playlists.length;
  1145. while (i--) {
  1146. const playlist = main.playlists[i];
  1147. setupMediaPlaylist({
  1148. playlist,
  1149. id: createPlaylistID(i, playlist.uri)
  1150. });
  1151. playlist.resolvedUri = resolveUrl(main.uri, playlist.uri);
  1152. main.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  1153. main.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  1154. // the stream can be played without it. Although an attributes property may have been
  1155. // added to the playlist to prevent undefined references, issue a warning to fix the
  1156. // manifest.
  1157. if (!playlist.attributes.BANDWIDTH) {
  1158. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  1159. }
  1160. }
  1161. };
  1162. /**
  1163. * Adds resolvedUri properties to each media group.
  1164. *
  1165. * @param {Object} main
  1166. * The main playlist
  1167. */
  1168. const resolveMediaGroupUris = main => {
  1169. forEachMediaGroup(main, properties => {
  1170. if (properties.uri) {
  1171. properties.resolvedUri = resolveUrl(main.uri, properties.uri);
  1172. }
  1173. });
  1174. };
  1175. /**
  1176. * Creates a main playlist wrapper to insert a sole media playlist into.
  1177. *
  1178. * @param {Object} media
  1179. * Media playlist
  1180. * @param {string} uri
  1181. * The media URI
  1182. *
  1183. * @return {Object}
  1184. * main playlist
  1185. */
  1186. const mainForMedia = (media, uri) => {
  1187. const id = createPlaylistID(0, uri);
  1188. const main = {
  1189. mediaGroups: {
  1190. 'AUDIO': {},
  1191. 'VIDEO': {},
  1192. 'CLOSED-CAPTIONS': {},
  1193. 'SUBTITLES': {}
  1194. },
  1195. uri: window__default["default"].location.href,
  1196. resolvedUri: window__default["default"].location.href,
  1197. playlists: [{
  1198. uri,
  1199. id,
  1200. resolvedUri: uri,
  1201. // m3u8-parser does not attach an attributes property to media playlists so make
  1202. // sure that the property is attached to avoid undefined reference errors
  1203. attributes: {}
  1204. }]
  1205. }; // set up ID reference
  1206. main.playlists[id] = main.playlists[0]; // URI reference added for backwards compatibility
  1207. main.playlists[uri] = main.playlists[0];
  1208. return main;
  1209. };
  1210. /**
  1211. * Does an in-place update of the main manifest to add updated playlist URI references
  1212. * as well as other properties needed by VHS that aren't included by the parser.
  1213. *
  1214. * @param {Object} main
  1215. * main manifest object
  1216. * @param {string} uri
  1217. * The source URI
  1218. * @param {function} createGroupID
  1219. * A function to determine how to create the groupID for mediaGroups
  1220. */
  1221. const addPropertiesToMain = (main, uri, createGroupID = groupID) => {
  1222. main.uri = uri;
  1223. for (let i = 0; i < main.playlists.length; i++) {
  1224. if (!main.playlists[i].uri) {
  1225. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  1226. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  1227. // TODO: consider adding dummy URIs in mpd-parser
  1228. const phonyUri = `placeholder-uri-${i}`;
  1229. main.playlists[i].uri = phonyUri;
  1230. }
  1231. }
  1232. const audioOnlyMain = isAudioOnly(main);
  1233. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1234. // add a playlist array under properties
  1235. if (!properties.playlists || !properties.playlists.length) {
  1236. // If the manifest is audio only and this media group does not have a uri, check
  1237. // if the media group is located in the main list of playlists. If it is, don't add
  1238. // placeholder properties as it shouldn't be considered an alternate audio track.
  1239. if (audioOnlyMain && mediaType === 'AUDIO' && !properties.uri) {
  1240. for (let i = 0; i < main.playlists.length; i++) {
  1241. const p = main.playlists[i];
  1242. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  1243. return;
  1244. }
  1245. }
  1246. }
  1247. properties.playlists = [_extends__default["default"]({}, properties)];
  1248. }
  1249. properties.playlists.forEach(function (p, i) {
  1250. const groupId = createGroupID(mediaType, groupKey, labelKey, p);
  1251. const id = createPlaylistID(i, groupId);
  1252. if (p.uri) {
  1253. p.resolvedUri = p.resolvedUri || resolveUrl(main.uri, p.uri);
  1254. } else {
  1255. // DEPRECATED, this has been added to prevent a breaking change.
  1256. // previously we only ever had a single media group playlist, so
  1257. // we mark the first playlist uri without prepending the index as we used to
  1258. // ideally we would do all of the playlists the same way.
  1259. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  1260. // the placeholder again
  1261. p.resolvedUri = p.uri;
  1262. }
  1263. p.id = p.id || id; // add an empty attributes object, all playlists are
  1264. // expected to have this.
  1265. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  1266. main.playlists[p.id] = p;
  1267. main.playlists[p.uri] = p;
  1268. });
  1269. });
  1270. setupMediaPlaylists(main);
  1271. resolveMediaGroupUris(main);
  1272. };
  1273. /**
  1274. * @file playlist-loader.js
  1275. *
  1276. * A state machine that manages the loading, caching, and updating of
  1277. * M3U8 playlists.
  1278. *
  1279. */
  1280. const {
  1281. EventTarget: EventTarget$1
  1282. } = videojs__default["default"];
  1283. const addLLHLSQueryDirectives = (uri, media) => {
  1284. if (media.endList || !media.serverControl) {
  1285. return uri;
  1286. }
  1287. const parameters = {};
  1288. if (media.serverControl.canBlockReload) {
  1289. const {
  1290. preloadSegment
  1291. } = media; // next msn is a zero based value, length is not.
  1292. let nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  1293. // that we are going to request a part of that preload segment.
  1294. // the logic below is used to determine that.
  1295. if (preloadSegment) {
  1296. const parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  1297. const nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  1298. // length of parts, then we know we had part preload hints
  1299. // and we need to add the _HLS_part= query
  1300. if (nextPart > -1 && nextPart !== parts.length - 1) {
  1301. // add existing parts to our preload hints
  1302. // eslint-disable-next-line
  1303. parameters._HLS_part = nextPart;
  1304. } // this if statement makes sure that we request the msn
  1305. // of the preload segment if:
  1306. // 1. the preload segment had parts (and was not yet a full segment)
  1307. // but was added to our segments array
  1308. // 2. the preload segment had preload hints for parts that are not in
  1309. // the manifest yet.
  1310. // in all other cases we want the segment after the preload segment
  1311. // which will be given by using media.segments.length because it is 1 based
  1312. // rather than 0 based.
  1313. if (nextPart > -1 || parts.length) {
  1314. nextMSN--;
  1315. }
  1316. } // add _HLS_msn= in front of any _HLS_part query
  1317. // eslint-disable-next-line
  1318. parameters._HLS_msn = nextMSN;
  1319. }
  1320. if (media.serverControl && media.serverControl.canSkipUntil) {
  1321. // add _HLS_skip= infront of all other queries.
  1322. // eslint-disable-next-line
  1323. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  1324. }
  1325. if (Object.keys(parameters).length) {
  1326. const parsedUri = new window__default["default"].URL(uri);
  1327. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  1328. if (!parameters.hasOwnProperty(name)) {
  1329. return;
  1330. }
  1331. parsedUri.searchParams.set(name, parameters[name]);
  1332. });
  1333. uri = parsedUri.toString();
  1334. }
  1335. return uri;
  1336. };
  1337. /**
  1338. * Returns a new segment object with properties and
  1339. * the parts array merged.
  1340. *
  1341. * @param {Object} a the old segment
  1342. * @param {Object} b the new segment
  1343. *
  1344. * @return {Object} the merged segment
  1345. */
  1346. const updateSegment = (a, b) => {
  1347. if (!a) {
  1348. return b;
  1349. }
  1350. const result = merge(a, b); // if only the old segment has preload hints
  1351. // and the new one does not, remove preload hints.
  1352. if (a.preloadHints && !b.preloadHints) {
  1353. delete result.preloadHints;
  1354. } // if only the old segment has parts
  1355. // then the parts are no longer valid
  1356. if (a.parts && !b.parts) {
  1357. delete result.parts; // if both segments have parts
  1358. // copy part propeties from the old segment
  1359. // to the new one.
  1360. } else if (a.parts && b.parts) {
  1361. for (let i = 0; i < b.parts.length; i++) {
  1362. if (a.parts && a.parts[i]) {
  1363. result.parts[i] = merge(a.parts[i], b.parts[i]);
  1364. }
  1365. }
  1366. } // set skipped to false for segments that have
  1367. // have had information merged from the old segment.
  1368. if (!a.skipped && b.skipped) {
  1369. result.skipped = false;
  1370. } // set preload to false for segments that have
  1371. // had information added in the new segment.
  1372. if (a.preload && !b.preload) {
  1373. result.preload = false;
  1374. }
  1375. return result;
  1376. };
  1377. /**
  1378. * Returns a new array of segments that is the result of merging
  1379. * properties from an older list of segments onto an updated
  1380. * list. No properties on the updated playlist will be ovewritten.
  1381. *
  1382. * @param {Array} original the outdated list of segments
  1383. * @param {Array} update the updated list of segments
  1384. * @param {number=} offset the index of the first update
  1385. * segment in the original segment list. For non-live playlists,
  1386. * this should always be zero and does not need to be
  1387. * specified. For live playlists, it should be the difference
  1388. * between the media sequence numbers in the original and updated
  1389. * playlists.
  1390. * @return {Array} a list of merged segment objects
  1391. */
  1392. const updateSegments = (original, update, offset) => {
  1393. const oldSegments = original.slice();
  1394. const newSegments = update.slice();
  1395. offset = offset || 0;
  1396. const result = [];
  1397. let currentMap;
  1398. for (let newIndex = 0; newIndex < newSegments.length; newIndex++) {
  1399. const oldSegment = oldSegments[newIndex + offset];
  1400. const newSegment = newSegments[newIndex];
  1401. if (oldSegment) {
  1402. currentMap = oldSegment.map || currentMap;
  1403. result.push(updateSegment(oldSegment, newSegment));
  1404. } else {
  1405. // carry over map to new segment if it is missing
  1406. if (currentMap && !newSegment.map) {
  1407. newSegment.map = currentMap;
  1408. }
  1409. result.push(newSegment);
  1410. }
  1411. }
  1412. return result;
  1413. };
  1414. const resolveSegmentUris = (segment, baseUri) => {
  1415. // preloadSegment will not have a uri at all
  1416. // as the segment isn't actually in the manifest yet, only parts
  1417. if (!segment.resolvedUri && segment.uri) {
  1418. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  1419. }
  1420. if (segment.key && !segment.key.resolvedUri) {
  1421. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  1422. }
  1423. if (segment.map && !segment.map.resolvedUri) {
  1424. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  1425. }
  1426. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  1427. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  1428. }
  1429. if (segment.parts && segment.parts.length) {
  1430. segment.parts.forEach(p => {
  1431. if (p.resolvedUri) {
  1432. return;
  1433. }
  1434. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1435. });
  1436. }
  1437. if (segment.preloadHints && segment.preloadHints.length) {
  1438. segment.preloadHints.forEach(p => {
  1439. if (p.resolvedUri) {
  1440. return;
  1441. }
  1442. p.resolvedUri = resolveUrl(baseUri, p.uri);
  1443. });
  1444. }
  1445. };
  1446. const getAllSegments = function (media) {
  1447. const segments = media.segments || [];
  1448. const preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  1449. // a usable segment, only include a preloadSegment that has
  1450. // parts.
  1451. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  1452. // if preloadHints has a MAP that means that the
  1453. // init segment is going to change. We cannot use any of the parts
  1454. // from this preload segment.
  1455. if (preloadSegment.preloadHints) {
  1456. for (let i = 0; i < preloadSegment.preloadHints.length; i++) {
  1457. if (preloadSegment.preloadHints[i].type === 'MAP') {
  1458. return segments;
  1459. }
  1460. }
  1461. } // set the duration for our preload segment to target duration.
  1462. preloadSegment.duration = media.targetDuration;
  1463. preloadSegment.preload = true;
  1464. segments.push(preloadSegment);
  1465. }
  1466. return segments;
  1467. }; // consider the playlist unchanged if the playlist object is the same or
  1468. // the number of segments is equal, the media sequence number is unchanged,
  1469. // and this playlist hasn't become the end of the playlist
  1470. 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;
  1471. /**
  1472. * Returns a new main playlist that is the result of merging an
  1473. * updated media playlist into the original version. If the
  1474. * updated media playlist does not match any of the playlist
  1475. * entries in the original main playlist, null is returned.
  1476. *
  1477. * @param {Object} main a parsed main M3U8 object
  1478. * @param {Object} media a parsed media M3U8 object
  1479. * @return {Object} a new object that represents the original
  1480. * main playlist with the updated media playlist merged in, or
  1481. * null if the merge produced no change.
  1482. */
  1483. const updateMain$1 = (main, newMedia, unchangedCheck = isPlaylistUnchanged) => {
  1484. const result = merge(main, {});
  1485. const oldMedia = result.playlists[newMedia.id];
  1486. if (!oldMedia) {
  1487. return null;
  1488. }
  1489. if (unchangedCheck(oldMedia, newMedia)) {
  1490. return null;
  1491. }
  1492. newMedia.segments = getAllSegments(newMedia);
  1493. const mergedPlaylist = merge(oldMedia, newMedia); // always use the new media's preload segment
  1494. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  1495. delete mergedPlaylist.preloadSegment;
  1496. } // if the update could overlap existing segment information, merge the two segment lists
  1497. if (oldMedia.segments) {
  1498. if (newMedia.skip) {
  1499. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  1500. // old properties into the new segments
  1501. for (let i = 0; i < newMedia.skip.skippedSegments; i++) {
  1502. newMedia.segments.unshift({
  1503. skipped: true
  1504. });
  1505. }
  1506. }
  1507. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  1508. } // resolve any segment URIs to prevent us from having to do it later
  1509. mergedPlaylist.segments.forEach(segment => {
  1510. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  1511. }); // TODO Right now in the playlists array there are two references to each playlist, one
  1512. // that is referenced by index, and one by URI. The index reference may no longer be
  1513. // necessary.
  1514. for (let i = 0; i < result.playlists.length; i++) {
  1515. if (result.playlists[i].id === newMedia.id) {
  1516. result.playlists[i] = mergedPlaylist;
  1517. }
  1518. }
  1519. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  1520. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  1521. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  1522. if (!properties.playlists) {
  1523. return;
  1524. }
  1525. for (let i = 0; i < properties.playlists.length; i++) {
  1526. if (newMedia.id === properties.playlists[i].id) {
  1527. properties.playlists[i] = mergedPlaylist;
  1528. }
  1529. }
  1530. });
  1531. return result;
  1532. };
  1533. /**
  1534. * Calculates the time to wait before refreshing a live playlist
  1535. *
  1536. * @param {Object} media
  1537. * The current media
  1538. * @param {boolean} update
  1539. * True if there were any updates from the last refresh, false otherwise
  1540. * @return {number}
  1541. * The time in ms to wait before refreshing the live playlist
  1542. */
  1543. const refreshDelay = (media, update) => {
  1544. const segments = media.segments || [];
  1545. const lastSegment = segments[segments.length - 1];
  1546. const lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  1547. const lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  1548. if (update && lastDuration) {
  1549. return lastDuration * 1000;
  1550. } // if the playlist is unchanged since the last reload or last segment duration
  1551. // cannot be determined, try again after half the target duration
  1552. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  1553. };
  1554. /**
  1555. * Load a playlist from a remote location
  1556. *
  1557. * @class PlaylistLoader
  1558. * @extends Stream
  1559. * @param {string|Object} src url or object of manifest
  1560. * @param {boolean} withCredentials the withCredentials xhr option
  1561. * @class
  1562. */
  1563. class PlaylistLoader extends EventTarget$1 {
  1564. constructor(src, vhs, options = {}) {
  1565. super();
  1566. if (!src) {
  1567. throw new Error('A non-empty playlist URL or object is required');
  1568. }
  1569. this.logger_ = logger('PlaylistLoader');
  1570. const {
  1571. withCredentials = false
  1572. } = options;
  1573. this.src = src;
  1574. this.vhs_ = vhs;
  1575. this.withCredentials = withCredentials;
  1576. const vhsOptions = vhs.options_;
  1577. this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  1578. this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  1579. this.llhls = vhsOptions && vhsOptions.llhls; // initialize the loader state
  1580. this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  1581. this.handleMediaupdatetimeout_ = this.handleMediaupdatetimeout_.bind(this);
  1582. this.on('mediaupdatetimeout', this.handleMediaupdatetimeout_);
  1583. }
  1584. handleMediaupdatetimeout_() {
  1585. if (this.state !== 'HAVE_METADATA') {
  1586. // only refresh the media playlist if no other activity is going on
  1587. return;
  1588. }
  1589. const media = this.media();
  1590. let uri = resolveUrl(this.main.uri, media.uri);
  1591. if (this.llhls) {
  1592. uri = addLLHLSQueryDirectives(uri, media);
  1593. }
  1594. this.state = 'HAVE_CURRENT_METADATA';
  1595. this.request = this.vhs_.xhr({
  1596. uri,
  1597. withCredentials: this.withCredentials
  1598. }, (error, req) => {
  1599. // disposed
  1600. if (!this.request) {
  1601. return;
  1602. }
  1603. if (error) {
  1604. return this.playlistRequestError(this.request, this.media(), 'HAVE_METADATA');
  1605. }
  1606. this.haveMetadata({
  1607. playlistString: this.request.responseText,
  1608. url: this.media().uri,
  1609. id: this.media().id
  1610. });
  1611. });
  1612. }
  1613. playlistRequestError(xhr, playlist, startingState) {
  1614. const {
  1615. uri,
  1616. id
  1617. } = playlist; // any in-flight request is now finished
  1618. this.request = null;
  1619. if (startingState) {
  1620. this.state = startingState;
  1621. }
  1622. this.error = {
  1623. playlist: this.main.playlists[id],
  1624. status: xhr.status,
  1625. message: `HLS playlist request error at URL: ${uri}.`,
  1626. responseText: xhr.responseText,
  1627. code: xhr.status >= 500 ? 4 : 2
  1628. };
  1629. this.trigger('error');
  1630. }
  1631. parseManifest_({
  1632. url,
  1633. manifestString
  1634. }) {
  1635. return parseManifest({
  1636. onwarn: ({
  1637. message
  1638. }) => this.logger_(`m3u8-parser warn for ${url}: ${message}`),
  1639. oninfo: ({
  1640. message
  1641. }) => this.logger_(`m3u8-parser info for ${url}: ${message}`),
  1642. manifestString,
  1643. customTagParsers: this.customTagParsers,
  1644. customTagMappers: this.customTagMappers,
  1645. llhls: this.llhls
  1646. });
  1647. }
  1648. /**
  1649. * Update the playlist loader's state in response to a new or updated playlist.
  1650. *
  1651. * @param {string} [playlistString]
  1652. * Playlist string (if playlistObject is not provided)
  1653. * @param {Object} [playlistObject]
  1654. * Playlist object (if playlistString is not provided)
  1655. * @param {string} url
  1656. * URL of playlist
  1657. * @param {string} id
  1658. * ID to use for playlist
  1659. */
  1660. haveMetadata({
  1661. playlistString,
  1662. playlistObject,
  1663. url,
  1664. id
  1665. }) {
  1666. // any in-flight request is now finished
  1667. this.request = null;
  1668. this.state = 'HAVE_METADATA';
  1669. const playlist = playlistObject || this.parseManifest_({
  1670. url,
  1671. manifestString: playlistString
  1672. });
  1673. playlist.lastRequest = Date.now();
  1674. setupMediaPlaylist({
  1675. playlist,
  1676. uri: url,
  1677. id
  1678. }); // merge this playlist into the main manifest
  1679. const update = updateMain$1(this.main, playlist);
  1680. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  1681. this.pendingMedia_ = null;
  1682. if (update) {
  1683. this.main = update;
  1684. this.media_ = this.main.playlists[id];
  1685. } else {
  1686. this.trigger('playlistunchanged');
  1687. }
  1688. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  1689. this.trigger('loadedplaylist');
  1690. }
  1691. /**
  1692. * Abort any outstanding work and clean up.
  1693. */
  1694. dispose() {
  1695. this.trigger('dispose');
  1696. this.stopRequest();
  1697. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  1698. window__default["default"].clearTimeout(this.finalRenditionTimeout);
  1699. this.off();
  1700. }
  1701. stopRequest() {
  1702. if (this.request) {
  1703. const oldRequest = this.request;
  1704. this.request = null;
  1705. oldRequest.onreadystatechange = null;
  1706. oldRequest.abort();
  1707. }
  1708. }
  1709. /**
  1710. * When called without any arguments, returns the currently
  1711. * active media playlist. When called with a single argument,
  1712. * triggers the playlist loader to asynchronously switch to the
  1713. * specified media playlist. Calling this method while the
  1714. * loader is in the HAVE_NOTHING causes an error to be emitted
  1715. * but otherwise has no effect.
  1716. *
  1717. * @param {Object=} playlist the parsed media playlist
  1718. * object to switch to
  1719. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  1720. *
  1721. * @return {Playlist} the current loaded media
  1722. */
  1723. media(playlist, shouldDelay) {
  1724. // getter
  1725. if (!playlist) {
  1726. return this.media_;
  1727. } // setter
  1728. if (this.state === 'HAVE_NOTHING') {
  1729. throw new Error('Cannot switch media playlist from ' + this.state);
  1730. } // find the playlist object if the target playlist has been
  1731. // specified by URI
  1732. if (typeof playlist === 'string') {
  1733. if (!this.main.playlists[playlist]) {
  1734. throw new Error('Unknown playlist URI: ' + playlist);
  1735. }
  1736. playlist = this.main.playlists[playlist];
  1737. }
  1738. window__default["default"].clearTimeout(this.finalRenditionTimeout);
  1739. if (shouldDelay) {
  1740. const delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  1741. this.finalRenditionTimeout = window__default["default"].setTimeout(this.media.bind(this, playlist, false), delay);
  1742. return;
  1743. }
  1744. const startingState = this.state;
  1745. const mediaChange = !this.media_ || playlist.id !== this.media_.id;
  1746. const mainPlaylistRef = this.main.playlists[playlist.id]; // switch to fully loaded playlists immediately
  1747. if (mainPlaylistRef && mainPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  1748. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  1749. playlist.endList && playlist.segments.length) {
  1750. // abort outstanding playlist requests
  1751. if (this.request) {
  1752. this.request.onreadystatechange = null;
  1753. this.request.abort();
  1754. this.request = null;
  1755. }
  1756. this.state = 'HAVE_METADATA';
  1757. this.media_ = playlist; // trigger media change if the active media has been updated
  1758. if (mediaChange) {
  1759. this.trigger('mediachanging');
  1760. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1761. // The initial playlist was a main manifest, and the first media selected was
  1762. // also provided (in the form of a resolved playlist object) as part of the
  1763. // source object (rather than just a URL). Therefore, since the media playlist
  1764. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  1765. // normal flow, and needs an explicit trigger here.
  1766. this.trigger('loadedmetadata');
  1767. } else {
  1768. this.trigger('mediachange');
  1769. }
  1770. }
  1771. return;
  1772. } // We update/set the timeout here so that live playlists
  1773. // that are not a media change will "start" the loader as expected.
  1774. // We expect that this function will start the media update timeout
  1775. // cycle again. This also prevents a playlist switch failure from
  1776. // causing us to stall during live.
  1777. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  1778. if (!mediaChange) {
  1779. return;
  1780. }
  1781. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  1782. if (this.request) {
  1783. if (playlist.resolvedUri === this.request.url) {
  1784. // requesting to switch to the same playlist multiple times
  1785. // has no effect after the first
  1786. return;
  1787. }
  1788. this.request.onreadystatechange = null;
  1789. this.request.abort();
  1790. this.request = null;
  1791. } // request the new playlist
  1792. if (this.media_) {
  1793. this.trigger('mediachanging');
  1794. }
  1795. this.pendingMedia_ = playlist;
  1796. this.request = this.vhs_.xhr({
  1797. uri: playlist.resolvedUri,
  1798. withCredentials: this.withCredentials
  1799. }, (error, req) => {
  1800. // disposed
  1801. if (!this.request) {
  1802. return;
  1803. }
  1804. playlist.lastRequest = Date.now();
  1805. playlist.resolvedUri = resolveManifestRedirect(playlist.resolvedUri, req);
  1806. if (error) {
  1807. return this.playlistRequestError(this.request, playlist, startingState);
  1808. }
  1809. this.haveMetadata({
  1810. playlistString: req.responseText,
  1811. url: playlist.uri,
  1812. id: playlist.id
  1813. }); // fire loadedmetadata the first time a media playlist is loaded
  1814. if (startingState === 'HAVE_MAIN_MANIFEST') {
  1815. this.trigger('loadedmetadata');
  1816. } else {
  1817. this.trigger('mediachange');
  1818. }
  1819. });
  1820. }
  1821. /**
  1822. * pause loading of the playlist
  1823. */
  1824. pause() {
  1825. if (this.mediaUpdateTimeout) {
  1826. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  1827. this.mediaUpdateTimeout = null;
  1828. }
  1829. this.stopRequest();
  1830. if (this.state === 'HAVE_NOTHING') {
  1831. // If we pause the loader before any data has been retrieved, its as if we never
  1832. // started, so reset to an unstarted state.
  1833. this.started = false;
  1834. } // Need to restore state now that no activity is happening
  1835. if (this.state === 'SWITCHING_MEDIA') {
  1836. // if the loader was in the process of switching media, it should either return to
  1837. // HAVE_MAIN_MANIFEST or HAVE_METADATA depending on if the loader has loaded a media
  1838. // playlist yet. This is determined by the existence of loader.media_
  1839. if (this.media_) {
  1840. this.state = 'HAVE_METADATA';
  1841. } else {
  1842. this.state = 'HAVE_MAIN_MANIFEST';
  1843. }
  1844. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  1845. this.state = 'HAVE_METADATA';
  1846. }
  1847. }
  1848. /**
  1849. * start loading of the playlist
  1850. */
  1851. load(shouldDelay) {
  1852. if (this.mediaUpdateTimeout) {
  1853. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  1854. this.mediaUpdateTimeout = null;
  1855. }
  1856. const media = this.media();
  1857. if (shouldDelay) {
  1858. const delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  1859. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  1860. this.mediaUpdateTimeout = null;
  1861. this.load();
  1862. }, delay);
  1863. return;
  1864. }
  1865. if (!this.started) {
  1866. this.start();
  1867. return;
  1868. }
  1869. if (media && !media.endList) {
  1870. this.trigger('mediaupdatetimeout');
  1871. } else {
  1872. this.trigger('loadedplaylist');
  1873. }
  1874. }
  1875. updateMediaUpdateTimeout_(delay) {
  1876. if (this.mediaUpdateTimeout) {
  1877. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  1878. this.mediaUpdateTimeout = null;
  1879. } // we only have use mediaupdatetimeout for live playlists.
  1880. if (!this.media() || this.media().endList) {
  1881. return;
  1882. }
  1883. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  1884. this.mediaUpdateTimeout = null;
  1885. this.trigger('mediaupdatetimeout');
  1886. this.updateMediaUpdateTimeout_(delay);
  1887. }, delay);
  1888. }
  1889. /**
  1890. * start loading of the playlist
  1891. */
  1892. start() {
  1893. this.started = true;
  1894. if (typeof this.src === 'object') {
  1895. // in the case of an entirely constructed manifest object (meaning there's no actual
  1896. // manifest on a server), default the uri to the page's href
  1897. if (!this.src.uri) {
  1898. this.src.uri = window__default["default"].location.href;
  1899. } // resolvedUri is added on internally after the initial request. Since there's no
  1900. // request for pre-resolved manifests, add on resolvedUri here.
  1901. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  1902. // request can be skipped (since the top level of the manifest, at a minimum, is
  1903. // already available as a parsed manifest object). However, if the manifest object
  1904. // represents a main playlist, some media playlists may need to be resolved before
  1905. // the starting segment list is available. Therefore, go directly to setup of the
  1906. // initial playlist, and let the normal flow continue from there.
  1907. //
  1908. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  1909. // that the first request is asynchronous.
  1910. setTimeout(() => {
  1911. this.setupInitialPlaylist(this.src);
  1912. }, 0);
  1913. return;
  1914. } // request the specified URL
  1915. this.request = this.vhs_.xhr({
  1916. uri: this.src,
  1917. withCredentials: this.withCredentials
  1918. }, (error, req) => {
  1919. // disposed
  1920. if (!this.request) {
  1921. return;
  1922. } // clear the loader's request reference
  1923. this.request = null;
  1924. if (error) {
  1925. this.error = {
  1926. status: req.status,
  1927. message: `HLS playlist request error at URL: ${this.src}.`,
  1928. responseText: req.responseText,
  1929. // MEDIA_ERR_NETWORK
  1930. code: 2
  1931. };
  1932. if (this.state === 'HAVE_NOTHING') {
  1933. this.started = false;
  1934. }
  1935. return this.trigger('error');
  1936. }
  1937. this.src = resolveManifestRedirect(this.src, req);
  1938. const manifest = this.parseManifest_({
  1939. manifestString: req.responseText,
  1940. url: this.src
  1941. });
  1942. this.setupInitialPlaylist(manifest);
  1943. });
  1944. }
  1945. srcUri() {
  1946. return typeof this.src === 'string' ? this.src : this.src.uri;
  1947. }
  1948. /**
  1949. * Given a manifest object that's either a main or media playlist, trigger the proper
  1950. * events and set the state of the playlist loader.
  1951. *
  1952. * If the manifest object represents a main playlist, `loadedplaylist` will be
  1953. * triggered to allow listeners to select a playlist. If none is selected, the loader
  1954. * will default to the first one in the playlists array.
  1955. *
  1956. * If the manifest object represents a media playlist, `loadedplaylist` will be
  1957. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  1958. *
  1959. * In the case of a media playlist, a main playlist object wrapper with one playlist
  1960. * will be created so that all logic can handle playlists in the same fashion (as an
  1961. * assumed manifest object schema).
  1962. *
  1963. * @param {Object} manifest
  1964. * The parsed manifest object
  1965. */
  1966. setupInitialPlaylist(manifest) {
  1967. this.state = 'HAVE_MAIN_MANIFEST';
  1968. if (manifest.playlists) {
  1969. this.main = manifest;
  1970. addPropertiesToMain(this.main, this.srcUri()); // If the initial main playlist has playlists wtih segments already resolved,
  1971. // then resolve URIs in advance, as they are usually done after a playlist request,
  1972. // which may not happen if the playlist is resolved.
  1973. manifest.playlists.forEach(playlist => {
  1974. playlist.segments = getAllSegments(playlist);
  1975. playlist.segments.forEach(segment => {
  1976. resolveSegmentUris(segment, playlist.resolvedUri);
  1977. });
  1978. });
  1979. this.trigger('loadedplaylist');
  1980. if (!this.request) {
  1981. // no media playlist was specifically selected so start
  1982. // from the first listed one
  1983. this.media(this.main.playlists[0]);
  1984. }
  1985. return;
  1986. } // In order to support media playlists passed in as vhs-json, the case where the uri
  1987. // is not provided as part of the manifest should be considered, and an appropriate
  1988. // default used.
  1989. const uri = this.srcUri() || window__default["default"].location.href;
  1990. this.main = mainForMedia(manifest, uri);
  1991. this.haveMetadata({
  1992. playlistObject: manifest,
  1993. url: uri,
  1994. id: this.main.playlists[0].id
  1995. });
  1996. this.trigger('loadedmetadata');
  1997. }
  1998. }
  1999. /**
  2000. * @file xhr.js
  2001. */
  2002. const {
  2003. xhr: videojsXHR
  2004. } = videojs__default["default"];
  2005. const callbackWrapper = function (request, error, response, callback) {
  2006. const reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  2007. if (!error && reqResponse) {
  2008. request.responseTime = Date.now();
  2009. request.roundTripTime = request.responseTime - request.requestTime;
  2010. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  2011. if (!request.bandwidth) {
  2012. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  2013. }
  2014. }
  2015. if (response.headers) {
  2016. request.responseHeaders = response.headers;
  2017. } // videojs.xhr now uses a specific code on the error
  2018. // object to signal that a request has timed out instead
  2019. // of setting a boolean on the request object
  2020. if (error && error.code === 'ETIMEDOUT') {
  2021. request.timedout = true;
  2022. } // videojs.xhr no longer considers status codes outside of 200 and 0
  2023. // (for file uris) to be errors, but the old XHR did, so emulate that
  2024. // behavior. Status 206 may be used in response to byterange requests.
  2025. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  2026. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  2027. }
  2028. callback(error, request);
  2029. };
  2030. const xhrFactory = function () {
  2031. const xhr = function XhrFunction(options, callback) {
  2032. // Add a default timeout
  2033. options = merge({
  2034. timeout: 45e3
  2035. }, options); // Allow an optional user-specified function to modify the option
  2036. // object before we construct the xhr request
  2037. const beforeRequest = XhrFunction.beforeRequest || videojs__default["default"].Vhs.xhr.beforeRequest;
  2038. if (beforeRequest && typeof beforeRequest === 'function') {
  2039. const newOptions = beforeRequest(options);
  2040. if (newOptions) {
  2041. options = newOptions;
  2042. }
  2043. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  2044. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  2045. const xhrMethod = videojs__default["default"].Vhs.xhr.original === true ? videojsXHR : videojs__default["default"].Vhs.xhr;
  2046. const request = xhrMethod(options, function (error, response) {
  2047. return callbackWrapper(request, error, response, callback);
  2048. });
  2049. const originalAbort = request.abort;
  2050. request.abort = function () {
  2051. request.aborted = true;
  2052. return originalAbort.apply(request, arguments);
  2053. };
  2054. request.uri = options.uri;
  2055. request.requestTime = Date.now();
  2056. return request;
  2057. };
  2058. xhr.original = true;
  2059. return xhr;
  2060. };
  2061. /**
  2062. * Turns segment byterange into a string suitable for use in
  2063. * HTTP Range requests
  2064. *
  2065. * @param {Object} byterange - an object with two values defining the start and end
  2066. * of a byte-range
  2067. */
  2068. const byterangeStr = function (byterange) {
  2069. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  2070. // header uses inclusive ranges
  2071. let byterangeEnd;
  2072. const byterangeStart = byterange.offset;
  2073. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  2074. byterangeEnd = window__default["default"].BigInt(byterange.offset) + window__default["default"].BigInt(byterange.length) - window__default["default"].BigInt(1);
  2075. } else {
  2076. byterangeEnd = byterange.offset + byterange.length - 1;
  2077. }
  2078. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  2079. };
  2080. /**
  2081. * Defines headers for use in the xhr request for a particular segment.
  2082. *
  2083. * @param {Object} segment - a simplified copy of the segmentInfo object
  2084. * from SegmentLoader
  2085. */
  2086. const segmentXhrHeaders = function (segment) {
  2087. const headers = {};
  2088. if (segment.byterange) {
  2089. headers.Range = byterangeStr(segment.byterange);
  2090. }
  2091. return headers;
  2092. };
  2093. /**
  2094. * @file bin-utils.js
  2095. */
  2096. /**
  2097. * convert a TimeRange to text
  2098. *
  2099. * @param {TimeRange} range the timerange to use for conversion
  2100. * @param {number} i the iterator on the range to convert
  2101. * @return {string} the range in string format
  2102. */
  2103. const textRange = function (range, i) {
  2104. return range.start(i) + '-' + range.end(i);
  2105. };
  2106. /**
  2107. * format a number as hex string
  2108. *
  2109. * @param {number} e The number
  2110. * @param {number} i the iterator
  2111. * @return {string} the hex formatted number as a string
  2112. */
  2113. const formatHexString = function (e, i) {
  2114. const value = e.toString(16);
  2115. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  2116. };
  2117. const formatAsciiString = function (e) {
  2118. if (e >= 0x20 && e < 0x7e) {
  2119. return String.fromCharCode(e);
  2120. }
  2121. return '.';
  2122. };
  2123. /**
  2124. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  2125. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  2126. *
  2127. * @param {Object} message
  2128. * Object of properties and values to send to the web worker
  2129. * @return {Object}
  2130. * Modified message with TypedArray values expanded
  2131. * @function createTransferableMessage
  2132. */
  2133. const createTransferableMessage = function (message) {
  2134. const transferable = {};
  2135. Object.keys(message).forEach(key => {
  2136. const value = message[key];
  2137. if (byteHelpers.isArrayBufferView(value)) {
  2138. transferable[key] = {
  2139. bytes: value.buffer,
  2140. byteOffset: value.byteOffset,
  2141. byteLength: value.byteLength
  2142. };
  2143. } else {
  2144. transferable[key] = value;
  2145. }
  2146. });
  2147. return transferable;
  2148. };
  2149. /**
  2150. * Returns a unique string identifier for a media initialization
  2151. * segment.
  2152. *
  2153. * @param {Object} initSegment
  2154. * the init segment object.
  2155. *
  2156. * @return {string} the generated init segment id
  2157. */
  2158. const initSegmentId = function (initSegment) {
  2159. const byterange = initSegment.byterange || {
  2160. length: Infinity,
  2161. offset: 0
  2162. };
  2163. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  2164. };
  2165. /**
  2166. * Returns a unique string identifier for a media segment key.
  2167. *
  2168. * @param {Object} key the encryption key
  2169. * @return {string} the unique id for the media segment key.
  2170. */
  2171. const segmentKeyId = function (key) {
  2172. return key.resolvedUri;
  2173. };
  2174. /**
  2175. * utils to help dump binary data to the console
  2176. *
  2177. * @param {Array|TypedArray} data
  2178. * data to dump to a string
  2179. *
  2180. * @return {string} the data as a hex string.
  2181. */
  2182. const hexDump = data => {
  2183. const bytes = Array.prototype.slice.call(data);
  2184. const step = 16;
  2185. let result = '';
  2186. let hex;
  2187. let ascii;
  2188. for (let j = 0; j < bytes.length / step; j++) {
  2189. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  2190. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  2191. result += hex + ' ' + ascii + '\n';
  2192. }
  2193. return result;
  2194. };
  2195. const tagDump = ({
  2196. bytes
  2197. }) => hexDump(bytes);
  2198. const textRanges = ranges => {
  2199. let result = '';
  2200. let i;
  2201. for (i = 0; i < ranges.length; i++) {
  2202. result += textRange(ranges, i) + ' ';
  2203. }
  2204. return result;
  2205. };
  2206. var utils = /*#__PURE__*/Object.freeze({
  2207. __proto__: null,
  2208. createTransferableMessage: createTransferableMessage,
  2209. initSegmentId: initSegmentId,
  2210. segmentKeyId: segmentKeyId,
  2211. hexDump: hexDump,
  2212. tagDump: tagDump,
  2213. textRanges: textRanges
  2214. });
  2215. // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  2216. // 25% was arbitrarily chosen, and may need to be refined over time.
  2217. const SEGMENT_END_FUDGE_PERCENT = 0.25;
  2218. /**
  2219. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  2220. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  2221. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  2222. *
  2223. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  2224. * point" (a point where we have a mapping from program time to player time, with player
  2225. * time being the post transmux start of the segment).
  2226. *
  2227. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  2228. *
  2229. * @param {number} playerTime the player time
  2230. * @param {Object} segment the segment which contains the player time
  2231. * @return {Date} program time
  2232. */
  2233. const playerTimeToProgramTime = (playerTime, segment) => {
  2234. if (!segment.dateTimeObject) {
  2235. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  2236. // be used to map the start of a segment with a real world time).
  2237. return null;
  2238. }
  2239. const transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  2240. const transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  2241. const startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  2242. const offsetFromSegmentStart = playerTime - startOfSegment;
  2243. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  2244. };
  2245. const originalSegmentVideoDuration = videoTimingInfo => {
  2246. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  2247. };
  2248. /**
  2249. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  2250. * returned segment might be an estimate or an accurate match.
  2251. *
  2252. * @param {string} programTime The ISO-8601 programTime to find a match for
  2253. * @param {Object} playlist A playlist object to search within
  2254. */
  2255. const findSegmentForProgramTime = (programTime, playlist) => {
  2256. // Assumptions:
  2257. // - verifyProgramDateTimeTags has already been run
  2258. // - live streams have been started
  2259. let dateTimeObject;
  2260. try {
  2261. dateTimeObject = new Date(programTime);
  2262. } catch (e) {
  2263. return null;
  2264. }
  2265. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2266. return null;
  2267. }
  2268. let segment = playlist.segments[0];
  2269. if (dateTimeObject < segment.dateTimeObject) {
  2270. // Requested time is before stream start.
  2271. return null;
  2272. }
  2273. for (let i = 0; i < playlist.segments.length - 1; i++) {
  2274. segment = playlist.segments[i];
  2275. const nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  2276. if (dateTimeObject < nextSegmentStart) {
  2277. break;
  2278. }
  2279. }
  2280. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2281. const lastSegmentStart = lastSegment.dateTimeObject;
  2282. const lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  2283. const lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  2284. if (dateTimeObject > lastSegmentEnd) {
  2285. // Beyond the end of the stream, or our best guess of the end of the stream.
  2286. return null;
  2287. }
  2288. if (dateTimeObject > lastSegmentStart) {
  2289. segment = lastSegment;
  2290. }
  2291. return {
  2292. segment,
  2293. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  2294. // Although, given that all segments have accurate date time objects, the segment
  2295. // selected should be accurate, unless the video has been transmuxed at some point
  2296. // (determined by the presence of the videoTimingInfo object), the segment's "player
  2297. // time" (the start time in the player) can't be considered accurate.
  2298. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2299. };
  2300. };
  2301. /**
  2302. * Finds a segment that contains the given player time(in seconds).
  2303. *
  2304. * @param {number} time The player time to find a match for
  2305. * @param {Object} playlist A playlist object to search within
  2306. */
  2307. const findSegmentForPlayerTime = (time, playlist) => {
  2308. // Assumptions:
  2309. // - there will always be a segment.duration
  2310. // - we can start from zero
  2311. // - segments are in time order
  2312. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  2313. return null;
  2314. }
  2315. let segmentEnd = 0;
  2316. let segment;
  2317. for (let i = 0; i < playlist.segments.length; i++) {
  2318. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  2319. // should contain the most accurate values we have for the segment's player times.
  2320. //
  2321. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  2322. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  2323. // calculate an end value.
  2324. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  2325. if (time <= segmentEnd) {
  2326. break;
  2327. }
  2328. }
  2329. const lastSegment = playlist.segments[playlist.segments.length - 1];
  2330. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  2331. // The time requested is beyond the stream end.
  2332. return null;
  2333. }
  2334. if (time > segmentEnd) {
  2335. // The time is within or beyond the last segment.
  2336. //
  2337. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  2338. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  2339. // Technically, because the duration value is only an estimate, the time may still
  2340. // exist in the last segment, however, there isn't enough information to make even
  2341. // a reasonable estimate.
  2342. return null;
  2343. }
  2344. segment = lastSegment;
  2345. }
  2346. return {
  2347. segment,
  2348. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  2349. // Because videoTimingInfo is only set after transmux, it is the only way to get
  2350. // accurate timing values.
  2351. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  2352. };
  2353. };
  2354. /**
  2355. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  2356. * If the offset returned is positive, the programTime occurs after the
  2357. * comparisonTimestamp.
  2358. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  2359. *
  2360. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  2361. * @param {string} programTime The programTime as an ISO-8601 string
  2362. * @return {number} offset
  2363. */
  2364. const getOffsetFromTimestamp = (comparisonTimeStamp, programTime) => {
  2365. let segmentDateTime;
  2366. let programDateTime;
  2367. try {
  2368. segmentDateTime = new Date(comparisonTimeStamp);
  2369. programDateTime = new Date(programTime);
  2370. } catch (e) {// TODO handle error
  2371. }
  2372. const segmentTimeEpoch = segmentDateTime.getTime();
  2373. const programTimeEpoch = programDateTime.getTime();
  2374. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  2375. };
  2376. /**
  2377. * Checks that all segments in this playlist have programDateTime tags.
  2378. *
  2379. * @param {Object} playlist A playlist object
  2380. */
  2381. const verifyProgramDateTimeTags = playlist => {
  2382. if (!playlist.segments || playlist.segments.length === 0) {
  2383. return false;
  2384. }
  2385. for (let i = 0; i < playlist.segments.length; i++) {
  2386. const segment = playlist.segments[i];
  2387. if (!segment.dateTimeObject) {
  2388. return false;
  2389. }
  2390. }
  2391. return true;
  2392. };
  2393. /**
  2394. * Returns the programTime of the media given a playlist and a playerTime.
  2395. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  2396. * If the segments containing the time requested have not been buffered yet, an estimate
  2397. * may be returned to the callback.
  2398. *
  2399. * @param {Object} args
  2400. * @param {Object} args.playlist A playlist object to search within
  2401. * @param {number} time A playerTime in seconds
  2402. * @param {Function} callback(err, programTime)
  2403. * @return {string} err.message A detailed error message
  2404. * @return {Object} programTime
  2405. * @return {number} programTime.mediaSeconds The streamTime in seconds
  2406. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  2407. */
  2408. const getProgramTime = ({
  2409. playlist,
  2410. time = undefined,
  2411. callback
  2412. }) => {
  2413. if (!callback) {
  2414. throw new Error('getProgramTime: callback must be provided');
  2415. }
  2416. if (!playlist || time === undefined) {
  2417. return callback({
  2418. message: 'getProgramTime: playlist and time must be provided'
  2419. });
  2420. }
  2421. const matchedSegment = findSegmentForPlayerTime(time, playlist);
  2422. if (!matchedSegment) {
  2423. return callback({
  2424. message: 'valid programTime was not found'
  2425. });
  2426. }
  2427. if (matchedSegment.type === 'estimate') {
  2428. return callback({
  2429. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  2430. seekTime: matchedSegment.estimatedStart
  2431. });
  2432. }
  2433. const programTimeObject = {
  2434. mediaSeconds: time
  2435. };
  2436. const programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  2437. if (programTime) {
  2438. programTimeObject.programDateTime = programTime.toISOString();
  2439. }
  2440. return callback(null, programTimeObject);
  2441. };
  2442. /**
  2443. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  2444. *
  2445. * @param {Object} args
  2446. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  2447. * @param {Object} args.playlist A playlist to look within
  2448. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  2449. * @param {Function} args.seekTo A method to perform a seek
  2450. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  2451. * @param {Object} args.tech The tech to seek on
  2452. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  2453. * @return {string} err.message A detailed error message
  2454. * @return {number} newTime The exact time that was seeked to in seconds
  2455. */
  2456. const seekToProgramTime = ({
  2457. programTime,
  2458. playlist,
  2459. retryCount = 2,
  2460. seekTo,
  2461. pauseAfterSeek = true,
  2462. tech,
  2463. callback
  2464. }) => {
  2465. if (!callback) {
  2466. throw new Error('seekToProgramTime: callback must be provided');
  2467. }
  2468. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  2469. return callback({
  2470. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  2471. });
  2472. }
  2473. if (!playlist.endList && !tech.hasStarted_) {
  2474. return callback({
  2475. message: 'player must be playing a live stream to start buffering'
  2476. });
  2477. }
  2478. if (!verifyProgramDateTimeTags(playlist)) {
  2479. return callback({
  2480. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  2481. });
  2482. }
  2483. const matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  2484. if (!matchedSegment) {
  2485. return callback({
  2486. message: `${programTime} was not found in the stream`
  2487. });
  2488. }
  2489. const segment = matchedSegment.segment;
  2490. const mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  2491. if (matchedSegment.type === 'estimate') {
  2492. // we've run out of retries
  2493. if (retryCount === 0) {
  2494. return callback({
  2495. message: `${programTime} is not buffered yet. Try again`
  2496. });
  2497. }
  2498. seekTo(matchedSegment.estimatedStart + mediaOffset);
  2499. tech.one('seeked', () => {
  2500. seekToProgramTime({
  2501. programTime,
  2502. playlist,
  2503. retryCount: retryCount - 1,
  2504. seekTo,
  2505. pauseAfterSeek,
  2506. tech,
  2507. callback
  2508. });
  2509. });
  2510. return;
  2511. } // Since the segment.start value is determined from the buffered end or ending time
  2512. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  2513. // modifications.
  2514. const seekToTime = segment.start + mediaOffset;
  2515. const seekedCallback = () => {
  2516. return callback(null, tech.currentTime());
  2517. }; // listen for seeked event
  2518. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  2519. if (pauseAfterSeek) {
  2520. tech.pause();
  2521. }
  2522. seekTo(seekToTime);
  2523. };
  2524. // which will only happen if the request is complete.
  2525. const callbackOnCompleted = (request, cb) => {
  2526. if (request.readyState === 4) {
  2527. return cb();
  2528. }
  2529. return;
  2530. };
  2531. const containerRequest = (uri, xhr, cb) => {
  2532. let bytes = [];
  2533. let id3Offset;
  2534. let finished = false;
  2535. const endRequestAndCallback = function (err, req, type, _bytes) {
  2536. req.abort();
  2537. finished = true;
  2538. return cb(err, req, type, _bytes);
  2539. };
  2540. const progressListener = function (error, request) {
  2541. if (finished) {
  2542. return;
  2543. }
  2544. if (error) {
  2545. return endRequestAndCallback(error, request, '', bytes);
  2546. } // grap the new part of content that was just downloaded
  2547. const newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  2548. bytes = byteHelpers.concatTypedArrays(bytes, byteHelpers.stringToBytes(newPart, true));
  2549. id3Offset = id3Offset || id3Helpers.getId3Offset(bytes); // we need at least 10 bytes to determine a type
  2550. // or we need at least two bytes after an id3Offset
  2551. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  2552. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2553. }
  2554. const type = containers.detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  2555. // to see the second sync byte, wait until we have enough data
  2556. // before declaring it ts
  2557. if (type === 'ts' && bytes.length < 188) {
  2558. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2559. } // this may be an unsynced ts segment
  2560. // wait for 376 bytes before detecting no container
  2561. if (!type && bytes.length < 376) {
  2562. return callbackOnCompleted(request, () => endRequestAndCallback(error, request, '', bytes));
  2563. }
  2564. return endRequestAndCallback(null, request, type, bytes);
  2565. };
  2566. const options = {
  2567. uri,
  2568. beforeSend(request) {
  2569. // this forces the browser to pass the bytes to us unprocessed
  2570. request.overrideMimeType('text/plain; charset=x-user-defined');
  2571. request.addEventListener('progress', function ({
  2572. total,
  2573. loaded
  2574. }) {
  2575. return callbackWrapper(request, null, {
  2576. statusCode: request.status
  2577. }, progressListener);
  2578. });
  2579. }
  2580. };
  2581. const request = xhr(options, function (error, response) {
  2582. return callbackWrapper(request, error, response, progressListener);
  2583. });
  2584. return request;
  2585. };
  2586. const {
  2587. EventTarget
  2588. } = videojs__default["default"];
  2589. const dashPlaylistUnchanged = function (a, b) {
  2590. if (!isPlaylistUnchanged(a, b)) {
  2591. return false;
  2592. } // for dash the above check will often return true in scenarios where
  2593. // the playlist actually has changed because mediaSequence isn't a
  2594. // dash thing, and we often set it to 1. So if the playlists have the same amount
  2595. // of segments we return true.
  2596. // So for dash we need to make sure that the underlying segments are different.
  2597. // if sidx changed then the playlists are different.
  2598. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  2599. return false;
  2600. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  2601. return false;
  2602. } // one or the other does not have segments
  2603. // there was a change.
  2604. if (a.segments && !b.segments || !a.segments && b.segments) {
  2605. return false;
  2606. } // neither has segments nothing changed
  2607. if (!a.segments && !b.segments) {
  2608. return true;
  2609. } // check segments themselves
  2610. for (let i = 0; i < a.segments.length; i++) {
  2611. const aSegment = a.segments[i];
  2612. const bSegment = b.segments[i]; // if uris are different between segments there was a change
  2613. if (aSegment.uri !== bSegment.uri) {
  2614. return false;
  2615. } // neither segment has a byterange, there will be no byterange change.
  2616. if (!aSegment.byterange && !bSegment.byterange) {
  2617. continue;
  2618. }
  2619. const aByterange = aSegment.byterange;
  2620. const bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  2621. if (aByterange && !bByterange || !aByterange && bByterange) {
  2622. return false;
  2623. } // if both segments have byterange with different offsets, there was a change.
  2624. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  2625. return false;
  2626. }
  2627. } // if everything was the same with segments, this is the same playlist.
  2628. return true;
  2629. };
  2630. /**
  2631. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  2632. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  2633. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  2634. * periods without continuous playback this function may need modification as well as the parser.
  2635. */
  2636. const dashGroupId = (type, group, label, playlist) => {
  2637. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  2638. const playlistId = playlist.attributes.NAME || label;
  2639. return `placeholder-uri-${type}-${group}-${playlistId}`;
  2640. };
  2641. /**
  2642. * Parses the main XML string and updates playlist URI references.
  2643. *
  2644. * @param {Object} config
  2645. * Object of arguments
  2646. * @param {string} config.mainXml
  2647. * The mpd XML
  2648. * @param {string} config.srcUrl
  2649. * The mpd URL
  2650. * @param {Date} config.clientOffset
  2651. * A time difference between server and client
  2652. * @param {Object} config.sidxMapping
  2653. * SIDX mappings for moof/mdat URIs and byte ranges
  2654. * @return {Object}
  2655. * The parsed mpd manifest object
  2656. */
  2657. const parseMainXml = ({
  2658. mainXml,
  2659. srcUrl,
  2660. clientOffset,
  2661. sidxMapping,
  2662. previousManifest
  2663. }) => {
  2664. const manifest = mpdParser.parse(mainXml, {
  2665. manifestUri: srcUrl,
  2666. clientOffset,
  2667. sidxMapping,
  2668. previousManifest
  2669. });
  2670. addPropertiesToMain(manifest, srcUrl, dashGroupId);
  2671. return manifest;
  2672. };
  2673. /**
  2674. * Removes any mediaGroup labels that no longer exist in the newMain
  2675. *
  2676. * @param {Object} update
  2677. * The previous mpd object being updated
  2678. * @param {Object} newMain
  2679. * The new mpd object
  2680. */
  2681. const removeOldMediaGroupLabels = (update, newMain) => {
  2682. forEachMediaGroup(update, (properties, type, group, label) => {
  2683. if (!(label in newMain.mediaGroups[type][group])) {
  2684. delete update.mediaGroups[type][group][label];
  2685. }
  2686. });
  2687. };
  2688. /**
  2689. * Returns a new main manifest that is the result of merging an updated main manifest
  2690. * into the original version.
  2691. *
  2692. * @param {Object} oldMain
  2693. * The old parsed mpd object
  2694. * @param {Object} newMain
  2695. * The updated parsed mpd object
  2696. * @return {Object}
  2697. * A new object representing the original main manifest with the updated media
  2698. * playlists merged in
  2699. */
  2700. const updateMain = (oldMain, newMain, sidxMapping) => {
  2701. let noChanges = true;
  2702. let update = merge(oldMain, {
  2703. // These are top level properties that can be updated
  2704. duration: newMain.duration,
  2705. minimumUpdatePeriod: newMain.minimumUpdatePeriod,
  2706. timelineStarts: newMain.timelineStarts
  2707. }); // First update the playlists in playlist list
  2708. for (let i = 0; i < newMain.playlists.length; i++) {
  2709. const playlist = newMain.playlists[i];
  2710. if (playlist.sidx) {
  2711. const sidxKey = mpdParser.generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  2712. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  2713. mpdParser.addSidxSegmentsToPlaylist(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  2714. }
  2715. }
  2716. const playlistUpdate = updateMain$1(update, playlist, dashPlaylistUnchanged);
  2717. if (playlistUpdate) {
  2718. update = playlistUpdate;
  2719. noChanges = false;
  2720. }
  2721. } // Then update media group playlists
  2722. forEachMediaGroup(newMain, (properties, type, group, label) => {
  2723. if (properties.playlists && properties.playlists.length) {
  2724. const id = properties.playlists[0].id;
  2725. const playlistUpdate = updateMain$1(update, properties.playlists[0], dashPlaylistUnchanged);
  2726. if (playlistUpdate) {
  2727. update = playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  2728. if (!(label in update.mediaGroups[type][group])) {
  2729. update.mediaGroups[type][group][label] = properties;
  2730. } // update the playlist reference within media groups
  2731. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  2732. noChanges = false;
  2733. }
  2734. }
  2735. }); // remove mediaGroup labels and references that no longer exist in the newMain
  2736. removeOldMediaGroupLabels(update, newMain);
  2737. if (newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  2738. noChanges = false;
  2739. }
  2740. if (noChanges) {
  2741. return null;
  2742. }
  2743. return update;
  2744. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  2745. // If the SIDXs have maps, the two maps should match,
  2746. // both `a` and `b` missing SIDXs is considered matching.
  2747. // If `a` or `b` but not both have a map, they aren't matching.
  2748. const equivalentSidx = (a, b) => {
  2749. const neitherMap = Boolean(!a.map && !b.map);
  2750. const equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  2751. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  2752. }; // exported for testing
  2753. const compareSidxEntry = (playlists, oldSidxMapping) => {
  2754. const newSidxMapping = {};
  2755. for (const id in playlists) {
  2756. const playlist = playlists[id];
  2757. const currentSidxInfo = playlist.sidx;
  2758. if (currentSidxInfo) {
  2759. const key = mpdParser.generateSidxKey(currentSidxInfo);
  2760. if (!oldSidxMapping[key]) {
  2761. break;
  2762. }
  2763. const savedSidxInfo = oldSidxMapping[key].sidxInfo;
  2764. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  2765. newSidxMapping[key] = oldSidxMapping[key];
  2766. }
  2767. }
  2768. }
  2769. return newSidxMapping;
  2770. };
  2771. /**
  2772. * A function that filters out changed items as they need to be requested separately.
  2773. *
  2774. * The method is exported for testing
  2775. *
  2776. * @param {Object} main the parsed mpd XML returned via mpd-parser
  2777. * @param {Object} oldSidxMapping the SIDX to compare against
  2778. */
  2779. const filterChangedSidxMappings = (main, oldSidxMapping) => {
  2780. const videoSidx = compareSidxEntry(main.playlists, oldSidxMapping);
  2781. let mediaGroupSidx = videoSidx;
  2782. forEachMediaGroup(main, (properties, mediaType, groupKey, labelKey) => {
  2783. if (properties.playlists && properties.playlists.length) {
  2784. const playlists = properties.playlists;
  2785. mediaGroupSidx = merge(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  2786. }
  2787. });
  2788. return mediaGroupSidx;
  2789. };
  2790. class DashPlaylistLoader extends EventTarget {
  2791. // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  2792. // playlist loader setups from media groups will expect to be able to pass a playlist
  2793. // (since there aren't external URLs to media playlists with DASH)
  2794. constructor(srcUrlOrPlaylist, vhs, options = {}, mainPlaylistLoader) {
  2795. super();
  2796. this.mainPlaylistLoader_ = mainPlaylistLoader || this;
  2797. if (!mainPlaylistLoader) {
  2798. this.isMain_ = true;
  2799. }
  2800. const {
  2801. withCredentials = false
  2802. } = options;
  2803. this.vhs_ = vhs;
  2804. this.withCredentials = withCredentials;
  2805. if (!srcUrlOrPlaylist) {
  2806. throw new Error('A non-empty playlist URL or object is required');
  2807. } // event naming?
  2808. this.on('minimumUpdatePeriod', () => {
  2809. this.refreshXml_();
  2810. }); // live playlist staleness timeout
  2811. this.on('mediaupdatetimeout', () => {
  2812. this.refreshMedia_(this.media().id);
  2813. });
  2814. this.state = 'HAVE_NOTHING';
  2815. this.loadedPlaylists_ = {};
  2816. this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  2817. // The mainPlaylistLoader will be created with a string
  2818. if (this.isMain_) {
  2819. this.mainPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  2820. // once multi-period is refactored
  2821. this.mainPlaylistLoader_.sidxMapping_ = {};
  2822. } else {
  2823. this.childPlaylist_ = srcUrlOrPlaylist;
  2824. }
  2825. }
  2826. requestErrored_(err, request, startingState) {
  2827. // disposed
  2828. if (!this.request) {
  2829. return true;
  2830. } // pending request is cleared
  2831. this.request = null;
  2832. if (err) {
  2833. // use the provided error object or create one
  2834. // based on the request/response
  2835. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  2836. status: request.status,
  2837. message: 'DASH request error at URL: ' + request.uri,
  2838. response: request.response,
  2839. // MEDIA_ERR_NETWORK
  2840. code: 2
  2841. };
  2842. if (startingState) {
  2843. this.state = startingState;
  2844. }
  2845. this.trigger('error');
  2846. return true;
  2847. }
  2848. }
  2849. /**
  2850. * Verify that the container of the sidx segment can be parsed
  2851. * and if it can, get and parse that segment.
  2852. */
  2853. addSidxSegments_(playlist, startingState, cb) {
  2854. const sidxKey = playlist.sidx && mpdParser.generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  2855. if (!playlist.sidx || !sidxKey || this.mainPlaylistLoader_.sidxMapping_[sidxKey]) {
  2856. // keep this function async
  2857. this.mediaRequest_ = window__default["default"].setTimeout(() => cb(false), 0);
  2858. return;
  2859. } // resolve the segment URL relative to the playlist
  2860. const uri = resolveManifestRedirect(playlist.sidx.resolvedUri);
  2861. const fin = (err, request) => {
  2862. if (this.requestErrored_(err, request, startingState)) {
  2863. return;
  2864. }
  2865. const sidxMapping = this.mainPlaylistLoader_.sidxMapping_;
  2866. let sidx;
  2867. try {
  2868. sidx = parseSidx__default["default"](byteHelpers.toUint8(request.response).subarray(8));
  2869. } catch (e) {
  2870. // sidx parsing failed.
  2871. this.requestErrored_(e, request, startingState);
  2872. return;
  2873. }
  2874. sidxMapping[sidxKey] = {
  2875. sidxInfo: playlist.sidx,
  2876. sidx
  2877. };
  2878. mpdParser.addSidxSegmentsToPlaylist(playlist, sidx, playlist.sidx.resolvedUri);
  2879. return cb(true);
  2880. };
  2881. this.request = containerRequest(uri, this.vhs_.xhr, (err, request, container, bytes) => {
  2882. if (err) {
  2883. return fin(err, request);
  2884. }
  2885. if (!container || container !== 'mp4') {
  2886. return fin({
  2887. status: request.status,
  2888. message: `Unsupported ${container || 'unknown'} container type for sidx segment at URL: ${uri}`,
  2889. // response is just bytes in this case
  2890. // but we really don't want to return that.
  2891. response: '',
  2892. playlist,
  2893. internal: true,
  2894. playlistExclusionDuration: Infinity,
  2895. // MEDIA_ERR_NETWORK
  2896. code: 2
  2897. }, request);
  2898. } // if we already downloaded the sidx bytes in the container request, use them
  2899. const {
  2900. offset,
  2901. length
  2902. } = playlist.sidx.byterange;
  2903. if (bytes.length >= length + offset) {
  2904. return fin(err, {
  2905. response: bytes.subarray(offset, offset + length),
  2906. status: request.status,
  2907. uri: request.uri
  2908. });
  2909. } // otherwise request sidx bytes
  2910. this.request = this.vhs_.xhr({
  2911. uri,
  2912. responseType: 'arraybuffer',
  2913. headers: segmentXhrHeaders({
  2914. byterange: playlist.sidx.byterange
  2915. })
  2916. }, fin);
  2917. });
  2918. }
  2919. dispose() {
  2920. this.trigger('dispose');
  2921. this.stopRequest();
  2922. this.loadedPlaylists_ = {};
  2923. window__default["default"].clearTimeout(this.minimumUpdatePeriodTimeout_);
  2924. window__default["default"].clearTimeout(this.mediaRequest_);
  2925. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  2926. this.mediaUpdateTimeout = null;
  2927. this.mediaRequest_ = null;
  2928. this.minimumUpdatePeriodTimeout_ = null;
  2929. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  2930. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  2931. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  2932. }
  2933. this.off();
  2934. }
  2935. hasPendingRequest() {
  2936. return this.request || this.mediaRequest_;
  2937. }
  2938. stopRequest() {
  2939. if (this.request) {
  2940. const oldRequest = this.request;
  2941. this.request = null;
  2942. oldRequest.onreadystatechange = null;
  2943. oldRequest.abort();
  2944. }
  2945. }
  2946. media(playlist) {
  2947. // getter
  2948. if (!playlist) {
  2949. return this.media_;
  2950. } // setter
  2951. if (this.state === 'HAVE_NOTHING') {
  2952. throw new Error('Cannot switch media playlist from ' + this.state);
  2953. }
  2954. const startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  2955. if (typeof playlist === 'string') {
  2956. if (!this.mainPlaylistLoader_.main.playlists[playlist]) {
  2957. throw new Error('Unknown playlist URI: ' + playlist);
  2958. }
  2959. playlist = this.mainPlaylistLoader_.main.playlists[playlist];
  2960. }
  2961. const mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  2962. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  2963. this.state = 'HAVE_METADATA';
  2964. this.media_ = playlist; // trigger media change if the active media has been updated
  2965. if (mediaChange) {
  2966. this.trigger('mediachanging');
  2967. this.trigger('mediachange');
  2968. }
  2969. return;
  2970. } // switching to the active playlist is a no-op
  2971. if (!mediaChange) {
  2972. return;
  2973. } // switching from an already loaded playlist
  2974. if (this.media_) {
  2975. this.trigger('mediachanging');
  2976. }
  2977. this.addSidxSegments_(playlist, startingState, sidxChanged => {
  2978. // everything is ready just continue to haveMetadata
  2979. this.haveMetadata({
  2980. startingState,
  2981. playlist
  2982. });
  2983. });
  2984. }
  2985. haveMetadata({
  2986. startingState,
  2987. playlist
  2988. }) {
  2989. this.state = 'HAVE_METADATA';
  2990. this.loadedPlaylists_[playlist.id] = playlist;
  2991. this.mediaRequest_ = null; // This will trigger loadedplaylist
  2992. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  2993. // to resolve setup of media groups
  2994. if (startingState === 'HAVE_MAIN_MANIFEST') {
  2995. this.trigger('loadedmetadata');
  2996. } else {
  2997. // trigger media change if the active media has been updated
  2998. this.trigger('mediachange');
  2999. }
  3000. }
  3001. pause() {
  3002. if (this.mainPlaylistLoader_.createMupOnMedia_) {
  3003. this.off('loadedmetadata', this.mainPlaylistLoader_.createMupOnMedia_);
  3004. this.mainPlaylistLoader_.createMupOnMedia_ = null;
  3005. }
  3006. this.stopRequest();
  3007. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  3008. this.mediaUpdateTimeout = null;
  3009. if (this.isMain_) {
  3010. window__default["default"].clearTimeout(this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_);
  3011. this.mainPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  3012. }
  3013. if (this.state === 'HAVE_NOTHING') {
  3014. // If we pause the loader before any data has been retrieved, its as if we never
  3015. // started, so reset to an unstarted state.
  3016. this.started = false;
  3017. }
  3018. }
  3019. load(isFinalRendition) {
  3020. window__default["default"].clearTimeout(this.mediaUpdateTimeout);
  3021. this.mediaUpdateTimeout = null;
  3022. const media = this.media();
  3023. if (isFinalRendition) {
  3024. const delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  3025. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => this.load(), delay);
  3026. return;
  3027. } // because the playlists are internal to the manifest, load should either load the
  3028. // main manifest, or do nothing but trigger an event
  3029. if (!this.started) {
  3030. this.start();
  3031. return;
  3032. }
  3033. if (media && !media.endList) {
  3034. // Check to see if this is the main loader and the MUP was cleared (this happens
  3035. // when the loader was paused). `media` should be set at this point since one is always
  3036. // set during `start()`.
  3037. if (this.isMain_ && !this.minimumUpdatePeriodTimeout_) {
  3038. // Trigger minimumUpdatePeriod to refresh the main manifest
  3039. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  3040. this.updateMinimumUpdatePeriodTimeout_();
  3041. }
  3042. this.trigger('mediaupdatetimeout');
  3043. } else {
  3044. this.trigger('loadedplaylist');
  3045. }
  3046. }
  3047. start() {
  3048. this.started = true; // We don't need to request the main manifest again
  3049. // Call this asynchronously to match the xhr request behavior below
  3050. if (!this.isMain_) {
  3051. this.mediaRequest_ = window__default["default"].setTimeout(() => this.haveMain_(), 0);
  3052. return;
  3053. }
  3054. this.requestMain_((req, mainChanged) => {
  3055. this.haveMain_();
  3056. if (!this.hasPendingRequest() && !this.media_) {
  3057. this.media(this.mainPlaylistLoader_.main.playlists[0]);
  3058. }
  3059. });
  3060. }
  3061. requestMain_(cb) {
  3062. this.request = this.vhs_.xhr({
  3063. uri: this.mainPlaylistLoader_.srcUrl,
  3064. withCredentials: this.withCredentials
  3065. }, (error, req) => {
  3066. if (this.requestErrored_(error, req)) {
  3067. if (this.state === 'HAVE_NOTHING') {
  3068. this.started = false;
  3069. }
  3070. return;
  3071. }
  3072. const mainChanged = req.responseText !== this.mainPlaylistLoader_.mainXml_;
  3073. this.mainPlaylistLoader_.mainXml_ = req.responseText;
  3074. if (req.responseHeaders && req.responseHeaders.date) {
  3075. this.mainLoaded_ = Date.parse(req.responseHeaders.date);
  3076. } else {
  3077. this.mainLoaded_ = Date.now();
  3078. }
  3079. this.mainPlaylistLoader_.srcUrl = resolveManifestRedirect(this.mainPlaylistLoader_.srcUrl, req);
  3080. if (mainChanged) {
  3081. this.handleMain_();
  3082. this.syncClientServerClock_(() => {
  3083. return cb(req, mainChanged);
  3084. });
  3085. return;
  3086. }
  3087. return cb(req, mainChanged);
  3088. });
  3089. }
  3090. /**
  3091. * Parses the main xml for UTCTiming node to sync the client clock to the server
  3092. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  3093. *
  3094. * @param {Function} done
  3095. * Function to call when clock sync has completed
  3096. */
  3097. syncClientServerClock_(done) {
  3098. const utcTiming = mpdParser.parseUTCTiming(this.mainPlaylistLoader_.mainXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  3099. // server clock
  3100. if (utcTiming === null) {
  3101. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3102. return done();
  3103. }
  3104. if (utcTiming.method === 'DIRECT') {
  3105. this.mainPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  3106. return done();
  3107. }
  3108. this.request = this.vhs_.xhr({
  3109. uri: resolveUrl(this.mainPlaylistLoader_.srcUrl, utcTiming.value),
  3110. method: utcTiming.method,
  3111. withCredentials: this.withCredentials
  3112. }, (error, req) => {
  3113. // disposed
  3114. if (!this.request) {
  3115. return;
  3116. }
  3117. if (error) {
  3118. // sync request failed, fall back to using date header from mpd
  3119. // TODO: log warning
  3120. this.mainPlaylistLoader_.clientOffset_ = this.mainLoaded_ - Date.now();
  3121. return done();
  3122. }
  3123. let serverTime;
  3124. if (utcTiming.method === 'HEAD') {
  3125. if (!req.responseHeaders || !req.responseHeaders.date) {
  3126. // expected date header not preset, fall back to using date header from mpd
  3127. // TODO: log warning
  3128. serverTime = this.mainLoaded_;
  3129. } else {
  3130. serverTime = Date.parse(req.responseHeaders.date);
  3131. }
  3132. } else {
  3133. serverTime = Date.parse(req.responseText);
  3134. }
  3135. this.mainPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  3136. done();
  3137. });
  3138. }
  3139. haveMain_() {
  3140. this.state = 'HAVE_MAIN_MANIFEST';
  3141. if (this.isMain_) {
  3142. // We have the main playlist at this point, so
  3143. // trigger this to allow PlaylistController
  3144. // to make an initial playlist selection
  3145. this.trigger('loadedplaylist');
  3146. } else if (!this.media_) {
  3147. // no media playlist was specifically selected so select
  3148. // the one the child playlist loader was created with
  3149. this.media(this.childPlaylist_);
  3150. }
  3151. }
  3152. handleMain_() {
  3153. // clear media request
  3154. this.mediaRequest_ = null;
  3155. const oldMain = this.mainPlaylistLoader_.main;
  3156. let newMain = parseMainXml({
  3157. mainXml: this.mainPlaylistLoader_.mainXml_,
  3158. srcUrl: this.mainPlaylistLoader_.srcUrl,
  3159. clientOffset: this.mainPlaylistLoader_.clientOffset_,
  3160. sidxMapping: this.mainPlaylistLoader_.sidxMapping_,
  3161. previousManifest: oldMain
  3162. }); // if we have an old main to compare the new main against
  3163. if (oldMain) {
  3164. newMain = updateMain(oldMain, newMain, this.mainPlaylistLoader_.sidxMapping_);
  3165. } // only update main if we have a new main
  3166. this.mainPlaylistLoader_.main = newMain ? newMain : oldMain;
  3167. const location = this.mainPlaylistLoader_.main.locations && this.mainPlaylistLoader_.main.locations[0];
  3168. if (location && location !== this.mainPlaylistLoader_.srcUrl) {
  3169. this.mainPlaylistLoader_.srcUrl = location;
  3170. }
  3171. if (!oldMain || newMain && newMain.minimumUpdatePeriod !== oldMain.minimumUpdatePeriod) {
  3172. this.updateMinimumUpdatePeriodTimeout_();
  3173. }
  3174. return Boolean(newMain);
  3175. }
  3176. updateMinimumUpdatePeriodTimeout_() {
  3177. const mpl = this.mainPlaylistLoader_; // cancel any pending creation of mup on media
  3178. // a new one will be added if needed.
  3179. if (mpl.createMupOnMedia_) {
  3180. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  3181. mpl.createMupOnMedia_ = null;
  3182. } // clear any pending timeouts
  3183. if (mpl.minimumUpdatePeriodTimeout_) {
  3184. window__default["default"].clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  3185. mpl.minimumUpdatePeriodTimeout_ = null;
  3186. }
  3187. let mup = mpl.main && mpl.main.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  3188. // MPD has no future validity, so a new one will need to be acquired when new
  3189. // media segments are to be made available. Thus, we use the target duration
  3190. // in this case
  3191. if (mup === 0) {
  3192. if (mpl.media()) {
  3193. mup = mpl.media().targetDuration * 1000;
  3194. } else {
  3195. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  3196. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  3197. }
  3198. } // if minimumUpdatePeriod is invalid or <= zero, which
  3199. // can happen when a live video becomes VOD. skip timeout
  3200. // creation.
  3201. if (typeof mup !== 'number' || mup <= 0) {
  3202. if (mup < 0) {
  3203. this.logger_(`found invalid minimumUpdatePeriod of ${mup}, not setting a timeout`);
  3204. }
  3205. return;
  3206. }
  3207. this.createMUPTimeout_(mup);
  3208. }
  3209. createMUPTimeout_(mup) {
  3210. const mpl = this.mainPlaylistLoader_;
  3211. mpl.minimumUpdatePeriodTimeout_ = window__default["default"].setTimeout(() => {
  3212. mpl.minimumUpdatePeriodTimeout_ = null;
  3213. mpl.trigger('minimumUpdatePeriod');
  3214. mpl.createMUPTimeout_(mup);
  3215. }, mup);
  3216. }
  3217. /**
  3218. * Sends request to refresh the main xml and updates the parsed main manifest
  3219. */
  3220. refreshXml_() {
  3221. this.requestMain_((req, mainChanged) => {
  3222. if (!mainChanged) {
  3223. return;
  3224. }
  3225. if (this.media_) {
  3226. this.media_ = this.mainPlaylistLoader_.main.playlists[this.media_.id];
  3227. } // This will filter out updated sidx info from the mapping
  3228. this.mainPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.sidxMapping_);
  3229. this.addSidxSegments_(this.media(), this.state, sidxChanged => {
  3230. // TODO: do we need to reload the current playlist?
  3231. this.refreshMedia_(this.media().id);
  3232. });
  3233. });
  3234. }
  3235. /**
  3236. * Refreshes the media playlist by re-parsing the main xml and updating playlist
  3237. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  3238. * from the main loader.
  3239. */
  3240. refreshMedia_(mediaID) {
  3241. if (!mediaID) {
  3242. throw new Error('refreshMedia_ must take a media id');
  3243. } // for main we have to reparse the main xml
  3244. // to re-create segments based on current timing values
  3245. // which may change media. We only skip updating the main manifest
  3246. // if this is the first time this.media_ is being set.
  3247. // as main was just parsed in that case.
  3248. if (this.media_ && this.isMain_) {
  3249. this.handleMain_();
  3250. }
  3251. const playlists = this.mainPlaylistLoader_.main.playlists;
  3252. const mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  3253. if (mediaChanged) {
  3254. this.media_ = playlists[mediaID];
  3255. } else {
  3256. this.trigger('playlistunchanged');
  3257. }
  3258. if (!this.mediaUpdateTimeout) {
  3259. const createMediaUpdateTimeout = () => {
  3260. if (this.media().endList) {
  3261. return;
  3262. }
  3263. this.mediaUpdateTimeout = window__default["default"].setTimeout(() => {
  3264. this.trigger('mediaupdatetimeout');
  3265. createMediaUpdateTimeout();
  3266. }, refreshDelay(this.media(), Boolean(mediaChanged)));
  3267. };
  3268. createMediaUpdateTimeout();
  3269. }
  3270. this.trigger('loadedplaylist');
  3271. }
  3272. }
  3273. var Config = {
  3274. GOAL_BUFFER_LENGTH: 30,
  3275. MAX_GOAL_BUFFER_LENGTH: 60,
  3276. BACK_BUFFER_LENGTH: 30,
  3277. GOAL_BUFFER_LENGTH_RATE: 1,
  3278. // 0.5 MB/s
  3279. INITIAL_BANDWIDTH: 4194304,
  3280. // A fudge factor to apply to advertised playlist bitrates to account for
  3281. // temporary flucations in client bandwidth
  3282. BANDWIDTH_VARIANCE: 1.2,
  3283. // How much of the buffer must be filled before we consider upswitching
  3284. BUFFER_LOW_WATER_LINE: 0,
  3285. MAX_BUFFER_LOW_WATER_LINE: 30,
  3286. // TODO: Remove this when experimentalBufferBasedABR is removed
  3287. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  3288. BUFFER_LOW_WATER_LINE_RATE: 1,
  3289. // If the buffer is greater than the high water line, we won't switch down
  3290. BUFFER_HIGH_WATER_LINE: 30
  3291. };
  3292. const stringToArrayBuffer = string => {
  3293. const view = new Uint8Array(new ArrayBuffer(string.length));
  3294. for (let i = 0; i < string.length; i++) {
  3295. view[i] = string.charCodeAt(i);
  3296. }
  3297. return view.buffer;
  3298. };
  3299. /* global Blob, BlobBuilder, Worker */
  3300. // unify worker interface
  3301. const browserWorkerPolyFill = function (workerObj) {
  3302. // node only supports on/off
  3303. workerObj.on = workerObj.addEventListener;
  3304. workerObj.off = workerObj.removeEventListener;
  3305. return workerObj;
  3306. };
  3307. const createObjectURL = function (str) {
  3308. try {
  3309. return URL.createObjectURL(new Blob([str], {
  3310. type: 'application/javascript'
  3311. }));
  3312. } catch (e) {
  3313. const blob = new BlobBuilder();
  3314. blob.append(str);
  3315. return URL.createObjectURL(blob.getBlob());
  3316. }
  3317. };
  3318. const factory = function (code) {
  3319. return function () {
  3320. const objectUrl = createObjectURL(code);
  3321. const worker = browserWorkerPolyFill(new Worker(objectUrl));
  3322. worker.objURL = objectUrl;
  3323. const terminate = worker.terminate;
  3324. worker.on = worker.addEventListener;
  3325. worker.off = worker.removeEventListener;
  3326. worker.terminate = function () {
  3327. URL.revokeObjectURL(objectUrl);
  3328. return terminate.call(this);
  3329. };
  3330. return worker;
  3331. };
  3332. };
  3333. const transform = function (code) {
  3334. return `var browserWorkerPolyFill = ${browserWorkerPolyFill.toString()};\n` + 'browserWorkerPolyFill(self);\n' + code;
  3335. };
  3336. const getWorkerString = function (fn) {
  3337. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  3338. };
  3339. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  3340. const workerCode$1 = transform(getWorkerString(function () {
  3341. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  3342. /**
  3343. * mux.js
  3344. *
  3345. * Copyright (c) Brightcove
  3346. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3347. *
  3348. * A lightweight readable stream implemention that handles event dispatching.
  3349. * Objects that inherit from streams should call init in their constructors.
  3350. */
  3351. var Stream$8 = function () {
  3352. this.init = function () {
  3353. var listeners = {};
  3354. /**
  3355. * Add a listener for a specified event type.
  3356. * @param type {string} the event name
  3357. * @param listener {function} the callback to be invoked when an event of
  3358. * the specified type occurs
  3359. */
  3360. this.on = function (type, listener) {
  3361. if (!listeners[type]) {
  3362. listeners[type] = [];
  3363. }
  3364. listeners[type] = listeners[type].concat(listener);
  3365. };
  3366. /**
  3367. * Remove a listener for a specified event type.
  3368. * @param type {string} the event name
  3369. * @param listener {function} a function previously registered for this
  3370. * type of event through `on`
  3371. */
  3372. this.off = function (type, listener) {
  3373. var index;
  3374. if (!listeners[type]) {
  3375. return false;
  3376. }
  3377. index = listeners[type].indexOf(listener);
  3378. listeners[type] = listeners[type].slice();
  3379. listeners[type].splice(index, 1);
  3380. return index > -1;
  3381. };
  3382. /**
  3383. * Trigger an event of the specified type on this stream. Any additional
  3384. * arguments to this function are passed as parameters to event listeners.
  3385. * @param type {string} the event name
  3386. */
  3387. this.trigger = function (type) {
  3388. var callbacks, i, length, args;
  3389. callbacks = listeners[type];
  3390. if (!callbacks) {
  3391. return;
  3392. } // Slicing the arguments on every invocation of this method
  3393. // can add a significant amount of overhead. Avoid the
  3394. // intermediate object creation for the common case of a
  3395. // single callback argument
  3396. if (arguments.length === 2) {
  3397. length = callbacks.length;
  3398. for (i = 0; i < length; ++i) {
  3399. callbacks[i].call(this, arguments[1]);
  3400. }
  3401. } else {
  3402. args = [];
  3403. i = arguments.length;
  3404. for (i = 1; i < arguments.length; ++i) {
  3405. args.push(arguments[i]);
  3406. }
  3407. length = callbacks.length;
  3408. for (i = 0; i < length; ++i) {
  3409. callbacks[i].apply(this, args);
  3410. }
  3411. }
  3412. };
  3413. /**
  3414. * Destroys the stream and cleans up.
  3415. */
  3416. this.dispose = function () {
  3417. listeners = {};
  3418. };
  3419. };
  3420. };
  3421. /**
  3422. * Forwards all `data` events on this stream to the destination stream. The
  3423. * destination stream should provide a method `push` to receive the data
  3424. * events as they arrive.
  3425. * @param destination {stream} the stream that will receive all `data` events
  3426. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  3427. * when the current stream emits a 'done' event
  3428. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  3429. */
  3430. Stream$8.prototype.pipe = function (destination) {
  3431. this.on('data', function (data) {
  3432. destination.push(data);
  3433. });
  3434. this.on('done', function (flushSource) {
  3435. destination.flush(flushSource);
  3436. });
  3437. this.on('partialdone', function (flushSource) {
  3438. destination.partialFlush(flushSource);
  3439. });
  3440. this.on('endedtimeline', function (flushSource) {
  3441. destination.endTimeline(flushSource);
  3442. });
  3443. this.on('reset', function (flushSource) {
  3444. destination.reset(flushSource);
  3445. });
  3446. return destination;
  3447. }; // Default stream functions that are expected to be overridden to perform
  3448. // actual work. These are provided by the prototype as a sort of no-op
  3449. // implementation so that we don't have to check for their existence in the
  3450. // `pipe` function above.
  3451. Stream$8.prototype.push = function (data) {
  3452. this.trigger('data', data);
  3453. };
  3454. Stream$8.prototype.flush = function (flushSource) {
  3455. this.trigger('done', flushSource);
  3456. };
  3457. Stream$8.prototype.partialFlush = function (flushSource) {
  3458. this.trigger('partialdone', flushSource);
  3459. };
  3460. Stream$8.prototype.endTimeline = function (flushSource) {
  3461. this.trigger('endedtimeline', flushSource);
  3462. };
  3463. Stream$8.prototype.reset = function (flushSource) {
  3464. this.trigger('reset', flushSource);
  3465. };
  3466. var stream = Stream$8;
  3467. var MAX_UINT32$1 = Math.pow(2, 32);
  3468. var getUint64$3 = function (uint8) {
  3469. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  3470. var value;
  3471. if (dv.getBigUint64) {
  3472. value = dv.getBigUint64(0);
  3473. if (value < Number.MAX_SAFE_INTEGER) {
  3474. return Number(value);
  3475. }
  3476. return value;
  3477. }
  3478. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  3479. };
  3480. var numbers = {
  3481. getUint64: getUint64$3,
  3482. MAX_UINT32: MAX_UINT32$1
  3483. };
  3484. /**
  3485. * mux.js
  3486. *
  3487. * Copyright (c) Brightcove
  3488. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3489. *
  3490. * Functions that generate fragmented MP4s suitable for use with Media
  3491. * Source Extensions.
  3492. */
  3493. var MAX_UINT32 = numbers.MAX_UINT32;
  3494. 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
  3495. (function () {
  3496. var i;
  3497. types = {
  3498. avc1: [],
  3499. // codingname
  3500. avcC: [],
  3501. btrt: [],
  3502. dinf: [],
  3503. dref: [],
  3504. esds: [],
  3505. ftyp: [],
  3506. hdlr: [],
  3507. mdat: [],
  3508. mdhd: [],
  3509. mdia: [],
  3510. mfhd: [],
  3511. minf: [],
  3512. moof: [],
  3513. moov: [],
  3514. mp4a: [],
  3515. // codingname
  3516. mvex: [],
  3517. mvhd: [],
  3518. pasp: [],
  3519. sdtp: [],
  3520. smhd: [],
  3521. stbl: [],
  3522. stco: [],
  3523. stsc: [],
  3524. stsd: [],
  3525. stsz: [],
  3526. stts: [],
  3527. styp: [],
  3528. tfdt: [],
  3529. tfhd: [],
  3530. traf: [],
  3531. trak: [],
  3532. trun: [],
  3533. trex: [],
  3534. tkhd: [],
  3535. vmhd: []
  3536. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  3537. // don't throw an error
  3538. if (typeof Uint8Array === 'undefined') {
  3539. return;
  3540. }
  3541. for (i in types) {
  3542. if (types.hasOwnProperty(i)) {
  3543. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  3544. }
  3545. }
  3546. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  3547. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  3548. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  3549. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  3550. 0x00, 0x00, 0x00, // flags
  3551. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3552. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3553. 0x00, 0x00, 0x00, 0x00, // reserved
  3554. 0x00, 0x00, 0x00, 0x00, // reserved
  3555. 0x00, 0x00, 0x00, 0x00, // reserved
  3556. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3557. ]);
  3558. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  3559. 0x00, 0x00, 0x00, // flags
  3560. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3561. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3562. 0x00, 0x00, 0x00, 0x00, // reserved
  3563. 0x00, 0x00, 0x00, 0x00, // reserved
  3564. 0x00, 0x00, 0x00, 0x00, // reserved
  3565. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3566. ]);
  3567. HDLR_TYPES = {
  3568. video: VIDEO_HDLR,
  3569. audio: AUDIO_HDLR
  3570. };
  3571. DREF = new Uint8Array([0x00, // version 0
  3572. 0x00, 0x00, 0x00, // flags
  3573. 0x00, 0x00, 0x00, 0x01, // entry_count
  3574. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3575. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3576. 0x00, // version 0
  3577. 0x00, 0x00, 0x01 // entry_flags
  3578. ]);
  3579. SMHD = new Uint8Array([0x00, // version
  3580. 0x00, 0x00, 0x00, // flags
  3581. 0x00, 0x00, // balance, 0 means centered
  3582. 0x00, 0x00 // reserved
  3583. ]);
  3584. STCO = new Uint8Array([0x00, // version
  3585. 0x00, 0x00, 0x00, // flags
  3586. 0x00, 0x00, 0x00, 0x00 // entry_count
  3587. ]);
  3588. STSC = STCO;
  3589. STSZ = new Uint8Array([0x00, // version
  3590. 0x00, 0x00, 0x00, // flags
  3591. 0x00, 0x00, 0x00, 0x00, // sample_size
  3592. 0x00, 0x00, 0x00, 0x00 // sample_count
  3593. ]);
  3594. STTS = STCO;
  3595. VMHD = new Uint8Array([0x00, // version
  3596. 0x00, 0x00, 0x01, // flags
  3597. 0x00, 0x00, // graphicsmode
  3598. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  3599. ]);
  3600. })();
  3601. box = function (type) {
  3602. var payload = [],
  3603. size = 0,
  3604. i,
  3605. result,
  3606. view;
  3607. for (i = 1; i < arguments.length; i++) {
  3608. payload.push(arguments[i]);
  3609. }
  3610. i = payload.length; // calculate the total size we need to allocate
  3611. while (i--) {
  3612. size += payload[i].byteLength;
  3613. }
  3614. result = new Uint8Array(size + 8);
  3615. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  3616. view.setUint32(0, result.byteLength);
  3617. result.set(type, 4); // copy the payload into the result
  3618. for (i = 0, size = 8; i < payload.length; i++) {
  3619. result.set(payload[i], size);
  3620. size += payload[i].byteLength;
  3621. }
  3622. return result;
  3623. };
  3624. dinf = function () {
  3625. return box(types.dinf, box(types.dref, DREF));
  3626. };
  3627. esds = function (track) {
  3628. return box(types.esds, new Uint8Array([0x00, // version
  3629. 0x00, 0x00, 0x00, // flags
  3630. // ES_Descriptor
  3631. 0x03, // tag, ES_DescrTag
  3632. 0x19, // length
  3633. 0x00, 0x00, // ES_ID
  3634. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  3635. // DecoderConfigDescriptor
  3636. 0x04, // tag, DecoderConfigDescrTag
  3637. 0x11, // length
  3638. 0x40, // object type
  3639. 0x15, // streamType
  3640. 0x00, 0x06, 0x00, // bufferSizeDB
  3641. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  3642. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  3643. // DecoderSpecificInfo
  3644. 0x05, // tag, DecoderSpecificInfoTag
  3645. 0x02, // length
  3646. // ISO/IEC 14496-3, AudioSpecificConfig
  3647. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  3648. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  3649. ]));
  3650. };
  3651. ftyp = function () {
  3652. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  3653. };
  3654. hdlr = function (type) {
  3655. return box(types.hdlr, HDLR_TYPES[type]);
  3656. };
  3657. mdat = function (data) {
  3658. return box(types.mdat, data);
  3659. };
  3660. mdhd = function (track) {
  3661. var result = new Uint8Array([0x00, // version 0
  3662. 0x00, 0x00, 0x00, // flags
  3663. 0x00, 0x00, 0x00, 0x02, // creation_time
  3664. 0x00, 0x00, 0x00, 0x03, // modification_time
  3665. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3666. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  3667. 0x55, 0xc4, // 'und' language (undetermined)
  3668. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  3669. // defined. The sample rate can be parsed out of an ADTS header, for
  3670. // instance.
  3671. if (track.samplerate) {
  3672. result[12] = track.samplerate >>> 24 & 0xFF;
  3673. result[13] = track.samplerate >>> 16 & 0xFF;
  3674. result[14] = track.samplerate >>> 8 & 0xFF;
  3675. result[15] = track.samplerate & 0xFF;
  3676. }
  3677. return box(types.mdhd, result);
  3678. };
  3679. mdia = function (track) {
  3680. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  3681. };
  3682. mfhd = function (sequenceNumber) {
  3683. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  3684. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  3685. ]));
  3686. };
  3687. minf = function (track) {
  3688. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  3689. };
  3690. moof = function (sequenceNumber, tracks) {
  3691. var trackFragments = [],
  3692. i = tracks.length; // build traf boxes for each track fragment
  3693. while (i--) {
  3694. trackFragments[i] = traf(tracks[i]);
  3695. }
  3696. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  3697. };
  3698. /**
  3699. * Returns a movie box.
  3700. * @param tracks {array} the tracks associated with this movie
  3701. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  3702. */
  3703. moov = function (tracks) {
  3704. var i = tracks.length,
  3705. boxes = [];
  3706. while (i--) {
  3707. boxes[i] = trak(tracks[i]);
  3708. }
  3709. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  3710. };
  3711. mvex = function (tracks) {
  3712. var i = tracks.length,
  3713. boxes = [];
  3714. while (i--) {
  3715. boxes[i] = trex(tracks[i]);
  3716. }
  3717. return box.apply(null, [types.mvex].concat(boxes));
  3718. };
  3719. mvhd = function (duration) {
  3720. var bytes = new Uint8Array([0x00, // version 0
  3721. 0x00, 0x00, 0x00, // flags
  3722. 0x00, 0x00, 0x00, 0x01, // creation_time
  3723. 0x00, 0x00, 0x00, 0x02, // modification_time
  3724. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  3725. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  3726. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  3727. 0x01, 0x00, // 1.0 volume
  3728. 0x00, 0x00, // reserved
  3729. 0x00, 0x00, 0x00, 0x00, // reserved
  3730. 0x00, 0x00, 0x00, 0x00, // reserved
  3731. 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
  3732. 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
  3733. 0xff, 0xff, 0xff, 0xff // next_track_ID
  3734. ]);
  3735. return box(types.mvhd, bytes);
  3736. };
  3737. sdtp = function (track) {
  3738. var samples = track.samples || [],
  3739. bytes = new Uint8Array(4 + samples.length),
  3740. flags,
  3741. i; // leave the full box header (4 bytes) all zero
  3742. // write the sample table
  3743. for (i = 0; i < samples.length; i++) {
  3744. flags = samples[i].flags;
  3745. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  3746. }
  3747. return box(types.sdtp, bytes);
  3748. };
  3749. stbl = function (track) {
  3750. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  3751. };
  3752. (function () {
  3753. var videoSample, audioSample;
  3754. stsd = function (track) {
  3755. return box(types.stsd, new Uint8Array([0x00, // version 0
  3756. 0x00, 0x00, 0x00, // flags
  3757. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  3758. };
  3759. videoSample = function (track) {
  3760. var sps = track.sps || [],
  3761. pps = track.pps || [],
  3762. sequenceParameterSets = [],
  3763. pictureParameterSets = [],
  3764. i,
  3765. avc1Box; // assemble the SPSs
  3766. for (i = 0; i < sps.length; i++) {
  3767. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  3768. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  3769. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  3770. } // assemble the PPSs
  3771. for (i = 0; i < pps.length; i++) {
  3772. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  3773. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  3774. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  3775. }
  3776. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3777. 0x00, 0x01, // data_reference_index
  3778. 0x00, 0x00, // pre_defined
  3779. 0x00, 0x00, // reserved
  3780. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  3781. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  3782. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  3783. 0x00, 0x48, 0x00, 0x00, // horizresolution
  3784. 0x00, 0x48, 0x00, 0x00, // vertresolution
  3785. 0x00, 0x00, 0x00, 0x00, // reserved
  3786. 0x00, 0x01, // frame_count
  3787. 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
  3788. 0x00, 0x18, // depth = 24
  3789. 0x11, 0x11 // pre_defined = -1
  3790. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  3791. track.profileIdc, // AVCProfileIndication
  3792. track.profileCompatibility, // profile_compatibility
  3793. track.levelIdc, // AVCLevelIndication
  3794. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  3795. ].concat([sps.length], // numOfSequenceParameterSets
  3796. sequenceParameterSets, // "SPS"
  3797. [pps.length], // numOfPictureParameterSets
  3798. pictureParameterSets // "PPS"
  3799. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  3800. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  3801. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  3802. ]))];
  3803. if (track.sarRatio) {
  3804. var hSpacing = track.sarRatio[0],
  3805. vSpacing = track.sarRatio[1];
  3806. 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])));
  3807. }
  3808. return box.apply(null, avc1Box);
  3809. };
  3810. audioSample = function (track) {
  3811. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  3812. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3813. 0x00, 0x01, // data_reference_index
  3814. // AudioSampleEntry, ISO/IEC 14496-12
  3815. 0x00, 0x00, 0x00, 0x00, // reserved
  3816. 0x00, 0x00, 0x00, 0x00, // reserved
  3817. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  3818. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  3819. 0x00, 0x00, // pre_defined
  3820. 0x00, 0x00, // reserved
  3821. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  3822. // MP4AudioSampleEntry, ISO/IEC 14496-14
  3823. ]), esds(track));
  3824. };
  3825. })();
  3826. tkhd = function (track) {
  3827. var result = new Uint8Array([0x00, // version 0
  3828. 0x00, 0x00, 0x07, // flags
  3829. 0x00, 0x00, 0x00, 0x00, // creation_time
  3830. 0x00, 0x00, 0x00, 0x00, // modification_time
  3831. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3832. 0x00, 0x00, 0x00, 0x00, // reserved
  3833. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  3834. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  3835. 0x00, 0x00, // layer
  3836. 0x00, 0x00, // alternate_group
  3837. 0x01, 0x00, // non-audio track volume
  3838. 0x00, 0x00, // reserved
  3839. 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
  3840. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  3841. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  3842. ]);
  3843. return box(types.tkhd, result);
  3844. };
  3845. /**
  3846. * Generate a track fragment (traf) box. A traf box collects metadata
  3847. * about tracks in a movie fragment (moof) box.
  3848. */
  3849. traf = function (track) {
  3850. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  3851. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  3852. 0x00, 0x00, 0x3a, // flags
  3853. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3854. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  3855. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3856. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3857. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  3858. ]));
  3859. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  3860. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  3861. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  3862. 0x00, 0x00, 0x00, // flags
  3863. // baseMediaDecodeTime
  3864. 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
  3865. // the containing moof to the first payload byte of the associated
  3866. // mdat
  3867. dataOffset = 32 + // tfhd
  3868. 20 + // tfdt
  3869. 8 + // traf header
  3870. 16 + // mfhd
  3871. 8 + // moof header
  3872. 8; // mdat header
  3873. // audio tracks require less metadata
  3874. if (track.type === 'audio') {
  3875. trackFragmentRun = trun$1(track, dataOffset);
  3876. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  3877. } // video tracks should contain an independent and disposable samples
  3878. // box (sdtp)
  3879. // generate one and adjust offsets to match
  3880. sampleDependencyTable = sdtp(track);
  3881. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  3882. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  3883. };
  3884. /**
  3885. * Generate a track box.
  3886. * @param track {object} a track definition
  3887. * @return {Uint8Array} the track box
  3888. */
  3889. trak = function (track) {
  3890. track.duration = track.duration || 0xffffffff;
  3891. return box(types.trak, tkhd(track), mdia(track));
  3892. };
  3893. trex = function (track) {
  3894. var result = new Uint8Array([0x00, // version 0
  3895. 0x00, 0x00, 0x00, // flags
  3896. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  3897. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  3898. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  3899. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  3900. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  3901. ]); // the last two bytes of default_sample_flags is the sample
  3902. // degradation priority, a hint about the importance of this sample
  3903. // relative to others. Lower the degradation priority for all sample
  3904. // types other than video.
  3905. if (track.type !== 'video') {
  3906. result[result.length - 1] = 0x00;
  3907. }
  3908. return box(types.trex, result);
  3909. };
  3910. (function () {
  3911. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  3912. // duration is present for the first sample, it will be present for
  3913. // all subsequent samples.
  3914. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  3915. trunHeader = function (samples, offset) {
  3916. var durationPresent = 0,
  3917. sizePresent = 0,
  3918. flagsPresent = 0,
  3919. compositionTimeOffset = 0; // trun flag constants
  3920. if (samples.length) {
  3921. if (samples[0].duration !== undefined) {
  3922. durationPresent = 0x1;
  3923. }
  3924. if (samples[0].size !== undefined) {
  3925. sizePresent = 0x2;
  3926. }
  3927. if (samples[0].flags !== undefined) {
  3928. flagsPresent = 0x4;
  3929. }
  3930. if (samples[0].compositionTimeOffset !== undefined) {
  3931. compositionTimeOffset = 0x8;
  3932. }
  3933. }
  3934. return [0x00, // version 0
  3935. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  3936. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  3937. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  3938. ];
  3939. };
  3940. videoTrun = function (track, offset) {
  3941. var bytesOffest, bytes, header, samples, sample, i;
  3942. samples = track.samples || [];
  3943. offset += 8 + 12 + 16 * samples.length;
  3944. header = trunHeader(samples, offset);
  3945. bytes = new Uint8Array(header.length + samples.length * 16);
  3946. bytes.set(header);
  3947. bytesOffest = header.length;
  3948. for (i = 0; i < samples.length; i++) {
  3949. sample = samples[i];
  3950. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  3951. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  3952. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  3953. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  3954. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  3955. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  3956. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  3957. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  3958. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  3959. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  3960. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  3961. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  3962. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  3963. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  3964. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  3965. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  3966. }
  3967. return box(types.trun, bytes);
  3968. };
  3969. audioTrun = function (track, offset) {
  3970. var bytes, bytesOffest, header, samples, sample, i;
  3971. samples = track.samples || [];
  3972. offset += 8 + 12 + 8 * samples.length;
  3973. header = trunHeader(samples, offset);
  3974. bytes = new Uint8Array(header.length + samples.length * 8);
  3975. bytes.set(header);
  3976. bytesOffest = header.length;
  3977. for (i = 0; i < samples.length; i++) {
  3978. sample = samples[i];
  3979. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  3980. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  3981. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  3982. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  3983. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  3984. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  3985. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  3986. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  3987. }
  3988. return box(types.trun, bytes);
  3989. };
  3990. trun$1 = function (track, offset) {
  3991. if (track.type === 'audio') {
  3992. return audioTrun(track, offset);
  3993. }
  3994. return videoTrun(track, offset);
  3995. };
  3996. })();
  3997. var mp4Generator = {
  3998. ftyp: ftyp,
  3999. mdat: mdat,
  4000. moof: moof,
  4001. moov: moov,
  4002. initSegment: function (tracks) {
  4003. var fileType = ftyp(),
  4004. movie = moov(tracks),
  4005. result;
  4006. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  4007. result.set(fileType);
  4008. result.set(movie, fileType.byteLength);
  4009. return result;
  4010. }
  4011. };
  4012. /**
  4013. * mux.js
  4014. *
  4015. * Copyright (c) Brightcove
  4016. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4017. */
  4018. // composed of the nal units that make up that frame
  4019. // Also keep track of cummulative data about the frame from the nal units such
  4020. // as the frame duration, starting pts, etc.
  4021. var groupNalsIntoFrames = function (nalUnits) {
  4022. var i,
  4023. currentNal,
  4024. currentFrame = [],
  4025. frames = []; // TODO added for LHLS, make sure this is OK
  4026. frames.byteLength = 0;
  4027. frames.nalCount = 0;
  4028. frames.duration = 0;
  4029. currentFrame.byteLength = 0;
  4030. for (i = 0; i < nalUnits.length; i++) {
  4031. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  4032. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  4033. // Since the very first nal unit is expected to be an AUD
  4034. // only push to the frames array when currentFrame is not empty
  4035. if (currentFrame.length) {
  4036. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  4037. frames.byteLength += currentFrame.byteLength;
  4038. frames.nalCount += currentFrame.length;
  4039. frames.duration += currentFrame.duration;
  4040. frames.push(currentFrame);
  4041. }
  4042. currentFrame = [currentNal];
  4043. currentFrame.byteLength = currentNal.data.byteLength;
  4044. currentFrame.pts = currentNal.pts;
  4045. currentFrame.dts = currentNal.dts;
  4046. } else {
  4047. // Specifically flag key frames for ease of use later
  4048. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  4049. currentFrame.keyFrame = true;
  4050. }
  4051. currentFrame.duration = currentNal.dts - currentFrame.dts;
  4052. currentFrame.byteLength += currentNal.data.byteLength;
  4053. currentFrame.push(currentNal);
  4054. }
  4055. } // For the last frame, use the duration of the previous frame if we
  4056. // have nothing better to go on
  4057. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  4058. currentFrame.duration = frames[frames.length - 1].duration;
  4059. } // Push the final frame
  4060. // TODO added for LHLS, make sure this is OK
  4061. frames.byteLength += currentFrame.byteLength;
  4062. frames.nalCount += currentFrame.length;
  4063. frames.duration += currentFrame.duration;
  4064. frames.push(currentFrame);
  4065. return frames;
  4066. }; // Convert an array of frames into an array of Gop with each Gop being composed
  4067. // of the frames that make up that Gop
  4068. // Also keep track of cummulative data about the Gop from the frames such as the
  4069. // Gop duration, starting pts, etc.
  4070. var groupFramesIntoGops = function (frames) {
  4071. var i,
  4072. currentFrame,
  4073. currentGop = [],
  4074. gops = []; // We must pre-set some of the values on the Gop since we
  4075. // keep running totals of these values
  4076. currentGop.byteLength = 0;
  4077. currentGop.nalCount = 0;
  4078. currentGop.duration = 0;
  4079. currentGop.pts = frames[0].pts;
  4080. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  4081. gops.byteLength = 0;
  4082. gops.nalCount = 0;
  4083. gops.duration = 0;
  4084. gops.pts = frames[0].pts;
  4085. gops.dts = frames[0].dts;
  4086. for (i = 0; i < frames.length; i++) {
  4087. currentFrame = frames[i];
  4088. if (currentFrame.keyFrame) {
  4089. // Since the very first frame is expected to be an keyframe
  4090. // only push to the gops array when currentGop is not empty
  4091. if (currentGop.length) {
  4092. gops.push(currentGop);
  4093. gops.byteLength += currentGop.byteLength;
  4094. gops.nalCount += currentGop.nalCount;
  4095. gops.duration += currentGop.duration;
  4096. }
  4097. currentGop = [currentFrame];
  4098. currentGop.nalCount = currentFrame.length;
  4099. currentGop.byteLength = currentFrame.byteLength;
  4100. currentGop.pts = currentFrame.pts;
  4101. currentGop.dts = currentFrame.dts;
  4102. currentGop.duration = currentFrame.duration;
  4103. } else {
  4104. currentGop.duration += currentFrame.duration;
  4105. currentGop.nalCount += currentFrame.length;
  4106. currentGop.byteLength += currentFrame.byteLength;
  4107. currentGop.push(currentFrame);
  4108. }
  4109. }
  4110. if (gops.length && currentGop.duration <= 0) {
  4111. currentGop.duration = gops[gops.length - 1].duration;
  4112. }
  4113. gops.byteLength += currentGop.byteLength;
  4114. gops.nalCount += currentGop.nalCount;
  4115. gops.duration += currentGop.duration; // push the final Gop
  4116. gops.push(currentGop);
  4117. return gops;
  4118. };
  4119. /*
  4120. * Search for the first keyframe in the GOPs and throw away all frames
  4121. * until that keyframe. Then extend the duration of the pulled keyframe
  4122. * and pull the PTS and DTS of the keyframe so that it covers the time
  4123. * range of the frames that were disposed.
  4124. *
  4125. * @param {Array} gops video GOPs
  4126. * @returns {Array} modified video GOPs
  4127. */
  4128. var extendFirstKeyFrame = function (gops) {
  4129. var currentGop;
  4130. if (!gops[0][0].keyFrame && gops.length > 1) {
  4131. // Remove the first GOP
  4132. currentGop = gops.shift();
  4133. gops.byteLength -= currentGop.byteLength;
  4134. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  4135. // first gop to cover the time period of the
  4136. // frames we just removed
  4137. gops[0][0].dts = currentGop.dts;
  4138. gops[0][0].pts = currentGop.pts;
  4139. gops[0][0].duration += currentGop.duration;
  4140. }
  4141. return gops;
  4142. };
  4143. /**
  4144. * Default sample object
  4145. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  4146. */
  4147. var createDefaultSample = function () {
  4148. return {
  4149. size: 0,
  4150. flags: {
  4151. isLeading: 0,
  4152. dependsOn: 1,
  4153. isDependedOn: 0,
  4154. hasRedundancy: 0,
  4155. degradationPriority: 0,
  4156. isNonSyncSample: 1
  4157. }
  4158. };
  4159. };
  4160. /*
  4161. * Collates information from a video frame into an object for eventual
  4162. * entry into an MP4 sample table.
  4163. *
  4164. * @param {Object} frame the video frame
  4165. * @param {Number} dataOffset the byte offset to position the sample
  4166. * @return {Object} object containing sample table info for a frame
  4167. */
  4168. var sampleForFrame = function (frame, dataOffset) {
  4169. var sample = createDefaultSample();
  4170. sample.dataOffset = dataOffset;
  4171. sample.compositionTimeOffset = frame.pts - frame.dts;
  4172. sample.duration = frame.duration;
  4173. sample.size = 4 * frame.length; // Space for nal unit size
  4174. sample.size += frame.byteLength;
  4175. if (frame.keyFrame) {
  4176. sample.flags.dependsOn = 2;
  4177. sample.flags.isNonSyncSample = 0;
  4178. }
  4179. return sample;
  4180. }; // generate the track's sample table from an array of gops
  4181. var generateSampleTable$1 = function (gops, baseDataOffset) {
  4182. var h,
  4183. i,
  4184. sample,
  4185. currentGop,
  4186. currentFrame,
  4187. dataOffset = baseDataOffset || 0,
  4188. samples = [];
  4189. for (h = 0; h < gops.length; h++) {
  4190. currentGop = gops[h];
  4191. for (i = 0; i < currentGop.length; i++) {
  4192. currentFrame = currentGop[i];
  4193. sample = sampleForFrame(currentFrame, dataOffset);
  4194. dataOffset += sample.size;
  4195. samples.push(sample);
  4196. }
  4197. }
  4198. return samples;
  4199. }; // generate the track's raw mdat data from an array of gops
  4200. var concatenateNalData = function (gops) {
  4201. var h,
  4202. i,
  4203. j,
  4204. currentGop,
  4205. currentFrame,
  4206. currentNal,
  4207. dataOffset = 0,
  4208. nalsByteLength = gops.byteLength,
  4209. numberOfNals = gops.nalCount,
  4210. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4211. data = new Uint8Array(totalByteLength),
  4212. view = new DataView(data.buffer); // For each Gop..
  4213. for (h = 0; h < gops.length; h++) {
  4214. currentGop = gops[h]; // For each Frame..
  4215. for (i = 0; i < currentGop.length; i++) {
  4216. currentFrame = currentGop[i]; // For each NAL..
  4217. for (j = 0; j < currentFrame.length; j++) {
  4218. currentNal = currentFrame[j];
  4219. view.setUint32(dataOffset, currentNal.data.byteLength);
  4220. dataOffset += 4;
  4221. data.set(currentNal.data, dataOffset);
  4222. dataOffset += currentNal.data.byteLength;
  4223. }
  4224. }
  4225. }
  4226. return data;
  4227. }; // generate the track's sample table from a frame
  4228. var generateSampleTableForFrame = function (frame, baseDataOffset) {
  4229. var sample,
  4230. dataOffset = baseDataOffset || 0,
  4231. samples = [];
  4232. sample = sampleForFrame(frame, dataOffset);
  4233. samples.push(sample);
  4234. return samples;
  4235. }; // generate the track's raw mdat data from a frame
  4236. var concatenateNalDataForFrame = function (frame) {
  4237. var i,
  4238. currentNal,
  4239. dataOffset = 0,
  4240. nalsByteLength = frame.byteLength,
  4241. numberOfNals = frame.length,
  4242. totalByteLength = nalsByteLength + 4 * numberOfNals,
  4243. data = new Uint8Array(totalByteLength),
  4244. view = new DataView(data.buffer); // For each NAL..
  4245. for (i = 0; i < frame.length; i++) {
  4246. currentNal = frame[i];
  4247. view.setUint32(dataOffset, currentNal.data.byteLength);
  4248. dataOffset += 4;
  4249. data.set(currentNal.data, dataOffset);
  4250. dataOffset += currentNal.data.byteLength;
  4251. }
  4252. return data;
  4253. };
  4254. var frameUtils$1 = {
  4255. groupNalsIntoFrames: groupNalsIntoFrames,
  4256. groupFramesIntoGops: groupFramesIntoGops,
  4257. extendFirstKeyFrame: extendFirstKeyFrame,
  4258. generateSampleTable: generateSampleTable$1,
  4259. concatenateNalData: concatenateNalData,
  4260. generateSampleTableForFrame: generateSampleTableForFrame,
  4261. concatenateNalDataForFrame: concatenateNalDataForFrame
  4262. };
  4263. /**
  4264. * mux.js
  4265. *
  4266. * Copyright (c) Brightcove
  4267. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4268. */
  4269. var highPrefix = [33, 16, 5, 32, 164, 27];
  4270. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  4271. var zeroFill = function (count) {
  4272. var a = [];
  4273. while (count--) {
  4274. a.push(0);
  4275. }
  4276. return a;
  4277. };
  4278. var makeTable = function (metaTable) {
  4279. return Object.keys(metaTable).reduce(function (obj, key) {
  4280. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  4281. return arr.concat(part);
  4282. }, []));
  4283. return obj;
  4284. }, {});
  4285. };
  4286. var silence;
  4287. var silence_1 = function () {
  4288. if (!silence) {
  4289. // Frames-of-silence to use for filling in missing AAC frames
  4290. var coneOfSilence = {
  4291. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  4292. 88200: [highPrefix, [231], zeroFill(170), [56]],
  4293. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  4294. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  4295. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  4296. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  4297. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  4298. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  4299. 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]],
  4300. 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]],
  4301. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  4302. };
  4303. silence = makeTable(coneOfSilence);
  4304. }
  4305. return silence;
  4306. };
  4307. /**
  4308. * mux.js
  4309. *
  4310. * Copyright (c) Brightcove
  4311. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4312. */
  4313. var ONE_SECOND_IN_TS$4 = 90000,
  4314. // 90kHz clock
  4315. secondsToVideoTs,
  4316. secondsToAudioTs,
  4317. videoTsToSeconds,
  4318. audioTsToSeconds,
  4319. audioTsToVideoTs,
  4320. videoTsToAudioTs,
  4321. metadataTsToSeconds;
  4322. secondsToVideoTs = function (seconds) {
  4323. return seconds * ONE_SECOND_IN_TS$4;
  4324. };
  4325. secondsToAudioTs = function (seconds, sampleRate) {
  4326. return seconds * sampleRate;
  4327. };
  4328. videoTsToSeconds = function (timestamp) {
  4329. return timestamp / ONE_SECOND_IN_TS$4;
  4330. };
  4331. audioTsToSeconds = function (timestamp, sampleRate) {
  4332. return timestamp / sampleRate;
  4333. };
  4334. audioTsToVideoTs = function (timestamp, sampleRate) {
  4335. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  4336. };
  4337. videoTsToAudioTs = function (timestamp, sampleRate) {
  4338. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  4339. };
  4340. /**
  4341. * Adjust ID3 tag or caption timing information by the timeline pts values
  4342. * (if keepOriginalTimestamps is false) and convert to seconds
  4343. */
  4344. metadataTsToSeconds = function (timestamp, timelineStartPts, keepOriginalTimestamps) {
  4345. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  4346. };
  4347. var clock$2 = {
  4348. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  4349. secondsToVideoTs: secondsToVideoTs,
  4350. secondsToAudioTs: secondsToAudioTs,
  4351. videoTsToSeconds: videoTsToSeconds,
  4352. audioTsToSeconds: audioTsToSeconds,
  4353. audioTsToVideoTs: audioTsToVideoTs,
  4354. videoTsToAudioTs: videoTsToAudioTs,
  4355. metadataTsToSeconds: metadataTsToSeconds
  4356. };
  4357. /**
  4358. * mux.js
  4359. *
  4360. * Copyright (c) Brightcove
  4361. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4362. */
  4363. var coneOfSilence = silence_1;
  4364. var clock$1 = clock$2;
  4365. /**
  4366. * Sum the `byteLength` properties of the data in each AAC frame
  4367. */
  4368. var sumFrameByteLengths = function (array) {
  4369. var i,
  4370. currentObj,
  4371. sum = 0; // sum the byteLength's all each nal unit in the frame
  4372. for (i = 0; i < array.length; i++) {
  4373. currentObj = array[i];
  4374. sum += currentObj.data.byteLength;
  4375. }
  4376. return sum;
  4377. }; // Possibly pad (prefix) the audio track with silence if appending this track
  4378. // would lead to the introduction of a gap in the audio buffer
  4379. var prefixWithSilence = function (track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  4380. var baseMediaDecodeTimeTs,
  4381. frameDuration = 0,
  4382. audioGapDuration = 0,
  4383. audioFillFrameCount = 0,
  4384. audioFillDuration = 0,
  4385. silentFrame,
  4386. i,
  4387. firstFrame;
  4388. if (!frames.length) {
  4389. return;
  4390. }
  4391. baseMediaDecodeTimeTs = clock$1.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  4392. frameDuration = Math.ceil(clock$1.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  4393. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  4394. // insert the shortest possible amount (audio gap or audio to video gap)
  4395. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  4396. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  4397. audioFillDuration = audioFillFrameCount * frameDuration;
  4398. } // don't attempt to fill gaps smaller than a single frame or larger
  4399. // than a half second
  4400. if (audioFillFrameCount < 1 || audioFillDuration > clock$1.ONE_SECOND_IN_TS / 2) {
  4401. return;
  4402. }
  4403. silentFrame = coneOfSilence()[track.samplerate];
  4404. if (!silentFrame) {
  4405. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  4406. // from the content instead
  4407. silentFrame = frames[0].data;
  4408. }
  4409. for (i = 0; i < audioFillFrameCount; i++) {
  4410. firstFrame = frames[0];
  4411. frames.splice(0, 0, {
  4412. data: silentFrame,
  4413. dts: firstFrame.dts - frameDuration,
  4414. pts: firstFrame.pts - frameDuration
  4415. });
  4416. }
  4417. track.baseMediaDecodeTime -= Math.floor(clock$1.videoTsToAudioTs(audioFillDuration, track.samplerate));
  4418. return audioFillDuration;
  4419. }; // If the audio segment extends before the earliest allowed dts
  4420. // value, remove AAC frames until starts at or after the earliest
  4421. // allowed DTS so that we don't end up with a negative baseMedia-
  4422. // DecodeTime for the audio track
  4423. var trimAdtsFramesByEarliestDts = function (adtsFrames, track, earliestAllowedDts) {
  4424. if (track.minSegmentDts >= earliestAllowedDts) {
  4425. return adtsFrames;
  4426. } // We will need to recalculate the earliest segment Dts
  4427. track.minSegmentDts = Infinity;
  4428. return adtsFrames.filter(function (currentFrame) {
  4429. // If this is an allowed frame, keep it and record it's Dts
  4430. if (currentFrame.dts >= earliestAllowedDts) {
  4431. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  4432. track.minSegmentPts = track.minSegmentDts;
  4433. return true;
  4434. } // Otherwise, discard it
  4435. return false;
  4436. });
  4437. }; // generate the track's raw mdat data from an array of frames
  4438. var generateSampleTable = function (frames) {
  4439. var i,
  4440. currentFrame,
  4441. samples = [];
  4442. for (i = 0; i < frames.length; i++) {
  4443. currentFrame = frames[i];
  4444. samples.push({
  4445. size: currentFrame.data.byteLength,
  4446. duration: 1024 // For AAC audio, all samples contain 1024 samples
  4447. });
  4448. }
  4449. return samples;
  4450. }; // generate the track's sample table from an array of frames
  4451. var concatenateFrameData = function (frames) {
  4452. var i,
  4453. currentFrame,
  4454. dataOffset = 0,
  4455. data = new Uint8Array(sumFrameByteLengths(frames));
  4456. for (i = 0; i < frames.length; i++) {
  4457. currentFrame = frames[i];
  4458. data.set(currentFrame.data, dataOffset);
  4459. dataOffset += currentFrame.data.byteLength;
  4460. }
  4461. return data;
  4462. };
  4463. var audioFrameUtils$1 = {
  4464. prefixWithSilence: prefixWithSilence,
  4465. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  4466. generateSampleTable: generateSampleTable,
  4467. concatenateFrameData: concatenateFrameData
  4468. };
  4469. /**
  4470. * mux.js
  4471. *
  4472. * Copyright (c) Brightcove
  4473. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4474. */
  4475. var ONE_SECOND_IN_TS$3 = clock$2.ONE_SECOND_IN_TS;
  4476. /**
  4477. * Store information about the start and end of the track and the
  4478. * duration for each frame/sample we process in order to calculate
  4479. * the baseMediaDecodeTime
  4480. */
  4481. var collectDtsInfo = function (track, data) {
  4482. if (typeof data.pts === 'number') {
  4483. if (track.timelineStartInfo.pts === undefined) {
  4484. track.timelineStartInfo.pts = data.pts;
  4485. }
  4486. if (track.minSegmentPts === undefined) {
  4487. track.minSegmentPts = data.pts;
  4488. } else {
  4489. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  4490. }
  4491. if (track.maxSegmentPts === undefined) {
  4492. track.maxSegmentPts = data.pts;
  4493. } else {
  4494. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  4495. }
  4496. }
  4497. if (typeof data.dts === 'number') {
  4498. if (track.timelineStartInfo.dts === undefined) {
  4499. track.timelineStartInfo.dts = data.dts;
  4500. }
  4501. if (track.minSegmentDts === undefined) {
  4502. track.minSegmentDts = data.dts;
  4503. } else {
  4504. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  4505. }
  4506. if (track.maxSegmentDts === undefined) {
  4507. track.maxSegmentDts = data.dts;
  4508. } else {
  4509. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  4510. }
  4511. }
  4512. };
  4513. /**
  4514. * Clear values used to calculate the baseMediaDecodeTime between
  4515. * tracks
  4516. */
  4517. var clearDtsInfo = function (track) {
  4518. delete track.minSegmentDts;
  4519. delete track.maxSegmentDts;
  4520. delete track.minSegmentPts;
  4521. delete track.maxSegmentPts;
  4522. };
  4523. /**
  4524. * Calculate the track's baseMediaDecodeTime based on the earliest
  4525. * DTS the transmuxer has ever seen and the minimum DTS for the
  4526. * current track
  4527. * @param track {object} track metadata configuration
  4528. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  4529. * in the source; false to adjust the first segment to start at 0.
  4530. */
  4531. var calculateTrackBaseMediaDecodeTime = function (track, keepOriginalTimestamps) {
  4532. var baseMediaDecodeTime,
  4533. scale,
  4534. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  4535. if (!keepOriginalTimestamps) {
  4536. minSegmentDts -= track.timelineStartInfo.dts;
  4537. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  4538. // we want the start of the first segment to be placed
  4539. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  4540. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  4541. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  4542. if (track.type === 'audio') {
  4543. // Audio has a different clock equal to the sampling_rate so we need to
  4544. // scale the PTS values into the clock rate of the track
  4545. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  4546. baseMediaDecodeTime *= scale;
  4547. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  4548. }
  4549. return baseMediaDecodeTime;
  4550. };
  4551. var trackDecodeInfo$1 = {
  4552. clearDtsInfo: clearDtsInfo,
  4553. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  4554. collectDtsInfo: collectDtsInfo
  4555. };
  4556. /**
  4557. * mux.js
  4558. *
  4559. * Copyright (c) Brightcove
  4560. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4561. *
  4562. * Reads in-band caption information from a video elementary
  4563. * stream. Captions must follow the CEA-708 standard for injection
  4564. * into an MPEG-2 transport streams.
  4565. * @see https://en.wikipedia.org/wiki/CEA-708
  4566. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  4567. */
  4568. // payload type field to indicate how they are to be
  4569. // interpreted. CEAS-708 caption content is always transmitted with
  4570. // payload type 0x04.
  4571. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  4572. RBSP_TRAILING_BITS = 128;
  4573. /**
  4574. * Parse a supplemental enhancement information (SEI) NAL unit.
  4575. * Stops parsing once a message of type ITU T T35 has been found.
  4576. *
  4577. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  4578. * @return {object} the parsed SEI payload
  4579. * @see Rec. ITU-T H.264, 7.3.2.3.1
  4580. */
  4581. var parseSei = function (bytes) {
  4582. var i = 0,
  4583. result = {
  4584. payloadType: -1,
  4585. payloadSize: 0
  4586. },
  4587. payloadType = 0,
  4588. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  4589. while (i < bytes.byteLength) {
  4590. // stop once we have hit the end of the sei_rbsp
  4591. if (bytes[i] === RBSP_TRAILING_BITS) {
  4592. break;
  4593. } // Parse payload type
  4594. while (bytes[i] === 0xFF) {
  4595. payloadType += 255;
  4596. i++;
  4597. }
  4598. payloadType += bytes[i++]; // Parse payload size
  4599. while (bytes[i] === 0xFF) {
  4600. payloadSize += 255;
  4601. i++;
  4602. }
  4603. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  4604. // there can only ever be one caption message in a frame's sei
  4605. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  4606. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  4607. if (userIdentifier === 'GA94') {
  4608. result.payloadType = payloadType;
  4609. result.payloadSize = payloadSize;
  4610. result.payload = bytes.subarray(i, i + payloadSize);
  4611. break;
  4612. } else {
  4613. result.payload = void 0;
  4614. }
  4615. } // skip the payload and parse the next message
  4616. i += payloadSize;
  4617. payloadType = 0;
  4618. payloadSize = 0;
  4619. }
  4620. return result;
  4621. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  4622. var parseUserData = function (sei) {
  4623. // itu_t_t35_contry_code must be 181 (United States) for
  4624. // captions
  4625. if (sei.payload[0] !== 181) {
  4626. return null;
  4627. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  4628. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  4629. return null;
  4630. } // the user_identifier should be "GA94" to indicate ATSC1 data
  4631. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  4632. return null;
  4633. } // finally, user_data_type_code should be 0x03 for caption data
  4634. if (sei.payload[7] !== 0x03) {
  4635. return null;
  4636. } // return the user_data_type_structure and strip the trailing
  4637. // marker bits
  4638. return sei.payload.subarray(8, sei.payload.length - 1);
  4639. }; // see CEA-708-D, section 4.4
  4640. var parseCaptionPackets = function (pts, userData) {
  4641. var results = [],
  4642. i,
  4643. count,
  4644. offset,
  4645. data; // if this is just filler, return immediately
  4646. if (!(userData[0] & 0x40)) {
  4647. return results;
  4648. } // parse out the cc_data_1 and cc_data_2 fields
  4649. count = userData[0] & 0x1f;
  4650. for (i = 0; i < count; i++) {
  4651. offset = i * 3;
  4652. data = {
  4653. type: userData[offset + 2] & 0x03,
  4654. pts: pts
  4655. }; // capture cc data when cc_valid is 1
  4656. if (userData[offset + 2] & 0x04) {
  4657. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  4658. results.push(data);
  4659. }
  4660. }
  4661. return results;
  4662. };
  4663. var discardEmulationPreventionBytes$1 = function (data) {
  4664. var length = data.byteLength,
  4665. emulationPreventionBytesPositions = [],
  4666. i = 1,
  4667. newLength,
  4668. newData; // Find all `Emulation Prevention Bytes`
  4669. while (i < length - 2) {
  4670. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  4671. emulationPreventionBytesPositions.push(i + 2);
  4672. i += 2;
  4673. } else {
  4674. i++;
  4675. }
  4676. } // If no Emulation Prevention Bytes were found just return the original
  4677. // array
  4678. if (emulationPreventionBytesPositions.length === 0) {
  4679. return data;
  4680. } // Create a new array to hold the NAL unit data
  4681. newLength = length - emulationPreventionBytesPositions.length;
  4682. newData = new Uint8Array(newLength);
  4683. var sourceIndex = 0;
  4684. for (i = 0; i < newLength; sourceIndex++, i++) {
  4685. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  4686. // Skip this byte
  4687. sourceIndex++; // Remove this position index
  4688. emulationPreventionBytesPositions.shift();
  4689. }
  4690. newData[i] = data[sourceIndex];
  4691. }
  4692. return newData;
  4693. }; // exports
  4694. var captionPacketParser = {
  4695. parseSei: parseSei,
  4696. parseUserData: parseUserData,
  4697. parseCaptionPackets: parseCaptionPackets,
  4698. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  4699. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  4700. };
  4701. /**
  4702. * mux.js
  4703. *
  4704. * Copyright (c) Brightcove
  4705. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4706. *
  4707. * Reads in-band caption information from a video elementary
  4708. * stream. Captions must follow the CEA-708 standard for injection
  4709. * into an MPEG-2 transport streams.
  4710. * @see https://en.wikipedia.org/wiki/CEA-708
  4711. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  4712. */
  4713. // Link To Transport
  4714. // -----------------
  4715. var Stream$7 = stream;
  4716. var cea708Parser = captionPacketParser;
  4717. var CaptionStream$2 = function (options) {
  4718. options = options || {};
  4719. CaptionStream$2.prototype.init.call(this); // parse708captions flag, default to true
  4720. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  4721. this.captionPackets_ = [];
  4722. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  4723. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  4724. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  4725. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  4726. ];
  4727. if (this.parse708captions_) {
  4728. this.cc708Stream_ = new Cea708Stream({
  4729. captionServices: options.captionServices
  4730. }); // eslint-disable-line no-use-before-define
  4731. }
  4732. this.reset(); // forward data and done events from CCs to this CaptionStream
  4733. this.ccStreams_.forEach(function (cc) {
  4734. cc.on('data', this.trigger.bind(this, 'data'));
  4735. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  4736. cc.on('done', this.trigger.bind(this, 'done'));
  4737. }, this);
  4738. if (this.parse708captions_) {
  4739. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  4740. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  4741. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  4742. }
  4743. };
  4744. CaptionStream$2.prototype = new Stream$7();
  4745. CaptionStream$2.prototype.push = function (event) {
  4746. var sei, userData, newCaptionPackets; // only examine SEI NALs
  4747. if (event.nalUnitType !== 'sei_rbsp') {
  4748. return;
  4749. } // parse the sei
  4750. sei = cea708Parser.parseSei(event.escapedRBSP); // no payload data, skip
  4751. if (!sei.payload) {
  4752. return;
  4753. } // ignore everything but user_data_registered_itu_t_t35
  4754. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  4755. return;
  4756. } // parse out the user data payload
  4757. userData = cea708Parser.parseUserData(sei); // ignore unrecognized userData
  4758. if (!userData) {
  4759. return;
  4760. } // Sometimes, the same segment # will be downloaded twice. To stop the
  4761. // caption data from being processed twice, we track the latest dts we've
  4762. // received and ignore everything with a dts before that. However, since
  4763. // data for a specific dts can be split across packets on either side of
  4764. // a segment boundary, we need to make sure we *don't* ignore the packets
  4765. // from the *next* segment that have dts === this.latestDts_. By constantly
  4766. // tracking the number of packets received with dts === this.latestDts_, we
  4767. // know how many should be ignored once we start receiving duplicates.
  4768. if (event.dts < this.latestDts_) {
  4769. // We've started getting older data, so set the flag.
  4770. this.ignoreNextEqualDts_ = true;
  4771. return;
  4772. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  4773. this.numSameDts_--;
  4774. if (!this.numSameDts_) {
  4775. // We've received the last duplicate packet, time to start processing again
  4776. this.ignoreNextEqualDts_ = false;
  4777. }
  4778. return;
  4779. } // parse out CC data packets and save them for later
  4780. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  4781. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  4782. if (this.latestDts_ !== event.dts) {
  4783. this.numSameDts_ = 0;
  4784. }
  4785. this.numSameDts_++;
  4786. this.latestDts_ = event.dts;
  4787. };
  4788. CaptionStream$2.prototype.flushCCStreams = function (flushType) {
  4789. this.ccStreams_.forEach(function (cc) {
  4790. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  4791. }, this);
  4792. };
  4793. CaptionStream$2.prototype.flushStream = function (flushType) {
  4794. // make sure we actually parsed captions before proceeding
  4795. if (!this.captionPackets_.length) {
  4796. this.flushCCStreams(flushType);
  4797. return;
  4798. } // In Chrome, the Array#sort function is not stable so add a
  4799. // presortIndex that we can use to ensure we get a stable-sort
  4800. this.captionPackets_.forEach(function (elem, idx) {
  4801. elem.presortIndex = idx;
  4802. }); // sort caption byte-pairs based on their PTS values
  4803. this.captionPackets_.sort(function (a, b) {
  4804. if (a.pts === b.pts) {
  4805. return a.presortIndex - b.presortIndex;
  4806. }
  4807. return a.pts - b.pts;
  4808. });
  4809. this.captionPackets_.forEach(function (packet) {
  4810. if (packet.type < 2) {
  4811. // Dispatch packet to the right Cea608Stream
  4812. this.dispatchCea608Packet(packet);
  4813. } else {
  4814. // Dispatch packet to the Cea708Stream
  4815. this.dispatchCea708Packet(packet);
  4816. }
  4817. }, this);
  4818. this.captionPackets_.length = 0;
  4819. this.flushCCStreams(flushType);
  4820. };
  4821. CaptionStream$2.prototype.flush = function () {
  4822. return this.flushStream('flush');
  4823. }; // Only called if handling partial data
  4824. CaptionStream$2.prototype.partialFlush = function () {
  4825. return this.flushStream('partialFlush');
  4826. };
  4827. CaptionStream$2.prototype.reset = function () {
  4828. this.latestDts_ = null;
  4829. this.ignoreNextEqualDts_ = false;
  4830. this.numSameDts_ = 0;
  4831. this.activeCea608Channel_ = [null, null];
  4832. this.ccStreams_.forEach(function (ccStream) {
  4833. ccStream.reset();
  4834. });
  4835. }; // From the CEA-608 spec:
  4836. /*
  4837. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  4838. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  4839. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  4840. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  4841. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  4842. * to switch to captioning or Text.
  4843. */
  4844. // With that in mind, we ignore any data between an XDS control code and a
  4845. // subsequent closed-captioning control code.
  4846. CaptionStream$2.prototype.dispatchCea608Packet = function (packet) {
  4847. // NOTE: packet.type is the CEA608 field
  4848. if (this.setsTextOrXDSActive(packet)) {
  4849. this.activeCea608Channel_[packet.type] = null;
  4850. } else if (this.setsChannel1Active(packet)) {
  4851. this.activeCea608Channel_[packet.type] = 0;
  4852. } else if (this.setsChannel2Active(packet)) {
  4853. this.activeCea608Channel_[packet.type] = 1;
  4854. }
  4855. if (this.activeCea608Channel_[packet.type] === null) {
  4856. // If we haven't received anything to set the active channel, or the
  4857. // packets are Text/XDS data, discard the data; we don't want jumbled
  4858. // captions
  4859. return;
  4860. }
  4861. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  4862. };
  4863. CaptionStream$2.prototype.setsChannel1Active = function (packet) {
  4864. return (packet.ccData & 0x7800) === 0x1000;
  4865. };
  4866. CaptionStream$2.prototype.setsChannel2Active = function (packet) {
  4867. return (packet.ccData & 0x7800) === 0x1800;
  4868. };
  4869. CaptionStream$2.prototype.setsTextOrXDSActive = function (packet) {
  4870. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  4871. };
  4872. CaptionStream$2.prototype.dispatchCea708Packet = function (packet) {
  4873. if (this.parse708captions_) {
  4874. this.cc708Stream_.push(packet);
  4875. }
  4876. }; // ----------------------
  4877. // Session to Application
  4878. // ----------------------
  4879. // This hash maps special and extended character codes to their
  4880. // proper Unicode equivalent. The first one-byte key is just a
  4881. // non-standard character code. The two-byte keys that follow are
  4882. // the extended CEA708 character codes, along with the preceding
  4883. // 0x10 extended character byte to distinguish these codes from
  4884. // non-extended character codes. Every CEA708 character code that
  4885. // is not in this object maps directly to a standard unicode
  4886. // character code.
  4887. // The transparent space and non-breaking transparent space are
  4888. // technically not fully supported since there is no code to
  4889. // make them transparent, so they have normal non-transparent
  4890. // stand-ins.
  4891. // The special closed caption (CC) character isn't a standard
  4892. // unicode character, so a fairly similar unicode character was
  4893. // chosen in it's place.
  4894. var CHARACTER_TRANSLATION_708 = {
  4895. 0x7f: 0x266a,
  4896. // ♪
  4897. 0x1020: 0x20,
  4898. // Transparent Space
  4899. 0x1021: 0xa0,
  4900. // Nob-breaking Transparent Space
  4901. 0x1025: 0x2026,
  4902. // …
  4903. 0x102a: 0x0160,
  4904. // Š
  4905. 0x102c: 0x0152,
  4906. // Œ
  4907. 0x1030: 0x2588,
  4908. // █
  4909. 0x1031: 0x2018,
  4910. // ‘
  4911. 0x1032: 0x2019,
  4912. // ’
  4913. 0x1033: 0x201c,
  4914. // “
  4915. 0x1034: 0x201d,
  4916. // ”
  4917. 0x1035: 0x2022,
  4918. // •
  4919. 0x1039: 0x2122,
  4920. // ™
  4921. 0x103a: 0x0161,
  4922. // š
  4923. 0x103c: 0x0153,
  4924. // œ
  4925. 0x103d: 0x2120,
  4926. // ℠
  4927. 0x103f: 0x0178,
  4928. // Ÿ
  4929. 0x1076: 0x215b,
  4930. // ⅛
  4931. 0x1077: 0x215c,
  4932. // ⅜
  4933. 0x1078: 0x215d,
  4934. // ⅝
  4935. 0x1079: 0x215e,
  4936. // ⅞
  4937. 0x107a: 0x23d0,
  4938. // ⏐
  4939. 0x107b: 0x23a4,
  4940. // ⎤
  4941. 0x107c: 0x23a3,
  4942. // ⎣
  4943. 0x107d: 0x23af,
  4944. // ⎯
  4945. 0x107e: 0x23a6,
  4946. // ⎦
  4947. 0x107f: 0x23a1,
  4948. // ⎡
  4949. 0x10a0: 0x3138 // ㄸ (CC char)
  4950. };
  4951. var get708CharFromCode = function (code) {
  4952. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  4953. if (code & 0x1000 && code === newCode) {
  4954. // Invalid extended code
  4955. return '';
  4956. }
  4957. return String.fromCharCode(newCode);
  4958. };
  4959. var within708TextBlock = function (b) {
  4960. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  4961. };
  4962. var Cea708Window = function (windowNum) {
  4963. this.windowNum = windowNum;
  4964. this.reset();
  4965. };
  4966. Cea708Window.prototype.reset = function () {
  4967. this.clearText();
  4968. this.pendingNewLine = false;
  4969. this.winAttr = {};
  4970. this.penAttr = {};
  4971. this.penLoc = {};
  4972. this.penColor = {}; // These default values are arbitrary,
  4973. // defineWindow will usually override them
  4974. this.visible = 0;
  4975. this.rowLock = 0;
  4976. this.columnLock = 0;
  4977. this.priority = 0;
  4978. this.relativePositioning = 0;
  4979. this.anchorVertical = 0;
  4980. this.anchorHorizontal = 0;
  4981. this.anchorPoint = 0;
  4982. this.rowCount = 1;
  4983. this.virtualRowCount = this.rowCount + 1;
  4984. this.columnCount = 41;
  4985. this.windowStyle = 0;
  4986. this.penStyle = 0;
  4987. };
  4988. Cea708Window.prototype.getText = function () {
  4989. return this.rows.join('\n');
  4990. };
  4991. Cea708Window.prototype.clearText = function () {
  4992. this.rows = [''];
  4993. this.rowIdx = 0;
  4994. };
  4995. Cea708Window.prototype.newLine = function (pts) {
  4996. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  4997. this.beforeRowOverflow(pts);
  4998. }
  4999. if (this.rows.length > 0) {
  5000. this.rows.push('');
  5001. this.rowIdx++;
  5002. } // Show all virtual rows since there's no visible scrolling
  5003. while (this.rows.length > this.virtualRowCount) {
  5004. this.rows.shift();
  5005. this.rowIdx--;
  5006. }
  5007. };
  5008. Cea708Window.prototype.isEmpty = function () {
  5009. if (this.rows.length === 0) {
  5010. return true;
  5011. } else if (this.rows.length === 1) {
  5012. return this.rows[0] === '';
  5013. }
  5014. return false;
  5015. };
  5016. Cea708Window.prototype.addText = function (text) {
  5017. this.rows[this.rowIdx] += text;
  5018. };
  5019. Cea708Window.prototype.backspace = function () {
  5020. if (!this.isEmpty()) {
  5021. var row = this.rows[this.rowIdx];
  5022. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  5023. }
  5024. };
  5025. var Cea708Service = function (serviceNum, encoding, stream) {
  5026. this.serviceNum = serviceNum;
  5027. this.text = '';
  5028. this.currentWindow = new Cea708Window(-1);
  5029. this.windows = [];
  5030. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  5031. if (typeof encoding === 'string') {
  5032. this.createTextDecoder(encoding);
  5033. }
  5034. };
  5035. /**
  5036. * Initialize service windows
  5037. * Must be run before service use
  5038. *
  5039. * @param {Integer} pts PTS value
  5040. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  5041. */
  5042. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  5043. this.startPts = pts;
  5044. for (var win = 0; win < 8; win++) {
  5045. this.windows[win] = new Cea708Window(win);
  5046. if (typeof beforeRowOverflow === 'function') {
  5047. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  5048. }
  5049. }
  5050. };
  5051. /**
  5052. * Set current window of service to be affected by commands
  5053. *
  5054. * @param {Integer} windowNum Window number
  5055. */
  5056. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  5057. this.currentWindow = this.windows[windowNum];
  5058. };
  5059. /**
  5060. * Try to create a TextDecoder if it is natively supported
  5061. */
  5062. Cea708Service.prototype.createTextDecoder = function (encoding) {
  5063. if (typeof TextDecoder === 'undefined') {
  5064. this.stream.trigger('log', {
  5065. level: 'warn',
  5066. message: 'The `encoding` option is unsupported without TextDecoder support'
  5067. });
  5068. } else {
  5069. try {
  5070. this.textDecoder_ = new TextDecoder(encoding);
  5071. } catch (error) {
  5072. this.stream.trigger('log', {
  5073. level: 'warn',
  5074. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  5075. });
  5076. }
  5077. }
  5078. };
  5079. var Cea708Stream = function (options) {
  5080. options = options || {};
  5081. Cea708Stream.prototype.init.call(this);
  5082. var self = this;
  5083. var captionServices = options.captionServices || {};
  5084. var captionServiceEncodings = {};
  5085. var serviceProps; // Get service encodings from captionServices option block
  5086. Object.keys(captionServices).forEach(serviceName => {
  5087. serviceProps = captionServices[serviceName];
  5088. if (/^SERVICE/.test(serviceName)) {
  5089. captionServiceEncodings[serviceName] = serviceProps.encoding;
  5090. }
  5091. });
  5092. this.serviceEncodings = captionServiceEncodings;
  5093. this.current708Packet = null;
  5094. this.services = {};
  5095. this.push = function (packet) {
  5096. if (packet.type === 3) {
  5097. // 708 packet start
  5098. self.new708Packet();
  5099. self.add708Bytes(packet);
  5100. } else {
  5101. if (self.current708Packet === null) {
  5102. // This should only happen at the start of a file if there's no packet start.
  5103. self.new708Packet();
  5104. }
  5105. self.add708Bytes(packet);
  5106. }
  5107. };
  5108. };
  5109. Cea708Stream.prototype = new Stream$7();
  5110. /**
  5111. * Push current 708 packet, create new 708 packet.
  5112. */
  5113. Cea708Stream.prototype.new708Packet = function () {
  5114. if (this.current708Packet !== null) {
  5115. this.push708Packet();
  5116. }
  5117. this.current708Packet = {
  5118. data: [],
  5119. ptsVals: []
  5120. };
  5121. };
  5122. /**
  5123. * Add pts and both bytes from packet into current 708 packet.
  5124. */
  5125. Cea708Stream.prototype.add708Bytes = function (packet) {
  5126. var data = packet.ccData;
  5127. var byte0 = data >>> 8;
  5128. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  5129. // that service blocks will always line up with byte pairs.
  5130. this.current708Packet.ptsVals.push(packet.pts);
  5131. this.current708Packet.data.push(byte0);
  5132. this.current708Packet.data.push(byte1);
  5133. };
  5134. /**
  5135. * Parse completed 708 packet into service blocks and push each service block.
  5136. */
  5137. Cea708Stream.prototype.push708Packet = function () {
  5138. var packet708 = this.current708Packet;
  5139. var packetData = packet708.data;
  5140. var serviceNum = null;
  5141. var blockSize = null;
  5142. var i = 0;
  5143. var b = packetData[i++];
  5144. packet708.seq = b >> 6;
  5145. packet708.sizeCode = b & 0x3f; // 0b00111111;
  5146. for (; i < packetData.length; i++) {
  5147. b = packetData[i++];
  5148. serviceNum = b >> 5;
  5149. blockSize = b & 0x1f; // 0b00011111
  5150. if (serviceNum === 7 && blockSize > 0) {
  5151. // Extended service num
  5152. b = packetData[i++];
  5153. serviceNum = b;
  5154. }
  5155. this.pushServiceBlock(serviceNum, i, blockSize);
  5156. if (blockSize > 0) {
  5157. i += blockSize - 1;
  5158. }
  5159. }
  5160. };
  5161. /**
  5162. * Parse service block, execute commands, read text.
  5163. *
  5164. * Note: While many of these commands serve important purposes,
  5165. * many others just parse out the parameters or attributes, but
  5166. * nothing is done with them because this is not a full and complete
  5167. * implementation of the entire 708 spec.
  5168. *
  5169. * @param {Integer} serviceNum Service number
  5170. * @param {Integer} start Start index of the 708 packet data
  5171. * @param {Integer} size Block size
  5172. */
  5173. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  5174. var b;
  5175. var i = start;
  5176. var packetData = this.current708Packet.data;
  5177. var service = this.services[serviceNum];
  5178. if (!service) {
  5179. service = this.initService(serviceNum, i);
  5180. }
  5181. for (; i < start + size && i < packetData.length; i++) {
  5182. b = packetData[i];
  5183. if (within708TextBlock(b)) {
  5184. i = this.handleText(i, service);
  5185. } else if (b === 0x18) {
  5186. i = this.multiByteCharacter(i, service);
  5187. } else if (b === 0x10) {
  5188. i = this.extendedCommands(i, service);
  5189. } else if (0x80 <= b && b <= 0x87) {
  5190. i = this.setCurrentWindow(i, service);
  5191. } else if (0x98 <= b && b <= 0x9f) {
  5192. i = this.defineWindow(i, service);
  5193. } else if (b === 0x88) {
  5194. i = this.clearWindows(i, service);
  5195. } else if (b === 0x8c) {
  5196. i = this.deleteWindows(i, service);
  5197. } else if (b === 0x89) {
  5198. i = this.displayWindows(i, service);
  5199. } else if (b === 0x8a) {
  5200. i = this.hideWindows(i, service);
  5201. } else if (b === 0x8b) {
  5202. i = this.toggleWindows(i, service);
  5203. } else if (b === 0x97) {
  5204. i = this.setWindowAttributes(i, service);
  5205. } else if (b === 0x90) {
  5206. i = this.setPenAttributes(i, service);
  5207. } else if (b === 0x91) {
  5208. i = this.setPenColor(i, service);
  5209. } else if (b === 0x92) {
  5210. i = this.setPenLocation(i, service);
  5211. } else if (b === 0x8f) {
  5212. service = this.reset(i, service);
  5213. } else if (b === 0x08) {
  5214. // BS: Backspace
  5215. service.currentWindow.backspace();
  5216. } else if (b === 0x0c) {
  5217. // FF: Form feed
  5218. service.currentWindow.clearText();
  5219. } else if (b === 0x0d) {
  5220. // CR: Carriage return
  5221. service.currentWindow.pendingNewLine = true;
  5222. } else if (b === 0x0e) {
  5223. // HCR: Horizontal carriage return
  5224. service.currentWindow.clearText();
  5225. } else if (b === 0x8d) {
  5226. // DLY: Delay, nothing to do
  5227. i++;
  5228. } else ;
  5229. }
  5230. };
  5231. /**
  5232. * Execute an extended command
  5233. *
  5234. * @param {Integer} i Current index in the 708 packet
  5235. * @param {Service} service The service object to be affected
  5236. * @return {Integer} New index after parsing
  5237. */
  5238. Cea708Stream.prototype.extendedCommands = function (i, service) {
  5239. var packetData = this.current708Packet.data;
  5240. var b = packetData[++i];
  5241. if (within708TextBlock(b)) {
  5242. i = this.handleText(i, service, {
  5243. isExtended: true
  5244. });
  5245. }
  5246. return i;
  5247. };
  5248. /**
  5249. * Get PTS value of a given byte index
  5250. *
  5251. * @param {Integer} byteIndex Index of the byte
  5252. * @return {Integer} PTS
  5253. */
  5254. Cea708Stream.prototype.getPts = function (byteIndex) {
  5255. // There's 1 pts value per 2 bytes
  5256. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  5257. };
  5258. /**
  5259. * Initializes a service
  5260. *
  5261. * @param {Integer} serviceNum Service number
  5262. * @return {Service} Initialized service object
  5263. */
  5264. Cea708Stream.prototype.initService = function (serviceNum, i) {
  5265. var serviceName = 'SERVICE' + serviceNum;
  5266. var self = this;
  5267. var serviceName;
  5268. var encoding;
  5269. if (serviceName in this.serviceEncodings) {
  5270. encoding = this.serviceEncodings[serviceName];
  5271. }
  5272. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  5273. this.services[serviceNum].init(this.getPts(i), function (pts) {
  5274. self.flushDisplayed(pts, self.services[serviceNum]);
  5275. });
  5276. return this.services[serviceNum];
  5277. };
  5278. /**
  5279. * Execute text writing to current window
  5280. *
  5281. * @param {Integer} i Current index in the 708 packet
  5282. * @param {Service} service The service object to be affected
  5283. * @return {Integer} New index after parsing
  5284. */
  5285. Cea708Stream.prototype.handleText = function (i, service, options) {
  5286. var isExtended = options && options.isExtended;
  5287. var isMultiByte = options && options.isMultiByte;
  5288. var packetData = this.current708Packet.data;
  5289. var extended = isExtended ? 0x1000 : 0x0000;
  5290. var currentByte = packetData[i];
  5291. var nextByte = packetData[i + 1];
  5292. var win = service.currentWindow;
  5293. var char;
  5294. var charCodeArray; // Use the TextDecoder if one was created for this service
  5295. if (service.textDecoder_ && !isExtended) {
  5296. if (isMultiByte) {
  5297. charCodeArray = [currentByte, nextByte];
  5298. i++;
  5299. } else {
  5300. charCodeArray = [currentByte];
  5301. }
  5302. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  5303. } else {
  5304. char = get708CharFromCode(extended | currentByte);
  5305. }
  5306. if (win.pendingNewLine && !win.isEmpty()) {
  5307. win.newLine(this.getPts(i));
  5308. }
  5309. win.pendingNewLine = false;
  5310. win.addText(char);
  5311. return i;
  5312. };
  5313. /**
  5314. * Handle decoding of multibyte character
  5315. *
  5316. * @param {Integer} i Current index in the 708 packet
  5317. * @param {Service} service The service object to be affected
  5318. * @return {Integer} New index after parsing
  5319. */
  5320. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  5321. var packetData = this.current708Packet.data;
  5322. var firstByte = packetData[i + 1];
  5323. var secondByte = packetData[i + 2];
  5324. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  5325. i = this.handleText(++i, service, {
  5326. isMultiByte: true
  5327. });
  5328. }
  5329. return i;
  5330. };
  5331. /**
  5332. * Parse and execute the CW# command.
  5333. *
  5334. * Set the current window.
  5335. *
  5336. * @param {Integer} i Current index in the 708 packet
  5337. * @param {Service} service The service object to be affected
  5338. * @return {Integer} New index after parsing
  5339. */
  5340. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  5341. var packetData = this.current708Packet.data;
  5342. var b = packetData[i];
  5343. var windowNum = b & 0x07;
  5344. service.setCurrentWindow(windowNum);
  5345. return i;
  5346. };
  5347. /**
  5348. * Parse and execute the DF# command.
  5349. *
  5350. * Define a window and set it as the current window.
  5351. *
  5352. * @param {Integer} i Current index in the 708 packet
  5353. * @param {Service} service The service object to be affected
  5354. * @return {Integer} New index after parsing
  5355. */
  5356. Cea708Stream.prototype.defineWindow = function (i, service) {
  5357. var packetData = this.current708Packet.data;
  5358. var b = packetData[i];
  5359. var windowNum = b & 0x07;
  5360. service.setCurrentWindow(windowNum);
  5361. var win = service.currentWindow;
  5362. b = packetData[++i];
  5363. win.visible = (b & 0x20) >> 5; // v
  5364. win.rowLock = (b & 0x10) >> 4; // rl
  5365. win.columnLock = (b & 0x08) >> 3; // cl
  5366. win.priority = b & 0x07; // p
  5367. b = packetData[++i];
  5368. win.relativePositioning = (b & 0x80) >> 7; // rp
  5369. win.anchorVertical = b & 0x7f; // av
  5370. b = packetData[++i];
  5371. win.anchorHorizontal = b; // ah
  5372. b = packetData[++i];
  5373. win.anchorPoint = (b & 0xf0) >> 4; // ap
  5374. win.rowCount = b & 0x0f; // rc
  5375. b = packetData[++i];
  5376. win.columnCount = b & 0x3f; // cc
  5377. b = packetData[++i];
  5378. win.windowStyle = (b & 0x38) >> 3; // ws
  5379. win.penStyle = b & 0x07; // ps
  5380. // The spec says there are (rowCount+1) "virtual rows"
  5381. win.virtualRowCount = win.rowCount + 1;
  5382. return i;
  5383. };
  5384. /**
  5385. * Parse and execute the SWA command.
  5386. *
  5387. * Set attributes of the current window.
  5388. *
  5389. * @param {Integer} i Current index in the 708 packet
  5390. * @param {Service} service The service object to be affected
  5391. * @return {Integer} New index after parsing
  5392. */
  5393. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  5394. var packetData = this.current708Packet.data;
  5395. var b = packetData[i];
  5396. var winAttr = service.currentWindow.winAttr;
  5397. b = packetData[++i];
  5398. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  5399. winAttr.fillRed = (b & 0x30) >> 4; // fr
  5400. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  5401. winAttr.fillBlue = b & 0x03; // fb
  5402. b = packetData[++i];
  5403. winAttr.borderType = (b & 0xc0) >> 6; // bt
  5404. winAttr.borderRed = (b & 0x30) >> 4; // br
  5405. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  5406. winAttr.borderBlue = b & 0x03; // bb
  5407. b = packetData[++i];
  5408. winAttr.borderType += (b & 0x80) >> 5; // bt
  5409. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  5410. winAttr.printDirection = (b & 0x30) >> 4; // pd
  5411. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  5412. winAttr.justify = b & 0x03; // j
  5413. b = packetData[++i];
  5414. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  5415. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  5416. winAttr.displayEffect = b & 0x03; // de
  5417. return i;
  5418. };
  5419. /**
  5420. * Gather text from all displayed windows and push a caption to output.
  5421. *
  5422. * @param {Integer} i Current index in the 708 packet
  5423. * @param {Service} service The service object to be affected
  5424. */
  5425. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  5426. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  5427. // display text in the correct order, but sample files so far have not shown any issue.
  5428. for (var winId = 0; winId < 8; winId++) {
  5429. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  5430. displayedText.push(service.windows[winId].getText());
  5431. }
  5432. }
  5433. service.endPts = pts;
  5434. service.text = displayedText.join('\n\n');
  5435. this.pushCaption(service);
  5436. service.startPts = pts;
  5437. };
  5438. /**
  5439. * Push a caption to output if the caption contains text.
  5440. *
  5441. * @param {Service} service The service object to be affected
  5442. */
  5443. Cea708Stream.prototype.pushCaption = function (service) {
  5444. if (service.text !== '') {
  5445. this.trigger('data', {
  5446. startPts: service.startPts,
  5447. endPts: service.endPts,
  5448. text: service.text,
  5449. stream: 'cc708_' + service.serviceNum
  5450. });
  5451. service.text = '';
  5452. service.startPts = service.endPts;
  5453. }
  5454. };
  5455. /**
  5456. * Parse and execute the DSW command.
  5457. *
  5458. * Set visible property of windows based on the parsed bitmask.
  5459. *
  5460. * @param {Integer} i Current index in the 708 packet
  5461. * @param {Service} service The service object to be affected
  5462. * @return {Integer} New index after parsing
  5463. */
  5464. Cea708Stream.prototype.displayWindows = function (i, service) {
  5465. var packetData = this.current708Packet.data;
  5466. var b = packetData[++i];
  5467. var pts = this.getPts(i);
  5468. this.flushDisplayed(pts, service);
  5469. for (var winId = 0; winId < 8; winId++) {
  5470. if (b & 0x01 << winId) {
  5471. service.windows[winId].visible = 1;
  5472. }
  5473. }
  5474. return i;
  5475. };
  5476. /**
  5477. * Parse and execute the HDW command.
  5478. *
  5479. * Set visible property of windows based on the parsed bitmask.
  5480. *
  5481. * @param {Integer} i Current index in the 708 packet
  5482. * @param {Service} service The service object to be affected
  5483. * @return {Integer} New index after parsing
  5484. */
  5485. Cea708Stream.prototype.hideWindows = function (i, service) {
  5486. var packetData = this.current708Packet.data;
  5487. var b = packetData[++i];
  5488. var pts = this.getPts(i);
  5489. this.flushDisplayed(pts, service);
  5490. for (var winId = 0; winId < 8; winId++) {
  5491. if (b & 0x01 << winId) {
  5492. service.windows[winId].visible = 0;
  5493. }
  5494. }
  5495. return i;
  5496. };
  5497. /**
  5498. * Parse and execute the TGW command.
  5499. *
  5500. * Set visible property of windows based on the parsed bitmask.
  5501. *
  5502. * @param {Integer} i Current index in the 708 packet
  5503. * @param {Service} service The service object to be affected
  5504. * @return {Integer} New index after parsing
  5505. */
  5506. Cea708Stream.prototype.toggleWindows = function (i, service) {
  5507. var packetData = this.current708Packet.data;
  5508. var b = packetData[++i];
  5509. var pts = this.getPts(i);
  5510. this.flushDisplayed(pts, service);
  5511. for (var winId = 0; winId < 8; winId++) {
  5512. if (b & 0x01 << winId) {
  5513. service.windows[winId].visible ^= 1;
  5514. }
  5515. }
  5516. return i;
  5517. };
  5518. /**
  5519. * Parse and execute the CLW command.
  5520. *
  5521. * Clear text of windows based on the parsed bitmask.
  5522. *
  5523. * @param {Integer} i Current index in the 708 packet
  5524. * @param {Service} service The service object to be affected
  5525. * @return {Integer} New index after parsing
  5526. */
  5527. Cea708Stream.prototype.clearWindows = function (i, service) {
  5528. var packetData = this.current708Packet.data;
  5529. var b = packetData[++i];
  5530. var pts = this.getPts(i);
  5531. this.flushDisplayed(pts, service);
  5532. for (var winId = 0; winId < 8; winId++) {
  5533. if (b & 0x01 << winId) {
  5534. service.windows[winId].clearText();
  5535. }
  5536. }
  5537. return i;
  5538. };
  5539. /**
  5540. * Parse and execute the DLW command.
  5541. *
  5542. * Re-initialize windows based on the parsed bitmask.
  5543. *
  5544. * @param {Integer} i Current index in the 708 packet
  5545. * @param {Service} service The service object to be affected
  5546. * @return {Integer} New index after parsing
  5547. */
  5548. Cea708Stream.prototype.deleteWindows = function (i, service) {
  5549. var packetData = this.current708Packet.data;
  5550. var b = packetData[++i];
  5551. var pts = this.getPts(i);
  5552. this.flushDisplayed(pts, service);
  5553. for (var winId = 0; winId < 8; winId++) {
  5554. if (b & 0x01 << winId) {
  5555. service.windows[winId].reset();
  5556. }
  5557. }
  5558. return i;
  5559. };
  5560. /**
  5561. * Parse and execute the SPA command.
  5562. *
  5563. * Set pen attributes of the current window.
  5564. *
  5565. * @param {Integer} i Current index in the 708 packet
  5566. * @param {Service} service The service object to be affected
  5567. * @return {Integer} New index after parsing
  5568. */
  5569. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  5570. var packetData = this.current708Packet.data;
  5571. var b = packetData[i];
  5572. var penAttr = service.currentWindow.penAttr;
  5573. b = packetData[++i];
  5574. penAttr.textTag = (b & 0xf0) >> 4; // tt
  5575. penAttr.offset = (b & 0x0c) >> 2; // o
  5576. penAttr.penSize = b & 0x03; // s
  5577. b = packetData[++i];
  5578. penAttr.italics = (b & 0x80) >> 7; // i
  5579. penAttr.underline = (b & 0x40) >> 6; // u
  5580. penAttr.edgeType = (b & 0x38) >> 3; // et
  5581. penAttr.fontStyle = b & 0x07; // fs
  5582. return i;
  5583. };
  5584. /**
  5585. * Parse and execute the SPC command.
  5586. *
  5587. * Set pen color of the current window.
  5588. *
  5589. * @param {Integer} i Current index in the 708 packet
  5590. * @param {Service} service The service object to be affected
  5591. * @return {Integer} New index after parsing
  5592. */
  5593. Cea708Stream.prototype.setPenColor = function (i, service) {
  5594. var packetData = this.current708Packet.data;
  5595. var b = packetData[i];
  5596. var penColor = service.currentWindow.penColor;
  5597. b = packetData[++i];
  5598. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  5599. penColor.fgRed = (b & 0x30) >> 4; // fr
  5600. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  5601. penColor.fgBlue = b & 0x03; // fb
  5602. b = packetData[++i];
  5603. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  5604. penColor.bgRed = (b & 0x30) >> 4; // br
  5605. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  5606. penColor.bgBlue = b & 0x03; // bb
  5607. b = packetData[++i];
  5608. penColor.edgeRed = (b & 0x30) >> 4; // er
  5609. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  5610. penColor.edgeBlue = b & 0x03; // eb
  5611. return i;
  5612. };
  5613. /**
  5614. * Parse and execute the SPL command.
  5615. *
  5616. * Set pen location of the current window.
  5617. *
  5618. * @param {Integer} i Current index in the 708 packet
  5619. * @param {Service} service The service object to be affected
  5620. * @return {Integer} New index after parsing
  5621. */
  5622. Cea708Stream.prototype.setPenLocation = function (i, service) {
  5623. var packetData = this.current708Packet.data;
  5624. var b = packetData[i];
  5625. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  5626. service.currentWindow.pendingNewLine = true;
  5627. b = packetData[++i];
  5628. penLoc.row = b & 0x0f; // r
  5629. b = packetData[++i];
  5630. penLoc.column = b & 0x3f; // c
  5631. return i;
  5632. };
  5633. /**
  5634. * Execute the RST command.
  5635. *
  5636. * Reset service to a clean slate. Re-initialize.
  5637. *
  5638. * @param {Integer} i Current index in the 708 packet
  5639. * @param {Service} service The service object to be affected
  5640. * @return {Service} Re-initialized service
  5641. */
  5642. Cea708Stream.prototype.reset = function (i, service) {
  5643. var pts = this.getPts(i);
  5644. this.flushDisplayed(pts, service);
  5645. return this.initService(service.serviceNum, i);
  5646. }; // This hash maps non-ASCII, special, and extended character codes to their
  5647. // proper Unicode equivalent. The first keys that are only a single byte
  5648. // are the non-standard ASCII characters, which simply map the CEA608 byte
  5649. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  5650. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  5651. // can be performed regardless of the field and data channel on which the
  5652. // character code was received.
  5653. var CHARACTER_TRANSLATION = {
  5654. 0x2a: 0xe1,
  5655. // á
  5656. 0x5c: 0xe9,
  5657. // é
  5658. 0x5e: 0xed,
  5659. // í
  5660. 0x5f: 0xf3,
  5661. // ó
  5662. 0x60: 0xfa,
  5663. // ú
  5664. 0x7b: 0xe7,
  5665. // ç
  5666. 0x7c: 0xf7,
  5667. // ÷
  5668. 0x7d: 0xd1,
  5669. // Ñ
  5670. 0x7e: 0xf1,
  5671. // ñ
  5672. 0x7f: 0x2588,
  5673. // █
  5674. 0x0130: 0xae,
  5675. // ®
  5676. 0x0131: 0xb0,
  5677. // °
  5678. 0x0132: 0xbd,
  5679. // ½
  5680. 0x0133: 0xbf,
  5681. // ¿
  5682. 0x0134: 0x2122,
  5683. // ™
  5684. 0x0135: 0xa2,
  5685. // ¢
  5686. 0x0136: 0xa3,
  5687. // £
  5688. 0x0137: 0x266a,
  5689. // ♪
  5690. 0x0138: 0xe0,
  5691. // à
  5692. 0x0139: 0xa0,
  5693. //
  5694. 0x013a: 0xe8,
  5695. // è
  5696. 0x013b: 0xe2,
  5697. // â
  5698. 0x013c: 0xea,
  5699. // ê
  5700. 0x013d: 0xee,
  5701. // î
  5702. 0x013e: 0xf4,
  5703. // ô
  5704. 0x013f: 0xfb,
  5705. // û
  5706. 0x0220: 0xc1,
  5707. // Á
  5708. 0x0221: 0xc9,
  5709. // É
  5710. 0x0222: 0xd3,
  5711. // Ó
  5712. 0x0223: 0xda,
  5713. // Ú
  5714. 0x0224: 0xdc,
  5715. // Ü
  5716. 0x0225: 0xfc,
  5717. // ü
  5718. 0x0226: 0x2018,
  5719. // ‘
  5720. 0x0227: 0xa1,
  5721. // ¡
  5722. 0x0228: 0x2a,
  5723. // *
  5724. 0x0229: 0x27,
  5725. // '
  5726. 0x022a: 0x2014,
  5727. // —
  5728. 0x022b: 0xa9,
  5729. // ©
  5730. 0x022c: 0x2120,
  5731. // ℠
  5732. 0x022d: 0x2022,
  5733. // •
  5734. 0x022e: 0x201c,
  5735. // “
  5736. 0x022f: 0x201d,
  5737. // ”
  5738. 0x0230: 0xc0,
  5739. // À
  5740. 0x0231: 0xc2,
  5741. // Â
  5742. 0x0232: 0xc7,
  5743. // Ç
  5744. 0x0233: 0xc8,
  5745. // È
  5746. 0x0234: 0xca,
  5747. // Ê
  5748. 0x0235: 0xcb,
  5749. // Ë
  5750. 0x0236: 0xeb,
  5751. // ë
  5752. 0x0237: 0xce,
  5753. // Î
  5754. 0x0238: 0xcf,
  5755. // Ï
  5756. 0x0239: 0xef,
  5757. // ï
  5758. 0x023a: 0xd4,
  5759. // Ô
  5760. 0x023b: 0xd9,
  5761. // Ù
  5762. 0x023c: 0xf9,
  5763. // ù
  5764. 0x023d: 0xdb,
  5765. // Û
  5766. 0x023e: 0xab,
  5767. // «
  5768. 0x023f: 0xbb,
  5769. // »
  5770. 0x0320: 0xc3,
  5771. // Ã
  5772. 0x0321: 0xe3,
  5773. // ã
  5774. 0x0322: 0xcd,
  5775. // Í
  5776. 0x0323: 0xcc,
  5777. // Ì
  5778. 0x0324: 0xec,
  5779. // ì
  5780. 0x0325: 0xd2,
  5781. // Ò
  5782. 0x0326: 0xf2,
  5783. // ò
  5784. 0x0327: 0xd5,
  5785. // Õ
  5786. 0x0328: 0xf5,
  5787. // õ
  5788. 0x0329: 0x7b,
  5789. // {
  5790. 0x032a: 0x7d,
  5791. // }
  5792. 0x032b: 0x5c,
  5793. // \
  5794. 0x032c: 0x5e,
  5795. // ^
  5796. 0x032d: 0x5f,
  5797. // _
  5798. 0x032e: 0x7c,
  5799. // |
  5800. 0x032f: 0x7e,
  5801. // ~
  5802. 0x0330: 0xc4,
  5803. // Ä
  5804. 0x0331: 0xe4,
  5805. // ä
  5806. 0x0332: 0xd6,
  5807. // Ö
  5808. 0x0333: 0xf6,
  5809. // ö
  5810. 0x0334: 0xdf,
  5811. // ß
  5812. 0x0335: 0xa5,
  5813. // ¥
  5814. 0x0336: 0xa4,
  5815. // ¤
  5816. 0x0337: 0x2502,
  5817. // │
  5818. 0x0338: 0xc5,
  5819. // Å
  5820. 0x0339: 0xe5,
  5821. // å
  5822. 0x033a: 0xd8,
  5823. // Ø
  5824. 0x033b: 0xf8,
  5825. // ø
  5826. 0x033c: 0x250c,
  5827. // ┌
  5828. 0x033d: 0x2510,
  5829. // ┐
  5830. 0x033e: 0x2514,
  5831. // └
  5832. 0x033f: 0x2518 // ┘
  5833. };
  5834. var getCharFromCode = function (code) {
  5835. if (code === null) {
  5836. return '';
  5837. }
  5838. code = CHARACTER_TRANSLATION[code] || code;
  5839. return String.fromCharCode(code);
  5840. }; // the index of the last row in a CEA-608 display buffer
  5841. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  5842. // getting it through bit logic.
  5843. 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
  5844. // cells. The "bottom" row is the last element in the outer array.
  5845. var createDisplayBuffer = function () {
  5846. var result = [],
  5847. i = BOTTOM_ROW + 1;
  5848. while (i--) {
  5849. result.push('');
  5850. }
  5851. return result;
  5852. };
  5853. var Cea608Stream = function (field, dataChannel) {
  5854. Cea608Stream.prototype.init.call(this);
  5855. this.field_ = field || 0;
  5856. this.dataChannel_ = dataChannel || 0;
  5857. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  5858. this.setConstants();
  5859. this.reset();
  5860. this.push = function (packet) {
  5861. var data, swap, char0, char1, text; // remove the parity bits
  5862. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  5863. if (data === this.lastControlCode_) {
  5864. this.lastControlCode_ = null;
  5865. return;
  5866. } // Store control codes
  5867. if ((data & 0xf000) === 0x1000) {
  5868. this.lastControlCode_ = data;
  5869. } else if (data !== this.PADDING_) {
  5870. this.lastControlCode_ = null;
  5871. }
  5872. char0 = data >>> 8;
  5873. char1 = data & 0xff;
  5874. if (data === this.PADDING_) {
  5875. return;
  5876. } else if (data === this.RESUME_CAPTION_LOADING_) {
  5877. this.mode_ = 'popOn';
  5878. } else if (data === this.END_OF_CAPTION_) {
  5879. // If an EOC is received while in paint-on mode, the displayed caption
  5880. // text should be swapped to non-displayed memory as if it was a pop-on
  5881. // caption. Because of that, we should explicitly switch back to pop-on
  5882. // mode
  5883. this.mode_ = 'popOn';
  5884. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  5885. this.flushDisplayed(packet.pts); // flip memory
  5886. swap = this.displayed_;
  5887. this.displayed_ = this.nonDisplayed_;
  5888. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  5889. this.startPts_ = packet.pts;
  5890. } else if (data === this.ROLL_UP_2_ROWS_) {
  5891. this.rollUpRows_ = 2;
  5892. this.setRollUp(packet.pts);
  5893. } else if (data === this.ROLL_UP_3_ROWS_) {
  5894. this.rollUpRows_ = 3;
  5895. this.setRollUp(packet.pts);
  5896. } else if (data === this.ROLL_UP_4_ROWS_) {
  5897. this.rollUpRows_ = 4;
  5898. this.setRollUp(packet.pts);
  5899. } else if (data === this.CARRIAGE_RETURN_) {
  5900. this.clearFormatting(packet.pts);
  5901. this.flushDisplayed(packet.pts);
  5902. this.shiftRowsUp_();
  5903. this.startPts_ = packet.pts;
  5904. } else if (data === this.BACKSPACE_) {
  5905. if (this.mode_ === 'popOn') {
  5906. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  5907. } else {
  5908. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  5909. }
  5910. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  5911. this.flushDisplayed(packet.pts);
  5912. this.displayed_ = createDisplayBuffer();
  5913. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  5914. this.nonDisplayed_ = createDisplayBuffer();
  5915. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  5916. if (this.mode_ !== 'paintOn') {
  5917. // NOTE: This should be removed when proper caption positioning is
  5918. // implemented
  5919. this.flushDisplayed(packet.pts);
  5920. this.displayed_ = createDisplayBuffer();
  5921. }
  5922. this.mode_ = 'paintOn';
  5923. this.startPts_ = packet.pts; // Append special characters to caption text
  5924. } else if (this.isSpecialCharacter(char0, char1)) {
  5925. // Bitmask char0 so that we can apply character transformations
  5926. // regardless of field and data channel.
  5927. // Then byte-shift to the left and OR with char1 so we can pass the
  5928. // entire character code to `getCharFromCode`.
  5929. char0 = (char0 & 0x03) << 8;
  5930. text = getCharFromCode(char0 | char1);
  5931. this[this.mode_](packet.pts, text);
  5932. this.column_++; // Append extended characters to caption text
  5933. } else if (this.isExtCharacter(char0, char1)) {
  5934. // Extended characters always follow their "non-extended" equivalents.
  5935. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  5936. // decoders are supposed to drop the "è", while compliant decoders
  5937. // backspace the "e" and insert "è".
  5938. // Delete the previous character
  5939. if (this.mode_ === 'popOn') {
  5940. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  5941. } else {
  5942. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  5943. } // Bitmask char0 so that we can apply character transformations
  5944. // regardless of field and data channel.
  5945. // Then byte-shift to the left and OR with char1 so we can pass the
  5946. // entire character code to `getCharFromCode`.
  5947. char0 = (char0 & 0x03) << 8;
  5948. text = getCharFromCode(char0 | char1);
  5949. this[this.mode_](packet.pts, text);
  5950. this.column_++; // Process mid-row codes
  5951. } else if (this.isMidRowCode(char0, char1)) {
  5952. // Attributes are not additive, so clear all formatting
  5953. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  5954. // should be replaced with spaces, so add one now
  5955. this[this.mode_](packet.pts, ' ');
  5956. this.column_++;
  5957. if ((char1 & 0xe) === 0xe) {
  5958. this.addFormatting(packet.pts, ['i']);
  5959. }
  5960. if ((char1 & 0x1) === 0x1) {
  5961. this.addFormatting(packet.pts, ['u']);
  5962. } // Detect offset control codes and adjust cursor
  5963. } else if (this.isOffsetControlCode(char0, char1)) {
  5964. // Cursor position is set by indent PAC (see below) in 4-column
  5965. // increments, with an additional offset code of 1-3 to reach any
  5966. // of the 32 columns specified by CEA-608. So all we need to do
  5967. // here is increment the column cursor by the given offset.
  5968. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  5969. } else if (this.isPAC(char0, char1)) {
  5970. // There's no logic for PAC -> row mapping, so we have to just
  5971. // find the row code in an array and use its index :(
  5972. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  5973. if (this.mode_ === 'rollUp') {
  5974. // This implies that the base row is incorrectly set.
  5975. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  5976. // of roll-up rows set.
  5977. if (row - this.rollUpRows_ + 1 < 0) {
  5978. row = this.rollUpRows_ - 1;
  5979. }
  5980. this.setRollUp(packet.pts, row);
  5981. }
  5982. if (row !== this.row_) {
  5983. // formatting is only persistent for current row
  5984. this.clearFormatting(packet.pts);
  5985. this.row_ = row;
  5986. } // All PACs can apply underline, so detect and apply
  5987. // (All odd-numbered second bytes set underline)
  5988. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  5989. this.addFormatting(packet.pts, ['u']);
  5990. }
  5991. if ((data & 0x10) === 0x10) {
  5992. // We've got an indent level code. Each successive even number
  5993. // increments the column cursor by 4, so we can get the desired
  5994. // column position by bit-shifting to the right (to get n/2)
  5995. // and multiplying by 4.
  5996. this.column_ = ((data & 0xe) >> 1) * 4;
  5997. }
  5998. if (this.isColorPAC(char1)) {
  5999. // it's a color code, though we only support white, which
  6000. // can be either normal or italicized. white italics can be
  6001. // either 0x4e or 0x6e depending on the row, so we just
  6002. // bitwise-and with 0xe to see if italics should be turned on
  6003. if ((char1 & 0xe) === 0xe) {
  6004. this.addFormatting(packet.pts, ['i']);
  6005. }
  6006. } // We have a normal character in char0, and possibly one in char1
  6007. } else if (this.isNormalChar(char0)) {
  6008. if (char1 === 0x00) {
  6009. char1 = null;
  6010. }
  6011. text = getCharFromCode(char0);
  6012. text += getCharFromCode(char1);
  6013. this[this.mode_](packet.pts, text);
  6014. this.column_ += text.length;
  6015. } // finish data processing
  6016. };
  6017. };
  6018. Cea608Stream.prototype = new Stream$7(); // Trigger a cue point that captures the current state of the
  6019. // display buffer
  6020. Cea608Stream.prototype.flushDisplayed = function (pts) {
  6021. var content = this.displayed_ // remove spaces from the start and end of the string
  6022. .map(function (row, index) {
  6023. try {
  6024. return row.trim();
  6025. } catch (e) {
  6026. // Ordinarily, this shouldn't happen. However, caption
  6027. // parsing errors should not throw exceptions and
  6028. // break playback.
  6029. this.trigger('log', {
  6030. level: 'warn',
  6031. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  6032. });
  6033. return '';
  6034. }
  6035. }, this) // combine all text rows to display in one cue
  6036. .join('\n') // and remove blank rows from the start and end, but not the middle
  6037. .replace(/^\n+|\n+$/g, '');
  6038. if (content.length) {
  6039. this.trigger('data', {
  6040. startPts: this.startPts_,
  6041. endPts: pts,
  6042. text: content,
  6043. stream: this.name_
  6044. });
  6045. }
  6046. };
  6047. /**
  6048. * Zero out the data, used for startup and on seek
  6049. */
  6050. Cea608Stream.prototype.reset = function () {
  6051. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  6052. // actually display captions. If a caption is shifted to a row
  6053. // with a lower index than this, it is cleared from the display
  6054. // buffer
  6055. this.topRow_ = 0;
  6056. this.startPts_ = 0;
  6057. this.displayed_ = createDisplayBuffer();
  6058. this.nonDisplayed_ = createDisplayBuffer();
  6059. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  6060. this.column_ = 0;
  6061. this.row_ = BOTTOM_ROW;
  6062. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  6063. this.formatting_ = [];
  6064. };
  6065. /**
  6066. * Sets up control code and related constants for this instance
  6067. */
  6068. Cea608Stream.prototype.setConstants = function () {
  6069. // The following attributes have these uses:
  6070. // ext_ : char0 for mid-row codes, and the base for extended
  6071. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  6072. // extended codes)
  6073. // control_: char0 for control codes, except byte-shifted to the
  6074. // left so that we can do this.control_ | CONTROL_CODE
  6075. // offset_: char0 for tab offset codes
  6076. //
  6077. // It's also worth noting that control codes, and _only_ control codes,
  6078. // differ between field 1 and field2. Field 2 control codes are always
  6079. // their field 1 value plus 1. That's why there's the "| field" on the
  6080. // control value.
  6081. if (this.dataChannel_ === 0) {
  6082. this.BASE_ = 0x10;
  6083. this.EXT_ = 0x11;
  6084. this.CONTROL_ = (0x14 | this.field_) << 8;
  6085. this.OFFSET_ = 0x17;
  6086. } else if (this.dataChannel_ === 1) {
  6087. this.BASE_ = 0x18;
  6088. this.EXT_ = 0x19;
  6089. this.CONTROL_ = (0x1c | this.field_) << 8;
  6090. this.OFFSET_ = 0x1f;
  6091. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  6092. // list is not exhaustive. For a more comprehensive listing and semantics see
  6093. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  6094. // Padding
  6095. this.PADDING_ = 0x0000; // Pop-on Mode
  6096. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  6097. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  6098. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  6099. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  6100. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  6101. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  6102. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  6103. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  6104. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  6105. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  6106. };
  6107. /**
  6108. * Detects if the 2-byte packet data is a special character
  6109. *
  6110. * Special characters have a second byte in the range 0x30 to 0x3f,
  6111. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  6112. * data channel 2).
  6113. *
  6114. * @param {Integer} char0 The first byte
  6115. * @param {Integer} char1 The second byte
  6116. * @return {Boolean} Whether the 2 bytes are an special character
  6117. */
  6118. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  6119. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  6120. };
  6121. /**
  6122. * Detects if the 2-byte packet data is an extended character
  6123. *
  6124. * Extended characters have a second byte in the range 0x20 to 0x3f,
  6125. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  6126. * 0x1a or 0x1b (for data channel 2).
  6127. *
  6128. * @param {Integer} char0 The first byte
  6129. * @param {Integer} char1 The second byte
  6130. * @return {Boolean} Whether the 2 bytes are an extended character
  6131. */
  6132. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  6133. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  6134. };
  6135. /**
  6136. * Detects if the 2-byte packet is a mid-row code
  6137. *
  6138. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  6139. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  6140. * channel 2).
  6141. *
  6142. * @param {Integer} char0 The first byte
  6143. * @param {Integer} char1 The second byte
  6144. * @return {Boolean} Whether the 2 bytes are a mid-row code
  6145. */
  6146. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  6147. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  6148. };
  6149. /**
  6150. * Detects if the 2-byte packet is an offset control code
  6151. *
  6152. * Offset control codes have a second byte in the range 0x21 to 0x23,
  6153. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  6154. * data channel 2).
  6155. *
  6156. * @param {Integer} char0 The first byte
  6157. * @param {Integer} char1 The second byte
  6158. * @return {Boolean} Whether the 2 bytes are an offset control code
  6159. */
  6160. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  6161. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  6162. };
  6163. /**
  6164. * Detects if the 2-byte packet is a Preamble Address Code
  6165. *
  6166. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  6167. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  6168. * range 0x40 to 0x7f.
  6169. *
  6170. * @param {Integer} char0 The first byte
  6171. * @param {Integer} char1 The second byte
  6172. * @return {Boolean} Whether the 2 bytes are a PAC
  6173. */
  6174. Cea608Stream.prototype.isPAC = function (char0, char1) {
  6175. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  6176. };
  6177. /**
  6178. * Detects if a packet's second byte is in the range of a PAC color code
  6179. *
  6180. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  6181. * 0x60 to 0x6f.
  6182. *
  6183. * @param {Integer} char1 The second byte
  6184. * @return {Boolean} Whether the byte is a color PAC
  6185. */
  6186. Cea608Stream.prototype.isColorPAC = function (char1) {
  6187. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  6188. };
  6189. /**
  6190. * Detects if a single byte is in the range of a normal character
  6191. *
  6192. * Normal text bytes are in the range 0x20 to 0x7f.
  6193. *
  6194. * @param {Integer} char The byte
  6195. * @return {Boolean} Whether the byte is a normal character
  6196. */
  6197. Cea608Stream.prototype.isNormalChar = function (char) {
  6198. return char >= 0x20 && char <= 0x7f;
  6199. };
  6200. /**
  6201. * Configures roll-up
  6202. *
  6203. * @param {Integer} pts Current PTS
  6204. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  6205. * a new position
  6206. */
  6207. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  6208. // Reset the base row to the bottom row when switching modes
  6209. if (this.mode_ !== 'rollUp') {
  6210. this.row_ = BOTTOM_ROW;
  6211. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  6212. this.flushDisplayed(pts);
  6213. this.nonDisplayed_ = createDisplayBuffer();
  6214. this.displayed_ = createDisplayBuffer();
  6215. }
  6216. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  6217. // move currently displayed captions (up or down) to the new base row
  6218. for (var i = 0; i < this.rollUpRows_; i++) {
  6219. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  6220. this.displayed_[this.row_ - i] = '';
  6221. }
  6222. }
  6223. if (newBaseRow === undefined) {
  6224. newBaseRow = this.row_;
  6225. }
  6226. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  6227. }; // Adds the opening HTML tag for the passed character to the caption text,
  6228. // and keeps track of it for later closing
  6229. Cea608Stream.prototype.addFormatting = function (pts, format) {
  6230. this.formatting_ = this.formatting_.concat(format);
  6231. var text = format.reduce(function (text, format) {
  6232. return text + '<' + format + '>';
  6233. }, '');
  6234. this[this.mode_](pts, text);
  6235. }; // Adds HTML closing tags for current formatting to caption text and
  6236. // clears remembered formatting
  6237. Cea608Stream.prototype.clearFormatting = function (pts) {
  6238. if (!this.formatting_.length) {
  6239. return;
  6240. }
  6241. var text = this.formatting_.reverse().reduce(function (text, format) {
  6242. return text + '</' + format + '>';
  6243. }, '');
  6244. this.formatting_ = [];
  6245. this[this.mode_](pts, text);
  6246. }; // Mode Implementations
  6247. Cea608Stream.prototype.popOn = function (pts, text) {
  6248. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  6249. baseRow += text;
  6250. this.nonDisplayed_[this.row_] = baseRow;
  6251. };
  6252. Cea608Stream.prototype.rollUp = function (pts, text) {
  6253. var baseRow = this.displayed_[this.row_];
  6254. baseRow += text;
  6255. this.displayed_[this.row_] = baseRow;
  6256. };
  6257. Cea608Stream.prototype.shiftRowsUp_ = function () {
  6258. var i; // clear out inactive rows
  6259. for (i = 0; i < this.topRow_; i++) {
  6260. this.displayed_[i] = '';
  6261. }
  6262. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  6263. this.displayed_[i] = '';
  6264. } // shift displayed rows up
  6265. for (i = this.topRow_; i < this.row_; i++) {
  6266. this.displayed_[i] = this.displayed_[i + 1];
  6267. } // clear out the bottom row
  6268. this.displayed_[this.row_] = '';
  6269. };
  6270. Cea608Stream.prototype.paintOn = function (pts, text) {
  6271. var baseRow = this.displayed_[this.row_];
  6272. baseRow += text;
  6273. this.displayed_[this.row_] = baseRow;
  6274. }; // exports
  6275. var captionStream = {
  6276. CaptionStream: CaptionStream$2,
  6277. Cea608Stream: Cea608Stream,
  6278. Cea708Stream: Cea708Stream
  6279. };
  6280. /**
  6281. * mux.js
  6282. *
  6283. * Copyright (c) Brightcove
  6284. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6285. */
  6286. var streamTypes = {
  6287. H264_STREAM_TYPE: 0x1B,
  6288. ADTS_STREAM_TYPE: 0x0F,
  6289. METADATA_STREAM_TYPE: 0x15
  6290. };
  6291. /**
  6292. * mux.js
  6293. *
  6294. * Copyright (c) Brightcove
  6295. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6296. *
  6297. * Accepts program elementary stream (PES) data events and corrects
  6298. * decode and presentation time stamps to account for a rollover
  6299. * of the 33 bit value.
  6300. */
  6301. var Stream$6 = stream;
  6302. var MAX_TS = 8589934592;
  6303. var RO_THRESH = 4294967296;
  6304. var TYPE_SHARED = 'shared';
  6305. var handleRollover$1 = function (value, reference) {
  6306. var direction = 1;
  6307. if (value > reference) {
  6308. // If the current timestamp value is greater than our reference timestamp and we detect a
  6309. // timestamp rollover, this means the roll over is happening in the opposite direction.
  6310. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  6311. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  6312. // rollover point. In loading this segment, the timestamp values will be very large,
  6313. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  6314. // the time stamp to be `value - 2^33`.
  6315. direction = -1;
  6316. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  6317. // cause an incorrect adjustment.
  6318. while (Math.abs(reference - value) > RO_THRESH) {
  6319. value += direction * MAX_TS;
  6320. }
  6321. return value;
  6322. };
  6323. var TimestampRolloverStream$1 = function (type) {
  6324. var lastDTS, referenceDTS;
  6325. TimestampRolloverStream$1.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  6326. // video and audio. We could use `undefined` here, but having a string
  6327. // makes debugging a little clearer.
  6328. this.type_ = type || TYPE_SHARED;
  6329. this.push = function (data) {
  6330. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  6331. // streams will only accept data that matches their type.
  6332. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  6333. return;
  6334. }
  6335. if (referenceDTS === undefined) {
  6336. referenceDTS = data.dts;
  6337. }
  6338. data.dts = handleRollover$1(data.dts, referenceDTS);
  6339. data.pts = handleRollover$1(data.pts, referenceDTS);
  6340. lastDTS = data.dts;
  6341. this.trigger('data', data);
  6342. };
  6343. this.flush = function () {
  6344. referenceDTS = lastDTS;
  6345. this.trigger('done');
  6346. };
  6347. this.endTimeline = function () {
  6348. this.flush();
  6349. this.trigger('endedtimeline');
  6350. };
  6351. this.discontinuity = function () {
  6352. referenceDTS = void 0;
  6353. lastDTS = void 0;
  6354. };
  6355. this.reset = function () {
  6356. this.discontinuity();
  6357. this.trigger('reset');
  6358. };
  6359. };
  6360. TimestampRolloverStream$1.prototype = new Stream$6();
  6361. var timestampRolloverStream = {
  6362. TimestampRolloverStream: TimestampRolloverStream$1,
  6363. handleRollover: handleRollover$1
  6364. }; // Once IE11 support is dropped, this function should be removed.
  6365. var typedArrayIndexOf$1 = (typedArray, element, fromIndex) => {
  6366. if (!typedArray) {
  6367. return -1;
  6368. }
  6369. var currentIndex = fromIndex;
  6370. for (; currentIndex < typedArray.length; currentIndex++) {
  6371. if (typedArray[currentIndex] === element) {
  6372. return currentIndex;
  6373. }
  6374. }
  6375. return -1;
  6376. };
  6377. var typedArray = {
  6378. typedArrayIndexOf: typedArrayIndexOf$1
  6379. };
  6380. /**
  6381. * mux.js
  6382. *
  6383. * Copyright (c) Brightcove
  6384. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6385. *
  6386. * Tools for parsing ID3 frame data
  6387. * @see http://id3.org/id3v2.3.0
  6388. */
  6389. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  6390. // Frames that allow different types of text encoding contain a text
  6391. // encoding description byte [ID3v2.4.0 section 4.]
  6392. textEncodingDescriptionByte = {
  6393. Iso88591: 0x00,
  6394. // ISO-8859-1, terminated with \0.
  6395. Utf16: 0x01,
  6396. // UTF-16 encoded Unicode BOM, terminated with \0\0
  6397. Utf16be: 0x02,
  6398. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  6399. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  6400. },
  6401. // return a percent-encoded representation of the specified byte range
  6402. // @see http://en.wikipedia.org/wiki/Percent-encoding
  6403. percentEncode$1 = function (bytes, start, end) {
  6404. var i,
  6405. result = '';
  6406. for (i = start; i < end; i++) {
  6407. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  6408. }
  6409. return result;
  6410. },
  6411. // return the string representation of the specified byte range,
  6412. // interpreted as UTf-8.
  6413. parseUtf8 = function (bytes, start, end) {
  6414. return decodeURIComponent(percentEncode$1(bytes, start, end));
  6415. },
  6416. // return the string representation of the specified byte range,
  6417. // interpreted as ISO-8859-1.
  6418. parseIso88591$1 = function (bytes, start, end) {
  6419. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  6420. },
  6421. parseSyncSafeInteger$1 = function (data) {
  6422. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  6423. },
  6424. frameParsers = {
  6425. 'APIC': function (frame) {
  6426. var i = 1,
  6427. mimeTypeEndIndex,
  6428. descriptionEndIndex,
  6429. LINK_MIME_TYPE = '-->';
  6430. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6431. // ignore frames with unrecognized character encodings
  6432. return;
  6433. } // parsing fields [ID3v2.4.0 section 4.14.]
  6434. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6435. if (mimeTypeEndIndex < 0) {
  6436. // malformed frame
  6437. return;
  6438. } // parsing Mime type field (terminated with \0)
  6439. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  6440. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  6441. frame.pictureType = frame.data[i];
  6442. i++;
  6443. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  6444. if (descriptionEndIndex < 0) {
  6445. // malformed frame
  6446. return;
  6447. } // parsing Description field (terminated with \0)
  6448. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  6449. i = descriptionEndIndex + 1;
  6450. if (frame.mimeType === LINK_MIME_TYPE) {
  6451. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  6452. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  6453. } else {
  6454. // parsing Picture Data field as binary data
  6455. frame.pictureData = frame.data.subarray(i, frame.data.length);
  6456. }
  6457. },
  6458. 'T*': function (frame) {
  6459. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6460. // ignore frames with unrecognized character encodings
  6461. return;
  6462. } // parse text field, do not include null terminator in the frame value
  6463. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  6464. 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.]
  6465. frame.values = frame.value.split('\0');
  6466. },
  6467. 'TXXX': function (frame) {
  6468. var descriptionEndIndex;
  6469. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6470. // ignore frames with unrecognized character encodings
  6471. return;
  6472. }
  6473. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6474. if (descriptionEndIndex === -1) {
  6475. return;
  6476. } // parse the text fields
  6477. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  6478. // frames that allow different types of encoding contain terminated text
  6479. // [ID3v2.4.0 section 4.]
  6480. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  6481. frame.data = frame.value;
  6482. },
  6483. 'W*': function (frame) {
  6484. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6485. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  6486. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  6487. },
  6488. 'WXXX': function (frame) {
  6489. var descriptionEndIndex;
  6490. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  6491. // ignore frames with unrecognized character encodings
  6492. return;
  6493. }
  6494. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  6495. if (descriptionEndIndex === -1) {
  6496. return;
  6497. } // parse the description and URL fields
  6498. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  6499. // if the value is followed by a string termination all the following information
  6500. // should be ignored [ID3v2.4.0 section 4.3]
  6501. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  6502. },
  6503. 'PRIV': function (frame) {
  6504. var i;
  6505. for (i = 0; i < frame.data.length; i++) {
  6506. if (frame.data[i] === 0) {
  6507. // parse the description and URL fields
  6508. frame.owner = parseIso88591$1(frame.data, 0, i);
  6509. break;
  6510. }
  6511. }
  6512. frame.privateData = frame.data.subarray(i + 1);
  6513. frame.data = frame.privateData;
  6514. }
  6515. };
  6516. var parseId3Frames$1 = function (data) {
  6517. var frameSize,
  6518. frameHeader,
  6519. frameStart = 10,
  6520. tagSize = 0,
  6521. frames = []; // If we don't have enough data for a header, 10 bytes,
  6522. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  6523. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  6524. return;
  6525. } // the frame size is transmitted as a 28-bit integer in the
  6526. // last four bytes of the ID3 header.
  6527. // The most significant bit of each byte is dropped and the
  6528. // results concatenated to recover the actual value.
  6529. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  6530. // convenient for our comparisons to include it
  6531. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  6532. var hasExtendedHeader = data[5] & 0x40;
  6533. if (hasExtendedHeader) {
  6534. // advance the frame start past the extended header
  6535. frameStart += 4; // header size field
  6536. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  6537. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  6538. } // parse one or more ID3 frames
  6539. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  6540. do {
  6541. // determine the number of bytes in this frame
  6542. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  6543. if (frameSize < 1) {
  6544. break;
  6545. }
  6546. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  6547. var frame = {
  6548. id: frameHeader,
  6549. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  6550. };
  6551. frame.key = frame.id; // parse frame values
  6552. if (frameParsers[frame.id]) {
  6553. // use frame specific parser
  6554. frameParsers[frame.id](frame);
  6555. } else if (frame.id[0] === 'T') {
  6556. // use text frame generic parser
  6557. frameParsers['T*'](frame);
  6558. } else if (frame.id[0] === 'W') {
  6559. // use URL link frame generic parser
  6560. frameParsers['W*'](frame);
  6561. }
  6562. frames.push(frame);
  6563. frameStart += 10; // advance past the frame header
  6564. frameStart += frameSize; // advance past the frame body
  6565. } while (frameStart < tagSize);
  6566. return frames;
  6567. };
  6568. var parseId3 = {
  6569. parseId3Frames: parseId3Frames$1,
  6570. parseSyncSafeInteger: parseSyncSafeInteger$1,
  6571. frameParsers: frameParsers
  6572. };
  6573. /**
  6574. * mux.js
  6575. *
  6576. * Copyright (c) Brightcove
  6577. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6578. *
  6579. * Accepts program elementary stream (PES) data events and parses out
  6580. * ID3 metadata from them, if present.
  6581. * @see http://id3.org/id3v2.3.0
  6582. */
  6583. var Stream$5 = stream,
  6584. StreamTypes$3 = streamTypes,
  6585. id3 = parseId3,
  6586. MetadataStream;
  6587. MetadataStream = function (options) {
  6588. var settings = {
  6589. // the bytes of the program-level descriptor field in MP2T
  6590. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  6591. // program element descriptors"
  6592. descriptor: options && options.descriptor
  6593. },
  6594. // the total size in bytes of the ID3 tag being parsed
  6595. tagSize = 0,
  6596. // tag data that is not complete enough to be parsed
  6597. buffer = [],
  6598. // the total number of bytes currently in the buffer
  6599. bufferSize = 0,
  6600. i;
  6601. MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  6602. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  6603. this.dispatchType = StreamTypes$3.METADATA_STREAM_TYPE.toString(16);
  6604. if (settings.descriptor) {
  6605. for (i = 0; i < settings.descriptor.length; i++) {
  6606. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  6607. }
  6608. }
  6609. this.push = function (chunk) {
  6610. var tag, frameStart, frameSize, frame, i, frameHeader;
  6611. if (chunk.type !== 'timed-metadata') {
  6612. return;
  6613. } // if data_alignment_indicator is set in the PES header,
  6614. // we must have the start of a new ID3 tag. Assume anything
  6615. // remaining in the buffer was malformed and throw it out
  6616. if (chunk.dataAlignmentIndicator) {
  6617. bufferSize = 0;
  6618. buffer.length = 0;
  6619. } // ignore events that don't look like ID3 data
  6620. 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))) {
  6621. this.trigger('log', {
  6622. level: 'warn',
  6623. message: 'Skipping unrecognized metadata packet'
  6624. });
  6625. return;
  6626. } // add this chunk to the data we've collected so far
  6627. buffer.push(chunk);
  6628. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  6629. if (buffer.length === 1) {
  6630. // the frame size is transmitted as a 28-bit integer in the
  6631. // last four bytes of the ID3 header.
  6632. // The most significant bit of each byte is dropped and the
  6633. // results concatenated to recover the actual value.
  6634. tagSize = id3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  6635. // convenient for our comparisons to include it
  6636. tagSize += 10;
  6637. } // if the entire frame has not arrived, wait for more data
  6638. if (bufferSize < tagSize) {
  6639. return;
  6640. } // collect the entire frame so it can be parsed
  6641. tag = {
  6642. data: new Uint8Array(tagSize),
  6643. frames: [],
  6644. pts: buffer[0].pts,
  6645. dts: buffer[0].dts
  6646. };
  6647. for (i = 0; i < tagSize;) {
  6648. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  6649. i += buffer[0].data.byteLength;
  6650. bufferSize -= buffer[0].data.byteLength;
  6651. buffer.shift();
  6652. } // find the start of the first frame and the end of the tag
  6653. frameStart = 10;
  6654. if (tag.data[5] & 0x40) {
  6655. // advance the frame start past the extended header
  6656. frameStart += 4; // header size field
  6657. frameStart += id3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  6658. tagSize -= id3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  6659. } // parse one or more ID3 frames
  6660. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  6661. do {
  6662. // determine the number of bytes in this frame
  6663. frameSize = id3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  6664. if (frameSize < 1) {
  6665. this.trigger('log', {
  6666. level: 'warn',
  6667. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  6668. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  6669. // to be sent along.
  6670. break;
  6671. }
  6672. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  6673. frame = {
  6674. id: frameHeader,
  6675. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  6676. };
  6677. frame.key = frame.id; // parse frame values
  6678. if (id3.frameParsers[frame.id]) {
  6679. // use frame specific parser
  6680. id3.frameParsers[frame.id](frame);
  6681. } else if (frame.id[0] === 'T') {
  6682. // use text frame generic parser
  6683. id3.frameParsers['T*'](frame);
  6684. } else if (frame.id[0] === 'W') {
  6685. // use URL link frame generic parser
  6686. id3.frameParsers['W*'](frame);
  6687. } // handle the special PRIV frame used to indicate the start
  6688. // time for raw AAC data
  6689. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  6690. var d = frame.data,
  6691. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  6692. size *= 4;
  6693. size += d[7] & 0x03;
  6694. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  6695. // on the value of this frame
  6696. // we couldn't have known the appropriate pts and dts before
  6697. // parsing this ID3 tag so set those values now
  6698. if (tag.pts === undefined && tag.dts === undefined) {
  6699. tag.pts = frame.timeStamp;
  6700. tag.dts = frame.timeStamp;
  6701. }
  6702. this.trigger('timestamp', frame);
  6703. }
  6704. tag.frames.push(frame);
  6705. frameStart += 10; // advance past the frame header
  6706. frameStart += frameSize; // advance past the frame body
  6707. } while (frameStart < tagSize);
  6708. this.trigger('data', tag);
  6709. };
  6710. };
  6711. MetadataStream.prototype = new Stream$5();
  6712. var metadataStream = MetadataStream;
  6713. /**
  6714. * mux.js
  6715. *
  6716. * Copyright (c) Brightcove
  6717. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6718. *
  6719. * A stream-based mp2t to mp4 converter. This utility can be used to
  6720. * deliver mp4s to a SourceBuffer on platforms that support native
  6721. * Media Source Extensions.
  6722. */
  6723. var Stream$4 = stream,
  6724. CaptionStream$1 = captionStream,
  6725. StreamTypes$2 = streamTypes,
  6726. TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  6727. var TransportPacketStream, TransportParseStream, ElementaryStream; // constants
  6728. var MP2T_PACKET_LENGTH$1 = 188,
  6729. // bytes
  6730. SYNC_BYTE$1 = 0x47;
  6731. /**
  6732. * Splits an incoming stream of binary data into MPEG-2 Transport
  6733. * Stream packets.
  6734. */
  6735. TransportPacketStream = function () {
  6736. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  6737. bytesInBuffer = 0;
  6738. TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  6739. /**
  6740. * Split a stream of data into M2TS packets
  6741. **/
  6742. this.push = function (bytes) {
  6743. var startIndex = 0,
  6744. endIndex = MP2T_PACKET_LENGTH$1,
  6745. everything; // If there are bytes remaining from the last segment, prepend them to the
  6746. // bytes that were pushed in
  6747. if (bytesInBuffer) {
  6748. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  6749. everything.set(buffer.subarray(0, bytesInBuffer));
  6750. everything.set(bytes, bytesInBuffer);
  6751. bytesInBuffer = 0;
  6752. } else {
  6753. everything = bytes;
  6754. } // While we have enough data for a packet
  6755. while (endIndex < everything.byteLength) {
  6756. // Look for a pair of start and end sync bytes in the data..
  6757. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  6758. // We found a packet so emit it and jump one whole packet forward in
  6759. // the stream
  6760. this.trigger('data', everything.subarray(startIndex, endIndex));
  6761. startIndex += MP2T_PACKET_LENGTH$1;
  6762. endIndex += MP2T_PACKET_LENGTH$1;
  6763. continue;
  6764. } // If we get here, we have somehow become de-synchronized and we need to step
  6765. // forward one byte at a time until we find a pair of sync bytes that denote
  6766. // a packet
  6767. startIndex++;
  6768. endIndex++;
  6769. } // If there was some data left over at the end of the segment that couldn't
  6770. // possibly be a whole packet, keep it because it might be the start of a packet
  6771. // that continues in the next segment
  6772. if (startIndex < everything.byteLength) {
  6773. buffer.set(everything.subarray(startIndex), 0);
  6774. bytesInBuffer = everything.byteLength - startIndex;
  6775. }
  6776. };
  6777. /**
  6778. * Passes identified M2TS packets to the TransportParseStream to be parsed
  6779. **/
  6780. this.flush = function () {
  6781. // If the buffer contains a whole packet when we are being flushed, emit it
  6782. // and empty the buffer. Otherwise hold onto the data because it may be
  6783. // important for decoding the next segment
  6784. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  6785. this.trigger('data', buffer);
  6786. bytesInBuffer = 0;
  6787. }
  6788. this.trigger('done');
  6789. };
  6790. this.endTimeline = function () {
  6791. this.flush();
  6792. this.trigger('endedtimeline');
  6793. };
  6794. this.reset = function () {
  6795. bytesInBuffer = 0;
  6796. this.trigger('reset');
  6797. };
  6798. };
  6799. TransportPacketStream.prototype = new Stream$4();
  6800. /**
  6801. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  6802. * forms of the individual transport stream packets.
  6803. */
  6804. TransportParseStream = function () {
  6805. var parsePsi, parsePat, parsePmt, self;
  6806. TransportParseStream.prototype.init.call(this);
  6807. self = this;
  6808. this.packetsWaitingForPmt = [];
  6809. this.programMapTable = undefined;
  6810. parsePsi = function (payload, psi) {
  6811. var offset = 0; // PSI packets may be split into multiple sections and those
  6812. // sections may be split into multiple packets. If a PSI
  6813. // section starts in this packet, the payload_unit_start_indicator
  6814. // will be true and the first byte of the payload will indicate
  6815. // the offset from the current position to the start of the
  6816. // section.
  6817. if (psi.payloadUnitStartIndicator) {
  6818. offset += payload[offset] + 1;
  6819. }
  6820. if (psi.type === 'pat') {
  6821. parsePat(payload.subarray(offset), psi);
  6822. } else {
  6823. parsePmt(payload.subarray(offset), psi);
  6824. }
  6825. };
  6826. parsePat = function (payload, pat) {
  6827. pat.section_number = payload[7]; // eslint-disable-line camelcase
  6828. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  6829. // skip the PSI header and parse the first PMT entry
  6830. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  6831. pat.pmtPid = self.pmtPid;
  6832. };
  6833. /**
  6834. * Parse out the relevant fields of a Program Map Table (PMT).
  6835. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  6836. * packet. The first byte in this array should be the table_id
  6837. * field.
  6838. * @param pmt {object} the object that should be decorated with
  6839. * fields parsed from the PMT.
  6840. */
  6841. parsePmt = function (payload, pmt) {
  6842. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  6843. // take effect. We don't believe this should ever be the case
  6844. // for HLS but we'll ignore "forward" PMT declarations if we see
  6845. // them. Future PMT declarations have the current_next_indicator
  6846. // set to zero.
  6847. if (!(payload[5] & 0x01)) {
  6848. return;
  6849. } // overwrite any existing program map table
  6850. self.programMapTable = {
  6851. video: null,
  6852. audio: null,
  6853. 'timed-metadata': {}
  6854. }; // the mapping table ends at the end of the current section
  6855. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  6856. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  6857. // long the program info descriptors are
  6858. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  6859. offset = 12 + programInfoLength;
  6860. while (offset < tableEnd) {
  6861. var streamType = payload[offset];
  6862. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  6863. // TODO: should this be done for metadata too? for now maintain behavior of
  6864. // multiple metadata streams
  6865. if (streamType === StreamTypes$2.H264_STREAM_TYPE && self.programMapTable.video === null) {
  6866. self.programMapTable.video = pid;
  6867. } else if (streamType === StreamTypes$2.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  6868. self.programMapTable.audio = pid;
  6869. } else if (streamType === StreamTypes$2.METADATA_STREAM_TYPE) {
  6870. // map pid to stream type for metadata streams
  6871. self.programMapTable['timed-metadata'][pid] = streamType;
  6872. } // move to the next table entry
  6873. // skip past the elementary stream descriptors, if present
  6874. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  6875. } // record the map on the packet as well
  6876. pmt.programMapTable = self.programMapTable;
  6877. };
  6878. /**
  6879. * Deliver a new MP2T packet to the next stream in the pipeline.
  6880. */
  6881. this.push = function (packet) {
  6882. var result = {},
  6883. offset = 4;
  6884. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  6885. result.pid = packet[1] & 0x1f;
  6886. result.pid <<= 8;
  6887. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  6888. // fifth byte of the TS packet header. The adaptation field is
  6889. // used to add stuffing to PES packets that don't fill a complete
  6890. // TS packet, and to specify some forms of timing and control data
  6891. // that we do not currently use.
  6892. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  6893. offset += packet[offset] + 1;
  6894. } // parse the rest of the packet based on the type
  6895. if (result.pid === 0) {
  6896. result.type = 'pat';
  6897. parsePsi(packet.subarray(offset), result);
  6898. this.trigger('data', result);
  6899. } else if (result.pid === this.pmtPid) {
  6900. result.type = 'pmt';
  6901. parsePsi(packet.subarray(offset), result);
  6902. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  6903. while (this.packetsWaitingForPmt.length) {
  6904. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  6905. }
  6906. } else if (this.programMapTable === undefined) {
  6907. // When we have not seen a PMT yet, defer further processing of
  6908. // PES packets until one has been parsed
  6909. this.packetsWaitingForPmt.push([packet, offset, result]);
  6910. } else {
  6911. this.processPes_(packet, offset, result);
  6912. }
  6913. };
  6914. this.processPes_ = function (packet, offset, result) {
  6915. // set the appropriate stream type
  6916. if (result.pid === this.programMapTable.video) {
  6917. result.streamType = StreamTypes$2.H264_STREAM_TYPE;
  6918. } else if (result.pid === this.programMapTable.audio) {
  6919. result.streamType = StreamTypes$2.ADTS_STREAM_TYPE;
  6920. } else {
  6921. // if not video or audio, it is timed-metadata or unknown
  6922. // if unknown, streamType will be undefined
  6923. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  6924. }
  6925. result.type = 'pes';
  6926. result.data = packet.subarray(offset);
  6927. this.trigger('data', result);
  6928. };
  6929. };
  6930. TransportParseStream.prototype = new Stream$4();
  6931. TransportParseStream.STREAM_TYPES = {
  6932. h264: 0x1b,
  6933. adts: 0x0f
  6934. };
  6935. /**
  6936. * Reconsistutes program elementary stream (PES) packets from parsed
  6937. * transport stream packets. That is, if you pipe an
  6938. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  6939. * events will be events which capture the bytes for individual PES
  6940. * packets plus relevant metadata that has been extracted from the
  6941. * container.
  6942. */
  6943. ElementaryStream = function () {
  6944. var self = this,
  6945. segmentHadPmt = false,
  6946. // PES packet fragments
  6947. video = {
  6948. data: [],
  6949. size: 0
  6950. },
  6951. audio = {
  6952. data: [],
  6953. size: 0
  6954. },
  6955. timedMetadata = {
  6956. data: [],
  6957. size: 0
  6958. },
  6959. programMapTable,
  6960. parsePes = function (payload, pes) {
  6961. var ptsDtsFlags;
  6962. const startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  6963. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  6964. // that are frame data that is continuing from the previous fragment. This
  6965. // is to check that the pes data is the start of a new pes payload
  6966. if (startPrefix !== 1) {
  6967. return;
  6968. } // get the packet length, this will be 0 for video
  6969. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  6970. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  6971. // and a DTS value. Determine what combination of values is
  6972. // available to work with.
  6973. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  6974. // performs all bitwise operations on 32-bit integers but javascript
  6975. // supports a much greater range (52-bits) of integer using standard
  6976. // mathematical operations.
  6977. // We construct a 31-bit value using bitwise operators over the 31
  6978. // most significant bits and then multiply by 4 (equal to a left-shift
  6979. // of 2) before we add the final 2 least significant bits of the
  6980. // timestamp (equal to an OR.)
  6981. if (ptsDtsFlags & 0xC0) {
  6982. // the PTS and DTS are not written out directly. For information
  6983. // on how they are encoded, see
  6984. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  6985. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  6986. pes.pts *= 4; // Left shift by 2
  6987. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  6988. pes.dts = pes.pts;
  6989. if (ptsDtsFlags & 0x40) {
  6990. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  6991. pes.dts *= 4; // Left shift by 2
  6992. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  6993. }
  6994. } // the data section starts immediately after the PES header.
  6995. // pes_header_data_length specifies the number of header bytes
  6996. // that follow the last byte of the field.
  6997. pes.data = payload.subarray(9 + payload[8]);
  6998. },
  6999. /**
  7000. * Pass completely parsed PES packets to the next stream in the pipeline
  7001. **/
  7002. flushStream = function (stream, type, forceFlush) {
  7003. var packetData = new Uint8Array(stream.size),
  7004. event = {
  7005. type: type
  7006. },
  7007. i = 0,
  7008. offset = 0,
  7009. packetFlushable = false,
  7010. fragment; // do nothing if there is not enough buffered data for a complete
  7011. // PES header
  7012. if (!stream.data.length || stream.size < 9) {
  7013. return;
  7014. }
  7015. event.trackId = stream.data[0].pid; // reassemble the packet
  7016. for (i = 0; i < stream.data.length; i++) {
  7017. fragment = stream.data[i];
  7018. packetData.set(fragment.data, offset);
  7019. offset += fragment.data.byteLength;
  7020. } // parse assembled packet's PES header
  7021. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  7022. // check that there is enough stream data to fill the packet
  7023. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  7024. if (forceFlush || packetFlushable) {
  7025. stream.size = 0;
  7026. stream.data.length = 0;
  7027. } // only emit packets that are complete. this is to avoid assembling
  7028. // incomplete PES packets due to poor segmentation
  7029. if (packetFlushable) {
  7030. self.trigger('data', event);
  7031. }
  7032. };
  7033. ElementaryStream.prototype.init.call(this);
  7034. /**
  7035. * Identifies M2TS packet types and parses PES packets using metadata
  7036. * parsed from the PMT
  7037. **/
  7038. this.push = function (data) {
  7039. ({
  7040. pat: function () {// we have to wait for the PMT to arrive as well before we
  7041. // have any meaningful metadata
  7042. },
  7043. pes: function () {
  7044. var stream, streamType;
  7045. switch (data.streamType) {
  7046. case StreamTypes$2.H264_STREAM_TYPE:
  7047. stream = video;
  7048. streamType = 'video';
  7049. break;
  7050. case StreamTypes$2.ADTS_STREAM_TYPE:
  7051. stream = audio;
  7052. streamType = 'audio';
  7053. break;
  7054. case StreamTypes$2.METADATA_STREAM_TYPE:
  7055. stream = timedMetadata;
  7056. streamType = 'timed-metadata';
  7057. break;
  7058. default:
  7059. // ignore unknown stream types
  7060. return;
  7061. } // if a new packet is starting, we can flush the completed
  7062. // packet
  7063. if (data.payloadUnitStartIndicator) {
  7064. flushStream(stream, streamType, true);
  7065. } // buffer this fragment until we are sure we've received the
  7066. // complete payload
  7067. stream.data.push(data);
  7068. stream.size += data.data.byteLength;
  7069. },
  7070. pmt: function () {
  7071. var event = {
  7072. type: 'metadata',
  7073. tracks: []
  7074. };
  7075. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  7076. if (programMapTable.video !== null) {
  7077. event.tracks.push({
  7078. timelineStartInfo: {
  7079. baseMediaDecodeTime: 0
  7080. },
  7081. id: +programMapTable.video,
  7082. codec: 'avc',
  7083. type: 'video'
  7084. });
  7085. }
  7086. if (programMapTable.audio !== null) {
  7087. event.tracks.push({
  7088. timelineStartInfo: {
  7089. baseMediaDecodeTime: 0
  7090. },
  7091. id: +programMapTable.audio,
  7092. codec: 'adts',
  7093. type: 'audio'
  7094. });
  7095. }
  7096. segmentHadPmt = true;
  7097. self.trigger('data', event);
  7098. }
  7099. })[data.type]();
  7100. };
  7101. this.reset = function () {
  7102. video.size = 0;
  7103. video.data.length = 0;
  7104. audio.size = 0;
  7105. audio.data.length = 0;
  7106. this.trigger('reset');
  7107. };
  7108. /**
  7109. * Flush any remaining input. Video PES packets may be of variable
  7110. * length. Normally, the start of a new video packet can trigger the
  7111. * finalization of the previous packet. That is not possible if no
  7112. * more video is forthcoming, however. In that case, some other
  7113. * mechanism (like the end of the file) has to be employed. When it is
  7114. * clear that no additional data is forthcoming, calling this method
  7115. * will flush the buffered packets.
  7116. */
  7117. this.flushStreams_ = function () {
  7118. // !!THIS ORDER IS IMPORTANT!!
  7119. // video first then audio
  7120. flushStream(video, 'video');
  7121. flushStream(audio, 'audio');
  7122. flushStream(timedMetadata, 'timed-metadata');
  7123. };
  7124. this.flush = function () {
  7125. // if on flush we haven't had a pmt emitted
  7126. // and we have a pmt to emit. emit the pmt
  7127. // so that we trigger a trackinfo downstream.
  7128. if (!segmentHadPmt && programMapTable) {
  7129. var pmt = {
  7130. type: 'metadata',
  7131. tracks: []
  7132. }; // translate audio and video streams to tracks
  7133. if (programMapTable.video !== null) {
  7134. pmt.tracks.push({
  7135. timelineStartInfo: {
  7136. baseMediaDecodeTime: 0
  7137. },
  7138. id: +programMapTable.video,
  7139. codec: 'avc',
  7140. type: 'video'
  7141. });
  7142. }
  7143. if (programMapTable.audio !== null) {
  7144. pmt.tracks.push({
  7145. timelineStartInfo: {
  7146. baseMediaDecodeTime: 0
  7147. },
  7148. id: +programMapTable.audio,
  7149. codec: 'adts',
  7150. type: 'audio'
  7151. });
  7152. }
  7153. self.trigger('data', pmt);
  7154. }
  7155. segmentHadPmt = false;
  7156. this.flushStreams_();
  7157. this.trigger('done');
  7158. };
  7159. };
  7160. ElementaryStream.prototype = new Stream$4();
  7161. var m2ts$1 = {
  7162. PAT_PID: 0x0000,
  7163. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  7164. TransportPacketStream: TransportPacketStream,
  7165. TransportParseStream: TransportParseStream,
  7166. ElementaryStream: ElementaryStream,
  7167. TimestampRolloverStream: TimestampRolloverStream,
  7168. CaptionStream: CaptionStream$1.CaptionStream,
  7169. Cea608Stream: CaptionStream$1.Cea608Stream,
  7170. Cea708Stream: CaptionStream$1.Cea708Stream,
  7171. MetadataStream: metadataStream
  7172. };
  7173. for (var type in StreamTypes$2) {
  7174. if (StreamTypes$2.hasOwnProperty(type)) {
  7175. m2ts$1[type] = StreamTypes$2[type];
  7176. }
  7177. }
  7178. var m2ts_1 = m2ts$1;
  7179. /**
  7180. * mux.js
  7181. *
  7182. * Copyright (c) Brightcove
  7183. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7184. */
  7185. var Stream$3 = stream;
  7186. var ONE_SECOND_IN_TS$2 = clock$2.ONE_SECOND_IN_TS;
  7187. var AdtsStream$1;
  7188. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7189. /*
  7190. * Accepts a ElementaryStream and emits data events with parsed
  7191. * AAC Audio Frames of the individual packets. Input audio in ADTS
  7192. * format is unpacked and re-emitted as AAC frames.
  7193. *
  7194. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  7195. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  7196. */
  7197. AdtsStream$1 = function (handlePartialSegments) {
  7198. var buffer,
  7199. frameNum = 0;
  7200. AdtsStream$1.prototype.init.call(this);
  7201. this.skipWarn_ = function (start, end) {
  7202. this.trigger('log', {
  7203. level: 'warn',
  7204. message: `adts skiping bytes ${start} to ${end} in frame ${frameNum} outside syncword`
  7205. });
  7206. };
  7207. this.push = function (packet) {
  7208. var i = 0,
  7209. frameLength,
  7210. protectionSkipBytes,
  7211. oldBuffer,
  7212. sampleCount,
  7213. adtsFrameDuration;
  7214. if (!handlePartialSegments) {
  7215. frameNum = 0;
  7216. }
  7217. if (packet.type !== 'audio') {
  7218. // ignore non-audio data
  7219. return;
  7220. } // Prepend any data in the buffer to the input data so that we can parse
  7221. // aac frames the cross a PES packet boundary
  7222. if (buffer && buffer.length) {
  7223. oldBuffer = buffer;
  7224. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  7225. buffer.set(oldBuffer);
  7226. buffer.set(packet.data, oldBuffer.byteLength);
  7227. } else {
  7228. buffer = packet.data;
  7229. } // unpack any ADTS frames which have been fully received
  7230. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  7231. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  7232. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  7233. while (i + 7 < buffer.length) {
  7234. // Look for the start of an ADTS header..
  7235. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  7236. if (typeof skip !== 'number') {
  7237. skip = i;
  7238. } // If a valid header was not found, jump one forward and attempt to
  7239. // find a valid ADTS header starting at the next byte
  7240. i++;
  7241. continue;
  7242. }
  7243. if (typeof skip === 'number') {
  7244. this.skipWarn_(skip, i);
  7245. skip = null;
  7246. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  7247. // end of the ADTS header
  7248. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  7249. // end of the sync sequence
  7250. // NOTE: frame length includes the size of the header
  7251. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  7252. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  7253. 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,
  7254. // then we have to wait for more data
  7255. if (buffer.byteLength - i < frameLength) {
  7256. break;
  7257. } // Otherwise, deliver the complete AAC frame
  7258. this.trigger('data', {
  7259. pts: packet.pts + frameNum * adtsFrameDuration,
  7260. dts: packet.dts + frameNum * adtsFrameDuration,
  7261. sampleCount: sampleCount,
  7262. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  7263. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  7264. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  7265. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  7266. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  7267. samplesize: 16,
  7268. // data is the frame without it's header
  7269. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  7270. });
  7271. frameNum++;
  7272. i += frameLength;
  7273. }
  7274. if (typeof skip === 'number') {
  7275. this.skipWarn_(skip, i);
  7276. skip = null;
  7277. } // remove processed bytes from the buffer.
  7278. buffer = buffer.subarray(i);
  7279. };
  7280. this.flush = function () {
  7281. frameNum = 0;
  7282. this.trigger('done');
  7283. };
  7284. this.reset = function () {
  7285. buffer = void 0;
  7286. this.trigger('reset');
  7287. };
  7288. this.endTimeline = function () {
  7289. buffer = void 0;
  7290. this.trigger('endedtimeline');
  7291. };
  7292. };
  7293. AdtsStream$1.prototype = new Stream$3();
  7294. var adts = AdtsStream$1;
  7295. /**
  7296. * mux.js
  7297. *
  7298. * Copyright (c) Brightcove
  7299. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7300. */
  7301. var ExpGolomb$1;
  7302. /**
  7303. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  7304. * scheme used by h264.
  7305. */
  7306. ExpGolomb$1 = function (workingData) {
  7307. var // the number of bytes left to examine in workingData
  7308. workingBytesAvailable = workingData.byteLength,
  7309. // the current word being examined
  7310. workingWord = 0,
  7311. // :uint
  7312. // the number of bits left to examine in the current word
  7313. workingBitsAvailable = 0; // :uint;
  7314. // ():uint
  7315. this.length = function () {
  7316. return 8 * workingBytesAvailable;
  7317. }; // ():uint
  7318. this.bitsAvailable = function () {
  7319. return 8 * workingBytesAvailable + workingBitsAvailable;
  7320. }; // ():void
  7321. this.loadWord = function () {
  7322. var position = workingData.byteLength - workingBytesAvailable,
  7323. workingBytes = new Uint8Array(4),
  7324. availableBytes = Math.min(4, workingBytesAvailable);
  7325. if (availableBytes === 0) {
  7326. throw new Error('no bytes available');
  7327. }
  7328. workingBytes.set(workingData.subarray(position, position + availableBytes));
  7329. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  7330. workingBitsAvailable = availableBytes * 8;
  7331. workingBytesAvailable -= availableBytes;
  7332. }; // (count:int):void
  7333. this.skipBits = function (count) {
  7334. var skipBytes; // :int
  7335. if (workingBitsAvailable > count) {
  7336. workingWord <<= count;
  7337. workingBitsAvailable -= count;
  7338. } else {
  7339. count -= workingBitsAvailable;
  7340. skipBytes = Math.floor(count / 8);
  7341. count -= skipBytes * 8;
  7342. workingBytesAvailable -= skipBytes;
  7343. this.loadWord();
  7344. workingWord <<= count;
  7345. workingBitsAvailable -= count;
  7346. }
  7347. }; // (size:int):uint
  7348. this.readBits = function (size) {
  7349. var bits = Math.min(workingBitsAvailable, size),
  7350. // :uint
  7351. valu = workingWord >>> 32 - bits; // :uint
  7352. // if size > 31, handle error
  7353. workingBitsAvailable -= bits;
  7354. if (workingBitsAvailable > 0) {
  7355. workingWord <<= bits;
  7356. } else if (workingBytesAvailable > 0) {
  7357. this.loadWord();
  7358. }
  7359. bits = size - bits;
  7360. if (bits > 0) {
  7361. return valu << bits | this.readBits(bits);
  7362. }
  7363. return valu;
  7364. }; // ():uint
  7365. this.skipLeadingZeros = function () {
  7366. var leadingZeroCount; // :uint
  7367. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  7368. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  7369. // the first bit of working word is 1
  7370. workingWord <<= leadingZeroCount;
  7371. workingBitsAvailable -= leadingZeroCount;
  7372. return leadingZeroCount;
  7373. }
  7374. } // we exhausted workingWord and still have not found a 1
  7375. this.loadWord();
  7376. return leadingZeroCount + this.skipLeadingZeros();
  7377. }; // ():void
  7378. this.skipUnsignedExpGolomb = function () {
  7379. this.skipBits(1 + this.skipLeadingZeros());
  7380. }; // ():void
  7381. this.skipExpGolomb = function () {
  7382. this.skipBits(1 + this.skipLeadingZeros());
  7383. }; // ():uint
  7384. this.readUnsignedExpGolomb = function () {
  7385. var clz = this.skipLeadingZeros(); // :uint
  7386. return this.readBits(clz + 1) - 1;
  7387. }; // ():int
  7388. this.readExpGolomb = function () {
  7389. var valu = this.readUnsignedExpGolomb(); // :int
  7390. if (0x01 & valu) {
  7391. // the number is odd if the low order bit is set
  7392. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  7393. }
  7394. return -1 * (valu >>> 1); // divide by two then make it negative
  7395. }; // Some convenience functions
  7396. // :Boolean
  7397. this.readBoolean = function () {
  7398. return this.readBits(1) === 1;
  7399. }; // ():int
  7400. this.readUnsignedByte = function () {
  7401. return this.readBits(8);
  7402. };
  7403. this.loadWord();
  7404. };
  7405. var expGolomb = ExpGolomb$1;
  7406. /**
  7407. * mux.js
  7408. *
  7409. * Copyright (c) Brightcove
  7410. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7411. */
  7412. var Stream$2 = stream;
  7413. var ExpGolomb = expGolomb;
  7414. var H264Stream$1, NalByteStream;
  7415. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  7416. /**
  7417. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  7418. */
  7419. NalByteStream = function () {
  7420. var syncPoint = 0,
  7421. i,
  7422. buffer;
  7423. NalByteStream.prototype.init.call(this);
  7424. /*
  7425. * Scans a byte stream and triggers a data event with the NAL units found.
  7426. * @param {Object} data Event received from H264Stream
  7427. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  7428. *
  7429. * @see H264Stream.push
  7430. */
  7431. this.push = function (data) {
  7432. var swapBuffer;
  7433. if (!buffer) {
  7434. buffer = data.data;
  7435. } else {
  7436. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  7437. swapBuffer.set(buffer);
  7438. swapBuffer.set(data.data, buffer.byteLength);
  7439. buffer = swapBuffer;
  7440. }
  7441. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  7442. // scan for NAL unit boundaries
  7443. // a match looks like this:
  7444. // 0 0 1 .. NAL .. 0 0 1
  7445. // ^ sync point ^ i
  7446. // or this:
  7447. // 0 0 1 .. NAL .. 0 0 0
  7448. // ^ sync point ^ i
  7449. // advance the sync point to a NAL start, if necessary
  7450. for (; syncPoint < len - 3; syncPoint++) {
  7451. if (buffer[syncPoint + 2] === 1) {
  7452. // the sync point is properly aligned
  7453. i = syncPoint + 5;
  7454. break;
  7455. }
  7456. }
  7457. while (i < len) {
  7458. // look at the current byte to determine if we've hit the end of
  7459. // a NAL unit boundary
  7460. switch (buffer[i]) {
  7461. case 0:
  7462. // skip past non-sync sequences
  7463. if (buffer[i - 1] !== 0) {
  7464. i += 2;
  7465. break;
  7466. } else if (buffer[i - 2] !== 0) {
  7467. i++;
  7468. break;
  7469. } // deliver the NAL unit if it isn't empty
  7470. if (syncPoint + 3 !== i - 2) {
  7471. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7472. } // drop trailing zeroes
  7473. do {
  7474. i++;
  7475. } while (buffer[i] !== 1 && i < len);
  7476. syncPoint = i - 2;
  7477. i += 3;
  7478. break;
  7479. case 1:
  7480. // skip past non-sync sequences
  7481. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  7482. i += 3;
  7483. break;
  7484. } // deliver the NAL unit
  7485. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  7486. syncPoint = i - 2;
  7487. i += 3;
  7488. break;
  7489. default:
  7490. // the current byte isn't a one or zero, so it cannot be part
  7491. // of a sync sequence
  7492. i += 3;
  7493. break;
  7494. }
  7495. } // filter out the NAL units that were delivered
  7496. buffer = buffer.subarray(syncPoint);
  7497. i -= syncPoint;
  7498. syncPoint = 0;
  7499. };
  7500. this.reset = function () {
  7501. buffer = null;
  7502. syncPoint = 0;
  7503. this.trigger('reset');
  7504. };
  7505. this.flush = function () {
  7506. // deliver the last buffered NAL unit
  7507. if (buffer && buffer.byteLength > 3) {
  7508. this.trigger('data', buffer.subarray(syncPoint + 3));
  7509. } // reset the stream state
  7510. buffer = null;
  7511. syncPoint = 0;
  7512. this.trigger('done');
  7513. };
  7514. this.endTimeline = function () {
  7515. this.flush();
  7516. this.trigger('endedtimeline');
  7517. };
  7518. };
  7519. NalByteStream.prototype = new Stream$2(); // values of profile_idc that indicate additional fields are included in the SPS
  7520. // see Recommendation ITU-T H.264 (4/2013),
  7521. // 7.3.2.1.1 Sequence parameter set data syntax
  7522. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  7523. 100: true,
  7524. 110: true,
  7525. 122: true,
  7526. 244: true,
  7527. 44: true,
  7528. 83: true,
  7529. 86: true,
  7530. 118: true,
  7531. 128: true,
  7532. // TODO: the three profiles below don't
  7533. // appear to have sps data in the specificiation anymore?
  7534. 138: true,
  7535. 139: true,
  7536. 134: true
  7537. };
  7538. /**
  7539. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  7540. * events.
  7541. */
  7542. H264Stream$1 = function () {
  7543. var nalByteStream = new NalByteStream(),
  7544. self,
  7545. trackId,
  7546. currentPts,
  7547. currentDts,
  7548. discardEmulationPreventionBytes,
  7549. readSequenceParameterSet,
  7550. skipScalingList;
  7551. H264Stream$1.prototype.init.call(this);
  7552. self = this;
  7553. /*
  7554. * Pushes a packet from a stream onto the NalByteStream
  7555. *
  7556. * @param {Object} packet - A packet received from a stream
  7557. * @param {Uint8Array} packet.data - The raw bytes of the packet
  7558. * @param {Number} packet.dts - Decode timestamp of the packet
  7559. * @param {Number} packet.pts - Presentation timestamp of the packet
  7560. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  7561. * @param {('video'|'audio')} packet.type - The type of packet
  7562. *
  7563. */
  7564. this.push = function (packet) {
  7565. if (packet.type !== 'video') {
  7566. return;
  7567. }
  7568. trackId = packet.trackId;
  7569. currentPts = packet.pts;
  7570. currentDts = packet.dts;
  7571. nalByteStream.push(packet);
  7572. };
  7573. /*
  7574. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  7575. * for the NALUs to the next stream component.
  7576. * Also, preprocess caption and sequence parameter NALUs.
  7577. *
  7578. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  7579. * @see NalByteStream.push
  7580. */
  7581. nalByteStream.on('data', function (data) {
  7582. var event = {
  7583. trackId: trackId,
  7584. pts: currentPts,
  7585. dts: currentDts,
  7586. data: data,
  7587. nalUnitTypeCode: data[0] & 0x1f
  7588. };
  7589. switch (event.nalUnitTypeCode) {
  7590. case 0x05:
  7591. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  7592. break;
  7593. case 0x06:
  7594. event.nalUnitType = 'sei_rbsp';
  7595. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  7596. break;
  7597. case 0x07:
  7598. event.nalUnitType = 'seq_parameter_set_rbsp';
  7599. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  7600. event.config = readSequenceParameterSet(event.escapedRBSP);
  7601. break;
  7602. case 0x08:
  7603. event.nalUnitType = 'pic_parameter_set_rbsp';
  7604. break;
  7605. case 0x09:
  7606. event.nalUnitType = 'access_unit_delimiter_rbsp';
  7607. break;
  7608. } // This triggers data on the H264Stream
  7609. self.trigger('data', event);
  7610. });
  7611. nalByteStream.on('done', function () {
  7612. self.trigger('done');
  7613. });
  7614. nalByteStream.on('partialdone', function () {
  7615. self.trigger('partialdone');
  7616. });
  7617. nalByteStream.on('reset', function () {
  7618. self.trigger('reset');
  7619. });
  7620. nalByteStream.on('endedtimeline', function () {
  7621. self.trigger('endedtimeline');
  7622. });
  7623. this.flush = function () {
  7624. nalByteStream.flush();
  7625. };
  7626. this.partialFlush = function () {
  7627. nalByteStream.partialFlush();
  7628. };
  7629. this.reset = function () {
  7630. nalByteStream.reset();
  7631. };
  7632. this.endTimeline = function () {
  7633. nalByteStream.endTimeline();
  7634. };
  7635. /**
  7636. * Advance the ExpGolomb decoder past a scaling list. The scaling
  7637. * list is optionally transmitted as part of a sequence parameter
  7638. * set and is not relevant to transmuxing.
  7639. * @param count {number} the number of entries in this scaling list
  7640. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  7641. * start of a scaling list
  7642. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  7643. */
  7644. skipScalingList = function (count, expGolombDecoder) {
  7645. var lastScale = 8,
  7646. nextScale = 8,
  7647. j,
  7648. deltaScale;
  7649. for (j = 0; j < count; j++) {
  7650. if (nextScale !== 0) {
  7651. deltaScale = expGolombDecoder.readExpGolomb();
  7652. nextScale = (lastScale + deltaScale + 256) % 256;
  7653. }
  7654. lastScale = nextScale === 0 ? lastScale : nextScale;
  7655. }
  7656. };
  7657. /**
  7658. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  7659. * Sequence Payload"
  7660. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  7661. * unit
  7662. * @return {Uint8Array} the RBSP without any Emulation
  7663. * Prevention Bytes
  7664. */
  7665. discardEmulationPreventionBytes = function (data) {
  7666. var length = data.byteLength,
  7667. emulationPreventionBytesPositions = [],
  7668. i = 1,
  7669. newLength,
  7670. newData; // Find all `Emulation Prevention Bytes`
  7671. while (i < length - 2) {
  7672. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  7673. emulationPreventionBytesPositions.push(i + 2);
  7674. i += 2;
  7675. } else {
  7676. i++;
  7677. }
  7678. } // If no Emulation Prevention Bytes were found just return the original
  7679. // array
  7680. if (emulationPreventionBytesPositions.length === 0) {
  7681. return data;
  7682. } // Create a new array to hold the NAL unit data
  7683. newLength = length - emulationPreventionBytesPositions.length;
  7684. newData = new Uint8Array(newLength);
  7685. var sourceIndex = 0;
  7686. for (i = 0; i < newLength; sourceIndex++, i++) {
  7687. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  7688. // Skip this byte
  7689. sourceIndex++; // Remove this position index
  7690. emulationPreventionBytesPositions.shift();
  7691. }
  7692. newData[i] = data[sourceIndex];
  7693. }
  7694. return newData;
  7695. };
  7696. /**
  7697. * Read a sequence parameter set and return some interesting video
  7698. * properties. A sequence parameter set is the H264 metadata that
  7699. * describes the properties of upcoming video frames.
  7700. * @param data {Uint8Array} the bytes of a sequence parameter set
  7701. * @return {object} an object with configuration parsed from the
  7702. * sequence parameter set, including the dimensions of the
  7703. * associated video frames.
  7704. */
  7705. readSequenceParameterSet = function (data) {
  7706. var frameCropLeftOffset = 0,
  7707. frameCropRightOffset = 0,
  7708. frameCropTopOffset = 0,
  7709. frameCropBottomOffset = 0,
  7710. expGolombDecoder,
  7711. profileIdc,
  7712. levelIdc,
  7713. profileCompatibility,
  7714. chromaFormatIdc,
  7715. picOrderCntType,
  7716. numRefFramesInPicOrderCntCycle,
  7717. picWidthInMbsMinus1,
  7718. picHeightInMapUnitsMinus1,
  7719. frameMbsOnlyFlag,
  7720. scalingListCount,
  7721. sarRatio = [1, 1],
  7722. aspectRatioIdc,
  7723. i;
  7724. expGolombDecoder = new ExpGolomb(data);
  7725. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  7726. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  7727. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  7728. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  7729. // some profiles have more optional data we don't need
  7730. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  7731. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  7732. if (chromaFormatIdc === 3) {
  7733. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  7734. }
  7735. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  7736. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  7737. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  7738. if (expGolombDecoder.readBoolean()) {
  7739. // seq_scaling_matrix_present_flag
  7740. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  7741. for (i = 0; i < scalingListCount; i++) {
  7742. if (expGolombDecoder.readBoolean()) {
  7743. // seq_scaling_list_present_flag[ i ]
  7744. if (i < 6) {
  7745. skipScalingList(16, expGolombDecoder);
  7746. } else {
  7747. skipScalingList(64, expGolombDecoder);
  7748. }
  7749. }
  7750. }
  7751. }
  7752. }
  7753. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  7754. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  7755. if (picOrderCntType === 0) {
  7756. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  7757. } else if (picOrderCntType === 1) {
  7758. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  7759. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  7760. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  7761. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  7762. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  7763. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  7764. }
  7765. }
  7766. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  7767. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  7768. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  7769. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  7770. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  7771. if (frameMbsOnlyFlag === 0) {
  7772. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  7773. }
  7774. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  7775. if (expGolombDecoder.readBoolean()) {
  7776. // frame_cropping_flag
  7777. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  7778. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  7779. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  7780. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  7781. }
  7782. if (expGolombDecoder.readBoolean()) {
  7783. // vui_parameters_present_flag
  7784. if (expGolombDecoder.readBoolean()) {
  7785. // aspect_ratio_info_present_flag
  7786. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  7787. switch (aspectRatioIdc) {
  7788. case 1:
  7789. sarRatio = [1, 1];
  7790. break;
  7791. case 2:
  7792. sarRatio = [12, 11];
  7793. break;
  7794. case 3:
  7795. sarRatio = [10, 11];
  7796. break;
  7797. case 4:
  7798. sarRatio = [16, 11];
  7799. break;
  7800. case 5:
  7801. sarRatio = [40, 33];
  7802. break;
  7803. case 6:
  7804. sarRatio = [24, 11];
  7805. break;
  7806. case 7:
  7807. sarRatio = [20, 11];
  7808. break;
  7809. case 8:
  7810. sarRatio = [32, 11];
  7811. break;
  7812. case 9:
  7813. sarRatio = [80, 33];
  7814. break;
  7815. case 10:
  7816. sarRatio = [18, 11];
  7817. break;
  7818. case 11:
  7819. sarRatio = [15, 11];
  7820. break;
  7821. case 12:
  7822. sarRatio = [64, 33];
  7823. break;
  7824. case 13:
  7825. sarRatio = [160, 99];
  7826. break;
  7827. case 14:
  7828. sarRatio = [4, 3];
  7829. break;
  7830. case 15:
  7831. sarRatio = [3, 2];
  7832. break;
  7833. case 16:
  7834. sarRatio = [2, 1];
  7835. break;
  7836. case 255:
  7837. {
  7838. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  7839. break;
  7840. }
  7841. }
  7842. if (sarRatio) {
  7843. sarRatio[0] / sarRatio[1];
  7844. }
  7845. }
  7846. }
  7847. return {
  7848. profileIdc: profileIdc,
  7849. levelIdc: levelIdc,
  7850. profileCompatibility: profileCompatibility,
  7851. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  7852. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  7853. // sar is sample aspect ratio
  7854. sarRatio: sarRatio
  7855. };
  7856. };
  7857. };
  7858. H264Stream$1.prototype = new Stream$2();
  7859. var h264 = {
  7860. H264Stream: H264Stream$1,
  7861. NalByteStream: NalByteStream
  7862. };
  7863. /**
  7864. * mux.js
  7865. *
  7866. * Copyright (c) Brightcove
  7867. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7868. *
  7869. * Utilities to detect basic properties and metadata about Aac data.
  7870. */
  7871. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  7872. var parseId3TagSize = function (header, byteIndex) {
  7873. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  7874. flags = header[byteIndex + 5],
  7875. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  7876. returnSize = returnSize >= 0 ? returnSize : 0;
  7877. if (footerPresent) {
  7878. return returnSize + 20;
  7879. }
  7880. return returnSize + 10;
  7881. };
  7882. var getId3Offset = function (data, offset) {
  7883. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  7884. return offset;
  7885. }
  7886. offset += parseId3TagSize(data, offset);
  7887. return getId3Offset(data, offset);
  7888. }; // TODO: use vhs-utils
  7889. var isLikelyAacData$1 = function (data) {
  7890. var offset = getId3Offset(data, 0);
  7891. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  7892. // is not mp3 data but aac data.
  7893. (data[offset + 1] & 0x16) === 0x10;
  7894. };
  7895. var parseSyncSafeInteger = function (data) {
  7896. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  7897. }; // return a percent-encoded representation of the specified byte range
  7898. // @see http://en.wikipedia.org/wiki/Percent-encoding
  7899. var percentEncode = function (bytes, start, end) {
  7900. var i,
  7901. result = '';
  7902. for (i = start; i < end; i++) {
  7903. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  7904. }
  7905. return result;
  7906. }; // return the string representation of the specified byte range,
  7907. // interpreted as ISO-8859-1.
  7908. var parseIso88591 = function (bytes, start, end) {
  7909. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  7910. };
  7911. var parseAdtsSize = function (header, byteIndex) {
  7912. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  7913. middle = header[byteIndex + 4] << 3,
  7914. highTwo = header[byteIndex + 3] & 0x3 << 11;
  7915. return highTwo | middle | lowThree;
  7916. };
  7917. var parseType$4 = function (header, byteIndex) {
  7918. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  7919. return 'timed-metadata';
  7920. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  7921. return 'audio';
  7922. }
  7923. return null;
  7924. };
  7925. var parseSampleRate = function (packet) {
  7926. var i = 0;
  7927. while (i + 5 < packet.length) {
  7928. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  7929. // If a valid header was not found, jump one forward and attempt to
  7930. // find a valid ADTS header starting at the next byte
  7931. i++;
  7932. continue;
  7933. }
  7934. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  7935. }
  7936. return null;
  7937. };
  7938. var parseAacTimestamp = function (packet) {
  7939. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  7940. frameStart = 10;
  7941. if (packet[5] & 0x40) {
  7942. // advance the frame start past the extended header
  7943. frameStart += 4; // header size field
  7944. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  7945. } // parse one or more ID3 frames
  7946. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  7947. do {
  7948. // determine the number of bytes in this frame
  7949. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  7950. if (frameSize < 1) {
  7951. return null;
  7952. }
  7953. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  7954. if (frameHeader === 'PRIV') {
  7955. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  7956. for (var i = 0; i < frame.byteLength; i++) {
  7957. if (frame[i] === 0) {
  7958. var owner = parseIso88591(frame, 0, i);
  7959. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  7960. var d = frame.subarray(i + 1);
  7961. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  7962. size *= 4;
  7963. size += d[7] & 0x03;
  7964. return size;
  7965. }
  7966. break;
  7967. }
  7968. }
  7969. }
  7970. frameStart += 10; // advance past the frame header
  7971. frameStart += frameSize; // advance past the frame body
  7972. } while (frameStart < packet.byteLength);
  7973. return null;
  7974. };
  7975. var utils = {
  7976. isLikelyAacData: isLikelyAacData$1,
  7977. parseId3TagSize: parseId3TagSize,
  7978. parseAdtsSize: parseAdtsSize,
  7979. parseType: parseType$4,
  7980. parseSampleRate: parseSampleRate,
  7981. parseAacTimestamp: parseAacTimestamp
  7982. };
  7983. /**
  7984. * mux.js
  7985. *
  7986. * Copyright (c) Brightcove
  7987. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7988. *
  7989. * A stream-based aac to mp4 converter. This utility can be used to
  7990. * deliver mp4s to a SourceBuffer on platforms that support native
  7991. * Media Source Extensions.
  7992. */
  7993. var Stream$1 = stream;
  7994. var aacUtils = utils; // Constants
  7995. var AacStream$1;
  7996. /**
  7997. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  7998. */
  7999. AacStream$1 = function () {
  8000. var everything = new Uint8Array(),
  8001. timeStamp = 0;
  8002. AacStream$1.prototype.init.call(this);
  8003. this.setTimestamp = function (timestamp) {
  8004. timeStamp = timestamp;
  8005. };
  8006. this.push = function (bytes) {
  8007. var frameSize = 0,
  8008. byteIndex = 0,
  8009. bytesLeft,
  8010. chunk,
  8011. packet,
  8012. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  8013. // bytes that were pushed in
  8014. if (everything.length) {
  8015. tempLength = everything.length;
  8016. everything = new Uint8Array(bytes.byteLength + tempLength);
  8017. everything.set(everything.subarray(0, tempLength));
  8018. everything.set(bytes, tempLength);
  8019. } else {
  8020. everything = bytes;
  8021. }
  8022. while (everything.length - byteIndex >= 3) {
  8023. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  8024. // Exit early because we don't have enough to parse
  8025. // the ID3 tag header
  8026. if (everything.length - byteIndex < 10) {
  8027. break;
  8028. } // check framesize
  8029. frameSize = aacUtils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8030. // to emit a full packet
  8031. // Add to byteIndex to support multiple ID3 tags in sequence
  8032. if (byteIndex + frameSize > everything.length) {
  8033. break;
  8034. }
  8035. chunk = {
  8036. type: 'timed-metadata',
  8037. data: everything.subarray(byteIndex, byteIndex + frameSize)
  8038. };
  8039. this.trigger('data', chunk);
  8040. byteIndex += frameSize;
  8041. continue;
  8042. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  8043. // Exit early because we don't have enough to parse
  8044. // the ADTS frame header
  8045. if (everything.length - byteIndex < 7) {
  8046. break;
  8047. }
  8048. frameSize = aacUtils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  8049. // to emit a full packet
  8050. if (byteIndex + frameSize > everything.length) {
  8051. break;
  8052. }
  8053. packet = {
  8054. type: 'audio',
  8055. data: everything.subarray(byteIndex, byteIndex + frameSize),
  8056. pts: timeStamp,
  8057. dts: timeStamp
  8058. };
  8059. this.trigger('data', packet);
  8060. byteIndex += frameSize;
  8061. continue;
  8062. }
  8063. byteIndex++;
  8064. }
  8065. bytesLeft = everything.length - byteIndex;
  8066. if (bytesLeft > 0) {
  8067. everything = everything.subarray(byteIndex);
  8068. } else {
  8069. everything = new Uint8Array();
  8070. }
  8071. };
  8072. this.reset = function () {
  8073. everything = new Uint8Array();
  8074. this.trigger('reset');
  8075. };
  8076. this.endTimeline = function () {
  8077. everything = new Uint8Array();
  8078. this.trigger('endedtimeline');
  8079. };
  8080. };
  8081. AacStream$1.prototype = new Stream$1();
  8082. var aac = AacStream$1;
  8083. var AUDIO_PROPERTIES$1 = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  8084. var audioProperties = AUDIO_PROPERTIES$1;
  8085. var VIDEO_PROPERTIES$1 = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  8086. var videoProperties = VIDEO_PROPERTIES$1;
  8087. /**
  8088. * mux.js
  8089. *
  8090. * Copyright (c) Brightcove
  8091. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8092. *
  8093. * A stream-based mp2t to mp4 converter. This utility can be used to
  8094. * deliver mp4s to a SourceBuffer on platforms that support native
  8095. * Media Source Extensions.
  8096. */
  8097. var Stream = stream;
  8098. var mp4 = mp4Generator;
  8099. var frameUtils = frameUtils$1;
  8100. var audioFrameUtils = audioFrameUtils$1;
  8101. var trackDecodeInfo = trackDecodeInfo$1;
  8102. var m2ts = m2ts_1;
  8103. var clock = clock$2;
  8104. var AdtsStream = adts;
  8105. var H264Stream = h264.H264Stream;
  8106. var AacStream = aac;
  8107. var isLikelyAacData = utils.isLikelyAacData;
  8108. var ONE_SECOND_IN_TS$1 = clock$2.ONE_SECOND_IN_TS;
  8109. var AUDIO_PROPERTIES = audioProperties;
  8110. var VIDEO_PROPERTIES = videoProperties; // object types
  8111. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  8112. var retriggerForStream = function (key, event) {
  8113. event.stream = key;
  8114. this.trigger('log', event);
  8115. };
  8116. var addPipelineLogRetriggers = function (transmuxer, pipeline) {
  8117. var keys = Object.keys(pipeline);
  8118. for (var i = 0; i < keys.length; i++) {
  8119. var key = keys[i]; // skip non-stream keys and headOfPipeline
  8120. // which is just a duplicate
  8121. if (key === 'headOfPipeline' || !pipeline[key].on) {
  8122. continue;
  8123. }
  8124. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  8125. }
  8126. };
  8127. /**
  8128. * Compare two arrays (even typed) for same-ness
  8129. */
  8130. var arrayEquals = function (a, b) {
  8131. var i;
  8132. if (a.length !== b.length) {
  8133. return false;
  8134. } // compare the value of each element in the array
  8135. for (i = 0; i < a.length; i++) {
  8136. if (a[i] !== b[i]) {
  8137. return false;
  8138. }
  8139. }
  8140. return true;
  8141. };
  8142. var generateSegmentTimingInfo = function (baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  8143. var ptsOffsetFromDts = startPts - startDts,
  8144. decodeDuration = endDts - startDts,
  8145. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  8146. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  8147. // In order to provide relevant values for the player times, base timing info on the
  8148. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  8149. return {
  8150. start: {
  8151. dts: baseMediaDecodeTime,
  8152. pts: baseMediaDecodeTime + ptsOffsetFromDts
  8153. },
  8154. end: {
  8155. dts: baseMediaDecodeTime + decodeDuration,
  8156. pts: baseMediaDecodeTime + presentationDuration
  8157. },
  8158. prependedContentDuration: prependedContentDuration,
  8159. baseMediaDecodeTime: baseMediaDecodeTime
  8160. };
  8161. };
  8162. /**
  8163. * Constructs a single-track, ISO BMFF media segment from AAC data
  8164. * events. The output of this stream can be fed to a SourceBuffer
  8165. * configured with a suitable initialization segment.
  8166. * @param track {object} track metadata configuration
  8167. * @param options {object} transmuxer options object
  8168. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8169. * in the source; false to adjust the first segment to start at 0.
  8170. */
  8171. AudioSegmentStream = function (track, options) {
  8172. var adtsFrames = [],
  8173. sequenceNumber,
  8174. earliestAllowedDts = 0,
  8175. audioAppendStartTs = 0,
  8176. videoBaseMediaDecodeTime = Infinity;
  8177. options = options || {};
  8178. sequenceNumber = options.firstSequenceNumber || 0;
  8179. AudioSegmentStream.prototype.init.call(this);
  8180. this.push = function (data) {
  8181. trackDecodeInfo.collectDtsInfo(track, data);
  8182. if (track) {
  8183. AUDIO_PROPERTIES.forEach(function (prop) {
  8184. track[prop] = data[prop];
  8185. });
  8186. } // buffer audio data until end() is called
  8187. adtsFrames.push(data);
  8188. };
  8189. this.setEarliestDts = function (earliestDts) {
  8190. earliestAllowedDts = earliestDts;
  8191. };
  8192. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  8193. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  8194. };
  8195. this.setAudioAppendStart = function (timestamp) {
  8196. audioAppendStartTs = timestamp;
  8197. };
  8198. this.flush = function () {
  8199. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  8200. if (adtsFrames.length === 0) {
  8201. this.trigger('done', 'AudioSegmentStream');
  8202. return;
  8203. }
  8204. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  8205. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  8206. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  8207. // samples (that is, adts frames) in the audio data
  8208. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  8209. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  8210. adtsFrames = [];
  8211. moof = mp4.moof(sequenceNumber, [track]);
  8212. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  8213. sequenceNumber++;
  8214. boxes.set(moof);
  8215. boxes.set(mdat, moof.byteLength);
  8216. trackDecodeInfo.clearDtsInfo(track);
  8217. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  8218. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  8219. // valid use-case where an init segment/data should be triggered without associated
  8220. // frames. Leaving for now, but should be looked into.
  8221. if (frames.length) {
  8222. segmentDuration = frames.length * frameDuration;
  8223. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  8224. // frame info is in video clock cycles. Convert to match expectation of
  8225. // listeners (that all timestamps will be based on video clock cycles).
  8226. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  8227. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  8228. this.trigger('timingInfo', {
  8229. start: frames[0].pts,
  8230. end: frames[0].pts + segmentDuration
  8231. });
  8232. }
  8233. this.trigger('data', {
  8234. track: track,
  8235. boxes: boxes
  8236. });
  8237. this.trigger('done', 'AudioSegmentStream');
  8238. };
  8239. this.reset = function () {
  8240. trackDecodeInfo.clearDtsInfo(track);
  8241. adtsFrames = [];
  8242. this.trigger('reset');
  8243. };
  8244. };
  8245. AudioSegmentStream.prototype = new Stream();
  8246. /**
  8247. * Constructs a single-track, ISO BMFF media segment from H264 data
  8248. * events. The output of this stream can be fed to a SourceBuffer
  8249. * configured with a suitable initialization segment.
  8250. * @param track {object} track metadata configuration
  8251. * @param options {object} transmuxer options object
  8252. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  8253. * gopsToAlignWith list when attempting to align gop pts
  8254. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8255. * in the source; false to adjust the first segment to start at 0.
  8256. */
  8257. VideoSegmentStream = function (track, options) {
  8258. var sequenceNumber,
  8259. nalUnits = [],
  8260. gopsToAlignWith = [],
  8261. config,
  8262. pps;
  8263. options = options || {};
  8264. sequenceNumber = options.firstSequenceNumber || 0;
  8265. VideoSegmentStream.prototype.init.call(this);
  8266. delete track.minPTS;
  8267. this.gopCache_ = [];
  8268. /**
  8269. * Constructs a ISO BMFF segment given H264 nalUnits
  8270. * @param {Object} nalUnit A data event representing a nalUnit
  8271. * @param {String} nalUnit.nalUnitType
  8272. * @param {Object} nalUnit.config Properties for a mp4 track
  8273. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  8274. * @see lib/codecs/h264.js
  8275. **/
  8276. this.push = function (nalUnit) {
  8277. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  8278. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  8279. config = nalUnit.config;
  8280. track.sps = [nalUnit.data];
  8281. VIDEO_PROPERTIES.forEach(function (prop) {
  8282. track[prop] = config[prop];
  8283. }, this);
  8284. }
  8285. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  8286. pps = nalUnit.data;
  8287. track.pps = [nalUnit.data];
  8288. } // buffer video until flush() is called
  8289. nalUnits.push(nalUnit);
  8290. };
  8291. /**
  8292. * Pass constructed ISO BMFF track and boxes on to the
  8293. * next stream in the pipeline
  8294. **/
  8295. this.flush = function () {
  8296. var frames,
  8297. gopForFusion,
  8298. gops,
  8299. moof,
  8300. mdat,
  8301. boxes,
  8302. prependedContentDuration = 0,
  8303. firstGop,
  8304. lastGop; // Throw away nalUnits at the start of the byte stream until
  8305. // we find the first AUD
  8306. while (nalUnits.length) {
  8307. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  8308. break;
  8309. }
  8310. nalUnits.shift();
  8311. } // Return early if no video data has been observed
  8312. if (nalUnits.length === 0) {
  8313. this.resetStream_();
  8314. this.trigger('done', 'VideoSegmentStream');
  8315. return;
  8316. } // Organize the raw nal-units into arrays that represent
  8317. // higher-level constructs such as frames and gops
  8318. // (group-of-pictures)
  8319. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  8320. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  8321. // a problem since MSE (on Chrome) requires a leading keyframe.
  8322. //
  8323. // We have two approaches to repairing this situation:
  8324. // 1) GOP-FUSION:
  8325. // This is where we keep track of the GOPS (group-of-pictures)
  8326. // from previous fragments and attempt to find one that we can
  8327. // prepend to the current fragment in order to create a valid
  8328. // fragment.
  8329. // 2) KEYFRAME-PULLING:
  8330. // Here we search for the first keyframe in the fragment and
  8331. // throw away all the frames between the start of the fragment
  8332. // and that keyframe. We then extend the duration and pull the
  8333. // PTS of the keyframe forward so that it covers the time range
  8334. // of the frames that were disposed of.
  8335. //
  8336. // #1 is far prefereable over #2 which can cause "stuttering" but
  8337. // requires more things to be just right.
  8338. if (!gops[0][0].keyFrame) {
  8339. // Search for a gop for fusion from our gopCache
  8340. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  8341. if (gopForFusion) {
  8342. // in order to provide more accurate timing information about the segment, save
  8343. // the number of seconds prepended to the original segment due to GOP fusion
  8344. prependedContentDuration = gopForFusion.duration;
  8345. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  8346. // new gop at the beginning
  8347. gops.byteLength += gopForFusion.byteLength;
  8348. gops.nalCount += gopForFusion.nalCount;
  8349. gops.pts = gopForFusion.pts;
  8350. gops.dts = gopForFusion.dts;
  8351. gops.duration += gopForFusion.duration;
  8352. } else {
  8353. // If we didn't find a candidate gop fall back to keyframe-pulling
  8354. gops = frameUtils.extendFirstKeyFrame(gops);
  8355. }
  8356. } // Trim gops to align with gopsToAlignWith
  8357. if (gopsToAlignWith.length) {
  8358. var alignedGops;
  8359. if (options.alignGopsAtEnd) {
  8360. alignedGops = this.alignGopsAtEnd_(gops);
  8361. } else {
  8362. alignedGops = this.alignGopsAtStart_(gops);
  8363. }
  8364. if (!alignedGops) {
  8365. // save all the nals in the last GOP into the gop cache
  8366. this.gopCache_.unshift({
  8367. gop: gops.pop(),
  8368. pps: track.pps,
  8369. sps: track.sps
  8370. }); // Keep a maximum of 6 GOPs in the cache
  8371. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8372. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  8373. this.resetStream_();
  8374. this.trigger('done', 'VideoSegmentStream');
  8375. return;
  8376. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  8377. // when recalculated before sending off to CoalesceStream
  8378. trackDecodeInfo.clearDtsInfo(track);
  8379. gops = alignedGops;
  8380. }
  8381. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  8382. // samples (that is, frames) in the video data
  8383. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  8384. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  8385. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  8386. this.trigger('processedGopsInfo', gops.map(function (gop) {
  8387. return {
  8388. pts: gop.pts,
  8389. dts: gop.dts,
  8390. byteLength: gop.byteLength
  8391. };
  8392. }));
  8393. firstGop = gops[0];
  8394. lastGop = gops[gops.length - 1];
  8395. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  8396. this.trigger('timingInfo', {
  8397. start: gops[0].pts,
  8398. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  8399. }); // save all the nals in the last GOP into the gop cache
  8400. this.gopCache_.unshift({
  8401. gop: gops.pop(),
  8402. pps: track.pps,
  8403. sps: track.sps
  8404. }); // Keep a maximum of 6 GOPs in the cache
  8405. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  8406. nalUnits = [];
  8407. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  8408. this.trigger('timelineStartInfo', track.timelineStartInfo);
  8409. moof = mp4.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  8410. // throwing away hundreds of media segment fragments
  8411. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  8412. sequenceNumber++;
  8413. boxes.set(moof);
  8414. boxes.set(mdat, moof.byteLength);
  8415. this.trigger('data', {
  8416. track: track,
  8417. boxes: boxes
  8418. });
  8419. this.resetStream_(); // Continue with the flush process now
  8420. this.trigger('done', 'VideoSegmentStream');
  8421. };
  8422. this.reset = function () {
  8423. this.resetStream_();
  8424. nalUnits = [];
  8425. this.gopCache_.length = 0;
  8426. gopsToAlignWith.length = 0;
  8427. this.trigger('reset');
  8428. };
  8429. this.resetStream_ = function () {
  8430. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  8431. // for instance, when we are rendition switching
  8432. config = undefined;
  8433. pps = undefined;
  8434. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  8435. // return it or return null if no good candidate was found
  8436. this.getGopForFusion_ = function (nalUnit) {
  8437. var halfSecond = 45000,
  8438. // Half-a-second in a 90khz clock
  8439. allowableOverlap = 10000,
  8440. // About 3 frames @ 30fps
  8441. nearestDistance = Infinity,
  8442. dtsDistance,
  8443. nearestGopObj,
  8444. currentGop,
  8445. currentGopObj,
  8446. i; // Search for the GOP nearest to the beginning of this nal unit
  8447. for (i = 0; i < this.gopCache_.length; i++) {
  8448. currentGopObj = this.gopCache_[i];
  8449. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  8450. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  8451. continue;
  8452. } // Reject Gops that would require a negative baseMediaDecodeTime
  8453. if (currentGop.dts < track.timelineStartInfo.dts) {
  8454. continue;
  8455. } // The distance between the end of the gop and the start of the nalUnit
  8456. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  8457. // a half-second of the nal unit
  8458. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  8459. // Always use the closest GOP we found if there is more than
  8460. // one candidate
  8461. if (!nearestGopObj || nearestDistance > dtsDistance) {
  8462. nearestGopObj = currentGopObj;
  8463. nearestDistance = dtsDistance;
  8464. }
  8465. }
  8466. }
  8467. if (nearestGopObj) {
  8468. return nearestGopObj.gop;
  8469. }
  8470. return null;
  8471. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  8472. // of gopsToAlignWith starting from the START of the list
  8473. this.alignGopsAtStart_ = function (gops) {
  8474. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  8475. byteLength = gops.byteLength;
  8476. nalCount = gops.nalCount;
  8477. duration = gops.duration;
  8478. alignIndex = gopIndex = 0;
  8479. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  8480. align = gopsToAlignWith[alignIndex];
  8481. gop = gops[gopIndex];
  8482. if (align.pts === gop.pts) {
  8483. break;
  8484. }
  8485. if (gop.pts > align.pts) {
  8486. // this current gop starts after the current gop we want to align on, so increment
  8487. // align index
  8488. alignIndex++;
  8489. continue;
  8490. } // current gop starts before the current gop we want to align on. so increment gop
  8491. // index
  8492. gopIndex++;
  8493. byteLength -= gop.byteLength;
  8494. nalCount -= gop.nalCount;
  8495. duration -= gop.duration;
  8496. }
  8497. if (gopIndex === 0) {
  8498. // no gops to trim
  8499. return gops;
  8500. }
  8501. if (gopIndex === gops.length) {
  8502. // all gops trimmed, skip appending all gops
  8503. return null;
  8504. }
  8505. alignedGops = gops.slice(gopIndex);
  8506. alignedGops.byteLength = byteLength;
  8507. alignedGops.duration = duration;
  8508. alignedGops.nalCount = nalCount;
  8509. alignedGops.pts = alignedGops[0].pts;
  8510. alignedGops.dts = alignedGops[0].dts;
  8511. return alignedGops;
  8512. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  8513. // of gopsToAlignWith starting from the END of the list
  8514. this.alignGopsAtEnd_ = function (gops) {
  8515. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  8516. alignIndex = gopsToAlignWith.length - 1;
  8517. gopIndex = gops.length - 1;
  8518. alignEndIndex = null;
  8519. matchFound = false;
  8520. while (alignIndex >= 0 && gopIndex >= 0) {
  8521. align = gopsToAlignWith[alignIndex];
  8522. gop = gops[gopIndex];
  8523. if (align.pts === gop.pts) {
  8524. matchFound = true;
  8525. break;
  8526. }
  8527. if (align.pts > gop.pts) {
  8528. alignIndex--;
  8529. continue;
  8530. }
  8531. if (alignIndex === gopsToAlignWith.length - 1) {
  8532. // gop.pts is greater than the last alignment candidate. If no match is found
  8533. // by the end of this loop, we still want to append gops that come after this
  8534. // point
  8535. alignEndIndex = gopIndex;
  8536. }
  8537. gopIndex--;
  8538. }
  8539. if (!matchFound && alignEndIndex === null) {
  8540. return null;
  8541. }
  8542. var trimIndex;
  8543. if (matchFound) {
  8544. trimIndex = gopIndex;
  8545. } else {
  8546. trimIndex = alignEndIndex;
  8547. }
  8548. if (trimIndex === 0) {
  8549. return gops;
  8550. }
  8551. var alignedGops = gops.slice(trimIndex);
  8552. var metadata = alignedGops.reduce(function (total, gop) {
  8553. total.byteLength += gop.byteLength;
  8554. total.duration += gop.duration;
  8555. total.nalCount += gop.nalCount;
  8556. return total;
  8557. }, {
  8558. byteLength: 0,
  8559. duration: 0,
  8560. nalCount: 0
  8561. });
  8562. alignedGops.byteLength = metadata.byteLength;
  8563. alignedGops.duration = metadata.duration;
  8564. alignedGops.nalCount = metadata.nalCount;
  8565. alignedGops.pts = alignedGops[0].pts;
  8566. alignedGops.dts = alignedGops[0].dts;
  8567. return alignedGops;
  8568. };
  8569. this.alignGopsWith = function (newGopsToAlignWith) {
  8570. gopsToAlignWith = newGopsToAlignWith;
  8571. };
  8572. };
  8573. VideoSegmentStream.prototype = new Stream();
  8574. /**
  8575. * A Stream that can combine multiple streams (ie. audio & video)
  8576. * into a single output segment for MSE. Also supports audio-only
  8577. * and video-only streams.
  8578. * @param options {object} transmuxer options object
  8579. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  8580. * in the source; false to adjust the first segment to start at media timeline start.
  8581. */
  8582. CoalesceStream = function (options, metadataStream) {
  8583. // Number of Tracks per output segment
  8584. // If greater than 1, we combine multiple
  8585. // tracks into a single segment
  8586. this.numberOfTracks = 0;
  8587. this.metadataStream = metadataStream;
  8588. options = options || {};
  8589. if (typeof options.remux !== 'undefined') {
  8590. this.remuxTracks = !!options.remux;
  8591. } else {
  8592. this.remuxTracks = true;
  8593. }
  8594. if (typeof options.keepOriginalTimestamps === 'boolean') {
  8595. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  8596. } else {
  8597. this.keepOriginalTimestamps = false;
  8598. }
  8599. this.pendingTracks = [];
  8600. this.videoTrack = null;
  8601. this.pendingBoxes = [];
  8602. this.pendingCaptions = [];
  8603. this.pendingMetadata = [];
  8604. this.pendingBytes = 0;
  8605. this.emittedTracks = 0;
  8606. CoalesceStream.prototype.init.call(this); // Take output from multiple
  8607. this.push = function (output) {
  8608. // buffer incoming captions until the associated video segment
  8609. // finishes
  8610. if (output.text) {
  8611. return this.pendingCaptions.push(output);
  8612. } // buffer incoming id3 tags until the final flush
  8613. if (output.frames) {
  8614. return this.pendingMetadata.push(output);
  8615. } // Add this track to the list of pending tracks and store
  8616. // important information required for the construction of
  8617. // the final segment
  8618. this.pendingTracks.push(output.track);
  8619. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  8620. // We unshift audio and push video because
  8621. // as of Chrome 75 when switching from
  8622. // one init segment to another if the video
  8623. // mdat does not appear after the audio mdat
  8624. // only audio will play for the duration of our transmux.
  8625. if (output.track.type === 'video') {
  8626. this.videoTrack = output.track;
  8627. this.pendingBoxes.push(output.boxes);
  8628. }
  8629. if (output.track.type === 'audio') {
  8630. this.audioTrack = output.track;
  8631. this.pendingBoxes.unshift(output.boxes);
  8632. }
  8633. };
  8634. };
  8635. CoalesceStream.prototype = new Stream();
  8636. CoalesceStream.prototype.flush = function (flushSource) {
  8637. var offset = 0,
  8638. event = {
  8639. captions: [],
  8640. captionStreams: {},
  8641. metadata: [],
  8642. info: {}
  8643. },
  8644. caption,
  8645. id3,
  8646. initSegment,
  8647. timelineStartPts = 0,
  8648. i;
  8649. if (this.pendingTracks.length < this.numberOfTracks) {
  8650. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  8651. // Return because we haven't received a flush from a data-generating
  8652. // portion of the segment (meaning that we have only recieved meta-data
  8653. // or captions.)
  8654. return;
  8655. } else if (this.remuxTracks) {
  8656. // Return until we have enough tracks from the pipeline to remux (if we
  8657. // are remuxing audio and video into a single MP4)
  8658. return;
  8659. } else if (this.pendingTracks.length === 0) {
  8660. // In the case where we receive a flush without any data having been
  8661. // received we consider it an emitted track for the purposes of coalescing
  8662. // `done` events.
  8663. // We do this for the case where there is an audio and video track in the
  8664. // segment but no audio data. (seen in several playlists with alternate
  8665. // audio tracks and no audio present in the main TS segments.)
  8666. this.emittedTracks++;
  8667. if (this.emittedTracks >= this.numberOfTracks) {
  8668. this.trigger('done');
  8669. this.emittedTracks = 0;
  8670. }
  8671. return;
  8672. }
  8673. }
  8674. if (this.videoTrack) {
  8675. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  8676. VIDEO_PROPERTIES.forEach(function (prop) {
  8677. event.info[prop] = this.videoTrack[prop];
  8678. }, this);
  8679. } else if (this.audioTrack) {
  8680. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  8681. AUDIO_PROPERTIES.forEach(function (prop) {
  8682. event.info[prop] = this.audioTrack[prop];
  8683. }, this);
  8684. }
  8685. if (this.videoTrack || this.audioTrack) {
  8686. if (this.pendingTracks.length === 1) {
  8687. event.type = this.pendingTracks[0].type;
  8688. } else {
  8689. event.type = 'combined';
  8690. }
  8691. this.emittedTracks += this.pendingTracks.length;
  8692. initSegment = mp4.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  8693. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  8694. // and track definitions
  8695. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  8696. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  8697. for (i = 0; i < this.pendingBoxes.length; i++) {
  8698. event.data.set(this.pendingBoxes[i], offset);
  8699. offset += this.pendingBoxes[i].byteLength;
  8700. } // Translate caption PTS times into second offsets to match the
  8701. // video timeline for the segment, and add track info
  8702. for (i = 0; i < this.pendingCaptions.length; i++) {
  8703. caption = this.pendingCaptions[i];
  8704. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  8705. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  8706. event.captionStreams[caption.stream] = true;
  8707. event.captions.push(caption);
  8708. } // Translate ID3 frame PTS times into second offsets to match the
  8709. // video timeline for the segment
  8710. for (i = 0; i < this.pendingMetadata.length; i++) {
  8711. id3 = this.pendingMetadata[i];
  8712. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  8713. event.metadata.push(id3);
  8714. } // We add this to every single emitted segment even though we only need
  8715. // it for the first
  8716. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  8717. this.pendingTracks.length = 0;
  8718. this.videoTrack = null;
  8719. this.pendingBoxes.length = 0;
  8720. this.pendingCaptions.length = 0;
  8721. this.pendingBytes = 0;
  8722. this.pendingMetadata.length = 0; // Emit the built segment
  8723. // We include captions and ID3 tags for backwards compatibility,
  8724. // ideally we should send only video and audio in the data event
  8725. this.trigger('data', event); // Emit each caption to the outside world
  8726. // Ideally, this would happen immediately on parsing captions,
  8727. // but we need to ensure that video data is sent back first
  8728. // so that caption timing can be adjusted to match video timing
  8729. for (i = 0; i < event.captions.length; i++) {
  8730. caption = event.captions[i];
  8731. this.trigger('caption', caption);
  8732. } // Emit each id3 tag to the outside world
  8733. // Ideally, this would happen immediately on parsing the tag,
  8734. // but we need to ensure that video data is sent back first
  8735. // so that ID3 frame timing can be adjusted to match video timing
  8736. for (i = 0; i < event.metadata.length; i++) {
  8737. id3 = event.metadata[i];
  8738. this.trigger('id3Frame', id3);
  8739. }
  8740. } // Only emit `done` if all tracks have been flushed and emitted
  8741. if (this.emittedTracks >= this.numberOfTracks) {
  8742. this.trigger('done');
  8743. this.emittedTracks = 0;
  8744. }
  8745. };
  8746. CoalesceStream.prototype.setRemux = function (val) {
  8747. this.remuxTracks = val;
  8748. };
  8749. /**
  8750. * A Stream that expects MP2T binary data as input and produces
  8751. * corresponding media segments, suitable for use with Media Source
  8752. * Extension (MSE) implementations that support the ISO BMFF byte
  8753. * stream format, like Chrome.
  8754. */
  8755. Transmuxer = function (options) {
  8756. var self = this,
  8757. hasFlushed = true,
  8758. videoTrack,
  8759. audioTrack;
  8760. Transmuxer.prototype.init.call(this);
  8761. options = options || {};
  8762. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  8763. this.transmuxPipeline_ = {};
  8764. this.setupAacPipeline = function () {
  8765. var pipeline = {};
  8766. this.transmuxPipeline_ = pipeline;
  8767. pipeline.type = 'aac';
  8768. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  8769. pipeline.aacStream = new AacStream();
  8770. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  8771. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  8772. pipeline.adtsStream = new AdtsStream();
  8773. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  8774. pipeline.headOfPipeline = pipeline.aacStream;
  8775. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  8776. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  8777. pipeline.metadataStream.on('timestamp', function (frame) {
  8778. pipeline.aacStream.setTimestamp(frame.timeStamp);
  8779. });
  8780. pipeline.aacStream.on('data', function (data) {
  8781. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  8782. return;
  8783. }
  8784. audioTrack = audioTrack || {
  8785. timelineStartInfo: {
  8786. baseMediaDecodeTime: self.baseMediaDecodeTime
  8787. },
  8788. codec: 'adts',
  8789. type: 'audio'
  8790. }; // hook up the audio segment stream to the first track with aac data
  8791. pipeline.coalesceStream.numberOfTracks++;
  8792. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  8793. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  8794. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  8795. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  8796. self.trigger('trackinfo', {
  8797. hasAudio: !!audioTrack,
  8798. hasVideo: !!videoTrack
  8799. });
  8800. }); // Re-emit any data coming from the coalesce stream to the outside world
  8801. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  8802. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  8803. addPipelineLogRetriggers(this, pipeline);
  8804. };
  8805. this.setupTsPipeline = function () {
  8806. var pipeline = {};
  8807. this.transmuxPipeline_ = pipeline;
  8808. pipeline.type = 'ts';
  8809. pipeline.metadataStream = new m2ts.MetadataStream(); // set up the parsing pipeline
  8810. pipeline.packetStream = new m2ts.TransportPacketStream();
  8811. pipeline.parseStream = new m2ts.TransportParseStream();
  8812. pipeline.elementaryStream = new m2ts.ElementaryStream();
  8813. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  8814. pipeline.adtsStream = new AdtsStream();
  8815. pipeline.h264Stream = new H264Stream();
  8816. pipeline.captionStream = new m2ts.CaptionStream(options);
  8817. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  8818. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  8819. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  8820. // demux the streams
  8821. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  8822. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  8823. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  8824. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  8825. pipeline.elementaryStream.on('data', function (data) {
  8826. var i;
  8827. if (data.type === 'metadata') {
  8828. i = data.tracks.length; // scan the tracks listed in the metadata
  8829. while (i--) {
  8830. if (!videoTrack && data.tracks[i].type === 'video') {
  8831. videoTrack = data.tracks[i];
  8832. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  8833. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  8834. audioTrack = data.tracks[i];
  8835. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  8836. }
  8837. } // hook up the video segment stream to the first track with h264 data
  8838. if (videoTrack && !pipeline.videoSegmentStream) {
  8839. pipeline.coalesceStream.numberOfTracks++;
  8840. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  8841. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  8842. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  8843. // When video emits timelineStartInfo data after a flush, we forward that
  8844. // info to the AudioSegmentStream, if it exists, because video timeline
  8845. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  8846. // because this is a particularly subtle form of timestamp alteration.
  8847. if (audioTrack && !options.keepOriginalTimestamps) {
  8848. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  8849. // very earliest DTS we have seen in video because Chrome will
  8850. // interpret any video track with a baseMediaDecodeTime that is
  8851. // non-zero as a gap.
  8852. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  8853. }
  8854. });
  8855. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  8856. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  8857. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  8858. if (audioTrack) {
  8859. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  8860. }
  8861. });
  8862. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  8863. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  8864. }
  8865. if (audioTrack && !pipeline.audioSegmentStream) {
  8866. // hook up the audio segment stream to the first track with aac data
  8867. pipeline.coalesceStream.numberOfTracks++;
  8868. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  8869. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  8870. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  8871. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  8872. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  8873. } // emit pmt info
  8874. self.trigger('trackinfo', {
  8875. hasAudio: !!audioTrack,
  8876. hasVideo: !!videoTrack
  8877. });
  8878. }
  8879. }); // Re-emit any data coming from the coalesce stream to the outside world
  8880. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  8881. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  8882. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  8883. self.trigger('id3Frame', id3Frame);
  8884. });
  8885. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  8886. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  8887. addPipelineLogRetriggers(this, pipeline);
  8888. }; // hook up the segment streams once track metadata is delivered
  8889. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  8890. var pipeline = this.transmuxPipeline_;
  8891. if (!options.keepOriginalTimestamps) {
  8892. this.baseMediaDecodeTime = baseMediaDecodeTime;
  8893. }
  8894. if (audioTrack) {
  8895. audioTrack.timelineStartInfo.dts = undefined;
  8896. audioTrack.timelineStartInfo.pts = undefined;
  8897. trackDecodeInfo.clearDtsInfo(audioTrack);
  8898. if (pipeline.audioTimestampRolloverStream) {
  8899. pipeline.audioTimestampRolloverStream.discontinuity();
  8900. }
  8901. }
  8902. if (videoTrack) {
  8903. if (pipeline.videoSegmentStream) {
  8904. pipeline.videoSegmentStream.gopCache_ = [];
  8905. }
  8906. videoTrack.timelineStartInfo.dts = undefined;
  8907. videoTrack.timelineStartInfo.pts = undefined;
  8908. trackDecodeInfo.clearDtsInfo(videoTrack);
  8909. pipeline.captionStream.reset();
  8910. }
  8911. if (pipeline.timestampRolloverStream) {
  8912. pipeline.timestampRolloverStream.discontinuity();
  8913. }
  8914. };
  8915. this.setAudioAppendStart = function (timestamp) {
  8916. if (audioTrack) {
  8917. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  8918. }
  8919. };
  8920. this.setRemux = function (val) {
  8921. var pipeline = this.transmuxPipeline_;
  8922. options.remux = val;
  8923. if (pipeline && pipeline.coalesceStream) {
  8924. pipeline.coalesceStream.setRemux(val);
  8925. }
  8926. };
  8927. this.alignGopsWith = function (gopsToAlignWith) {
  8928. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  8929. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  8930. }
  8931. };
  8932. this.getLogTrigger_ = function (key) {
  8933. var self = this;
  8934. return function (event) {
  8935. event.stream = key;
  8936. self.trigger('log', event);
  8937. };
  8938. }; // feed incoming data to the front of the parsing pipeline
  8939. this.push = function (data) {
  8940. if (hasFlushed) {
  8941. var isAac = isLikelyAacData(data);
  8942. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  8943. this.setupAacPipeline();
  8944. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  8945. this.setupTsPipeline();
  8946. }
  8947. hasFlushed = false;
  8948. }
  8949. this.transmuxPipeline_.headOfPipeline.push(data);
  8950. }; // flush any buffered data
  8951. this.flush = function () {
  8952. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  8953. this.transmuxPipeline_.headOfPipeline.flush();
  8954. };
  8955. this.endTimeline = function () {
  8956. this.transmuxPipeline_.headOfPipeline.endTimeline();
  8957. };
  8958. this.reset = function () {
  8959. if (this.transmuxPipeline_.headOfPipeline) {
  8960. this.transmuxPipeline_.headOfPipeline.reset();
  8961. }
  8962. }; // Caption data has to be reset when seeking outside buffered range
  8963. this.resetCaptions = function () {
  8964. if (this.transmuxPipeline_.captionStream) {
  8965. this.transmuxPipeline_.captionStream.reset();
  8966. }
  8967. };
  8968. };
  8969. Transmuxer.prototype = new Stream();
  8970. var transmuxer = {
  8971. Transmuxer: Transmuxer,
  8972. VideoSegmentStream: VideoSegmentStream,
  8973. AudioSegmentStream: AudioSegmentStream,
  8974. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  8975. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  8976. // exported for testing
  8977. generateSegmentTimingInfo: generateSegmentTimingInfo
  8978. };
  8979. /**
  8980. * mux.js
  8981. *
  8982. * Copyright (c) Brightcove
  8983. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8984. */
  8985. var toUnsigned$3 = function (value) {
  8986. return value >>> 0;
  8987. };
  8988. var toHexString$1 = function (value) {
  8989. return ('00' + value.toString(16)).slice(-2);
  8990. };
  8991. var bin = {
  8992. toUnsigned: toUnsigned$3,
  8993. toHexString: toHexString$1
  8994. };
  8995. var parseType$3 = function (buffer) {
  8996. var result = '';
  8997. result += String.fromCharCode(buffer[0]);
  8998. result += String.fromCharCode(buffer[1]);
  8999. result += String.fromCharCode(buffer[2]);
  9000. result += String.fromCharCode(buffer[3]);
  9001. return result;
  9002. };
  9003. var parseType_1 = parseType$3;
  9004. var toUnsigned$2 = bin.toUnsigned;
  9005. var parseType$2 = parseType_1;
  9006. var findBox$2 = function (data, path) {
  9007. var results = [],
  9008. i,
  9009. size,
  9010. type,
  9011. end,
  9012. subresults;
  9013. if (!path.length) {
  9014. // short-circuit the search for empty paths
  9015. return null;
  9016. }
  9017. for (i = 0; i < data.byteLength;) {
  9018. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  9019. type = parseType$2(data.subarray(i + 4, i + 8));
  9020. end = size > 1 ? i + size : data.byteLength;
  9021. if (type === path[0]) {
  9022. if (path.length === 1) {
  9023. // this is the end of the path and we've found the box we were
  9024. // looking for
  9025. results.push(data.subarray(i + 8, end));
  9026. } else {
  9027. // recursively search for the next box along the path
  9028. subresults = findBox$2(data.subarray(i + 8, end), path.slice(1));
  9029. if (subresults.length) {
  9030. results = results.concat(subresults);
  9031. }
  9032. }
  9033. }
  9034. i = end;
  9035. } // we've finished searching all of data
  9036. return results;
  9037. };
  9038. var findBox_1 = findBox$2;
  9039. var toUnsigned$1 = bin.toUnsigned;
  9040. var getUint64$2 = numbers.getUint64;
  9041. var tfdt = function (data) {
  9042. var result = {
  9043. version: data[0],
  9044. flags: new Uint8Array(data.subarray(1, 4))
  9045. };
  9046. if (result.version === 1) {
  9047. result.baseMediaDecodeTime = getUint64$2(data.subarray(4));
  9048. } else {
  9049. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  9050. }
  9051. return result;
  9052. };
  9053. var parseTfdt$2 = tfdt;
  9054. var parseSampleFlags$1 = function (flags) {
  9055. return {
  9056. isLeading: (flags[0] & 0x0c) >>> 2,
  9057. dependsOn: flags[0] & 0x03,
  9058. isDependedOn: (flags[1] & 0xc0) >>> 6,
  9059. hasRedundancy: (flags[1] & 0x30) >>> 4,
  9060. paddingValue: (flags[1] & 0x0e) >>> 1,
  9061. isNonSyncSample: flags[1] & 0x01,
  9062. degradationPriority: flags[2] << 8 | flags[3]
  9063. };
  9064. };
  9065. var parseSampleFlags_1 = parseSampleFlags$1;
  9066. var parseSampleFlags = parseSampleFlags_1;
  9067. var trun = function (data) {
  9068. var result = {
  9069. version: data[0],
  9070. flags: new Uint8Array(data.subarray(1, 4)),
  9071. samples: []
  9072. },
  9073. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9074. // Flag interpretation
  9075. dataOffsetPresent = result.flags[2] & 0x01,
  9076. // compare with 2nd byte of 0x1
  9077. firstSampleFlagsPresent = result.flags[2] & 0x04,
  9078. // compare with 2nd byte of 0x4
  9079. sampleDurationPresent = result.flags[1] & 0x01,
  9080. // compare with 2nd byte of 0x100
  9081. sampleSizePresent = result.flags[1] & 0x02,
  9082. // compare with 2nd byte of 0x200
  9083. sampleFlagsPresent = result.flags[1] & 0x04,
  9084. // compare with 2nd byte of 0x400
  9085. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  9086. // compare with 2nd byte of 0x800
  9087. sampleCount = view.getUint32(4),
  9088. offset = 8,
  9089. sample;
  9090. if (dataOffsetPresent) {
  9091. // 32 bit signed integer
  9092. result.dataOffset = view.getInt32(offset);
  9093. offset += 4;
  9094. } // Overrides the flags for the first sample only. The order of
  9095. // optional values will be: duration, size, compositionTimeOffset
  9096. if (firstSampleFlagsPresent && sampleCount) {
  9097. sample = {
  9098. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  9099. };
  9100. offset += 4;
  9101. if (sampleDurationPresent) {
  9102. sample.duration = view.getUint32(offset);
  9103. offset += 4;
  9104. }
  9105. if (sampleSizePresent) {
  9106. sample.size = view.getUint32(offset);
  9107. offset += 4;
  9108. }
  9109. if (sampleCompositionTimeOffsetPresent) {
  9110. if (result.version === 1) {
  9111. sample.compositionTimeOffset = view.getInt32(offset);
  9112. } else {
  9113. sample.compositionTimeOffset = view.getUint32(offset);
  9114. }
  9115. offset += 4;
  9116. }
  9117. result.samples.push(sample);
  9118. sampleCount--;
  9119. }
  9120. while (sampleCount--) {
  9121. sample = {};
  9122. if (sampleDurationPresent) {
  9123. sample.duration = view.getUint32(offset);
  9124. offset += 4;
  9125. }
  9126. if (sampleSizePresent) {
  9127. sample.size = view.getUint32(offset);
  9128. offset += 4;
  9129. }
  9130. if (sampleFlagsPresent) {
  9131. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  9132. offset += 4;
  9133. }
  9134. if (sampleCompositionTimeOffsetPresent) {
  9135. if (result.version === 1) {
  9136. sample.compositionTimeOffset = view.getInt32(offset);
  9137. } else {
  9138. sample.compositionTimeOffset = view.getUint32(offset);
  9139. }
  9140. offset += 4;
  9141. }
  9142. result.samples.push(sample);
  9143. }
  9144. return result;
  9145. };
  9146. var parseTrun$2 = trun;
  9147. var tfhd = function (data) {
  9148. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9149. result = {
  9150. version: data[0],
  9151. flags: new Uint8Array(data.subarray(1, 4)),
  9152. trackId: view.getUint32(4)
  9153. },
  9154. baseDataOffsetPresent = result.flags[2] & 0x01,
  9155. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  9156. defaultSampleDurationPresent = result.flags[2] & 0x08,
  9157. defaultSampleSizePresent = result.flags[2] & 0x10,
  9158. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  9159. durationIsEmpty = result.flags[0] & 0x010000,
  9160. defaultBaseIsMoof = result.flags[0] & 0x020000,
  9161. i;
  9162. i = 8;
  9163. if (baseDataOffsetPresent) {
  9164. i += 4; // truncate top 4 bytes
  9165. // FIXME: should we read the full 64 bits?
  9166. result.baseDataOffset = view.getUint32(12);
  9167. i += 4;
  9168. }
  9169. if (sampleDescriptionIndexPresent) {
  9170. result.sampleDescriptionIndex = view.getUint32(i);
  9171. i += 4;
  9172. }
  9173. if (defaultSampleDurationPresent) {
  9174. result.defaultSampleDuration = view.getUint32(i);
  9175. i += 4;
  9176. }
  9177. if (defaultSampleSizePresent) {
  9178. result.defaultSampleSize = view.getUint32(i);
  9179. i += 4;
  9180. }
  9181. if (defaultSampleFlagsPresent) {
  9182. result.defaultSampleFlags = view.getUint32(i);
  9183. }
  9184. if (durationIsEmpty) {
  9185. result.durationIsEmpty = true;
  9186. }
  9187. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  9188. result.baseDataOffsetIsMoof = true;
  9189. }
  9190. return result;
  9191. };
  9192. var parseTfhd$2 = tfhd;
  9193. var win;
  9194. if (typeof window !== "undefined") {
  9195. win = window;
  9196. } else if (typeof commonjsGlobal !== "undefined") {
  9197. win = commonjsGlobal;
  9198. } else if (typeof self !== "undefined") {
  9199. win = self;
  9200. } else {
  9201. win = {};
  9202. }
  9203. var window_1 = win;
  9204. /**
  9205. * mux.js
  9206. *
  9207. * Copyright (c) Brightcove
  9208. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9209. *
  9210. * Reads in-band CEA-708 captions out of FMP4 segments.
  9211. * @see https://en.wikipedia.org/wiki/CEA-708
  9212. */
  9213. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  9214. var CaptionStream = captionStream.CaptionStream;
  9215. var findBox$1 = findBox_1;
  9216. var parseTfdt$1 = parseTfdt$2;
  9217. var parseTrun$1 = parseTrun$2;
  9218. var parseTfhd$1 = parseTfhd$2;
  9219. var window$2 = window_1;
  9220. /**
  9221. * Maps an offset in the mdat to a sample based on the the size of the samples.
  9222. * Assumes that `parseSamples` has been called first.
  9223. *
  9224. * @param {Number} offset - The offset into the mdat
  9225. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  9226. * @return {?Object} The matching sample, or null if no match was found.
  9227. *
  9228. * @see ISO-BMFF-12/2015, Section 8.8.8
  9229. **/
  9230. var mapToSample = function (offset, samples) {
  9231. var approximateOffset = offset;
  9232. for (var i = 0; i < samples.length; i++) {
  9233. var sample = samples[i];
  9234. if (approximateOffset < sample.size) {
  9235. return sample;
  9236. }
  9237. approximateOffset -= sample.size;
  9238. }
  9239. return null;
  9240. };
  9241. /**
  9242. * Finds SEI nal units contained in a Media Data Box.
  9243. * Assumes that `parseSamples` has been called first.
  9244. *
  9245. * @param {Uint8Array} avcStream - The bytes of the mdat
  9246. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  9247. * @param {Number} trackId - The trackId of this video track
  9248. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  9249. * The contents of the seiNal should match what is expected by
  9250. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  9251. *
  9252. * @see ISO-BMFF-12/2015, Section 8.1.1
  9253. * @see Rec. ITU-T H.264, 7.3.2.3.1
  9254. **/
  9255. var findSeiNals = function (avcStream, samples, trackId) {
  9256. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  9257. result = {
  9258. logs: [],
  9259. seiNals: []
  9260. },
  9261. seiNal,
  9262. i,
  9263. length,
  9264. lastMatchedSample;
  9265. for (i = 0; i + 4 < avcStream.length; i += length) {
  9266. length = avcView.getUint32(i);
  9267. i += 4; // Bail if this doesn't appear to be an H264 stream
  9268. if (length <= 0) {
  9269. continue;
  9270. }
  9271. switch (avcStream[i] & 0x1F) {
  9272. case 0x06:
  9273. var data = avcStream.subarray(i + 1, i + 1 + length);
  9274. var matchingSample = mapToSample(i, samples);
  9275. seiNal = {
  9276. nalUnitType: 'sei_rbsp',
  9277. size: length,
  9278. data: data,
  9279. escapedRBSP: discardEmulationPreventionBytes(data),
  9280. trackId: trackId
  9281. };
  9282. if (matchingSample) {
  9283. seiNal.pts = matchingSample.pts;
  9284. seiNal.dts = matchingSample.dts;
  9285. lastMatchedSample = matchingSample;
  9286. } else if (lastMatchedSample) {
  9287. // If a matching sample cannot be found, use the last
  9288. // sample's values as they should be as close as possible
  9289. seiNal.pts = lastMatchedSample.pts;
  9290. seiNal.dts = lastMatchedSample.dts;
  9291. } else {
  9292. result.logs.push({
  9293. level: 'warn',
  9294. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  9295. });
  9296. break;
  9297. }
  9298. result.seiNals.push(seiNal);
  9299. break;
  9300. }
  9301. }
  9302. return result;
  9303. };
  9304. /**
  9305. * Parses sample information out of Track Run Boxes and calculates
  9306. * the absolute presentation and decode timestamps of each sample.
  9307. *
  9308. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  9309. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  9310. @see ISO-BMFF-12/2015, Section 8.8.12
  9311. * @param {Object} tfhd - The parsed Track Fragment Header
  9312. * @see inspect.parseTfhd
  9313. * @return {Object[]} the parsed samples
  9314. *
  9315. * @see ISO-BMFF-12/2015, Section 8.8.8
  9316. **/
  9317. var parseSamples = function (truns, baseMediaDecodeTime, tfhd) {
  9318. var currentDts = baseMediaDecodeTime;
  9319. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  9320. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  9321. var trackId = tfhd.trackId;
  9322. var allSamples = [];
  9323. truns.forEach(function (trun) {
  9324. // Note: We currently do not parse the sample table as well
  9325. // as the trun. It's possible some sources will require this.
  9326. // moov > trak > mdia > minf > stbl
  9327. var trackRun = parseTrun$1(trun);
  9328. var samples = trackRun.samples;
  9329. samples.forEach(function (sample) {
  9330. if (sample.duration === undefined) {
  9331. sample.duration = defaultSampleDuration;
  9332. }
  9333. if (sample.size === undefined) {
  9334. sample.size = defaultSampleSize;
  9335. }
  9336. sample.trackId = trackId;
  9337. sample.dts = currentDts;
  9338. if (sample.compositionTimeOffset === undefined) {
  9339. sample.compositionTimeOffset = 0;
  9340. }
  9341. if (typeof currentDts === 'bigint') {
  9342. sample.pts = currentDts + window$2.BigInt(sample.compositionTimeOffset);
  9343. currentDts += window$2.BigInt(sample.duration);
  9344. } else {
  9345. sample.pts = currentDts + sample.compositionTimeOffset;
  9346. currentDts += sample.duration;
  9347. }
  9348. });
  9349. allSamples = allSamples.concat(samples);
  9350. });
  9351. return allSamples;
  9352. };
  9353. /**
  9354. * Parses out caption nals from an FMP4 segment's video tracks.
  9355. *
  9356. * @param {Uint8Array} segment - The bytes of a single segment
  9357. * @param {Number} videoTrackId - The trackId of a video track in the segment
  9358. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  9359. * a list of seiNals found in that track
  9360. **/
  9361. var parseCaptionNals = function (segment, videoTrackId) {
  9362. // To get the samples
  9363. var trafs = findBox$1(segment, ['moof', 'traf']); // To get SEI NAL units
  9364. var mdats = findBox$1(segment, ['mdat']);
  9365. var captionNals = {};
  9366. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  9367. mdats.forEach(function (mdat, index) {
  9368. var matchingTraf = trafs[index];
  9369. mdatTrafPairs.push({
  9370. mdat: mdat,
  9371. traf: matchingTraf
  9372. });
  9373. });
  9374. mdatTrafPairs.forEach(function (pair) {
  9375. var mdat = pair.mdat;
  9376. var traf = pair.traf;
  9377. var tfhd = findBox$1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  9378. var headerInfo = parseTfhd$1(tfhd[0]);
  9379. var trackId = headerInfo.trackId;
  9380. var tfdt = findBox$1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  9381. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt$1(tfdt[0]).baseMediaDecodeTime : 0;
  9382. var truns = findBox$1(traf, ['trun']);
  9383. var samples;
  9384. var result; // Only parse video data for the chosen video track
  9385. if (videoTrackId === trackId && truns.length > 0) {
  9386. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  9387. result = findSeiNals(mdat, samples, trackId);
  9388. if (!captionNals[trackId]) {
  9389. captionNals[trackId] = {
  9390. seiNals: [],
  9391. logs: []
  9392. };
  9393. }
  9394. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  9395. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  9396. }
  9397. });
  9398. return captionNals;
  9399. };
  9400. /**
  9401. * Parses out inband captions from an MP4 container and returns
  9402. * caption objects that can be used by WebVTT and the TextTrack API.
  9403. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  9404. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  9405. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  9406. *
  9407. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9408. * @param {Number} trackId - The id of the video track to parse
  9409. * @param {Number} timescale - The timescale for the video track from the init segment
  9410. *
  9411. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  9412. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  9413. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  9414. * @return {String} parsedCaptions[].text - The visible content of the caption
  9415. **/
  9416. var parseEmbeddedCaptions = function (segment, trackId, timescale) {
  9417. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9418. if (trackId === null) {
  9419. return null;
  9420. }
  9421. captionNals = parseCaptionNals(segment, trackId);
  9422. var trackNals = captionNals[trackId] || {};
  9423. return {
  9424. seiNals: trackNals.seiNals,
  9425. logs: trackNals.logs,
  9426. timescale: timescale
  9427. };
  9428. };
  9429. /**
  9430. * Converts SEI NALUs into captions that can be used by video.js
  9431. **/
  9432. var CaptionParser = function () {
  9433. var isInitialized = false;
  9434. var captionStream; // Stores segments seen before trackId and timescale are set
  9435. var segmentCache; // Stores video track ID of the track being parsed
  9436. var trackId; // Stores the timescale of the track being parsed
  9437. var timescale; // Stores captions parsed so far
  9438. var parsedCaptions; // Stores whether we are receiving partial data or not
  9439. var parsingPartial;
  9440. /**
  9441. * A method to indicate whether a CaptionParser has been initalized
  9442. * @returns {Boolean}
  9443. **/
  9444. this.isInitialized = function () {
  9445. return isInitialized;
  9446. };
  9447. /**
  9448. * Initializes the underlying CaptionStream, SEI NAL parsing
  9449. * and management, and caption collection
  9450. **/
  9451. this.init = function (options) {
  9452. captionStream = new CaptionStream();
  9453. isInitialized = true;
  9454. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  9455. captionStream.on('data', function (event) {
  9456. // Convert to seconds in the source's timescale
  9457. event.startTime = event.startPts / timescale;
  9458. event.endTime = event.endPts / timescale;
  9459. parsedCaptions.captions.push(event);
  9460. parsedCaptions.captionStreams[event.stream] = true;
  9461. });
  9462. captionStream.on('log', function (log) {
  9463. parsedCaptions.logs.push(log);
  9464. });
  9465. };
  9466. /**
  9467. * Determines if a new video track will be selected
  9468. * or if the timescale changed
  9469. * @return {Boolean}
  9470. **/
  9471. this.isNewInit = function (videoTrackIds, timescales) {
  9472. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  9473. return false;
  9474. }
  9475. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  9476. };
  9477. /**
  9478. * Parses out SEI captions and interacts with underlying
  9479. * CaptionStream to return dispatched captions
  9480. *
  9481. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  9482. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  9483. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  9484. * @see parseEmbeddedCaptions
  9485. * @see m2ts/caption-stream.js
  9486. **/
  9487. this.parse = function (segment, videoTrackIds, timescales) {
  9488. var parsedData;
  9489. if (!this.isInitialized()) {
  9490. return null; // This is not likely to be a video segment
  9491. } else if (!videoTrackIds || !timescales) {
  9492. return null;
  9493. } else if (this.isNewInit(videoTrackIds, timescales)) {
  9494. // Use the first video track only as there is no
  9495. // mechanism to switch to other video tracks
  9496. trackId = videoTrackIds[0];
  9497. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  9498. // data until we have one.
  9499. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  9500. } else if (trackId === null || !timescale) {
  9501. segmentCache.push(segment);
  9502. return null;
  9503. } // Now that a timescale and trackId is set, parse cached segments
  9504. while (segmentCache.length > 0) {
  9505. var cachedSegment = segmentCache.shift();
  9506. this.parse(cachedSegment, videoTrackIds, timescales);
  9507. }
  9508. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  9509. if (parsedData && parsedData.logs) {
  9510. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  9511. }
  9512. if (parsedData === null || !parsedData.seiNals) {
  9513. if (parsedCaptions.logs.length) {
  9514. return {
  9515. logs: parsedCaptions.logs,
  9516. captions: [],
  9517. captionStreams: []
  9518. };
  9519. }
  9520. return null;
  9521. }
  9522. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  9523. this.flushStream();
  9524. return parsedCaptions;
  9525. };
  9526. /**
  9527. * Pushes SEI NALUs onto CaptionStream
  9528. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  9529. * Assumes that `parseCaptionNals` has been called first
  9530. * @see m2ts/caption-stream.js
  9531. **/
  9532. this.pushNals = function (nals) {
  9533. if (!this.isInitialized() || !nals || nals.length === 0) {
  9534. return null;
  9535. }
  9536. nals.forEach(function (nal) {
  9537. captionStream.push(nal);
  9538. });
  9539. };
  9540. /**
  9541. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  9542. * @see m2ts/caption-stream.js
  9543. **/
  9544. this.flushStream = function () {
  9545. if (!this.isInitialized()) {
  9546. return null;
  9547. }
  9548. if (!parsingPartial) {
  9549. captionStream.flush();
  9550. } else {
  9551. captionStream.partialFlush();
  9552. }
  9553. };
  9554. /**
  9555. * Reset caption buckets for new data
  9556. **/
  9557. this.clearParsedCaptions = function () {
  9558. parsedCaptions.captions = [];
  9559. parsedCaptions.captionStreams = {};
  9560. parsedCaptions.logs = [];
  9561. };
  9562. /**
  9563. * Resets underlying CaptionStream
  9564. * @see m2ts/caption-stream.js
  9565. **/
  9566. this.resetCaptionStream = function () {
  9567. if (!this.isInitialized()) {
  9568. return null;
  9569. }
  9570. captionStream.reset();
  9571. };
  9572. /**
  9573. * Convenience method to clear all captions flushed from the
  9574. * CaptionStream and still being parsed
  9575. * @see m2ts/caption-stream.js
  9576. **/
  9577. this.clearAllCaptions = function () {
  9578. this.clearParsedCaptions();
  9579. this.resetCaptionStream();
  9580. };
  9581. /**
  9582. * Reset caption parser
  9583. **/
  9584. this.reset = function () {
  9585. segmentCache = [];
  9586. trackId = null;
  9587. timescale = null;
  9588. if (!parsedCaptions) {
  9589. parsedCaptions = {
  9590. captions: [],
  9591. // CC1, CC2, CC3, CC4
  9592. captionStreams: {},
  9593. logs: []
  9594. };
  9595. } else {
  9596. this.clearParsedCaptions();
  9597. }
  9598. this.resetCaptionStream();
  9599. };
  9600. this.reset();
  9601. };
  9602. var captionParser = CaptionParser;
  9603. /**
  9604. * Returns the first string in the data array ending with a null char '\0'
  9605. * @param {UInt8} data
  9606. * @returns the string with the null char
  9607. */
  9608. var uint8ToCString$1 = function (data) {
  9609. var index = 0;
  9610. var curChar = String.fromCharCode(data[index]);
  9611. var retString = '';
  9612. while (curChar !== '\0') {
  9613. retString += curChar;
  9614. index++;
  9615. curChar = String.fromCharCode(data[index]);
  9616. } // Add nullChar
  9617. retString += curChar;
  9618. return retString;
  9619. };
  9620. var string = {
  9621. uint8ToCString: uint8ToCString$1
  9622. };
  9623. var uint8ToCString = string.uint8ToCString;
  9624. var getUint64$1 = numbers.getUint64;
  9625. /**
  9626. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  9627. * References:
  9628. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  9629. * https://aomediacodec.github.io/id3-emsg/
  9630. *
  9631. * Takes emsg box data as a uint8 array and returns a emsg box object
  9632. * @param {UInt8Array} boxData data from emsg box
  9633. * @returns A parsed emsg box object
  9634. */
  9635. var parseEmsgBox = function (boxData) {
  9636. // version + flags
  9637. var offset = 4;
  9638. var version = boxData[0];
  9639. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  9640. if (version === 0) {
  9641. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  9642. offset += scheme_id_uri.length;
  9643. value = uint8ToCString(boxData.subarray(offset));
  9644. offset += value.length;
  9645. var dv = new DataView(boxData.buffer);
  9646. timescale = dv.getUint32(offset);
  9647. offset += 4;
  9648. presentation_time_delta = dv.getUint32(offset);
  9649. offset += 4;
  9650. event_duration = dv.getUint32(offset);
  9651. offset += 4;
  9652. id = dv.getUint32(offset);
  9653. offset += 4;
  9654. } else if (version === 1) {
  9655. var dv = new DataView(boxData.buffer);
  9656. timescale = dv.getUint32(offset);
  9657. offset += 4;
  9658. presentation_time = getUint64$1(boxData.subarray(offset));
  9659. offset += 8;
  9660. event_duration = dv.getUint32(offset);
  9661. offset += 4;
  9662. id = dv.getUint32(offset);
  9663. offset += 4;
  9664. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  9665. offset += scheme_id_uri.length;
  9666. value = uint8ToCString(boxData.subarray(offset));
  9667. offset += value.length;
  9668. }
  9669. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  9670. var emsgBox = {
  9671. scheme_id_uri,
  9672. value,
  9673. // if timescale is undefined or 0 set to 1
  9674. timescale: timescale ? timescale : 1,
  9675. presentation_time,
  9676. presentation_time_delta,
  9677. event_duration,
  9678. id,
  9679. message_data
  9680. };
  9681. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  9682. };
  9683. /**
  9684. * Scales a presentation time or time delta with an offset with a provided timescale
  9685. * @param {number} presentationTime
  9686. * @param {number} timescale
  9687. * @param {number} timeDelta
  9688. * @param {number} offset
  9689. * @returns the scaled time as a number
  9690. */
  9691. var scaleTime = function (presentationTime, timescale, timeDelta, offset) {
  9692. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  9693. };
  9694. /**
  9695. * Checks the emsg box data for validity based on the version
  9696. * @param {number} version of the emsg box to validate
  9697. * @param {Object} emsg the emsg data to validate
  9698. * @returns if the box is valid as a boolean
  9699. */
  9700. var isValidEmsgBox = function (version, emsg) {
  9701. var hasScheme = emsg.scheme_id_uri !== '\0';
  9702. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  9703. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  9704. return !(version > 1) && isValidV0Box || isValidV1Box;
  9705. }; // Utility function to check if an object is defined
  9706. var isDefined = function (data) {
  9707. return data !== undefined || data !== null;
  9708. };
  9709. var emsg$1 = {
  9710. parseEmsgBox: parseEmsgBox,
  9711. scaleTime: scaleTime
  9712. };
  9713. /**
  9714. * mux.js
  9715. *
  9716. * Copyright (c) Brightcove
  9717. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9718. *
  9719. * Utilities to detect basic properties and metadata about MP4s.
  9720. */
  9721. var toUnsigned = bin.toUnsigned;
  9722. var toHexString = bin.toHexString;
  9723. var findBox = findBox_1;
  9724. var parseType$1 = parseType_1;
  9725. var emsg = emsg$1;
  9726. var parseTfhd = parseTfhd$2;
  9727. var parseTrun = parseTrun$2;
  9728. var parseTfdt = parseTfdt$2;
  9729. var getUint64 = numbers.getUint64;
  9730. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  9731. var window$1 = window_1;
  9732. var parseId3Frames = parseId3.parseId3Frames;
  9733. /**
  9734. * Parses an MP4 initialization segment and extracts the timescale
  9735. * values for any declared tracks. Timescale values indicate the
  9736. * number of clock ticks per second to assume for time-based values
  9737. * elsewhere in the MP4.
  9738. *
  9739. * To determine the start time of an MP4, you need two pieces of
  9740. * information: the timescale unit and the earliest base media decode
  9741. * time. Multiple timescales can be specified within an MP4 but the
  9742. * base media decode time is always expressed in the timescale from
  9743. * the media header box for the track:
  9744. * ```
  9745. * moov > trak > mdia > mdhd.timescale
  9746. * ```
  9747. * @param init {Uint8Array} the bytes of the init segment
  9748. * @return {object} a hash of track ids to timescale values or null if
  9749. * the init segment is malformed.
  9750. */
  9751. timescale = function (init) {
  9752. var result = {},
  9753. traks = findBox(init, ['moov', 'trak']); // mdhd timescale
  9754. return traks.reduce(function (result, trak) {
  9755. var tkhd, version, index, id, mdhd;
  9756. tkhd = findBox(trak, ['tkhd'])[0];
  9757. if (!tkhd) {
  9758. return null;
  9759. }
  9760. version = tkhd[0];
  9761. index = version === 0 ? 12 : 20;
  9762. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  9763. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  9764. if (!mdhd) {
  9765. return null;
  9766. }
  9767. version = mdhd[0];
  9768. index = version === 0 ? 12 : 20;
  9769. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  9770. return result;
  9771. }, result);
  9772. };
  9773. /**
  9774. * Determine the base media decode start time, in seconds, for an MP4
  9775. * fragment. If multiple fragments are specified, the earliest time is
  9776. * returned.
  9777. *
  9778. * The base media decode time can be parsed from track fragment
  9779. * metadata:
  9780. * ```
  9781. * moof > traf > tfdt.baseMediaDecodeTime
  9782. * ```
  9783. * It requires the timescale value from the mdhd to interpret.
  9784. *
  9785. * @param timescale {object} a hash of track ids to timescale values.
  9786. * @return {number} the earliest base media decode start time for the
  9787. * fragment, in seconds
  9788. */
  9789. startTime = function (timescale, fragment) {
  9790. var trafs; // we need info from two childrend of each track fragment box
  9791. trafs = findBox(fragment, ['moof', 'traf']); // determine the start times for each track
  9792. var lowestTime = trafs.reduce(function (acc, traf) {
  9793. var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
  9794. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  9795. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  9796. var tfdt = findBox(traf, ['tfdt'])[0];
  9797. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  9798. var baseTime; // version 1 is 64 bit
  9799. if (tfdt[0] === 1) {
  9800. baseTime = getUint64(tfdt.subarray(4, 12));
  9801. } else {
  9802. baseTime = dv.getUint32(4);
  9803. } // convert base time to seconds if it is a valid number.
  9804. let seconds;
  9805. if (typeof baseTime === 'bigint') {
  9806. seconds = baseTime / window$1.BigInt(scale);
  9807. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  9808. seconds = baseTime / scale;
  9809. }
  9810. if (seconds < Number.MAX_SAFE_INTEGER) {
  9811. seconds = Number(seconds);
  9812. }
  9813. if (seconds < acc) {
  9814. acc = seconds;
  9815. }
  9816. return acc;
  9817. }, Infinity);
  9818. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  9819. };
  9820. /**
  9821. * Determine the composition start, in seconds, for an MP4
  9822. * fragment.
  9823. *
  9824. * The composition start time of a fragment can be calculated using the base
  9825. * media decode time, composition time offset, and timescale, as follows:
  9826. *
  9827. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  9828. *
  9829. * All of the aforementioned information is contained within a media fragment's
  9830. * `traf` box, except for timescale info, which comes from the initialization
  9831. * segment, so a track id (also contained within a `traf`) is also necessary to
  9832. * associate it with a timescale
  9833. *
  9834. *
  9835. * @param timescales {object} - a hash of track ids to timescale values.
  9836. * @param fragment {Unit8Array} - the bytes of a media segment
  9837. * @return {number} the composition start time for the fragment, in seconds
  9838. **/
  9839. compositionStartTime = function (timescales, fragment) {
  9840. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  9841. var baseMediaDecodeTime = 0;
  9842. var compositionTimeOffset = 0;
  9843. var trackId;
  9844. if (trafBoxes && trafBoxes.length) {
  9845. // The spec states that track run samples contained within a `traf` box are contiguous, but
  9846. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  9847. // We will assume that they are, so we only need the first to calculate start time.
  9848. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  9849. var trun = findBox(trafBoxes[0], ['trun'])[0];
  9850. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  9851. if (tfhd) {
  9852. var parsedTfhd = parseTfhd(tfhd);
  9853. trackId = parsedTfhd.trackId;
  9854. }
  9855. if (tfdt) {
  9856. var parsedTfdt = parseTfdt(tfdt);
  9857. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  9858. }
  9859. if (trun) {
  9860. var parsedTrun = parseTrun(trun);
  9861. if (parsedTrun.samples && parsedTrun.samples.length) {
  9862. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  9863. }
  9864. }
  9865. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  9866. // specified.
  9867. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  9868. if (typeof baseMediaDecodeTime === 'bigint') {
  9869. compositionTimeOffset = window$1.BigInt(compositionTimeOffset);
  9870. timescale = window$1.BigInt(timescale);
  9871. }
  9872. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  9873. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  9874. result = Number(result);
  9875. }
  9876. return result;
  9877. };
  9878. /**
  9879. * Find the trackIds of the video tracks in this source.
  9880. * Found by parsing the Handler Reference and Track Header Boxes:
  9881. * moov > trak > mdia > hdlr
  9882. * moov > trak > tkhd
  9883. *
  9884. * @param {Uint8Array} init - The bytes of the init segment for this source
  9885. * @return {Number[]} A list of trackIds
  9886. *
  9887. * @see ISO-BMFF-12/2015, Section 8.4.3
  9888. **/
  9889. getVideoTrackIds = function (init) {
  9890. var traks = findBox(init, ['moov', 'trak']);
  9891. var videoTrackIds = [];
  9892. traks.forEach(function (trak) {
  9893. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  9894. var tkhds = findBox(trak, ['tkhd']);
  9895. hdlrs.forEach(function (hdlr, index) {
  9896. var handlerType = parseType$1(hdlr.subarray(8, 12));
  9897. var tkhd = tkhds[index];
  9898. var view;
  9899. var version;
  9900. var trackId;
  9901. if (handlerType === 'vide') {
  9902. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  9903. version = view.getUint8(0);
  9904. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  9905. videoTrackIds.push(trackId);
  9906. }
  9907. });
  9908. });
  9909. return videoTrackIds;
  9910. };
  9911. getTimescaleFromMediaHeader = function (mdhd) {
  9912. // mdhd is a FullBox, meaning it will have its own version as the first byte
  9913. var version = mdhd[0];
  9914. var index = version === 0 ? 12 : 20;
  9915. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  9916. };
  9917. /**
  9918. * Get all the video, audio, and hint tracks from a non fragmented
  9919. * mp4 segment
  9920. */
  9921. getTracks = function (init) {
  9922. var traks = findBox(init, ['moov', 'trak']);
  9923. var tracks = [];
  9924. traks.forEach(function (trak) {
  9925. var track = {};
  9926. var tkhd = findBox(trak, ['tkhd'])[0];
  9927. var view, tkhdVersion; // id
  9928. if (tkhd) {
  9929. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  9930. tkhdVersion = view.getUint8(0);
  9931. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  9932. }
  9933. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0]; // type
  9934. if (hdlr) {
  9935. var type = parseType$1(hdlr.subarray(8, 12));
  9936. if (type === 'vide') {
  9937. track.type = 'video';
  9938. } else if (type === 'soun') {
  9939. track.type = 'audio';
  9940. } else {
  9941. track.type = type;
  9942. }
  9943. } // codec
  9944. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  9945. if (stsd) {
  9946. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  9947. track.codec = parseType$1(sampleDescriptions.subarray(4, 8));
  9948. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  9949. var codecConfig, codecConfigType;
  9950. if (codecBox) {
  9951. // https://tools.ietf.org/html/rfc6381#section-3.3
  9952. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  9953. // we don't need anything but the "config" parameter of the
  9954. // avc1 codecBox
  9955. codecConfig = codecBox.subarray(78);
  9956. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  9957. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  9958. track.codec += '.'; // left padded with zeroes for single digit hex
  9959. // profile idc
  9960. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  9961. track.codec += toHexString(codecConfig[10]); // level idc
  9962. track.codec += toHexString(codecConfig[11]);
  9963. } else {
  9964. // TODO: show a warning that we couldn't parse the codec
  9965. // and are using the default
  9966. track.codec = 'avc1.4d400d';
  9967. }
  9968. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  9969. // we do not need anything but the streamDescriptor of the mp4a codecBox
  9970. codecConfig = codecBox.subarray(28);
  9971. codecConfigType = parseType$1(codecConfig.subarray(4, 8));
  9972. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  9973. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  9974. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  9975. } else {
  9976. // TODO: show a warning that we couldn't parse the codec
  9977. // and are using the default
  9978. track.codec = 'mp4a.40.2';
  9979. }
  9980. } else {
  9981. // flac, opus, etc
  9982. track.codec = track.codec.toLowerCase();
  9983. }
  9984. }
  9985. }
  9986. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  9987. if (mdhd) {
  9988. track.timescale = getTimescaleFromMediaHeader(mdhd);
  9989. }
  9990. tracks.push(track);
  9991. });
  9992. return tracks;
  9993. };
  9994. /**
  9995. * Returns an array of emsg ID3 data from the provided segmentData.
  9996. * An offset can also be provided as the Latest Arrival Time to calculate
  9997. * the Event Start Time of v0 EMSG boxes.
  9998. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  9999. *
  10000. * @param {Uint8Array} segmentData the segment byte array.
  10001. * @param {number} offset the segment start time or Latest Arrival Time,
  10002. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  10003. */
  10004. getEmsgID3 = function (segmentData, offset = 0) {
  10005. var emsgBoxes = findBox(segmentData, ['emsg']);
  10006. return emsgBoxes.map(data => {
  10007. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  10008. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  10009. return {
  10010. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  10011. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  10012. frames: parsedId3Frames
  10013. };
  10014. });
  10015. };
  10016. var probe$2 = {
  10017. // export mp4 inspector's findBox and parseType for backwards compatibility
  10018. findBox: findBox,
  10019. parseType: parseType$1,
  10020. timescale: timescale,
  10021. startTime: startTime,
  10022. compositionStartTime: compositionStartTime,
  10023. videoTrackIds: getVideoTrackIds,
  10024. tracks: getTracks,
  10025. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  10026. getEmsgID3: getEmsgID3
  10027. };
  10028. /**
  10029. * mux.js
  10030. *
  10031. * Copyright (c) Brightcove
  10032. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10033. *
  10034. * Utilities to detect basic properties and metadata about TS Segments.
  10035. */
  10036. var StreamTypes$1 = streamTypes;
  10037. var parsePid = function (packet) {
  10038. var pid = packet[1] & 0x1f;
  10039. pid <<= 8;
  10040. pid |= packet[2];
  10041. return pid;
  10042. };
  10043. var parsePayloadUnitStartIndicator = function (packet) {
  10044. return !!(packet[1] & 0x40);
  10045. };
  10046. var parseAdaptionField = function (packet) {
  10047. var offset = 0; // if an adaption field is present, its length is specified by the
  10048. // fifth byte of the TS packet header. The adaptation field is
  10049. // used to add stuffing to PES packets that don't fill a complete
  10050. // TS packet, and to specify some forms of timing and control data
  10051. // that we do not currently use.
  10052. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  10053. offset += packet[4] + 1;
  10054. }
  10055. return offset;
  10056. };
  10057. var parseType = function (packet, pmtPid) {
  10058. var pid = parsePid(packet);
  10059. if (pid === 0) {
  10060. return 'pat';
  10061. } else if (pid === pmtPid) {
  10062. return 'pmt';
  10063. } else if (pmtPid) {
  10064. return 'pes';
  10065. }
  10066. return null;
  10067. };
  10068. var parsePat = function (packet) {
  10069. var pusi = parsePayloadUnitStartIndicator(packet);
  10070. var offset = 4 + parseAdaptionField(packet);
  10071. if (pusi) {
  10072. offset += packet[offset] + 1;
  10073. }
  10074. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  10075. };
  10076. var parsePmt = function (packet) {
  10077. var programMapTable = {};
  10078. var pusi = parsePayloadUnitStartIndicator(packet);
  10079. var payloadOffset = 4 + parseAdaptionField(packet);
  10080. if (pusi) {
  10081. payloadOffset += packet[payloadOffset] + 1;
  10082. } // PMTs can be sent ahead of the time when they should actually
  10083. // take effect. We don't believe this should ever be the case
  10084. // for HLS but we'll ignore "forward" PMT declarations if we see
  10085. // them. Future PMT declarations have the current_next_indicator
  10086. // set to zero.
  10087. if (!(packet[payloadOffset + 5] & 0x01)) {
  10088. return;
  10089. }
  10090. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  10091. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  10092. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  10093. // long the program info descriptors are
  10094. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  10095. var offset = 12 + programInfoLength;
  10096. while (offset < tableEnd) {
  10097. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  10098. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  10099. // skip past the elementary stream descriptors, if present
  10100. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  10101. }
  10102. return programMapTable;
  10103. };
  10104. var parsePesType = function (packet, programMapTable) {
  10105. var pid = parsePid(packet);
  10106. var type = programMapTable[pid];
  10107. switch (type) {
  10108. case StreamTypes$1.H264_STREAM_TYPE:
  10109. return 'video';
  10110. case StreamTypes$1.ADTS_STREAM_TYPE:
  10111. return 'audio';
  10112. case StreamTypes$1.METADATA_STREAM_TYPE:
  10113. return 'timed-metadata';
  10114. default:
  10115. return null;
  10116. }
  10117. };
  10118. var parsePesTime = function (packet) {
  10119. var pusi = parsePayloadUnitStartIndicator(packet);
  10120. if (!pusi) {
  10121. return null;
  10122. }
  10123. var offset = 4 + parseAdaptionField(packet);
  10124. if (offset >= packet.byteLength) {
  10125. // From the H 222.0 MPEG-TS spec
  10126. // "For transport stream packets carrying PES packets, stuffing is needed when there
  10127. // is insufficient PES packet data to completely fill the transport stream packet
  10128. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  10129. // the sum of the lengths of the data elements in it, so that the payload bytes
  10130. // remaining after the adaptation field exactly accommodates the available PES packet
  10131. // data."
  10132. //
  10133. // If the offset is >= the length of the packet, then the packet contains no data
  10134. // and instead is just adaption field stuffing bytes
  10135. return null;
  10136. }
  10137. var pes = null;
  10138. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  10139. // and a DTS value. Determine what combination of values is
  10140. // available to work with.
  10141. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  10142. // performs all bitwise operations on 32-bit integers but javascript
  10143. // supports a much greater range (52-bits) of integer using standard
  10144. // mathematical operations.
  10145. // We construct a 31-bit value using bitwise operators over the 31
  10146. // most significant bits and then multiply by 4 (equal to a left-shift
  10147. // of 2) before we add the final 2 least significant bits of the
  10148. // timestamp (equal to an OR.)
  10149. if (ptsDtsFlags & 0xC0) {
  10150. pes = {}; // the PTS and DTS are not written out directly. For information
  10151. // on how they are encoded, see
  10152. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  10153. 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;
  10154. pes.pts *= 4; // Left shift by 2
  10155. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  10156. pes.dts = pes.pts;
  10157. if (ptsDtsFlags & 0x40) {
  10158. 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;
  10159. pes.dts *= 4; // Left shift by 2
  10160. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  10161. }
  10162. }
  10163. return pes;
  10164. };
  10165. var parseNalUnitType = function (type) {
  10166. switch (type) {
  10167. case 0x05:
  10168. return 'slice_layer_without_partitioning_rbsp_idr';
  10169. case 0x06:
  10170. return 'sei_rbsp';
  10171. case 0x07:
  10172. return 'seq_parameter_set_rbsp';
  10173. case 0x08:
  10174. return 'pic_parameter_set_rbsp';
  10175. case 0x09:
  10176. return 'access_unit_delimiter_rbsp';
  10177. default:
  10178. return null;
  10179. }
  10180. };
  10181. var videoPacketContainsKeyFrame = function (packet) {
  10182. var offset = 4 + parseAdaptionField(packet);
  10183. var frameBuffer = packet.subarray(offset);
  10184. var frameI = 0;
  10185. var frameSyncPoint = 0;
  10186. var foundKeyFrame = false;
  10187. var nalType; // advance the sync point to a NAL start, if necessary
  10188. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  10189. if (frameBuffer[frameSyncPoint + 2] === 1) {
  10190. // the sync point is properly aligned
  10191. frameI = frameSyncPoint + 5;
  10192. break;
  10193. }
  10194. }
  10195. while (frameI < frameBuffer.byteLength) {
  10196. // look at the current byte to determine if we've hit the end of
  10197. // a NAL unit boundary
  10198. switch (frameBuffer[frameI]) {
  10199. case 0:
  10200. // skip past non-sync sequences
  10201. if (frameBuffer[frameI - 1] !== 0) {
  10202. frameI += 2;
  10203. break;
  10204. } else if (frameBuffer[frameI - 2] !== 0) {
  10205. frameI++;
  10206. break;
  10207. }
  10208. if (frameSyncPoint + 3 !== frameI - 2) {
  10209. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10210. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10211. foundKeyFrame = true;
  10212. }
  10213. } // drop trailing zeroes
  10214. do {
  10215. frameI++;
  10216. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  10217. frameSyncPoint = frameI - 2;
  10218. frameI += 3;
  10219. break;
  10220. case 1:
  10221. // skip past non-sync sequences
  10222. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  10223. frameI += 3;
  10224. break;
  10225. }
  10226. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10227. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10228. foundKeyFrame = true;
  10229. }
  10230. frameSyncPoint = frameI - 2;
  10231. frameI += 3;
  10232. break;
  10233. default:
  10234. // the current byte isn't a one or zero, so it cannot be part
  10235. // of a sync sequence
  10236. frameI += 3;
  10237. break;
  10238. }
  10239. }
  10240. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  10241. frameI -= frameSyncPoint;
  10242. frameSyncPoint = 0; // parse the final nal
  10243. if (frameBuffer && frameBuffer.byteLength > 3) {
  10244. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  10245. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  10246. foundKeyFrame = true;
  10247. }
  10248. }
  10249. return foundKeyFrame;
  10250. };
  10251. var probe$1 = {
  10252. parseType: parseType,
  10253. parsePat: parsePat,
  10254. parsePmt: parsePmt,
  10255. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  10256. parsePesType: parsePesType,
  10257. parsePesTime: parsePesTime,
  10258. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  10259. };
  10260. /**
  10261. * mux.js
  10262. *
  10263. * Copyright (c) Brightcove
  10264. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10265. *
  10266. * Parse mpeg2 transport stream packets to extract basic timing information
  10267. */
  10268. var StreamTypes = streamTypes;
  10269. var handleRollover = timestampRolloverStream.handleRollover;
  10270. var probe = {};
  10271. probe.ts = probe$1;
  10272. probe.aac = utils;
  10273. var ONE_SECOND_IN_TS = clock$2.ONE_SECOND_IN_TS;
  10274. var MP2T_PACKET_LENGTH = 188,
  10275. // bytes
  10276. SYNC_BYTE = 0x47;
  10277. /**
  10278. * walks through segment data looking for pat and pmt packets to parse out
  10279. * program map table information
  10280. */
  10281. var parsePsi_ = function (bytes, pmt) {
  10282. var startIndex = 0,
  10283. endIndex = MP2T_PACKET_LENGTH,
  10284. packet,
  10285. type;
  10286. while (endIndex < bytes.byteLength) {
  10287. // Look for a pair of start and end sync bytes in the data..
  10288. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10289. // We found a packet
  10290. packet = bytes.subarray(startIndex, endIndex);
  10291. type = probe.ts.parseType(packet, pmt.pid);
  10292. switch (type) {
  10293. case 'pat':
  10294. pmt.pid = probe.ts.parsePat(packet);
  10295. break;
  10296. case 'pmt':
  10297. var table = probe.ts.parsePmt(packet);
  10298. pmt.table = pmt.table || {};
  10299. Object.keys(table).forEach(function (key) {
  10300. pmt.table[key] = table[key];
  10301. });
  10302. break;
  10303. }
  10304. startIndex += MP2T_PACKET_LENGTH;
  10305. endIndex += MP2T_PACKET_LENGTH;
  10306. continue;
  10307. } // If we get here, we have somehow become de-synchronized and we need to step
  10308. // forward one byte at a time until we find a pair of sync bytes that denote
  10309. // a packet
  10310. startIndex++;
  10311. endIndex++;
  10312. }
  10313. };
  10314. /**
  10315. * walks through the segment data from the start and end to get timing information
  10316. * for the first and last audio pes packets
  10317. */
  10318. var parseAudioPes_ = function (bytes, pmt, result) {
  10319. var startIndex = 0,
  10320. endIndex = MP2T_PACKET_LENGTH,
  10321. packet,
  10322. type,
  10323. pesType,
  10324. pusi,
  10325. parsed;
  10326. var endLoop = false; // Start walking from start of segment to get first audio packet
  10327. while (endIndex <= bytes.byteLength) {
  10328. // Look for a pair of start and end sync bytes in the data..
  10329. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10330. // We found a packet
  10331. packet = bytes.subarray(startIndex, endIndex);
  10332. type = probe.ts.parseType(packet, pmt.pid);
  10333. switch (type) {
  10334. case 'pes':
  10335. pesType = probe.ts.parsePesType(packet, pmt.table);
  10336. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10337. if (pesType === 'audio' && pusi) {
  10338. parsed = probe.ts.parsePesTime(packet);
  10339. if (parsed) {
  10340. parsed.type = 'audio';
  10341. result.audio.push(parsed);
  10342. endLoop = true;
  10343. }
  10344. }
  10345. break;
  10346. }
  10347. if (endLoop) {
  10348. break;
  10349. }
  10350. startIndex += MP2T_PACKET_LENGTH;
  10351. endIndex += MP2T_PACKET_LENGTH;
  10352. continue;
  10353. } // If we get here, we have somehow become de-synchronized and we need to step
  10354. // forward one byte at a time until we find a pair of sync bytes that denote
  10355. // a packet
  10356. startIndex++;
  10357. endIndex++;
  10358. } // Start walking from end of segment to get last audio packet
  10359. endIndex = bytes.byteLength;
  10360. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10361. endLoop = false;
  10362. while (startIndex >= 0) {
  10363. // Look for a pair of start and end sync bytes in the data..
  10364. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  10365. // We found a packet
  10366. packet = bytes.subarray(startIndex, endIndex);
  10367. type = probe.ts.parseType(packet, pmt.pid);
  10368. switch (type) {
  10369. case 'pes':
  10370. pesType = probe.ts.parsePesType(packet, pmt.table);
  10371. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10372. if (pesType === 'audio' && pusi) {
  10373. parsed = probe.ts.parsePesTime(packet);
  10374. if (parsed) {
  10375. parsed.type = 'audio';
  10376. result.audio.push(parsed);
  10377. endLoop = true;
  10378. }
  10379. }
  10380. break;
  10381. }
  10382. if (endLoop) {
  10383. break;
  10384. }
  10385. startIndex -= MP2T_PACKET_LENGTH;
  10386. endIndex -= MP2T_PACKET_LENGTH;
  10387. continue;
  10388. } // If we get here, we have somehow become de-synchronized and we need to step
  10389. // forward one byte at a time until we find a pair of sync bytes that denote
  10390. // a packet
  10391. startIndex--;
  10392. endIndex--;
  10393. }
  10394. };
  10395. /**
  10396. * walks through the segment data from the start and end to get timing information
  10397. * for the first and last video pes packets as well as timing information for the first
  10398. * key frame.
  10399. */
  10400. var parseVideoPes_ = function (bytes, pmt, result) {
  10401. var startIndex = 0,
  10402. endIndex = MP2T_PACKET_LENGTH,
  10403. packet,
  10404. type,
  10405. pesType,
  10406. pusi,
  10407. parsed,
  10408. frame,
  10409. i,
  10410. pes;
  10411. var endLoop = false;
  10412. var currentFrame = {
  10413. data: [],
  10414. size: 0
  10415. }; // Start walking from start of segment to get first video packet
  10416. while (endIndex < bytes.byteLength) {
  10417. // Look for a pair of start and end sync bytes in the data..
  10418. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10419. // We found a packet
  10420. packet = bytes.subarray(startIndex, endIndex);
  10421. type = probe.ts.parseType(packet, pmt.pid);
  10422. switch (type) {
  10423. case 'pes':
  10424. pesType = probe.ts.parsePesType(packet, pmt.table);
  10425. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10426. if (pesType === 'video') {
  10427. if (pusi && !endLoop) {
  10428. parsed = probe.ts.parsePesTime(packet);
  10429. if (parsed) {
  10430. parsed.type = 'video';
  10431. result.video.push(parsed);
  10432. endLoop = true;
  10433. }
  10434. }
  10435. if (!result.firstKeyFrame) {
  10436. if (pusi) {
  10437. if (currentFrame.size !== 0) {
  10438. frame = new Uint8Array(currentFrame.size);
  10439. i = 0;
  10440. while (currentFrame.data.length) {
  10441. pes = currentFrame.data.shift();
  10442. frame.set(pes, i);
  10443. i += pes.byteLength;
  10444. }
  10445. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  10446. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  10447. // the keyframe seems to work fine with HLS playback
  10448. // and definitely preferable to a crash with TypeError...
  10449. if (firstKeyFrame) {
  10450. result.firstKeyFrame = firstKeyFrame;
  10451. result.firstKeyFrame.type = 'video';
  10452. } else {
  10453. // eslint-disable-next-line
  10454. 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.');
  10455. }
  10456. }
  10457. currentFrame.size = 0;
  10458. }
  10459. }
  10460. currentFrame.data.push(packet);
  10461. currentFrame.size += packet.byteLength;
  10462. }
  10463. }
  10464. break;
  10465. }
  10466. if (endLoop && result.firstKeyFrame) {
  10467. break;
  10468. }
  10469. startIndex += MP2T_PACKET_LENGTH;
  10470. endIndex += MP2T_PACKET_LENGTH;
  10471. continue;
  10472. } // If we get here, we have somehow become de-synchronized and we need to step
  10473. // forward one byte at a time until we find a pair of sync bytes that denote
  10474. // a packet
  10475. startIndex++;
  10476. endIndex++;
  10477. } // Start walking from end of segment to get last video packet
  10478. endIndex = bytes.byteLength;
  10479. startIndex = endIndex - MP2T_PACKET_LENGTH;
  10480. endLoop = false;
  10481. while (startIndex >= 0) {
  10482. // Look for a pair of start and end sync bytes in the data..
  10483. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  10484. // We found a packet
  10485. packet = bytes.subarray(startIndex, endIndex);
  10486. type = probe.ts.parseType(packet, pmt.pid);
  10487. switch (type) {
  10488. case 'pes':
  10489. pesType = probe.ts.parsePesType(packet, pmt.table);
  10490. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  10491. if (pesType === 'video' && pusi) {
  10492. parsed = probe.ts.parsePesTime(packet);
  10493. if (parsed) {
  10494. parsed.type = 'video';
  10495. result.video.push(parsed);
  10496. endLoop = true;
  10497. }
  10498. }
  10499. break;
  10500. }
  10501. if (endLoop) {
  10502. break;
  10503. }
  10504. startIndex -= MP2T_PACKET_LENGTH;
  10505. endIndex -= MP2T_PACKET_LENGTH;
  10506. continue;
  10507. } // If we get here, we have somehow become de-synchronized and we need to step
  10508. // forward one byte at a time until we find a pair of sync bytes that denote
  10509. // a packet
  10510. startIndex--;
  10511. endIndex--;
  10512. }
  10513. };
  10514. /**
  10515. * Adjusts the timestamp information for the segment to account for
  10516. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  10517. */
  10518. var adjustTimestamp_ = function (segmentInfo, baseTimestamp) {
  10519. if (segmentInfo.audio && segmentInfo.audio.length) {
  10520. var audioBaseTimestamp = baseTimestamp;
  10521. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  10522. audioBaseTimestamp = segmentInfo.audio[0].dts;
  10523. }
  10524. segmentInfo.audio.forEach(function (info) {
  10525. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  10526. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  10527. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  10528. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  10529. });
  10530. }
  10531. if (segmentInfo.video && segmentInfo.video.length) {
  10532. var videoBaseTimestamp = baseTimestamp;
  10533. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  10534. videoBaseTimestamp = segmentInfo.video[0].dts;
  10535. }
  10536. segmentInfo.video.forEach(function (info) {
  10537. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  10538. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  10539. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  10540. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  10541. });
  10542. if (segmentInfo.firstKeyFrame) {
  10543. var frame = segmentInfo.firstKeyFrame;
  10544. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  10545. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  10546. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  10547. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  10548. }
  10549. }
  10550. };
  10551. /**
  10552. * inspects the aac data stream for start and end time information
  10553. */
  10554. var inspectAac_ = function (bytes) {
  10555. var endLoop = false,
  10556. audioCount = 0,
  10557. sampleRate = null,
  10558. timestamp = null,
  10559. frameSize = 0,
  10560. byteIndex = 0,
  10561. packet;
  10562. while (bytes.length - byteIndex >= 3) {
  10563. var type = probe.aac.parseType(bytes, byteIndex);
  10564. switch (type) {
  10565. case 'timed-metadata':
  10566. // Exit early because we don't have enough to parse
  10567. // the ID3 tag header
  10568. if (bytes.length - byteIndex < 10) {
  10569. endLoop = true;
  10570. break;
  10571. }
  10572. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  10573. // to emit a full packet
  10574. if (frameSize > bytes.length) {
  10575. endLoop = true;
  10576. break;
  10577. }
  10578. if (timestamp === null) {
  10579. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  10580. timestamp = probe.aac.parseAacTimestamp(packet);
  10581. }
  10582. byteIndex += frameSize;
  10583. break;
  10584. case 'audio':
  10585. // Exit early because we don't have enough to parse
  10586. // the ADTS frame header
  10587. if (bytes.length - byteIndex < 7) {
  10588. endLoop = true;
  10589. break;
  10590. }
  10591. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  10592. // to emit a full packet
  10593. if (frameSize > bytes.length) {
  10594. endLoop = true;
  10595. break;
  10596. }
  10597. if (sampleRate === null) {
  10598. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  10599. sampleRate = probe.aac.parseSampleRate(packet);
  10600. }
  10601. audioCount++;
  10602. byteIndex += frameSize;
  10603. break;
  10604. default:
  10605. byteIndex++;
  10606. break;
  10607. }
  10608. if (endLoop) {
  10609. return null;
  10610. }
  10611. }
  10612. if (sampleRate === null || timestamp === null) {
  10613. return null;
  10614. }
  10615. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  10616. var result = {
  10617. audio: [{
  10618. type: 'audio',
  10619. dts: timestamp,
  10620. pts: timestamp
  10621. }, {
  10622. type: 'audio',
  10623. dts: timestamp + audioCount * 1024 * audioTimescale,
  10624. pts: timestamp + audioCount * 1024 * audioTimescale
  10625. }]
  10626. };
  10627. return result;
  10628. };
  10629. /**
  10630. * inspects the transport stream segment data for start and end time information
  10631. * of the audio and video tracks (when present) as well as the first key frame's
  10632. * start time.
  10633. */
  10634. var inspectTs_ = function (bytes) {
  10635. var pmt = {
  10636. pid: null,
  10637. table: null
  10638. };
  10639. var result = {};
  10640. parsePsi_(bytes, pmt);
  10641. for (var pid in pmt.table) {
  10642. if (pmt.table.hasOwnProperty(pid)) {
  10643. var type = pmt.table[pid];
  10644. switch (type) {
  10645. case StreamTypes.H264_STREAM_TYPE:
  10646. result.video = [];
  10647. parseVideoPes_(bytes, pmt, result);
  10648. if (result.video.length === 0) {
  10649. delete result.video;
  10650. }
  10651. break;
  10652. case StreamTypes.ADTS_STREAM_TYPE:
  10653. result.audio = [];
  10654. parseAudioPes_(bytes, pmt, result);
  10655. if (result.audio.length === 0) {
  10656. delete result.audio;
  10657. }
  10658. break;
  10659. }
  10660. }
  10661. }
  10662. return result;
  10663. };
  10664. /**
  10665. * Inspects segment byte data and returns an object with start and end timing information
  10666. *
  10667. * @param {Uint8Array} bytes The segment byte data
  10668. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  10669. * timestamps for rollover. This value must be in 90khz clock.
  10670. * @return {Object} Object containing start and end frame timing info of segment.
  10671. */
  10672. var inspect = function (bytes, baseTimestamp) {
  10673. var isAacData = probe.aac.isLikelyAacData(bytes);
  10674. var result;
  10675. if (isAacData) {
  10676. result = inspectAac_(bytes);
  10677. } else {
  10678. result = inspectTs_(bytes);
  10679. }
  10680. if (!result || !result.audio && !result.video) {
  10681. return null;
  10682. }
  10683. adjustTimestamp_(result, baseTimestamp);
  10684. return result;
  10685. };
  10686. var tsInspector = {
  10687. inspect: inspect,
  10688. parseAudioPes_: parseAudioPes_
  10689. };
  10690. /* global self */
  10691. /**
  10692. * Re-emits transmuxer events by converting them into messages to the
  10693. * world outside the worker.
  10694. *
  10695. * @param {Object} transmuxer the transmuxer to wire events on
  10696. * @private
  10697. */
  10698. const wireTransmuxerEvents = function (self, transmuxer) {
  10699. transmuxer.on('data', function (segment) {
  10700. // transfer ownership of the underlying ArrayBuffer
  10701. // instead of doing a copy to save memory
  10702. // ArrayBuffers are transferable but generic TypedArrays are not
  10703. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  10704. const initArray = segment.initSegment;
  10705. segment.initSegment = {
  10706. data: initArray.buffer,
  10707. byteOffset: initArray.byteOffset,
  10708. byteLength: initArray.byteLength
  10709. };
  10710. const typedArray = segment.data;
  10711. segment.data = typedArray.buffer;
  10712. self.postMessage({
  10713. action: 'data',
  10714. segment,
  10715. byteOffset: typedArray.byteOffset,
  10716. byteLength: typedArray.byteLength
  10717. }, [segment.data]);
  10718. });
  10719. transmuxer.on('done', function (data) {
  10720. self.postMessage({
  10721. action: 'done'
  10722. });
  10723. });
  10724. transmuxer.on('gopInfo', function (gopInfo) {
  10725. self.postMessage({
  10726. action: 'gopInfo',
  10727. gopInfo
  10728. });
  10729. });
  10730. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  10731. const videoSegmentTimingInfo = {
  10732. start: {
  10733. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  10734. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  10735. },
  10736. end: {
  10737. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  10738. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  10739. },
  10740. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  10741. };
  10742. if (timingInfo.prependedContentDuration) {
  10743. videoSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  10744. }
  10745. self.postMessage({
  10746. action: 'videoSegmentTimingInfo',
  10747. videoSegmentTimingInfo
  10748. });
  10749. });
  10750. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  10751. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  10752. const audioSegmentTimingInfo = {
  10753. start: {
  10754. decode: clock$2.videoTsToSeconds(timingInfo.start.dts),
  10755. presentation: clock$2.videoTsToSeconds(timingInfo.start.pts)
  10756. },
  10757. end: {
  10758. decode: clock$2.videoTsToSeconds(timingInfo.end.dts),
  10759. presentation: clock$2.videoTsToSeconds(timingInfo.end.pts)
  10760. },
  10761. baseMediaDecodeTime: clock$2.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  10762. };
  10763. if (timingInfo.prependedContentDuration) {
  10764. audioSegmentTimingInfo.prependedContentDuration = clock$2.videoTsToSeconds(timingInfo.prependedContentDuration);
  10765. }
  10766. self.postMessage({
  10767. action: 'audioSegmentTimingInfo',
  10768. audioSegmentTimingInfo
  10769. });
  10770. });
  10771. transmuxer.on('id3Frame', function (id3Frame) {
  10772. self.postMessage({
  10773. action: 'id3Frame',
  10774. id3Frame
  10775. });
  10776. });
  10777. transmuxer.on('caption', function (caption) {
  10778. self.postMessage({
  10779. action: 'caption',
  10780. caption
  10781. });
  10782. });
  10783. transmuxer.on('trackinfo', function (trackInfo) {
  10784. self.postMessage({
  10785. action: 'trackinfo',
  10786. trackInfo
  10787. });
  10788. });
  10789. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  10790. // convert to video TS since we prioritize video time over audio
  10791. self.postMessage({
  10792. action: 'audioTimingInfo',
  10793. audioTimingInfo: {
  10794. start: clock$2.videoTsToSeconds(audioTimingInfo.start),
  10795. end: clock$2.videoTsToSeconds(audioTimingInfo.end)
  10796. }
  10797. });
  10798. });
  10799. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  10800. self.postMessage({
  10801. action: 'videoTimingInfo',
  10802. videoTimingInfo: {
  10803. start: clock$2.videoTsToSeconds(videoTimingInfo.start),
  10804. end: clock$2.videoTsToSeconds(videoTimingInfo.end)
  10805. }
  10806. });
  10807. });
  10808. transmuxer.on('log', function (log) {
  10809. self.postMessage({
  10810. action: 'log',
  10811. log
  10812. });
  10813. });
  10814. };
  10815. /**
  10816. * All incoming messages route through this hash. If no function exists
  10817. * to handle an incoming message, then we ignore the message.
  10818. *
  10819. * @class MessageHandlers
  10820. * @param {Object} options the options to initialize with
  10821. */
  10822. class MessageHandlers {
  10823. constructor(self, options) {
  10824. this.options = options || {};
  10825. this.self = self;
  10826. this.init();
  10827. }
  10828. /**
  10829. * initialize our web worker and wire all the events.
  10830. */
  10831. init() {
  10832. if (this.transmuxer) {
  10833. this.transmuxer.dispose();
  10834. }
  10835. this.transmuxer = new transmuxer.Transmuxer(this.options);
  10836. wireTransmuxerEvents(this.self, this.transmuxer);
  10837. }
  10838. pushMp4Captions(data) {
  10839. if (!this.captionParser) {
  10840. this.captionParser = new captionParser();
  10841. this.captionParser.init();
  10842. }
  10843. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  10844. const parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  10845. this.self.postMessage({
  10846. action: 'mp4Captions',
  10847. captions: parsed && parsed.captions || [],
  10848. logs: parsed && parsed.logs || [],
  10849. data: segment.buffer
  10850. }, [segment.buffer]);
  10851. }
  10852. probeMp4StartTime({
  10853. timescales,
  10854. data
  10855. }) {
  10856. const startTime = probe$2.startTime(timescales, data);
  10857. this.self.postMessage({
  10858. action: 'probeMp4StartTime',
  10859. startTime,
  10860. data
  10861. }, [data.buffer]);
  10862. }
  10863. probeMp4Tracks({
  10864. data
  10865. }) {
  10866. const tracks = probe$2.tracks(data);
  10867. this.self.postMessage({
  10868. action: 'probeMp4Tracks',
  10869. tracks,
  10870. data
  10871. }, [data.buffer]);
  10872. }
  10873. /**
  10874. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  10875. * internal "media time," as well as whether it contains video and/or audio.
  10876. *
  10877. * @private
  10878. * @param {Uint8Array} bytes - segment bytes
  10879. * @param {number} baseStartTime
  10880. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  10881. * This value should be in seconds, as it's converted to a 90khz clock within the
  10882. * function body.
  10883. * @return {Object} The start time of the current segment in "media time" as well as
  10884. * whether it contains video and/or audio
  10885. */
  10886. probeTs({
  10887. data,
  10888. baseStartTime
  10889. }) {
  10890. const tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock$2.ONE_SECOND_IN_TS : void 0;
  10891. const timeInfo = tsInspector.inspect(data, tsStartTime);
  10892. let result = null;
  10893. if (timeInfo) {
  10894. result = {
  10895. // each type's time info comes back as an array of 2 times, start and end
  10896. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  10897. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  10898. };
  10899. if (result.hasVideo) {
  10900. result.videoStart = timeInfo.video[0].ptsTime;
  10901. }
  10902. if (result.hasAudio) {
  10903. result.audioStart = timeInfo.audio[0].ptsTime;
  10904. }
  10905. }
  10906. this.self.postMessage({
  10907. action: 'probeTs',
  10908. result,
  10909. data
  10910. }, [data.buffer]);
  10911. }
  10912. clearAllMp4Captions() {
  10913. if (this.captionParser) {
  10914. this.captionParser.clearAllCaptions();
  10915. }
  10916. }
  10917. clearParsedMp4Captions() {
  10918. if (this.captionParser) {
  10919. this.captionParser.clearParsedCaptions();
  10920. }
  10921. }
  10922. /**
  10923. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  10924. * processing.
  10925. *
  10926. * @param {ArrayBuffer} data data to push into the muxer
  10927. */
  10928. push(data) {
  10929. // Cast array buffer to correct type for transmuxer
  10930. const segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  10931. this.transmuxer.push(segment);
  10932. }
  10933. /**
  10934. * Recreate the transmuxer so that the next segment added via `push`
  10935. * start with a fresh transmuxer.
  10936. */
  10937. reset() {
  10938. this.transmuxer.reset();
  10939. }
  10940. /**
  10941. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  10942. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  10943. * set relative to the first based on the PTS values.
  10944. *
  10945. * @param {Object} data used to set the timestamp offset in the muxer
  10946. */
  10947. setTimestampOffset(data) {
  10948. const timestampOffset = data.timestampOffset || 0;
  10949. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock$2.secondsToVideoTs(timestampOffset)));
  10950. }
  10951. setAudioAppendStart(data) {
  10952. this.transmuxer.setAudioAppendStart(Math.ceil(clock$2.secondsToVideoTs(data.appendStart)));
  10953. }
  10954. setRemux(data) {
  10955. this.transmuxer.setRemux(data.remux);
  10956. }
  10957. /**
  10958. * Forces the pipeline to finish processing the last segment and emit it's
  10959. * results.
  10960. *
  10961. * @param {Object} data event data, not really used
  10962. */
  10963. flush(data) {
  10964. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  10965. self.postMessage({
  10966. action: 'done',
  10967. type: 'transmuxed'
  10968. });
  10969. }
  10970. endTimeline() {
  10971. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  10972. // timelines
  10973. self.postMessage({
  10974. action: 'endedtimeline',
  10975. type: 'transmuxed'
  10976. });
  10977. }
  10978. alignGopsWith(data) {
  10979. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  10980. }
  10981. }
  10982. /**
  10983. * Our web worker interface so that things can talk to mux.js
  10984. * that will be running in a web worker. the scope is passed to this by
  10985. * webworkify.
  10986. *
  10987. * @param {Object} self the scope for the web worker
  10988. */
  10989. self.onmessage = function (event) {
  10990. if (event.data.action === 'init' && event.data.options) {
  10991. this.messageHandlers = new MessageHandlers(self, event.data.options);
  10992. return;
  10993. }
  10994. if (!this.messageHandlers) {
  10995. this.messageHandlers = new MessageHandlers(self);
  10996. }
  10997. if (event.data && event.data.action && event.data.action !== 'init') {
  10998. if (this.messageHandlers[event.data.action]) {
  10999. this.messageHandlers[event.data.action](event.data);
  11000. }
  11001. }
  11002. };
  11003. }));
  11004. var TransmuxWorker = factory(workerCode$1);
  11005. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  11006. const handleData_ = (event, transmuxedData, callback) => {
  11007. const {
  11008. type,
  11009. initSegment,
  11010. captions,
  11011. captionStreams,
  11012. metadata,
  11013. videoFrameDtsTime,
  11014. videoFramePtsTime
  11015. } = event.data.segment;
  11016. transmuxedData.buffer.push({
  11017. captions,
  11018. captionStreams,
  11019. metadata
  11020. });
  11021. const boxes = event.data.segment.boxes || {
  11022. data: event.data.segment.data
  11023. };
  11024. const result = {
  11025. type,
  11026. // cast ArrayBuffer to TypedArray
  11027. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  11028. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  11029. };
  11030. if (typeof videoFrameDtsTime !== 'undefined') {
  11031. result.videoFrameDtsTime = videoFrameDtsTime;
  11032. }
  11033. if (typeof videoFramePtsTime !== 'undefined') {
  11034. result.videoFramePtsTime = videoFramePtsTime;
  11035. }
  11036. callback(result);
  11037. };
  11038. const handleDone_ = ({
  11039. transmuxedData,
  11040. callback
  11041. }) => {
  11042. // Previously we only returned data on data events,
  11043. // not on done events. Clear out the buffer to keep that consistent.
  11044. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  11045. // have received
  11046. callback(transmuxedData);
  11047. };
  11048. const handleGopInfo_ = (event, transmuxedData) => {
  11049. transmuxedData.gopInfo = event.data.gopInfo;
  11050. };
  11051. const processTransmux = options => {
  11052. const {
  11053. transmuxer,
  11054. bytes,
  11055. audioAppendStart,
  11056. gopsToAlignWith,
  11057. remux,
  11058. onData,
  11059. onTrackInfo,
  11060. onAudioTimingInfo,
  11061. onVideoTimingInfo,
  11062. onVideoSegmentTimingInfo,
  11063. onAudioSegmentTimingInfo,
  11064. onId3,
  11065. onCaptions,
  11066. onDone,
  11067. onEndedTimeline,
  11068. onTransmuxerLog,
  11069. isEndOfTimeline
  11070. } = options;
  11071. const transmuxedData = {
  11072. buffer: []
  11073. };
  11074. let waitForEndedTimelineEvent = isEndOfTimeline;
  11075. const handleMessage = event => {
  11076. if (transmuxer.currentTransmux !== options) {
  11077. // disposed
  11078. return;
  11079. }
  11080. if (event.data.action === 'data') {
  11081. handleData_(event, transmuxedData, onData);
  11082. }
  11083. if (event.data.action === 'trackinfo') {
  11084. onTrackInfo(event.data.trackInfo);
  11085. }
  11086. if (event.data.action === 'gopInfo') {
  11087. handleGopInfo_(event, transmuxedData);
  11088. }
  11089. if (event.data.action === 'audioTimingInfo') {
  11090. onAudioTimingInfo(event.data.audioTimingInfo);
  11091. }
  11092. if (event.data.action === 'videoTimingInfo') {
  11093. onVideoTimingInfo(event.data.videoTimingInfo);
  11094. }
  11095. if (event.data.action === 'videoSegmentTimingInfo') {
  11096. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  11097. }
  11098. if (event.data.action === 'audioSegmentTimingInfo') {
  11099. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  11100. }
  11101. if (event.data.action === 'id3Frame') {
  11102. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  11103. }
  11104. if (event.data.action === 'caption') {
  11105. onCaptions(event.data.caption);
  11106. }
  11107. if (event.data.action === 'endedtimeline') {
  11108. waitForEndedTimelineEvent = false;
  11109. onEndedTimeline();
  11110. }
  11111. if (event.data.action === 'log') {
  11112. onTransmuxerLog(event.data.log);
  11113. } // wait for the transmuxed event since we may have audio and video
  11114. if (event.data.type !== 'transmuxed') {
  11115. return;
  11116. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  11117. // of a timeline, that means there may still be data events before the segment
  11118. // processing can be considerred complete. In that case, the final event should be
  11119. // an "endedtimeline" event with the type "transmuxed."
  11120. if (waitForEndedTimelineEvent) {
  11121. return;
  11122. }
  11123. transmuxer.onmessage = null;
  11124. handleDone_({
  11125. transmuxedData,
  11126. callback: onDone
  11127. });
  11128. /* eslint-disable no-use-before-define */
  11129. dequeue(transmuxer);
  11130. /* eslint-enable */
  11131. };
  11132. transmuxer.onmessage = handleMessage;
  11133. if (audioAppendStart) {
  11134. transmuxer.postMessage({
  11135. action: 'setAudioAppendStart',
  11136. appendStart: audioAppendStart
  11137. });
  11138. } // allow empty arrays to be passed to clear out GOPs
  11139. if (Array.isArray(gopsToAlignWith)) {
  11140. transmuxer.postMessage({
  11141. action: 'alignGopsWith',
  11142. gopsToAlignWith
  11143. });
  11144. }
  11145. if (typeof remux !== 'undefined') {
  11146. transmuxer.postMessage({
  11147. action: 'setRemux',
  11148. remux
  11149. });
  11150. }
  11151. if (bytes.byteLength) {
  11152. const buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  11153. const byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  11154. transmuxer.postMessage({
  11155. action: 'push',
  11156. // Send the typed-array of data as an ArrayBuffer so that
  11157. // it can be sent as a "Transferable" and avoid the costly
  11158. // memory copy
  11159. data: buffer,
  11160. // To recreate the original typed-array, we need information
  11161. // about what portion of the ArrayBuffer it was a view into
  11162. byteOffset,
  11163. byteLength: bytes.byteLength
  11164. }, [buffer]);
  11165. }
  11166. if (isEndOfTimeline) {
  11167. transmuxer.postMessage({
  11168. action: 'endTimeline'
  11169. });
  11170. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  11171. // the end of the segment
  11172. transmuxer.postMessage({
  11173. action: 'flush'
  11174. });
  11175. };
  11176. const dequeue = transmuxer => {
  11177. transmuxer.currentTransmux = null;
  11178. if (transmuxer.transmuxQueue.length) {
  11179. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  11180. if (typeof transmuxer.currentTransmux === 'function') {
  11181. transmuxer.currentTransmux();
  11182. } else {
  11183. processTransmux(transmuxer.currentTransmux);
  11184. }
  11185. }
  11186. };
  11187. const processAction = (transmuxer, action) => {
  11188. transmuxer.postMessage({
  11189. action
  11190. });
  11191. dequeue(transmuxer);
  11192. };
  11193. const enqueueAction = (action, transmuxer) => {
  11194. if (!transmuxer.currentTransmux) {
  11195. transmuxer.currentTransmux = action;
  11196. processAction(transmuxer, action);
  11197. return;
  11198. }
  11199. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  11200. };
  11201. const reset = transmuxer => {
  11202. enqueueAction('reset', transmuxer);
  11203. };
  11204. const endTimeline = transmuxer => {
  11205. enqueueAction('endTimeline', transmuxer);
  11206. };
  11207. const transmux = options => {
  11208. if (!options.transmuxer.currentTransmux) {
  11209. options.transmuxer.currentTransmux = options;
  11210. processTransmux(options);
  11211. return;
  11212. }
  11213. options.transmuxer.transmuxQueue.push(options);
  11214. };
  11215. const createTransmuxer = options => {
  11216. const transmuxer = new TransmuxWorker();
  11217. transmuxer.currentTransmux = null;
  11218. transmuxer.transmuxQueue = [];
  11219. const term = transmuxer.terminate;
  11220. transmuxer.terminate = () => {
  11221. transmuxer.currentTransmux = null;
  11222. transmuxer.transmuxQueue.length = 0;
  11223. return term.call(transmuxer);
  11224. };
  11225. transmuxer.postMessage({
  11226. action: 'init',
  11227. options
  11228. });
  11229. return transmuxer;
  11230. };
  11231. var segmentTransmuxer = {
  11232. reset,
  11233. endTimeline,
  11234. transmux,
  11235. createTransmuxer
  11236. };
  11237. const workerCallback = function (options) {
  11238. const transmuxer = options.transmuxer;
  11239. const endAction = options.endAction || options.action;
  11240. const callback = options.callback;
  11241. const message = _extends__default["default"]({}, options, {
  11242. endAction: null,
  11243. transmuxer: null,
  11244. callback: null
  11245. });
  11246. const listenForEndEvent = event => {
  11247. if (event.data.action !== endAction) {
  11248. return;
  11249. }
  11250. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  11251. if (event.data.data) {
  11252. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  11253. if (options.data) {
  11254. options.data = event.data.data;
  11255. }
  11256. }
  11257. callback(event.data);
  11258. };
  11259. transmuxer.addEventListener('message', listenForEndEvent);
  11260. if (options.data) {
  11261. const isArrayBuffer = options.data instanceof ArrayBuffer;
  11262. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  11263. message.byteLength = options.data.byteLength;
  11264. const transfers = [isArrayBuffer ? options.data : options.data.buffer];
  11265. transmuxer.postMessage(message, transfers);
  11266. } else {
  11267. transmuxer.postMessage(message);
  11268. }
  11269. };
  11270. const REQUEST_ERRORS = {
  11271. FAILURE: 2,
  11272. TIMEOUT: -101,
  11273. ABORTED: -102
  11274. };
  11275. /**
  11276. * Abort all requests
  11277. *
  11278. * @param {Object} activeXhrs - an object that tracks all XHR requests
  11279. */
  11280. const abortAll = activeXhrs => {
  11281. activeXhrs.forEach(xhr => {
  11282. xhr.abort();
  11283. });
  11284. };
  11285. /**
  11286. * Gather important bandwidth stats once a request has completed
  11287. *
  11288. * @param {Object} request - the XHR request from which to gather stats
  11289. */
  11290. const getRequestStats = request => {
  11291. return {
  11292. bandwidth: request.bandwidth,
  11293. bytesReceived: request.bytesReceived || 0,
  11294. roundTripTime: request.roundTripTime || 0
  11295. };
  11296. };
  11297. /**
  11298. * If possible gather bandwidth stats as a request is in
  11299. * progress
  11300. *
  11301. * @param {Event} progressEvent - an event object from an XHR's progress event
  11302. */
  11303. const getProgressStats = progressEvent => {
  11304. const request = progressEvent.target;
  11305. const roundTripTime = Date.now() - request.requestTime;
  11306. const stats = {
  11307. bandwidth: Infinity,
  11308. bytesReceived: 0,
  11309. roundTripTime: roundTripTime || 0
  11310. };
  11311. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  11312. // because we should only use bandwidth stats on progress to determine when
  11313. // abort a request early due to insufficient bandwidth
  11314. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  11315. return stats;
  11316. };
  11317. /**
  11318. * Handle all error conditions in one place and return an object
  11319. * with all the information
  11320. *
  11321. * @param {Error|null} error - if non-null signals an error occured with the XHR
  11322. * @param {Object} request - the XHR request that possibly generated the error
  11323. */
  11324. const handleErrors = (error, request) => {
  11325. if (request.timedout) {
  11326. return {
  11327. status: request.status,
  11328. message: 'HLS request timed-out at URL: ' + request.uri,
  11329. code: REQUEST_ERRORS.TIMEOUT,
  11330. xhr: request
  11331. };
  11332. }
  11333. if (request.aborted) {
  11334. return {
  11335. status: request.status,
  11336. message: 'HLS request aborted at URL: ' + request.uri,
  11337. code: REQUEST_ERRORS.ABORTED,
  11338. xhr: request
  11339. };
  11340. }
  11341. if (error) {
  11342. return {
  11343. status: request.status,
  11344. message: 'HLS request errored at URL: ' + request.uri,
  11345. code: REQUEST_ERRORS.FAILURE,
  11346. xhr: request
  11347. };
  11348. }
  11349. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  11350. return {
  11351. status: request.status,
  11352. message: 'Empty HLS response at URL: ' + request.uri,
  11353. code: REQUEST_ERRORS.FAILURE,
  11354. xhr: request
  11355. };
  11356. }
  11357. return null;
  11358. };
  11359. /**
  11360. * Handle responses for key data and convert the key data to the correct format
  11361. * for the decryption step later
  11362. *
  11363. * @param {Object} segment - a simplified copy of the segmentInfo object
  11364. * from SegmentLoader
  11365. * @param {Array} objects - objects to add the key bytes to.
  11366. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11367. * this request
  11368. */
  11369. const handleKeyResponse = (segment, objects, finishProcessingFn) => (error, request) => {
  11370. const response = request.response;
  11371. const errorObj = handleErrors(error, request);
  11372. if (errorObj) {
  11373. return finishProcessingFn(errorObj, segment);
  11374. }
  11375. if (response.byteLength !== 16) {
  11376. return finishProcessingFn({
  11377. status: request.status,
  11378. message: 'Invalid HLS key at URL: ' + request.uri,
  11379. code: REQUEST_ERRORS.FAILURE,
  11380. xhr: request
  11381. }, segment);
  11382. }
  11383. const view = new DataView(response);
  11384. const bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  11385. for (let i = 0; i < objects.length; i++) {
  11386. objects[i].bytes = bytes;
  11387. }
  11388. return finishProcessingFn(null, segment);
  11389. };
  11390. const parseInitSegment = (segment, callback) => {
  11391. const type = containers.detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  11392. // only know how to parse mp4 init segments at the moment
  11393. if (type !== 'mp4') {
  11394. const uri = segment.map.resolvedUri || segment.map.uri;
  11395. return callback({
  11396. internal: true,
  11397. message: `Found unsupported ${type || 'unknown'} container for initialization segment at URL: ${uri}`,
  11398. code: REQUEST_ERRORS.FAILURE
  11399. });
  11400. }
  11401. workerCallback({
  11402. action: 'probeMp4Tracks',
  11403. data: segment.map.bytes,
  11404. transmuxer: segment.transmuxer,
  11405. callback: ({
  11406. tracks,
  11407. data
  11408. }) => {
  11409. // transfer bytes back to us
  11410. segment.map.bytes = data;
  11411. tracks.forEach(function (track) {
  11412. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  11413. if (segment.map.tracks[track.type]) {
  11414. return;
  11415. }
  11416. segment.map.tracks[track.type] = track;
  11417. if (typeof track.id === 'number' && track.timescale) {
  11418. segment.map.timescales = segment.map.timescales || {};
  11419. segment.map.timescales[track.id] = track.timescale;
  11420. }
  11421. });
  11422. return callback(null);
  11423. }
  11424. });
  11425. };
  11426. /**
  11427. * Handle init-segment responses
  11428. *
  11429. * @param {Object} segment - a simplified copy of the segmentInfo object
  11430. * from SegmentLoader
  11431. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11432. * this request
  11433. */
  11434. const handleInitSegmentResponse = ({
  11435. segment,
  11436. finishProcessingFn
  11437. }) => (error, request) => {
  11438. const errorObj = handleErrors(error, request);
  11439. if (errorObj) {
  11440. return finishProcessingFn(errorObj, segment);
  11441. }
  11442. const bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  11443. // until the key request is done to decrypt.
  11444. if (segment.map.key) {
  11445. segment.map.encryptedBytes = bytes;
  11446. return finishProcessingFn(null, segment);
  11447. }
  11448. segment.map.bytes = bytes;
  11449. parseInitSegment(segment, function (parseError) {
  11450. if (parseError) {
  11451. parseError.xhr = request;
  11452. parseError.status = request.status;
  11453. return finishProcessingFn(parseError, segment);
  11454. }
  11455. finishProcessingFn(null, segment);
  11456. });
  11457. };
  11458. /**
  11459. * Response handler for segment-requests being sure to set the correct
  11460. * property depending on whether the segment is encryped or not
  11461. * Also records and keeps track of stats that are used for ABR purposes
  11462. *
  11463. * @param {Object} segment - a simplified copy of the segmentInfo object
  11464. * from SegmentLoader
  11465. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  11466. * this request
  11467. */
  11468. const handleSegmentResponse = ({
  11469. segment,
  11470. finishProcessingFn,
  11471. responseType
  11472. }) => (error, request) => {
  11473. const errorObj = handleErrors(error, request);
  11474. if (errorObj) {
  11475. return finishProcessingFn(errorObj, segment);
  11476. }
  11477. const newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  11478. // thrown for two primary cases:
  11479. // 1. the mime type override stops working, or is not implemented for a specific
  11480. // browser
  11481. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  11482. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  11483. segment.stats = getRequestStats(request);
  11484. if (segment.key) {
  11485. segment.encryptedBytes = new Uint8Array(newBytes);
  11486. } else {
  11487. segment.bytes = new Uint8Array(newBytes);
  11488. }
  11489. return finishProcessingFn(null, segment);
  11490. };
  11491. const transmuxAndNotify = ({
  11492. segment,
  11493. bytes,
  11494. trackInfoFn,
  11495. timingInfoFn,
  11496. videoSegmentTimingInfoFn,
  11497. audioSegmentTimingInfoFn,
  11498. id3Fn,
  11499. captionsFn,
  11500. isEndOfTimeline,
  11501. endedTimelineFn,
  11502. dataFn,
  11503. doneFn,
  11504. onTransmuxerLog
  11505. }) => {
  11506. const fmp4Tracks = segment.map && segment.map.tracks || {};
  11507. const isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  11508. // One reason for this is that in the case of full segments, we want to trust start
  11509. // times from the probe, rather than the transmuxer.
  11510. let audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  11511. const audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  11512. let videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  11513. const videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  11514. const finish = () => transmux({
  11515. bytes,
  11516. transmuxer: segment.transmuxer,
  11517. audioAppendStart: segment.audioAppendStart,
  11518. gopsToAlignWith: segment.gopsToAlignWith,
  11519. remux: isMuxed,
  11520. onData: result => {
  11521. result.type = result.type === 'combined' ? 'video' : result.type;
  11522. dataFn(segment, result);
  11523. },
  11524. onTrackInfo: trackInfo => {
  11525. if (trackInfoFn) {
  11526. if (isMuxed) {
  11527. trackInfo.isMuxed = true;
  11528. }
  11529. trackInfoFn(segment, trackInfo);
  11530. }
  11531. },
  11532. onAudioTimingInfo: audioTimingInfo => {
  11533. // we only want the first start value we encounter
  11534. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  11535. audioStartFn(audioTimingInfo.start);
  11536. audioStartFn = null;
  11537. } // we want to continually update the end time
  11538. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  11539. audioEndFn(audioTimingInfo.end);
  11540. }
  11541. },
  11542. onVideoTimingInfo: videoTimingInfo => {
  11543. // we only want the first start value we encounter
  11544. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  11545. videoStartFn(videoTimingInfo.start);
  11546. videoStartFn = null;
  11547. } // we want to continually update the end time
  11548. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  11549. videoEndFn(videoTimingInfo.end);
  11550. }
  11551. },
  11552. onVideoSegmentTimingInfo: videoSegmentTimingInfo => {
  11553. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  11554. },
  11555. onAudioSegmentTimingInfo: audioSegmentTimingInfo => {
  11556. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  11557. },
  11558. onId3: (id3Frames, dispatchType) => {
  11559. id3Fn(segment, id3Frames, dispatchType);
  11560. },
  11561. onCaptions: captions => {
  11562. captionsFn(segment, [captions]);
  11563. },
  11564. isEndOfTimeline,
  11565. onEndedTimeline: () => {
  11566. endedTimelineFn();
  11567. },
  11568. onTransmuxerLog,
  11569. onDone: result => {
  11570. if (!doneFn) {
  11571. return;
  11572. }
  11573. result.type = result.type === 'combined' ? 'video' : result.type;
  11574. doneFn(null, segment, result);
  11575. }
  11576. }); // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  11577. // Meaning cached frame data may corrupt our notion of where this segment
  11578. // really starts. To get around this, probe for the info needed.
  11579. workerCallback({
  11580. action: 'probeTs',
  11581. transmuxer: segment.transmuxer,
  11582. data: bytes,
  11583. baseStartTime: segment.baseStartTime,
  11584. callback: data => {
  11585. segment.bytes = bytes = data.data;
  11586. const probeResult = data.result;
  11587. if (probeResult) {
  11588. trackInfoFn(segment, {
  11589. hasAudio: probeResult.hasAudio,
  11590. hasVideo: probeResult.hasVideo,
  11591. isMuxed
  11592. });
  11593. trackInfoFn = null;
  11594. if (probeResult.hasAudio && !isMuxed) {
  11595. audioStartFn(probeResult.audioStart);
  11596. }
  11597. if (probeResult.hasVideo) {
  11598. videoStartFn(probeResult.videoStart);
  11599. }
  11600. audioStartFn = null;
  11601. videoStartFn = null;
  11602. }
  11603. finish();
  11604. }
  11605. });
  11606. };
  11607. const handleSegmentBytes = ({
  11608. segment,
  11609. bytes,
  11610. trackInfoFn,
  11611. timingInfoFn,
  11612. videoSegmentTimingInfoFn,
  11613. audioSegmentTimingInfoFn,
  11614. id3Fn,
  11615. captionsFn,
  11616. isEndOfTimeline,
  11617. endedTimelineFn,
  11618. dataFn,
  11619. doneFn,
  11620. onTransmuxerLog
  11621. }) => {
  11622. let bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  11623. // We should have a handler that fetches the number of bytes required
  11624. // to check if something is fmp4. This will allow us to save bandwidth
  11625. // because we can only exclude a playlist and abort requests
  11626. // by codec after trackinfo triggers.
  11627. if (containers.isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  11628. segment.isFmp4 = true;
  11629. const {
  11630. tracks
  11631. } = segment.map;
  11632. const trackInfo = {
  11633. isFmp4: true,
  11634. hasVideo: !!tracks.video,
  11635. hasAudio: !!tracks.audio
  11636. }; // if we have a audio track, with a codec that is not set to
  11637. // encrypted audio
  11638. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  11639. trackInfo.audioCodec = tracks.audio.codec;
  11640. } // if we have a video track, with a codec that is not set to
  11641. // encrypted video
  11642. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  11643. trackInfo.videoCodec = tracks.video.codec;
  11644. }
  11645. if (tracks.video && tracks.audio) {
  11646. trackInfo.isMuxed = true;
  11647. } // since we don't support appending fmp4 data on progress, we know we have the full
  11648. // segment here
  11649. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  11650. // time. The end time can be roughly calculated by the receiver using the duration.
  11651. //
  11652. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  11653. // that is the true start of the segment (where the playback engine should begin
  11654. // decoding).
  11655. const finishLoading = captions => {
  11656. // if the track still has audio at this point it is only possible
  11657. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  11658. // above.
  11659. // we make sure to use segment.bytes here as that
  11660. dataFn(segment, {
  11661. data: bytesAsUint8Array,
  11662. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  11663. });
  11664. if (captions && captions.length) {
  11665. captionsFn(segment, captions);
  11666. }
  11667. doneFn(null, segment, {});
  11668. };
  11669. workerCallback({
  11670. action: 'probeMp4StartTime',
  11671. timescales: segment.map.timescales,
  11672. data: bytesAsUint8Array,
  11673. transmuxer: segment.transmuxer,
  11674. callback: ({
  11675. data,
  11676. startTime
  11677. }) => {
  11678. // transfer bytes back to us
  11679. bytes = data.buffer;
  11680. segment.bytes = bytesAsUint8Array = data;
  11681. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  11682. timingInfoFn(segment, 'audio', 'start', startTime);
  11683. }
  11684. if (trackInfo.hasVideo) {
  11685. timingInfoFn(segment, 'video', 'start', startTime);
  11686. } // Run through the CaptionParser in case there are captions.
  11687. // Initialize CaptionParser if it hasn't been yet
  11688. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  11689. finishLoading();
  11690. return;
  11691. }
  11692. workerCallback({
  11693. action: 'pushMp4Captions',
  11694. endAction: 'mp4Captions',
  11695. transmuxer: segment.transmuxer,
  11696. data: bytesAsUint8Array,
  11697. timescales: segment.map.timescales,
  11698. trackIds: [tracks.video.id],
  11699. callback: message => {
  11700. // transfer bytes back to us
  11701. bytes = message.data.buffer;
  11702. segment.bytes = bytesAsUint8Array = message.data;
  11703. message.logs.forEach(function (log) {
  11704. onTransmuxerLog(merge(log, {
  11705. stream: 'mp4CaptionParser'
  11706. }));
  11707. });
  11708. finishLoading(message.captions);
  11709. }
  11710. });
  11711. }
  11712. });
  11713. return;
  11714. } // VTT or other segments that don't need processing
  11715. if (!segment.transmuxer) {
  11716. doneFn(null, segment, {});
  11717. return;
  11718. }
  11719. if (typeof segment.container === 'undefined') {
  11720. segment.container = containers.detectContainerForBytes(bytesAsUint8Array);
  11721. }
  11722. if (segment.container !== 'ts' && segment.container !== 'aac') {
  11723. trackInfoFn(segment, {
  11724. hasAudio: false,
  11725. hasVideo: false
  11726. });
  11727. doneFn(null, segment, {});
  11728. return;
  11729. } // ts or aac
  11730. transmuxAndNotify({
  11731. segment,
  11732. bytes,
  11733. trackInfoFn,
  11734. timingInfoFn,
  11735. videoSegmentTimingInfoFn,
  11736. audioSegmentTimingInfoFn,
  11737. id3Fn,
  11738. captionsFn,
  11739. isEndOfTimeline,
  11740. endedTimelineFn,
  11741. dataFn,
  11742. doneFn,
  11743. onTransmuxerLog
  11744. });
  11745. };
  11746. const decrypt = function ({
  11747. id,
  11748. key,
  11749. encryptedBytes,
  11750. decryptionWorker
  11751. }, callback) {
  11752. const decryptionHandler = event => {
  11753. if (event.data.source === id) {
  11754. decryptionWorker.removeEventListener('message', decryptionHandler);
  11755. const decrypted = event.data.decrypted;
  11756. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  11757. }
  11758. };
  11759. decryptionWorker.addEventListener('message', decryptionHandler);
  11760. let keyBytes;
  11761. if (key.bytes.slice) {
  11762. keyBytes = key.bytes.slice();
  11763. } else {
  11764. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  11765. } // incrementally decrypt the bytes
  11766. decryptionWorker.postMessage(createTransferableMessage({
  11767. source: id,
  11768. encrypted: encryptedBytes,
  11769. key: keyBytes,
  11770. iv: key.iv
  11771. }), [encryptedBytes.buffer, keyBytes.buffer]);
  11772. };
  11773. /**
  11774. * Decrypt the segment via the decryption web worker
  11775. *
  11776. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  11777. * routines
  11778. * @param {Object} segment - a simplified copy of the segmentInfo object
  11779. * from SegmentLoader
  11780. * @param {Function} trackInfoFn - a callback that receives track info
  11781. * @param {Function} timingInfoFn - a callback that receives timing info
  11782. * @param {Function} videoSegmentTimingInfoFn
  11783. * a callback that receives video timing info based on media times and
  11784. * any adjustments made by the transmuxer
  11785. * @param {Function} audioSegmentTimingInfoFn
  11786. * a callback that receives audio timing info based on media times and
  11787. * any adjustments made by the transmuxer
  11788. * @param {boolean} isEndOfTimeline
  11789. * true if this segment represents the last segment in a timeline
  11790. * @param {Function} endedTimelineFn
  11791. * a callback made when a timeline is ended, will only be called if
  11792. * isEndOfTimeline is true
  11793. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  11794. * and ready to use
  11795. * @param {Function} doneFn - a callback that is executed after decryption has completed
  11796. */
  11797. const decryptSegment = ({
  11798. decryptionWorker,
  11799. segment,
  11800. trackInfoFn,
  11801. timingInfoFn,
  11802. videoSegmentTimingInfoFn,
  11803. audioSegmentTimingInfoFn,
  11804. id3Fn,
  11805. captionsFn,
  11806. isEndOfTimeline,
  11807. endedTimelineFn,
  11808. dataFn,
  11809. doneFn,
  11810. onTransmuxerLog
  11811. }) => {
  11812. decrypt({
  11813. id: segment.requestId,
  11814. key: segment.key,
  11815. encryptedBytes: segment.encryptedBytes,
  11816. decryptionWorker
  11817. }, decryptedBytes => {
  11818. segment.bytes = decryptedBytes;
  11819. handleSegmentBytes({
  11820. segment,
  11821. bytes: segment.bytes,
  11822. trackInfoFn,
  11823. timingInfoFn,
  11824. videoSegmentTimingInfoFn,
  11825. audioSegmentTimingInfoFn,
  11826. id3Fn,
  11827. captionsFn,
  11828. isEndOfTimeline,
  11829. endedTimelineFn,
  11830. dataFn,
  11831. doneFn,
  11832. onTransmuxerLog
  11833. });
  11834. });
  11835. };
  11836. /**
  11837. * This function waits for all XHRs to finish (with either success or failure)
  11838. * before continueing processing via it's callback. The function gathers errors
  11839. * from each request into a single errors array so that the error status for
  11840. * each request can be examined later.
  11841. *
  11842. * @param {Object} activeXhrs - an object that tracks all XHR requests
  11843. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  11844. * routines
  11845. * @param {Function} trackInfoFn - a callback that receives track info
  11846. * @param {Function} timingInfoFn - a callback that receives timing info
  11847. * @param {Function} videoSegmentTimingInfoFn
  11848. * a callback that receives video timing info based on media times and
  11849. * any adjustments made by the transmuxer
  11850. * @param {Function} audioSegmentTimingInfoFn
  11851. * a callback that receives audio timing info based on media times and
  11852. * any adjustments made by the transmuxer
  11853. * @param {Function} id3Fn - a callback that receives ID3 metadata
  11854. * @param {Function} captionsFn - a callback that receives captions
  11855. * @param {boolean} isEndOfTimeline
  11856. * true if this segment represents the last segment in a timeline
  11857. * @param {Function} endedTimelineFn
  11858. * a callback made when a timeline is ended, will only be called if
  11859. * isEndOfTimeline is true
  11860. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  11861. * and ready to use
  11862. * @param {Function} doneFn - a callback that is executed after all resources have been
  11863. * downloaded and any decryption completed
  11864. */
  11865. const waitForCompletion = ({
  11866. activeXhrs,
  11867. decryptionWorker,
  11868. trackInfoFn,
  11869. timingInfoFn,
  11870. videoSegmentTimingInfoFn,
  11871. audioSegmentTimingInfoFn,
  11872. id3Fn,
  11873. captionsFn,
  11874. isEndOfTimeline,
  11875. endedTimelineFn,
  11876. dataFn,
  11877. doneFn,
  11878. onTransmuxerLog
  11879. }) => {
  11880. let count = 0;
  11881. let didError = false;
  11882. return (error, segment) => {
  11883. if (didError) {
  11884. return;
  11885. }
  11886. if (error) {
  11887. didError = true; // If there are errors, we have to abort any outstanding requests
  11888. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  11889. // handle the aborted events from those requests, there are some cases where we may
  11890. // never get an aborted event. For instance, if the network connection is lost and
  11891. // there were two requests, the first may have triggered an error immediately, while
  11892. // the second request remains unsent. In that case, the aborted algorithm will not
  11893. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  11894. //
  11895. // We also can't rely on the ready state of the XHR, since the request that
  11896. // triggered the connection error may also show as a ready state of 0 (unsent).
  11897. // Therefore, we have to finish this group of requests immediately after the first
  11898. // seen error.
  11899. return doneFn(error, segment);
  11900. }
  11901. count += 1;
  11902. if (count === activeXhrs.length) {
  11903. const segmentFinish = function () {
  11904. if (segment.encryptedBytes) {
  11905. return decryptSegment({
  11906. decryptionWorker,
  11907. segment,
  11908. trackInfoFn,
  11909. timingInfoFn,
  11910. videoSegmentTimingInfoFn,
  11911. audioSegmentTimingInfoFn,
  11912. id3Fn,
  11913. captionsFn,
  11914. isEndOfTimeline,
  11915. endedTimelineFn,
  11916. dataFn,
  11917. doneFn,
  11918. onTransmuxerLog
  11919. });
  11920. } // Otherwise, everything is ready just continue
  11921. handleSegmentBytes({
  11922. segment,
  11923. bytes: segment.bytes,
  11924. trackInfoFn,
  11925. timingInfoFn,
  11926. videoSegmentTimingInfoFn,
  11927. audioSegmentTimingInfoFn,
  11928. id3Fn,
  11929. captionsFn,
  11930. isEndOfTimeline,
  11931. endedTimelineFn,
  11932. dataFn,
  11933. doneFn,
  11934. onTransmuxerLog
  11935. });
  11936. }; // Keep track of when *all* of the requests have completed
  11937. segment.endOfAllRequests = Date.now();
  11938. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  11939. return decrypt({
  11940. decryptionWorker,
  11941. // add -init to the "id" to differentiate between segment
  11942. // and init segment decryption, just in case they happen
  11943. // at the same time at some point in the future.
  11944. id: segment.requestId + '-init',
  11945. encryptedBytes: segment.map.encryptedBytes,
  11946. key: segment.map.key
  11947. }, decryptedBytes => {
  11948. segment.map.bytes = decryptedBytes;
  11949. parseInitSegment(segment, parseError => {
  11950. if (parseError) {
  11951. abortAll(activeXhrs);
  11952. return doneFn(parseError, segment);
  11953. }
  11954. segmentFinish();
  11955. });
  11956. });
  11957. }
  11958. segmentFinish();
  11959. }
  11960. };
  11961. };
  11962. /**
  11963. * Calls the abort callback if any request within the batch was aborted. Will only call
  11964. * the callback once per batch of requests, even if multiple were aborted.
  11965. *
  11966. * @param {Object} loadendState - state to check to see if the abort function was called
  11967. * @param {Function} abortFn - callback to call for abort
  11968. */
  11969. const handleLoadEnd = ({
  11970. loadendState,
  11971. abortFn
  11972. }) => event => {
  11973. const request = event.target;
  11974. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  11975. abortFn();
  11976. loadendState.calledAbortFn = true;
  11977. }
  11978. };
  11979. /**
  11980. * Simple progress event callback handler that gathers some stats before
  11981. * executing a provided callback with the `segment` object
  11982. *
  11983. * @param {Object} segment - a simplified copy of the segmentInfo object
  11984. * from SegmentLoader
  11985. * @param {Function} progressFn - a callback that is executed each time a progress event
  11986. * is received
  11987. * @param {Function} trackInfoFn - a callback that receives track info
  11988. * @param {Function} timingInfoFn - a callback that receives timing info
  11989. * @param {Function} videoSegmentTimingInfoFn
  11990. * a callback that receives video timing info based on media times and
  11991. * any adjustments made by the transmuxer
  11992. * @param {Function} audioSegmentTimingInfoFn
  11993. * a callback that receives audio timing info based on media times and
  11994. * any adjustments made by the transmuxer
  11995. * @param {boolean} isEndOfTimeline
  11996. * true if this segment represents the last segment in a timeline
  11997. * @param {Function} endedTimelineFn
  11998. * a callback made when a timeline is ended, will only be called if
  11999. * isEndOfTimeline is true
  12000. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  12001. * and ready to use
  12002. * @param {Event} event - the progress event object from XMLHttpRequest
  12003. */
  12004. const handleProgress = ({
  12005. segment,
  12006. progressFn,
  12007. trackInfoFn,
  12008. timingInfoFn,
  12009. videoSegmentTimingInfoFn,
  12010. audioSegmentTimingInfoFn,
  12011. id3Fn,
  12012. captionsFn,
  12013. isEndOfTimeline,
  12014. endedTimelineFn,
  12015. dataFn
  12016. }) => event => {
  12017. const request = event.target;
  12018. if (request.aborted) {
  12019. return;
  12020. }
  12021. segment.stats = merge(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  12022. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  12023. segment.stats.firstBytesReceivedAt = Date.now();
  12024. }
  12025. return progressFn(event, segment);
  12026. };
  12027. /**
  12028. * Load all resources and does any processing necessary for a media-segment
  12029. *
  12030. * Features:
  12031. * decrypts the media-segment if it has a key uri and an iv
  12032. * aborts *all* requests if *any* one request fails
  12033. *
  12034. * The segment object, at minimum, has the following format:
  12035. * {
  12036. * resolvedUri: String,
  12037. * [transmuxer]: Object,
  12038. * [byterange]: {
  12039. * offset: Number,
  12040. * length: Number
  12041. * },
  12042. * [key]: {
  12043. * resolvedUri: String
  12044. * [byterange]: {
  12045. * offset: Number,
  12046. * length: Number
  12047. * },
  12048. * iv: {
  12049. * bytes: Uint32Array
  12050. * }
  12051. * },
  12052. * [map]: {
  12053. * resolvedUri: String,
  12054. * [byterange]: {
  12055. * offset: Number,
  12056. * length: Number
  12057. * },
  12058. * [bytes]: Uint8Array
  12059. * }
  12060. * }
  12061. * ...where [name] denotes optional properties
  12062. *
  12063. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  12064. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  12065. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  12066. * decryption routines
  12067. * @param {Object} segment - a simplified copy of the segmentInfo object
  12068. * from SegmentLoader
  12069. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  12070. * aborted
  12071. * @param {Function} progressFn - a callback that receives progress events from the main
  12072. * segment's xhr request
  12073. * @param {Function} trackInfoFn - a callback that receives track info
  12074. * @param {Function} timingInfoFn - a callback that receives timing info
  12075. * @param {Function} videoSegmentTimingInfoFn
  12076. * a callback that receives video timing info based on media times and
  12077. * any adjustments made by the transmuxer
  12078. * @param {Function} audioSegmentTimingInfoFn
  12079. * a callback that receives audio timing info based on media times and
  12080. * any adjustments made by the transmuxer
  12081. * @param {Function} id3Fn - a callback that receives ID3 metadata
  12082. * @param {Function} captionsFn - a callback that receives captions
  12083. * @param {boolean} isEndOfTimeline
  12084. * true if this segment represents the last segment in a timeline
  12085. * @param {Function} endedTimelineFn
  12086. * a callback made when a timeline is ended, will only be called if
  12087. * isEndOfTimeline is true
  12088. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  12089. * request, transmuxed if needed
  12090. * @param {Function} doneFn - a callback that is executed only once all requests have
  12091. * succeeded or failed
  12092. * @return {Function} a function that, when invoked, immediately aborts all
  12093. * outstanding requests
  12094. */
  12095. const mediaSegmentRequest = ({
  12096. xhr,
  12097. xhrOptions,
  12098. decryptionWorker,
  12099. segment,
  12100. abortFn,
  12101. progressFn,
  12102. trackInfoFn,
  12103. timingInfoFn,
  12104. videoSegmentTimingInfoFn,
  12105. audioSegmentTimingInfoFn,
  12106. id3Fn,
  12107. captionsFn,
  12108. isEndOfTimeline,
  12109. endedTimelineFn,
  12110. dataFn,
  12111. doneFn,
  12112. onTransmuxerLog
  12113. }) => {
  12114. const activeXhrs = [];
  12115. const finishProcessingFn = waitForCompletion({
  12116. activeXhrs,
  12117. decryptionWorker,
  12118. trackInfoFn,
  12119. timingInfoFn,
  12120. videoSegmentTimingInfoFn,
  12121. audioSegmentTimingInfoFn,
  12122. id3Fn,
  12123. captionsFn,
  12124. isEndOfTimeline,
  12125. endedTimelineFn,
  12126. dataFn,
  12127. doneFn,
  12128. onTransmuxerLog
  12129. }); // optionally, request the decryption key
  12130. if (segment.key && !segment.key.bytes) {
  12131. const objects = [segment.key];
  12132. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  12133. objects.push(segment.map.key);
  12134. }
  12135. const keyRequestOptions = merge(xhrOptions, {
  12136. uri: segment.key.resolvedUri,
  12137. responseType: 'arraybuffer'
  12138. });
  12139. const keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  12140. const keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  12141. activeXhrs.push(keyXhr);
  12142. } // optionally, request the associated media init segment
  12143. if (segment.map && !segment.map.bytes) {
  12144. const differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  12145. if (differentMapKey) {
  12146. const mapKeyRequestOptions = merge(xhrOptions, {
  12147. uri: segment.map.key.resolvedUri,
  12148. responseType: 'arraybuffer'
  12149. });
  12150. const mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  12151. const mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  12152. activeXhrs.push(mapKeyXhr);
  12153. }
  12154. const initSegmentOptions = merge(xhrOptions, {
  12155. uri: segment.map.resolvedUri,
  12156. responseType: 'arraybuffer',
  12157. headers: segmentXhrHeaders(segment.map)
  12158. });
  12159. const initSegmentRequestCallback = handleInitSegmentResponse({
  12160. segment,
  12161. finishProcessingFn
  12162. });
  12163. const initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  12164. activeXhrs.push(initSegmentXhr);
  12165. }
  12166. const segmentRequestOptions = merge(xhrOptions, {
  12167. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  12168. responseType: 'arraybuffer',
  12169. headers: segmentXhrHeaders(segment)
  12170. });
  12171. const segmentRequestCallback = handleSegmentResponse({
  12172. segment,
  12173. finishProcessingFn,
  12174. responseType: segmentRequestOptions.responseType
  12175. });
  12176. const segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  12177. segmentXhr.addEventListener('progress', handleProgress({
  12178. segment,
  12179. progressFn,
  12180. trackInfoFn,
  12181. timingInfoFn,
  12182. videoSegmentTimingInfoFn,
  12183. audioSegmentTimingInfoFn,
  12184. id3Fn,
  12185. captionsFn,
  12186. isEndOfTimeline,
  12187. endedTimelineFn,
  12188. dataFn
  12189. }));
  12190. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  12191. // multiple times, provide a shared state object
  12192. const loadendState = {};
  12193. activeXhrs.forEach(activeXhr => {
  12194. activeXhr.addEventListener('loadend', handleLoadEnd({
  12195. loadendState,
  12196. abortFn
  12197. }));
  12198. });
  12199. return () => abortAll(activeXhrs);
  12200. };
  12201. /**
  12202. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  12203. * codec strings, or translating codec strings into objects that can be examined.
  12204. */
  12205. const logFn$1 = logger('CodecUtils');
  12206. /**
  12207. * Returns a set of codec strings parsed from the playlist or the default
  12208. * codec strings if no codecs were specified in the playlist
  12209. *
  12210. * @param {Playlist} media the current media playlist
  12211. * @return {Object} an object with the video and audio codecs
  12212. */
  12213. const getCodecs = function (media) {
  12214. // if the codecs were explicitly specified, use them instead of the
  12215. // defaults
  12216. const mediaAttributes = media.attributes || {};
  12217. if (mediaAttributes.CODECS) {
  12218. return codecs_js.parseCodecs(mediaAttributes.CODECS);
  12219. }
  12220. };
  12221. const isMaat = (main, media) => {
  12222. const mediaAttributes = media.attributes || {};
  12223. return main && main.mediaGroups && main.mediaGroups.AUDIO && mediaAttributes.AUDIO && main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12224. };
  12225. const isMuxed = (main, media) => {
  12226. if (!isMaat(main, media)) {
  12227. return true;
  12228. }
  12229. const mediaAttributes = media.attributes || {};
  12230. const audioGroup = main.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  12231. for (const groupId in audioGroup) {
  12232. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  12233. // or there are listed playlists (the case for DASH, as the manifest will have already
  12234. // provided all of the details necessary to generate the audio playlist, as opposed to
  12235. // HLS' externally requested playlists), then the content is demuxed.
  12236. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  12237. return true;
  12238. }
  12239. }
  12240. return false;
  12241. };
  12242. const unwrapCodecList = function (codecList) {
  12243. const codecs = {};
  12244. codecList.forEach(({
  12245. mediaType,
  12246. type,
  12247. details
  12248. }) => {
  12249. codecs[mediaType] = codecs[mediaType] || [];
  12250. codecs[mediaType].push(codecs_js.translateLegacyCodec(`${type}${details}`));
  12251. });
  12252. Object.keys(codecs).forEach(function (mediaType) {
  12253. if (codecs[mediaType].length > 1) {
  12254. 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.`);
  12255. codecs[mediaType] = null;
  12256. return;
  12257. }
  12258. codecs[mediaType] = codecs[mediaType][0];
  12259. });
  12260. return codecs;
  12261. };
  12262. const codecCount = function (codecObj) {
  12263. let count = 0;
  12264. if (codecObj.audio) {
  12265. count++;
  12266. }
  12267. if (codecObj.video) {
  12268. count++;
  12269. }
  12270. return count;
  12271. };
  12272. /**
  12273. * Calculates the codec strings for a working configuration of
  12274. * SourceBuffers to play variant streams in a main playlist. If
  12275. * there is no possible working configuration, an empty object will be
  12276. * returned.
  12277. *
  12278. * @param main {Object} the m3u8 object for the main playlist
  12279. * @param media {Object} the m3u8 object for the variant playlist
  12280. * @return {Object} the codec strings.
  12281. *
  12282. * @private
  12283. */
  12284. const codecsForPlaylist = function (main, media) {
  12285. const mediaAttributes = media.attributes || {};
  12286. const codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  12287. // Put another way, there is no way to have a video-only multiple-audio HLS!
  12288. if (isMaat(main, media) && !codecInfo.audio) {
  12289. if (!isMuxed(main, media)) {
  12290. // It is possible for codecs to be specified on the audio media group playlist but
  12291. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  12292. // video are always separate (and separately specified).
  12293. const defaultCodecs = unwrapCodecList(codecs_js.codecsFromDefault(main, mediaAttributes.AUDIO) || []);
  12294. if (defaultCodecs.audio) {
  12295. codecInfo.audio = defaultCodecs.audio;
  12296. }
  12297. }
  12298. }
  12299. return codecInfo;
  12300. };
  12301. const logFn = logger('PlaylistSelector');
  12302. const representationToString = function (representation) {
  12303. if (!representation || !representation.playlist) {
  12304. return;
  12305. }
  12306. const playlist = representation.playlist;
  12307. return JSON.stringify({
  12308. id: playlist.id,
  12309. bandwidth: representation.bandwidth,
  12310. width: representation.width,
  12311. height: representation.height,
  12312. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  12313. });
  12314. }; // Utilities
  12315. /**
  12316. * Returns the CSS value for the specified property on an element
  12317. * using `getComputedStyle`. Firefox has a long-standing issue where
  12318. * getComputedStyle() may return null when running in an iframe with
  12319. * `display: none`.
  12320. *
  12321. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  12322. * @param {HTMLElement} el the htmlelement to work on
  12323. * @param {string} the proprety to get the style for
  12324. */
  12325. const safeGetComputedStyle = function (el, property) {
  12326. if (!el) {
  12327. return '';
  12328. }
  12329. const result = window__default["default"].getComputedStyle(el);
  12330. if (!result) {
  12331. return '';
  12332. }
  12333. return result[property];
  12334. };
  12335. /**
  12336. * Resuable stable sort function
  12337. *
  12338. * @param {Playlists} array
  12339. * @param {Function} sortFn Different comparators
  12340. * @function stableSort
  12341. */
  12342. const stableSort = function (array, sortFn) {
  12343. const newArray = array.slice();
  12344. array.sort(function (left, right) {
  12345. const cmp = sortFn(left, right);
  12346. if (cmp === 0) {
  12347. return newArray.indexOf(left) - newArray.indexOf(right);
  12348. }
  12349. return cmp;
  12350. });
  12351. };
  12352. /**
  12353. * A comparator function to sort two playlist object by bandwidth.
  12354. *
  12355. * @param {Object} left a media playlist object
  12356. * @param {Object} right a media playlist object
  12357. * @return {number} Greater than zero if the bandwidth attribute of
  12358. * left is greater than the corresponding attribute of right. Less
  12359. * than zero if the bandwidth of right is greater than left and
  12360. * exactly zero if the two are equal.
  12361. */
  12362. const comparePlaylistBandwidth = function (left, right) {
  12363. let leftBandwidth;
  12364. let rightBandwidth;
  12365. if (left.attributes.BANDWIDTH) {
  12366. leftBandwidth = left.attributes.BANDWIDTH;
  12367. }
  12368. leftBandwidth = leftBandwidth || window__default["default"].Number.MAX_VALUE;
  12369. if (right.attributes.BANDWIDTH) {
  12370. rightBandwidth = right.attributes.BANDWIDTH;
  12371. }
  12372. rightBandwidth = rightBandwidth || window__default["default"].Number.MAX_VALUE;
  12373. return leftBandwidth - rightBandwidth;
  12374. };
  12375. /**
  12376. * A comparator function to sort two playlist object by resolution (width).
  12377. *
  12378. * @param {Object} left a media playlist object
  12379. * @param {Object} right a media playlist object
  12380. * @return {number} Greater than zero if the resolution.width attribute of
  12381. * left is greater than the corresponding attribute of right. Less
  12382. * than zero if the resolution.width of right is greater than left and
  12383. * exactly zero if the two are equal.
  12384. */
  12385. const comparePlaylistResolution = function (left, right) {
  12386. let leftWidth;
  12387. let rightWidth;
  12388. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  12389. leftWidth = left.attributes.RESOLUTION.width;
  12390. }
  12391. leftWidth = leftWidth || window__default["default"].Number.MAX_VALUE;
  12392. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  12393. rightWidth = right.attributes.RESOLUTION.width;
  12394. }
  12395. rightWidth = rightWidth || window__default["default"].Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  12396. // have the same media dimensions/ resolution
  12397. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  12398. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  12399. }
  12400. return leftWidth - rightWidth;
  12401. };
  12402. /**
  12403. * Chooses the appropriate media playlist based on bandwidth and player size
  12404. *
  12405. * @param {Object} main
  12406. * Object representation of the main manifest
  12407. * @param {number} playerBandwidth
  12408. * Current calculated bandwidth of the player
  12409. * @param {number} playerWidth
  12410. * Current width of the player element (should account for the device pixel ratio)
  12411. * @param {number} playerHeight
  12412. * Current height of the player element (should account for the device pixel ratio)
  12413. * @param {boolean} limitRenditionByPlayerDimensions
  12414. * True if the player width and height should be used during the selection, false otherwise
  12415. * @param {Object} playlistController
  12416. * the current playlistController object
  12417. * @return {Playlist} the highest bitrate playlist less than the
  12418. * currently detected bandwidth, accounting for some amount of
  12419. * bandwidth variance
  12420. */
  12421. let simpleSelector = function (main, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, playlistController) {
  12422. // If we end up getting called before `main` is available, exit early
  12423. if (!main) {
  12424. return;
  12425. }
  12426. const options = {
  12427. bandwidth: playerBandwidth,
  12428. width: playerWidth,
  12429. height: playerHeight,
  12430. limitRenditionByPlayerDimensions
  12431. };
  12432. let playlists = main.playlists; // if playlist is audio only, select between currently active audio group playlists.
  12433. if (Playlist.isAudioOnly(main)) {
  12434. playlists = playlistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  12435. // at the buttom of this function for debugging.
  12436. options.audioOnly = true;
  12437. } // convert the playlists to an intermediary representation to make comparisons easier
  12438. let sortedPlaylistReps = playlists.map(playlist => {
  12439. let bandwidth;
  12440. const width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  12441. const height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  12442. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  12443. bandwidth = bandwidth || window__default["default"].Number.MAX_VALUE;
  12444. return {
  12445. bandwidth,
  12446. width,
  12447. height,
  12448. playlist
  12449. };
  12450. });
  12451. stableSort(sortedPlaylistReps, (left, right) => left.bandwidth - right.bandwidth); // filter out any playlists that have been excluded due to
  12452. // incompatible configurations
  12453. sortedPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isIncompatible(rep.playlist)); // filter out any playlists that have been disabled manually through the representations
  12454. // api or excluded temporarily due to playback errors.
  12455. let enabledPlaylistReps = sortedPlaylistReps.filter(rep => Playlist.isEnabled(rep.playlist));
  12456. if (!enabledPlaylistReps.length) {
  12457. // if there are no enabled playlists, then they have all been excluded or disabled
  12458. // by the user through the representations api. In this case, ignore exclusion and
  12459. // fallback to what the user wants by using playlists the user has not disabled.
  12460. enabledPlaylistReps = sortedPlaylistReps.filter(rep => !Playlist.isDisabled(rep.playlist));
  12461. } // filter out any variant that has greater effective bitrate
  12462. // than the current estimated bandwidth
  12463. const bandwidthPlaylistReps = enabledPlaylistReps.filter(rep => rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth);
  12464. let highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  12465. // and then taking the very first element
  12466. 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.
  12467. if (limitRenditionByPlayerDimensions === false) {
  12468. const chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  12469. if (chosenRep && chosenRep.playlist) {
  12470. let type = 'sortedPlaylistReps';
  12471. if (bandwidthBestRep) {
  12472. type = 'bandwidthBestRep';
  12473. }
  12474. if (enabledPlaylistReps[0]) {
  12475. type = 'enabledPlaylistReps';
  12476. }
  12477. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  12478. return chosenRep.playlist;
  12479. }
  12480. logFn('could not choose a playlist with options', options);
  12481. return null;
  12482. } // filter out playlists without resolution information
  12483. const haveResolution = bandwidthPlaylistReps.filter(rep => rep.width && rep.height); // sort variants by resolution
  12484. stableSort(haveResolution, (left, right) => left.width - right.width); // if we have the exact resolution as the player use it
  12485. const resolutionBestRepList = haveResolution.filter(rep => rep.width === playerWidth && rep.height === playerHeight);
  12486. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  12487. const resolutionBestRep = resolutionBestRepList.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  12488. let resolutionPlusOneList;
  12489. let resolutionPlusOneSmallest;
  12490. let resolutionPlusOneRep; // find the smallest variant that is larger than the player
  12491. // if there is no match of exact resolution
  12492. if (!resolutionBestRep) {
  12493. resolutionPlusOneList = haveResolution.filter(rep => rep.width > playerWidth || rep.height > playerHeight); // find all the variants have the same smallest resolution
  12494. resolutionPlusOneSmallest = resolutionPlusOneList.filter(rep => rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height); // ensure that we also pick the highest bandwidth variant that
  12495. // is just-larger-than the video player
  12496. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  12497. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(rep => rep.bandwidth === highestRemainingBandwidthRep.bandwidth)[0];
  12498. }
  12499. let leastPixelDiffRep; // If this selector proves to be better than others,
  12500. // resolutionPlusOneRep and resolutionBestRep and all
  12501. // the code involving them should be removed.
  12502. if (playlistController.leastPixelDiffSelector) {
  12503. // find the variant that is closest to the player's pixel size
  12504. const leastPixelDiffList = haveResolution.map(rep => {
  12505. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  12506. return rep;
  12507. }); // get the highest bandwidth, closest resolution playlist
  12508. stableSort(leastPixelDiffList, (left, right) => {
  12509. // sort by highest bandwidth if pixelDiff is the same
  12510. if (left.pixelDiff === right.pixelDiff) {
  12511. return right.bandwidth - left.bandwidth;
  12512. }
  12513. return left.pixelDiff - right.pixelDiff;
  12514. });
  12515. leastPixelDiffRep = leastPixelDiffList[0];
  12516. } // fallback chain of variants
  12517. const chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  12518. if (chosenRep && chosenRep.playlist) {
  12519. let type = 'sortedPlaylistReps';
  12520. if (leastPixelDiffRep) {
  12521. type = 'leastPixelDiffRep';
  12522. } else if (resolutionPlusOneRep) {
  12523. type = 'resolutionPlusOneRep';
  12524. } else if (resolutionBestRep) {
  12525. type = 'resolutionBestRep';
  12526. } else if (bandwidthBestRep) {
  12527. type = 'bandwidthBestRep';
  12528. } else if (enabledPlaylistReps[0]) {
  12529. type = 'enabledPlaylistReps';
  12530. }
  12531. logFn(`choosing ${representationToString(chosenRep)} using ${type} with options`, options);
  12532. return chosenRep.playlist;
  12533. }
  12534. logFn('could not choose a playlist with options', options);
  12535. return null;
  12536. };
  12537. /**
  12538. * Chooses the appropriate media playlist based on the most recent
  12539. * bandwidth estimate and the player size.
  12540. *
  12541. * Expects to be called within the context of an instance of VhsHandler
  12542. *
  12543. * @return {Playlist} the highest bitrate playlist less than the
  12544. * currently detected bandwidth, accounting for some amount of
  12545. * bandwidth variance
  12546. */
  12547. const lastBandwidthSelector = function () {
  12548. const pixelRatio = this.useDevicePixelRatio ? window__default["default"].devicePixelRatio || 1 : 1;
  12549. 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_);
  12550. };
  12551. /**
  12552. * Chooses the appropriate media playlist based on an
  12553. * exponential-weighted moving average of the bandwidth after
  12554. * filtering for player size.
  12555. *
  12556. * Expects to be called within the context of an instance of VhsHandler
  12557. *
  12558. * @param {number} decay - a number between 0 and 1. Higher values of
  12559. * this parameter will cause previous bandwidth estimates to lose
  12560. * significance more quickly.
  12561. * @return {Function} a function which can be invoked to create a new
  12562. * playlist selector function.
  12563. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  12564. */
  12565. const movingAverageBandwidthSelector = function (decay) {
  12566. let average = -1;
  12567. let lastSystemBandwidth = -1;
  12568. if (decay < 0 || decay > 1) {
  12569. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  12570. }
  12571. return function () {
  12572. const pixelRatio = this.useDevicePixelRatio ? window__default["default"].devicePixelRatio || 1 : 1;
  12573. if (average < 0) {
  12574. average = this.systemBandwidth;
  12575. lastSystemBandwidth = this.systemBandwidth;
  12576. } // stop the average value from decaying for every 250ms
  12577. // when the systemBandwidth is constant
  12578. // and
  12579. // stop average from setting to a very low value when the
  12580. // systemBandwidth becomes 0 in case of chunk cancellation
  12581. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  12582. average = decay * this.systemBandwidth + (1 - decay) * average;
  12583. lastSystemBandwidth = this.systemBandwidth;
  12584. }
  12585. 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_);
  12586. };
  12587. };
  12588. /**
  12589. * Chooses the appropriate media playlist based on the potential to rebuffer
  12590. *
  12591. * @param {Object} settings
  12592. * Object of information required to use this selector
  12593. * @param {Object} settings.main
  12594. * Object representation of the main manifest
  12595. * @param {number} settings.currentTime
  12596. * The current time of the player
  12597. * @param {number} settings.bandwidth
  12598. * Current measured bandwidth
  12599. * @param {number} settings.duration
  12600. * Duration of the media
  12601. * @param {number} settings.segmentDuration
  12602. * Segment duration to be used in round trip time calculations
  12603. * @param {number} settings.timeUntilRebuffer
  12604. * Time left in seconds until the player has to rebuffer
  12605. * @param {number} settings.currentTimeline
  12606. * The current timeline segments are being loaded from
  12607. * @param {SyncController} settings.syncController
  12608. * SyncController for determining if we have a sync point for a given playlist
  12609. * @return {Object|null}
  12610. * {Object} return.playlist
  12611. * The highest bandwidth playlist with the least amount of rebuffering
  12612. * {Number} return.rebufferingImpact
  12613. * The amount of time in seconds switching to this playlist will rebuffer. A
  12614. * negative value means that switching will cause zero rebuffering.
  12615. */
  12616. const minRebufferMaxBandwidthSelector = function (settings) {
  12617. const {
  12618. main,
  12619. currentTime,
  12620. bandwidth,
  12621. duration,
  12622. segmentDuration,
  12623. timeUntilRebuffer,
  12624. currentTimeline,
  12625. syncController
  12626. } = settings; // filter out any playlists that have been excluded due to
  12627. // incompatible configurations
  12628. const compatiblePlaylists = main.playlists.filter(playlist => !Playlist.isIncompatible(playlist)); // filter out any playlists that have been disabled manually through the representations
  12629. // api or excluded temporarily due to playback errors.
  12630. let enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  12631. if (!enabledPlaylists.length) {
  12632. // if there are no enabled playlists, then they have all been excluded or disabled
  12633. // by the user through the representations api. In this case, ignore exclusion and
  12634. // fallback to what the user wants by using playlists the user has not disabled.
  12635. enabledPlaylists = compatiblePlaylists.filter(playlist => !Playlist.isDisabled(playlist));
  12636. }
  12637. const bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  12638. const rebufferingEstimates = bandwidthPlaylists.map(playlist => {
  12639. const syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  12640. // sync request first. This will double the request time
  12641. const numRequests = syncPoint ? 1 : 2;
  12642. const requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  12643. const rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  12644. return {
  12645. playlist,
  12646. rebufferingImpact
  12647. };
  12648. });
  12649. const noRebufferingPlaylists = rebufferingEstimates.filter(estimate => estimate.rebufferingImpact <= 0); // Sort by bandwidth DESC
  12650. stableSort(noRebufferingPlaylists, (a, b) => comparePlaylistBandwidth(b.playlist, a.playlist));
  12651. if (noRebufferingPlaylists.length) {
  12652. return noRebufferingPlaylists[0];
  12653. }
  12654. stableSort(rebufferingEstimates, (a, b) => a.rebufferingImpact - b.rebufferingImpact);
  12655. return rebufferingEstimates[0] || null;
  12656. };
  12657. /**
  12658. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  12659. * one with video. If no renditions with video exist, return the lowest audio rendition.
  12660. *
  12661. * Expects to be called within the context of an instance of VhsHandler
  12662. *
  12663. * @return {Object|null}
  12664. * {Object} return.playlist
  12665. * The lowest bitrate playlist that contains a video codec. If no such rendition
  12666. * exists pick the lowest audio rendition.
  12667. */
  12668. const lowestBitrateCompatibleVariantSelector = function () {
  12669. // filter out any playlists that have been excluded due to
  12670. // incompatible configurations or playback errors
  12671. const playlists = this.playlists.main.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  12672. stableSort(playlists, (a, b) => comparePlaylistBandwidth(a, b)); // Parse and assume that playlists with no video codec have no video
  12673. // (this is not necessarily true, although it is generally true).
  12674. //
  12675. // If an entire manifest has no valid videos everything will get filtered
  12676. // out.
  12677. const playlistsWithVideo = playlists.filter(playlist => !!codecsForPlaylist(this.playlists.main, playlist).video);
  12678. return playlistsWithVideo[0] || null;
  12679. };
  12680. /**
  12681. * Combine all segments into a single Uint8Array
  12682. *
  12683. * @param {Object} segmentObj
  12684. * @return {Uint8Array} concatenated bytes
  12685. * @private
  12686. */
  12687. const concatSegments = segmentObj => {
  12688. let offset = 0;
  12689. let tempBuffer;
  12690. if (segmentObj.bytes) {
  12691. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  12692. segmentObj.segments.forEach(segment => {
  12693. tempBuffer.set(segment, offset);
  12694. offset += segment.byteLength;
  12695. });
  12696. }
  12697. return tempBuffer;
  12698. };
  12699. /**
  12700. * @file text-tracks.js
  12701. */
  12702. /**
  12703. * Create captions text tracks on video.js if they do not exist
  12704. *
  12705. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  12706. * @param {Object} tech the video.js tech
  12707. * @param {Object} captionStream the caption stream to create
  12708. * @private
  12709. */
  12710. const createCaptionsTrackIfNotExists = function (inbandTextTracks, tech, captionStream) {
  12711. if (!inbandTextTracks[captionStream]) {
  12712. tech.trigger({
  12713. type: 'usage',
  12714. name: 'vhs-608'
  12715. });
  12716. let instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  12717. if (/^cc708_/.test(captionStream)) {
  12718. instreamId = 'SERVICE' + captionStream.split('_')[1];
  12719. }
  12720. const track = tech.textTracks().getTrackById(instreamId);
  12721. if (track) {
  12722. // Resuse an existing track with a CC# id because this was
  12723. // very likely created by videojs-contrib-hls from information
  12724. // in the m3u8 for us to use
  12725. inbandTextTracks[captionStream] = track;
  12726. } else {
  12727. // This section gets called when we have caption services that aren't specified in the manifest.
  12728. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  12729. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  12730. let label = captionStream;
  12731. let language = captionStream;
  12732. let def = false;
  12733. const captionService = captionServices[instreamId];
  12734. if (captionService) {
  12735. label = captionService.label;
  12736. language = captionService.language;
  12737. def = captionService.default;
  12738. } // Otherwise, create a track with the default `CC#` label and
  12739. // without a language
  12740. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  12741. kind: 'captions',
  12742. id: instreamId,
  12743. // TODO: investigate why this doesn't seem to turn the caption on by default
  12744. default: def,
  12745. label,
  12746. language
  12747. }, false).track;
  12748. }
  12749. }
  12750. };
  12751. /**
  12752. * Add caption text track data to a source handler given an array of captions
  12753. *
  12754. * @param {Object}
  12755. * @param {Object} inbandTextTracks the inband text tracks
  12756. * @param {number} timestampOffset the timestamp offset of the source buffer
  12757. * @param {Array} captionArray an array of caption data
  12758. * @private
  12759. */
  12760. const addCaptionData = function ({
  12761. inbandTextTracks,
  12762. captionArray,
  12763. timestampOffset
  12764. }) {
  12765. if (!captionArray) {
  12766. return;
  12767. }
  12768. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  12769. captionArray.forEach(caption => {
  12770. const track = caption.stream;
  12771. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  12772. });
  12773. };
  12774. /**
  12775. * Define properties on a cue for backwards compatability,
  12776. * but warn the user that the way that they are using it
  12777. * is depricated and will be removed at a later date.
  12778. *
  12779. * @param {Cue} cue the cue to add the properties on
  12780. * @private
  12781. */
  12782. const deprecateOldCue = function (cue) {
  12783. Object.defineProperties(cue.frame, {
  12784. id: {
  12785. get() {
  12786. videojs__default["default"].log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  12787. return cue.value.key;
  12788. }
  12789. },
  12790. value: {
  12791. get() {
  12792. videojs__default["default"].log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  12793. return cue.value.data;
  12794. }
  12795. },
  12796. privateData: {
  12797. get() {
  12798. videojs__default["default"].log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  12799. return cue.value.data;
  12800. }
  12801. }
  12802. });
  12803. };
  12804. /**
  12805. * Add metadata text track data to a source handler given an array of metadata
  12806. *
  12807. * @param {Object}
  12808. * @param {Object} inbandTextTracks the inband text tracks
  12809. * @param {Array} metadataArray an array of meta data
  12810. * @param {number} timestampOffset the timestamp offset of the source buffer
  12811. * @param {number} videoDuration the duration of the video
  12812. * @private
  12813. */
  12814. const addMetadata = ({
  12815. inbandTextTracks,
  12816. metadataArray,
  12817. timestampOffset,
  12818. videoDuration
  12819. }) => {
  12820. if (!metadataArray) {
  12821. return;
  12822. }
  12823. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  12824. const metadataTrack = inbandTextTracks.metadataTrack_;
  12825. if (!metadataTrack) {
  12826. return;
  12827. }
  12828. metadataArray.forEach(metadata => {
  12829. const time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  12830. // ignore this bit of metadata.
  12831. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  12832. // which is the "Title/Songname/Content description" frame
  12833. if (typeof time !== 'number' || window__default["default"].isNaN(time) || time < 0 || !(time < Infinity)) {
  12834. return;
  12835. }
  12836. metadata.frames.forEach(frame => {
  12837. const cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  12838. cue.frame = frame;
  12839. cue.value = frame;
  12840. deprecateOldCue(cue);
  12841. metadataTrack.addCue(cue);
  12842. });
  12843. });
  12844. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  12845. return;
  12846. } // Updating the metadeta cues so that
  12847. // the endTime of each cue is the startTime of the next cue
  12848. // the endTime of last cue is the duration of the video
  12849. const cues = metadataTrack.cues;
  12850. const cuesArray = []; // Create a copy of the TextTrackCueList...
  12851. // ...disregarding cues with a falsey value
  12852. for (let i = 0; i < cues.length; i++) {
  12853. if (cues[i]) {
  12854. cuesArray.push(cues[i]);
  12855. }
  12856. } // Group cues by their startTime value
  12857. const cuesGroupedByStartTime = cuesArray.reduce((obj, cue) => {
  12858. const timeSlot = obj[cue.startTime] || [];
  12859. timeSlot.push(cue);
  12860. obj[cue.startTime] = timeSlot;
  12861. return obj;
  12862. }, {}); // Sort startTimes by ascending order
  12863. const sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort((a, b) => Number(a) - Number(b)); // Map each cue group's endTime to the next group's startTime
  12864. sortedStartTimes.forEach((startTime, idx) => {
  12865. const cueGroup = cuesGroupedByStartTime[startTime];
  12866. const nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  12867. cueGroup.forEach(cue => {
  12868. cue.endTime = nextTime;
  12869. });
  12870. });
  12871. };
  12872. /**
  12873. * Create metadata text track on video.js if it does not exist
  12874. *
  12875. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  12876. * @param {string} dispatchType the inband metadata track dispatch type
  12877. * @param {Object} tech the video.js tech
  12878. * @private
  12879. */
  12880. const createMetadataTrackIfNotExists = (inbandTextTracks, dispatchType, tech) => {
  12881. if (inbandTextTracks.metadataTrack_) {
  12882. return;
  12883. }
  12884. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  12885. kind: 'metadata',
  12886. label: 'Timed Metadata'
  12887. }, false).track;
  12888. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  12889. };
  12890. /**
  12891. * Remove cues from a track on video.js.
  12892. *
  12893. * @param {Double} start start of where we should remove the cue
  12894. * @param {Double} end end of where the we should remove the cue
  12895. * @param {Object} track the text track to remove the cues from
  12896. * @private
  12897. */
  12898. const removeCuesFromTrack = function (start, end, track) {
  12899. let i;
  12900. let cue;
  12901. if (!track) {
  12902. return;
  12903. }
  12904. if (!track.cues) {
  12905. return;
  12906. }
  12907. i = track.cues.length;
  12908. while (i--) {
  12909. cue = track.cues[i]; // Remove any cue within the provided start and end time
  12910. if (cue.startTime >= start && cue.endTime <= end) {
  12911. track.removeCue(cue);
  12912. }
  12913. }
  12914. };
  12915. /**
  12916. * Remove duplicate cues from a track on video.js (a cue is considered a
  12917. * duplicate if it has the same time interval and text as another)
  12918. *
  12919. * @param {Object} track the text track to remove the duplicate cues from
  12920. * @private
  12921. */
  12922. const removeDuplicateCuesFromTrack = function (track) {
  12923. const cues = track.cues;
  12924. if (!cues) {
  12925. return;
  12926. }
  12927. for (let i = 0; i < cues.length; i++) {
  12928. const duplicates = [];
  12929. let occurrences = 0;
  12930. for (let j = 0; j < cues.length; j++) {
  12931. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  12932. occurrences++;
  12933. if (occurrences > 1) {
  12934. duplicates.push(cues[j]);
  12935. }
  12936. }
  12937. }
  12938. if (duplicates.length) {
  12939. duplicates.forEach(dupe => track.removeCue(dupe));
  12940. }
  12941. }
  12942. };
  12943. /**
  12944. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  12945. * front of current time.
  12946. *
  12947. * @param {Array} buffer
  12948. * The current buffer of gop information
  12949. * @param {number} currentTime
  12950. * The current time
  12951. * @param {Double} mapping
  12952. * Offset to map display time to stream presentation time
  12953. * @return {Array}
  12954. * List of gops considered safe to append over
  12955. */
  12956. const gopsSafeToAlignWith = (buffer, currentTime, mapping) => {
  12957. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  12958. return [];
  12959. } // pts value for current time + 3 seconds to give a bit more wiggle room
  12960. const currentTimePts = Math.ceil((currentTime - mapping + 3) * clock.ONE_SECOND_IN_TS);
  12961. let i;
  12962. for (i = 0; i < buffer.length; i++) {
  12963. if (buffer[i].pts > currentTimePts) {
  12964. break;
  12965. }
  12966. }
  12967. return buffer.slice(i);
  12968. };
  12969. /**
  12970. * Appends gop information (timing and byteLength) received by the transmuxer for the
  12971. * gops appended in the last call to appendBuffer
  12972. *
  12973. * @param {Array} buffer
  12974. * The current buffer of gop information
  12975. * @param {Array} gops
  12976. * List of new gop information
  12977. * @param {boolean} replace
  12978. * If true, replace the buffer with the new gop information. If false, append the
  12979. * new gop information to the buffer in the right location of time.
  12980. * @return {Array}
  12981. * Updated list of gop information
  12982. */
  12983. const updateGopBuffer = (buffer, gops, replace) => {
  12984. if (!gops.length) {
  12985. return buffer;
  12986. }
  12987. if (replace) {
  12988. // If we are in safe append mode, then completely overwrite the gop buffer
  12989. // with the most recent appeneded data. This will make sure that when appending
  12990. // future segments, we only try to align with gops that are both ahead of current
  12991. // time and in the last segment appended.
  12992. return gops.slice();
  12993. }
  12994. const start = gops[0].pts;
  12995. let i = 0;
  12996. for (i; i < buffer.length; i++) {
  12997. if (buffer[i].pts >= start) {
  12998. break;
  12999. }
  13000. }
  13001. return buffer.slice(0, i).concat(gops);
  13002. };
  13003. /**
  13004. * Removes gop information in buffer that overlaps with provided start and end
  13005. *
  13006. * @param {Array} buffer
  13007. * The current buffer of gop information
  13008. * @param {Double} start
  13009. * position to start the remove at
  13010. * @param {Double} end
  13011. * position to end the remove at
  13012. * @param {Double} mapping
  13013. * Offset to map display time to stream presentation time
  13014. */
  13015. const removeGopBuffer = (buffer, start, end, mapping) => {
  13016. const startPts = Math.ceil((start - mapping) * clock.ONE_SECOND_IN_TS);
  13017. const endPts = Math.ceil((end - mapping) * clock.ONE_SECOND_IN_TS);
  13018. const updatedBuffer = buffer.slice();
  13019. let i = buffer.length;
  13020. while (i--) {
  13021. if (buffer[i].pts <= endPts) {
  13022. break;
  13023. }
  13024. }
  13025. if (i === -1) {
  13026. // no removal because end of remove range is before start of buffer
  13027. return updatedBuffer;
  13028. }
  13029. let j = i + 1;
  13030. while (j--) {
  13031. if (buffer[j].pts <= startPts) {
  13032. break;
  13033. }
  13034. } // clamp remove range start to 0 index
  13035. j = Math.max(j, 0);
  13036. updatedBuffer.splice(j, i - j + 1);
  13037. return updatedBuffer;
  13038. };
  13039. const shallowEqual = function (a, b) {
  13040. // if both are undefined
  13041. // or one or the other is undefined
  13042. // they are not equal
  13043. if (!a && !b || !a && b || a && !b) {
  13044. return false;
  13045. } // they are the same object and thus, equal
  13046. if (a === b) {
  13047. return true;
  13048. } // sort keys so we can make sure they have
  13049. // all the same keys later.
  13050. const akeys = Object.keys(a).sort();
  13051. const bkeys = Object.keys(b).sort(); // different number of keys, not equal
  13052. if (akeys.length !== bkeys.length) {
  13053. return false;
  13054. }
  13055. for (let i = 0; i < akeys.length; i++) {
  13056. const key = akeys[i]; // different sorted keys, not equal
  13057. if (key !== bkeys[i]) {
  13058. return false;
  13059. } // different values, not equal
  13060. if (a[key] !== b[key]) {
  13061. return false;
  13062. }
  13063. }
  13064. return true;
  13065. };
  13066. // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  13067. const QUOTA_EXCEEDED_ERR = 22;
  13068. /**
  13069. * The segment loader has no recourse except to fetch a segment in the
  13070. * current playlist and use the internal timestamps in that segment to
  13071. * generate a syncPoint. This function returns a good candidate index
  13072. * for that process.
  13073. *
  13074. * @param {Array} segments - the segments array from a playlist.
  13075. * @return {number} An index of a segment from the playlist to load
  13076. */
  13077. const getSyncSegmentCandidate = function (currentTimeline, segments, targetTime) {
  13078. segments = segments || [];
  13079. const timelineSegments = [];
  13080. let time = 0;
  13081. for (let i = 0; i < segments.length; i++) {
  13082. const segment = segments[i];
  13083. if (currentTimeline === segment.timeline) {
  13084. timelineSegments.push(i);
  13085. time += segment.duration;
  13086. if (time > targetTime) {
  13087. return i;
  13088. }
  13089. }
  13090. }
  13091. if (timelineSegments.length === 0) {
  13092. return 0;
  13093. } // default to the last timeline segment
  13094. return timelineSegments[timelineSegments.length - 1];
  13095. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  13096. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  13097. // as a start to prevent any potential issues with removing content too close to the
  13098. // playhead.
  13099. const MIN_BACK_BUFFER = 1; // in ms
  13100. const CHECK_BUFFER_DELAY = 500;
  13101. const finite = num => typeof num === 'number' && isFinite(num); // With most content hovering around 30fps, if a segment has a duration less than a half
  13102. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  13103. // not accurately reflect the rest of the content.
  13104. const MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  13105. const illegalMediaSwitch = (loaderType, startingMedia, trackInfo) => {
  13106. // Although these checks should most likely cover non 'main' types, for now it narrows
  13107. // the scope of our checks.
  13108. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  13109. return null;
  13110. }
  13111. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  13112. return 'Neither audio nor video found in segment.';
  13113. }
  13114. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  13115. 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.';
  13116. }
  13117. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  13118. 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.';
  13119. }
  13120. return null;
  13121. };
  13122. /**
  13123. * Calculates a time value that is safe to remove from the back buffer without interrupting
  13124. * playback.
  13125. *
  13126. * @param {TimeRange} seekable
  13127. * The current seekable range
  13128. * @param {number} currentTime
  13129. * The current time of the player
  13130. * @param {number} targetDuration
  13131. * The target duration of the current playlist
  13132. * @return {number}
  13133. * Time that is safe to remove from the back buffer without interrupting playback
  13134. */
  13135. const safeBackBufferTrimTime = (seekable, currentTime, targetDuration) => {
  13136. // 30 seconds before the playhead provides a safe default for trimming.
  13137. //
  13138. // Choosing a reasonable default is particularly important for high bitrate content and
  13139. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  13140. // throw an APPEND_BUFFER_ERR.
  13141. let trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  13142. if (seekable.length) {
  13143. // Some live playlists may have a shorter window of content than the full allowed back
  13144. // buffer. For these playlists, don't save content that's no longer within the window.
  13145. trimTime = Math.max(trimTime, seekable.start(0));
  13146. } // Don't remove within target duration of the current time to avoid the possibility of
  13147. // removing the GOP currently being played, as removing it can cause playback stalls.
  13148. const maxTrimTime = currentTime - targetDuration;
  13149. return Math.min(maxTrimTime, trimTime);
  13150. };
  13151. const segmentInfoString = segmentInfo => {
  13152. const {
  13153. startOfSegment,
  13154. duration,
  13155. segment,
  13156. part,
  13157. playlist: {
  13158. mediaSequence: seq,
  13159. id,
  13160. segments = []
  13161. },
  13162. mediaIndex: index,
  13163. partIndex,
  13164. timeline
  13165. } = segmentInfo;
  13166. const segmentLen = segments.length - 1;
  13167. let selection = 'mediaIndex/partIndex increment';
  13168. if (segmentInfo.getMediaInfoForTime) {
  13169. selection = `getMediaInfoForTime (${segmentInfo.getMediaInfoForTime})`;
  13170. } else if (segmentInfo.isSyncRequest) {
  13171. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  13172. }
  13173. if (segmentInfo.independent) {
  13174. selection += ` with independent ${segmentInfo.independent}`;
  13175. }
  13176. const hasPartIndex = typeof partIndex === 'number';
  13177. const name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  13178. const zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  13179. preloadSegment: segment
  13180. }) - 1 : 0;
  13181. 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}]`;
  13182. };
  13183. const timingInfoPropertyForMedia = mediaType => `${mediaType}TimingInfo`;
  13184. /**
  13185. * Returns the timestamp offset to use for the segment.
  13186. *
  13187. * @param {number} segmentTimeline
  13188. * The timeline of the segment
  13189. * @param {number} currentTimeline
  13190. * The timeline currently being followed by the loader
  13191. * @param {number} startOfSegment
  13192. * The estimated segment start
  13193. * @param {TimeRange[]} buffered
  13194. * The loader's buffer
  13195. * @param {boolean} overrideCheck
  13196. * If true, no checks are made to see if the timestamp offset value should be set,
  13197. * but sets it directly to a value.
  13198. *
  13199. * @return {number|null}
  13200. * Either a number representing a new timestamp offset, or null if the segment is
  13201. * part of the same timeline
  13202. */
  13203. const timestampOffsetForSegment = ({
  13204. segmentTimeline,
  13205. currentTimeline,
  13206. startOfSegment,
  13207. buffered,
  13208. overrideCheck
  13209. }) => {
  13210. // Check to see if we are crossing a discontinuity to see if we need to set the
  13211. // timestamp offset on the transmuxer and source buffer.
  13212. //
  13213. // Previously, we changed the timestampOffset if the start of this segment was less than
  13214. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  13215. // behavior, especially around long running live streams.
  13216. if (!overrideCheck && segmentTimeline === currentTimeline) {
  13217. return null;
  13218. } // When changing renditions, it's possible to request a segment on an older timeline. For
  13219. // instance, given two renditions with the following:
  13220. //
  13221. // #EXTINF:10
  13222. // segment1
  13223. // #EXT-X-DISCONTINUITY
  13224. // #EXTINF:10
  13225. // segment2
  13226. // #EXTINF:10
  13227. // segment3
  13228. //
  13229. // And the current player state:
  13230. //
  13231. // current time: 8
  13232. // buffer: 0 => 20
  13233. //
  13234. // The next segment on the current rendition would be segment3, filling the buffer from
  13235. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  13236. // then the next segment to be requested will be segment1 from the new rendition in
  13237. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  13238. // content (since it would position segment1 of the new rendition starting at 20s). This
  13239. // case can be identified when the new segment's timeline is a prior value. Instead of
  13240. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  13241. // more accurate to the actual start time of the segment.
  13242. if (segmentTimeline < currentTimeline) {
  13243. return startOfSegment;
  13244. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  13245. // value uses the end of the last segment if it is available. While this value
  13246. // should often be correct, it's better to rely on the buffered end, as the new
  13247. // content post discontinuity should line up with the buffered end as if it were
  13248. // time 0 for the new content.
  13249. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  13250. };
  13251. /**
  13252. * Returns whether or not the loader should wait for a timeline change from the timeline
  13253. * change controller before processing the segment.
  13254. *
  13255. * Primary timing in VHS goes by video. This is different from most media players, as
  13256. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  13257. * will continue to use video as the primary timing source, due to the current logic and
  13258. * expectations built around it.
  13259. * Since the timing follows video, in order to maintain sync, the video loader is
  13260. * responsible for setting both audio and video source buffer timestamp offsets.
  13261. *
  13262. * Setting different values for audio and video source buffers could lead to
  13263. * desyncing. The following examples demonstrate some of the situations where this
  13264. * distinction is important. Note that all of these cases involve demuxed content. When
  13265. * content is muxed, the audio and video are packaged together, therefore syncing
  13266. * separate media playlists is not an issue.
  13267. *
  13268. * CASE 1: Audio prepares to load a new timeline before video:
  13269. *
  13270. * Timeline: 0 1
  13271. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13272. * Audio Loader: ^
  13273. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13274. * Video Loader ^
  13275. *
  13276. * In the above example, the audio loader is preparing to load the 6th segment, the first
  13277. * after a discontinuity, while the video loader is still loading the 5th segment, before
  13278. * the discontinuity.
  13279. *
  13280. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  13281. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  13282. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  13283. * the audio loader must provide the audioAppendStart value to trim the content in the
  13284. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  13285. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  13286. * segment until that value is provided.
  13287. *
  13288. * CASE 2: Video prepares to load a new timeline before audio:
  13289. *
  13290. * Timeline: 0 1
  13291. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13292. * Audio Loader: ^
  13293. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13294. * Video Loader ^
  13295. *
  13296. * In the above example, the video loader is preparing to load the 6th segment, the first
  13297. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  13298. * the discontinuity.
  13299. *
  13300. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  13301. * segment is loaded and processed, both the video and audio timestamp offsets will be
  13302. * set, since video is used as the primary timing source. This is to ensure content lines
  13303. * up appropriately, as any modifications to the video timing are reflected by audio when
  13304. * the video loader sets the audio and video timestamp offsets to the same value. However,
  13305. * setting the timestamp offset for audio before audio has had a chance to change
  13306. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  13307. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  13308. *
  13309. * CASE 3: When seeking, audio prepares to load a new timeline before video
  13310. *
  13311. * Timeline: 0 1
  13312. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13313. * Audio Loader: ^
  13314. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  13315. * Video Loader ^
  13316. *
  13317. * In the above example, both audio and video loaders are loading segments from timeline
  13318. * 0, but imagine that the seek originated from timeline 1.
  13319. *
  13320. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  13321. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  13322. * must wait for the video loader to load its segment and update both the audio and video
  13323. * timestamp offsets before it may load and append its own segment. This is the case
  13324. * whether the seek results in a mismatched segment request (e.g., the audio loader
  13325. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  13326. * loaders choose to load the same segment index from each playlist, as the segments may
  13327. * not be aligned perfectly, even for matching segment indexes.
  13328. *
  13329. * @param {Object} timelinechangeController
  13330. * @param {number} currentTimeline
  13331. * The timeline currently being followed by the loader
  13332. * @param {number} segmentTimeline
  13333. * The timeline of the segment being loaded
  13334. * @param {('main'|'audio')} loaderType
  13335. * The loader type
  13336. * @param {boolean} audioDisabled
  13337. * Whether the audio is disabled for the loader. This should only be true when the
  13338. * loader may have muxed audio in its segment, but should not append it, e.g., for
  13339. * the main loader when an alternate audio playlist is active.
  13340. *
  13341. * @return {boolean}
  13342. * Whether the loader should wait for a timeline change from the timeline change
  13343. * controller before processing the segment
  13344. */
  13345. const shouldWaitForTimelineChange = ({
  13346. timelineChangeController,
  13347. currentTimeline,
  13348. segmentTimeline,
  13349. loaderType,
  13350. audioDisabled
  13351. }) => {
  13352. if (currentTimeline === segmentTimeline) {
  13353. return false;
  13354. }
  13355. if (loaderType === 'audio') {
  13356. const lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  13357. type: 'main'
  13358. }); // Audio loader should wait if:
  13359. //
  13360. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  13361. // * main hasn't yet changed to the timeline audio is looking to load
  13362. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  13363. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  13364. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  13365. // loader's segments (or the content is audio/video only and handled by the main
  13366. // loader).
  13367. if (loaderType === 'main' && audioDisabled) {
  13368. const pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  13369. type: 'audio'
  13370. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  13371. // change to the current timeline.
  13372. //
  13373. // Since the main loader is responsible for setting the timestamp offset for both
  13374. // audio and video, the main loader must wait for audio to be about to change to its
  13375. // timeline before setting the offset, otherwise, if audio is behind in loading,
  13376. // segments from the previous timeline would be adjusted by the new timestamp offset.
  13377. //
  13378. // This requirement means that video will not cross a timeline until the audio is
  13379. // about to cross to it, so that way audio and video will always cross the timeline
  13380. // together.
  13381. //
  13382. // In addition to normal timeline changes, these rules also apply to the start of a
  13383. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  13384. // that these rules apply to the first timeline change because if they did not, it's
  13385. // possible that the main loader will cross two timelines before the audio loader has
  13386. // crossed one. Logic may be implemented to handle the startup as a special case, but
  13387. // it's easier to simply treat all timeline changes the same.
  13388. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  13389. return false;
  13390. }
  13391. return true;
  13392. }
  13393. return false;
  13394. };
  13395. const mediaDuration = timingInfos => {
  13396. let maxDuration = 0;
  13397. ['video', 'audio'].forEach(function (type) {
  13398. const typeTimingInfo = timingInfos[`${type}TimingInfo`];
  13399. if (!typeTimingInfo) {
  13400. return;
  13401. }
  13402. const {
  13403. start,
  13404. end
  13405. } = typeTimingInfo;
  13406. let duration;
  13407. if (typeof start === 'bigint' || typeof end === 'bigint') {
  13408. duration = window__default["default"].BigInt(end) - window__default["default"].BigInt(start);
  13409. } else if (typeof start === 'number' && typeof end === 'number') {
  13410. duration = end - start;
  13411. }
  13412. if (typeof duration !== 'undefined' && duration > maxDuration) {
  13413. maxDuration = duration;
  13414. }
  13415. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  13416. // as we only need BigInt when we are above that.
  13417. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  13418. maxDuration = Number(maxDuration);
  13419. }
  13420. return maxDuration;
  13421. };
  13422. const segmentTooLong = ({
  13423. segmentDuration,
  13424. maxDuration
  13425. }) => {
  13426. // 0 duration segments are most likely due to metadata only segments or a lack of
  13427. // information.
  13428. if (!segmentDuration) {
  13429. return false;
  13430. } // For HLS:
  13431. //
  13432. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  13433. // The EXTINF duration of each Media Segment in the Playlist
  13434. // file, when rounded to the nearest integer, MUST be less than or equal
  13435. // to the target duration; longer segments can trigger playback stalls
  13436. // or other errors.
  13437. //
  13438. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  13439. // duration. Although that reported duration is occasionally approximate (i.e., not
  13440. // exact), a strict check may report that a segment is too long more often in DASH.
  13441. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  13442. };
  13443. const getTroublesomeSegmentDurationMessage = (segmentInfo, sourceType) => {
  13444. // Right now we aren't following DASH's timing model exactly, so only perform
  13445. // this check for HLS content.
  13446. if (sourceType !== 'hls') {
  13447. return null;
  13448. }
  13449. const segmentDuration = mediaDuration({
  13450. audioTimingInfo: segmentInfo.audioTimingInfo,
  13451. videoTimingInfo: segmentInfo.videoTimingInfo
  13452. }); // Don't report if we lack information.
  13453. //
  13454. // If the segment has a duration of 0 it is either a lack of information or a
  13455. // metadata only segment and shouldn't be reported here.
  13456. if (!segmentDuration) {
  13457. return null;
  13458. }
  13459. const targetDuration = segmentInfo.playlist.targetDuration;
  13460. const isSegmentWayTooLong = segmentTooLong({
  13461. segmentDuration,
  13462. maxDuration: targetDuration * 2
  13463. });
  13464. const isSegmentSlightlyTooLong = segmentTooLong({
  13465. segmentDuration,
  13466. maxDuration: targetDuration
  13467. });
  13468. 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';
  13469. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  13470. return {
  13471. severity: isSegmentWayTooLong ? 'warn' : 'info',
  13472. message: segmentTooLongMessage
  13473. };
  13474. }
  13475. return null;
  13476. };
  13477. /**
  13478. * An object that manages segment loading and appending.
  13479. *
  13480. * @class SegmentLoader
  13481. * @param {Object} options required and optional options
  13482. * @extends videojs.EventTarget
  13483. */
  13484. class SegmentLoader extends videojs__default["default"].EventTarget {
  13485. constructor(settings, options = {}) {
  13486. super(); // check pre-conditions
  13487. if (!settings) {
  13488. throw new TypeError('Initialization settings are required');
  13489. }
  13490. if (typeof settings.currentTime !== 'function') {
  13491. throw new TypeError('No currentTime getter specified');
  13492. }
  13493. if (!settings.mediaSource) {
  13494. throw new TypeError('No MediaSource specified');
  13495. } // public properties
  13496. this.bandwidth = settings.bandwidth;
  13497. this.throughput = {
  13498. rate: 0,
  13499. count: 0
  13500. };
  13501. this.roundTrip = NaN;
  13502. this.resetStats_();
  13503. this.mediaIndex = null;
  13504. this.partIndex = null; // private settings
  13505. this.hasPlayed_ = settings.hasPlayed;
  13506. this.currentTime_ = settings.currentTime;
  13507. this.seekable_ = settings.seekable;
  13508. this.seeking_ = settings.seeking;
  13509. this.duration_ = settings.duration;
  13510. this.mediaSource_ = settings.mediaSource;
  13511. this.vhs_ = settings.vhs;
  13512. this.loaderType_ = settings.loaderType;
  13513. this.currentMediaInfo_ = void 0;
  13514. this.startingMediaInfo_ = void 0;
  13515. this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  13516. this.goalBufferLength_ = settings.goalBufferLength;
  13517. this.sourceType_ = settings.sourceType;
  13518. this.sourceUpdater_ = settings.sourceUpdater;
  13519. this.inbandTextTracks_ = settings.inbandTextTracks;
  13520. this.state_ = 'INIT';
  13521. this.timelineChangeController_ = settings.timelineChangeController;
  13522. this.shouldSaveSegmentTimingInfo_ = true;
  13523. this.parse708captions_ = settings.parse708captions;
  13524. this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  13525. this.captionServices_ = settings.captionServices;
  13526. this.exactManifestTimings = settings.exactManifestTimings; // private instance variables
  13527. this.checkBufferTimeout_ = null;
  13528. this.error_ = void 0;
  13529. this.currentTimeline_ = -1;
  13530. this.pendingSegment_ = null;
  13531. this.xhrOptions_ = null;
  13532. this.pendingSegments_ = [];
  13533. this.audioDisabled_ = false;
  13534. this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  13535. this.gopBuffer_ = [];
  13536. this.timeMapping_ = 0;
  13537. this.safeAppend_ = videojs__default["default"].browser.IE_VERSION >= 11;
  13538. this.appendInitSegment_ = {
  13539. audio: true,
  13540. video: true
  13541. };
  13542. this.playlistOfLastInitSegment_ = {
  13543. audio: null,
  13544. video: null
  13545. };
  13546. this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  13547. // information yet to start the loading process (e.g., if the audio loader wants to
  13548. // load a segment from the next timeline but the main loader hasn't yet crossed that
  13549. // timeline), then the load call will be added to the queue until it is ready to be
  13550. // processed.
  13551. this.loadQueue_ = [];
  13552. this.metadataQueue_ = {
  13553. id3: [],
  13554. caption: []
  13555. };
  13556. this.waitingOnRemove_ = false;
  13557. this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  13558. this.activeInitSegmentId_ = null;
  13559. this.initSegments_ = {}; // HLSe playback
  13560. this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  13561. this.keyCache_ = {};
  13562. this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  13563. // between a time in the display time and a segment index within
  13564. // a playlist
  13565. this.syncController_ = settings.syncController;
  13566. this.syncPoint_ = {
  13567. segmentIndex: 0,
  13568. time: 0
  13569. };
  13570. this.transmuxer_ = this.createTransmuxer_();
  13571. this.triggerSyncInfoUpdate_ = () => this.trigger('syncinfoupdate');
  13572. this.syncController_.on('syncinfoupdate', this.triggerSyncInfoUpdate_);
  13573. this.mediaSource_.addEventListener('sourceopen', () => {
  13574. if (!this.isEndOfStream_()) {
  13575. this.ended_ = false;
  13576. }
  13577. }); // ...for determining the fetch location
  13578. this.fetchAtBuffer_ = false;
  13579. this.logger_ = logger(`SegmentLoader[${this.loaderType_}]`);
  13580. Object.defineProperty(this, 'state', {
  13581. get() {
  13582. return this.state_;
  13583. },
  13584. set(newState) {
  13585. if (newState !== this.state_) {
  13586. this.logger_(`${this.state_} -> ${newState}`);
  13587. this.state_ = newState;
  13588. this.trigger('statechange');
  13589. }
  13590. }
  13591. });
  13592. this.sourceUpdater_.on('ready', () => {
  13593. if (this.hasEnoughInfoToAppend_()) {
  13594. this.processCallQueue_();
  13595. }
  13596. }); // Only the main loader needs to listen for pending timeline changes, as the main
  13597. // loader should wait for audio to be ready to change its timeline so that both main
  13598. // and audio timelines change together. For more details, see the
  13599. // shouldWaitForTimelineChange function.
  13600. if (this.loaderType_ === 'main') {
  13601. this.timelineChangeController_.on('pendingtimelinechange', () => {
  13602. if (this.hasEnoughInfoToAppend_()) {
  13603. this.processCallQueue_();
  13604. }
  13605. });
  13606. } // The main loader only listens on pending timeline changes, but the audio loader,
  13607. // since its loads follow main, needs to listen on timeline changes. For more details,
  13608. // see the shouldWaitForTimelineChange function.
  13609. if (this.loaderType_ === 'audio') {
  13610. this.timelineChangeController_.on('timelinechange', () => {
  13611. if (this.hasEnoughInfoToLoad_()) {
  13612. this.processLoadQueue_();
  13613. }
  13614. if (this.hasEnoughInfoToAppend_()) {
  13615. this.processCallQueue_();
  13616. }
  13617. });
  13618. }
  13619. }
  13620. createTransmuxer_() {
  13621. return segmentTransmuxer.createTransmuxer({
  13622. remux: false,
  13623. alignGopsAtEnd: this.safeAppend_,
  13624. keepOriginalTimestamps: true,
  13625. parse708captions: this.parse708captions_,
  13626. captionServices: this.captionServices_
  13627. });
  13628. }
  13629. /**
  13630. * reset all of our media stats
  13631. *
  13632. * @private
  13633. */
  13634. resetStats_() {
  13635. this.mediaBytesTransferred = 0;
  13636. this.mediaRequests = 0;
  13637. this.mediaRequestsAborted = 0;
  13638. this.mediaRequestsTimedout = 0;
  13639. this.mediaRequestsErrored = 0;
  13640. this.mediaTransferDuration = 0;
  13641. this.mediaSecondsLoaded = 0;
  13642. this.mediaAppends = 0;
  13643. }
  13644. /**
  13645. * dispose of the SegmentLoader and reset to the default state
  13646. */
  13647. dispose() {
  13648. this.trigger('dispose');
  13649. this.state = 'DISPOSED';
  13650. this.pause();
  13651. this.abort_();
  13652. if (this.transmuxer_) {
  13653. this.transmuxer_.terminate();
  13654. }
  13655. this.resetStats_();
  13656. if (this.checkBufferTimeout_) {
  13657. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  13658. }
  13659. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  13660. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  13661. }
  13662. this.off();
  13663. }
  13664. setAudio(enable) {
  13665. this.audioDisabled_ = !enable;
  13666. if (enable) {
  13667. this.appendInitSegment_.audio = true;
  13668. } else {
  13669. // remove current track audio if it gets disabled
  13670. this.sourceUpdater_.removeAudio(0, this.duration_());
  13671. }
  13672. }
  13673. /**
  13674. * abort anything that is currently doing on with the SegmentLoader
  13675. * and reset to a default state
  13676. */
  13677. abort() {
  13678. if (this.state !== 'WAITING') {
  13679. if (this.pendingSegment_) {
  13680. this.pendingSegment_ = null;
  13681. }
  13682. return;
  13683. }
  13684. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  13685. // since we are no longer "waiting" on any requests. XHR callback is not always run
  13686. // when the request is aborted. This will prevent the loader from being stuck in the
  13687. // WAITING state indefinitely.
  13688. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  13689. // next segment
  13690. if (!this.paused()) {
  13691. this.monitorBuffer_();
  13692. }
  13693. }
  13694. /**
  13695. * abort all pending xhr requests and null any pending segements
  13696. *
  13697. * @private
  13698. */
  13699. abort_() {
  13700. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  13701. this.pendingSegment_.abortRequests();
  13702. } // clear out the segment being processed
  13703. this.pendingSegment_ = null;
  13704. this.callQueue_ = [];
  13705. this.loadQueue_ = [];
  13706. this.metadataQueue_.id3 = [];
  13707. this.metadataQueue_.caption = [];
  13708. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  13709. this.waitingOnRemove_ = false;
  13710. window__default["default"].clearTimeout(this.quotaExceededErrorRetryTimeout_);
  13711. this.quotaExceededErrorRetryTimeout_ = null;
  13712. }
  13713. checkForAbort_(requestId) {
  13714. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  13715. // callback that happens should reset the state to READY so that loading can continue.
  13716. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  13717. this.state = 'READY';
  13718. return true;
  13719. }
  13720. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  13721. return true;
  13722. }
  13723. return false;
  13724. }
  13725. /**
  13726. * set an error on the segment loader and null out any pending segements
  13727. *
  13728. * @param {Error} error the error to set on the SegmentLoader
  13729. * @return {Error} the error that was set or that is currently set
  13730. */
  13731. error(error) {
  13732. if (typeof error !== 'undefined') {
  13733. this.logger_('error occurred:', error);
  13734. this.error_ = error;
  13735. }
  13736. this.pendingSegment_ = null;
  13737. return this.error_;
  13738. }
  13739. endOfStream() {
  13740. this.ended_ = true;
  13741. if (this.transmuxer_) {
  13742. // need to clear out any cached data to prepare for the new segment
  13743. segmentTransmuxer.reset(this.transmuxer_);
  13744. }
  13745. this.gopBuffer_.length = 0;
  13746. this.pause();
  13747. this.trigger('ended');
  13748. }
  13749. /**
  13750. * Indicates which time ranges are buffered
  13751. *
  13752. * @return {TimeRange}
  13753. * TimeRange object representing the current buffered ranges
  13754. */
  13755. buffered_() {
  13756. const trackInfo = this.getMediaInfo_();
  13757. if (!this.sourceUpdater_ || !trackInfo) {
  13758. return createTimeRanges();
  13759. }
  13760. if (this.loaderType_ === 'main') {
  13761. const {
  13762. hasAudio,
  13763. hasVideo,
  13764. isMuxed
  13765. } = trackInfo;
  13766. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  13767. return this.sourceUpdater_.buffered();
  13768. }
  13769. if (hasVideo) {
  13770. return this.sourceUpdater_.videoBuffered();
  13771. }
  13772. } // One case that can be ignored for now is audio only with alt audio,
  13773. // as we don't yet have proper support for that.
  13774. return this.sourceUpdater_.audioBuffered();
  13775. }
  13776. /**
  13777. * Gets and sets init segment for the provided map
  13778. *
  13779. * @param {Object} map
  13780. * The map object representing the init segment to get or set
  13781. * @param {boolean=} set
  13782. * If true, the init segment for the provided map should be saved
  13783. * @return {Object}
  13784. * map object for desired init segment
  13785. */
  13786. initSegmentForMap(map, set = false) {
  13787. if (!map) {
  13788. return null;
  13789. }
  13790. const id = initSegmentId(map);
  13791. let storedMap = this.initSegments_[id];
  13792. if (set && !storedMap && map.bytes) {
  13793. this.initSegments_[id] = storedMap = {
  13794. resolvedUri: map.resolvedUri,
  13795. byterange: map.byterange,
  13796. bytes: map.bytes,
  13797. tracks: map.tracks,
  13798. timescales: map.timescales
  13799. };
  13800. }
  13801. return storedMap || map;
  13802. }
  13803. /**
  13804. * Gets and sets key for the provided key
  13805. *
  13806. * @param {Object} key
  13807. * The key object representing the key to get or set
  13808. * @param {boolean=} set
  13809. * If true, the key for the provided key should be saved
  13810. * @return {Object}
  13811. * Key object for desired key
  13812. */
  13813. segmentKey(key, set = false) {
  13814. if (!key) {
  13815. return null;
  13816. }
  13817. const id = segmentKeyId(key);
  13818. let storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  13819. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  13820. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  13821. this.keyCache_[id] = storedKey = {
  13822. resolvedUri: key.resolvedUri,
  13823. bytes: key.bytes
  13824. };
  13825. }
  13826. const result = {
  13827. resolvedUri: (storedKey || key).resolvedUri
  13828. };
  13829. if (storedKey) {
  13830. result.bytes = storedKey.bytes;
  13831. }
  13832. return result;
  13833. }
  13834. /**
  13835. * Returns true if all configuration required for loading is present, otherwise false.
  13836. *
  13837. * @return {boolean} True if the all configuration is ready for loading
  13838. * @private
  13839. */
  13840. couldBeginLoading_() {
  13841. return this.playlist_ && !this.paused();
  13842. }
  13843. /**
  13844. * load a playlist and start to fill the buffer
  13845. */
  13846. load() {
  13847. // un-pause
  13848. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  13849. // specified
  13850. if (!this.playlist_) {
  13851. return;
  13852. } // if all the configuration is ready, initialize and begin loading
  13853. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  13854. return this.init_();
  13855. } // if we're in the middle of processing a segment already, don't
  13856. // kick off an additional segment request
  13857. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  13858. return;
  13859. }
  13860. this.state = 'READY';
  13861. }
  13862. /**
  13863. * Once all the starting parameters have been specified, begin
  13864. * operation. This method should only be invoked from the INIT
  13865. * state.
  13866. *
  13867. * @private
  13868. */
  13869. init_() {
  13870. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  13871. // audio data from the muxed content should be removed
  13872. this.resetEverything();
  13873. return this.monitorBuffer_();
  13874. }
  13875. /**
  13876. * set a playlist on the segment loader
  13877. *
  13878. * @param {PlaylistLoader} media the playlist to set on the segment loader
  13879. */
  13880. playlist(newPlaylist, options = {}) {
  13881. if (!newPlaylist) {
  13882. return;
  13883. }
  13884. const oldPlaylist = this.playlist_;
  13885. const segmentInfo = this.pendingSegment_;
  13886. this.playlist_ = newPlaylist;
  13887. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  13888. // is always our zero-time so force a sync update each time the playlist
  13889. // is refreshed from the server
  13890. //
  13891. // Use the INIT state to determine if playback has started, as the playlist sync info
  13892. // should be fixed once requests begin (as sync points are generated based on sync
  13893. // info), but not before then.
  13894. if (this.state === 'INIT') {
  13895. newPlaylist.syncInfo = {
  13896. mediaSequence: newPlaylist.mediaSequence,
  13897. time: 0
  13898. }; // Setting the date time mapping means mapping the program date time (if available)
  13899. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  13900. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  13901. // be updated as the playlist is refreshed before the loader starts loading, the
  13902. // program date time mapping needs to be updated as well.
  13903. //
  13904. // This mapping is only done for the main loader because a program date time should
  13905. // map equivalently between playlists.
  13906. if (this.loaderType_ === 'main') {
  13907. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  13908. }
  13909. }
  13910. let oldId = null;
  13911. if (oldPlaylist) {
  13912. if (oldPlaylist.id) {
  13913. oldId = oldPlaylist.id;
  13914. } else if (oldPlaylist.uri) {
  13915. oldId = oldPlaylist.uri;
  13916. }
  13917. }
  13918. this.logger_(`playlist update [${oldId} => ${newPlaylist.id || newPlaylist.uri}]`); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  13919. // in LIVE, we always want to update with new playlists (including refreshes)
  13920. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  13921. // buffering now
  13922. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  13923. return this.init_();
  13924. }
  13925. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  13926. if (this.mediaIndex !== null) {
  13927. // we must reset/resync the segment loader when we switch renditions and
  13928. // the segment loader is already synced to the previous rendition
  13929. // on playlist changes we want it to be possible to fetch
  13930. // at the buffer for vod but not for live. So we use resetLoader
  13931. // for live and resyncLoader for vod. We want this because
  13932. // if a playlist uses independent and non-independent segments/parts the
  13933. // buffer may not accurately reflect the next segment that we should try
  13934. // downloading.
  13935. if (!newPlaylist.endList) {
  13936. this.resetLoader();
  13937. } else {
  13938. this.resyncLoader();
  13939. }
  13940. }
  13941. this.currentMediaInfo_ = void 0;
  13942. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  13943. return;
  13944. } // we reloaded the same playlist so we are in a live scenario
  13945. // and we will likely need to adjust the mediaIndex
  13946. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  13947. this.logger_(`live window shift [${mediaSequenceDiff}]`); // update the mediaIndex on the SegmentLoader
  13948. // this is important because we can abort a request and this value must be
  13949. // equal to the last appended mediaIndex
  13950. if (this.mediaIndex !== null) {
  13951. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  13952. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  13953. // new playlist was incremented by 1.
  13954. if (this.mediaIndex < 0) {
  13955. this.mediaIndex = null;
  13956. this.partIndex = null;
  13957. } else {
  13958. const segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  13959. // unless parts fell off of the playlist for this segment.
  13960. // In that case we need to reset partIndex and resync
  13961. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  13962. const mediaIndex = this.mediaIndex;
  13963. this.logger_(`currently processing part (index ${this.partIndex}) no longer exists.`);
  13964. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  13965. // as the part was dropped from our current playlists segment.
  13966. // The mediaIndex will still be valid so keep that around.
  13967. this.mediaIndex = mediaIndex;
  13968. }
  13969. }
  13970. } // update the mediaIndex on the SegmentInfo object
  13971. // this is important because we will update this.mediaIndex with this value
  13972. // in `handleAppendsDone_` after the segment has been successfully appended
  13973. if (segmentInfo) {
  13974. segmentInfo.mediaIndex -= mediaSequenceDiff;
  13975. if (segmentInfo.mediaIndex < 0) {
  13976. segmentInfo.mediaIndex = null;
  13977. segmentInfo.partIndex = null;
  13978. } else {
  13979. // we need to update the referenced segment so that timing information is
  13980. // saved for the new playlist's segment, however, if the segment fell off the
  13981. // playlist, we can leave the old reference and just lose the timing info
  13982. if (segmentInfo.mediaIndex >= 0) {
  13983. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  13984. }
  13985. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  13986. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  13987. }
  13988. }
  13989. }
  13990. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  13991. }
  13992. /**
  13993. * Prevent the loader from fetching additional segments. If there
  13994. * is a segment request outstanding, it will finish processing
  13995. * before the loader halts. A segment loader can be unpaused by
  13996. * calling load().
  13997. */
  13998. pause() {
  13999. if (this.checkBufferTimeout_) {
  14000. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  14001. this.checkBufferTimeout_ = null;
  14002. }
  14003. }
  14004. /**
  14005. * Returns whether the segment loader is fetching additional
  14006. * segments when given the opportunity. This property can be
  14007. * modified through calls to pause() and load().
  14008. */
  14009. paused() {
  14010. return this.checkBufferTimeout_ === null;
  14011. }
  14012. /**
  14013. * Delete all the buffered data and reset the SegmentLoader
  14014. *
  14015. * @param {Function} [done] an optional callback to be executed when the remove
  14016. * operation is complete
  14017. */
  14018. resetEverything(done) {
  14019. this.ended_ = false;
  14020. this.activeInitSegmentId_ = null;
  14021. this.appendInitSegment_ = {
  14022. audio: true,
  14023. video: true
  14024. };
  14025. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  14026. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  14027. // we then clamp the value to duration if necessary.
  14028. this.remove(0, Infinity, done); // clears fmp4 captions
  14029. if (this.transmuxer_) {
  14030. this.transmuxer_.postMessage({
  14031. action: 'clearAllMp4Captions'
  14032. }); // reset the cache in the transmuxer
  14033. this.transmuxer_.postMessage({
  14034. action: 'reset'
  14035. });
  14036. }
  14037. }
  14038. /**
  14039. * Force the SegmentLoader to resync and start loading around the currentTime instead
  14040. * of starting at the end of the buffer
  14041. *
  14042. * Useful for fast quality changes
  14043. */
  14044. resetLoader() {
  14045. this.fetchAtBuffer_ = false;
  14046. this.resyncLoader();
  14047. }
  14048. /**
  14049. * Force the SegmentLoader to restart synchronization and make a conservative guess
  14050. * before returning to the simple walk-forward method
  14051. */
  14052. resyncLoader() {
  14053. if (this.transmuxer_) {
  14054. // need to clear out any cached data to prepare for the new segment
  14055. segmentTransmuxer.reset(this.transmuxer_);
  14056. }
  14057. this.mediaIndex = null;
  14058. this.partIndex = null;
  14059. this.syncPoint_ = null;
  14060. this.isPendingTimestampOffset_ = false;
  14061. this.callQueue_ = [];
  14062. this.loadQueue_ = [];
  14063. this.metadataQueue_.id3 = [];
  14064. this.metadataQueue_.caption = [];
  14065. this.abort();
  14066. if (this.transmuxer_) {
  14067. this.transmuxer_.postMessage({
  14068. action: 'clearParsedMp4Captions'
  14069. });
  14070. }
  14071. }
  14072. /**
  14073. * Remove any data in the source buffer between start and end times
  14074. *
  14075. * @param {number} start - the start time of the region to remove from the buffer
  14076. * @param {number} end - the end time of the region to remove from the buffer
  14077. * @param {Function} [done] - an optional callback to be executed when the remove
  14078. * @param {boolean} force - force all remove operations to happen
  14079. * operation is complete
  14080. */
  14081. remove(start, end, done = () => {}, force = false) {
  14082. // clamp end to duration if we need to remove everything.
  14083. // This is due to a browser bug that causes issues if we remove to Infinity.
  14084. // videojs/videojs-contrib-hls#1225
  14085. if (end === Infinity) {
  14086. end = this.duration_();
  14087. } // skip removes that would throw an error
  14088. // commonly happens during a rendition switch at the start of a video
  14089. // from start 0 to end 0
  14090. if (end <= start) {
  14091. this.logger_('skipping remove because end ${end} is <= start ${start}');
  14092. return;
  14093. }
  14094. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  14095. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  14096. return;
  14097. } // set it to one to complete this function's removes
  14098. let removesRemaining = 1;
  14099. const removeFinished = () => {
  14100. removesRemaining--;
  14101. if (removesRemaining === 0) {
  14102. done();
  14103. }
  14104. };
  14105. if (force || !this.audioDisabled_) {
  14106. removesRemaining++;
  14107. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  14108. } // While it would be better to only remove video if the main loader has video, this
  14109. // should be safe with audio only as removeVideo will call back even if there's no
  14110. // video buffer.
  14111. //
  14112. // In theory we can check to see if there's video before calling the remove, but in
  14113. // the event that we're switching between renditions and from video to audio only
  14114. // (when we add support for that), we may need to clear the video contents despite
  14115. // what the new media will contain.
  14116. if (force || this.loaderType_ === 'main') {
  14117. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  14118. removesRemaining++;
  14119. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  14120. } // remove any captions and ID3 tags
  14121. for (const track in this.inbandTextTracks_) {
  14122. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  14123. }
  14124. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  14125. removeFinished();
  14126. }
  14127. /**
  14128. * (re-)schedule monitorBufferTick_ to run as soon as possible
  14129. *
  14130. * @private
  14131. */
  14132. monitorBuffer_() {
  14133. if (this.checkBufferTimeout_) {
  14134. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  14135. }
  14136. this.checkBufferTimeout_ = window__default["default"].setTimeout(this.monitorBufferTick_.bind(this), 1);
  14137. }
  14138. /**
  14139. * As long as the SegmentLoader is in the READY state, periodically
  14140. * invoke fillBuffer_().
  14141. *
  14142. * @private
  14143. */
  14144. monitorBufferTick_() {
  14145. if (this.state === 'READY') {
  14146. this.fillBuffer_();
  14147. }
  14148. if (this.checkBufferTimeout_) {
  14149. window__default["default"].clearTimeout(this.checkBufferTimeout_);
  14150. }
  14151. this.checkBufferTimeout_ = window__default["default"].setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  14152. }
  14153. /**
  14154. * fill the buffer with segements unless the sourceBuffers are
  14155. * currently updating
  14156. *
  14157. * Note: this function should only ever be called by monitorBuffer_
  14158. * and never directly
  14159. *
  14160. * @private
  14161. */
  14162. fillBuffer_() {
  14163. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  14164. // except when we're ready for the next segment, this check can most likely be removed
  14165. if (this.sourceUpdater_.updating()) {
  14166. return;
  14167. } // see if we need to begin loading immediately
  14168. const segmentInfo = this.chooseNextRequest_();
  14169. if (!segmentInfo) {
  14170. return;
  14171. }
  14172. if (typeof segmentInfo.timestampOffset === 'number') {
  14173. this.isPendingTimestampOffset_ = false;
  14174. this.timelineChangeController_.pendingTimelineChange({
  14175. type: this.loaderType_,
  14176. from: this.currentTimeline_,
  14177. to: segmentInfo.timeline
  14178. });
  14179. }
  14180. this.loadSegment_(segmentInfo);
  14181. }
  14182. /**
  14183. * Determines if we should call endOfStream on the media source based
  14184. * on the state of the buffer or if appened segment was the final
  14185. * segment in the playlist.
  14186. *
  14187. * @param {number} [mediaIndex] the media index of segment we last appended
  14188. * @param {Object} [playlist] a media playlist object
  14189. * @return {boolean} do we need to call endOfStream on the MediaSource
  14190. */
  14191. isEndOfStream_(mediaIndex = this.mediaIndex, playlist = this.playlist_, partIndex = this.partIndex) {
  14192. if (!playlist || !this.mediaSource_) {
  14193. return false;
  14194. }
  14195. const segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  14196. const appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  14197. 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
  14198. // so that MediaSources can trigger the `ended` event when it runs out of
  14199. // buffered data instead of waiting for me
  14200. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  14201. }
  14202. /**
  14203. * Determines what request should be made given current segment loader state.
  14204. *
  14205. * @return {Object} a request object that describes the segment/part to load
  14206. */
  14207. chooseNextRequest_() {
  14208. const buffered = this.buffered_();
  14209. const bufferedEnd = lastBufferedEnd(buffered) || 0;
  14210. const bufferedTime = timeAheadOf(buffered, this.currentTime_());
  14211. const preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  14212. const haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  14213. const segments = this.playlist_.segments; // return no segment if:
  14214. // 1. we don't have segments
  14215. // 2. The video has not yet played and we already downloaded a segment
  14216. // 3. we already have enough buffered time
  14217. if (!segments.length || preloaded || haveEnoughBuffer) {
  14218. return null;
  14219. }
  14220. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  14221. const next = {
  14222. partIndex: null,
  14223. mediaIndex: null,
  14224. startOfSegment: null,
  14225. playlist: this.playlist_,
  14226. isSyncRequest: Boolean(!this.syncPoint_)
  14227. };
  14228. if (next.isSyncRequest) {
  14229. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  14230. } else if (this.mediaIndex !== null) {
  14231. const segment = segments[this.mediaIndex];
  14232. const partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  14233. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  14234. if (segment.parts && segment.parts[partIndex + 1]) {
  14235. next.mediaIndex = this.mediaIndex;
  14236. next.partIndex = partIndex + 1;
  14237. } else {
  14238. next.mediaIndex = this.mediaIndex + 1;
  14239. }
  14240. } else {
  14241. // Find the segment containing the end of the buffer or current time.
  14242. const {
  14243. segmentIndex,
  14244. startTime,
  14245. partIndex
  14246. } = Playlist.getMediaInfoForTime({
  14247. exactManifestTimings: this.exactManifestTimings,
  14248. playlist: this.playlist_,
  14249. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  14250. startingPartIndex: this.syncPoint_.partIndex,
  14251. startingSegmentIndex: this.syncPoint_.segmentIndex,
  14252. startTime: this.syncPoint_.time
  14253. });
  14254. next.getMediaInfoForTime = this.fetchAtBuffer_ ? `bufferedEnd ${bufferedEnd}` : `currentTime ${this.currentTime_()}`;
  14255. next.mediaIndex = segmentIndex;
  14256. next.startOfSegment = startTime;
  14257. next.partIndex = partIndex;
  14258. }
  14259. const nextSegment = segments[next.mediaIndex];
  14260. let nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  14261. // the next partIndex is invalid do not choose a next segment.
  14262. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  14263. return null;
  14264. } // if the next segment has parts, and we don't have a partIndex.
  14265. // Set partIndex to 0
  14266. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  14267. next.partIndex = 0;
  14268. nextPart = nextSegment.parts[0];
  14269. } // if we have no buffered data then we need to make sure
  14270. // that the next part we append is "independent" if possible.
  14271. // So we check if the previous part is independent, and request
  14272. // it if it is.
  14273. if (!bufferedTime && nextPart && !nextPart.independent) {
  14274. if (next.partIndex === 0) {
  14275. const lastSegment = segments[next.mediaIndex - 1];
  14276. const lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  14277. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  14278. next.mediaIndex -= 1;
  14279. next.partIndex = lastSegment.parts.length - 1;
  14280. next.independent = 'previous segment';
  14281. }
  14282. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  14283. next.partIndex -= 1;
  14284. next.independent = 'previous part';
  14285. }
  14286. }
  14287. const ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  14288. // 1. this is the last segment in the playlist
  14289. // 2. end of stream has been called on the media source already
  14290. // 3. the player is not seeking
  14291. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  14292. return null;
  14293. }
  14294. return this.generateSegmentInfo_(next);
  14295. }
  14296. generateSegmentInfo_(options) {
  14297. const {
  14298. independent,
  14299. playlist,
  14300. mediaIndex,
  14301. startOfSegment,
  14302. isSyncRequest,
  14303. partIndex,
  14304. forceTimestampOffset,
  14305. getMediaInfoForTime
  14306. } = options;
  14307. const segment = playlist.segments[mediaIndex];
  14308. const part = typeof partIndex === 'number' && segment.parts[partIndex];
  14309. const segmentInfo = {
  14310. requestId: 'segment-loader-' + Math.random(),
  14311. // resolve the segment URL relative to the playlist
  14312. uri: part && part.resolvedUri || segment.resolvedUri,
  14313. // the segment's mediaIndex at the time it was requested
  14314. mediaIndex,
  14315. partIndex: part ? partIndex : null,
  14316. // whether or not to update the SegmentLoader's state with this
  14317. // segment's mediaIndex
  14318. isSyncRequest,
  14319. startOfSegment,
  14320. // the segment's playlist
  14321. playlist,
  14322. // unencrypted bytes of the segment
  14323. bytes: null,
  14324. // when a key is defined for this segment, the encrypted bytes
  14325. encryptedBytes: null,
  14326. // The target timestampOffset for this segment when we append it
  14327. // to the source buffer
  14328. timestampOffset: null,
  14329. // The timeline that the segment is in
  14330. timeline: segment.timeline,
  14331. // The expected duration of the segment in seconds
  14332. duration: part && part.duration || segment.duration,
  14333. // retain the segment in case the playlist updates while doing an async process
  14334. segment,
  14335. part,
  14336. byteLength: 0,
  14337. transmuxer: this.transmuxer_,
  14338. // type of getMediaInfoForTime that was used to get this segment
  14339. getMediaInfoForTime,
  14340. independent
  14341. };
  14342. const overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  14343. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  14344. segmentTimeline: segment.timeline,
  14345. currentTimeline: this.currentTimeline_,
  14346. startOfSegment,
  14347. buffered: this.buffered_(),
  14348. overrideCheck
  14349. });
  14350. const audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  14351. if (typeof audioBufferedEnd === 'number') {
  14352. // since the transmuxer is using the actual timing values, but the buffer is
  14353. // adjusted by the timestamp offset, we must adjust the value here
  14354. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  14355. }
  14356. if (this.sourceUpdater_.videoBuffered().length) {
  14357. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  14358. // adjusted by the timestmap offset, we must adjust the value here
  14359. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  14360. }
  14361. return segmentInfo;
  14362. } // get the timestampoffset for a segment,
  14363. // added so that vtt segment loader can override and prevent
  14364. // adding timestamp offsets.
  14365. timestampOffsetForSegment_(options) {
  14366. return timestampOffsetForSegment(options);
  14367. }
  14368. /**
  14369. * Determines if the network has enough bandwidth to complete the current segment
  14370. * request in a timely manner. If not, the request will be aborted early and bandwidth
  14371. * updated to trigger a playlist switch.
  14372. *
  14373. * @param {Object} stats
  14374. * Object containing stats about the request timing and size
  14375. * @private
  14376. */
  14377. earlyAbortWhenNeeded_(stats) {
  14378. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  14379. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  14380. // the lowestEnabledRendition.
  14381. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  14382. !this.playlist_.attributes.BANDWIDTH) {
  14383. return;
  14384. } // Wait at least 1 second since the first byte of data has been received before
  14385. // using the calculated bandwidth from the progress event to allow the bitrate
  14386. // to stabilize
  14387. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  14388. return;
  14389. }
  14390. const currentTime = this.currentTime_();
  14391. const measuredBandwidth = stats.bandwidth;
  14392. const segmentDuration = this.pendingSegment_.duration;
  14393. const requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  14394. // if we are only left with less than 1 second when the request completes.
  14395. // A negative timeUntilRebuffering indicates we are already rebuffering
  14396. const timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  14397. // is larger than the estimated time until the player runs out of forward buffer
  14398. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  14399. return;
  14400. }
  14401. const switchCandidate = minRebufferMaxBandwidthSelector({
  14402. main: this.vhs_.playlists.main,
  14403. currentTime,
  14404. bandwidth: measuredBandwidth,
  14405. duration: this.duration_(),
  14406. segmentDuration,
  14407. timeUntilRebuffer: timeUntilRebuffer$1,
  14408. currentTimeline: this.currentTimeline_,
  14409. syncController: this.syncController_
  14410. });
  14411. if (!switchCandidate) {
  14412. return;
  14413. }
  14414. const rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  14415. const timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  14416. let minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  14417. // potential round trip time of the new request so that we are not too aggressive
  14418. // with switching to a playlist that might save us a fraction of a second.
  14419. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  14420. minimumTimeSaving = 1;
  14421. }
  14422. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  14423. return;
  14424. } // set the bandwidth to that of the desired playlist being sure to scale by
  14425. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  14426. // don't trigger a bandwidthupdate as the bandwidth is artifial
  14427. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  14428. this.trigger('earlyabort');
  14429. }
  14430. handleAbort_(segmentInfo) {
  14431. this.logger_(`Aborting ${segmentInfoString(segmentInfo)}`);
  14432. this.mediaRequestsAborted += 1;
  14433. }
  14434. /**
  14435. * XHR `progress` event handler
  14436. *
  14437. * @param {Event}
  14438. * The XHR `progress` event
  14439. * @param {Object} simpleSegment
  14440. * A simplified segment object copy
  14441. * @private
  14442. */
  14443. handleProgress_(event, simpleSegment) {
  14444. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14445. if (this.checkForAbort_(simpleSegment.requestId)) {
  14446. return;
  14447. }
  14448. this.trigger('progress');
  14449. }
  14450. handleTrackInfo_(simpleSegment, trackInfo) {
  14451. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14452. if (this.checkForAbort_(simpleSegment.requestId)) {
  14453. return;
  14454. }
  14455. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  14456. return;
  14457. }
  14458. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  14459. // Guard against cases where we're not getting track info at all until we are
  14460. // certain that all streams will provide it.
  14461. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  14462. this.appendInitSegment_ = {
  14463. audio: true,
  14464. video: true
  14465. };
  14466. this.startingMediaInfo_ = trackInfo;
  14467. this.currentMediaInfo_ = trackInfo;
  14468. this.logger_('trackinfo update', trackInfo);
  14469. this.trigger('trackinfo');
  14470. } // trackinfo may cause an abort if the trackinfo
  14471. // causes a codec change to an unsupported codec.
  14472. if (this.checkForAbort_(simpleSegment.requestId)) {
  14473. return;
  14474. } // set trackinfo on the pending segment so that
  14475. // it can append.
  14476. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  14477. if (this.hasEnoughInfoToAppend_()) {
  14478. this.processCallQueue_();
  14479. }
  14480. }
  14481. handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  14482. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14483. if (this.checkForAbort_(simpleSegment.requestId)) {
  14484. return;
  14485. }
  14486. const segmentInfo = this.pendingSegment_;
  14487. const timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  14488. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  14489. segmentInfo[timingInfoProperty][timeType] = time;
  14490. this.logger_(`timinginfo: ${mediaType} - ${timeType} - ${time}`); // check if any calls were waiting on the timing info
  14491. if (this.hasEnoughInfoToAppend_()) {
  14492. this.processCallQueue_();
  14493. }
  14494. }
  14495. handleCaptions_(simpleSegment, captionData) {
  14496. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14497. if (this.checkForAbort_(simpleSegment.requestId)) {
  14498. return;
  14499. } // This could only happen with fmp4 segments, but
  14500. // should still not happen in general
  14501. if (captionData.length === 0) {
  14502. this.logger_('SegmentLoader received no captions from a caption event');
  14503. return;
  14504. }
  14505. const segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  14506. // can be adjusted by the timestamp offset
  14507. if (!segmentInfo.hasAppendedData_) {
  14508. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  14509. return;
  14510. }
  14511. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  14512. const captionTracks = {}; // get total start/end and captions for each track/stream
  14513. captionData.forEach(caption => {
  14514. // caption.stream is actually a track name...
  14515. // set to the existing values in tracks or default values
  14516. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  14517. // Infinity, as any other value will be less than this
  14518. startTime: Infinity,
  14519. captions: [],
  14520. // 0 as an other value will be more than this
  14521. endTime: 0
  14522. };
  14523. const captionTrack = captionTracks[caption.stream];
  14524. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  14525. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  14526. captionTrack.captions.push(caption);
  14527. });
  14528. Object.keys(captionTracks).forEach(trackName => {
  14529. const {
  14530. startTime,
  14531. endTime,
  14532. captions
  14533. } = captionTracks[trackName];
  14534. const inbandTextTracks = this.inbandTextTracks_;
  14535. this.logger_(`adding cues from ${startTime} -> ${endTime} for ${trackName}`);
  14536. createCaptionsTrackIfNotExists(inbandTextTracks, this.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  14537. // We do this because a rendition change that also changes the timescale for captions
  14538. // will result in captions being re-parsed for certain segments. If we add them again
  14539. // without clearing we will have two of the same captions visible.
  14540. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  14541. addCaptionData({
  14542. captionArray: captions,
  14543. inbandTextTracks,
  14544. timestampOffset
  14545. });
  14546. }); // Reset stored captions since we added parsed
  14547. // captions to a text track at this point
  14548. if (this.transmuxer_) {
  14549. this.transmuxer_.postMessage({
  14550. action: 'clearParsedMp4Captions'
  14551. });
  14552. }
  14553. }
  14554. handleId3_(simpleSegment, id3Frames, dispatchType) {
  14555. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14556. if (this.checkForAbort_(simpleSegment.requestId)) {
  14557. return;
  14558. }
  14559. const segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  14560. if (!segmentInfo.hasAppendedData_) {
  14561. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  14562. return;
  14563. }
  14564. const timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  14565. // audio/video source with a metadata track, and an alt audio with a metadata track.
  14566. // However, this probably won't happen, and if it does it can be handled then.
  14567. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  14568. addMetadata({
  14569. inbandTextTracks: this.inbandTextTracks_,
  14570. metadataArray: id3Frames,
  14571. timestampOffset,
  14572. videoDuration: this.duration_()
  14573. });
  14574. }
  14575. processMetadataQueue_() {
  14576. this.metadataQueue_.id3.forEach(fn => fn());
  14577. this.metadataQueue_.caption.forEach(fn => fn());
  14578. this.metadataQueue_.id3 = [];
  14579. this.metadataQueue_.caption = [];
  14580. }
  14581. processCallQueue_() {
  14582. const callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  14583. // functions may check the length of the load queue and default to pushing themselves
  14584. // back onto the queue.
  14585. this.callQueue_ = [];
  14586. callQueue.forEach(fun => fun());
  14587. }
  14588. processLoadQueue_() {
  14589. const loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  14590. // functions may check the length of the load queue and default to pushing themselves
  14591. // back onto the queue.
  14592. this.loadQueue_ = [];
  14593. loadQueue.forEach(fun => fun());
  14594. }
  14595. /**
  14596. * Determines whether the loader has enough info to load the next segment.
  14597. *
  14598. * @return {boolean}
  14599. * Whether or not the loader has enough info to load the next segment
  14600. */
  14601. hasEnoughInfoToLoad_() {
  14602. // Since primary timing goes by video, only the audio loader potentially needs to wait
  14603. // to load.
  14604. if (this.loaderType_ !== 'audio') {
  14605. return true;
  14606. }
  14607. const segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  14608. // enough info to load.
  14609. if (!segmentInfo) {
  14610. return false;
  14611. } // The first segment can and should be loaded immediately so that source buffers are
  14612. // created together (before appending). Source buffer creation uses the presence of
  14613. // audio and video data to determine whether to create audio/video source buffers, and
  14614. // uses processed (transmuxed or parsed) media to determine the types required.
  14615. if (!this.getCurrentMediaInfo_()) {
  14616. return true;
  14617. }
  14618. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  14619. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  14620. // But in practice, there are a few reasons why it is better to wait until a loader
  14621. // is ready to append that segment before requesting and downloading:
  14622. //
  14623. // 1. Because audio and main loaders cross discontinuities together, if this loader
  14624. // is waiting for the other to catch up, then instead of requesting another
  14625. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  14626. // allotted to the loader currently behind.
  14627. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  14628. // is ready to be processed or not, isolating the queueing behavior to the loader.
  14629. // 3. The audio loader bases some of its segment properties on timing information
  14630. // provided by the main loader, meaning that, if the logic for waiting on
  14631. // processing was in media-segment-request, then it would also need to know how
  14632. // to re-generate the segment information after the main loader caught up.
  14633. shouldWaitForTimelineChange({
  14634. timelineChangeController: this.timelineChangeController_,
  14635. currentTimeline: this.currentTimeline_,
  14636. segmentTimeline: segmentInfo.timeline,
  14637. loaderType: this.loaderType_,
  14638. audioDisabled: this.audioDisabled_
  14639. })) {
  14640. return false;
  14641. }
  14642. return true;
  14643. }
  14644. getCurrentMediaInfo_(segmentInfo = this.pendingSegment_) {
  14645. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  14646. }
  14647. getMediaInfo_(segmentInfo = this.pendingSegment_) {
  14648. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  14649. }
  14650. getPendingSegmentPlaylist() {
  14651. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  14652. }
  14653. hasEnoughInfoToAppend_() {
  14654. if (!this.sourceUpdater_.ready()) {
  14655. return false;
  14656. } // If content needs to be removed or the loader is waiting on an append reattempt,
  14657. // then no additional content should be appended until the prior append is resolved.
  14658. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  14659. return false;
  14660. }
  14661. const segmentInfo = this.pendingSegment_;
  14662. const trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  14663. // we do not have information on this specific
  14664. // segment yet
  14665. if (!segmentInfo || !trackInfo) {
  14666. return false;
  14667. }
  14668. const {
  14669. hasAudio,
  14670. hasVideo,
  14671. isMuxed
  14672. } = trackInfo;
  14673. if (hasVideo && !segmentInfo.videoTimingInfo) {
  14674. return false;
  14675. } // muxed content only relies on video timing information for now.
  14676. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  14677. return false;
  14678. }
  14679. if (shouldWaitForTimelineChange({
  14680. timelineChangeController: this.timelineChangeController_,
  14681. currentTimeline: this.currentTimeline_,
  14682. segmentTimeline: segmentInfo.timeline,
  14683. loaderType: this.loaderType_,
  14684. audioDisabled: this.audioDisabled_
  14685. })) {
  14686. return false;
  14687. }
  14688. return true;
  14689. }
  14690. handleData_(simpleSegment, result) {
  14691. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  14692. if (this.checkForAbort_(simpleSegment.requestId)) {
  14693. return;
  14694. } // If there's anything in the call queue, then this data came later and should be
  14695. // executed after the calls currently queued.
  14696. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  14697. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  14698. return;
  14699. }
  14700. const segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  14701. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  14702. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  14703. // logic may change behavior depending on the state, and changing state too early may
  14704. // inflate our estimates of bandwidth. In the future this should be re-examined to
  14705. // note more granular states.
  14706. // don't process and append data if the mediaSource is closed
  14707. if (this.mediaSource_.readyState === 'closed') {
  14708. return;
  14709. } // if this request included an initialization segment, save that data
  14710. // to the initSegment cache
  14711. if (simpleSegment.map) {
  14712. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  14713. segmentInfo.segment.map = simpleSegment.map;
  14714. } // if this request included a segment key, save that data in the cache
  14715. if (simpleSegment.key) {
  14716. this.segmentKey(simpleSegment.key, true);
  14717. }
  14718. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  14719. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  14720. if (segmentInfo.isFmp4) {
  14721. this.trigger('fmp4');
  14722. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  14723. } else {
  14724. const trackInfo = this.getCurrentMediaInfo_();
  14725. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  14726. let firstVideoFrameTimeForData;
  14727. if (useVideoTimingInfo) {
  14728. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  14729. } // Segment loader knows more about segment timing than the transmuxer (in certain
  14730. // aspects), so make any changes required for a more accurate start time.
  14731. // Don't set the end time yet, as the segment may not be finished processing.
  14732. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  14733. currentStart: segmentInfo.timingInfo.start,
  14734. playlist: segmentInfo.playlist,
  14735. mediaIndex: segmentInfo.mediaIndex,
  14736. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  14737. useVideoTimingInfo,
  14738. firstVideoFrameTimeForData,
  14739. videoTimingInfo: segmentInfo.videoTimingInfo,
  14740. audioTimingInfo: segmentInfo.audioTimingInfo
  14741. });
  14742. } // Init segments for audio and video only need to be appended in certain cases. Now
  14743. // that data is about to be appended, we can check the final cases to determine
  14744. // whether we should append an init segment.
  14745. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  14746. // as we use the start of the segment to offset the best guess (playlist provided)
  14747. // timestamp offset.
  14748. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  14749. // be appended or not.
  14750. if (segmentInfo.isSyncRequest) {
  14751. // first save/update our timing info for this segment.
  14752. // this is what allows us to choose an accurate segment
  14753. // and the main reason we make a sync request.
  14754. this.updateTimingInfoEnd_(segmentInfo);
  14755. this.syncController_.saveSegmentTimingInfo({
  14756. segmentInfo,
  14757. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  14758. });
  14759. const next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  14760. // after taking into account its timing info, do not append it.
  14761. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  14762. this.logger_('sync segment was incorrect, not appending');
  14763. return;
  14764. } // otherwise append it like any other segment as our guess was correct.
  14765. this.logger_('sync segment was correct, appending');
  14766. } // Save some state so that in the future anything waiting on first append (and/or
  14767. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  14768. // we need some notion of whether the timestamp offset or other relevant information
  14769. // has had a chance to be set.
  14770. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  14771. this.processMetadataQueue_();
  14772. this.appendData_(segmentInfo, result);
  14773. }
  14774. updateAppendInitSegmentStatus(segmentInfo, type) {
  14775. // alt audio doesn't manage timestamp offset
  14776. 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
  14777. // segment for each chunk
  14778. !segmentInfo.changedTimestampOffset) {
  14779. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  14780. // append init segments
  14781. this.appendInitSegment_ = {
  14782. audio: true,
  14783. video: true
  14784. };
  14785. }
  14786. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  14787. // make sure we append init segment on playlist changes, in case the media config
  14788. // changed
  14789. this.appendInitSegment_[type] = true;
  14790. }
  14791. }
  14792. getInitSegmentAndUpdateState_({
  14793. type,
  14794. initSegment,
  14795. map,
  14796. playlist
  14797. }) {
  14798. // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  14799. // (Section 3) required to parse the applicable Media Segments. It applies to every
  14800. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  14801. // or until the end of the playlist."
  14802. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  14803. if (map) {
  14804. const id = initSegmentId(map);
  14805. if (this.activeInitSegmentId_ === id) {
  14806. // don't need to re-append the init segment if the ID matches
  14807. return null;
  14808. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  14809. // obtained) init segment
  14810. //
  14811. // this also caches the init segment for later use
  14812. initSegment = this.initSegmentForMap(map, true).bytes;
  14813. this.activeInitSegmentId_ = id;
  14814. } // We used to always prepend init segments for video, however, that shouldn't be
  14815. // necessary. Instead, we should only append on changes, similar to what we've always
  14816. // done for audio. This is more important (though may not be that important) for
  14817. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  14818. // appends.
  14819. if (initSegment && this.appendInitSegment_[type]) {
  14820. // Make sure we track the playlist that we last used for the init segment, so that
  14821. // we can re-append the init segment in the event that we get data from a new
  14822. // playlist. Discontinuities and track changes are handled in other sections.
  14823. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  14824. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  14825. // we are appending the muxer init segment
  14826. this.activeInitSegmentId_ = null;
  14827. return initSegment;
  14828. }
  14829. return null;
  14830. }
  14831. handleQuotaExceededError_({
  14832. segmentInfo,
  14833. type,
  14834. bytes
  14835. }, error) {
  14836. const audioBuffered = this.sourceUpdater_.audioBuffered();
  14837. const videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  14838. // should be cleared out during the buffer removals. However, log in case it helps
  14839. // debug.
  14840. if (audioBuffered.length > 1) {
  14841. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  14842. }
  14843. if (videoBuffered.length > 1) {
  14844. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  14845. }
  14846. const audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  14847. const audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  14848. const videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  14849. const videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  14850. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  14851. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  14852. // allow for appends of segments this size). In the future, it may be possible to
  14853. // split up the segment and append in pieces, but for now, error out this playlist
  14854. // in an attempt to switch to a more manageable rendition.
  14855. 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(', ')}, `);
  14856. this.error({
  14857. message: 'Quota exceeded error with append of a single segment of content',
  14858. excludeUntil: Infinity
  14859. });
  14860. this.trigger('error');
  14861. return;
  14862. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  14863. // that the segment-loader should block on future events until this one is handled, so
  14864. // that it doesn't keep moving onto further segments. Adding the call to the call
  14865. // queue will prevent further appends until waitingOnRemove_ and
  14866. // quotaExceededErrorRetryTimeout_ are cleared.
  14867. //
  14868. // Note that this will only block the current loader. In the case of demuxed content,
  14869. // the other load may keep filling as fast as possible. In practice, this should be
  14870. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  14871. // source buffer, or video fills without enough room for audio to append (and without
  14872. // the availability of clearing out seconds of back buffer to make room for audio).
  14873. // But it might still be good to handle this case in the future as a TODO.
  14874. this.waitingOnRemove_ = true;
  14875. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  14876. segmentInfo,
  14877. type,
  14878. bytes
  14879. }));
  14880. const currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  14881. // before retrying.
  14882. const timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  14883. this.logger_(`On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to ${timeToRemoveUntil}`);
  14884. this.remove(0, timeToRemoveUntil, () => {
  14885. this.logger_(`On QUOTA_EXCEEDED_ERR, retrying append in ${MIN_BACK_BUFFER}s`);
  14886. this.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  14887. // attempts (since we can't clear less than the minimum)
  14888. this.quotaExceededErrorRetryTimeout_ = window__default["default"].setTimeout(() => {
  14889. this.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  14890. this.quotaExceededErrorRetryTimeout_ = null;
  14891. this.processCallQueue_();
  14892. }, MIN_BACK_BUFFER * 1000);
  14893. }, true);
  14894. }
  14895. handleAppendError_({
  14896. segmentInfo,
  14897. type,
  14898. bytes
  14899. }, error) {
  14900. // if there's no error, nothing to do
  14901. if (!error) {
  14902. return;
  14903. }
  14904. if (error.code === QUOTA_EXCEEDED_ERR) {
  14905. this.handleQuotaExceededError_({
  14906. segmentInfo,
  14907. type,
  14908. bytes
  14909. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  14910. // to trigger an append error.
  14911. return;
  14912. }
  14913. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  14914. 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.
  14915. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  14916. //
  14917. // Trigger a special error so that it can be handled separately from normal,
  14918. // recoverable errors.
  14919. this.trigger('appenderror');
  14920. }
  14921. appendToSourceBuffer_({
  14922. segmentInfo,
  14923. type,
  14924. initSegment,
  14925. data,
  14926. bytes
  14927. }) {
  14928. // If this is a re-append, bytes were already created and don't need to be recreated
  14929. if (!bytes) {
  14930. const segments = [data];
  14931. let byteLength = data.byteLength;
  14932. if (initSegment) {
  14933. // if the media initialization segment is changing, append it before the content
  14934. // segment
  14935. segments.unshift(initSegment);
  14936. byteLength += initSegment.byteLength;
  14937. } // Technically we should be OK appending the init segment separately, however, we
  14938. // haven't yet tested that, and prepending is how we have always done things.
  14939. bytes = concatSegments({
  14940. bytes: byteLength,
  14941. segments
  14942. });
  14943. }
  14944. this.sourceUpdater_.appendBuffer({
  14945. segmentInfo,
  14946. type,
  14947. bytes
  14948. }, this.handleAppendError_.bind(this, {
  14949. segmentInfo,
  14950. type,
  14951. bytes
  14952. }));
  14953. }
  14954. handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  14955. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  14956. return;
  14957. }
  14958. const segment = this.pendingSegment_.segment;
  14959. const timingInfoProperty = `${type}TimingInfo`;
  14960. if (!segment[timingInfoProperty]) {
  14961. segment[timingInfoProperty] = {};
  14962. }
  14963. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  14964. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  14965. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  14966. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  14967. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  14968. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  14969. }
  14970. appendData_(segmentInfo, result) {
  14971. const {
  14972. type,
  14973. data
  14974. } = result;
  14975. if (!data || !data.byteLength) {
  14976. return;
  14977. }
  14978. if (type === 'audio' && this.audioDisabled_) {
  14979. return;
  14980. }
  14981. const initSegment = this.getInitSegmentAndUpdateState_({
  14982. type,
  14983. initSegment: result.initSegment,
  14984. playlist: segmentInfo.playlist,
  14985. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  14986. });
  14987. this.appendToSourceBuffer_({
  14988. segmentInfo,
  14989. type,
  14990. initSegment,
  14991. data
  14992. });
  14993. }
  14994. /**
  14995. * load a specific segment from a request into the buffer
  14996. *
  14997. * @private
  14998. */
  14999. loadSegment_(segmentInfo) {
  15000. this.state = 'WAITING';
  15001. this.pendingSegment_ = segmentInfo;
  15002. this.trimBackBuffer_(segmentInfo);
  15003. if (typeof segmentInfo.timestampOffset === 'number') {
  15004. if (this.transmuxer_) {
  15005. this.transmuxer_.postMessage({
  15006. action: 'clearAllMp4Captions'
  15007. });
  15008. }
  15009. }
  15010. if (!this.hasEnoughInfoToLoad_()) {
  15011. this.loadQueue_.push(() => {
  15012. // regenerate the audioAppendStart, timestampOffset, etc as they
  15013. // may have changed since this function was added to the queue.
  15014. const options = _extends__default["default"]({}, segmentInfo, {
  15015. forceTimestampOffset: true
  15016. });
  15017. _extends__default["default"](segmentInfo, this.generateSegmentInfo_(options));
  15018. this.isPendingTimestampOffset_ = false;
  15019. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15020. });
  15021. return;
  15022. }
  15023. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  15024. }
  15025. updateTransmuxerAndRequestSegment_(segmentInfo) {
  15026. // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  15027. // the transmuxer still needs to be updated before then.
  15028. //
  15029. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  15030. // offset must be passed to the transmuxer for stream correcting adjustments.
  15031. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  15032. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  15033. segmentInfo.gopsToAlignWith = [];
  15034. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  15035. this.transmuxer_.postMessage({
  15036. action: 'reset'
  15037. });
  15038. this.transmuxer_.postMessage({
  15039. action: 'setTimestampOffset',
  15040. timestampOffset: segmentInfo.timestampOffset
  15041. });
  15042. }
  15043. const simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  15044. const isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  15045. const isWalkingForward = this.mediaIndex !== null;
  15046. const isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  15047. // the first timeline
  15048. segmentInfo.timeline > 0;
  15049. const isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  15050. 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),
  15051. // then this init segment has never been seen before and should be appended.
  15052. //
  15053. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  15054. // both to true and leave the decision of whether to append the init segment to append time.
  15055. if (simpleSegment.map && !simpleSegment.map.bytes) {
  15056. this.logger_('going to request init segment.');
  15057. this.appendInitSegment_ = {
  15058. video: true,
  15059. audio: true
  15060. };
  15061. }
  15062. segmentInfo.abortRequests = mediaSegmentRequest({
  15063. xhr: this.vhs_.xhr,
  15064. xhrOptions: this.xhrOptions_,
  15065. decryptionWorker: this.decrypter_,
  15066. segment: simpleSegment,
  15067. abortFn: this.handleAbort_.bind(this, segmentInfo),
  15068. progressFn: this.handleProgress_.bind(this),
  15069. trackInfoFn: this.handleTrackInfo_.bind(this),
  15070. timingInfoFn: this.handleTimingInfo_.bind(this),
  15071. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  15072. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  15073. captionsFn: this.handleCaptions_.bind(this),
  15074. isEndOfTimeline,
  15075. endedTimelineFn: () => {
  15076. this.logger_('received endedtimeline callback');
  15077. },
  15078. id3Fn: this.handleId3_.bind(this),
  15079. dataFn: this.handleData_.bind(this),
  15080. doneFn: this.segmentRequestFinished_.bind(this),
  15081. onTransmuxerLog: ({
  15082. message,
  15083. level,
  15084. stream
  15085. }) => {
  15086. this.logger_(`${segmentInfoString(segmentInfo)} logged from transmuxer stream ${stream} as a ${level}: ${message}`);
  15087. }
  15088. });
  15089. }
  15090. /**
  15091. * trim the back buffer so that we don't have too much data
  15092. * in the source buffer
  15093. *
  15094. * @private
  15095. *
  15096. * @param {Object} segmentInfo - the current segment
  15097. */
  15098. trimBackBuffer_(segmentInfo) {
  15099. const removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  15100. // buffer and a very conservative "garbage collector"
  15101. // We manually clear out the old buffer to ensure
  15102. // we don't trigger the QuotaExceeded error
  15103. // on the source buffer during subsequent appends
  15104. if (removeToTime > 0) {
  15105. this.remove(0, removeToTime);
  15106. }
  15107. }
  15108. /**
  15109. * created a simplified copy of the segment object with just the
  15110. * information necessary to perform the XHR and decryption
  15111. *
  15112. * @private
  15113. *
  15114. * @param {Object} segmentInfo - the current segment
  15115. * @return {Object} a simplified segment object copy
  15116. */
  15117. createSimplifiedSegmentObj_(segmentInfo) {
  15118. const segment = segmentInfo.segment;
  15119. const part = segmentInfo.part;
  15120. const simpleSegment = {
  15121. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  15122. byterange: part ? part.byterange : segment.byterange,
  15123. requestId: segmentInfo.requestId,
  15124. transmuxer: segmentInfo.transmuxer,
  15125. audioAppendStart: segmentInfo.audioAppendStart,
  15126. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  15127. part: segmentInfo.part
  15128. };
  15129. const previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  15130. if (previousSegment && previousSegment.timeline === segment.timeline) {
  15131. // The baseStartTime of a segment is used to handle rollover when probing the TS
  15132. // segment to retrieve timing information. Since the probe only looks at the media's
  15133. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  15134. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  15135. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  15136. // seconds of media time, so should be used here. The previous segment is used since
  15137. // the end of the previous segment should represent the beginning of the current
  15138. // segment, so long as they are on the same timeline.
  15139. if (previousSegment.videoTimingInfo) {
  15140. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  15141. } else if (previousSegment.audioTimingInfo) {
  15142. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  15143. }
  15144. }
  15145. if (segment.key) {
  15146. // if the media sequence is greater than 2^32, the IV will be incorrect
  15147. // assuming 10s segments, that would be about 1300 years
  15148. const iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  15149. simpleSegment.key = this.segmentKey(segment.key);
  15150. simpleSegment.key.iv = iv;
  15151. }
  15152. if (segment.map) {
  15153. simpleSegment.map = this.initSegmentForMap(segment.map);
  15154. }
  15155. return simpleSegment;
  15156. }
  15157. saveTransferStats_(stats) {
  15158. // every request counts as a media request even if it has been aborted
  15159. // or canceled due to a timeout
  15160. this.mediaRequests += 1;
  15161. if (stats) {
  15162. this.mediaBytesTransferred += stats.bytesReceived;
  15163. this.mediaTransferDuration += stats.roundTripTime;
  15164. }
  15165. }
  15166. saveBandwidthRelatedStats_(duration, stats) {
  15167. // byteLength will be used for throughput, and should be based on bytes receieved,
  15168. // which we only know at the end of the request and should reflect total bytes
  15169. // downloaded rather than just bytes processed from components of the segment
  15170. this.pendingSegment_.byteLength = stats.bytesReceived;
  15171. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  15172. this.logger_(`Ignoring segment's bandwidth because its duration of ${duration}` + ` is less than the min to record ${MIN_SEGMENT_DURATION_TO_SAVE_STATS}`);
  15173. return;
  15174. }
  15175. this.bandwidth = stats.bandwidth;
  15176. this.roundTrip = stats.roundTripTime;
  15177. }
  15178. handleTimeout_() {
  15179. // although the VTT segment loader bandwidth isn't really used, it's good to
  15180. // maintain functinality between segment loaders
  15181. this.mediaRequestsTimedout += 1;
  15182. this.bandwidth = 1;
  15183. this.roundTrip = NaN;
  15184. this.trigger('bandwidthupdate');
  15185. this.trigger('timeout');
  15186. }
  15187. /**
  15188. * Handle the callback from the segmentRequest function and set the
  15189. * associated SegmentLoader state and errors if necessary
  15190. *
  15191. * @private
  15192. */
  15193. segmentRequestFinished_(error, simpleSegment, result) {
  15194. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  15195. // check the call queue directly since this function doesn't need to deal with any
  15196. // data, and can continue even if the source buffers are not set up and we didn't get
  15197. // any data from the segment
  15198. if (this.callQueue_.length) {
  15199. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  15200. return;
  15201. }
  15202. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  15203. if (!this.pendingSegment_) {
  15204. return;
  15205. } // the request was aborted and the SegmentLoader has already started
  15206. // another request. this can happen when the timeout for an aborted
  15207. // request triggers due to a limitation in the XHR library
  15208. // do not count this as any sort of request or we risk double-counting
  15209. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  15210. return;
  15211. } // an error occurred from the active pendingSegment_ so reset everything
  15212. if (error) {
  15213. this.pendingSegment_ = null;
  15214. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  15215. if (error.code === REQUEST_ERRORS.ABORTED) {
  15216. return;
  15217. }
  15218. this.pause(); // the error is really just that at least one of the requests timed-out
  15219. // set the bandwidth to a very low value and trigger an ABR switch to
  15220. // take emergency action
  15221. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  15222. this.handleTimeout_();
  15223. return;
  15224. } // if control-flow has arrived here, then the error is real
  15225. // emit an error event to exclude the current playlist
  15226. this.mediaRequestsErrored += 1;
  15227. this.error(error);
  15228. this.trigger('error');
  15229. return;
  15230. }
  15231. const segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  15232. // generated for ABR purposes
  15233. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  15234. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  15235. if (result.gopInfo) {
  15236. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  15237. } // Although we may have already started appending on progress, we shouldn't switch the
  15238. // state away from loading until we are officially done loading the segment data.
  15239. this.state = 'APPENDING'; // used for testing
  15240. this.trigger('appending');
  15241. this.waitForAppendsToComplete_(segmentInfo);
  15242. }
  15243. setTimeMapping_(timeline) {
  15244. const timelineMapping = this.syncController_.mappingForTimeline(timeline);
  15245. if (timelineMapping !== null) {
  15246. this.timeMapping_ = timelineMapping;
  15247. }
  15248. }
  15249. updateMediaSecondsLoaded_(segment) {
  15250. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  15251. this.mediaSecondsLoaded += segment.end - segment.start;
  15252. } else {
  15253. this.mediaSecondsLoaded += segment.duration;
  15254. }
  15255. }
  15256. shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  15257. if (timestampOffset === null) {
  15258. return false;
  15259. } // note that we're potentially using the same timestamp offset for both video and
  15260. // audio
  15261. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15262. return true;
  15263. }
  15264. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15265. return true;
  15266. }
  15267. return false;
  15268. }
  15269. trueSegmentStart_({
  15270. currentStart,
  15271. playlist,
  15272. mediaIndex,
  15273. firstVideoFrameTimeForData,
  15274. currentVideoTimestampOffset,
  15275. useVideoTimingInfo,
  15276. videoTimingInfo,
  15277. audioTimingInfo
  15278. }) {
  15279. if (typeof currentStart !== 'undefined') {
  15280. // if start was set once, keep using it
  15281. return currentStart;
  15282. }
  15283. if (!useVideoTimingInfo) {
  15284. return audioTimingInfo.start;
  15285. }
  15286. const previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  15287. // within that segment. Since the transmuxer maintains a cache of incomplete data
  15288. // from and/or the last frame seen, the start time may reflect a frame that starts
  15289. // in the previous segment. Check for that case and ensure the start time is
  15290. // accurate for the segment.
  15291. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  15292. return firstVideoFrameTimeForData;
  15293. }
  15294. return videoTimingInfo.start;
  15295. }
  15296. waitForAppendsToComplete_(segmentInfo) {
  15297. const trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  15298. if (!trackInfo) {
  15299. this.error({
  15300. message: 'No starting media returned, likely due to an unsupported media format.',
  15301. playlistExclusionDuration: Infinity
  15302. });
  15303. this.trigger('error');
  15304. return;
  15305. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  15306. // on each queue this loader is responsible for to ensure that the appends are
  15307. // complete.
  15308. const {
  15309. hasAudio,
  15310. hasVideo,
  15311. isMuxed
  15312. } = trackInfo;
  15313. const waitForVideo = this.loaderType_ === 'main' && hasVideo;
  15314. const waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  15315. segmentInfo.waitingOnAppends = 0; // segments with no data
  15316. if (!segmentInfo.hasAppendedData_) {
  15317. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  15318. // When there's no audio or video data in the segment, there's no audio or video
  15319. // timing information.
  15320. //
  15321. // If there's no audio or video timing information, then the timestamp offset
  15322. // can't be adjusted to the appropriate value for the transmuxer and source
  15323. // buffers.
  15324. //
  15325. // Therefore, the next segment should be used to set the timestamp offset.
  15326. this.isPendingTimestampOffset_ = true;
  15327. } // override settings for metadata only segments
  15328. segmentInfo.timingInfo = {
  15329. start: 0
  15330. };
  15331. segmentInfo.waitingOnAppends++;
  15332. if (!this.isPendingTimestampOffset_) {
  15333. // update the timestampoffset
  15334. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  15335. // no video/audio data.
  15336. this.processMetadataQueue_();
  15337. } // append is "done" instantly with no data.
  15338. this.checkAppendsDone_(segmentInfo);
  15339. return;
  15340. } // Since source updater could call back synchronously, do the increments first.
  15341. if (waitForVideo) {
  15342. segmentInfo.waitingOnAppends++;
  15343. }
  15344. if (waitForAudio) {
  15345. segmentInfo.waitingOnAppends++;
  15346. }
  15347. if (waitForVideo) {
  15348. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15349. }
  15350. if (waitForAudio) {
  15351. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  15352. }
  15353. }
  15354. checkAppendsDone_(segmentInfo) {
  15355. if (this.checkForAbort_(segmentInfo.requestId)) {
  15356. return;
  15357. }
  15358. segmentInfo.waitingOnAppends--;
  15359. if (segmentInfo.waitingOnAppends === 0) {
  15360. this.handleAppendsDone_();
  15361. }
  15362. }
  15363. checkForIllegalMediaSwitch(trackInfo) {
  15364. const illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  15365. if (illegalMediaSwitchError) {
  15366. this.error({
  15367. message: illegalMediaSwitchError,
  15368. playlistExclusionDuration: Infinity
  15369. });
  15370. this.trigger('error');
  15371. return true;
  15372. }
  15373. return false;
  15374. }
  15375. updateSourceBufferTimestampOffset_(segmentInfo) {
  15376. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  15377. // priority, timing-wise, so we must wait
  15378. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  15379. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  15380. this.loaderType_ !== 'main') {
  15381. return;
  15382. }
  15383. let didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  15384. // the timing info here comes from video. In the event that the audio is longer than
  15385. // the video, this will trim the start of the audio.
  15386. // This also trims any offset from 0 at the beginning of the media
  15387. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  15388. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  15389. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  15390. timingInfo: segmentInfo.timingInfo
  15391. }); // In the event that there are part segment downloads, each will try to update the
  15392. // timestamp offset. Retaining this bit of state prevents us from updating in the
  15393. // future (within the same segment), however, there may be a better way to handle it.
  15394. segmentInfo.changedTimestampOffset = true;
  15395. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  15396. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  15397. didChange = true;
  15398. }
  15399. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  15400. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  15401. didChange = true;
  15402. }
  15403. if (didChange) {
  15404. this.trigger('timestampoffset');
  15405. }
  15406. }
  15407. getSegmentStartTimeForTimestampOffsetCalculation_({
  15408. videoTimingInfo,
  15409. audioTimingInfo,
  15410. timingInfo
  15411. }) {
  15412. if (!this.useDtsForTimestampOffset_) {
  15413. return timingInfo.start;
  15414. }
  15415. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  15416. return videoTimingInfo.transmuxedDecodeStart;
  15417. } // handle audio only
  15418. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  15419. return audioTimingInfo.transmuxedDecodeStart;
  15420. } // handle content not transmuxed (e.g., MP4)
  15421. return timingInfo.start;
  15422. }
  15423. updateTimingInfoEnd_(segmentInfo) {
  15424. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  15425. const trackInfo = this.getMediaInfo_();
  15426. const useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  15427. const prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  15428. if (!prioritizedTimingInfo) {
  15429. return;
  15430. }
  15431. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  15432. // current example is the case of fmp4), so use the rough duration to calculate an
  15433. // end time.
  15434. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  15435. }
  15436. /**
  15437. * callback to run when appendBuffer is finished. detects if we are
  15438. * in a good state to do things with the data we got, or if we need
  15439. * to wait for more
  15440. *
  15441. * @private
  15442. */
  15443. handleAppendsDone_() {
  15444. // appendsdone can cause an abort
  15445. if (this.pendingSegment_) {
  15446. this.trigger('appendsdone');
  15447. }
  15448. if (!this.pendingSegment_) {
  15449. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  15450. // all appending cases?
  15451. if (!this.paused()) {
  15452. this.monitorBuffer_();
  15453. }
  15454. return;
  15455. }
  15456. const segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  15457. // best to wait until all appends are done so we're sure that the primary media is
  15458. // finished (and we have its end time).
  15459. this.updateTimingInfoEnd_(segmentInfo);
  15460. if (this.shouldSaveSegmentTimingInfo_) {
  15461. // Timeline mappings should only be saved for the main loader. This is for multiple
  15462. // reasons:
  15463. //
  15464. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  15465. // and the main loader try to save the timeline mapping, whichever comes later
  15466. // will overwrite the first. In theory this is OK, as the mappings should be the
  15467. // same, however, it breaks for (2)
  15468. // 2) In the event of a live stream, the initial live point will make for a somewhat
  15469. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  15470. // the mapping will be off for one of the streams, dependent on which one was
  15471. // first saved (see (1)).
  15472. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  15473. //
  15474. // Since the audio loader will wait for the main loader to load the first segment,
  15475. // the main loader will save the first timeline mapping, and ensure that there won't
  15476. // be a case where audio loads two segments without saving a mapping (thus leading
  15477. // to missing segment timing info).
  15478. this.syncController_.saveSegmentTimingInfo({
  15479. segmentInfo,
  15480. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  15481. });
  15482. }
  15483. const segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  15484. if (segmentDurationMessage) {
  15485. if (segmentDurationMessage.severity === 'warn') {
  15486. videojs__default["default"].log.warn(segmentDurationMessage.message);
  15487. } else {
  15488. this.logger_(segmentDurationMessage.message);
  15489. }
  15490. }
  15491. this.recordThroughput_(segmentInfo);
  15492. this.pendingSegment_ = null;
  15493. this.state = 'READY';
  15494. if (segmentInfo.isSyncRequest) {
  15495. this.trigger('syncinfoupdate'); // if the sync request was not appended
  15496. // then it was not the correct segment.
  15497. // throw it away and use the data it gave us
  15498. // to get the correct one.
  15499. if (!segmentInfo.hasAppendedData_) {
  15500. this.logger_(`Throwing away un-appended sync request ${segmentInfoString(segmentInfo)}`);
  15501. return;
  15502. }
  15503. }
  15504. this.logger_(`Appended ${segmentInfoString(segmentInfo)}`);
  15505. this.addSegmentMetadataCue_(segmentInfo);
  15506. this.fetchAtBuffer_ = true;
  15507. if (this.currentTimeline_ !== segmentInfo.timeline) {
  15508. this.timelineChangeController_.lastTimelineChange({
  15509. type: this.loaderType_,
  15510. from: this.currentTimeline_,
  15511. to: segmentInfo.timeline
  15512. }); // If audio is not disabled, the main segment loader is responsible for updating
  15513. // the audio timeline as well. If the content is video only, this won't have any
  15514. // impact.
  15515. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  15516. this.timelineChangeController_.lastTimelineChange({
  15517. type: 'audio',
  15518. from: this.currentTimeline_,
  15519. to: segmentInfo.timeline
  15520. });
  15521. }
  15522. }
  15523. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  15524. // the following conditional otherwise it may consider this a bad "guess"
  15525. // and attempt to resync when the post-update seekable window and live
  15526. // point would mean that this was the perfect segment to fetch
  15527. this.trigger('syncinfoupdate');
  15528. const segment = segmentInfo.segment;
  15529. const part = segmentInfo.part;
  15530. const badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  15531. 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
  15532. // the currentTime_ that means that our conservative guess was too conservative.
  15533. // In that case, reset the loader state so that we try to use any information gained
  15534. // from the previous request to create a new, more accurate, sync-point.
  15535. if (badSegmentGuess || badPartGuess) {
  15536. this.logger_(`bad ${badSegmentGuess ? 'segment' : 'part'} ${segmentInfoString(segmentInfo)}`);
  15537. this.resetEverything();
  15538. return;
  15539. }
  15540. const isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  15541. // and conservatively guess
  15542. if (isWalkingForward) {
  15543. this.trigger('bandwidthupdate');
  15544. }
  15545. this.trigger('progress');
  15546. this.mediaIndex = segmentInfo.mediaIndex;
  15547. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  15548. // buffer, end the stream. this ensures the "ended" event will
  15549. // fire if playback reaches that point.
  15550. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  15551. this.endOfStream();
  15552. } // used for testing
  15553. this.trigger('appended');
  15554. if (segmentInfo.hasAppendedData_) {
  15555. this.mediaAppends++;
  15556. }
  15557. if (!this.paused()) {
  15558. this.monitorBuffer_();
  15559. }
  15560. }
  15561. /**
  15562. * Records the current throughput of the decrypt, transmux, and append
  15563. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  15564. * moving average of the throughput. `throughput.count` is the number of
  15565. * data points in the average.
  15566. *
  15567. * @private
  15568. * @param {Object} segmentInfo the object returned by loadSegment
  15569. */
  15570. recordThroughput_(segmentInfo) {
  15571. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  15572. 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}`);
  15573. return;
  15574. }
  15575. const rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  15576. // by zero in the case where the throughput is ridiculously high
  15577. const segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  15578. const segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  15579. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  15580. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  15581. }
  15582. /**
  15583. * Adds a cue to the segment-metadata track with some metadata information about the
  15584. * segment
  15585. *
  15586. * @private
  15587. * @param {Object} segmentInfo
  15588. * the object returned by loadSegment
  15589. * @method addSegmentMetadataCue_
  15590. */
  15591. addSegmentMetadataCue_(segmentInfo) {
  15592. if (!this.segmentMetadataTrack_) {
  15593. return;
  15594. }
  15595. const segment = segmentInfo.segment;
  15596. const start = segment.start;
  15597. const end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  15598. if (!finite(start) || !finite(end)) {
  15599. return;
  15600. }
  15601. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  15602. const Cue = window__default["default"].WebKitDataCue || window__default["default"].VTTCue;
  15603. const value = {
  15604. custom: segment.custom,
  15605. dateTimeObject: segment.dateTimeObject,
  15606. dateTimeString: segment.dateTimeString,
  15607. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  15608. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  15609. codecs: segmentInfo.playlist.attributes.CODECS,
  15610. byteLength: segmentInfo.byteLength,
  15611. uri: segmentInfo.uri,
  15612. timeline: segmentInfo.timeline,
  15613. playlist: segmentInfo.playlist.id,
  15614. start,
  15615. end
  15616. };
  15617. const data = JSON.stringify(value);
  15618. const cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  15619. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  15620. cue.value = value;
  15621. this.segmentMetadataTrack_.addCue(cue);
  15622. }
  15623. }
  15624. function noop() {}
  15625. const toTitleCase = function (string) {
  15626. if (typeof string !== 'string') {
  15627. return string;
  15628. }
  15629. return string.replace(/./, w => w.toUpperCase());
  15630. };
  15631. /**
  15632. * @file source-updater.js
  15633. */
  15634. const bufferTypes = ['video', 'audio'];
  15635. const updating = (type, sourceUpdater) => {
  15636. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15637. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  15638. };
  15639. const nextQueueIndexOfType = (type, queue) => {
  15640. for (let i = 0; i < queue.length; i++) {
  15641. const queueEntry = queue[i];
  15642. if (queueEntry.type === 'mediaSource') {
  15643. // If the next entry is a media source entry (uses multiple source buffers), block
  15644. // processing to allow it to go through first.
  15645. return null;
  15646. }
  15647. if (queueEntry.type === type) {
  15648. return i;
  15649. }
  15650. }
  15651. return null;
  15652. };
  15653. const shiftQueue = (type, sourceUpdater) => {
  15654. if (sourceUpdater.queue.length === 0) {
  15655. return;
  15656. }
  15657. let queueIndex = 0;
  15658. let queueEntry = sourceUpdater.queue[queueIndex];
  15659. if (queueEntry.type === 'mediaSource') {
  15660. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  15661. sourceUpdater.queue.shift();
  15662. queueEntry.action(sourceUpdater);
  15663. if (queueEntry.doneFn) {
  15664. queueEntry.doneFn();
  15665. } // Only specific source buffer actions must wait for async updateend events. Media
  15666. // Source actions process synchronously. Therefore, both audio and video source
  15667. // buffers are now clear to process the next queue entries.
  15668. shiftQueue('audio', sourceUpdater);
  15669. shiftQueue('video', sourceUpdater);
  15670. } // Media Source actions require both source buffers, so if the media source action
  15671. // couldn't process yet (because one or both source buffers are busy), block other
  15672. // queue actions until both are available and the media source action can process.
  15673. return;
  15674. }
  15675. if (type === 'mediaSource') {
  15676. // If the queue was shifted by a media source action (this happens when pushing a
  15677. // media source action onto the queue), then it wasn't from an updateend event from an
  15678. // audio or video source buffer, so there's no change from previous state, and no
  15679. // processing should be done.
  15680. return;
  15681. } // Media source queue entries don't need to consider whether the source updater is
  15682. // started (i.e., source buffers are created) as they don't need the source buffers, but
  15683. // source buffer queue entries do.
  15684. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || updating(type, sourceUpdater)) {
  15685. return;
  15686. }
  15687. if (queueEntry.type !== type) {
  15688. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  15689. if (queueIndex === null) {
  15690. // Either there's no queue entry that uses this source buffer type in the queue, or
  15691. // there's a media source queue entry before the next entry of this type, in which
  15692. // case wait for that action to process first.
  15693. return;
  15694. }
  15695. queueEntry = sourceUpdater.queue[queueIndex];
  15696. }
  15697. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  15698. //
  15699. // The queue pending operation must be set before the action is performed in the event
  15700. // that the action results in a synchronous event that is acted upon. For instance, if
  15701. // an exception is thrown that can be handled, it's possible that new actions will be
  15702. // appended to an empty queue and immediately executed, but would not have the correct
  15703. // pending information if this property was set after the action was performed.
  15704. sourceUpdater.queuePending[type] = queueEntry;
  15705. queueEntry.action(type, sourceUpdater);
  15706. if (!queueEntry.doneFn) {
  15707. // synchronous operation, process next entry
  15708. sourceUpdater.queuePending[type] = null;
  15709. shiftQueue(type, sourceUpdater);
  15710. return;
  15711. }
  15712. };
  15713. const cleanupBuffer = (type, sourceUpdater) => {
  15714. const buffer = sourceUpdater[`${type}Buffer`];
  15715. const titleType = toTitleCase(type);
  15716. if (!buffer) {
  15717. return;
  15718. }
  15719. buffer.removeEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  15720. buffer.removeEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  15721. sourceUpdater.codecs[type] = null;
  15722. sourceUpdater[`${type}Buffer`] = null;
  15723. };
  15724. const inSourceBuffers = (mediaSource, sourceBuffer) => mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  15725. const actions = {
  15726. appendBuffer: (bytes, segmentInfo, onError) => (type, sourceUpdater) => {
  15727. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15728. // or the media source does not contain this source buffer.
  15729. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15730. return;
  15731. }
  15732. sourceUpdater.logger_(`Appending segment ${segmentInfo.mediaIndex}'s ${bytes.length} bytes to ${type}Buffer`);
  15733. try {
  15734. sourceBuffer.appendBuffer(bytes);
  15735. } catch (e) {
  15736. sourceUpdater.logger_(`Error with code ${e.code} ` + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + `when appending segment ${segmentInfo.mediaIndex} to ${type}Buffer`);
  15737. sourceUpdater.queuePending[type] = null;
  15738. onError(e);
  15739. }
  15740. },
  15741. remove: (start, end) => (type, sourceUpdater) => {
  15742. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15743. // or the media source does not contain this source buffer.
  15744. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15745. return;
  15746. }
  15747. sourceUpdater.logger_(`Removing ${start} to ${end} from ${type}Buffer`);
  15748. try {
  15749. sourceBuffer.remove(start, end);
  15750. } catch (e) {
  15751. sourceUpdater.logger_(`Remove ${start} to ${end} from ${type}Buffer failed`);
  15752. }
  15753. },
  15754. timestampOffset: offset => (type, sourceUpdater) => {
  15755. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15756. // or the media source does not contain this source buffer.
  15757. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15758. return;
  15759. }
  15760. sourceUpdater.logger_(`Setting ${type}timestampOffset to ${offset}`);
  15761. sourceBuffer.timestampOffset = offset;
  15762. },
  15763. callback: callback => (type, sourceUpdater) => {
  15764. callback();
  15765. },
  15766. endOfStream: error => sourceUpdater => {
  15767. if (sourceUpdater.mediaSource.readyState !== 'open') {
  15768. return;
  15769. }
  15770. sourceUpdater.logger_(`Calling mediaSource endOfStream(${error || ''})`);
  15771. try {
  15772. sourceUpdater.mediaSource.endOfStream(error);
  15773. } catch (e) {
  15774. videojs__default["default"].log.warn('Failed to call media source endOfStream', e);
  15775. }
  15776. },
  15777. duration: duration => sourceUpdater => {
  15778. sourceUpdater.logger_(`Setting mediaSource duration to ${duration}`);
  15779. try {
  15780. sourceUpdater.mediaSource.duration = duration;
  15781. } catch (e) {
  15782. videojs__default["default"].log.warn('Failed to set media source duration', e);
  15783. }
  15784. },
  15785. abort: () => (type, sourceUpdater) => {
  15786. if (sourceUpdater.mediaSource.readyState !== 'open') {
  15787. return;
  15788. }
  15789. const sourceBuffer = sourceUpdater[`${type}Buffer`]; // can't do anything if the media source / source buffer is null
  15790. // or the media source does not contain this source buffer.
  15791. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15792. return;
  15793. }
  15794. sourceUpdater.logger_(`calling abort on ${type}Buffer`);
  15795. try {
  15796. sourceBuffer.abort();
  15797. } catch (e) {
  15798. videojs__default["default"].log.warn(`Failed to abort on ${type}Buffer`, e);
  15799. }
  15800. },
  15801. addSourceBuffer: (type, codec) => sourceUpdater => {
  15802. const titleType = toTitleCase(type);
  15803. const mime = codecs_js.getMimeForCodec(codec);
  15804. sourceUpdater.logger_(`Adding ${type}Buffer with codec ${codec} to mediaSource`);
  15805. const sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  15806. sourceBuffer.addEventListener('updateend', sourceUpdater[`on${titleType}UpdateEnd_`]);
  15807. sourceBuffer.addEventListener('error', sourceUpdater[`on${titleType}Error_`]);
  15808. sourceUpdater.codecs[type] = codec;
  15809. sourceUpdater[`${type}Buffer`] = sourceBuffer;
  15810. },
  15811. removeSourceBuffer: type => sourceUpdater => {
  15812. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15813. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  15814. // or the media source does not contain this source buffer.
  15815. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15816. return;
  15817. }
  15818. sourceUpdater.logger_(`Removing ${type}Buffer with codec ${sourceUpdater.codecs[type]} from mediaSource`);
  15819. try {
  15820. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  15821. } catch (e) {
  15822. videojs__default["default"].log.warn(`Failed to removeSourceBuffer ${type}Buffer`, e);
  15823. }
  15824. },
  15825. changeType: codec => (type, sourceUpdater) => {
  15826. const sourceBuffer = sourceUpdater[`${type}Buffer`];
  15827. const mime = codecs_js.getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  15828. // or the media source does not contain this source buffer.
  15829. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  15830. return;
  15831. } // do not update codec if we don't need to.
  15832. if (sourceUpdater.codecs[type] === codec) {
  15833. return;
  15834. }
  15835. sourceUpdater.logger_(`changing ${type}Buffer codec from ${sourceUpdater.codecs[type]} to ${codec}`);
  15836. sourceBuffer.changeType(mime);
  15837. sourceUpdater.codecs[type] = codec;
  15838. }
  15839. };
  15840. const pushQueue = ({
  15841. type,
  15842. sourceUpdater,
  15843. action,
  15844. doneFn,
  15845. name
  15846. }) => {
  15847. sourceUpdater.queue.push({
  15848. type,
  15849. action,
  15850. doneFn,
  15851. name
  15852. });
  15853. shiftQueue(type, sourceUpdater);
  15854. };
  15855. const onUpdateend = (type, sourceUpdater) => e => {
  15856. // Although there should, in theory, be a pending action for any updateend receieved,
  15857. // there are some actions that may trigger updateend events without set definitions in
  15858. // the w3c spec. For instance, setting the duration on the media source may trigger
  15859. // updateend events on source buffers. This does not appear to be in the spec. As such,
  15860. // if we encounter an updateend without a corresponding pending action from our queue
  15861. // for that source buffer type, process the next action.
  15862. if (sourceUpdater.queuePending[type]) {
  15863. const doneFn = sourceUpdater.queuePending[type].doneFn;
  15864. sourceUpdater.queuePending[type] = null;
  15865. if (doneFn) {
  15866. // if there's an error, report it
  15867. doneFn(sourceUpdater[`${type}Error_`]);
  15868. }
  15869. }
  15870. shiftQueue(type, sourceUpdater);
  15871. };
  15872. /**
  15873. * A queue of callbacks to be serialized and applied when a
  15874. * MediaSource and its associated SourceBuffers are not in the
  15875. * updating state. It is used by the segment loader to update the
  15876. * underlying SourceBuffers when new data is loaded, for instance.
  15877. *
  15878. * @class SourceUpdater
  15879. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  15880. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  15881. */
  15882. class SourceUpdater extends videojs__default["default"].EventTarget {
  15883. constructor(mediaSource) {
  15884. super();
  15885. this.mediaSource = mediaSource;
  15886. this.sourceopenListener_ = () => shiftQueue('mediaSource', this);
  15887. this.mediaSource.addEventListener('sourceopen', this.sourceopenListener_);
  15888. this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  15889. this.audioTimestampOffset_ = 0;
  15890. this.videoTimestampOffset_ = 0;
  15891. this.queue = [];
  15892. this.queuePending = {
  15893. audio: null,
  15894. video: null
  15895. };
  15896. this.delayedAudioAppendQueue_ = [];
  15897. this.videoAppendQueued_ = false;
  15898. this.codecs = {};
  15899. this.onVideoUpdateEnd_ = onUpdateend('video', this);
  15900. this.onAudioUpdateEnd_ = onUpdateend('audio', this);
  15901. this.onVideoError_ = e => {
  15902. // used for debugging
  15903. this.videoError_ = e;
  15904. };
  15905. this.onAudioError_ = e => {
  15906. // used for debugging
  15907. this.audioError_ = e;
  15908. };
  15909. this.createdSourceBuffers_ = false;
  15910. this.initializedEme_ = false;
  15911. this.triggeredReady_ = false;
  15912. }
  15913. initializedEme() {
  15914. this.initializedEme_ = true;
  15915. this.triggerReady();
  15916. }
  15917. hasCreatedSourceBuffers() {
  15918. // if false, likely waiting on one of the segment loaders to get enough data to create
  15919. // source buffers
  15920. return this.createdSourceBuffers_;
  15921. }
  15922. hasInitializedAnyEme() {
  15923. return this.initializedEme_;
  15924. }
  15925. ready() {
  15926. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  15927. }
  15928. createSourceBuffers(codecs) {
  15929. if (this.hasCreatedSourceBuffers()) {
  15930. // already created them before
  15931. return;
  15932. } // the intial addOrChangeSourceBuffers will always be
  15933. // two add buffers.
  15934. this.addOrChangeSourceBuffers(codecs);
  15935. this.createdSourceBuffers_ = true;
  15936. this.trigger('createdsourcebuffers');
  15937. this.triggerReady();
  15938. }
  15939. triggerReady() {
  15940. // only allow ready to be triggered once, this prevents the case
  15941. // where:
  15942. // 1. we trigger createdsourcebuffers
  15943. // 2. ie 11 synchronously initializates eme
  15944. // 3. the synchronous initialization causes us to trigger ready
  15945. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  15946. if (this.ready() && !this.triggeredReady_) {
  15947. this.triggeredReady_ = true;
  15948. this.trigger('ready');
  15949. }
  15950. }
  15951. /**
  15952. * Add a type of source buffer to the media source.
  15953. *
  15954. * @param {string} type
  15955. * The type of source buffer to add.
  15956. *
  15957. * @param {string} codec
  15958. * The codec to add the source buffer with.
  15959. */
  15960. addSourceBuffer(type, codec) {
  15961. pushQueue({
  15962. type: 'mediaSource',
  15963. sourceUpdater: this,
  15964. action: actions.addSourceBuffer(type, codec),
  15965. name: 'addSourceBuffer'
  15966. });
  15967. }
  15968. /**
  15969. * call abort on a source buffer.
  15970. *
  15971. * @param {string} type
  15972. * The type of source buffer to call abort on.
  15973. */
  15974. abort(type) {
  15975. pushQueue({
  15976. type,
  15977. sourceUpdater: this,
  15978. action: actions.abort(type),
  15979. name: 'abort'
  15980. });
  15981. }
  15982. /**
  15983. * Call removeSourceBuffer and remove a specific type
  15984. * of source buffer on the mediaSource.
  15985. *
  15986. * @param {string} type
  15987. * The type of source buffer to remove.
  15988. */
  15989. removeSourceBuffer(type) {
  15990. if (!this.canRemoveSourceBuffer()) {
  15991. videojs__default["default"].log.error('removeSourceBuffer is not supported!');
  15992. return;
  15993. }
  15994. pushQueue({
  15995. type: 'mediaSource',
  15996. sourceUpdater: this,
  15997. action: actions.removeSourceBuffer(type),
  15998. name: 'removeSourceBuffer'
  15999. });
  16000. }
  16001. /**
  16002. * Whether or not the removeSourceBuffer function is supported
  16003. * on the mediaSource.
  16004. *
  16005. * @return {boolean}
  16006. * if removeSourceBuffer can be called.
  16007. */
  16008. canRemoveSourceBuffer() {
  16009. // IE reports that it supports removeSourceBuffer, but often throws
  16010. // errors when attempting to use the function. So we report that it
  16011. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  16012. // throws errors, so we report that it does not support this as well.
  16013. return !videojs__default["default"].browser.IE_VERSION && !videojs__default["default"].browser.IS_FIREFOX && window__default["default"].MediaSource && window__default["default"].MediaSource.prototype && typeof window__default["default"].MediaSource.prototype.removeSourceBuffer === 'function';
  16014. }
  16015. /**
  16016. * Whether or not the changeType function is supported
  16017. * on our SourceBuffers.
  16018. *
  16019. * @return {boolean}
  16020. * if changeType can be called.
  16021. */
  16022. static canChangeType() {
  16023. return window__default["default"].SourceBuffer && window__default["default"].SourceBuffer.prototype && typeof window__default["default"].SourceBuffer.prototype.changeType === 'function';
  16024. }
  16025. /**
  16026. * Whether or not the changeType function is supported
  16027. * on our SourceBuffers.
  16028. *
  16029. * @return {boolean}
  16030. * if changeType can be called.
  16031. */
  16032. canChangeType() {
  16033. return this.constructor.canChangeType();
  16034. }
  16035. /**
  16036. * Call the changeType function on a source buffer, given the code and type.
  16037. *
  16038. * @param {string} type
  16039. * The type of source buffer to call changeType on.
  16040. *
  16041. * @param {string} codec
  16042. * The codec string to change type with on the source buffer.
  16043. */
  16044. changeType(type, codec) {
  16045. if (!this.canChangeType()) {
  16046. videojs__default["default"].log.error('changeType is not supported!');
  16047. return;
  16048. }
  16049. pushQueue({
  16050. type,
  16051. sourceUpdater: this,
  16052. action: actions.changeType(codec),
  16053. name: 'changeType'
  16054. });
  16055. }
  16056. /**
  16057. * Add source buffers with a codec or, if they are already created,
  16058. * call changeType on source buffers using changeType.
  16059. *
  16060. * @param {Object} codecs
  16061. * Codecs to switch to
  16062. */
  16063. addOrChangeSourceBuffers(codecs) {
  16064. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  16065. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  16066. }
  16067. Object.keys(codecs).forEach(type => {
  16068. const codec = codecs[type];
  16069. if (!this.hasCreatedSourceBuffers()) {
  16070. return this.addSourceBuffer(type, codec);
  16071. }
  16072. if (this.canChangeType()) {
  16073. this.changeType(type, codec);
  16074. }
  16075. });
  16076. }
  16077. /**
  16078. * Queue an update to append an ArrayBuffer.
  16079. *
  16080. * @param {MediaObject} object containing audioBytes and/or videoBytes
  16081. * @param {Function} done the function to call when done
  16082. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  16083. */
  16084. appendBuffer(options, doneFn) {
  16085. const {
  16086. segmentInfo,
  16087. type,
  16088. bytes
  16089. } = options;
  16090. this.processedAppend_ = true;
  16091. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  16092. this.delayedAudioAppendQueue_.push([options, doneFn]);
  16093. this.logger_(`delayed audio append of ${bytes.length} until video append`);
  16094. return;
  16095. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  16096. // not be fired. This means that the queue will be blocked until the next action
  16097. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  16098. // these errors by calling the doneFn with the specific error.
  16099. const onError = doneFn;
  16100. pushQueue({
  16101. type,
  16102. sourceUpdater: this,
  16103. action: actions.appendBuffer(bytes, segmentInfo || {
  16104. mediaIndex: -1
  16105. }, onError),
  16106. doneFn,
  16107. name: 'appendBuffer'
  16108. });
  16109. if (type === 'video') {
  16110. this.videoAppendQueued_ = true;
  16111. if (!this.delayedAudioAppendQueue_.length) {
  16112. return;
  16113. }
  16114. const queue = this.delayedAudioAppendQueue_.slice();
  16115. this.logger_(`queuing delayed audio ${queue.length} appendBuffers`);
  16116. this.delayedAudioAppendQueue_.length = 0;
  16117. queue.forEach(que => {
  16118. this.appendBuffer.apply(this, que);
  16119. });
  16120. }
  16121. }
  16122. /**
  16123. * Get the audio buffer's buffered timerange.
  16124. *
  16125. * @return {TimeRange}
  16126. * The audio buffer's buffered time range
  16127. */
  16128. audioBuffered() {
  16129. // no media source/source buffer or it isn't in the media sources
  16130. // source buffer list
  16131. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  16132. return createTimeRanges();
  16133. }
  16134. return this.audioBuffer.buffered ? this.audioBuffer.buffered : createTimeRanges();
  16135. }
  16136. /**
  16137. * Get the video buffer's buffered timerange.
  16138. *
  16139. * @return {TimeRange}
  16140. * The video buffer's buffered time range
  16141. */
  16142. videoBuffered() {
  16143. // no media source/source buffer or it isn't in the media sources
  16144. // source buffer list
  16145. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  16146. return createTimeRanges();
  16147. }
  16148. return this.videoBuffer.buffered ? this.videoBuffer.buffered : createTimeRanges();
  16149. }
  16150. /**
  16151. * Get a combined video/audio buffer's buffered timerange.
  16152. *
  16153. * @return {TimeRange}
  16154. * the combined time range
  16155. */
  16156. buffered() {
  16157. const video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  16158. const audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  16159. if (audio && !video) {
  16160. return this.audioBuffered();
  16161. }
  16162. if (video && !audio) {
  16163. return this.videoBuffered();
  16164. }
  16165. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  16166. }
  16167. /**
  16168. * Add a callback to the queue that will set duration on the mediaSource.
  16169. *
  16170. * @param {number} duration
  16171. * The duration to set
  16172. *
  16173. * @param {Function} [doneFn]
  16174. * function to run after duration has been set.
  16175. */
  16176. setDuration(duration, doneFn = noop) {
  16177. // In order to set the duration on the media source, it's necessary to wait for all
  16178. // source buffers to no longer be updating. "If the updating attribute equals true on
  16179. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16180. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16181. pushQueue({
  16182. type: 'mediaSource',
  16183. sourceUpdater: this,
  16184. action: actions.duration(duration),
  16185. name: 'duration',
  16186. doneFn
  16187. });
  16188. }
  16189. /**
  16190. * Add a mediaSource endOfStream call to the queue
  16191. *
  16192. * @param {Error} [error]
  16193. * Call endOfStream with an error
  16194. *
  16195. * @param {Function} [doneFn]
  16196. * A function that should be called when the
  16197. * endOfStream call has finished.
  16198. */
  16199. endOfStream(error = null, doneFn = noop) {
  16200. if (typeof error !== 'string') {
  16201. error = undefined;
  16202. } // In order to set the duration on the media source, it's necessary to wait for all
  16203. // source buffers to no longer be updating. "If the updating attribute equals true on
  16204. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  16205. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  16206. pushQueue({
  16207. type: 'mediaSource',
  16208. sourceUpdater: this,
  16209. action: actions.endOfStream(error),
  16210. name: 'endOfStream',
  16211. doneFn
  16212. });
  16213. }
  16214. /**
  16215. * Queue an update to remove a time range from the buffer.
  16216. *
  16217. * @param {number} start where to start the removal
  16218. * @param {number} end where to end the removal
  16219. * @param {Function} [done=noop] optional callback to be executed when the remove
  16220. * operation is complete
  16221. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16222. */
  16223. removeAudio(start, end, done = noop) {
  16224. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  16225. done();
  16226. return;
  16227. }
  16228. pushQueue({
  16229. type: 'audio',
  16230. sourceUpdater: this,
  16231. action: actions.remove(start, end),
  16232. doneFn: done,
  16233. name: 'remove'
  16234. });
  16235. }
  16236. /**
  16237. * Queue an update to remove a time range from the buffer.
  16238. *
  16239. * @param {number} start where to start the removal
  16240. * @param {number} end where to end the removal
  16241. * @param {Function} [done=noop] optional callback to be executed when the remove
  16242. * operation is complete
  16243. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  16244. */
  16245. removeVideo(start, end, done = noop) {
  16246. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  16247. done();
  16248. return;
  16249. }
  16250. pushQueue({
  16251. type: 'video',
  16252. sourceUpdater: this,
  16253. action: actions.remove(start, end),
  16254. doneFn: done,
  16255. name: 'remove'
  16256. });
  16257. }
  16258. /**
  16259. * Whether the underlying sourceBuffer is updating or not
  16260. *
  16261. * @return {boolean} the updating status of the SourceBuffer
  16262. */
  16263. updating() {
  16264. // the audio/video source buffer is updating
  16265. if (updating('audio', this) || updating('video', this)) {
  16266. return true;
  16267. }
  16268. return false;
  16269. }
  16270. /**
  16271. * Set/get the timestampoffset on the audio SourceBuffer
  16272. *
  16273. * @return {number} the timestamp offset
  16274. */
  16275. audioTimestampOffset(offset) {
  16276. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  16277. this.audioTimestampOffset_ !== offset) {
  16278. pushQueue({
  16279. type: 'audio',
  16280. sourceUpdater: this,
  16281. action: actions.timestampOffset(offset),
  16282. name: 'timestampOffset'
  16283. });
  16284. this.audioTimestampOffset_ = offset;
  16285. }
  16286. return this.audioTimestampOffset_;
  16287. }
  16288. /**
  16289. * Set/get the timestampoffset on the video SourceBuffer
  16290. *
  16291. * @return {number} the timestamp offset
  16292. */
  16293. videoTimestampOffset(offset) {
  16294. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  16295. this.videoTimestampOffset !== offset) {
  16296. pushQueue({
  16297. type: 'video',
  16298. sourceUpdater: this,
  16299. action: actions.timestampOffset(offset),
  16300. name: 'timestampOffset'
  16301. });
  16302. this.videoTimestampOffset_ = offset;
  16303. }
  16304. return this.videoTimestampOffset_;
  16305. }
  16306. /**
  16307. * Add a function to the queue that will be called
  16308. * when it is its turn to run in the audio queue.
  16309. *
  16310. * @param {Function} callback
  16311. * The callback to queue.
  16312. */
  16313. audioQueueCallback(callback) {
  16314. if (!this.audioBuffer) {
  16315. return;
  16316. }
  16317. pushQueue({
  16318. type: 'audio',
  16319. sourceUpdater: this,
  16320. action: actions.callback(callback),
  16321. name: 'callback'
  16322. });
  16323. }
  16324. /**
  16325. * Add a function to the queue that will be called
  16326. * when it is its turn to run in the video queue.
  16327. *
  16328. * @param {Function} callback
  16329. * The callback to queue.
  16330. */
  16331. videoQueueCallback(callback) {
  16332. if (!this.videoBuffer) {
  16333. return;
  16334. }
  16335. pushQueue({
  16336. type: 'video',
  16337. sourceUpdater: this,
  16338. action: actions.callback(callback),
  16339. name: 'callback'
  16340. });
  16341. }
  16342. /**
  16343. * dispose of the source updater and the underlying sourceBuffer
  16344. */
  16345. dispose() {
  16346. this.trigger('dispose');
  16347. bufferTypes.forEach(type => {
  16348. this.abort(type);
  16349. if (this.canRemoveSourceBuffer()) {
  16350. this.removeSourceBuffer(type);
  16351. } else {
  16352. this[`${type}QueueCallback`](() => cleanupBuffer(type, this));
  16353. }
  16354. });
  16355. this.videoAppendQueued_ = false;
  16356. this.delayedAudioAppendQueue_.length = 0;
  16357. if (this.sourceopenListener_) {
  16358. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  16359. }
  16360. this.off();
  16361. }
  16362. }
  16363. const uint8ToUtf8 = uintArray => decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  16364. /**
  16365. * @file vtt-segment-loader.js
  16366. */
  16367. const VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(char => char.charCodeAt(0)));
  16368. class NoVttJsError extends Error {
  16369. constructor() {
  16370. super('Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.');
  16371. }
  16372. }
  16373. /**
  16374. * An object that manages segment loading and appending.
  16375. *
  16376. * @class VTTSegmentLoader
  16377. * @param {Object} options required and optional options
  16378. * @extends videojs.EventTarget
  16379. */
  16380. class VTTSegmentLoader extends SegmentLoader {
  16381. constructor(settings, options = {}) {
  16382. super(settings, options); // SegmentLoader requires a MediaSource be specified or it will throw an error;
  16383. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  16384. this.mediaSource_ = null;
  16385. this.subtitlesTrack_ = null;
  16386. this.loaderType_ = 'subtitle';
  16387. this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  16388. this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  16389. // the sync controller leads to improper behavior.
  16390. this.shouldSaveSegmentTimingInfo_ = false;
  16391. }
  16392. createTransmuxer_() {
  16393. // don't need to transmux any subtitles
  16394. return null;
  16395. }
  16396. /**
  16397. * Indicates which time ranges are buffered
  16398. *
  16399. * @return {TimeRange}
  16400. * TimeRange object representing the current buffered ranges
  16401. */
  16402. buffered_() {
  16403. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  16404. return createTimeRanges();
  16405. }
  16406. const cues = this.subtitlesTrack_.cues;
  16407. const start = cues[0].startTime;
  16408. const end = cues[cues.length - 1].startTime;
  16409. return createTimeRanges([[start, end]]);
  16410. }
  16411. /**
  16412. * Gets and sets init segment for the provided map
  16413. *
  16414. * @param {Object} map
  16415. * The map object representing the init segment to get or set
  16416. * @param {boolean=} set
  16417. * If true, the init segment for the provided map should be saved
  16418. * @return {Object}
  16419. * map object for desired init segment
  16420. */
  16421. initSegmentForMap(map, set = false) {
  16422. if (!map) {
  16423. return null;
  16424. }
  16425. const id = initSegmentId(map);
  16426. let storedMap = this.initSegments_[id];
  16427. if (set && !storedMap && map.bytes) {
  16428. // append WebVTT line terminators to the media initialization segment if it exists
  16429. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  16430. // requires two or more WebVTT line terminators between the WebVTT header and the
  16431. // rest of the file
  16432. const combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  16433. const combinedSegment = new Uint8Array(combinedByteLength);
  16434. combinedSegment.set(map.bytes);
  16435. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  16436. this.initSegments_[id] = storedMap = {
  16437. resolvedUri: map.resolvedUri,
  16438. byterange: map.byterange,
  16439. bytes: combinedSegment
  16440. };
  16441. }
  16442. return storedMap || map;
  16443. }
  16444. /**
  16445. * Returns true if all configuration required for loading is present, otherwise false.
  16446. *
  16447. * @return {boolean} True if the all configuration is ready for loading
  16448. * @private
  16449. */
  16450. couldBeginLoading_() {
  16451. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  16452. }
  16453. /**
  16454. * Once all the starting parameters have been specified, begin
  16455. * operation. This method should only be invoked from the INIT
  16456. * state.
  16457. *
  16458. * @private
  16459. */
  16460. init_() {
  16461. this.state = 'READY';
  16462. this.resetEverything();
  16463. return this.monitorBuffer_();
  16464. }
  16465. /**
  16466. * Set a subtitle track on the segment loader to add subtitles to
  16467. *
  16468. * @param {TextTrack=} track
  16469. * The text track to add loaded subtitles to
  16470. * @return {TextTrack}
  16471. * Returns the subtitles track
  16472. */
  16473. track(track) {
  16474. if (typeof track === 'undefined') {
  16475. return this.subtitlesTrack_;
  16476. }
  16477. this.subtitlesTrack_ = track; // if we were unpaused but waiting for a sourceUpdater, start
  16478. // buffering now
  16479. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  16480. this.init_();
  16481. }
  16482. return this.subtitlesTrack_;
  16483. }
  16484. /**
  16485. * Remove any data in the source buffer between start and end times
  16486. *
  16487. * @param {number} start - the start time of the region to remove from the buffer
  16488. * @param {number} end - the end time of the region to remove from the buffer
  16489. */
  16490. remove(start, end) {
  16491. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  16492. }
  16493. /**
  16494. * fill the buffer with segements unless the sourceBuffers are
  16495. * currently updating
  16496. *
  16497. * Note: this function should only ever be called by monitorBuffer_
  16498. * and never directly
  16499. *
  16500. * @private
  16501. */
  16502. fillBuffer_() {
  16503. // see if we need to begin loading immediately
  16504. const segmentInfo = this.chooseNextRequest_();
  16505. if (!segmentInfo) {
  16506. return;
  16507. }
  16508. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  16509. // We don't have the timestamp offset that we need to sync subtitles.
  16510. // Rerun on a timestamp offset or user interaction.
  16511. const checkTimestampOffset = () => {
  16512. this.state = 'READY';
  16513. if (!this.paused()) {
  16514. // if not paused, queue a buffer check as soon as possible
  16515. this.monitorBuffer_();
  16516. }
  16517. };
  16518. this.syncController_.one('timestampoffset', checkTimestampOffset);
  16519. this.state = 'WAITING_ON_TIMELINE';
  16520. return;
  16521. }
  16522. this.loadSegment_(segmentInfo);
  16523. } // never set a timestamp offset for vtt segments.
  16524. timestampOffsetForSegment_() {
  16525. return null;
  16526. }
  16527. chooseNextRequest_() {
  16528. return this.skipEmptySegments_(super.chooseNextRequest_());
  16529. }
  16530. /**
  16531. * Prevents the segment loader from requesting segments we know contain no subtitles
  16532. * by walking forward until we find the next segment that we don't know whether it is
  16533. * empty or not.
  16534. *
  16535. * @param {Object} segmentInfo
  16536. * a segment info object that describes the current segment
  16537. * @return {Object}
  16538. * a segment info object that describes the current segment
  16539. */
  16540. skipEmptySegments_(segmentInfo) {
  16541. while (segmentInfo && segmentInfo.segment.empty) {
  16542. // stop at the last possible segmentInfo
  16543. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  16544. segmentInfo = null;
  16545. break;
  16546. }
  16547. segmentInfo = this.generateSegmentInfo_({
  16548. playlist: segmentInfo.playlist,
  16549. mediaIndex: segmentInfo.mediaIndex + 1,
  16550. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  16551. isSyncRequest: segmentInfo.isSyncRequest
  16552. });
  16553. }
  16554. return segmentInfo;
  16555. }
  16556. stopForError(error) {
  16557. this.error(error);
  16558. this.state = 'READY';
  16559. this.pause();
  16560. this.trigger('error');
  16561. }
  16562. /**
  16563. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  16564. *
  16565. * @private
  16566. */
  16567. segmentRequestFinished_(error, simpleSegment, result) {
  16568. if (!this.subtitlesTrack_) {
  16569. this.state = 'READY';
  16570. return;
  16571. }
  16572. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  16573. if (!this.pendingSegment_) {
  16574. this.state = 'READY';
  16575. this.mediaRequestsAborted += 1;
  16576. return;
  16577. }
  16578. if (error) {
  16579. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  16580. this.handleTimeout_();
  16581. }
  16582. if (error.code === REQUEST_ERRORS.ABORTED) {
  16583. this.mediaRequestsAborted += 1;
  16584. } else {
  16585. this.mediaRequestsErrored += 1;
  16586. }
  16587. this.stopForError(error);
  16588. return;
  16589. }
  16590. const segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  16591. // maintain functionality between segment loaders
  16592. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  16593. if (simpleSegment.key) {
  16594. this.segmentKey(simpleSegment.key, true);
  16595. }
  16596. this.state = 'APPENDING'; // used for tests
  16597. this.trigger('appending');
  16598. const segment = segmentInfo.segment;
  16599. if (segment.map) {
  16600. segment.map.bytes = simpleSegment.map.bytes;
  16601. }
  16602. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  16603. if (typeof window__default["default"].WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  16604. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  16605. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  16606. this.loadVttJs().then(() => this.segmentRequestFinished_(error, simpleSegment, result), () => this.stopForError({
  16607. message: 'Error loading vtt.js'
  16608. }));
  16609. return;
  16610. }
  16611. segment.requested = true;
  16612. try {
  16613. this.parseVTTCues_(segmentInfo);
  16614. } catch (e) {
  16615. this.stopForError({
  16616. message: e.message
  16617. });
  16618. return;
  16619. }
  16620. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  16621. if (segmentInfo.cues.length) {
  16622. segmentInfo.timingInfo = {
  16623. start: segmentInfo.cues[0].startTime,
  16624. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  16625. };
  16626. } else {
  16627. segmentInfo.timingInfo = {
  16628. start: segmentInfo.startOfSegment,
  16629. end: segmentInfo.startOfSegment + segmentInfo.duration
  16630. };
  16631. }
  16632. if (segmentInfo.isSyncRequest) {
  16633. this.trigger('syncinfoupdate');
  16634. this.pendingSegment_ = null;
  16635. this.state = 'READY';
  16636. return;
  16637. }
  16638. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  16639. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  16640. // the subtitle track
  16641. segmentInfo.cues.forEach(cue => {
  16642. this.subtitlesTrack_.addCue(this.featuresNativeTextTracks_ ? new window__default["default"].VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  16643. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  16644. // cues to have identical time-intervals, but if the text is also identical
  16645. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  16646. // "overlaps" VTT segments)
  16647. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  16648. this.handleAppendsDone_();
  16649. }
  16650. handleData_() {// noop as we shouldn't be getting video/audio data captions
  16651. // that we do not support here.
  16652. }
  16653. updateTimingInfoEnd_() {// noop
  16654. }
  16655. /**
  16656. * Uses the WebVTT parser to parse the segment response
  16657. *
  16658. * @throws NoVttJsError
  16659. *
  16660. * @param {Object} segmentInfo
  16661. * a segment info object that describes the current segment
  16662. * @private
  16663. */
  16664. parseVTTCues_(segmentInfo) {
  16665. let decoder;
  16666. let decodeBytesToString = false;
  16667. if (typeof window__default["default"].WebVTT !== 'function') {
  16668. // caller is responsible for exception handling.
  16669. throw new NoVttJsError();
  16670. }
  16671. if (typeof window__default["default"].TextDecoder === 'function') {
  16672. decoder = new window__default["default"].TextDecoder('utf8');
  16673. } else {
  16674. decoder = window__default["default"].WebVTT.StringDecoder();
  16675. decodeBytesToString = true;
  16676. }
  16677. const parser = new window__default["default"].WebVTT.Parser(window__default["default"], window__default["default"].vttjs, decoder);
  16678. segmentInfo.cues = [];
  16679. segmentInfo.timestampmap = {
  16680. MPEGTS: 0,
  16681. LOCAL: 0
  16682. };
  16683. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  16684. parser.ontimestampmap = map => {
  16685. segmentInfo.timestampmap = map;
  16686. };
  16687. parser.onparsingerror = error => {
  16688. videojs__default["default"].log.warn('Error encountered when parsing cues: ' + error.message);
  16689. };
  16690. if (segmentInfo.segment.map) {
  16691. let mapData = segmentInfo.segment.map.bytes;
  16692. if (decodeBytesToString) {
  16693. mapData = uint8ToUtf8(mapData);
  16694. }
  16695. parser.parse(mapData);
  16696. }
  16697. let segmentData = segmentInfo.bytes;
  16698. if (decodeBytesToString) {
  16699. segmentData = uint8ToUtf8(segmentData);
  16700. }
  16701. parser.parse(segmentData);
  16702. parser.flush();
  16703. }
  16704. /**
  16705. * Updates the start and end times of any cues parsed by the WebVTT parser using
  16706. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  16707. * from the SyncController
  16708. *
  16709. * @param {Object} segmentInfo
  16710. * a segment info object that describes the current segment
  16711. * @param {Object} mappingObj
  16712. * object containing a mapping from TS to media time
  16713. * @param {Object} playlist
  16714. * the playlist object containing the segment
  16715. * @private
  16716. */
  16717. updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  16718. const segment = segmentInfo.segment;
  16719. if (!mappingObj) {
  16720. // If the sync controller does not have a mapping of TS to Media Time for the
  16721. // timeline, then we don't have enough information to update the cue
  16722. // start/end times
  16723. return;
  16724. }
  16725. if (!segmentInfo.cues.length) {
  16726. // If there are no cues, we also do not have enough information to figure out
  16727. // segment timing. Mark that the segment contains no cues so we don't re-request
  16728. // an empty segment.
  16729. segment.empty = true;
  16730. return;
  16731. }
  16732. const timestampmap = segmentInfo.timestampmap;
  16733. const diff = timestampmap.MPEGTS / clock.ONE_SECOND_IN_TS - timestampmap.LOCAL + mappingObj.mapping;
  16734. segmentInfo.cues.forEach(cue => {
  16735. // First convert cue time to TS time using the timestamp-map provided within the vtt
  16736. cue.startTime += diff;
  16737. cue.endTime += diff;
  16738. });
  16739. if (!playlist.syncInfo) {
  16740. const firstStart = segmentInfo.cues[0].startTime;
  16741. const lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  16742. playlist.syncInfo = {
  16743. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  16744. time: Math.min(firstStart, lastStart - segment.duration)
  16745. };
  16746. }
  16747. }
  16748. }
  16749. /**
  16750. * @file ad-cue-tags.js
  16751. */
  16752. /**
  16753. * Searches for an ad cue that overlaps with the given mediaTime
  16754. *
  16755. * @param {Object} track
  16756. * the track to find the cue for
  16757. *
  16758. * @param {number} mediaTime
  16759. * the time to find the cue at
  16760. *
  16761. * @return {Object|null}
  16762. * the found cue or null
  16763. */
  16764. const findAdCue = function (track, mediaTime) {
  16765. const cues = track.cues;
  16766. for (let i = 0; i < cues.length; i++) {
  16767. const cue = cues[i];
  16768. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  16769. return cue;
  16770. }
  16771. }
  16772. return null;
  16773. };
  16774. const updateAdCues = function (media, track, offset = 0) {
  16775. if (!media.segments) {
  16776. return;
  16777. }
  16778. let mediaTime = offset;
  16779. let cue;
  16780. for (let i = 0; i < media.segments.length; i++) {
  16781. const segment = media.segments[i];
  16782. if (!cue) {
  16783. // Since the cues will span for at least the segment duration, adding a fudge
  16784. // factor of half segment duration will prevent duplicate cues from being
  16785. // created when timing info is not exact (e.g. cue start time initialized
  16786. // at 10.006677, but next call mediaTime is 10.003332 )
  16787. cue = findAdCue(track, mediaTime + segment.duration / 2);
  16788. }
  16789. if (cue) {
  16790. if ('cueIn' in segment) {
  16791. // Found a CUE-IN so end the cue
  16792. cue.endTime = mediaTime;
  16793. cue.adEndTime = mediaTime;
  16794. mediaTime += segment.duration;
  16795. cue = null;
  16796. continue;
  16797. }
  16798. if (mediaTime < cue.endTime) {
  16799. // Already processed this mediaTime for this cue
  16800. mediaTime += segment.duration;
  16801. continue;
  16802. } // otherwise extend cue until a CUE-IN is found
  16803. cue.endTime += segment.duration;
  16804. } else {
  16805. if ('cueOut' in segment) {
  16806. cue = new window__default["default"].VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  16807. cue.adStartTime = mediaTime; // Assumes tag format to be
  16808. // #EXT-X-CUE-OUT:30
  16809. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  16810. track.addCue(cue);
  16811. }
  16812. if ('cueOutCont' in segment) {
  16813. // Entered into the middle of an ad cue
  16814. // Assumes tag formate to be
  16815. // #EXT-X-CUE-OUT-CONT:10/30
  16816. const [adOffset, adTotal] = segment.cueOutCont.split('/').map(parseFloat);
  16817. cue = new window__default["default"].VTTCue(mediaTime, mediaTime + segment.duration, '');
  16818. cue.adStartTime = mediaTime - adOffset;
  16819. cue.adEndTime = cue.adStartTime + adTotal;
  16820. track.addCue(cue);
  16821. }
  16822. }
  16823. mediaTime += segment.duration;
  16824. }
  16825. };
  16826. /**
  16827. * @file sync-controller.js
  16828. */
  16829. // synchronize expired playlist segments.
  16830. // the max media sequence diff is 48 hours of live stream
  16831. // content with two second segments. Anything larger than that
  16832. // will likely be invalid.
  16833. const MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  16834. const syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  16835. // the equivalence display-time 0 === segment-index 0
  16836. {
  16837. name: 'VOD',
  16838. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16839. if (duration !== Infinity) {
  16840. const syncPoint = {
  16841. time: 0,
  16842. segmentIndex: 0,
  16843. partIndex: null
  16844. };
  16845. return syncPoint;
  16846. }
  16847. return null;
  16848. }
  16849. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  16850. {
  16851. name: 'ProgramDateTime',
  16852. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16853. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  16854. return null;
  16855. }
  16856. let syncPoint = null;
  16857. let lastDistance = null;
  16858. const partsAndSegments = getPartsAndSegments(playlist);
  16859. currentTime = currentTime || 0;
  16860. for (let i = 0; i < partsAndSegments.length; i++) {
  16861. // start from the end and loop backwards for live
  16862. // or start from the front and loop forwards for non-live
  16863. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  16864. const partAndSegment = partsAndSegments[index];
  16865. const segment = partAndSegment.segment;
  16866. const datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  16867. if (!datetimeMapping || !segment.dateTimeObject) {
  16868. continue;
  16869. }
  16870. const segmentTime = segment.dateTimeObject.getTime() / 1000;
  16871. let start = segmentTime + datetimeMapping; // take part duration into account.
  16872. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  16873. for (let z = 0; z < partAndSegment.partIndex; z++) {
  16874. start += segment.parts[z].duration;
  16875. }
  16876. }
  16877. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  16878. // currentTime and can stop looking for better candidates
  16879. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  16880. break;
  16881. }
  16882. lastDistance = distance;
  16883. syncPoint = {
  16884. time: start,
  16885. segmentIndex: partAndSegment.segmentIndex,
  16886. partIndex: partAndSegment.partIndex
  16887. };
  16888. }
  16889. return syncPoint;
  16890. }
  16891. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  16892. // segment in the current timeline with timing data
  16893. {
  16894. name: 'Segment',
  16895. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16896. let syncPoint = null;
  16897. let lastDistance = null;
  16898. currentTime = currentTime || 0;
  16899. const partsAndSegments = getPartsAndSegments(playlist);
  16900. for (let i = 0; i < partsAndSegments.length; i++) {
  16901. // start from the end and loop backwards for live
  16902. // or start from the front and loop forwards for non-live
  16903. const index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  16904. const partAndSegment = partsAndSegments[index];
  16905. const segment = partAndSegment.segment;
  16906. const start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  16907. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  16908. const distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  16909. // currentTime and can stop looking for better candidates
  16910. if (lastDistance !== null && lastDistance < distance) {
  16911. break;
  16912. }
  16913. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  16914. lastDistance = distance;
  16915. syncPoint = {
  16916. time: start,
  16917. segmentIndex: partAndSegment.segmentIndex,
  16918. partIndex: partAndSegment.partIndex
  16919. };
  16920. }
  16921. }
  16922. }
  16923. return syncPoint;
  16924. }
  16925. }, // Stategy "Discontinuity": We have a discontinuity with a known
  16926. // display-time
  16927. {
  16928. name: 'Discontinuity',
  16929. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16930. let syncPoint = null;
  16931. currentTime = currentTime || 0;
  16932. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  16933. let lastDistance = null;
  16934. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  16935. const segmentIndex = playlist.discontinuityStarts[i];
  16936. const discontinuity = playlist.discontinuitySequence + i + 1;
  16937. const discontinuitySync = syncController.discontinuities[discontinuity];
  16938. if (discontinuitySync) {
  16939. const distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  16940. // currentTime and can stop looking for better candidates
  16941. if (lastDistance !== null && lastDistance < distance) {
  16942. break;
  16943. }
  16944. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  16945. lastDistance = distance;
  16946. syncPoint = {
  16947. time: discontinuitySync.time,
  16948. segmentIndex,
  16949. partIndex: null
  16950. };
  16951. }
  16952. }
  16953. }
  16954. }
  16955. return syncPoint;
  16956. }
  16957. }, // Stategy "Playlist": We have a playlist with a known mapping of
  16958. // segment index to display time
  16959. {
  16960. name: 'Playlist',
  16961. run: (syncController, playlist, duration, currentTimeline, currentTime) => {
  16962. if (playlist.syncInfo) {
  16963. const syncPoint = {
  16964. time: playlist.syncInfo.time,
  16965. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  16966. partIndex: null
  16967. };
  16968. return syncPoint;
  16969. }
  16970. return null;
  16971. }
  16972. }];
  16973. class SyncController extends videojs__default["default"].EventTarget {
  16974. constructor(options = {}) {
  16975. super(); // ...for synching across variants
  16976. this.timelines = [];
  16977. this.discontinuities = [];
  16978. this.timelineToDatetimeMappings = {};
  16979. this.logger_ = logger('SyncController');
  16980. }
  16981. /**
  16982. * Find a sync-point for the playlist specified
  16983. *
  16984. * A sync-point is defined as a known mapping from display-time to
  16985. * a segment-index in the current playlist.
  16986. *
  16987. * @param {Playlist} playlist
  16988. * The playlist that needs a sync-point
  16989. * @param {number} duration
  16990. * Duration of the MediaSource (Infinite if playing a live source)
  16991. * @param {number} currentTimeline
  16992. * The last timeline from which a segment was loaded
  16993. * @return {Object}
  16994. * A sync-point object
  16995. */
  16996. getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  16997. const syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  16998. if (!syncPoints.length) {
  16999. // Signal that we need to attempt to get a sync-point manually
  17000. // by fetching a segment in the playlist and constructing
  17001. // a sync-point from that information
  17002. return null;
  17003. } // Now find the sync-point that is closest to the currentTime because
  17004. // that should result in the most accurate guess about which segment
  17005. // to fetch
  17006. return this.selectSyncPoint_(syncPoints, {
  17007. key: 'time',
  17008. value: currentTime
  17009. });
  17010. }
  17011. /**
  17012. * Calculate the amount of time that has expired off the playlist during playback
  17013. *
  17014. * @param {Playlist} playlist
  17015. * Playlist object to calculate expired from
  17016. * @param {number} duration
  17017. * Duration of the MediaSource (Infinity if playling a live source)
  17018. * @return {number|null}
  17019. * The amount of time that has expired off the playlist during playback. Null
  17020. * if no sync-points for the playlist can be found.
  17021. */
  17022. getExpiredTime(playlist, duration) {
  17023. if (!playlist || !playlist.segments) {
  17024. return null;
  17025. }
  17026. const syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  17027. if (!syncPoints.length) {
  17028. return null;
  17029. }
  17030. const syncPoint = this.selectSyncPoint_(syncPoints, {
  17031. key: 'segmentIndex',
  17032. value: 0
  17033. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  17034. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  17035. if (syncPoint.segmentIndex > 0) {
  17036. syncPoint.time *= -1;
  17037. }
  17038. return Math.abs(syncPoint.time + sumDurations({
  17039. defaultDuration: playlist.targetDuration,
  17040. durationList: playlist.segments,
  17041. startIndex: syncPoint.segmentIndex,
  17042. endIndex: 0
  17043. }));
  17044. }
  17045. /**
  17046. * Runs each sync-point strategy and returns a list of sync-points returned by the
  17047. * strategies
  17048. *
  17049. * @private
  17050. * @param {Playlist} playlist
  17051. * The playlist that needs a sync-point
  17052. * @param {number} duration
  17053. * Duration of the MediaSource (Infinity if playing a live source)
  17054. * @param {number} currentTimeline
  17055. * The last timeline from which a segment was loaded
  17056. * @return {Array}
  17057. * A list of sync-point objects
  17058. */
  17059. runStrategies_(playlist, duration, currentTimeline, currentTime) {
  17060. const syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  17061. for (let i = 0; i < syncPointStrategies.length; i++) {
  17062. const strategy = syncPointStrategies[i];
  17063. const syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  17064. if (syncPoint) {
  17065. syncPoint.strategy = strategy.name;
  17066. syncPoints.push({
  17067. strategy: strategy.name,
  17068. syncPoint
  17069. });
  17070. }
  17071. }
  17072. return syncPoints;
  17073. }
  17074. /**
  17075. * Selects the sync-point nearest the specified target
  17076. *
  17077. * @private
  17078. * @param {Array} syncPoints
  17079. * List of sync-points to select from
  17080. * @param {Object} target
  17081. * Object specifying the property and value we are targeting
  17082. * @param {string} target.key
  17083. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  17084. * @param {number} target.value
  17085. * The value to target for the specified key.
  17086. * @return {Object}
  17087. * The sync-point nearest the target
  17088. */
  17089. selectSyncPoint_(syncPoints, target) {
  17090. let bestSyncPoint = syncPoints[0].syncPoint;
  17091. let bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  17092. let bestStrategy = syncPoints[0].strategy;
  17093. for (let i = 1; i < syncPoints.length; i++) {
  17094. const newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  17095. if (newDistance < bestDistance) {
  17096. bestDistance = newDistance;
  17097. bestSyncPoint = syncPoints[i].syncPoint;
  17098. bestStrategy = syncPoints[i].strategy;
  17099. }
  17100. }
  17101. 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}` : '') + ']');
  17102. return bestSyncPoint;
  17103. }
  17104. /**
  17105. * Save any meta-data present on the segments when segments leave
  17106. * the live window to the playlist to allow for synchronization at the
  17107. * playlist level later.
  17108. *
  17109. * @param {Playlist} oldPlaylist - The previous active playlist
  17110. * @param {Playlist} newPlaylist - The updated and most current playlist
  17111. */
  17112. saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  17113. const mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  17114. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  17115. videojs__default["default"].log.warn(`Not saving expired segment info. Media sequence gap ${mediaSequenceDiff} is too large.`);
  17116. return;
  17117. } // When a segment expires from the playlist and it has a start time
  17118. // save that information as a possible sync-point reference in future
  17119. for (let i = mediaSequenceDiff - 1; i >= 0; i--) {
  17120. const lastRemovedSegment = oldPlaylist.segments[i];
  17121. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  17122. newPlaylist.syncInfo = {
  17123. mediaSequence: oldPlaylist.mediaSequence + i,
  17124. time: lastRemovedSegment.start
  17125. };
  17126. this.logger_(`playlist refresh sync: [time:${newPlaylist.syncInfo.time},` + ` mediaSequence: ${newPlaylist.syncInfo.mediaSequence}]`);
  17127. this.trigger('syncinfoupdate');
  17128. break;
  17129. }
  17130. }
  17131. }
  17132. /**
  17133. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  17134. * before segments start to load.
  17135. *
  17136. * @param {Playlist} playlist - The currently active playlist
  17137. */
  17138. setDateTimeMappingForStart(playlist) {
  17139. // It's possible for the playlist to be updated before playback starts, meaning time
  17140. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  17141. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  17142. // unless the mappings are cleared.
  17143. this.timelineToDatetimeMappings = {};
  17144. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  17145. const firstSegment = playlist.segments[0];
  17146. const playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  17147. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  17148. }
  17149. }
  17150. /**
  17151. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  17152. * based on the latest timing information.
  17153. *
  17154. * @param {Object} options
  17155. * Options object
  17156. * @param {SegmentInfo} options.segmentInfo
  17157. * The current active request information
  17158. * @param {boolean} options.shouldSaveTimelineMapping
  17159. * If there's a timeline change, determines if the timeline mapping should be
  17160. * saved for timeline mapping and program date time mappings.
  17161. */
  17162. saveSegmentTimingInfo({
  17163. segmentInfo,
  17164. shouldSaveTimelineMapping
  17165. }) {
  17166. const didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  17167. const segment = segmentInfo.segment;
  17168. if (didCalculateSegmentTimeMapping) {
  17169. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  17170. // now with segment timing information
  17171. if (!segmentInfo.playlist.syncInfo) {
  17172. segmentInfo.playlist.syncInfo = {
  17173. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  17174. time: segment.start
  17175. };
  17176. }
  17177. }
  17178. const dateTime = segment.dateTimeObject;
  17179. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  17180. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  17181. }
  17182. }
  17183. timestampOffsetForTimeline(timeline) {
  17184. if (typeof this.timelines[timeline] === 'undefined') {
  17185. return null;
  17186. }
  17187. return this.timelines[timeline].time;
  17188. }
  17189. mappingForTimeline(timeline) {
  17190. if (typeof this.timelines[timeline] === 'undefined') {
  17191. return null;
  17192. }
  17193. return this.timelines[timeline].mapping;
  17194. }
  17195. /**
  17196. * Use the "media time" for a segment to generate a mapping to "display time" and
  17197. * save that display time to the segment.
  17198. *
  17199. * @private
  17200. * @param {SegmentInfo} segmentInfo
  17201. * The current active request information
  17202. * @param {Object} timingInfo
  17203. * The start and end time of the current segment in "media time"
  17204. * @param {boolean} shouldSaveTimelineMapping
  17205. * If there's a timeline change, determines if the timeline mapping should be
  17206. * saved in timelines.
  17207. * @return {boolean}
  17208. * Returns false if segment time mapping could not be calculated
  17209. */
  17210. calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  17211. // TODO: remove side effects
  17212. const segment = segmentInfo.segment;
  17213. const part = segmentInfo.part;
  17214. let mappingObj = this.timelines[segmentInfo.timeline];
  17215. let start;
  17216. let end;
  17217. if (typeof segmentInfo.timestampOffset === 'number') {
  17218. mappingObj = {
  17219. time: segmentInfo.startOfSegment,
  17220. mapping: segmentInfo.startOfSegment - timingInfo.start
  17221. };
  17222. if (shouldSaveTimelineMapping) {
  17223. this.timelines[segmentInfo.timeline] = mappingObj;
  17224. this.trigger('timestampoffset');
  17225. this.logger_(`time mapping for timeline ${segmentInfo.timeline}: ` + `[time: ${mappingObj.time}] [mapping: ${mappingObj.mapping}]`);
  17226. }
  17227. start = segmentInfo.startOfSegment;
  17228. end = timingInfo.end + mappingObj.mapping;
  17229. } else if (mappingObj) {
  17230. start = timingInfo.start + mappingObj.mapping;
  17231. end = timingInfo.end + mappingObj.mapping;
  17232. } else {
  17233. return false;
  17234. }
  17235. if (part) {
  17236. part.start = start;
  17237. part.end = end;
  17238. } // If we don't have a segment start yet or the start value we got
  17239. // is less than our current segment.start value, save a new start value.
  17240. // We have to do this because parts will have segment timing info saved
  17241. // multiple times and we want segment start to be the earliest part start
  17242. // value for that segment.
  17243. if (!segment.start || start < segment.start) {
  17244. segment.start = start;
  17245. }
  17246. segment.end = end;
  17247. return true;
  17248. }
  17249. /**
  17250. * Each time we have discontinuity in the playlist, attempt to calculate the location
  17251. * in display of the start of the discontinuity and save that. We also save an accuracy
  17252. * value so that we save values with the most accuracy (closest to 0.)
  17253. *
  17254. * @private
  17255. * @param {SegmentInfo} segmentInfo - The current active request information
  17256. */
  17257. saveDiscontinuitySyncInfo_(segmentInfo) {
  17258. const playlist = segmentInfo.playlist;
  17259. const segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  17260. // the start of the range and it's accuracy is 0 (greater accuracy values
  17261. // mean more approximation)
  17262. if (segment.discontinuity) {
  17263. this.discontinuities[segment.timeline] = {
  17264. time: segment.start,
  17265. accuracy: 0
  17266. };
  17267. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  17268. // Search for future discontinuities that we can provide better timing
  17269. // information for and save that information for sync purposes
  17270. for (let i = 0; i < playlist.discontinuityStarts.length; i++) {
  17271. const segmentIndex = playlist.discontinuityStarts[i];
  17272. const discontinuity = playlist.discontinuitySequence + i + 1;
  17273. const mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  17274. const accuracy = Math.abs(mediaIndexDiff);
  17275. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  17276. let time;
  17277. if (mediaIndexDiff < 0) {
  17278. time = segment.start - sumDurations({
  17279. defaultDuration: playlist.targetDuration,
  17280. durationList: playlist.segments,
  17281. startIndex: segmentInfo.mediaIndex,
  17282. endIndex: segmentIndex
  17283. });
  17284. } else {
  17285. time = segment.end + sumDurations({
  17286. defaultDuration: playlist.targetDuration,
  17287. durationList: playlist.segments,
  17288. startIndex: segmentInfo.mediaIndex + 1,
  17289. endIndex: segmentIndex
  17290. });
  17291. }
  17292. this.discontinuities[discontinuity] = {
  17293. time,
  17294. accuracy
  17295. };
  17296. }
  17297. }
  17298. }
  17299. }
  17300. dispose() {
  17301. this.trigger('dispose');
  17302. this.off();
  17303. }
  17304. }
  17305. /**
  17306. * The TimelineChangeController acts as a source for segment loaders to listen for and
  17307. * keep track of latest and pending timeline changes. This is useful to ensure proper
  17308. * sync, as each loader may need to make a consideration for what timeline the other
  17309. * loader is on before making changes which could impact the other loader's media.
  17310. *
  17311. * @class TimelineChangeController
  17312. * @extends videojs.EventTarget
  17313. */
  17314. class TimelineChangeController extends videojs__default["default"].EventTarget {
  17315. constructor() {
  17316. super();
  17317. this.pendingTimelineChanges_ = {};
  17318. this.lastTimelineChanges_ = {};
  17319. }
  17320. clearPendingTimelineChange(type) {
  17321. this.pendingTimelineChanges_[type] = null;
  17322. this.trigger('pendingtimelinechange');
  17323. }
  17324. pendingTimelineChange({
  17325. type,
  17326. from,
  17327. to
  17328. }) {
  17329. if (typeof from === 'number' && typeof to === 'number') {
  17330. this.pendingTimelineChanges_[type] = {
  17331. type,
  17332. from,
  17333. to
  17334. };
  17335. this.trigger('pendingtimelinechange');
  17336. }
  17337. return this.pendingTimelineChanges_[type];
  17338. }
  17339. lastTimelineChange({
  17340. type,
  17341. from,
  17342. to
  17343. }) {
  17344. if (typeof from === 'number' && typeof to === 'number') {
  17345. this.lastTimelineChanges_[type] = {
  17346. type,
  17347. from,
  17348. to
  17349. };
  17350. delete this.pendingTimelineChanges_[type];
  17351. this.trigger('timelinechange');
  17352. }
  17353. return this.lastTimelineChanges_[type];
  17354. }
  17355. dispose() {
  17356. this.trigger('dispose');
  17357. this.pendingTimelineChanges_ = {};
  17358. this.lastTimelineChanges_ = {};
  17359. this.off();
  17360. }
  17361. }
  17362. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  17363. const workerCode = transform(getWorkerString(function () {
  17364. /**
  17365. * @file stream.js
  17366. */
  17367. /**
  17368. * A lightweight readable stream implemention that handles event dispatching.
  17369. *
  17370. * @class Stream
  17371. */
  17372. var Stream = /*#__PURE__*/function () {
  17373. function Stream() {
  17374. this.listeners = {};
  17375. }
  17376. /**
  17377. * Add a listener for a specified event type.
  17378. *
  17379. * @param {string} type the event name
  17380. * @param {Function} listener the callback to be invoked when an event of
  17381. * the specified type occurs
  17382. */
  17383. var _proto = Stream.prototype;
  17384. _proto.on = function on(type, listener) {
  17385. if (!this.listeners[type]) {
  17386. this.listeners[type] = [];
  17387. }
  17388. this.listeners[type].push(listener);
  17389. }
  17390. /**
  17391. * Remove a listener for a specified event type.
  17392. *
  17393. * @param {string} type the event name
  17394. * @param {Function} listener a function previously registered for this
  17395. * type of event through `on`
  17396. * @return {boolean} if we could turn it off or not
  17397. */
  17398. ;
  17399. _proto.off = function off(type, listener) {
  17400. if (!this.listeners[type]) {
  17401. return false;
  17402. }
  17403. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  17404. // In Video.js we slice listener functions
  17405. // on trigger so that it does not mess up the order
  17406. // while we loop through.
  17407. //
  17408. // Here we slice on off so that the loop in trigger
  17409. // can continue using it's old reference to loop without
  17410. // messing up the order.
  17411. this.listeners[type] = this.listeners[type].slice(0);
  17412. this.listeners[type].splice(index, 1);
  17413. return index > -1;
  17414. }
  17415. /**
  17416. * Trigger an event of the specified type on this stream. Any additional
  17417. * arguments to this function are passed as parameters to event listeners.
  17418. *
  17419. * @param {string} type the event name
  17420. */
  17421. ;
  17422. _proto.trigger = function trigger(type) {
  17423. var callbacks = this.listeners[type];
  17424. if (!callbacks) {
  17425. return;
  17426. } // Slicing the arguments on every invocation of this method
  17427. // can add a significant amount of overhead. Avoid the
  17428. // intermediate object creation for the common case of a
  17429. // single callback argument
  17430. if (arguments.length === 2) {
  17431. var length = callbacks.length;
  17432. for (var i = 0; i < length; ++i) {
  17433. callbacks[i].call(this, arguments[1]);
  17434. }
  17435. } else {
  17436. var args = Array.prototype.slice.call(arguments, 1);
  17437. var _length = callbacks.length;
  17438. for (var _i = 0; _i < _length; ++_i) {
  17439. callbacks[_i].apply(this, args);
  17440. }
  17441. }
  17442. }
  17443. /**
  17444. * Destroys the stream and cleans up.
  17445. */
  17446. ;
  17447. _proto.dispose = function dispose() {
  17448. this.listeners = {};
  17449. }
  17450. /**
  17451. * Forwards all `data` events on this stream to the destination stream. The
  17452. * destination stream should provide a method `push` to receive the data
  17453. * events as they arrive.
  17454. *
  17455. * @param {Stream} destination the stream that will receive all `data` events
  17456. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  17457. */
  17458. ;
  17459. _proto.pipe = function pipe(destination) {
  17460. this.on('data', function (data) {
  17461. destination.push(data);
  17462. });
  17463. };
  17464. return Stream;
  17465. }();
  17466. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  17467. /**
  17468. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  17469. *
  17470. * @param padded {Uint8Array} unencrypted bytes that have been padded
  17471. * @return {Uint8Array} the unpadded bytes
  17472. * @see http://tools.ietf.org/html/rfc5652
  17473. */
  17474. function unpad(padded) {
  17475. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  17476. }
  17477. /*! @name aes-decrypter @version 4.0.1 @license Apache-2.0 */
  17478. /**
  17479. * @file aes.js
  17480. *
  17481. * This file contains an adaptation of the AES decryption algorithm
  17482. * from the Standford Javascript Cryptography Library. That work is
  17483. * covered by the following copyright and permissions notice:
  17484. *
  17485. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  17486. * All rights reserved.
  17487. *
  17488. * Redistribution and use in source and binary forms, with or without
  17489. * modification, are permitted provided that the following conditions are
  17490. * met:
  17491. *
  17492. * 1. Redistributions of source code must retain the above copyright
  17493. * notice, this list of conditions and the following disclaimer.
  17494. *
  17495. * 2. Redistributions in binary form must reproduce the above
  17496. * copyright notice, this list of conditions and the following
  17497. * disclaimer in the documentation and/or other materials provided
  17498. * with the distribution.
  17499. *
  17500. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  17501. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  17502. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17503. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  17504. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  17505. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  17506. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  17507. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  17508. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  17509. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  17510. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  17511. *
  17512. * The views and conclusions contained in the software and documentation
  17513. * are those of the authors and should not be interpreted as representing
  17514. * official policies, either expressed or implied, of the authors.
  17515. */
  17516. /**
  17517. * Expand the S-box tables.
  17518. *
  17519. * @private
  17520. */
  17521. const precompute = function () {
  17522. const tables = [[[], [], [], [], []], [[], [], [], [], []]];
  17523. const encTable = tables[0];
  17524. const decTable = tables[1];
  17525. const sbox = encTable[4];
  17526. const sboxInv = decTable[4];
  17527. let i;
  17528. let x;
  17529. let xInv;
  17530. const d = [];
  17531. const th = [];
  17532. let x2;
  17533. let x4;
  17534. let x8;
  17535. let s;
  17536. let tEnc;
  17537. let tDec; // Compute double and third tables
  17538. for (i = 0; i < 256; i++) {
  17539. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  17540. }
  17541. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  17542. // Compute sbox
  17543. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  17544. s = s >> 8 ^ s & 255 ^ 99;
  17545. sbox[x] = s;
  17546. sboxInv[s] = x; // Compute MixColumns
  17547. x8 = d[x4 = d[x2 = d[x]]];
  17548. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  17549. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  17550. for (i = 0; i < 4; i++) {
  17551. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  17552. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  17553. }
  17554. } // Compactify. Considerable speedup on Firefox.
  17555. for (i = 0; i < 5; i++) {
  17556. encTable[i] = encTable[i].slice(0);
  17557. decTable[i] = decTable[i].slice(0);
  17558. }
  17559. return tables;
  17560. };
  17561. let aesTables = null;
  17562. /**
  17563. * Schedule out an AES key for both encryption and decryption. This
  17564. * is a low-level class. Use a cipher mode to do bulk encryption.
  17565. *
  17566. * @class AES
  17567. * @param key {Array} The key as an array of 4, 6 or 8 words.
  17568. */
  17569. class AES {
  17570. constructor(key) {
  17571. /**
  17572. * The expanded S-box and inverse S-box tables. These will be computed
  17573. * on the client so that we don't have to send them down the wire.
  17574. *
  17575. * There are two tables, _tables[0] is for encryption and
  17576. * _tables[1] is for decryption.
  17577. *
  17578. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  17579. * last (_tables[01][4]) is the S-box itself.
  17580. *
  17581. * @private
  17582. */
  17583. // if we have yet to precompute the S-box tables
  17584. // do so now
  17585. if (!aesTables) {
  17586. aesTables = precompute();
  17587. } // then make a copy of that object for use
  17588. 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()]];
  17589. let i;
  17590. let j;
  17591. let tmp;
  17592. const sbox = this._tables[0][4];
  17593. const decTable = this._tables[1];
  17594. const keyLen = key.length;
  17595. let rcon = 1;
  17596. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  17597. throw new Error('Invalid aes key size');
  17598. }
  17599. const encKey = key.slice(0);
  17600. const decKey = [];
  17601. this._key = [encKey, decKey]; // schedule encryption keys
  17602. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  17603. tmp = encKey[i - 1]; // apply sbox
  17604. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  17605. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  17606. if (i % keyLen === 0) {
  17607. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  17608. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  17609. }
  17610. }
  17611. encKey[i] = encKey[i - keyLen] ^ tmp;
  17612. } // schedule decryption keys
  17613. for (j = 0; i; j++, i--) {
  17614. tmp = encKey[j & 3 ? i : i - 4];
  17615. if (i <= 4 || j < 4) {
  17616. decKey[j] = tmp;
  17617. } else {
  17618. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  17619. }
  17620. }
  17621. }
  17622. /**
  17623. * Decrypt 16 bytes, specified as four 32-bit words.
  17624. *
  17625. * @param {number} encrypted0 the first word to decrypt
  17626. * @param {number} encrypted1 the second word to decrypt
  17627. * @param {number} encrypted2 the third word to decrypt
  17628. * @param {number} encrypted3 the fourth word to decrypt
  17629. * @param {Int32Array} out the array to write the decrypted words
  17630. * into
  17631. * @param {number} offset the offset into the output array to start
  17632. * writing results
  17633. * @return {Array} The plaintext.
  17634. */
  17635. decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  17636. const key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  17637. let a = encrypted0 ^ key[0];
  17638. let b = encrypted3 ^ key[1];
  17639. let c = encrypted2 ^ key[2];
  17640. let d = encrypted1 ^ key[3];
  17641. let a2;
  17642. let b2;
  17643. let c2; // key.length === 2 ?
  17644. const nInnerRounds = key.length / 4 - 2;
  17645. let i;
  17646. let kIndex = 4;
  17647. const table = this._tables[1]; // load up the tables
  17648. const table0 = table[0];
  17649. const table1 = table[1];
  17650. const table2 = table[2];
  17651. const table3 = table[3];
  17652. const sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  17653. for (i = 0; i < nInnerRounds; i++) {
  17654. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  17655. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  17656. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  17657. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  17658. kIndex += 4;
  17659. a = a2;
  17660. b = b2;
  17661. c = c2;
  17662. } // Last round.
  17663. for (i = 0; i < 4; i++) {
  17664. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  17665. a2 = a;
  17666. a = b;
  17667. b = c;
  17668. c = d;
  17669. d = a2;
  17670. }
  17671. }
  17672. }
  17673. /**
  17674. * @file async-stream.js
  17675. */
  17676. /**
  17677. * A wrapper around the Stream class to use setTimeout
  17678. * and run stream "jobs" Asynchronously
  17679. *
  17680. * @class AsyncStream
  17681. * @extends Stream
  17682. */
  17683. class AsyncStream extends Stream {
  17684. constructor() {
  17685. super(Stream);
  17686. this.jobs = [];
  17687. this.delay = 1;
  17688. this.timeout_ = null;
  17689. }
  17690. /**
  17691. * process an async job
  17692. *
  17693. * @private
  17694. */
  17695. processJob_() {
  17696. this.jobs.shift()();
  17697. if (this.jobs.length) {
  17698. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  17699. } else {
  17700. this.timeout_ = null;
  17701. }
  17702. }
  17703. /**
  17704. * push a job into the stream
  17705. *
  17706. * @param {Function} job the job to push into the stream
  17707. */
  17708. push(job) {
  17709. this.jobs.push(job);
  17710. if (!this.timeout_) {
  17711. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  17712. }
  17713. }
  17714. }
  17715. /**
  17716. * @file decrypter.js
  17717. *
  17718. * An asynchronous implementation of AES-128 CBC decryption with
  17719. * PKCS#7 padding.
  17720. */
  17721. /**
  17722. * Convert network-order (big-endian) bytes into their little-endian
  17723. * representation.
  17724. */
  17725. const ntoh = function (word) {
  17726. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  17727. };
  17728. /**
  17729. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  17730. *
  17731. * @param {Uint8Array} encrypted the encrypted bytes
  17732. * @param {Uint32Array} key the bytes of the decryption key
  17733. * @param {Uint32Array} initVector the initialization vector (IV) to
  17734. * use for the first round of CBC.
  17735. * @return {Uint8Array} the decrypted bytes
  17736. *
  17737. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  17738. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  17739. * @see https://tools.ietf.org/html/rfc2315
  17740. */
  17741. const decrypt = function (encrypted, key, initVector) {
  17742. // word-level access to the encrypted bytes
  17743. const encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  17744. const decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  17745. const decrypted = new Uint8Array(encrypted.byteLength);
  17746. const decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  17747. // decrypted data
  17748. let init0;
  17749. let init1;
  17750. let init2;
  17751. let init3;
  17752. let encrypted0;
  17753. let encrypted1;
  17754. let encrypted2;
  17755. let encrypted3; // iteration variable
  17756. let wordIx; // pull out the words of the IV to ensure we don't modify the
  17757. // passed-in reference and easier access
  17758. init0 = initVector[0];
  17759. init1 = initVector[1];
  17760. init2 = initVector[2];
  17761. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  17762. // to each decrypted block
  17763. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  17764. // convert big-endian (network order) words into little-endian
  17765. // (javascript order)
  17766. encrypted0 = ntoh(encrypted32[wordIx]);
  17767. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  17768. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  17769. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  17770. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  17771. // plaintext
  17772. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  17773. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  17774. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  17775. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  17776. init0 = encrypted0;
  17777. init1 = encrypted1;
  17778. init2 = encrypted2;
  17779. init3 = encrypted3;
  17780. }
  17781. return decrypted;
  17782. };
  17783. /**
  17784. * The `Decrypter` class that manages decryption of AES
  17785. * data through `AsyncStream` objects and the `decrypt`
  17786. * function
  17787. *
  17788. * @param {Uint8Array} encrypted the encrypted bytes
  17789. * @param {Uint32Array} key the bytes of the decryption key
  17790. * @param {Uint32Array} initVector the initialization vector (IV) to
  17791. * @param {Function} done the function to run when done
  17792. * @class Decrypter
  17793. */
  17794. class Decrypter {
  17795. constructor(encrypted, key, initVector, done) {
  17796. const step = Decrypter.STEP;
  17797. const encrypted32 = new Int32Array(encrypted.buffer);
  17798. const decrypted = new Uint8Array(encrypted.byteLength);
  17799. let i = 0;
  17800. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  17801. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  17802. for (i = step; i < encrypted32.length; i += step) {
  17803. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  17804. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  17805. } // invoke the done() callback when everything is finished
  17806. this.asyncStream_.push(function () {
  17807. // remove pkcs#7 padding from the decrypted bytes
  17808. done(null, unpad(decrypted));
  17809. });
  17810. }
  17811. /**
  17812. * a getter for step the maximum number of bytes to process at one time
  17813. *
  17814. * @return {number} the value of step 32000
  17815. */
  17816. static get STEP() {
  17817. // 4 * 8000;
  17818. return 32000;
  17819. }
  17820. /**
  17821. * @private
  17822. */
  17823. decryptChunk_(encrypted, key, initVector, decrypted) {
  17824. return function () {
  17825. const bytes = decrypt(encrypted, key, initVector);
  17826. decrypted.set(bytes, encrypted.byteOffset);
  17827. };
  17828. }
  17829. }
  17830. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  17831. var win;
  17832. if (typeof window !== "undefined") {
  17833. win = window;
  17834. } else if (typeof commonjsGlobal !== "undefined") {
  17835. win = commonjsGlobal;
  17836. } else if (typeof self !== "undefined") {
  17837. win = self;
  17838. } else {
  17839. win = {};
  17840. }
  17841. var window_1 = win;
  17842. var isArrayBufferView = function isArrayBufferView(obj) {
  17843. if (ArrayBuffer.isView === 'function') {
  17844. return ArrayBuffer.isView(obj);
  17845. }
  17846. return obj && obj.buffer instanceof ArrayBuffer;
  17847. };
  17848. var BigInt = window_1.BigInt || Number;
  17849. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  17850. (function () {
  17851. var a = new Uint16Array([0xFFCC]);
  17852. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  17853. if (b[0] === 0xFF) {
  17854. return 'big';
  17855. }
  17856. if (b[0] === 0xCC) {
  17857. return 'little';
  17858. }
  17859. return 'unknown';
  17860. })();
  17861. /**
  17862. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  17863. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  17864. *
  17865. * @param {Object} message
  17866. * Object of properties and values to send to the web worker
  17867. * @return {Object}
  17868. * Modified message with TypedArray values expanded
  17869. * @function createTransferableMessage
  17870. */
  17871. const createTransferableMessage = function (message) {
  17872. const transferable = {};
  17873. Object.keys(message).forEach(key => {
  17874. const value = message[key];
  17875. if (isArrayBufferView(value)) {
  17876. transferable[key] = {
  17877. bytes: value.buffer,
  17878. byteOffset: value.byteOffset,
  17879. byteLength: value.byteLength
  17880. };
  17881. } else {
  17882. transferable[key] = value;
  17883. }
  17884. });
  17885. return transferable;
  17886. };
  17887. /* global self */
  17888. /**
  17889. * Our web worker interface so that things can talk to aes-decrypter
  17890. * that will be running in a web worker. the scope is passed to this by
  17891. * webworkify.
  17892. */
  17893. self.onmessage = function (event) {
  17894. const data = event.data;
  17895. const encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  17896. const key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  17897. const iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  17898. /* eslint-disable no-new, handle-callback-err */
  17899. new Decrypter(encrypted, key, iv, function (err, bytes) {
  17900. self.postMessage(createTransferableMessage({
  17901. source: data.source,
  17902. decrypted: bytes
  17903. }), [bytes.buffer]);
  17904. });
  17905. /* eslint-enable */
  17906. };
  17907. }));
  17908. var Decrypter = factory(workerCode);
  17909. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  17910. /**
  17911. * Convert the properties of an HLS track into an audioTrackKind.
  17912. *
  17913. * @private
  17914. */
  17915. const audioTrackKind_ = properties => {
  17916. let kind = properties.default ? 'main' : 'alternative';
  17917. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  17918. kind = 'main-desc';
  17919. }
  17920. return kind;
  17921. };
  17922. /**
  17923. * Pause provided segment loader and playlist loader if active
  17924. *
  17925. * @param {SegmentLoader} segmentLoader
  17926. * SegmentLoader to pause
  17927. * @param {Object} mediaType
  17928. * Active media type
  17929. * @function stopLoaders
  17930. */
  17931. const stopLoaders = (segmentLoader, mediaType) => {
  17932. segmentLoader.abort();
  17933. segmentLoader.pause();
  17934. if (mediaType && mediaType.activePlaylistLoader) {
  17935. mediaType.activePlaylistLoader.pause();
  17936. mediaType.activePlaylistLoader = null;
  17937. }
  17938. };
  17939. /**
  17940. * Start loading provided segment loader and playlist loader
  17941. *
  17942. * @param {PlaylistLoader} playlistLoader
  17943. * PlaylistLoader to start loading
  17944. * @param {Object} mediaType
  17945. * Active media type
  17946. * @function startLoaders
  17947. */
  17948. const startLoaders = (playlistLoader, mediaType) => {
  17949. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  17950. // playlist loader
  17951. mediaType.activePlaylistLoader = playlistLoader;
  17952. playlistLoader.load();
  17953. };
  17954. /**
  17955. * Returns a function to be called when the media group changes. It performs a
  17956. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  17957. * change of group is merely a rendition switch of the same content at another encoding,
  17958. * rather than a change of content, such as switching audio from English to Spanish.
  17959. *
  17960. * @param {string} type
  17961. * MediaGroup type
  17962. * @param {Object} settings
  17963. * Object containing required information for media groups
  17964. * @return {Function}
  17965. * Handler for a non-destructive resync of SegmentLoader when the active media
  17966. * group changes.
  17967. * @function onGroupChanged
  17968. */
  17969. const onGroupChanged = (type, settings) => () => {
  17970. const {
  17971. segmentLoaders: {
  17972. [type]: segmentLoader,
  17973. main: mainSegmentLoader
  17974. },
  17975. mediaTypes: {
  17976. [type]: mediaType
  17977. }
  17978. } = settings;
  17979. const activeTrack = mediaType.activeTrack();
  17980. const activeGroup = mediaType.getActiveGroup();
  17981. const previousActiveLoader = mediaType.activePlaylistLoader;
  17982. const lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  17983. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  17984. return;
  17985. }
  17986. mediaType.lastGroup_ = activeGroup;
  17987. mediaType.lastTrack_ = activeTrack;
  17988. stopLoaders(segmentLoader, mediaType);
  17989. if (!activeGroup || activeGroup.isMainPlaylist) {
  17990. // there is no group active or active group is a main playlist and won't change
  17991. return;
  17992. }
  17993. if (!activeGroup.playlistLoader) {
  17994. if (previousActiveLoader) {
  17995. // The previous group had a playlist loader but the new active group does not
  17996. // this means we are switching from demuxed to muxed audio. In this case we want to
  17997. // do a destructive reset of the main segment loader and not restart the audio
  17998. // loaders.
  17999. mainSegmentLoader.resetEverything();
  18000. }
  18001. return;
  18002. } // Non-destructive resync
  18003. segmentLoader.resyncLoader();
  18004. startLoaders(activeGroup.playlistLoader, mediaType);
  18005. };
  18006. const onGroupChanging = (type, settings) => () => {
  18007. const {
  18008. segmentLoaders: {
  18009. [type]: segmentLoader
  18010. },
  18011. mediaTypes: {
  18012. [type]: mediaType
  18013. }
  18014. } = settings;
  18015. mediaType.lastGroup_ = null;
  18016. segmentLoader.abort();
  18017. segmentLoader.pause();
  18018. };
  18019. /**
  18020. * Returns a function to be called when the media track changes. It performs a
  18021. * destructive reset of the SegmentLoader to ensure we start loading as close to
  18022. * currentTime as possible.
  18023. *
  18024. * @param {string} type
  18025. * MediaGroup type
  18026. * @param {Object} settings
  18027. * Object containing required information for media groups
  18028. * @return {Function}
  18029. * Handler for a destructive reset of SegmentLoader when the active media
  18030. * track changes.
  18031. * @function onTrackChanged
  18032. */
  18033. const onTrackChanged = (type, settings) => () => {
  18034. const {
  18035. mainPlaylistLoader,
  18036. segmentLoaders: {
  18037. [type]: segmentLoader,
  18038. main: mainSegmentLoader
  18039. },
  18040. mediaTypes: {
  18041. [type]: mediaType
  18042. }
  18043. } = settings;
  18044. const activeTrack = mediaType.activeTrack();
  18045. const activeGroup = mediaType.getActiveGroup();
  18046. const previousActiveLoader = mediaType.activePlaylistLoader;
  18047. const lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  18048. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  18049. return;
  18050. }
  18051. mediaType.lastGroup_ = activeGroup;
  18052. mediaType.lastTrack_ = activeTrack;
  18053. stopLoaders(segmentLoader, mediaType);
  18054. if (!activeGroup) {
  18055. // there is no group active so we do not want to restart loaders
  18056. return;
  18057. }
  18058. if (activeGroup.isMainPlaylist) {
  18059. // track did not change, do nothing
  18060. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  18061. return;
  18062. }
  18063. const pc = settings.vhs.playlistController_;
  18064. const newPlaylist = pc.selectPlaylist(); // media will not change do nothing
  18065. if (pc.media() === newPlaylist) {
  18066. return;
  18067. }
  18068. mediaType.logger_(`track change. Switching main audio from ${lastTrack.id} to ${activeTrack.id}`);
  18069. mainPlaylistLoader.pause();
  18070. mainSegmentLoader.resetEverything();
  18071. pc.fastQualityChange_(newPlaylist);
  18072. return;
  18073. }
  18074. if (type === 'AUDIO') {
  18075. if (!activeGroup.playlistLoader) {
  18076. // when switching from demuxed audio/video to muxed audio/video (noted by no
  18077. // playlist loader for the audio group), we want to do a destructive reset of the
  18078. // main segment loader and not restart the audio loaders
  18079. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  18080. // it should be stopped
  18081. mainSegmentLoader.resetEverything();
  18082. return;
  18083. } // although the segment loader is an audio segment loader, call the setAudio
  18084. // function to ensure it is prepared to re-append the init segment (or handle other
  18085. // config changes)
  18086. segmentLoader.setAudio(true);
  18087. mainSegmentLoader.setAudio(false);
  18088. }
  18089. if (previousActiveLoader === activeGroup.playlistLoader) {
  18090. // Nothing has actually changed. This can happen because track change events can fire
  18091. // multiple times for a "single" change. One for enabling the new active track, and
  18092. // one for disabling the track that was active
  18093. startLoaders(activeGroup.playlistLoader, mediaType);
  18094. return;
  18095. }
  18096. if (segmentLoader.track) {
  18097. // For WebVTT, set the new text track in the segmentloader
  18098. segmentLoader.track(activeTrack);
  18099. } // destructive reset
  18100. segmentLoader.resetEverything();
  18101. startLoaders(activeGroup.playlistLoader, mediaType);
  18102. };
  18103. const onError = {
  18104. /**
  18105. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18106. * an error.
  18107. *
  18108. * @param {string} type
  18109. * MediaGroup type
  18110. * @param {Object} settings
  18111. * Object containing required information for media groups
  18112. * @return {Function}
  18113. * Error handler. Logs warning (or error if the playlist is excluded) to
  18114. * console and switches back to default audio track.
  18115. * @function onError.AUDIO
  18116. */
  18117. AUDIO: (type, settings) => () => {
  18118. const {
  18119. segmentLoaders: {
  18120. [type]: segmentLoader
  18121. },
  18122. mediaTypes: {
  18123. [type]: mediaType
  18124. },
  18125. excludePlaylist
  18126. } = settings;
  18127. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  18128. const activeTrack = mediaType.activeTrack();
  18129. const activeGroup = mediaType.activeGroup();
  18130. const id = (activeGroup.filter(group => group.default)[0] || activeGroup[0]).id;
  18131. const defaultTrack = mediaType.tracks[id];
  18132. if (activeTrack === defaultTrack) {
  18133. // Default track encountered an error. All we can do now is exclude the current
  18134. // rendition and hope another will switch audio groups
  18135. excludePlaylist({
  18136. error: {
  18137. message: 'Problem encountered loading the default audio track.'
  18138. }
  18139. });
  18140. return;
  18141. }
  18142. videojs__default["default"].log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  18143. for (const trackId in mediaType.tracks) {
  18144. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  18145. }
  18146. mediaType.onTrackChanged();
  18147. },
  18148. /**
  18149. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  18150. * an error.
  18151. *
  18152. * @param {string} type
  18153. * MediaGroup type
  18154. * @param {Object} settings
  18155. * Object containing required information for media groups
  18156. * @return {Function}
  18157. * Error handler. Logs warning to console and disables the active subtitle track
  18158. * @function onError.SUBTITLES
  18159. */
  18160. SUBTITLES: (type, settings) => () => {
  18161. const {
  18162. segmentLoaders: {
  18163. [type]: segmentLoader
  18164. },
  18165. mediaTypes: {
  18166. [type]: mediaType
  18167. }
  18168. } = settings;
  18169. videojs__default["default"].log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  18170. stopLoaders(segmentLoader, mediaType);
  18171. const track = mediaType.activeTrack();
  18172. if (track) {
  18173. track.mode = 'disabled';
  18174. }
  18175. mediaType.onTrackChanged();
  18176. }
  18177. };
  18178. const setupListeners = {
  18179. /**
  18180. * Setup event listeners for audio playlist loader
  18181. *
  18182. * @param {string} type
  18183. * MediaGroup type
  18184. * @param {PlaylistLoader|null} playlistLoader
  18185. * PlaylistLoader to register listeners on
  18186. * @param {Object} settings
  18187. * Object containing required information for media groups
  18188. * @function setupListeners.AUDIO
  18189. */
  18190. AUDIO: (type, playlistLoader, settings) => {
  18191. if (!playlistLoader) {
  18192. // no playlist loader means audio will be muxed with the video
  18193. return;
  18194. }
  18195. const {
  18196. tech,
  18197. requestOptions,
  18198. segmentLoaders: {
  18199. [type]: segmentLoader
  18200. }
  18201. } = settings;
  18202. playlistLoader.on('loadedmetadata', () => {
  18203. const media = playlistLoader.media();
  18204. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  18205. // permits, start downloading segments
  18206. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  18207. segmentLoader.load();
  18208. }
  18209. });
  18210. playlistLoader.on('loadedplaylist', () => {
  18211. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  18212. if (!tech.paused()) {
  18213. segmentLoader.load();
  18214. }
  18215. });
  18216. playlistLoader.on('error', onError[type](type, settings));
  18217. },
  18218. /**
  18219. * Setup event listeners for subtitle playlist loader
  18220. *
  18221. * @param {string} type
  18222. * MediaGroup type
  18223. * @param {PlaylistLoader|null} playlistLoader
  18224. * PlaylistLoader to register listeners on
  18225. * @param {Object} settings
  18226. * Object containing required information for media groups
  18227. * @function setupListeners.SUBTITLES
  18228. */
  18229. SUBTITLES: (type, playlistLoader, settings) => {
  18230. const {
  18231. tech,
  18232. requestOptions,
  18233. segmentLoaders: {
  18234. [type]: segmentLoader
  18235. },
  18236. mediaTypes: {
  18237. [type]: mediaType
  18238. }
  18239. } = settings;
  18240. playlistLoader.on('loadedmetadata', () => {
  18241. const media = playlistLoader.media();
  18242. segmentLoader.playlist(media, requestOptions);
  18243. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  18244. // permits, start downloading segments
  18245. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  18246. segmentLoader.load();
  18247. }
  18248. });
  18249. playlistLoader.on('loadedplaylist', () => {
  18250. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  18251. if (!tech.paused()) {
  18252. segmentLoader.load();
  18253. }
  18254. });
  18255. playlistLoader.on('error', onError[type](type, settings));
  18256. }
  18257. };
  18258. const initialize = {
  18259. /**
  18260. * Setup PlaylistLoaders and AudioTracks for the audio groups
  18261. *
  18262. * @param {string} type
  18263. * MediaGroup type
  18264. * @param {Object} settings
  18265. * Object containing required information for media groups
  18266. * @function initialize.AUDIO
  18267. */
  18268. 'AUDIO': (type, settings) => {
  18269. const {
  18270. vhs,
  18271. sourceType,
  18272. segmentLoaders: {
  18273. [type]: segmentLoader
  18274. },
  18275. requestOptions,
  18276. main: {
  18277. mediaGroups
  18278. },
  18279. mediaTypes: {
  18280. [type]: {
  18281. groups,
  18282. tracks,
  18283. logger_
  18284. }
  18285. },
  18286. mainPlaylistLoader
  18287. } = settings;
  18288. const audioOnlyMain = isAudioOnly(mainPlaylistLoader.main); // force a default if we have none
  18289. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  18290. mediaGroups[type] = {
  18291. main: {
  18292. default: {
  18293. default: true
  18294. }
  18295. }
  18296. };
  18297. if (audioOnlyMain) {
  18298. mediaGroups[type].main.default.playlists = mainPlaylistLoader.main.playlists;
  18299. }
  18300. }
  18301. for (const groupId in mediaGroups[type]) {
  18302. if (!groups[groupId]) {
  18303. groups[groupId] = [];
  18304. }
  18305. for (const variantLabel in mediaGroups[type][groupId]) {
  18306. let properties = mediaGroups[type][groupId][variantLabel];
  18307. let playlistLoader;
  18308. if (audioOnlyMain) {
  18309. logger_(`AUDIO group '${groupId}' label '${variantLabel}' is a main playlist`);
  18310. properties.isMainPlaylist = true;
  18311. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  18312. // use the resolved media playlist object
  18313. } else if (sourceType === 'vhs-json' && properties.playlists) {
  18314. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  18315. } else if (properties.resolvedUri) {
  18316. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  18317. // should we even have properties.playlists in this check.
  18318. } else if (properties.playlists && sourceType === 'dash') {
  18319. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  18320. } else {
  18321. // no resolvedUri means the audio is muxed with the video when using this
  18322. // audio track
  18323. playlistLoader = null;
  18324. }
  18325. properties = merge({
  18326. id: variantLabel,
  18327. playlistLoader
  18328. }, properties);
  18329. setupListeners[type](type, properties.playlistLoader, settings);
  18330. groups[groupId].push(properties);
  18331. if (typeof tracks[variantLabel] === 'undefined') {
  18332. const track = new videojs__default["default"].AudioTrack({
  18333. id: variantLabel,
  18334. kind: audioTrackKind_(properties),
  18335. enabled: false,
  18336. language: properties.language,
  18337. default: properties.default,
  18338. label: variantLabel
  18339. });
  18340. tracks[variantLabel] = track;
  18341. }
  18342. }
  18343. } // setup single error event handler for the segment loader
  18344. segmentLoader.on('error', onError[type](type, settings));
  18345. },
  18346. /**
  18347. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  18348. *
  18349. * @param {string} type
  18350. * MediaGroup type
  18351. * @param {Object} settings
  18352. * Object containing required information for media groups
  18353. * @function initialize.SUBTITLES
  18354. */
  18355. 'SUBTITLES': (type, settings) => {
  18356. const {
  18357. tech,
  18358. vhs,
  18359. sourceType,
  18360. segmentLoaders: {
  18361. [type]: segmentLoader
  18362. },
  18363. requestOptions,
  18364. main: {
  18365. mediaGroups
  18366. },
  18367. mediaTypes: {
  18368. [type]: {
  18369. groups,
  18370. tracks
  18371. }
  18372. },
  18373. mainPlaylistLoader
  18374. } = settings;
  18375. for (const groupId in mediaGroups[type]) {
  18376. if (!groups[groupId]) {
  18377. groups[groupId] = [];
  18378. }
  18379. for (const variantLabel in mediaGroups[type][groupId]) {
  18380. if (mediaGroups[type][groupId][variantLabel].forced) {
  18381. // Subtitle playlists with the forced attribute are not selectable in Safari.
  18382. // According to Apple's HLS Authoring Specification:
  18383. // If content has forced subtitles and regular subtitles in a given language,
  18384. // the regular subtitles track in that language MUST contain both the forced
  18385. // subtitles and the regular subtitles for that language.
  18386. // Because of this requirement and that Safari does not add forced subtitles,
  18387. // forced subtitles are skipped here to maintain consistent experience across
  18388. // all platforms
  18389. continue;
  18390. }
  18391. let properties = mediaGroups[type][groupId][variantLabel];
  18392. let playlistLoader;
  18393. if (sourceType === 'hls') {
  18394. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  18395. } else if (sourceType === 'dash') {
  18396. const playlists = properties.playlists.filter(p => p.excludeUntil !== Infinity);
  18397. if (!playlists.length) {
  18398. return;
  18399. }
  18400. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, mainPlaylistLoader);
  18401. } else if (sourceType === 'vhs-json') {
  18402. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  18403. // as provided, otherwise use the resolved URI to load the playlist
  18404. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  18405. }
  18406. properties = merge({
  18407. id: variantLabel,
  18408. playlistLoader
  18409. }, properties);
  18410. setupListeners[type](type, properties.playlistLoader, settings);
  18411. groups[groupId].push(properties);
  18412. if (typeof tracks[variantLabel] === 'undefined') {
  18413. const track = tech.addRemoteTextTrack({
  18414. id: variantLabel,
  18415. kind: 'subtitles',
  18416. default: properties.default && properties.autoselect,
  18417. language: properties.language,
  18418. label: variantLabel
  18419. }, false).track;
  18420. tracks[variantLabel] = track;
  18421. }
  18422. }
  18423. } // setup single error event handler for the segment loader
  18424. segmentLoader.on('error', onError[type](type, settings));
  18425. },
  18426. /**
  18427. * Setup TextTracks for the closed-caption groups
  18428. *
  18429. * @param {String} type
  18430. * MediaGroup type
  18431. * @param {Object} settings
  18432. * Object containing required information for media groups
  18433. * @function initialize['CLOSED-CAPTIONS']
  18434. */
  18435. 'CLOSED-CAPTIONS': (type, settings) => {
  18436. const {
  18437. tech,
  18438. main: {
  18439. mediaGroups
  18440. },
  18441. mediaTypes: {
  18442. [type]: {
  18443. groups,
  18444. tracks
  18445. }
  18446. }
  18447. } = settings;
  18448. for (const groupId in mediaGroups[type]) {
  18449. if (!groups[groupId]) {
  18450. groups[groupId] = [];
  18451. }
  18452. for (const variantLabel in mediaGroups[type][groupId]) {
  18453. const properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  18454. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  18455. continue;
  18456. }
  18457. const captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  18458. let newProps = {
  18459. label: variantLabel,
  18460. language: properties.language,
  18461. instreamId: properties.instreamId,
  18462. default: properties.default && properties.autoselect
  18463. };
  18464. if (captionServices[newProps.instreamId]) {
  18465. newProps = merge(newProps, captionServices[newProps.instreamId]);
  18466. }
  18467. if (newProps.default === undefined) {
  18468. delete newProps.default;
  18469. } // No PlaylistLoader is required for Closed-Captions because the captions are
  18470. // embedded within the video stream
  18471. groups[groupId].push(merge({
  18472. id: variantLabel
  18473. }, properties));
  18474. if (typeof tracks[variantLabel] === 'undefined') {
  18475. const track = tech.addRemoteTextTrack({
  18476. id: newProps.instreamId,
  18477. kind: 'captions',
  18478. default: newProps.default,
  18479. language: newProps.language,
  18480. label: newProps.label
  18481. }, false).track;
  18482. tracks[variantLabel] = track;
  18483. }
  18484. }
  18485. }
  18486. }
  18487. };
  18488. const groupMatch = (list, media) => {
  18489. for (let i = 0; i < list.length; i++) {
  18490. if (playlistMatch(media, list[i])) {
  18491. return true;
  18492. }
  18493. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  18494. return true;
  18495. }
  18496. }
  18497. return false;
  18498. };
  18499. /**
  18500. * Returns a function used to get the active group of the provided type
  18501. *
  18502. * @param {string} type
  18503. * MediaGroup type
  18504. * @param {Object} settings
  18505. * Object containing required information for media groups
  18506. * @return {Function}
  18507. * Function that returns the active media group for the provided type. Takes an
  18508. * optional parameter {TextTrack} track. If no track is provided, a list of all
  18509. * variants in the group, otherwise the variant corresponding to the provided
  18510. * track is returned.
  18511. * @function activeGroup
  18512. */
  18513. const activeGroup = (type, settings) => track => {
  18514. const {
  18515. mainPlaylistLoader,
  18516. mediaTypes: {
  18517. [type]: {
  18518. groups
  18519. }
  18520. }
  18521. } = settings;
  18522. const media = mainPlaylistLoader.media();
  18523. if (!media) {
  18524. return null;
  18525. }
  18526. let variants = null; // set to variants to main media active group
  18527. if (media.attributes[type]) {
  18528. variants = groups[media.attributes[type]];
  18529. }
  18530. const groupKeys = Object.keys(groups);
  18531. if (!variants) {
  18532. // find the mainPlaylistLoader media
  18533. // that is in a media group if we are dealing
  18534. // with audio only
  18535. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.main)) {
  18536. for (let i = 0; i < groupKeys.length; i++) {
  18537. const groupPropertyList = groups[groupKeys[i]];
  18538. if (groupMatch(groupPropertyList, media)) {
  18539. variants = groupPropertyList;
  18540. break;
  18541. }
  18542. } // use the main group if it exists
  18543. } else if (groups.main) {
  18544. variants = groups.main; // only one group, use that one
  18545. } else if (groupKeys.length === 1) {
  18546. variants = groups[groupKeys[0]];
  18547. }
  18548. }
  18549. if (typeof track === 'undefined') {
  18550. return variants;
  18551. }
  18552. if (track === null || !variants) {
  18553. // An active track was specified so a corresponding group is expected. track === null
  18554. // means no track is currently active so there is no corresponding group
  18555. return null;
  18556. }
  18557. return variants.filter(props => props.id === track.id)[0] || null;
  18558. };
  18559. const activeTrack = {
  18560. /**
  18561. * Returns a function used to get the active track of type provided
  18562. *
  18563. * @param {string} type
  18564. * MediaGroup type
  18565. * @param {Object} settings
  18566. * Object containing required information for media groups
  18567. * @return {Function}
  18568. * Function that returns the active media track for the provided type. Returns
  18569. * null if no track is active
  18570. * @function activeTrack.AUDIO
  18571. */
  18572. AUDIO: (type, settings) => () => {
  18573. const {
  18574. mediaTypes: {
  18575. [type]: {
  18576. tracks
  18577. }
  18578. }
  18579. } = settings;
  18580. for (const id in tracks) {
  18581. if (tracks[id].enabled) {
  18582. return tracks[id];
  18583. }
  18584. }
  18585. return null;
  18586. },
  18587. /**
  18588. * Returns a function used to get the active track of type provided
  18589. *
  18590. * @param {string} type
  18591. * MediaGroup type
  18592. * @param {Object} settings
  18593. * Object containing required information for media groups
  18594. * @return {Function}
  18595. * Function that returns the active media track for the provided type. Returns
  18596. * null if no track is active
  18597. * @function activeTrack.SUBTITLES
  18598. */
  18599. SUBTITLES: (type, settings) => () => {
  18600. const {
  18601. mediaTypes: {
  18602. [type]: {
  18603. tracks
  18604. }
  18605. }
  18606. } = settings;
  18607. for (const id in tracks) {
  18608. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  18609. return tracks[id];
  18610. }
  18611. }
  18612. return null;
  18613. }
  18614. };
  18615. const getActiveGroup = (type, {
  18616. mediaTypes
  18617. }) => () => {
  18618. const activeTrack_ = mediaTypes[type].activeTrack();
  18619. if (!activeTrack_) {
  18620. return null;
  18621. }
  18622. return mediaTypes[type].activeGroup(activeTrack_);
  18623. };
  18624. /**
  18625. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  18626. * Closed-Captions) specified in the main manifest.
  18627. *
  18628. * @param {Object} settings
  18629. * Object containing required information for setting up the media groups
  18630. * @param {Tech} settings.tech
  18631. * The tech of the player
  18632. * @param {Object} settings.requestOptions
  18633. * XHR request options used by the segment loaders
  18634. * @param {PlaylistLoader} settings.mainPlaylistLoader
  18635. * PlaylistLoader for the main source
  18636. * @param {VhsHandler} settings.vhs
  18637. * VHS SourceHandler
  18638. * @param {Object} settings.main
  18639. * The parsed main manifest
  18640. * @param {Object} settings.mediaTypes
  18641. * Object to store the loaders, tracks, and utility methods for each media type
  18642. * @param {Function} settings.excludePlaylist
  18643. * Excludes the current rendition and forces a rendition switch.
  18644. * @function setupMediaGroups
  18645. */
  18646. const setupMediaGroups = settings => {
  18647. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  18648. initialize[type](type, settings);
  18649. });
  18650. const {
  18651. mediaTypes,
  18652. mainPlaylistLoader,
  18653. tech,
  18654. vhs,
  18655. segmentLoaders: {
  18656. ['AUDIO']: audioSegmentLoader,
  18657. main: mainSegmentLoader
  18658. }
  18659. } = settings; // setup active group and track getters and change event handlers
  18660. ['AUDIO', 'SUBTITLES'].forEach(type => {
  18661. mediaTypes[type].activeGroup = activeGroup(type, settings);
  18662. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  18663. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  18664. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  18665. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  18666. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  18667. }); // DO NOT enable the default subtitle or caption track.
  18668. // DO enable the default audio track
  18669. const audioGroup = mediaTypes.AUDIO.activeGroup();
  18670. if (audioGroup) {
  18671. const groupId = (audioGroup.filter(group => group.default)[0] || audioGroup[0]).id;
  18672. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  18673. mediaTypes.AUDIO.onGroupChanged();
  18674. mediaTypes.AUDIO.onTrackChanged();
  18675. const activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  18676. // track is changed, but needs to be handled here since the track may not be considered
  18677. // changed on the first call to onTrackChanged
  18678. if (!activeAudioGroup.playlistLoader) {
  18679. // either audio is muxed with video or the stream is audio only
  18680. mainSegmentLoader.setAudio(true);
  18681. } else {
  18682. // audio is demuxed
  18683. mainSegmentLoader.setAudio(false);
  18684. audioSegmentLoader.setAudio(true);
  18685. }
  18686. }
  18687. mainPlaylistLoader.on('mediachange', () => {
  18688. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanged());
  18689. });
  18690. mainPlaylistLoader.on('mediachanging', () => {
  18691. ['AUDIO', 'SUBTITLES'].forEach(type => mediaTypes[type].onGroupChanging());
  18692. }); // custom audio track change event handler for usage event
  18693. const onAudioTrackChanged = () => {
  18694. mediaTypes.AUDIO.onTrackChanged();
  18695. tech.trigger({
  18696. type: 'usage',
  18697. name: 'vhs-audio-change'
  18698. });
  18699. };
  18700. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  18701. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  18702. vhs.on('dispose', () => {
  18703. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  18704. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  18705. }); // clear existing audio tracks and add the ones we just created
  18706. tech.clearTracks('audio');
  18707. for (const id in mediaTypes.AUDIO.tracks) {
  18708. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  18709. }
  18710. };
  18711. /**
  18712. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  18713. * media type
  18714. *
  18715. * @return {Object}
  18716. * Object to store the loaders, tracks, and utility methods for each media type
  18717. * @function createMediaTypes
  18718. */
  18719. const createMediaTypes = () => {
  18720. const mediaTypes = {};
  18721. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(type => {
  18722. mediaTypes[type] = {
  18723. groups: {},
  18724. tracks: {},
  18725. activePlaylistLoader: null,
  18726. activeGroup: noop,
  18727. activeTrack: noop,
  18728. getActiveGroup: noop,
  18729. onGroupChanged: noop,
  18730. onTrackChanged: noop,
  18731. lastTrack_: null,
  18732. logger_: logger(`MediaGroups[${type}]`)
  18733. };
  18734. });
  18735. return mediaTypes;
  18736. };
  18737. /**
  18738. * @file playlist-controller.js
  18739. */
  18740. const ABORT_EARLY_EXCLUSION_SECONDS = 60 * 2;
  18741. let Vhs$1; // SegmentLoader stats that need to have each loader's
  18742. // values summed to calculate the final value
  18743. const loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  18744. const sumLoaderStat = function (stat) {
  18745. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  18746. };
  18747. const shouldSwitchToMedia = function ({
  18748. currentPlaylist,
  18749. buffered,
  18750. currentTime,
  18751. nextPlaylist,
  18752. bufferLowWaterLine,
  18753. bufferHighWaterLine,
  18754. duration,
  18755. bufferBasedABR,
  18756. log
  18757. }) {
  18758. // we have no other playlist to switch to
  18759. if (!nextPlaylist) {
  18760. videojs__default["default"].log.warn('We received no playlist to switch to. Please check your stream.');
  18761. return false;
  18762. }
  18763. const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
  18764. if (!currentPlaylist) {
  18765. log(`${sharedLogLine} as current playlist is not set`);
  18766. return true;
  18767. } // no need to switch if playlist is the same
  18768. if (nextPlaylist.id === currentPlaylist.id) {
  18769. return false;
  18770. } // determine if current time is in a buffered range.
  18771. const isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  18772. // This is because in LIVE, the player plays 3 segments from the end of the
  18773. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  18774. // in those segments, a viewer will never experience a rendition upswitch.
  18775. if (!currentPlaylist.endList) {
  18776. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  18777. // doubles the time to first playback.
  18778. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  18779. log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
  18780. return false;
  18781. }
  18782. log(`${sharedLogLine} as current playlist is live`);
  18783. return true;
  18784. }
  18785. const forwardBuffer = timeAheadOf(buffered, currentTime);
  18786. 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
  18787. // duration is below the max potential low water line
  18788. if (duration < maxBufferLowWaterLine) {
  18789. log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
  18790. return true;
  18791. }
  18792. const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  18793. const currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  18794. // we can switch down
  18795. if (nextBandwidth < currBandwidth && (!bufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  18796. let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
  18797. if (bufferBasedABR) {
  18798. logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
  18799. }
  18800. log(logLine);
  18801. return true;
  18802. } // and if our buffer is higher than the low water line,
  18803. // we can switch up
  18804. if ((!bufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  18805. let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
  18806. if (bufferBasedABR) {
  18807. logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
  18808. }
  18809. log(logLine);
  18810. return true;
  18811. }
  18812. log(`not ${sharedLogLine} as no switching criteria met`);
  18813. return false;
  18814. };
  18815. /**
  18816. * the main playlist controller controller all interactons
  18817. * between playlists and segmentloaders. At this time this mainly
  18818. * involves a main playlist and a series of audio playlists
  18819. * if they are available
  18820. *
  18821. * @class PlaylistController
  18822. * @extends videojs.EventTarget
  18823. */
  18824. class PlaylistController extends videojs__default["default"].EventTarget {
  18825. constructor(options) {
  18826. super();
  18827. const {
  18828. src,
  18829. withCredentials,
  18830. tech,
  18831. bandwidth,
  18832. externVhs,
  18833. useCueTags,
  18834. playlistExclusionDuration,
  18835. enableLowInitialPlaylist,
  18836. sourceType,
  18837. cacheEncryptionKeys,
  18838. bufferBasedABR,
  18839. leastPixelDiffSelector,
  18840. captionServices
  18841. } = options;
  18842. if (!src) {
  18843. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  18844. }
  18845. let {
  18846. maxPlaylistRetries
  18847. } = options;
  18848. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  18849. maxPlaylistRetries = Infinity;
  18850. }
  18851. Vhs$1 = externVhs;
  18852. this.bufferBasedABR = Boolean(bufferBasedABR);
  18853. this.leastPixelDiffSelector = Boolean(leastPixelDiffSelector);
  18854. this.withCredentials = withCredentials;
  18855. this.tech_ = tech;
  18856. this.vhs_ = tech.vhs;
  18857. this.sourceType_ = sourceType;
  18858. this.useCueTags_ = useCueTags;
  18859. this.playlistExclusionDuration = playlistExclusionDuration;
  18860. this.maxPlaylistRetries = maxPlaylistRetries;
  18861. this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  18862. if (this.useCueTags_) {
  18863. this.cueTagsTrack_ = this.tech_.addTextTrack('metadata', 'ad-cues');
  18864. this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  18865. }
  18866. this.requestOptions_ = {
  18867. withCredentials,
  18868. maxPlaylistRetries,
  18869. timeout: null
  18870. };
  18871. this.on('error', this.pauseLoading);
  18872. this.mediaTypes_ = createMediaTypes();
  18873. this.mediaSource = new window__default["default"].MediaSource();
  18874. this.handleDurationChange_ = this.handleDurationChange_.bind(this);
  18875. this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
  18876. this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
  18877. this.mediaSource.addEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  18878. this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
  18879. this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  18880. // everything, and the MediaSource should not be detached without a proper disposal
  18881. this.seekable_ = createTimeRanges();
  18882. this.hasPlayed_ = false;
  18883. this.syncController_ = new SyncController(options);
  18884. this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  18885. kind: 'metadata',
  18886. label: 'segment-metadata'
  18887. }, false).track;
  18888. this.decrypter_ = new Decrypter();
  18889. this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
  18890. this.inbandTextTracks_ = {};
  18891. this.timelineChangeController_ = new TimelineChangeController();
  18892. const segmentLoaderSettings = {
  18893. vhs: this.vhs_,
  18894. parse708captions: options.parse708captions,
  18895. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  18896. captionServices,
  18897. mediaSource: this.mediaSource,
  18898. currentTime: this.tech_.currentTime.bind(this.tech_),
  18899. seekable: () => this.seekable(),
  18900. seeking: () => this.tech_.seeking(),
  18901. duration: () => this.duration(),
  18902. hasPlayed: () => this.hasPlayed_,
  18903. goalBufferLength: () => this.goalBufferLength(),
  18904. bandwidth,
  18905. syncController: this.syncController_,
  18906. decrypter: this.decrypter_,
  18907. sourceType: this.sourceType_,
  18908. inbandTextTracks: this.inbandTextTracks_,
  18909. cacheEncryptionKeys,
  18910. sourceUpdater: this.sourceUpdater_,
  18911. timelineChangeController: this.timelineChangeController_,
  18912. exactManifestTimings: options.exactManifestTimings
  18913. }; // The source type check not only determines whether a special DASH playlist loader
  18914. // should be used, but also covers the case where the provided src is a vhs-json
  18915. // manifest object (instead of a URL). In the case of vhs-json, the default
  18916. // PlaylistLoader should be used.
  18917. this.mainPlaylistLoader_ = this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) : new PlaylistLoader(src, this.vhs_, this.requestOptions_);
  18918. this.setupMainPlaylistLoaderListeners_(); // setup segment loaders
  18919. // combined audio/video or just video when alternate audio track is selected
  18920. this.mainSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  18921. segmentMetadataTrack: this.segmentMetadataTrack_,
  18922. loaderType: 'main'
  18923. }), options); // alternate audio track
  18924. this.audioSegmentLoader_ = new SegmentLoader(merge(segmentLoaderSettings, {
  18925. loaderType: 'audio'
  18926. }), options);
  18927. this.subtitleSegmentLoader_ = new VTTSegmentLoader(merge(segmentLoaderSettings, {
  18928. loaderType: 'vtt',
  18929. featuresNativeTextTracks: this.tech_.featuresNativeTextTracks,
  18930. loadVttJs: () => new Promise((resolve, reject) => {
  18931. function onLoad() {
  18932. tech.off('vttjserror', onError);
  18933. resolve();
  18934. }
  18935. function onError() {
  18936. tech.off('vttjsloaded', onLoad);
  18937. reject();
  18938. }
  18939. tech.one('vttjsloaded', onLoad);
  18940. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  18941. tech.addWebVttScript_();
  18942. })
  18943. }), options);
  18944. this.setupSegmentLoaderListeners_();
  18945. if (this.bufferBasedABR) {
  18946. this.mainPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
  18947. this.tech_.on('pause', () => this.stopABRTimer_());
  18948. this.tech_.on('play', () => this.startABRTimer_());
  18949. } // Create SegmentLoader stat-getters
  18950. // mediaRequests_
  18951. // mediaRequestsAborted_
  18952. // mediaRequestsTimedout_
  18953. // mediaRequestsErrored_
  18954. // mediaTransferDuration_
  18955. // mediaBytesTransferred_
  18956. // mediaAppends_
  18957. loaderStats.forEach(stat => {
  18958. this[stat + '_'] = sumLoaderStat.bind(this, stat);
  18959. });
  18960. this.logger_ = logger('pc');
  18961. this.triggeredFmp4Usage = false;
  18962. if (this.tech_.preload() === 'none') {
  18963. this.loadOnPlay_ = () => {
  18964. this.loadOnPlay_ = null;
  18965. this.mainPlaylistLoader_.load();
  18966. };
  18967. this.tech_.one('play', this.loadOnPlay_);
  18968. } else {
  18969. this.mainPlaylistLoader_.load();
  18970. }
  18971. this.timeToLoadedData__ = -1;
  18972. this.mainAppendsToLoadedData__ = -1;
  18973. this.audioAppendsToLoadedData__ = -1;
  18974. const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  18975. this.tech_.one(event, () => {
  18976. const timeToLoadedDataStart = Date.now();
  18977. this.tech_.one('loadeddata', () => {
  18978. this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  18979. this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
  18980. this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
  18981. });
  18982. });
  18983. }
  18984. mainAppendsToLoadedData_() {
  18985. return this.mainAppendsToLoadedData__;
  18986. }
  18987. audioAppendsToLoadedData_() {
  18988. return this.audioAppendsToLoadedData__;
  18989. }
  18990. appendsToLoadedData_() {
  18991. const main = this.mainAppendsToLoadedData_();
  18992. const audio = this.audioAppendsToLoadedData_();
  18993. if (main === -1 || audio === -1) {
  18994. return -1;
  18995. }
  18996. return main + audio;
  18997. }
  18998. timeToLoadedData_() {
  18999. return this.timeToLoadedData__;
  19000. }
  19001. /**
  19002. * Run selectPlaylist and switch to the new playlist if we should
  19003. *
  19004. * @param {string} [reason=abr] a reason for why the ABR check is made
  19005. * @private
  19006. */
  19007. checkABR_(reason = 'abr') {
  19008. const nextPlaylist = this.selectPlaylist();
  19009. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  19010. this.switchMedia_(nextPlaylist, reason);
  19011. }
  19012. }
  19013. switchMedia_(playlist, cause, delay) {
  19014. const oldMedia = this.media();
  19015. const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  19016. const newId = playlist.id || playlist.uri;
  19017. if (oldId && oldId !== newId) {
  19018. this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
  19019. this.tech_.trigger({
  19020. type: 'usage',
  19021. name: `vhs-rendition-change-${cause}`
  19022. });
  19023. }
  19024. this.mainPlaylistLoader_.media(playlist, delay);
  19025. }
  19026. /**
  19027. * Start a timer that periodically calls checkABR_
  19028. *
  19029. * @private
  19030. */
  19031. startABRTimer_() {
  19032. this.stopABRTimer_();
  19033. this.abrTimer_ = window__default["default"].setInterval(() => this.checkABR_(), 250);
  19034. }
  19035. /**
  19036. * Stop the timer that periodically calls checkABR_
  19037. *
  19038. * @private
  19039. */
  19040. stopABRTimer_() {
  19041. // if we're scrubbing, we don't need to pause.
  19042. // This getter will be added to Video.js in version 7.11.
  19043. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  19044. return;
  19045. }
  19046. window__default["default"].clearInterval(this.abrTimer_);
  19047. this.abrTimer_ = null;
  19048. }
  19049. /**
  19050. * Get a list of playlists for the currently selected audio playlist
  19051. *
  19052. * @return {Array} the array of audio playlists
  19053. */
  19054. getAudioTrackPlaylists_() {
  19055. const main = this.main();
  19056. const defaultPlaylists = main && main.playlists || []; // if we don't have any audio groups then we can only
  19057. // assume that the audio tracks are contained in main
  19058. // playlist array, use that or an empty array.
  19059. if (!main || !main.mediaGroups || !main.mediaGroups.AUDIO) {
  19060. return defaultPlaylists;
  19061. }
  19062. const AUDIO = main.mediaGroups.AUDIO;
  19063. const groupKeys = Object.keys(AUDIO);
  19064. let track; // get the current active track
  19065. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  19066. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from main if mediaTypes_ isn't setup yet
  19067. } else {
  19068. // default group is `main` or just the first group.
  19069. const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  19070. for (const label in defaultGroup) {
  19071. if (defaultGroup[label].default) {
  19072. track = {
  19073. label
  19074. };
  19075. break;
  19076. }
  19077. }
  19078. } // no active track no playlists.
  19079. if (!track) {
  19080. return defaultPlaylists;
  19081. }
  19082. const playlists = []; // get all of the playlists that are possible for the
  19083. // active track.
  19084. for (const group in AUDIO) {
  19085. if (AUDIO[group][track.label]) {
  19086. const properties = AUDIO[group][track.label];
  19087. if (properties.playlists && properties.playlists.length) {
  19088. playlists.push.apply(playlists, properties.playlists);
  19089. } else if (properties.uri) {
  19090. playlists.push(properties);
  19091. } else if (main.playlists.length) {
  19092. // if an audio group does not have a uri
  19093. // see if we have main playlists that use it as a group.
  19094. // if we do then add those to the playlists list.
  19095. for (let i = 0; i < main.playlists.length; i++) {
  19096. const playlist = main.playlists[i];
  19097. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  19098. playlists.push(playlist);
  19099. }
  19100. }
  19101. }
  19102. }
  19103. }
  19104. if (!playlists.length) {
  19105. return defaultPlaylists;
  19106. }
  19107. return playlists;
  19108. }
  19109. /**
  19110. * Register event handlers on the main playlist loader. A helper
  19111. * function for construction time.
  19112. *
  19113. * @private
  19114. */
  19115. setupMainPlaylistLoaderListeners_() {
  19116. this.mainPlaylistLoader_.on('loadedmetadata', () => {
  19117. const media = this.mainPlaylistLoader_.media();
  19118. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  19119. // timeout the request.
  19120. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  19121. this.requestOptions_.timeout = 0;
  19122. } else {
  19123. this.requestOptions_.timeout = requestTimeout;
  19124. } // if this isn't a live video and preload permits, start
  19125. // downloading segments
  19126. if (media.endList && this.tech_.preload() !== 'none') {
  19127. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  19128. this.mainSegmentLoader_.load();
  19129. }
  19130. setupMediaGroups({
  19131. sourceType: this.sourceType_,
  19132. segmentLoaders: {
  19133. AUDIO: this.audioSegmentLoader_,
  19134. SUBTITLES: this.subtitleSegmentLoader_,
  19135. main: this.mainSegmentLoader_
  19136. },
  19137. tech: this.tech_,
  19138. requestOptions: this.requestOptions_,
  19139. mainPlaylistLoader: this.mainPlaylistLoader_,
  19140. vhs: this.vhs_,
  19141. main: this.main(),
  19142. mediaTypes: this.mediaTypes_,
  19143. excludePlaylist: this.excludePlaylist.bind(this)
  19144. });
  19145. this.triggerPresenceUsage_(this.main(), media);
  19146. this.setupFirstPlay();
  19147. if (!this.mediaTypes_.AUDIO.activePlaylistLoader || this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  19148. this.trigger('selectedinitialmedia');
  19149. } else {
  19150. // We must wait for the active audio playlist loader to
  19151. // finish setting up before triggering this event so the
  19152. // representations API and EME setup is correct
  19153. this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
  19154. this.trigger('selectedinitialmedia');
  19155. });
  19156. }
  19157. });
  19158. this.mainPlaylistLoader_.on('loadedplaylist', () => {
  19159. if (this.loadOnPlay_) {
  19160. this.tech_.off('play', this.loadOnPlay_);
  19161. }
  19162. let updatedPlaylist = this.mainPlaylistLoader_.media();
  19163. if (!updatedPlaylist) {
  19164. // exclude any variants that are not supported by the browser before selecting
  19165. // an initial media as the playlist selectors do not consider browser support
  19166. this.excludeUnsupportedVariants_();
  19167. let selectedMedia;
  19168. if (this.enableLowInitialPlaylist) {
  19169. selectedMedia = this.selectInitialPlaylist();
  19170. }
  19171. if (!selectedMedia) {
  19172. selectedMedia = this.selectPlaylist();
  19173. }
  19174. if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
  19175. return;
  19176. }
  19177. this.initialMedia_ = selectedMedia;
  19178. this.switchMedia_(this.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  19179. // fire again since the playlist will be requested. In the case of vhs-json
  19180. // (where the manifest object is provided as the source), when the media
  19181. // playlist's `segments` list is already available, a media playlist won't be
  19182. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  19183. // called on its own here.
  19184. const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
  19185. if (!haveJsonSource) {
  19186. return;
  19187. }
  19188. updatedPlaylist = this.initialMedia_;
  19189. }
  19190. this.handleUpdatedMediaPlaylist(updatedPlaylist);
  19191. });
  19192. this.mainPlaylistLoader_.on('error', () => {
  19193. const error = this.mainPlaylistLoader_.error;
  19194. this.excludePlaylist({
  19195. playlistToExclude: error.playlist,
  19196. error
  19197. });
  19198. });
  19199. this.mainPlaylistLoader_.on('mediachanging', () => {
  19200. this.mainSegmentLoader_.abort();
  19201. this.mainSegmentLoader_.pause();
  19202. });
  19203. this.mainPlaylistLoader_.on('mediachange', () => {
  19204. const media = this.mainPlaylistLoader_.media();
  19205. const requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  19206. // timeout the request.
  19207. if (isLowestEnabledRendition(this.mainPlaylistLoader_.main, this.mainPlaylistLoader_.media())) {
  19208. this.requestOptions_.timeout = 0;
  19209. } else {
  19210. this.requestOptions_.timeout = requestTimeout;
  19211. }
  19212. this.mainPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  19213. // that the segments have changed in some way and use that to
  19214. // update the SegmentLoader instead of doing it twice here and
  19215. // on `loadedplaylist`
  19216. this.mainSegmentLoader_.playlist(media, this.requestOptions_);
  19217. this.mainSegmentLoader_.load();
  19218. this.tech_.trigger({
  19219. type: 'mediachange',
  19220. bubbles: true
  19221. });
  19222. });
  19223. this.mainPlaylistLoader_.on('playlistunchanged', () => {
  19224. const updatedPlaylist = this.mainPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  19225. // excluded for not-changing. We likely just have a really slowly updating
  19226. // playlist.
  19227. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  19228. return;
  19229. }
  19230. const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
  19231. if (playlistOutdated) {
  19232. // Playlist has stopped updating and we're stuck at its end. Try to
  19233. // exclude it and switch to another playlist in the hope that that
  19234. // one is updating (and give the player a chance to re-adjust to the
  19235. // safe live point).
  19236. this.excludePlaylist({
  19237. error: {
  19238. message: 'Playlist no longer updating.',
  19239. reason: 'playlist-unchanged'
  19240. }
  19241. }); // useful for monitoring QoS
  19242. this.tech_.trigger('playliststuck');
  19243. }
  19244. });
  19245. this.mainPlaylistLoader_.on('renditiondisabled', () => {
  19246. this.tech_.trigger({
  19247. type: 'usage',
  19248. name: 'vhs-rendition-disabled'
  19249. });
  19250. });
  19251. this.mainPlaylistLoader_.on('renditionenabled', () => {
  19252. this.tech_.trigger({
  19253. type: 'usage',
  19254. name: 'vhs-rendition-enabled'
  19255. });
  19256. });
  19257. }
  19258. /**
  19259. * Given an updated media playlist (whether it was loaded for the first time, or
  19260. * refreshed for live playlists), update any relevant properties and state to reflect
  19261. * changes in the media that should be accounted for (e.g., cues and duration).
  19262. *
  19263. * @param {Object} updatedPlaylist the updated media playlist object
  19264. *
  19265. * @private
  19266. */
  19267. handleUpdatedMediaPlaylist(updatedPlaylist) {
  19268. if (this.useCueTags_) {
  19269. this.updateAdCues_(updatedPlaylist);
  19270. } // TODO: Create a new event on the PlaylistLoader that signals
  19271. // that the segments have changed in some way and use that to
  19272. // update the SegmentLoader instead of doing it twice here and
  19273. // on `mediachange`
  19274. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  19275. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  19276. // as it is possible that it was temporarily stopped while waiting for
  19277. // a playlist (e.g., in case the playlist errored and we re-requested it).
  19278. if (!this.tech_.paused()) {
  19279. this.mainSegmentLoader_.load();
  19280. if (this.audioSegmentLoader_) {
  19281. this.audioSegmentLoader_.load();
  19282. }
  19283. }
  19284. }
  19285. /**
  19286. * A helper function for triggerring presence usage events once per source
  19287. *
  19288. * @private
  19289. */
  19290. triggerPresenceUsage_(main, media) {
  19291. const mediaGroups = main.mediaGroups || {};
  19292. let defaultDemuxed = true;
  19293. const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  19294. for (const mediaGroup in mediaGroups.AUDIO) {
  19295. for (const label in mediaGroups.AUDIO[mediaGroup]) {
  19296. const properties = mediaGroups.AUDIO[mediaGroup][label];
  19297. if (!properties.uri) {
  19298. defaultDemuxed = false;
  19299. }
  19300. }
  19301. }
  19302. if (defaultDemuxed) {
  19303. this.tech_.trigger({
  19304. type: 'usage',
  19305. name: 'vhs-demuxed'
  19306. });
  19307. }
  19308. if (Object.keys(mediaGroups.SUBTITLES).length) {
  19309. this.tech_.trigger({
  19310. type: 'usage',
  19311. name: 'vhs-webvtt'
  19312. });
  19313. }
  19314. if (Vhs$1.Playlist.isAes(media)) {
  19315. this.tech_.trigger({
  19316. type: 'usage',
  19317. name: 'vhs-aes'
  19318. });
  19319. }
  19320. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  19321. this.tech_.trigger({
  19322. type: 'usage',
  19323. name: 'vhs-alternate-audio'
  19324. });
  19325. }
  19326. if (this.useCueTags_) {
  19327. this.tech_.trigger({
  19328. type: 'usage',
  19329. name: 'vhs-playlist-cue-tags'
  19330. });
  19331. }
  19332. }
  19333. shouldSwitchToMedia_(nextPlaylist) {
  19334. const currentPlaylist = this.mainPlaylistLoader_.media() || this.mainPlaylistLoader_.pendingMedia_;
  19335. const currentTime = this.tech_.currentTime();
  19336. const bufferLowWaterLine = this.bufferLowWaterLine();
  19337. const bufferHighWaterLine = this.bufferHighWaterLine();
  19338. const buffered = this.tech_.buffered();
  19339. return shouldSwitchToMedia({
  19340. buffered,
  19341. currentTime,
  19342. currentPlaylist,
  19343. nextPlaylist,
  19344. bufferLowWaterLine,
  19345. bufferHighWaterLine,
  19346. duration: this.duration(),
  19347. bufferBasedABR: this.bufferBasedABR,
  19348. log: this.logger_
  19349. });
  19350. }
  19351. /**
  19352. * Register event handlers on the segment loaders. A helper function
  19353. * for construction time.
  19354. *
  19355. * @private
  19356. */
  19357. setupSegmentLoaderListeners_() {
  19358. this.mainSegmentLoader_.on('bandwidthupdate', () => {
  19359. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  19360. // useful to check to see if a rendition switch should be made.
  19361. this.checkABR_('bandwidthupdate');
  19362. this.tech_.trigger('bandwidthupdate');
  19363. });
  19364. this.mainSegmentLoader_.on('timeout', () => {
  19365. if (this.bufferBasedABR) {
  19366. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  19367. // Here the only consideration is that for buffer based ABR there's no guarantee
  19368. // of an immediate switch (since the bandwidth is averaged with a timeout
  19369. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  19370. this.mainSegmentLoader_.load();
  19371. }
  19372. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  19373. // based ABR.
  19374. if (!this.bufferBasedABR) {
  19375. this.mainSegmentLoader_.on('progress', () => {
  19376. this.trigger('progress');
  19377. });
  19378. }
  19379. this.mainSegmentLoader_.on('error', () => {
  19380. const error = this.mainSegmentLoader_.error();
  19381. this.excludePlaylist({
  19382. playlistToExclude: error.playlist,
  19383. error
  19384. });
  19385. });
  19386. this.mainSegmentLoader_.on('appenderror', () => {
  19387. this.error = this.mainSegmentLoader_.error_;
  19388. this.trigger('error');
  19389. });
  19390. this.mainSegmentLoader_.on('syncinfoupdate', () => {
  19391. this.onSyncInfoUpdate_();
  19392. });
  19393. this.mainSegmentLoader_.on('timestampoffset', () => {
  19394. this.tech_.trigger({
  19395. type: 'usage',
  19396. name: 'vhs-timestamp-offset'
  19397. });
  19398. });
  19399. this.audioSegmentLoader_.on('syncinfoupdate', () => {
  19400. this.onSyncInfoUpdate_();
  19401. });
  19402. this.audioSegmentLoader_.on('appenderror', () => {
  19403. this.error = this.audioSegmentLoader_.error_;
  19404. this.trigger('error');
  19405. });
  19406. this.mainSegmentLoader_.on('ended', () => {
  19407. this.logger_('main segment loader ended');
  19408. this.onEndOfStream();
  19409. });
  19410. this.mainSegmentLoader_.on('earlyabort', event => {
  19411. // never try to early abort with the new ABR algorithm
  19412. if (this.bufferBasedABR) {
  19413. return;
  19414. }
  19415. this.delegateLoaders_('all', ['abort']);
  19416. this.excludePlaylist({
  19417. error: {
  19418. message: 'Aborted early because there isn\'t enough bandwidth to complete ' + 'the request without rebuffering.'
  19419. },
  19420. playlistExclusionDuration: ABORT_EARLY_EXCLUSION_SECONDS
  19421. });
  19422. });
  19423. const updateCodecs = () => {
  19424. if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
  19425. return this.tryToCreateSourceBuffers_();
  19426. }
  19427. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  19428. if (!codecs) {
  19429. return;
  19430. }
  19431. this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  19432. };
  19433. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  19434. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  19435. this.mainSegmentLoader_.on('fmp4', () => {
  19436. if (!this.triggeredFmp4Usage) {
  19437. this.tech_.trigger({
  19438. type: 'usage',
  19439. name: 'vhs-fmp4'
  19440. });
  19441. this.triggeredFmp4Usage = true;
  19442. }
  19443. });
  19444. this.audioSegmentLoader_.on('fmp4', () => {
  19445. if (!this.triggeredFmp4Usage) {
  19446. this.tech_.trigger({
  19447. type: 'usage',
  19448. name: 'vhs-fmp4'
  19449. });
  19450. this.triggeredFmp4Usage = true;
  19451. }
  19452. });
  19453. this.audioSegmentLoader_.on('ended', () => {
  19454. this.logger_('audioSegmentLoader ended');
  19455. this.onEndOfStream();
  19456. });
  19457. }
  19458. mediaSecondsLoaded_() {
  19459. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  19460. }
  19461. /**
  19462. * Call load on our SegmentLoaders
  19463. */
  19464. load() {
  19465. this.mainSegmentLoader_.load();
  19466. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19467. this.audioSegmentLoader_.load();
  19468. }
  19469. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  19470. this.subtitleSegmentLoader_.load();
  19471. }
  19472. }
  19473. /**
  19474. * Re-tune playback quality level for the current player
  19475. * conditions. This method will perform destructive actions like removing
  19476. * already buffered content in order to readjust the currently active
  19477. * playlist quickly. This is good for manual quality changes
  19478. *
  19479. * @private
  19480. */
  19481. fastQualityChange_(media = this.selectPlaylist()) {
  19482. if (media === this.mainPlaylistLoader_.media()) {
  19483. this.logger_('skipping fastQualityChange because new media is same as old');
  19484. return;
  19485. }
  19486. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  19487. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  19488. // ahead is roughly the minimum that will accomplish this across a variety of content
  19489. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  19490. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  19491. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  19492. this.mainSegmentLoader_.resetEverything(() => {
  19493. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  19494. // from the previously enabled rendition to load before the new playlist has finished loading
  19495. if (videojs__default["default"].browser.IE_VERSION || videojs__default["default"].browser.IS_EDGE) {
  19496. this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
  19497. } else {
  19498. this.tech_.setCurrentTime(this.tech_.currentTime());
  19499. }
  19500. }); // don't need to reset audio as it is reset when media changes
  19501. }
  19502. /**
  19503. * Begin playback.
  19504. */
  19505. play() {
  19506. if (this.setupFirstPlay()) {
  19507. return;
  19508. }
  19509. if (this.tech_.ended()) {
  19510. this.tech_.setCurrentTime(0);
  19511. }
  19512. if (this.hasPlayed_) {
  19513. this.load();
  19514. }
  19515. const seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  19516. // seek forward to the live point
  19517. if (this.tech_.duration() === Infinity) {
  19518. if (this.tech_.currentTime() < seekable.start(0)) {
  19519. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  19520. }
  19521. }
  19522. }
  19523. /**
  19524. * Seek to the latest media position if this is a live video and the
  19525. * player and video are loaded and initialized.
  19526. */
  19527. setupFirstPlay() {
  19528. const media = this.mainPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  19529. // If 1) there is no active media
  19530. // 2) the player is paused
  19531. // 3) the first play has already been setup
  19532. // then exit early
  19533. if (!media || this.tech_.paused() || this.hasPlayed_) {
  19534. return false;
  19535. } // when the video is a live stream
  19536. if (!media.endList) {
  19537. const seekable = this.seekable();
  19538. if (!seekable.length) {
  19539. // without a seekable range, the player cannot seek to begin buffering at the live
  19540. // point
  19541. return false;
  19542. }
  19543. if (videojs__default["default"].browser.IE_VERSION && this.tech_.readyState() === 0) {
  19544. // IE11 throws an InvalidStateError if you try to set currentTime while the
  19545. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  19546. this.tech_.one('loadedmetadata', () => {
  19547. this.trigger('firstplay');
  19548. this.tech_.setCurrentTime(seekable.end(0));
  19549. this.hasPlayed_ = true;
  19550. });
  19551. return false;
  19552. } // trigger firstplay to inform the source handler to ignore the next seek event
  19553. this.trigger('firstplay'); // seek to the live point
  19554. this.tech_.setCurrentTime(seekable.end(0));
  19555. }
  19556. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  19557. this.load();
  19558. return true;
  19559. }
  19560. /**
  19561. * handle the sourceopen event on the MediaSource
  19562. *
  19563. * @private
  19564. */
  19565. handleSourceOpen_() {
  19566. // Only attempt to create the source buffer if none already exist.
  19567. // handleSourceOpen is also called when we are "re-opening" a source buffer
  19568. // after `endOfStream` has been called (in response to a seek for instance)
  19569. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  19570. // code in video.js but is required because play() must be invoked
  19571. // *after* the media source has opened.
  19572. if (this.tech_.autoplay()) {
  19573. const playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  19574. // on browsers which return a promise
  19575. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  19576. playPromise.then(null, e => {});
  19577. }
  19578. }
  19579. this.trigger('sourceopen');
  19580. }
  19581. /**
  19582. * handle the sourceended event on the MediaSource
  19583. *
  19584. * @private
  19585. */
  19586. handleSourceEnded_() {
  19587. if (!this.inbandTextTracks_.metadataTrack_) {
  19588. return;
  19589. }
  19590. const cues = this.inbandTextTracks_.metadataTrack_.cues;
  19591. if (!cues || !cues.length) {
  19592. return;
  19593. }
  19594. const duration = this.duration();
  19595. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  19596. }
  19597. /**
  19598. * handle the durationchange event on the MediaSource
  19599. *
  19600. * @private
  19601. */
  19602. handleDurationChange_() {
  19603. this.tech_.trigger('durationchange');
  19604. }
  19605. /**
  19606. * Calls endOfStream on the media source when all active stream types have called
  19607. * endOfStream
  19608. *
  19609. * @param {string} streamType
  19610. * Stream type of the segment loader that called endOfStream
  19611. * @private
  19612. */
  19613. onEndOfStream() {
  19614. let isEndOfStream = this.mainSegmentLoader_.ended_;
  19615. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19616. const mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  19617. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  19618. // if we do not know if the main segment loader contains video yet or if we
  19619. // definitively know the main segment loader contains video, then we need to wait
  19620. // for both main and audio segment loaders to call endOfStream
  19621. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  19622. } else {
  19623. // otherwise just rely on the audio loader
  19624. isEndOfStream = this.audioSegmentLoader_.ended_;
  19625. }
  19626. }
  19627. if (!isEndOfStream) {
  19628. return;
  19629. }
  19630. this.stopABRTimer_();
  19631. this.sourceUpdater_.endOfStream();
  19632. }
  19633. /**
  19634. * Check if a playlist has stopped being updated
  19635. *
  19636. * @param {Object} playlist the media playlist object
  19637. * @return {boolean} whether the playlist has stopped being updated or not
  19638. */
  19639. stuckAtPlaylistEnd_(playlist) {
  19640. const seekable = this.seekable();
  19641. if (!seekable.length) {
  19642. // playlist doesn't have enough information to determine whether we are stuck
  19643. return false;
  19644. }
  19645. const expired = this.syncController_.getExpiredTime(playlist, this.duration());
  19646. if (expired === null) {
  19647. return false;
  19648. } // does not use the safe live end to calculate playlist end, since we
  19649. // don't want to say we are stuck while there is still content
  19650. const absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  19651. const currentTime = this.tech_.currentTime();
  19652. const buffered = this.tech_.buffered();
  19653. if (!buffered.length) {
  19654. // return true if the playhead reached the absolute end of the playlist
  19655. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  19656. }
  19657. const bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  19658. // end of playlist
  19659. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  19660. }
  19661. /**
  19662. * Exclude a playlist for a set amount of time, making it unavailable for selection by
  19663. * the rendition selection algorithm, then force a new playlist (rendition) selection.
  19664. *
  19665. * @param {Object=} playlistToExclude
  19666. * the playlist to exclude, defaults to the currently selected playlist
  19667. * @param {Object=} error
  19668. * an optional error
  19669. * @param {number=} playlistExclusionDuration
  19670. * an optional number of seconds to exclude the playlist
  19671. */
  19672. excludePlaylist({
  19673. playlistToExclude = this.mainPlaylistLoader_.media(),
  19674. error = {},
  19675. playlistExclusionDuration
  19676. }) {
  19677. // If the `error` was generated by the playlist loader, it will contain
  19678. // the playlist we were trying to load (but failed) and that should be
  19679. // excluded instead of the currently selected playlist which is likely
  19680. // out-of-date in this scenario
  19681. playlistToExclude = playlistToExclude || this.mainPlaylistLoader_.media();
  19682. playlistExclusionDuration = playlistExclusionDuration || error.playlistExclusionDuration || this.playlistExclusionDuration; // If there is no current playlist, then an error occurred while we were
  19683. // trying to load the main OR while we were disposing of the tech
  19684. if (!playlistToExclude) {
  19685. this.error = error;
  19686. if (this.mediaSource.readyState !== 'open') {
  19687. this.trigger('error');
  19688. } else {
  19689. this.sourceUpdater_.endOfStream('network');
  19690. }
  19691. return;
  19692. }
  19693. playlistToExclude.playlistErrors_++;
  19694. const playlists = this.mainPlaylistLoader_.main.playlists;
  19695. const enabledPlaylists = playlists.filter(isEnabled);
  19696. const isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === playlistToExclude; // Don't exclude the only playlist unless it was excluded
  19697. // forever
  19698. if (playlists.length === 1 && playlistExclusionDuration !== Infinity) {
  19699. videojs__default["default"].log.warn(`Problem encountered with playlist ${playlistToExclude.id}. ` + 'Trying again since it is the only playlist.');
  19700. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  19701. return this.mainPlaylistLoader_.load(isFinalRendition);
  19702. }
  19703. if (isFinalRendition) {
  19704. // Since we're on the final non-excluded playlist, and we're about to exclude
  19705. // it, instead of erring the player or retrying this playlist, clear out the current
  19706. // exclusion list. This allows other playlists to be attempted in case any have been
  19707. // fixed.
  19708. let reincluded = false;
  19709. playlists.forEach(playlist => {
  19710. // skip current playlist which is about to be excluded
  19711. if (playlist === playlistToExclude) {
  19712. return;
  19713. }
  19714. const excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  19715. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  19716. reincluded = true;
  19717. delete playlist.excludeUntil;
  19718. }
  19719. });
  19720. if (reincluded) {
  19721. 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
  19722. // playlist. This is needed for users relying on the retryplaylist event to catch a
  19723. // case where the player might be stuck and looping through "dead" playlists.
  19724. this.tech_.trigger('retryplaylist');
  19725. }
  19726. } // Exclude this playlist
  19727. let excludeUntil;
  19728. if (playlistToExclude.playlistErrors_ > this.maxPlaylistRetries) {
  19729. excludeUntil = Infinity;
  19730. } else {
  19731. excludeUntil = Date.now() + playlistExclusionDuration * 1000;
  19732. }
  19733. playlistToExclude.excludeUntil = excludeUntil;
  19734. if (error.reason) {
  19735. playlistToExclude.lastExcludeReason_ = error.reason;
  19736. }
  19737. this.tech_.trigger('excludeplaylist');
  19738. this.tech_.trigger({
  19739. type: 'usage',
  19740. name: 'vhs-rendition-excluded'
  19741. }); // TODO: only load a new playlist if we're excluding the current playlist
  19742. // If this function was called with a playlist that's not the current active playlist
  19743. // (e.g., media().id !== playlistToExclude.id),
  19744. // then a new playlist should not be selected and loaded, as there's nothing wrong with the current playlist.
  19745. const nextPlaylist = this.selectPlaylist();
  19746. if (!nextPlaylist) {
  19747. this.error = 'Playback cannot continue. No available working or supported playlists.';
  19748. this.trigger('error');
  19749. return;
  19750. }
  19751. const logFn = error.internal ? this.logger_ : videojs__default["default"].log.warn;
  19752. const errorMessage = error.message ? ' ' + error.message : '';
  19753. logFn(`${error.internal ? 'Internal problem' : 'Problem'} encountered with playlist ${playlistToExclude.id}.` + `${errorMessage} Switching to playlist ${nextPlaylist.id}.`); // if audio group changed reset audio loaders
  19754. if (nextPlaylist.attributes.AUDIO !== playlistToExclude.attributes.AUDIO) {
  19755. this.delegateLoaders_('audio', ['abort', 'pause']);
  19756. } // if subtitle group changed reset subtitle loaders
  19757. if (nextPlaylist.attributes.SUBTITLES !== playlistToExclude.attributes.SUBTITLES) {
  19758. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  19759. }
  19760. this.delegateLoaders_('main', ['abort', 'pause']);
  19761. const delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  19762. 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
  19763. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  19764. }
  19765. /**
  19766. * Pause all segment/playlist loaders
  19767. */
  19768. pauseLoading() {
  19769. this.delegateLoaders_('all', ['abort', 'pause']);
  19770. this.stopABRTimer_();
  19771. }
  19772. /**
  19773. * Call a set of functions in order on playlist loaders, segment loaders,
  19774. * or both types of loaders.
  19775. *
  19776. * @param {string} filter
  19777. * Filter loaders that should call fnNames using a string. Can be:
  19778. * * all - run on all loaders
  19779. * * audio - run on all audio loaders
  19780. * * subtitle - run on all subtitle loaders
  19781. * * main - run on the main loaders
  19782. *
  19783. * @param {Array|string} fnNames
  19784. * A string or array of function names to call.
  19785. */
  19786. delegateLoaders_(filter, fnNames) {
  19787. const loaders = [];
  19788. const dontFilterPlaylist = filter === 'all';
  19789. if (dontFilterPlaylist || filter === 'main') {
  19790. loaders.push(this.mainPlaylistLoader_);
  19791. }
  19792. const mediaTypes = [];
  19793. if (dontFilterPlaylist || filter === 'audio') {
  19794. mediaTypes.push('AUDIO');
  19795. }
  19796. if (dontFilterPlaylist || filter === 'subtitle') {
  19797. mediaTypes.push('CLOSED-CAPTIONS');
  19798. mediaTypes.push('SUBTITLES');
  19799. }
  19800. mediaTypes.forEach(mediaType => {
  19801. const loader = this.mediaTypes_[mediaType] && this.mediaTypes_[mediaType].activePlaylistLoader;
  19802. if (loader) {
  19803. loaders.push(loader);
  19804. }
  19805. });
  19806. ['main', 'audio', 'subtitle'].forEach(name => {
  19807. const loader = this[`${name}SegmentLoader_`];
  19808. if (loader && (filter === name || filter === 'all')) {
  19809. loaders.push(loader);
  19810. }
  19811. });
  19812. loaders.forEach(loader => fnNames.forEach(fnName => {
  19813. if (typeof loader[fnName] === 'function') {
  19814. loader[fnName]();
  19815. }
  19816. }));
  19817. }
  19818. /**
  19819. * set the current time on all segment loaders
  19820. *
  19821. * @param {TimeRange} currentTime the current time to set
  19822. * @return {TimeRange} the current time
  19823. */
  19824. setCurrentTime(currentTime) {
  19825. const buffered = findRange(this.tech_.buffered(), currentTime);
  19826. if (!(this.mainPlaylistLoader_ && this.mainPlaylistLoader_.media())) {
  19827. // return immediately if the metadata is not ready yet
  19828. return 0;
  19829. } // it's clearly an edge-case but don't thrown an error if asked to
  19830. // seek within an empty playlist
  19831. if (!this.mainPlaylistLoader_.media().segments) {
  19832. return 0;
  19833. } // if the seek location is already buffered, continue buffering as usual
  19834. if (buffered && buffered.length) {
  19835. return currentTime;
  19836. } // cancel outstanding requests so we begin buffering at the new
  19837. // location
  19838. this.mainSegmentLoader_.resetEverything();
  19839. this.mainSegmentLoader_.abort();
  19840. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19841. this.audioSegmentLoader_.resetEverything();
  19842. this.audioSegmentLoader_.abort();
  19843. }
  19844. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  19845. this.subtitleSegmentLoader_.resetEverything();
  19846. this.subtitleSegmentLoader_.abort();
  19847. } // start segment loader loading in case they are paused
  19848. this.load();
  19849. }
  19850. /**
  19851. * get the current duration
  19852. *
  19853. * @return {TimeRange} the duration
  19854. */
  19855. duration() {
  19856. if (!this.mainPlaylistLoader_) {
  19857. return 0;
  19858. }
  19859. const media = this.mainPlaylistLoader_.media();
  19860. if (!media) {
  19861. // no playlists loaded yet, so can't determine a duration
  19862. return 0;
  19863. } // Don't rely on the media source for duration in the case of a live playlist since
  19864. // setting the native MediaSource's duration to infinity ends up with consequences to
  19865. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  19866. //
  19867. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  19868. // however, few browsers have support for setLiveSeekableRange()
  19869. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  19870. //
  19871. // Until a time when the duration of the media source can be set to infinity, and a
  19872. // seekable range specified across browsers, just return Infinity.
  19873. if (!media.endList) {
  19874. return Infinity;
  19875. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  19876. // available). If it's not available, fall back to a playlist-calculated estimate.
  19877. if (this.mediaSource) {
  19878. return this.mediaSource.duration;
  19879. }
  19880. return Vhs$1.Playlist.duration(media);
  19881. }
  19882. /**
  19883. * check the seekable range
  19884. *
  19885. * @return {TimeRange} the seekable range
  19886. */
  19887. seekable() {
  19888. return this.seekable_;
  19889. }
  19890. onSyncInfoUpdate_() {
  19891. let audioSeekable; // TODO check for creation of both source buffers before updating seekable
  19892. //
  19893. // A fix was made to this function where a check for
  19894. // this.sourceUpdater_.hasCreatedSourceBuffers
  19895. // was added to ensure that both source buffers were created before seekable was
  19896. // updated. However, it originally had a bug where it was checking for a true and
  19897. // returning early instead of checking for false. Setting it to check for false to
  19898. // return early though created other issues. A call to play() would check for seekable
  19899. // end without verifying that a seekable range was present. In addition, even checking
  19900. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  19901. // due to a media update calling load on the segment loaders, skipping a seek to live,
  19902. // thereby starting live streams at the beginning of the stream rather than at the end.
  19903. //
  19904. // This conditional should be fixed to wait for the creation of two source buffers at
  19905. // the same time as the other sections of code are fixed to properly seek to live and
  19906. // not throw an error due to checking for a seekable end when no seekable range exists.
  19907. //
  19908. // For now, fall back to the older behavior, with the understanding that the seekable
  19909. // range may not be completely correct, leading to a suboptimal initial live point.
  19910. if (!this.mainPlaylistLoader_) {
  19911. return;
  19912. }
  19913. let media = this.mainPlaylistLoader_.media();
  19914. if (!media) {
  19915. return;
  19916. }
  19917. let expired = this.syncController_.getExpiredTime(media, this.duration());
  19918. if (expired === null) {
  19919. // not enough information to update seekable
  19920. return;
  19921. }
  19922. const main = this.mainPlaylistLoader_.main;
  19923. const mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  19924. if (mainSeekable.length === 0) {
  19925. return;
  19926. }
  19927. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  19928. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  19929. expired = this.syncController_.getExpiredTime(media, this.duration());
  19930. if (expired === null) {
  19931. return;
  19932. }
  19933. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(main, media));
  19934. if (audioSeekable.length === 0) {
  19935. return;
  19936. }
  19937. }
  19938. let oldEnd;
  19939. let oldStart;
  19940. if (this.seekable_ && this.seekable_.length) {
  19941. oldEnd = this.seekable_.end(0);
  19942. oldStart = this.seekable_.start(0);
  19943. }
  19944. if (!audioSeekable) {
  19945. // seekable has been calculated based on buffering video data so it
  19946. // can be returned directly
  19947. this.seekable_ = mainSeekable;
  19948. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  19949. // seekables are pretty far off, rely on main
  19950. this.seekable_ = mainSeekable;
  19951. } else {
  19952. 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)]]);
  19953. } // seekable is the same as last time
  19954. if (this.seekable_ && this.seekable_.length) {
  19955. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  19956. return;
  19957. }
  19958. }
  19959. this.logger_(`seekable updated [${printableRange(this.seekable_)}]`);
  19960. this.tech_.trigger('seekablechanged');
  19961. }
  19962. /**
  19963. * Update the player duration
  19964. */
  19965. updateDuration(isLive) {
  19966. if (this.updateDuration_) {
  19967. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  19968. this.updateDuration_ = null;
  19969. }
  19970. if (this.mediaSource.readyState !== 'open') {
  19971. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  19972. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  19973. return;
  19974. }
  19975. if (isLive) {
  19976. const seekable = this.seekable();
  19977. if (!seekable.length) {
  19978. return;
  19979. } // Even in the case of a live playlist, the native MediaSource's duration should not
  19980. // be set to Infinity (even though this would be expected for a live playlist), since
  19981. // setting the native MediaSource's duration to infinity ends up with consequences to
  19982. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  19983. //
  19984. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  19985. // however, few browsers have support for setLiveSeekableRange()
  19986. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  19987. //
  19988. // Until a time when the duration of the media source can be set to infinity, and a
  19989. // seekable range specified across browsers, the duration should be greater than or
  19990. // equal to the last possible seekable value.
  19991. // MediaSource duration starts as NaN
  19992. // It is possible (and probable) that this case will never be reached for many
  19993. // sources, since the MediaSource reports duration as the highest value without
  19994. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  19995. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  19996. // time will be between 0 and 100, the native media source may report the duration
  19997. // as 200. However, since we report duration separate from the media source (as
  19998. // Infinity), and as long as the native media source duration value is greater than
  19999. // our reported seekable range, seeks will work as expected. The large number as
  20000. // duration for live is actually a strategy used by some players to work around the
  20001. // issue of live seekable ranges cited above.
  20002. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  20003. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  20004. }
  20005. return;
  20006. }
  20007. const buffered = this.tech_.buffered();
  20008. let duration = Vhs$1.Playlist.duration(this.mainPlaylistLoader_.media());
  20009. if (buffered.length > 0) {
  20010. duration = Math.max(duration, buffered.end(buffered.length - 1));
  20011. }
  20012. if (this.mediaSource.duration !== duration) {
  20013. this.sourceUpdater_.setDuration(duration);
  20014. }
  20015. }
  20016. /**
  20017. * dispose of the PlaylistController and everything
  20018. * that it controls
  20019. */
  20020. dispose() {
  20021. this.trigger('dispose');
  20022. this.decrypter_.terminate();
  20023. this.mainPlaylistLoader_.dispose();
  20024. this.mainSegmentLoader_.dispose();
  20025. if (this.loadOnPlay_) {
  20026. this.tech_.off('play', this.loadOnPlay_);
  20027. }
  20028. ['AUDIO', 'SUBTITLES'].forEach(type => {
  20029. const groups = this.mediaTypes_[type].groups;
  20030. for (const id in groups) {
  20031. groups[id].forEach(group => {
  20032. if (group.playlistLoader) {
  20033. group.playlistLoader.dispose();
  20034. }
  20035. });
  20036. }
  20037. });
  20038. this.audioSegmentLoader_.dispose();
  20039. this.subtitleSegmentLoader_.dispose();
  20040. this.sourceUpdater_.dispose();
  20041. this.timelineChangeController_.dispose();
  20042. this.stopABRTimer_();
  20043. if (this.updateDuration_) {
  20044. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  20045. }
  20046. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  20047. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  20048. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  20049. this.off();
  20050. }
  20051. /**
  20052. * return the main playlist object if we have one
  20053. *
  20054. * @return {Object} the main playlist object that we parsed
  20055. */
  20056. main() {
  20057. return this.mainPlaylistLoader_.main;
  20058. }
  20059. /**
  20060. * return the currently selected playlist
  20061. *
  20062. * @return {Object} the currently selected playlist object that we parsed
  20063. */
  20064. media() {
  20065. // playlist loader will not return media if it has not been fully loaded
  20066. return this.mainPlaylistLoader_.media() || this.initialMedia_;
  20067. }
  20068. areMediaTypesKnown_() {
  20069. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  20070. const hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  20071. // otherwise check on the segment loader.
  20072. const hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  20073. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  20074. return false;
  20075. }
  20076. return true;
  20077. }
  20078. getCodecsOrExclude_() {
  20079. const media = {
  20080. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  20081. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  20082. };
  20083. const playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  20084. media.video = media.main;
  20085. const playlistCodecs = codecsForPlaylist(this.main(), playlist);
  20086. const codecs = {};
  20087. const usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  20088. if (media.main.hasVideo) {
  20089. codecs.video = playlistCodecs.video || media.main.videoCodec || codecs_js.DEFAULT_VIDEO_CODEC;
  20090. }
  20091. if (media.main.isMuxed) {
  20092. codecs.video += `,${playlistCodecs.audio || media.main.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC}`;
  20093. }
  20094. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  20095. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || codecs_js.DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  20096. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  20097. } // no codecs, no playback.
  20098. if (!codecs.audio && !codecs.video) {
  20099. this.excludePlaylist({
  20100. playlistToExclude: playlist,
  20101. error: {
  20102. message: 'Could not determine codecs for playlist.'
  20103. },
  20104. playlistExclusionDuration: Infinity
  20105. });
  20106. return;
  20107. } // fmp4 relies on browser support, while ts relies on muxer support
  20108. const supportFunction = (isFmp4, codec) => isFmp4 ? codecs_js.browserSupportsCodec(codec) : codecs_js.muxerSupportsCodec(codec);
  20109. const unsupportedCodecs = {};
  20110. let unsupportedAudio;
  20111. ['video', 'audio'].forEach(function (type) {
  20112. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  20113. const supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  20114. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  20115. unsupportedCodecs[supporter].push(codecs[type]);
  20116. if (type === 'audio') {
  20117. unsupportedAudio = supporter;
  20118. }
  20119. }
  20120. });
  20121. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  20122. const audioGroup = playlist.attributes.AUDIO;
  20123. this.main().playlists.forEach(variant => {
  20124. const variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  20125. if (variantAudioGroup === audioGroup && variant !== playlist) {
  20126. variant.excludeUntil = Infinity;
  20127. }
  20128. });
  20129. this.logger_(`excluding audio group ${audioGroup} as ${unsupportedAudio} does not support codec(s): "${codecs.audio}"`);
  20130. } // if we have any unsupported codecs exclude this playlist.
  20131. if (Object.keys(unsupportedCodecs).length) {
  20132. const message = Object.keys(unsupportedCodecs).reduce((acc, supporter) => {
  20133. if (acc) {
  20134. acc += ', ';
  20135. }
  20136. acc += `${supporter} does not support codec(s): "${unsupportedCodecs[supporter].join(',')}"`;
  20137. return acc;
  20138. }, '') + '.';
  20139. this.excludePlaylist({
  20140. playlistToExclude: playlist,
  20141. error: {
  20142. internal: true,
  20143. message
  20144. },
  20145. playlistExclusionDuration: Infinity
  20146. });
  20147. return;
  20148. } // check if codec switching is happening
  20149. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  20150. const switchMessages = [];
  20151. ['video', 'audio'].forEach(type => {
  20152. const newCodec = (codecs_js.parseCodecs(this.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  20153. const oldCodec = (codecs_js.parseCodecs(codecs[type] || '')[0] || {}).type;
  20154. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  20155. switchMessages.push(`"${this.sourceUpdater_.codecs[type]}" -> "${codecs[type]}"`);
  20156. }
  20157. });
  20158. if (switchMessages.length) {
  20159. this.excludePlaylist({
  20160. playlistToExclude: playlist,
  20161. error: {
  20162. message: `Codec switching not supported: ${switchMessages.join(', ')}.`,
  20163. internal: true
  20164. },
  20165. playlistExclusionDuration: Infinity
  20166. });
  20167. return;
  20168. }
  20169. } // TODO: when using the muxer shouldn't we just return
  20170. // the codecs that the muxer outputs?
  20171. return codecs;
  20172. }
  20173. /**
  20174. * Create source buffers and exlude any incompatible renditions.
  20175. *
  20176. * @private
  20177. */
  20178. tryToCreateSourceBuffers_() {
  20179. // media source is not ready yet or sourceBuffers are already
  20180. // created.
  20181. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  20182. return;
  20183. }
  20184. if (!this.areMediaTypesKnown_()) {
  20185. return;
  20186. }
  20187. const codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  20188. if (!codecs) {
  20189. return;
  20190. }
  20191. this.sourceUpdater_.createSourceBuffers(codecs);
  20192. const codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  20193. this.excludeIncompatibleVariants_(codecString);
  20194. }
  20195. /**
  20196. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  20197. */
  20198. excludeUnsupportedVariants_() {
  20199. const playlists = this.main().playlists;
  20200. const ids = []; // TODO: why don't we have a property to loop through all
  20201. // playlist? Why did we ever mix indexes and keys?
  20202. Object.keys(playlists).forEach(key => {
  20203. const variant = playlists[key]; // check if we already processed this playlist.
  20204. if (ids.indexOf(variant.id) !== -1) {
  20205. return;
  20206. }
  20207. ids.push(variant.id);
  20208. const codecs = codecsForPlaylist(this.main, variant);
  20209. const unsupported = [];
  20210. if (codecs.audio && !codecs_js.muxerSupportsCodec(codecs.audio) && !codecs_js.browserSupportsCodec(codecs.audio)) {
  20211. unsupported.push(`audio codec ${codecs.audio}`);
  20212. }
  20213. if (codecs.video && !codecs_js.muxerSupportsCodec(codecs.video) && !codecs_js.browserSupportsCodec(codecs.video)) {
  20214. unsupported.push(`video codec ${codecs.video}`);
  20215. }
  20216. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  20217. unsupported.push(`text codec ${codecs.text}`);
  20218. }
  20219. if (unsupported.length) {
  20220. variant.excludeUntil = Infinity;
  20221. this.logger_(`excluding ${variant.id} for unsupported: ${unsupported.join(', ')}`);
  20222. }
  20223. });
  20224. }
  20225. /**
  20226. * Exclude playlists that are known to be codec or
  20227. * stream-incompatible with the SourceBuffer configuration. For
  20228. * instance, Media Source Extensions would cause the video element to
  20229. * stall waiting for video data if you switched from a variant with
  20230. * video and audio to an audio-only one.
  20231. *
  20232. * @param {Object} media a media playlist compatible with the current
  20233. * set of SourceBuffers. Variants in the current main playlist that
  20234. * do not appear to have compatible codec or stream configurations
  20235. * will be excluded from the default playlist selection algorithm
  20236. * indefinitely.
  20237. * @private
  20238. */
  20239. excludeIncompatibleVariants_(codecString) {
  20240. const ids = [];
  20241. const playlists = this.main().playlists;
  20242. const codecs = unwrapCodecList(codecs_js.parseCodecs(codecString));
  20243. const codecCount_ = codecCount(codecs);
  20244. const videoDetails = codecs.video && codecs_js.parseCodecs(codecs.video)[0] || null;
  20245. const audioDetails = codecs.audio && codecs_js.parseCodecs(codecs.audio)[0] || null;
  20246. Object.keys(playlists).forEach(key => {
  20247. const variant = playlists[key]; // check if we already processed this playlist.
  20248. // or it if it is already excluded forever.
  20249. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  20250. return;
  20251. }
  20252. ids.push(variant.id);
  20253. const exclusionReasons = []; // get codecs from the playlist for this variant
  20254. const variantCodecs = codecsForPlaylist(this.mainPlaylistLoader_.main, variant);
  20255. const variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  20256. // variant is incompatible. Wait for mux.js to probe
  20257. if (!variantCodecs.audio && !variantCodecs.video) {
  20258. return;
  20259. } // TODO: we can support this by removing the
  20260. // old media source and creating a new one, but it will take some work.
  20261. // The number of streams cannot change
  20262. if (variantCodecCount !== codecCount_) {
  20263. exclusionReasons.push(`codec count "${variantCodecCount}" !== "${codecCount_}"`);
  20264. } // only exclude playlists by codec change, if codecs cannot switch
  20265. // during playback.
  20266. if (!this.sourceUpdater_.canChangeType()) {
  20267. const variantVideoDetails = variantCodecs.video && codecs_js.parseCodecs(variantCodecs.video)[0] || null;
  20268. const variantAudioDetails = variantCodecs.audio && codecs_js.parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  20269. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  20270. exclusionReasons.push(`video codec "${variantVideoDetails.type}" !== "${videoDetails.type}"`);
  20271. } // the audio codec cannot change
  20272. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  20273. exclusionReasons.push(`audio codec "${variantAudioDetails.type}" !== "${audioDetails.type}"`);
  20274. }
  20275. }
  20276. if (exclusionReasons.length) {
  20277. variant.excludeUntil = Infinity;
  20278. this.logger_(`excluding ${variant.id}: ${exclusionReasons.join(' && ')}`);
  20279. }
  20280. });
  20281. }
  20282. updateAdCues_(media) {
  20283. let offset = 0;
  20284. const seekable = this.seekable();
  20285. if (seekable.length) {
  20286. offset = seekable.start(0);
  20287. }
  20288. updateAdCues(media, this.cueTagsTrack_, offset);
  20289. }
  20290. /**
  20291. * Calculates the desired forward buffer length based on current time
  20292. *
  20293. * @return {number} Desired forward buffer length in seconds
  20294. */
  20295. goalBufferLength() {
  20296. const currentTime = this.tech_.currentTime();
  20297. const initial = Config.GOAL_BUFFER_LENGTH;
  20298. const rate = Config.GOAL_BUFFER_LENGTH_RATE;
  20299. const max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  20300. return Math.min(initial + currentTime * rate, max);
  20301. }
  20302. /**
  20303. * Calculates the desired buffer low water line based on current time
  20304. *
  20305. * @return {number} Desired buffer low water line in seconds
  20306. */
  20307. bufferLowWaterLine() {
  20308. const currentTime = this.tech_.currentTime();
  20309. const initial = Config.BUFFER_LOW_WATER_LINE;
  20310. const rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  20311. const max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  20312. const newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  20313. return Math.min(initial + currentTime * rate, this.bufferBasedABR ? newMax : max);
  20314. }
  20315. bufferHighWaterLine() {
  20316. return Config.BUFFER_HIGH_WATER_LINE;
  20317. }
  20318. }
  20319. /**
  20320. * Returns a function that acts as the Enable/disable playlist function.
  20321. *
  20322. * @param {PlaylistLoader} loader - The main playlist loader
  20323. * @param {string} playlistID - id of the playlist
  20324. * @param {Function} changePlaylistFn - A function to be called after a
  20325. * playlist's enabled-state has been changed. Will NOT be called if a
  20326. * playlist's enabled-state is unchanged
  20327. * @param {boolean=} enable - Value to set the playlist enabled-state to
  20328. * or if undefined returns the current enabled-state for the playlist
  20329. * @return {Function} Function for setting/getting enabled
  20330. */
  20331. const enableFunction = (loader, playlistID, changePlaylistFn) => enable => {
  20332. const playlist = loader.main.playlists[playlistID];
  20333. const incompatible = isIncompatible(playlist);
  20334. const currentlyEnabled = isEnabled(playlist);
  20335. if (typeof enable === 'undefined') {
  20336. return currentlyEnabled;
  20337. }
  20338. if (enable) {
  20339. delete playlist.disabled;
  20340. } else {
  20341. playlist.disabled = true;
  20342. }
  20343. if (enable !== currentlyEnabled && !incompatible) {
  20344. // Ensure the outside world knows about our changes
  20345. changePlaylistFn();
  20346. if (enable) {
  20347. loader.trigger('renditionenabled');
  20348. } else {
  20349. loader.trigger('renditiondisabled');
  20350. }
  20351. }
  20352. return enable;
  20353. };
  20354. /**
  20355. * The representation object encapsulates the publicly visible information
  20356. * in a media playlist along with a setter/getter-type function (enabled)
  20357. * for changing the enabled-state of a particular playlist entry
  20358. *
  20359. * @class Representation
  20360. */
  20361. class Representation {
  20362. constructor(vhsHandler, playlist, id) {
  20363. const {
  20364. playlistController_: pc
  20365. } = vhsHandler;
  20366. const qualityChangeFunction = pc.fastQualityChange_.bind(pc); // some playlist attributes are optional
  20367. if (playlist.attributes) {
  20368. const resolution = playlist.attributes.RESOLUTION;
  20369. this.width = resolution && resolution.width;
  20370. this.height = resolution && resolution.height;
  20371. this.bandwidth = playlist.attributes.BANDWIDTH;
  20372. this.frameRate = playlist.attributes['FRAME-RATE'];
  20373. }
  20374. this.codecs = codecsForPlaylist(pc.main(), playlist);
  20375. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  20376. // within the main playlist
  20377. this.id = id; // Partially-apply the enableFunction to create a playlist-
  20378. // specific variant
  20379. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  20380. }
  20381. }
  20382. /**
  20383. * A mixin function that adds the `representations` api to an instance
  20384. * of the VhsHandler class
  20385. *
  20386. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  20387. * representation API into
  20388. */
  20389. const renditionSelectionMixin = function (vhsHandler) {
  20390. // Add a single API-specific function to the VhsHandler instance
  20391. vhsHandler.representations = () => {
  20392. const main = vhsHandler.playlistController_.main();
  20393. const playlists = isAudioOnly(main) ? vhsHandler.playlistController_.getAudioTrackPlaylists_() : main.playlists;
  20394. if (!playlists) {
  20395. return [];
  20396. }
  20397. return playlists.filter(media => !isIncompatible(media)).map((e, i) => new Representation(vhsHandler, e, e.id));
  20398. };
  20399. };
  20400. /**
  20401. * @file playback-watcher.js
  20402. *
  20403. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  20404. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  20405. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  20406. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  20407. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  20408. */
  20409. const timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  20410. /**
  20411. * @class PlaybackWatcher
  20412. */
  20413. class PlaybackWatcher {
  20414. /**
  20415. * Represents an PlaybackWatcher object.
  20416. *
  20417. * @class
  20418. * @param {Object} options an object that includes the tech and settings
  20419. */
  20420. constructor(options) {
  20421. this.playlistController_ = options.playlistController;
  20422. this.tech_ = options.tech;
  20423. this.seekable = options.seekable;
  20424. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  20425. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  20426. this.media = options.media;
  20427. this.consecutiveUpdates = 0;
  20428. this.lastRecordedTime = null;
  20429. this.checkCurrentTimeTimeout_ = null;
  20430. this.logger_ = logger('PlaybackWatcher');
  20431. this.logger_('initialize');
  20432. const playHandler = () => this.monitorCurrentTime_();
  20433. const canPlayHandler = () => this.monitorCurrentTime_();
  20434. const waitingHandler = () => this.techWaiting_();
  20435. const cancelTimerHandler = () => this.resetTimeUpdate_();
  20436. const pc = this.playlistController_;
  20437. const loaderTypes = ['main', 'subtitle', 'audio'];
  20438. const loaderChecks = {};
  20439. loaderTypes.forEach(type => {
  20440. loaderChecks[type] = {
  20441. reset: () => this.resetSegmentDownloads_(type),
  20442. updateend: () => this.checkSegmentDownloads_(type)
  20443. };
  20444. pc[`${type}SegmentLoader_`].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  20445. // isn't changing we want to reset. We cannot assume that the new rendition
  20446. // will also be stalled, until after new appends.
  20447. pc[`${type}SegmentLoader_`].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  20448. // This prevents one segment playlists (single vtt or single segment content)
  20449. // from being detected as stalling. As the buffer will not change in those cases, since
  20450. // the buffer is the entire video duration.
  20451. this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  20452. });
  20453. /**
  20454. * We check if a seek was into a gap through the following steps:
  20455. * 1. We get a seeking event and we do not get a seeked event. This means that
  20456. * a seek was attempted but not completed.
  20457. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  20458. * removed everything from our buffer and appended a segment, and should be ready
  20459. * to check for gaps.
  20460. */
  20461. const setSeekingHandlers = fn => {
  20462. ['main', 'audio'].forEach(type => {
  20463. pc[`${type}SegmentLoader_`][fn]('appended', this.seekingAppendCheck_);
  20464. });
  20465. };
  20466. this.seekingAppendCheck_ = () => {
  20467. if (this.fixesBadSeeks_()) {
  20468. this.consecutiveUpdates = 0;
  20469. this.lastRecordedTime = this.tech_.currentTime();
  20470. setSeekingHandlers('off');
  20471. }
  20472. };
  20473. this.clearSeekingAppendCheck_ = () => setSeekingHandlers('off');
  20474. this.watchForBadSeeking_ = () => {
  20475. this.clearSeekingAppendCheck_();
  20476. setSeekingHandlers('on');
  20477. };
  20478. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  20479. this.tech_.on('seeking', this.watchForBadSeeking_);
  20480. this.tech_.on('waiting', waitingHandler);
  20481. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  20482. this.tech_.on('canplay', canPlayHandler);
  20483. /*
  20484. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  20485. is surfaced in one of two ways:
  20486. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  20487. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  20488. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  20489. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  20490. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  20491. even if the player is in a playing state
  20492. */
  20493. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  20494. this.dispose = () => {
  20495. this.clearSeekingAppendCheck_();
  20496. this.logger_('dispose');
  20497. this.tech_.off('waiting', waitingHandler);
  20498. this.tech_.off(timerCancelEvents, cancelTimerHandler);
  20499. this.tech_.off('canplay', canPlayHandler);
  20500. this.tech_.off('play', playHandler);
  20501. this.tech_.off('seeking', this.watchForBadSeeking_);
  20502. this.tech_.off('seeked', this.clearSeekingAppendCheck_);
  20503. loaderTypes.forEach(type => {
  20504. pc[`${type}SegmentLoader_`].off('appendsdone', loaderChecks[type].updateend);
  20505. pc[`${type}SegmentLoader_`].off('playlistupdate', loaderChecks[type].reset);
  20506. this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  20507. });
  20508. if (this.checkCurrentTimeTimeout_) {
  20509. window__default["default"].clearTimeout(this.checkCurrentTimeTimeout_);
  20510. }
  20511. this.resetTimeUpdate_();
  20512. };
  20513. }
  20514. /**
  20515. * Periodically check current time to see if playback stopped
  20516. *
  20517. * @private
  20518. */
  20519. monitorCurrentTime_() {
  20520. this.checkCurrentTime_();
  20521. if (this.checkCurrentTimeTimeout_) {
  20522. window__default["default"].clearTimeout(this.checkCurrentTimeTimeout_);
  20523. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  20524. this.checkCurrentTimeTimeout_ = window__default["default"].setTimeout(this.monitorCurrentTime_.bind(this), 250);
  20525. }
  20526. /**
  20527. * Reset stalled download stats for a specific type of loader
  20528. *
  20529. * @param {string} type
  20530. * The segment loader type to check.
  20531. *
  20532. * @listens SegmentLoader#playlistupdate
  20533. * @listens Tech#seeking
  20534. * @listens Tech#seeked
  20535. */
  20536. resetSegmentDownloads_(type) {
  20537. const loader = this.playlistController_[`${type}SegmentLoader_`];
  20538. if (this[`${type}StalledDownloads_`] > 0) {
  20539. this.logger_(`resetting possible stalled download count for ${type} loader`);
  20540. }
  20541. this[`${type}StalledDownloads_`] = 0;
  20542. this[`${type}Buffered_`] = loader.buffered_();
  20543. }
  20544. /**
  20545. * Checks on every segment `appendsdone` to see
  20546. * if segment appends are making progress. If they are not
  20547. * and we are still downloading bytes. We exclude the playlist.
  20548. *
  20549. * @param {string} type
  20550. * The segment loader type to check.
  20551. *
  20552. * @listens SegmentLoader#appendsdone
  20553. */
  20554. checkSegmentDownloads_(type) {
  20555. const pc = this.playlistController_;
  20556. const loader = pc[`${type}SegmentLoader_`];
  20557. const buffered = loader.buffered_();
  20558. const isBufferedDifferent = isRangeDifferent(this[`${type}Buffered_`], buffered);
  20559. this[`${type}Buffered_`] = buffered; // if another watcher is going to fix the issue or
  20560. // the buffered value for this loader changed
  20561. // appends are working
  20562. if (isBufferedDifferent) {
  20563. this.resetSegmentDownloads_(type);
  20564. return;
  20565. }
  20566. this[`${type}StalledDownloads_`]++;
  20567. this.logger_(`found #${this[`${type}StalledDownloads_`]} ${type} appends that did not increase buffer (possible stalled download)`, {
  20568. playlistId: loader.playlist_ && loader.playlist_.id,
  20569. buffered: timeRangesToArray(buffered)
  20570. }); // after 10 possibly stalled appends with no reset, exclude
  20571. if (this[`${type}StalledDownloads_`] < 10) {
  20572. return;
  20573. }
  20574. this.logger_(`${type} loader stalled download exclusion`);
  20575. this.resetSegmentDownloads_(type);
  20576. this.tech_.trigger({
  20577. type: 'usage',
  20578. name: `vhs-${type}-download-exclusion`
  20579. });
  20580. if (type === 'subtitle') {
  20581. return;
  20582. } // TODO: should we exclude audio tracks rather than main tracks
  20583. // when type is audio?
  20584. pc.excludePlaylist({
  20585. error: {
  20586. message: `Excessive ${type} segment downloading detected.`
  20587. },
  20588. playlistExclusionDuration: Infinity
  20589. });
  20590. }
  20591. /**
  20592. * The purpose of this function is to emulate the "waiting" event on
  20593. * browsers that do not emit it when they are waiting for more
  20594. * data to continue playback
  20595. *
  20596. * @private
  20597. */
  20598. checkCurrentTime_() {
  20599. if (this.tech_.paused() || this.tech_.seeking()) {
  20600. return;
  20601. }
  20602. const currentTime = this.tech_.currentTime();
  20603. const buffered = this.tech_.buffered();
  20604. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  20605. // If current time is at the end of the final buffered region, then any playback
  20606. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  20607. // should fire a `waiting` event in this scenario, but due to browser and tech
  20608. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  20609. // responding to a native `waiting` event when the tech fails to emit one.
  20610. return this.techWaiting_();
  20611. }
  20612. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  20613. this.consecutiveUpdates++;
  20614. this.waiting_();
  20615. } else if (currentTime === this.lastRecordedTime) {
  20616. this.consecutiveUpdates++;
  20617. } else {
  20618. this.consecutiveUpdates = 0;
  20619. this.lastRecordedTime = currentTime;
  20620. }
  20621. }
  20622. /**
  20623. * Resets the 'timeupdate' mechanism designed to detect that we are stalled
  20624. *
  20625. * @private
  20626. */
  20627. resetTimeUpdate_() {
  20628. this.consecutiveUpdates = 0;
  20629. }
  20630. /**
  20631. * Fixes situations where there's a bad seek
  20632. *
  20633. * @return {boolean} whether an action was taken to fix the seek
  20634. * @private
  20635. */
  20636. fixesBadSeeks_() {
  20637. const seeking = this.tech_.seeking();
  20638. if (!seeking) {
  20639. return false;
  20640. } // TODO: It's possible that these seekable checks should be moved out of this function
  20641. // and into a function that runs on seekablechange. It's also possible that we only need
  20642. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  20643. // seekable range.
  20644. const seekable = this.seekable();
  20645. const currentTime = this.tech_.currentTime();
  20646. const isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  20647. let seekTo;
  20648. if (isAfterSeekableRange) {
  20649. const seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  20650. seekTo = seekableEnd;
  20651. }
  20652. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  20653. const seekableStart = seekable.start(0); // sync to the beginning of the live window
  20654. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  20655. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  20656. // happen in live with a 3 segment playlist), then don't use a time delta
  20657. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  20658. }
  20659. if (typeof seekTo !== 'undefined') {
  20660. this.logger_(`Trying to seek outside of seekable at time ${currentTime} with ` + `seekable range ${printableRange(seekable)}. Seeking to ` + `${seekTo}.`);
  20661. this.tech_.setCurrentTime(seekTo);
  20662. return true;
  20663. }
  20664. const sourceUpdater = this.playlistController_.sourceUpdater_;
  20665. const buffered = this.tech_.buffered();
  20666. const audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  20667. const videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  20668. const media = this.media(); // verify that at least two segment durations or one part duration have been
  20669. // appended before checking for a gap.
  20670. const minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  20671. // appended before checking for a gap.
  20672. const bufferedToCheck = [audioBuffered, videoBuffered];
  20673. for (let i = 0; i < bufferedToCheck.length; i++) {
  20674. // skip null buffered
  20675. if (!bufferedToCheck[i]) {
  20676. continue;
  20677. }
  20678. const timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  20679. // duration behind we haven't appended enough to call this a bad seek.
  20680. if (timeAhead < minAppendedDuration) {
  20681. return false;
  20682. }
  20683. }
  20684. const nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  20685. // to seek over the gap
  20686. if (nextRange.length === 0) {
  20687. return false;
  20688. }
  20689. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  20690. this.logger_(`Buffered region starts (${nextRange.start(0)}) ` + ` just beyond seek point (${currentTime}). Seeking to ${seekTo}.`);
  20691. this.tech_.setCurrentTime(seekTo);
  20692. return true;
  20693. }
  20694. /**
  20695. * Handler for situations when we determine the player is waiting.
  20696. *
  20697. * @private
  20698. */
  20699. waiting_() {
  20700. if (this.techWaiting_()) {
  20701. return;
  20702. } // All tech waiting checks failed. Use last resort correction
  20703. const currentTime = this.tech_.currentTime();
  20704. const buffered = this.tech_.buffered();
  20705. const currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  20706. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  20707. // currentTime is usually enough to kickstart the player. This checks that the player
  20708. // is currently within a buffered region before attempting a corrective seek.
  20709. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  20710. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  20711. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  20712. // to avoid triggering an `unknownwaiting` event when the network is slow.
  20713. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  20714. this.resetTimeUpdate_();
  20715. this.tech_.setCurrentTime(currentTime);
  20716. 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
  20717. this.tech_.trigger({
  20718. type: 'usage',
  20719. name: 'vhs-unknown-waiting'
  20720. });
  20721. return;
  20722. }
  20723. }
  20724. /**
  20725. * Handler for situations when the tech fires a `waiting` event
  20726. *
  20727. * @return {boolean}
  20728. * True if an action (or none) was needed to correct the waiting. False if no
  20729. * checks passed
  20730. * @private
  20731. */
  20732. techWaiting_() {
  20733. const seekable = this.seekable();
  20734. const currentTime = this.tech_.currentTime();
  20735. if (this.tech_.seeking()) {
  20736. // Tech is seeking or already waiting on another action, no action needed
  20737. return true;
  20738. }
  20739. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  20740. const livePoint = seekable.end(seekable.length - 1);
  20741. this.logger_(`Fell out of live window at time ${currentTime}. Seeking to ` + `live point (seekable end) ${livePoint}`);
  20742. this.resetTimeUpdate_();
  20743. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  20744. this.tech_.trigger({
  20745. type: 'usage',
  20746. name: 'vhs-live-resync'
  20747. });
  20748. return true;
  20749. }
  20750. const sourceUpdater = this.tech_.vhs.playlistController_.sourceUpdater_;
  20751. const buffered = this.tech_.buffered();
  20752. const videoUnderflow = this.videoUnderflow_({
  20753. audioBuffered: sourceUpdater.audioBuffered(),
  20754. videoBuffered: sourceUpdater.videoBuffered(),
  20755. currentTime
  20756. });
  20757. if (videoUnderflow) {
  20758. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  20759. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  20760. // allows the video to catch up to the audio position without losing any audio
  20761. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  20762. this.resetTimeUpdate_();
  20763. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  20764. this.tech_.trigger({
  20765. type: 'usage',
  20766. name: 'vhs-video-underflow'
  20767. });
  20768. return true;
  20769. }
  20770. const nextRange = findNextRange(buffered, currentTime); // check for gap
  20771. if (nextRange.length > 0) {
  20772. this.logger_(`Stopped at ${currentTime} and seeking to ${nextRange.start(0)}`);
  20773. this.resetTimeUpdate_();
  20774. this.skipTheGap_(currentTime);
  20775. return true;
  20776. } // All checks failed. Returning false to indicate failure to correct waiting
  20777. return false;
  20778. }
  20779. afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow = false) {
  20780. if (!seekable.length) {
  20781. // we can't make a solid case if there's no seekable, default to false
  20782. return false;
  20783. }
  20784. let allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  20785. const isLive = !playlist.endList;
  20786. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  20787. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  20788. }
  20789. if (currentTime > allowedEnd) {
  20790. return true;
  20791. }
  20792. return false;
  20793. }
  20794. beforeSeekableWindow_(seekable, currentTime) {
  20795. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  20796. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  20797. return true;
  20798. }
  20799. return false;
  20800. }
  20801. videoUnderflow_({
  20802. videoBuffered,
  20803. audioBuffered,
  20804. currentTime
  20805. }) {
  20806. // audio only content will not have video underflow :)
  20807. if (!videoBuffered) {
  20808. return;
  20809. }
  20810. let gap; // find a gap in demuxed content.
  20811. if (videoBuffered.length && audioBuffered.length) {
  20812. // in Chrome audio will continue to play for ~3s when we run out of video
  20813. // so we have to check that the video buffer did have some buffer in the
  20814. // past.
  20815. const lastVideoRange = findRange(videoBuffered, currentTime - 3);
  20816. const videoRange = findRange(videoBuffered, currentTime);
  20817. const audioRange = findRange(audioBuffered, currentTime);
  20818. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  20819. gap = {
  20820. start: lastVideoRange.end(0),
  20821. end: audioRange.end(0)
  20822. };
  20823. } // find a gap in muxed content.
  20824. } else {
  20825. const nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  20826. // stuck in a gap due to video underflow.
  20827. if (!nextRange.length) {
  20828. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  20829. }
  20830. }
  20831. if (gap) {
  20832. this.logger_(`Encountered a gap in video from ${gap.start} to ${gap.end}. ` + `Seeking to current time ${currentTime}`);
  20833. return true;
  20834. }
  20835. return false;
  20836. }
  20837. /**
  20838. * Timer callback. If playback still has not proceeded, then we seek
  20839. * to the start of the next buffered region.
  20840. *
  20841. * @private
  20842. */
  20843. skipTheGap_(scheduledCurrentTime) {
  20844. const buffered = this.tech_.buffered();
  20845. const currentTime = this.tech_.currentTime();
  20846. const nextRange = findNextRange(buffered, currentTime);
  20847. this.resetTimeUpdate_();
  20848. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  20849. return;
  20850. }
  20851. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  20852. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  20853. this.tech_.trigger({
  20854. type: 'usage',
  20855. name: 'vhs-gap-skip'
  20856. });
  20857. }
  20858. gapFromVideoUnderflow_(buffered, currentTime) {
  20859. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  20860. // playing for ~3 seconds after the video gap starts. This is done to account for
  20861. // video buffer underflow/underrun (note that this is not done when there is audio
  20862. // buffer underflow/underrun -- in that case the video will stop as soon as it
  20863. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  20864. // video stalls). The player's time will reflect the playthrough of audio, so the
  20865. // time will appear as if we are in a buffered region, even if we are stuck in a
  20866. // "gap."
  20867. //
  20868. // Example:
  20869. // video buffer: 0 => 10.1, 10.2 => 20
  20870. // audio buffer: 0 => 20
  20871. // overall buffer: 0 => 10.1, 10.2 => 20
  20872. // current time: 13
  20873. //
  20874. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  20875. // however, the audio continued playing until it reached ~3 seconds past the gap
  20876. // (13 seconds), at which point it stops as well. Since current time is past the
  20877. // gap, findNextRange will return no ranges.
  20878. //
  20879. // To check for this issue, we see if there is a gap that starts somewhere within
  20880. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  20881. const gaps = findGaps(buffered);
  20882. for (let i = 0; i < gaps.length; i++) {
  20883. const start = gaps.start(i);
  20884. const end = gaps.end(i); // gap is starts no more than 4 seconds back
  20885. if (currentTime - start < 4 && currentTime - start > 2) {
  20886. return {
  20887. start,
  20888. end
  20889. };
  20890. }
  20891. }
  20892. return null;
  20893. }
  20894. }
  20895. const defaultOptions = {
  20896. errorInterval: 30,
  20897. getSource(next) {
  20898. const tech = this.tech({
  20899. IWillNotUseThisInPlugins: true
  20900. });
  20901. const sourceObj = tech.currentSource_ || this.currentSource();
  20902. return next(sourceObj);
  20903. }
  20904. };
  20905. /**
  20906. * Main entry point for the plugin
  20907. *
  20908. * @param {Player} player a reference to a videojs Player instance
  20909. * @param {Object} [options] an object with plugin options
  20910. * @private
  20911. */
  20912. const initPlugin = function (player, options) {
  20913. let lastCalled = 0;
  20914. let seekTo = 0;
  20915. const localOptions = merge(defaultOptions, options);
  20916. player.ready(() => {
  20917. player.trigger({
  20918. type: 'usage',
  20919. name: 'vhs-error-reload-initialized'
  20920. });
  20921. });
  20922. /**
  20923. * Player modifications to perform that must wait until `loadedmetadata`
  20924. * has been triggered
  20925. *
  20926. * @private
  20927. */
  20928. const loadedMetadataHandler = function () {
  20929. if (seekTo) {
  20930. player.currentTime(seekTo);
  20931. }
  20932. };
  20933. /**
  20934. * Set the source on the player element, play, and seek if necessary
  20935. *
  20936. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  20937. * @private
  20938. */
  20939. const setSource = function (sourceObj) {
  20940. if (sourceObj === null || sourceObj === undefined) {
  20941. return;
  20942. }
  20943. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  20944. player.one('loadedmetadata', loadedMetadataHandler);
  20945. player.src(sourceObj);
  20946. player.trigger({
  20947. type: 'usage',
  20948. name: 'vhs-error-reload'
  20949. });
  20950. player.play();
  20951. };
  20952. /**
  20953. * Attempt to get a source from either the built-in getSource function
  20954. * or a custom function provided via the options
  20955. *
  20956. * @private
  20957. */
  20958. const errorHandler = function () {
  20959. // Do not attempt to reload the source if a source-reload occurred before
  20960. // 'errorInterval' time has elapsed since the last source-reload
  20961. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  20962. player.trigger({
  20963. type: 'usage',
  20964. name: 'vhs-error-reload-canceled'
  20965. });
  20966. return;
  20967. }
  20968. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  20969. videojs__default["default"].log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  20970. return;
  20971. }
  20972. lastCalled = Date.now();
  20973. return localOptions.getSource.call(player, setSource);
  20974. };
  20975. /**
  20976. * Unbind any event handlers that were bound by the plugin
  20977. *
  20978. * @private
  20979. */
  20980. const cleanupEvents = function () {
  20981. player.off('loadedmetadata', loadedMetadataHandler);
  20982. player.off('error', errorHandler);
  20983. player.off('dispose', cleanupEvents);
  20984. };
  20985. /**
  20986. * Cleanup before re-initializing the plugin
  20987. *
  20988. * @param {Object} [newOptions] an object with plugin options
  20989. * @private
  20990. */
  20991. const reinitPlugin = function (newOptions) {
  20992. cleanupEvents();
  20993. initPlugin(player, newOptions);
  20994. };
  20995. player.on('error', errorHandler);
  20996. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  20997. // initializing the plugin
  20998. player.reloadSourceOnError = reinitPlugin;
  20999. };
  21000. /**
  21001. * Reload the source when an error is detected as long as there
  21002. * wasn't an error previously within the last 30 seconds
  21003. *
  21004. * @param {Object} [options] an object with plugin options
  21005. */
  21006. const reloadSourceOnError = function (options) {
  21007. initPlugin(this, options);
  21008. };
  21009. var version$4 = "3.0.2";
  21010. var version$3 = "6.3.0";
  21011. var version$2 = "1.0.1";
  21012. var version$1 = "6.0.0";
  21013. var version = "4.0.1";
  21014. /**
  21015. * @file videojs-http-streaming.js
  21016. *
  21017. * The main file for the VHS project.
  21018. * License: https://github.com/videojs/videojs-http-streaming/blob/main/LICENSE
  21019. */
  21020. const Vhs = {
  21021. PlaylistLoader,
  21022. Playlist,
  21023. utils,
  21024. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  21025. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  21026. lastBandwidthSelector,
  21027. movingAverageBandwidthSelector,
  21028. comparePlaylistBandwidth,
  21029. comparePlaylistResolution,
  21030. xhr: xhrFactory()
  21031. }; // Define getter/setters for config properties
  21032. Object.keys(Config).forEach(prop => {
  21033. Object.defineProperty(Vhs, prop, {
  21034. get() {
  21035. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  21036. return Config[prop];
  21037. },
  21038. set(value) {
  21039. videojs__default["default"].log.warn(`using Vhs.${prop} is UNSAFE be sure you know what you are doing`);
  21040. if (typeof value !== 'number' || value < 0) {
  21041. videojs__default["default"].log.warn(`value of Vhs.${prop} must be greater than or equal to 0`);
  21042. return;
  21043. }
  21044. Config[prop] = value;
  21045. }
  21046. });
  21047. });
  21048. const LOCAL_STORAGE_KEY = 'videojs-vhs';
  21049. /**
  21050. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  21051. *
  21052. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  21053. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  21054. * @function handleVhsMediaChange
  21055. */
  21056. const handleVhsMediaChange = function (qualityLevels, playlistLoader) {
  21057. const newPlaylist = playlistLoader.media();
  21058. let selectedIndex = -1;
  21059. for (let i = 0; i < qualityLevels.length; i++) {
  21060. if (qualityLevels[i].id === newPlaylist.id) {
  21061. selectedIndex = i;
  21062. break;
  21063. }
  21064. }
  21065. qualityLevels.selectedIndex_ = selectedIndex;
  21066. qualityLevels.trigger({
  21067. selectedIndex,
  21068. type: 'change'
  21069. });
  21070. };
  21071. /**
  21072. * Adds quality levels to list once playlist metadata is available
  21073. *
  21074. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  21075. * @param {Object} vhs Vhs object to listen to for media events.
  21076. * @function handleVhsLoadedMetadata
  21077. */
  21078. const handleVhsLoadedMetadata = function (qualityLevels, vhs) {
  21079. vhs.representations().forEach(rep => {
  21080. qualityLevels.addQualityLevel(rep);
  21081. });
  21082. handleVhsMediaChange(qualityLevels, vhs.playlists);
  21083. }; // VHS is a source handler, not a tech. Make sure attempts to use it
  21084. // as one do not cause exceptions.
  21085. Vhs.canPlaySource = function () {
  21086. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  21087. };
  21088. const emeKeySystems = (keySystemOptions, mainPlaylist, audioPlaylist) => {
  21089. if (!keySystemOptions) {
  21090. return keySystemOptions;
  21091. }
  21092. let codecs = {};
  21093. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  21094. codecs = unwrapCodecList(codecs_js.parseCodecs(mainPlaylist.attributes.CODECS));
  21095. }
  21096. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  21097. codecs.audio = audioPlaylist.attributes.CODECS;
  21098. }
  21099. const videoContentType = codecs_js.getMimeForCodec(codecs.video);
  21100. const audioContentType = codecs_js.getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  21101. const keySystemContentTypes = {};
  21102. for (const keySystem in keySystemOptions) {
  21103. keySystemContentTypes[keySystem] = {};
  21104. if (audioContentType) {
  21105. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  21106. }
  21107. if (videoContentType) {
  21108. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  21109. } // Default to using the video playlist's PSSH even though they may be different, as
  21110. // videojs-contrib-eme will only accept one in the options.
  21111. //
  21112. // This shouldn't be an issue for most cases as early intialization will handle all
  21113. // unique PSSH values, and if they aren't, then encrypted events should have the
  21114. // specific information needed for the unique license.
  21115. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  21116. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  21117. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  21118. // so we need to prevent overwriting the URL entirely
  21119. if (typeof keySystemOptions[keySystem] === 'string') {
  21120. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  21121. }
  21122. }
  21123. return merge(keySystemOptions, keySystemContentTypes);
  21124. };
  21125. /**
  21126. * @typedef {Object} KeySystems
  21127. *
  21128. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  21129. * Note: not all options are listed here.
  21130. *
  21131. * @property {Uint8Array} [pssh]
  21132. * Protection System Specific Header
  21133. */
  21134. /**
  21135. * Goes through all the playlists and collects an array of KeySystems options objects
  21136. * containing each playlist's keySystems and their pssh values, if available.
  21137. *
  21138. * @param {Object[]} playlists
  21139. * The playlists to look through
  21140. * @param {string[]} keySystems
  21141. * The keySystems to collect pssh values for
  21142. *
  21143. * @return {KeySystems[]}
  21144. * An array of KeySystems objects containing available key systems and their
  21145. * pssh values
  21146. */
  21147. const getAllPsshKeySystemsOptions = (playlists, keySystems) => {
  21148. return playlists.reduce((keySystemsArr, playlist) => {
  21149. if (!playlist.contentProtection) {
  21150. return keySystemsArr;
  21151. }
  21152. const keySystemsOptions = keySystems.reduce((keySystemsObj, keySystem) => {
  21153. const keySystemOptions = playlist.contentProtection[keySystem];
  21154. if (keySystemOptions && keySystemOptions.pssh) {
  21155. keySystemsObj[keySystem] = {
  21156. pssh: keySystemOptions.pssh
  21157. };
  21158. }
  21159. return keySystemsObj;
  21160. }, {});
  21161. if (Object.keys(keySystemsOptions).length) {
  21162. keySystemsArr.push(keySystemsOptions);
  21163. }
  21164. return keySystemsArr;
  21165. }, []);
  21166. };
  21167. /**
  21168. * Returns a promise that waits for the
  21169. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  21170. *
  21171. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  21172. * browsers.
  21173. *
  21174. * As per the above ticket, this is particularly important for Chrome, where, if
  21175. * unencrypted content is appended before encrypted content and the key session has not
  21176. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  21177. * during playback.
  21178. *
  21179. * @param {Object} player
  21180. * The player instance
  21181. * @param {Object[]} sourceKeySystems
  21182. * The key systems options from the player source
  21183. * @param {Object} [audioMedia]
  21184. * The active audio media playlist (optional)
  21185. * @param {Object[]} mainPlaylists
  21186. * The playlists found on the main playlist object
  21187. *
  21188. * @return {Object}
  21189. * Promise that resolves when the key session has been created
  21190. */
  21191. const waitForKeySessionCreation = ({
  21192. player,
  21193. sourceKeySystems,
  21194. audioMedia,
  21195. mainPlaylists
  21196. }) => {
  21197. if (!player.eme.initializeMediaKeys) {
  21198. return Promise.resolve();
  21199. } // TODO should all audio PSSH values be initialized for DRM?
  21200. //
  21201. // All unique video rendition pssh values are initialized for DRM, but here only
  21202. // the initial audio playlist license is initialized. In theory, an encrypted
  21203. // event should be fired if the user switches to an alternative audio playlist
  21204. // where a license is required, but this case hasn't yet been tested. In addition, there
  21205. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  21206. // languages).
  21207. const playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  21208. const keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  21209. const initializationFinishedPromises = [];
  21210. const keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  21211. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  21212. // return for IE11 above, and the existence of modern EME APIs in addition to
  21213. // ms-prefixed APIs on Edge should prevent this from being a concern.
  21214. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  21215. keySystemsOptionsArr.forEach(keySystemsOptions => {
  21216. keySessionCreatedPromises.push(new Promise((resolve, reject) => {
  21217. player.tech_.one('keysessioncreated', resolve);
  21218. }));
  21219. initializationFinishedPromises.push(new Promise((resolve, reject) => {
  21220. player.eme.initializeMediaKeys({
  21221. keySystems: keySystemsOptions
  21222. }, err => {
  21223. if (err) {
  21224. reject(err);
  21225. return;
  21226. }
  21227. resolve();
  21228. });
  21229. }));
  21230. }); // The reasons Promise.race is chosen over Promise.any:
  21231. //
  21232. // * Promise.any is only available in Safari 14+.
  21233. // * None of these promises are expected to reject. If they do reject, it might be
  21234. // better here for the race to surface the rejection, rather than mask it by using
  21235. // Promise.any.
  21236. return Promise.race([// If a session was previously created, these will all finish resolving without
  21237. // creating a new session, otherwise it will take until the end of all license
  21238. // requests, which is why the key session check is used (to make setup much faster).
  21239. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  21240. Promise.race(keySessionCreatedPromises)]);
  21241. };
  21242. /**
  21243. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  21244. * there are keySystems on the source, sets up source options to prepare the source for
  21245. * eme.
  21246. *
  21247. * @param {Object} player
  21248. * The player instance
  21249. * @param {Object[]} sourceKeySystems
  21250. * The key systems options from the player source
  21251. * @param {Object} media
  21252. * The active media playlist
  21253. * @param {Object} [audioMedia]
  21254. * The active audio media playlist (optional)
  21255. *
  21256. * @return {boolean}
  21257. * Whether or not options were configured and EME is available
  21258. */
  21259. const setupEmeOptions = ({
  21260. player,
  21261. sourceKeySystems,
  21262. media,
  21263. audioMedia
  21264. }) => {
  21265. const sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  21266. if (!sourceOptions) {
  21267. return false;
  21268. }
  21269. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  21270. // do nothing.
  21271. if (sourceOptions && !player.eme) {
  21272. videojs__default["default"].log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  21273. return false;
  21274. }
  21275. return true;
  21276. };
  21277. const getVhsLocalStorage = () => {
  21278. if (!window__default["default"].localStorage) {
  21279. return null;
  21280. }
  21281. const storedObject = window__default["default"].localStorage.getItem(LOCAL_STORAGE_KEY);
  21282. if (!storedObject) {
  21283. return null;
  21284. }
  21285. try {
  21286. return JSON.parse(storedObject);
  21287. } catch (e) {
  21288. // someone may have tampered with the value
  21289. return null;
  21290. }
  21291. };
  21292. const updateVhsLocalStorage = options => {
  21293. if (!window__default["default"].localStorage) {
  21294. return false;
  21295. }
  21296. let objectToStore = getVhsLocalStorage();
  21297. objectToStore = objectToStore ? merge(objectToStore, options) : options;
  21298. try {
  21299. window__default["default"].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  21300. } catch (e) {
  21301. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  21302. // storage is set to 0).
  21303. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  21304. // No need to perform any operation.
  21305. return false;
  21306. }
  21307. return objectToStore;
  21308. };
  21309. /**
  21310. * Parses VHS-supported media types from data URIs. See
  21311. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  21312. * for information on data URIs.
  21313. *
  21314. * @param {string} dataUri
  21315. * The data URI
  21316. *
  21317. * @return {string|Object}
  21318. * The parsed object/string, or the original string if no supported media type
  21319. * was found
  21320. */
  21321. const expandDataUri = dataUri => {
  21322. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  21323. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  21324. } // no known case for this data URI, return the string as-is
  21325. return dataUri;
  21326. };
  21327. /**
  21328. * Whether the browser has built-in HLS support.
  21329. */
  21330. Vhs.supportsNativeHls = function () {
  21331. if (!document__default["default"] || !document__default["default"].createElement) {
  21332. return false;
  21333. }
  21334. const video = document__default["default"].createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  21335. if (!videojs__default["default"].getTech('Html5').isSupported()) {
  21336. return false;
  21337. } // HLS manifests can go by many mime-types
  21338. const canPlay = [// Apple santioned
  21339. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  21340. 'audio/mpegurl', // Very common
  21341. 'audio/x-mpegurl', // Very common
  21342. 'application/x-mpegurl', // Included for completeness
  21343. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  21344. return canPlay.some(function (canItPlay) {
  21345. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  21346. });
  21347. }();
  21348. Vhs.supportsNativeDash = function () {
  21349. if (!document__default["default"] || !document__default["default"].createElement || !videojs__default["default"].getTech('Html5').isSupported()) {
  21350. return false;
  21351. }
  21352. return /maybe|probably/i.test(document__default["default"].createElement('video').canPlayType('application/dash+xml'));
  21353. }();
  21354. Vhs.supportsTypeNatively = type => {
  21355. if (type === 'hls') {
  21356. return Vhs.supportsNativeHls;
  21357. }
  21358. if (type === 'dash') {
  21359. return Vhs.supportsNativeDash;
  21360. }
  21361. return false;
  21362. };
  21363. /**
  21364. * VHS is a source handler, not a tech. Make sure attempts to use it
  21365. * as one do not cause exceptions.
  21366. */
  21367. Vhs.isSupported = function () {
  21368. return videojs__default["default"].log.warn('VHS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  21369. };
  21370. const Component = videojs__default["default"].getComponent('Component');
  21371. /**
  21372. * The Vhs Handler object, where we orchestrate all of the parts
  21373. * of VHS to interact with video.js
  21374. *
  21375. * @class VhsHandler
  21376. * @extends videojs.Component
  21377. * @param {Object} source the soruce object
  21378. * @param {Tech} tech the parent tech object
  21379. * @param {Object} options optional and required options
  21380. */
  21381. class VhsHandler extends Component {
  21382. constructor(source, tech, options) {
  21383. super(tech, options.vhs); // if a tech level `initialBandwidth` option was passed
  21384. // use that over the VHS level `bandwidth` option
  21385. if (typeof options.initialBandwidth === 'number') {
  21386. this.options_.bandwidth = options.initialBandwidth;
  21387. }
  21388. this.logger_ = logger('VhsHandler'); // we need access to the player in some cases,
  21389. // so, get it from Video.js via the `playerId`
  21390. if (tech.options_ && tech.options_.playerId) {
  21391. const _player = videojs__default["default"].getPlayer(tech.options_.playerId);
  21392. this.player_ = _player;
  21393. }
  21394. this.tech_ = tech;
  21395. this.source_ = source;
  21396. this.stats = {};
  21397. this.ignoreNextSeekingEvent_ = false;
  21398. this.setOptions_();
  21399. if (this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  21400. tech.overrideNativeAudioTracks(true);
  21401. tech.overrideNativeVideoTracks(true);
  21402. } else if (this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  21403. // overriding native VHS only works if audio tracks have been emulated
  21404. // error early if we're misconfigured
  21405. throw new Error('Overriding native VHS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  21406. } // listen for fullscreenchange events for this player so that we
  21407. // can adjust our quality selection quickly
  21408. this.on(document__default["default"], ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], event => {
  21409. const fullscreenElement = document__default["default"].fullscreenElement || document__default["default"].webkitFullscreenElement || document__default["default"].mozFullScreenElement || document__default["default"].msFullscreenElement;
  21410. if (fullscreenElement && fullscreenElement.contains(this.tech_.el())) {
  21411. this.playlistController_.fastQualityChange_();
  21412. } else {
  21413. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  21414. // than full screen, see if there should be a rendition switch down to preserve
  21415. // bandwidth.
  21416. this.playlistController_.checkABR_();
  21417. }
  21418. });
  21419. this.on(this.tech_, 'seeking', function () {
  21420. if (this.ignoreNextSeekingEvent_) {
  21421. this.ignoreNextSeekingEvent_ = false;
  21422. return;
  21423. }
  21424. this.setCurrentTime(this.tech_.currentTime());
  21425. });
  21426. this.on(this.tech_, 'error', function () {
  21427. // verify that the error was real and we are loaded
  21428. // enough to have pc loaded.
  21429. if (this.tech_.error() && this.playlistController_) {
  21430. this.playlistController_.pauseLoading();
  21431. }
  21432. });
  21433. this.on(this.tech_, 'play', this.play);
  21434. }
  21435. setOptions_() {
  21436. // defaults
  21437. this.options_.withCredentials = this.options_.withCredentials || false;
  21438. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  21439. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  21440. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  21441. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  21442. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  21443. this.options_.customTagParsers = this.options_.customTagParsers || [];
  21444. this.options_.customTagMappers = this.options_.customTagMappers || [];
  21445. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  21446. this.options_.llhls = this.options_.llhls === false ? false : true;
  21447. this.options_.bufferBasedABR = this.options_.bufferBasedABR || false;
  21448. if (typeof this.options_.playlistExclusionDuration !== 'number') {
  21449. this.options_.playlistExclusionDuration = 5 * 60;
  21450. }
  21451. if (typeof this.options_.bandwidth !== 'number') {
  21452. if (this.options_.useBandwidthFromLocalStorage) {
  21453. const storedObject = getVhsLocalStorage();
  21454. if (storedObject && storedObject.bandwidth) {
  21455. this.options_.bandwidth = storedObject.bandwidth;
  21456. this.tech_.trigger({
  21457. type: 'usage',
  21458. name: 'vhs-bandwidth-from-local-storage'
  21459. });
  21460. }
  21461. if (storedObject && storedObject.throughput) {
  21462. this.options_.throughput = storedObject.throughput;
  21463. this.tech_.trigger({
  21464. type: 'usage',
  21465. name: 'vhs-throughput-from-local-storage'
  21466. });
  21467. }
  21468. }
  21469. } // if bandwidth was not set by options or pulled from local storage, start playlist
  21470. // selection at a reasonable bandwidth
  21471. if (typeof this.options_.bandwidth !== 'number') {
  21472. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  21473. } // If the bandwidth number is unchanged from the initial setting
  21474. // then this takes precedence over the enableLowInitialPlaylist option
  21475. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  21476. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'customTagParsers', 'customTagMappers', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'bufferBasedABR', 'liveRangeSafeTimeDelta', 'llhls', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'exactManifestTimings', 'leastPixelDiffSelector'].forEach(option => {
  21477. if (typeof this.source_[option] !== 'undefined') {
  21478. this.options_[option] = this.source_[option];
  21479. }
  21480. });
  21481. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  21482. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  21483. }
  21484. /**
  21485. * called when player.src gets called, handle a new source
  21486. *
  21487. * @param {Object} src the source object to handle
  21488. */
  21489. src(src, type) {
  21490. // do nothing if the src is falsey
  21491. if (!src) {
  21492. return;
  21493. }
  21494. this.setOptions_(); // add main playlist controller options
  21495. this.options_.src = expandDataUri(this.source_.src);
  21496. this.options_.tech = this.tech_;
  21497. this.options_.externVhs = Vhs;
  21498. this.options_.sourceType = mediaTypes_js.simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  21499. this.options_.seekTo = time => {
  21500. this.tech_.setCurrentTime(time);
  21501. };
  21502. this.playlistController_ = new PlaylistController(this.options_);
  21503. const playbackWatcherOptions = merge({
  21504. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  21505. }, this.options_, {
  21506. seekable: () => this.seekable(),
  21507. media: () => this.playlistController_.media(),
  21508. playlistController: this.playlistController_
  21509. });
  21510. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  21511. this.playlistController_.on('error', () => {
  21512. const player = videojs__default["default"].players[this.tech_.options_.playerId];
  21513. let error = this.playlistController_.error;
  21514. if (typeof error === 'object' && !error.code) {
  21515. error.code = 3;
  21516. } else if (typeof error === 'string') {
  21517. error = {
  21518. message: error,
  21519. code: 3
  21520. };
  21521. }
  21522. player.error(error);
  21523. });
  21524. const defaultSelector = this.options_.bufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  21525. // compatibility with < v2
  21526. this.playlistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  21527. this.playlistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  21528. this.playlists = this.playlistController_.mainPlaylistLoader_;
  21529. this.mediaSource = this.playlistController_.mediaSource; // Proxy assignment of some properties to the main playlist
  21530. // controller. Using a custom property for backwards compatibility
  21531. // with < v2
  21532. Object.defineProperties(this, {
  21533. selectPlaylist: {
  21534. get() {
  21535. return this.playlistController_.selectPlaylist;
  21536. },
  21537. set(selectPlaylist) {
  21538. this.playlistController_.selectPlaylist = selectPlaylist.bind(this);
  21539. }
  21540. },
  21541. throughput: {
  21542. get() {
  21543. return this.playlistController_.mainSegmentLoader_.throughput.rate;
  21544. },
  21545. set(throughput) {
  21546. this.playlistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  21547. // for the cumulative average
  21548. this.playlistController_.mainSegmentLoader_.throughput.count = 1;
  21549. }
  21550. },
  21551. bandwidth: {
  21552. get() {
  21553. let playerBandwidthEst = this.playlistController_.mainSegmentLoader_.bandwidth;
  21554. const networkInformation = window__default["default"].navigator.connection || window__default["default"].navigator.mozConnection || window__default["default"].navigator.webkitConnection;
  21555. const tenMbpsAsBitsPerSecond = 10e6;
  21556. if (this.options_.useNetworkInformationApi && networkInformation) {
  21557. // downlink returns Mbps
  21558. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  21559. const networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  21560. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  21561. // high quality streams are not filtered out.
  21562. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  21563. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  21564. } else {
  21565. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  21566. }
  21567. }
  21568. return playerBandwidthEst;
  21569. },
  21570. set(bandwidth) {
  21571. this.playlistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  21572. // `count` is set to zero that current value of `rate` isn't included
  21573. // in the cumulative average
  21574. this.playlistController_.mainSegmentLoader_.throughput = {
  21575. rate: 0,
  21576. count: 0
  21577. };
  21578. }
  21579. },
  21580. /**
  21581. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  21582. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  21583. * the entire process after that - decryption, transmuxing, and appending - provided
  21584. * by `throughput`.
  21585. *
  21586. * Since the two process are serial, the overall system bandwidth is given by:
  21587. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  21588. */
  21589. systemBandwidth: {
  21590. get() {
  21591. const invBandwidth = 1 / (this.bandwidth || 1);
  21592. let invThroughput;
  21593. if (this.throughput > 0) {
  21594. invThroughput = 1 / this.throughput;
  21595. } else {
  21596. invThroughput = 0;
  21597. }
  21598. const systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  21599. return systemBitrate;
  21600. },
  21601. set() {
  21602. videojs__default["default"].log.error('The "systemBandwidth" property is read-only');
  21603. }
  21604. }
  21605. });
  21606. if (this.options_.bandwidth) {
  21607. this.bandwidth = this.options_.bandwidth;
  21608. }
  21609. if (this.options_.throughput) {
  21610. this.throughput = this.options_.throughput;
  21611. }
  21612. Object.defineProperties(this.stats, {
  21613. bandwidth: {
  21614. get: () => this.bandwidth || 0,
  21615. enumerable: true
  21616. },
  21617. mediaRequests: {
  21618. get: () => this.playlistController_.mediaRequests_() || 0,
  21619. enumerable: true
  21620. },
  21621. mediaRequestsAborted: {
  21622. get: () => this.playlistController_.mediaRequestsAborted_() || 0,
  21623. enumerable: true
  21624. },
  21625. mediaRequestsTimedout: {
  21626. get: () => this.playlistController_.mediaRequestsTimedout_() || 0,
  21627. enumerable: true
  21628. },
  21629. mediaRequestsErrored: {
  21630. get: () => this.playlistController_.mediaRequestsErrored_() || 0,
  21631. enumerable: true
  21632. },
  21633. mediaTransferDuration: {
  21634. get: () => this.playlistController_.mediaTransferDuration_() || 0,
  21635. enumerable: true
  21636. },
  21637. mediaBytesTransferred: {
  21638. get: () => this.playlistController_.mediaBytesTransferred_() || 0,
  21639. enumerable: true
  21640. },
  21641. mediaSecondsLoaded: {
  21642. get: () => this.playlistController_.mediaSecondsLoaded_() || 0,
  21643. enumerable: true
  21644. },
  21645. mediaAppends: {
  21646. get: () => this.playlistController_.mediaAppends_() || 0,
  21647. enumerable: true
  21648. },
  21649. mainAppendsToLoadedData: {
  21650. get: () => this.playlistController_.mainAppendsToLoadedData_() || 0,
  21651. enumerable: true
  21652. },
  21653. audioAppendsToLoadedData: {
  21654. get: () => this.playlistController_.audioAppendsToLoadedData_() || 0,
  21655. enumerable: true
  21656. },
  21657. appendsToLoadedData: {
  21658. get: () => this.playlistController_.appendsToLoadedData_() || 0,
  21659. enumerable: true
  21660. },
  21661. timeToLoadedData: {
  21662. get: () => this.playlistController_.timeToLoadedData_() || 0,
  21663. enumerable: true
  21664. },
  21665. buffered: {
  21666. get: () => timeRangesToArray(this.tech_.buffered()),
  21667. enumerable: true
  21668. },
  21669. currentTime: {
  21670. get: () => this.tech_.currentTime(),
  21671. enumerable: true
  21672. },
  21673. currentSource: {
  21674. get: () => this.tech_.currentSource_,
  21675. enumerable: true
  21676. },
  21677. currentTech: {
  21678. get: () => this.tech_.name_,
  21679. enumerable: true
  21680. },
  21681. duration: {
  21682. get: () => this.tech_.duration(),
  21683. enumerable: true
  21684. },
  21685. main: {
  21686. get: () => this.playlists.main,
  21687. enumerable: true
  21688. },
  21689. playerDimensions: {
  21690. get: () => this.tech_.currentDimensions(),
  21691. enumerable: true
  21692. },
  21693. seekable: {
  21694. get: () => timeRangesToArray(this.tech_.seekable()),
  21695. enumerable: true
  21696. },
  21697. timestamp: {
  21698. get: () => Date.now(),
  21699. enumerable: true
  21700. },
  21701. videoPlaybackQuality: {
  21702. get: () => this.tech_.getVideoPlaybackQuality(),
  21703. enumerable: true
  21704. }
  21705. });
  21706. this.tech_.one('canplay', this.playlistController_.setupFirstPlay.bind(this.playlistController_));
  21707. this.tech_.on('bandwidthupdate', () => {
  21708. if (this.options_.useBandwidthFromLocalStorage) {
  21709. updateVhsLocalStorage({
  21710. bandwidth: this.bandwidth,
  21711. throughput: Math.round(this.throughput)
  21712. });
  21713. }
  21714. });
  21715. this.playlistController_.on('selectedinitialmedia', () => {
  21716. // Add the manual rendition mix-in to VhsHandler
  21717. renditionSelectionMixin(this);
  21718. });
  21719. this.playlistController_.sourceUpdater_.on('createdsourcebuffers', () => {
  21720. this.setupEme_();
  21721. }); // the bandwidth of the primary segment loader is our best
  21722. // estimate of overall bandwidth
  21723. this.on(this.playlistController_, 'progress', function () {
  21724. this.tech_.trigger('progress');
  21725. }); // In the live case, we need to ignore the very first `seeking` event since
  21726. // that will be the result of the seek-to-live behavior
  21727. this.on(this.playlistController_, 'firstplay', function () {
  21728. this.ignoreNextSeekingEvent_ = true;
  21729. });
  21730. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  21731. // this can occur if someone sets the src in player.ready(), for instance
  21732. if (!this.tech_.el()) {
  21733. return;
  21734. }
  21735. this.mediaSourceUrl_ = window__default["default"].URL.createObjectURL(this.playlistController_.mediaSource);
  21736. this.tech_.src(this.mediaSourceUrl_);
  21737. }
  21738. createKeySessions_() {
  21739. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  21740. this.logger_('waiting for EME key session creation');
  21741. waitForKeySessionCreation({
  21742. player: this.player_,
  21743. sourceKeySystems: this.source_.keySystems,
  21744. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  21745. mainPlaylists: this.playlists.main.playlists
  21746. }).then(() => {
  21747. this.logger_('created EME key session');
  21748. this.playlistController_.sourceUpdater_.initializedEme();
  21749. }).catch(err => {
  21750. this.logger_('error while creating EME key session', err);
  21751. this.player_.error({
  21752. message: 'Failed to initialize media keys for EME',
  21753. code: 3
  21754. });
  21755. });
  21756. }
  21757. handleWaitingForKey_() {
  21758. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  21759. // the key is in the manifest. While this should've happened on initial source load, it
  21760. // may happen again in live streams where the keys change, and the manifest info
  21761. // reflects the update.
  21762. //
  21763. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  21764. // already requested keys for, we don't have to worry about this generating extraneous
  21765. // requests.
  21766. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  21767. this.createKeySessions_();
  21768. }
  21769. /**
  21770. * If necessary and EME is available, sets up EME options and waits for key session
  21771. * creation.
  21772. *
  21773. * This function also updates the source updater so taht it can be used, as for some
  21774. * browsers, EME must be configured before content is appended (if appending unencrypted
  21775. * content before encrypted content).
  21776. */
  21777. setupEme_() {
  21778. const audioPlaylistLoader = this.playlistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  21779. const didSetupEmeOptions = setupEmeOptions({
  21780. player: this.player_,
  21781. sourceKeySystems: this.source_.keySystems,
  21782. media: this.playlists.media(),
  21783. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  21784. });
  21785. this.player_.tech_.on('keystatuschange', e => {
  21786. if (e.status !== 'output-restricted') {
  21787. return;
  21788. }
  21789. const mainPlaylist = this.playlistController_.main();
  21790. if (!mainPlaylist || !mainPlaylist.playlists) {
  21791. return;
  21792. }
  21793. const excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  21794. mainPlaylist.playlists.forEach(playlist => {
  21795. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  21796. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  21797. playlist.excludeUntil = Infinity;
  21798. excludedHDPlaylists.push(playlist);
  21799. }
  21800. }
  21801. });
  21802. if (excludedHDPlaylists.length) {
  21803. videojs__default["default"].log.warn('DRM keystatus changed to "output-restricted." Removing the following HD playlists ' + 'that will most likely fail to play and clearing the buffer. ' + 'This may be due to HDCP restrictions on the stream and the capabilities of the current device.', ...excludedHDPlaylists); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  21804. this.playlistController_.fastQualityChange_();
  21805. }
  21806. });
  21807. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  21808. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  21809. // promises.
  21810. if (videojs__default["default"].browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  21811. // If EME options were not set up, we've done all we could to initialize EME.
  21812. this.playlistController_.sourceUpdater_.initializedEme();
  21813. return;
  21814. }
  21815. this.createKeySessions_();
  21816. }
  21817. /**
  21818. * Initializes the quality levels and sets listeners to update them.
  21819. *
  21820. * @method setupQualityLevels_
  21821. * @private
  21822. */
  21823. setupQualityLevels_() {
  21824. const player = videojs__default["default"].players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  21825. // or qualityLevels_ listeners have already been setup, do nothing.
  21826. if (!player || !player.qualityLevels || this.qualityLevels_) {
  21827. return;
  21828. }
  21829. this.qualityLevels_ = player.qualityLevels();
  21830. this.playlistController_.on('selectedinitialmedia', () => {
  21831. handleVhsLoadedMetadata(this.qualityLevels_, this);
  21832. });
  21833. this.playlists.on('mediachange', () => {
  21834. handleVhsMediaChange(this.qualityLevels_, this.playlists);
  21835. });
  21836. }
  21837. /**
  21838. * return the version
  21839. */
  21840. static version() {
  21841. return {
  21842. '@videojs/http-streaming': version$4,
  21843. 'mux.js': version$3,
  21844. 'mpd-parser': version$2,
  21845. 'm3u8-parser': version$1,
  21846. 'aes-decrypter': version
  21847. };
  21848. }
  21849. /**
  21850. * return the version
  21851. */
  21852. version() {
  21853. return this.constructor.version();
  21854. }
  21855. canChangeType() {
  21856. return SourceUpdater.canChangeType();
  21857. }
  21858. /**
  21859. * Begin playing the video.
  21860. */
  21861. play() {
  21862. this.playlistController_.play();
  21863. }
  21864. /**
  21865. * a wrapper around the function in PlaylistController
  21866. */
  21867. setCurrentTime(currentTime) {
  21868. this.playlistController_.setCurrentTime(currentTime);
  21869. }
  21870. /**
  21871. * a wrapper around the function in PlaylistController
  21872. */
  21873. duration() {
  21874. return this.playlistController_.duration();
  21875. }
  21876. /**
  21877. * a wrapper around the function in PlaylistController
  21878. */
  21879. seekable() {
  21880. return this.playlistController_.seekable();
  21881. }
  21882. /**
  21883. * Abort all outstanding work and cleanup.
  21884. */
  21885. dispose() {
  21886. if (this.playbackWatcher_) {
  21887. this.playbackWatcher_.dispose();
  21888. }
  21889. if (this.playlistController_) {
  21890. this.playlistController_.dispose();
  21891. }
  21892. if (this.qualityLevels_) {
  21893. this.qualityLevels_.dispose();
  21894. }
  21895. if (this.tech_ && this.tech_.vhs) {
  21896. delete this.tech_.vhs;
  21897. }
  21898. if (this.mediaSourceUrl_ && window__default["default"].URL.revokeObjectURL) {
  21899. window__default["default"].URL.revokeObjectURL(this.mediaSourceUrl_);
  21900. this.mediaSourceUrl_ = null;
  21901. }
  21902. if (this.tech_) {
  21903. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  21904. }
  21905. super.dispose();
  21906. }
  21907. convertToProgramTime(time, callback) {
  21908. return getProgramTime({
  21909. playlist: this.playlistController_.media(),
  21910. time,
  21911. callback
  21912. });
  21913. } // the player must be playing before calling this
  21914. seekToProgramTime(programTime, callback, pauseAfterSeek = true, retryCount = 2) {
  21915. return seekToProgramTime({
  21916. programTime,
  21917. playlist: this.playlistController_.media(),
  21918. retryCount,
  21919. pauseAfterSeek,
  21920. seekTo: this.options_.seekTo,
  21921. tech: this.options_.tech,
  21922. callback
  21923. });
  21924. }
  21925. }
  21926. /**
  21927. * The Source Handler object, which informs video.js what additional
  21928. * MIME types are supported and sets up playback. It is registered
  21929. * automatically to the appropriate tech based on the capabilities of
  21930. * the browser it is running in. It is not necessary to use or modify
  21931. * this object in normal usage.
  21932. */
  21933. const VhsSourceHandler = {
  21934. name: 'videojs-http-streaming',
  21935. VERSION: version$4,
  21936. canHandleSource(srcObj, options = {}) {
  21937. const localOptions = merge(videojs__default["default"].options, options);
  21938. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  21939. },
  21940. handleSource(source, tech, options = {}) {
  21941. const localOptions = merge(videojs__default["default"].options, options);
  21942. tech.vhs = new VhsHandler(source, tech, localOptions);
  21943. tech.vhs.xhr = xhrFactory();
  21944. tech.vhs.src(source.src, source.type);
  21945. return tech.vhs;
  21946. },
  21947. canPlayType(type, options) {
  21948. const simpleType = mediaTypes_js.simpleTypeFromSourceType(type);
  21949. if (!simpleType) {
  21950. return '';
  21951. }
  21952. const overrideNative = VhsSourceHandler.getOverrideNative(options);
  21953. const supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  21954. const canUseMsePlayback = !supportsTypeNatively || overrideNative;
  21955. return canUseMsePlayback ? 'maybe' : '';
  21956. },
  21957. getOverrideNative(options = {}) {
  21958. const {
  21959. vhs = {}
  21960. } = options;
  21961. const defaultOverrideNative = !(videojs__default["default"].browser.IS_ANY_SAFARI || videojs__default["default"].browser.IS_IOS);
  21962. const {
  21963. overrideNative = defaultOverrideNative
  21964. } = vhs;
  21965. return overrideNative;
  21966. }
  21967. };
  21968. /**
  21969. * Check to see if the native MediaSource object exists and supports
  21970. * an MP4 container with both H.264 video and AAC-LC audio.
  21971. *
  21972. * @return {boolean} if native media sources are supported
  21973. */
  21974. const supportsNativeMediaSources = () => {
  21975. return codecs_js.browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  21976. }; // register source handlers with the appropriate techs
  21977. if (supportsNativeMediaSources()) {
  21978. videojs__default["default"].getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  21979. }
  21980. videojs__default["default"].VhsHandler = VhsHandler;
  21981. videojs__default["default"].VhsSourceHandler = VhsSourceHandler;
  21982. videojs__default["default"].Vhs = Vhs;
  21983. if (!videojs__default["default"].use) {
  21984. videojs__default["default"].registerComponent('Vhs', Vhs);
  21985. }
  21986. videojs__default["default"].options.vhs = videojs__default["default"].options.vhs || {};
  21987. if (!videojs__default["default"].getPlugin || !videojs__default["default"].getPlugin('reloadSourceOnError')) {
  21988. videojs__default["default"].registerPlugin('reloadSourceOnError', reloadSourceOnError);
  21989. }
  21990. Object.defineProperty(exports, 'simpleTypeFromSourceType', {
  21991. enumerable: true,
  21992. get: function () { return mediaTypes_js.simpleTypeFromSourceType; }
  21993. });
  21994. exports.LOCAL_STORAGE_KEY = LOCAL_STORAGE_KEY;
  21995. exports.Vhs = Vhs;
  21996. exports.VhsHandler = VhsHandler;
  21997. exports.VhsSourceHandler = VhsSourceHandler;
  21998. exports.emeKeySystems = emeKeySystems;
  21999. exports.expandDataUri = expandDataUri;
  22000. exports.getAllPsshKeySystemsOptions = getAllPsshKeySystemsOptions;
  22001. exports.setupEmeOptions = setupEmeOptions;
  22002. exports.waitForKeySessionCreation = waitForKeySessionCreation;