hls.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404
  1. (function __HLS_WORKER_BUNDLE__(__IN_WORKER__){
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Hls = factory());
  6. })(this, (function () { 'use strict';
  7. function _construct(t, e, r) {
  8. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  9. var o = [null];
  10. o.push.apply(o, e);
  11. var p = new (t.bind.apply(t, o))();
  12. return r && _setPrototypeOf(p, r.prototype), p;
  13. }
  14. function _defineProperties(e, r) {
  15. for (var t = 0; t < r.length; t++) {
  16. var o = r[t];
  17. o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
  18. }
  19. }
  20. function _createClass(e, r, t) {
  21. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  22. writable: false
  23. }), e;
  24. }
  25. function _defineProperty(e, r, t) {
  26. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  27. value: t,
  28. enumerable: true,
  29. configurable: true,
  30. writable: true
  31. }) : e[r] = t, e;
  32. }
  33. function _extends() {
  34. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  35. for (var e = 1; e < arguments.length; e++) {
  36. var t = arguments[e];
  37. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  38. }
  39. return n;
  40. }, _extends.apply(null, arguments);
  41. }
  42. function _getPrototypeOf(t) {
  43. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  44. return t.__proto__ || Object.getPrototypeOf(t);
  45. }, _getPrototypeOf(t);
  46. }
  47. function _inheritsLoose(t, o) {
  48. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  49. }
  50. function _isNativeFunction(t) {
  51. try {
  52. return -1 !== Function.toString.call(t).indexOf("[native code]");
  53. } catch (n) {
  54. return "function" == typeof t;
  55. }
  56. }
  57. function _isNativeReflectConstruct() {
  58. try {
  59. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  60. } catch (t) {}
  61. return (_isNativeReflectConstruct = function () {
  62. return !!t;
  63. })();
  64. }
  65. function ownKeys(e, r) {
  66. var t = Object.keys(e);
  67. if (Object.getOwnPropertySymbols) {
  68. var o = Object.getOwnPropertySymbols(e);
  69. r && (o = o.filter(function (r) {
  70. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  71. })), t.push.apply(t, o);
  72. }
  73. return t;
  74. }
  75. function _objectSpread2(e) {
  76. for (var r = 1; r < arguments.length; r++) {
  77. var t = null != arguments[r] ? arguments[r] : {};
  78. r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
  79. _defineProperty(e, r, t[r]);
  80. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  81. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  82. });
  83. }
  84. return e;
  85. }
  86. function _setPrototypeOf(t, e) {
  87. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  88. return t.__proto__ = e, t;
  89. }, _setPrototypeOf(t, e);
  90. }
  91. function _toPrimitive(t, r) {
  92. if ("object" != typeof t || !t) return t;
  93. var e = t[Symbol.toPrimitive];
  94. if (void 0 !== e) {
  95. var i = e.call(t, r);
  96. if ("object" != typeof i) return i;
  97. throw new TypeError("@@toPrimitive must return a primitive value.");
  98. }
  99. return ("string" === r ? String : Number)(t);
  100. }
  101. function _toPropertyKey(t) {
  102. var i = _toPrimitive(t, "string");
  103. return "symbol" == typeof i ? i : i + "";
  104. }
  105. function _wrapNativeSuper(t) {
  106. var r = "function" == typeof Map ? new Map() : void 0;
  107. return _wrapNativeSuper = function (t) {
  108. if (null === t || !_isNativeFunction(t)) return t;
  109. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  110. if (void 0 !== r) {
  111. if (r.has(t)) return r.get(t);
  112. r.set(t, Wrapper);
  113. }
  114. function Wrapper() {
  115. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  116. }
  117. return Wrapper.prototype = Object.create(t.prototype, {
  118. constructor: {
  119. value: Wrapper,
  120. enumerable: false,
  121. writable: true,
  122. configurable: true
  123. }
  124. }), _setPrototypeOf(Wrapper, t);
  125. }, _wrapNativeSuper(t);
  126. }
  127. /**
  128. * Generate a random v4 UUID
  129. *
  130. * @returns A random v4 UUID
  131. *
  132. * @group Utils
  133. *
  134. * @beta
  135. */
  136. function uuid() {
  137. try {
  138. return crypto.randomUUID();
  139. } catch (error) {
  140. try {
  141. var url = URL.createObjectURL(new Blob());
  142. var _uuid = url.toString();
  143. URL.revokeObjectURL(url);
  144. return _uuid.slice(_uuid.lastIndexOf('/') + 1);
  145. } catch (error) {
  146. var dt = new Date().getTime();
  147. var _uuid2 = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  148. var r = (dt + Math.random() * 16) % 16 | 0;
  149. dt = Math.floor(dt / 16);
  150. return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
  151. });
  152. return _uuid2;
  153. }
  154. }
  155. }
  156. function getDefaultExportFromCjs (x) {
  157. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  158. }
  159. var eventemitter3 = {exports: {}};
  160. var hasRequiredEventemitter3;
  161. function requireEventemitter3 () {
  162. if (hasRequiredEventemitter3) return eventemitter3.exports;
  163. hasRequiredEventemitter3 = 1;
  164. (function (module) {
  165. var has = Object.prototype.hasOwnProperty
  166. , prefix = '~';
  167. /**
  168. * Constructor to create a storage for our `EE` objects.
  169. * An `Events` instance is a plain object whose properties are event names.
  170. *
  171. * @constructor
  172. * @private
  173. */
  174. function Events() {}
  175. //
  176. // We try to not inherit from `Object.prototype`. In some engines creating an
  177. // instance in this way is faster than calling `Object.create(null)` directly.
  178. // If `Object.create(null)` is not supported we prefix the event names with a
  179. // character to make sure that the built-in object properties are not
  180. // overridden or used as an attack vector.
  181. //
  182. if (Object.create) {
  183. Events.prototype = Object.create(null);
  184. //
  185. // This hack is needed because the `__proto__` property is still inherited in
  186. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  187. //
  188. if (!new Events().__proto__) prefix = false;
  189. }
  190. /**
  191. * Representation of a single event listener.
  192. *
  193. * @param {Function} fn The listener function.
  194. * @param {*} context The context to invoke the listener with.
  195. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  196. * @constructor
  197. * @private
  198. */
  199. function EE(fn, context, once) {
  200. this.fn = fn;
  201. this.context = context;
  202. this.once = once || false;
  203. }
  204. /**
  205. * Add a listener for a given event.
  206. *
  207. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  208. * @param {(String|Symbol)} event The event name.
  209. * @param {Function} fn The listener function.
  210. * @param {*} context The context to invoke the listener with.
  211. * @param {Boolean} once Specify if the listener is a one-time listener.
  212. * @returns {EventEmitter}
  213. * @private
  214. */
  215. function addListener(emitter, event, fn, context, once) {
  216. if (typeof fn !== 'function') {
  217. throw new TypeError('The listener must be a function');
  218. }
  219. var listener = new EE(fn, context || emitter, once)
  220. , evt = prefix ? prefix + event : event;
  221. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  222. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  223. else emitter._events[evt] = [emitter._events[evt], listener];
  224. return emitter;
  225. }
  226. /**
  227. * Clear event by name.
  228. *
  229. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  230. * @param {(String|Symbol)} evt The Event name.
  231. * @private
  232. */
  233. function clearEvent(emitter, evt) {
  234. if (--emitter._eventsCount === 0) emitter._events = new Events();
  235. else delete emitter._events[evt];
  236. }
  237. /**
  238. * Minimal `EventEmitter` interface that is molded against the Node.js
  239. * `EventEmitter` interface.
  240. *
  241. * @constructor
  242. * @public
  243. */
  244. function EventEmitter() {
  245. this._events = new Events();
  246. this._eventsCount = 0;
  247. }
  248. /**
  249. * Return an array listing the events for which the emitter has registered
  250. * listeners.
  251. *
  252. * @returns {Array}
  253. * @public
  254. */
  255. EventEmitter.prototype.eventNames = function eventNames() {
  256. var names = []
  257. , events
  258. , name;
  259. if (this._eventsCount === 0) return names;
  260. for (name in (events = this._events)) {
  261. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  262. }
  263. if (Object.getOwnPropertySymbols) {
  264. return names.concat(Object.getOwnPropertySymbols(events));
  265. }
  266. return names;
  267. };
  268. /**
  269. * Return the listeners registered for a given event.
  270. *
  271. * @param {(String|Symbol)} event The event name.
  272. * @returns {Array} The registered listeners.
  273. * @public
  274. */
  275. EventEmitter.prototype.listeners = function listeners(event) {
  276. var evt = prefix ? prefix + event : event
  277. , handlers = this._events[evt];
  278. if (!handlers) return [];
  279. if (handlers.fn) return [handlers.fn];
  280. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  281. ee[i] = handlers[i].fn;
  282. }
  283. return ee;
  284. };
  285. /**
  286. * Return the number of listeners listening to a given event.
  287. *
  288. * @param {(String|Symbol)} event The event name.
  289. * @returns {Number} The number of listeners.
  290. * @public
  291. */
  292. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  293. var evt = prefix ? prefix + event : event
  294. , listeners = this._events[evt];
  295. if (!listeners) return 0;
  296. if (listeners.fn) return 1;
  297. return listeners.length;
  298. };
  299. /**
  300. * Calls each of the listeners registered for a given event.
  301. *
  302. * @param {(String|Symbol)} event The event name.
  303. * @returns {Boolean} `true` if the event had listeners, else `false`.
  304. * @public
  305. */
  306. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  307. var evt = prefix ? prefix + event : event;
  308. if (!this._events[evt]) return false;
  309. var listeners = this._events[evt]
  310. , len = arguments.length
  311. , args
  312. , i;
  313. if (listeners.fn) {
  314. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  315. switch (len) {
  316. case 1: return listeners.fn.call(listeners.context), true;
  317. case 2: return listeners.fn.call(listeners.context, a1), true;
  318. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  319. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  320. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  321. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  322. }
  323. for (i = 1, args = new Array(len -1); i < len; i++) {
  324. args[i - 1] = arguments[i];
  325. }
  326. listeners.fn.apply(listeners.context, args);
  327. } else {
  328. var length = listeners.length
  329. , j;
  330. for (i = 0; i < length; i++) {
  331. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  332. switch (len) {
  333. case 1: listeners[i].fn.call(listeners[i].context); break;
  334. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  335. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  336. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  337. default:
  338. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  339. args[j - 1] = arguments[j];
  340. }
  341. listeners[i].fn.apply(listeners[i].context, args);
  342. }
  343. }
  344. }
  345. return true;
  346. };
  347. /**
  348. * Add a listener for a given event.
  349. *
  350. * @param {(String|Symbol)} event The event name.
  351. * @param {Function} fn The listener function.
  352. * @param {*} [context=this] The context to invoke the listener with.
  353. * @returns {EventEmitter} `this`.
  354. * @public
  355. */
  356. EventEmitter.prototype.on = function on(event, fn, context) {
  357. return addListener(this, event, fn, context, false);
  358. };
  359. /**
  360. * Add a one-time listener for a given event.
  361. *
  362. * @param {(String|Symbol)} event The event name.
  363. * @param {Function} fn The listener function.
  364. * @param {*} [context=this] The context to invoke the listener with.
  365. * @returns {EventEmitter} `this`.
  366. * @public
  367. */
  368. EventEmitter.prototype.once = function once(event, fn, context) {
  369. return addListener(this, event, fn, context, true);
  370. };
  371. /**
  372. * Remove the listeners of a given event.
  373. *
  374. * @param {(String|Symbol)} event The event name.
  375. * @param {Function} fn Only remove the listeners that match this function.
  376. * @param {*} context Only remove the listeners that have this context.
  377. * @param {Boolean} once Only remove one-time listeners.
  378. * @returns {EventEmitter} `this`.
  379. * @public
  380. */
  381. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  382. var evt = prefix ? prefix + event : event;
  383. if (!this._events[evt]) return this;
  384. if (!fn) {
  385. clearEvent(this, evt);
  386. return this;
  387. }
  388. var listeners = this._events[evt];
  389. if (listeners.fn) {
  390. if (
  391. listeners.fn === fn &&
  392. (!once || listeners.once) &&
  393. (!context || listeners.context === context)
  394. ) {
  395. clearEvent(this, evt);
  396. }
  397. } else {
  398. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  399. if (
  400. listeners[i].fn !== fn ||
  401. (once && !listeners[i].once) ||
  402. (context && listeners[i].context !== context)
  403. ) {
  404. events.push(listeners[i]);
  405. }
  406. }
  407. //
  408. // Reset the array, or remove it completely if we have no more listeners.
  409. //
  410. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  411. else clearEvent(this, evt);
  412. }
  413. return this;
  414. };
  415. /**
  416. * Remove all listeners, or those of the specified event.
  417. *
  418. * @param {(String|Symbol)} [event] The event name.
  419. * @returns {EventEmitter} `this`.
  420. * @public
  421. */
  422. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  423. var evt;
  424. if (event) {
  425. evt = prefix ? prefix + event : event;
  426. if (this._events[evt]) clearEvent(this, evt);
  427. } else {
  428. this._events = new Events();
  429. this._eventsCount = 0;
  430. }
  431. return this;
  432. };
  433. //
  434. // Alias methods names because people roll like that.
  435. //
  436. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  437. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  438. //
  439. // Expose the prefix.
  440. //
  441. EventEmitter.prefixed = prefix;
  442. //
  443. // Allow `EventEmitter` to be imported as module namespace.
  444. //
  445. EventEmitter.EventEmitter = EventEmitter;
  446. //
  447. // Expose the module.
  448. //
  449. {
  450. module.exports = EventEmitter;
  451. }
  452. } (eventemitter3));
  453. return eventemitter3.exports;
  454. }
  455. var eventemitter3Exports = requireEventemitter3();
  456. var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventemitter3Exports);
  457. var urlToolkit = {exports: {}};
  458. var hasRequiredUrlToolkit;
  459. function requireUrlToolkit () {
  460. if (hasRequiredUrlToolkit) return urlToolkit.exports;
  461. hasRequiredUrlToolkit = 1;
  462. (function (module, exports) {
  463. // see https://tools.ietf.org/html/rfc1808
  464. (function (root) {
  465. var URL_REGEX =
  466. /^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/;
  467. var FIRST_SEGMENT_REGEX = /^(?=([^\/?#]*))\1([^]*)$/;
  468. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  469. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  470. var URLToolkit = {
  471. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  472. // E.g
  473. // With opts.alwaysNormalize = false (default, spec compliant)
  474. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  475. // With opts.alwaysNormalize = true (not spec compliant)
  476. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  477. buildAbsoluteURL: function (baseURL, relativeURL, opts) {
  478. opts = opts || {};
  479. // remove any remaining space and CRLF
  480. baseURL = baseURL.trim();
  481. relativeURL = relativeURL.trim();
  482. if (!relativeURL) {
  483. // 2a) If the embedded URL is entirely empty, it inherits the
  484. // entire base URL (i.e., is set equal to the base URL)
  485. // and we are done.
  486. if (!opts.alwaysNormalize) {
  487. return baseURL;
  488. }
  489. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  490. if (!basePartsForNormalise) {
  491. throw new Error('Error trying to parse base URL.');
  492. }
  493. basePartsForNormalise.path = URLToolkit.normalizePath(
  494. basePartsForNormalise.path
  495. );
  496. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  497. }
  498. var relativeParts = URLToolkit.parseURL(relativeURL);
  499. if (!relativeParts) {
  500. throw new Error('Error trying to parse relative URL.');
  501. }
  502. if (relativeParts.scheme) {
  503. // 2b) If the embedded URL starts with a scheme name, it is
  504. // interpreted as an absolute URL and we are done.
  505. if (!opts.alwaysNormalize) {
  506. return relativeURL;
  507. }
  508. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  509. return URLToolkit.buildURLFromParts(relativeParts);
  510. }
  511. var baseParts = URLToolkit.parseURL(baseURL);
  512. if (!baseParts) {
  513. throw new Error('Error trying to parse base URL.');
  514. }
  515. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  516. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  517. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  518. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  519. baseParts.netLoc = pathParts[1];
  520. baseParts.path = pathParts[2];
  521. }
  522. if (baseParts.netLoc && !baseParts.path) {
  523. baseParts.path = '/';
  524. }
  525. var builtParts = {
  526. // 2c) Otherwise, the embedded URL inherits the scheme of
  527. // the base URL.
  528. scheme: baseParts.scheme,
  529. netLoc: relativeParts.netLoc,
  530. path: null,
  531. params: relativeParts.params,
  532. query: relativeParts.query,
  533. fragment: relativeParts.fragment,
  534. };
  535. if (!relativeParts.netLoc) {
  536. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  537. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  538. // (if any) of the base URL.
  539. builtParts.netLoc = baseParts.netLoc;
  540. // 4) If the embedded URL path is preceded by a slash "/", the
  541. // path is not relative and we skip to Step 7.
  542. if (relativeParts.path[0] !== '/') {
  543. if (!relativeParts.path) {
  544. // 5) If the embedded URL path is empty (and not preceded by a
  545. // slash), then the embedded URL inherits the base URL path
  546. builtParts.path = baseParts.path;
  547. // 5a) if the embedded URL's <params> is non-empty, we skip to
  548. // step 7; otherwise, it inherits the <params> of the base
  549. // URL (if any) and
  550. if (!relativeParts.params) {
  551. builtParts.params = baseParts.params;
  552. // 5b) if the embedded URL's <query> is non-empty, we skip to
  553. // step 7; otherwise, it inherits the <query> of the base
  554. // URL (if any) and we skip to step 7.
  555. if (!relativeParts.query) {
  556. builtParts.query = baseParts.query;
  557. }
  558. }
  559. } else {
  560. // 6) The last segment of the base URL's path (anything
  561. // following the rightmost slash "/", or the entire path if no
  562. // slash is present) is removed and the embedded URL's path is
  563. // appended in its place.
  564. var baseURLPath = baseParts.path;
  565. var newPath =
  566. baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
  567. relativeParts.path;
  568. builtParts.path = URLToolkit.normalizePath(newPath);
  569. }
  570. }
  571. }
  572. if (builtParts.path === null) {
  573. builtParts.path = opts.alwaysNormalize
  574. ? URLToolkit.normalizePath(relativeParts.path)
  575. : relativeParts.path;
  576. }
  577. return URLToolkit.buildURLFromParts(builtParts);
  578. },
  579. parseURL: function (url) {
  580. var parts = URL_REGEX.exec(url);
  581. if (!parts) {
  582. return null;
  583. }
  584. return {
  585. scheme: parts[1] || '',
  586. netLoc: parts[2] || '',
  587. path: parts[3] || '',
  588. params: parts[4] || '',
  589. query: parts[5] || '',
  590. fragment: parts[6] || '',
  591. };
  592. },
  593. normalizePath: function (path) {
  594. // The following operations are
  595. // then applied, in order, to the new path:
  596. // 6a) All occurrences of "./", where "." is a complete path
  597. // segment, are removed.
  598. // 6b) If the path ends with "." as a complete path segment,
  599. // that "." is removed.
  600. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  601. // 6c) All occurrences of "<segment>/../", where <segment> is a
  602. // complete path segment not equal to "..", are removed.
  603. // Removal of these path segments is performed iteratively,
  604. // removing the leftmost matching pattern on each iteration,
  605. // until no matching pattern remains.
  606. // 6d) If the path ends with "<segment>/..", where <segment> is a
  607. // complete path segment not equal to "..", that
  608. // "<segment>/.." is removed.
  609. while (
  610. path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
  611. ) {}
  612. return path.split('').reverse().join('');
  613. },
  614. buildURLFromParts: function (parts) {
  615. return (
  616. parts.scheme +
  617. parts.netLoc +
  618. parts.path +
  619. parts.params +
  620. parts.query +
  621. parts.fragment
  622. );
  623. },
  624. };
  625. module.exports = URLToolkit;
  626. })();
  627. } (urlToolkit));
  628. return urlToolkit.exports;
  629. }
  630. var urlToolkitExports = requireUrlToolkit();
  631. // https://caniuse.com/mdn-javascript_builtins_number_isfinite
  632. var isFiniteNumber = Number.isFinite || function (value) {
  633. return typeof value === 'number' && isFinite(value);
  634. };
  635. // https://caniuse.com/mdn-javascript_builtins_number_issafeinteger
  636. var isSafeInteger = Number.isSafeInteger || function (value) {
  637. return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;
  638. };
  639. var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  640. var ErrorTypes = /*#__PURE__*/function (ErrorTypes) {
  641. // Identifier for a network error (loading error / timeout ...)
  642. ErrorTypes["NETWORK_ERROR"] = "networkError";
  643. // Identifier for a media Error (video/parsing/mediasource error)
  644. ErrorTypes["MEDIA_ERROR"] = "mediaError";
  645. // EME (encrypted media extensions) errors
  646. ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
  647. // Identifier for a mux Error (demuxing/remuxing)
  648. ErrorTypes["MUX_ERROR"] = "muxError";
  649. // Identifier for all other errors
  650. ErrorTypes["OTHER_ERROR"] = "otherError";
  651. return ErrorTypes;
  652. }({});
  653. var ErrorDetails = /*#__PURE__*/function (ErrorDetails) {
  654. ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
  655. ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
  656. ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
  657. ErrorDetails["KEY_SYSTEM_NO_CONFIGURED_LICENSE"] = "keySystemNoConfiguredLicense";
  658. ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
  659. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED"] = "keySystemServerCertificateRequestFailed";
  660. ErrorDetails["KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED"] = "keySystemServerCertificateUpdateFailed";
  661. ErrorDetails["KEY_SYSTEM_SESSION_UPDATE_FAILED"] = "keySystemSessionUpdateFailed";
  662. ErrorDetails["KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED"] = "keySystemStatusOutputRestricted";
  663. ErrorDetails["KEY_SYSTEM_STATUS_INTERNAL_ERROR"] = "keySystemStatusInternalError";
  664. ErrorDetails["KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR"] = "keySystemDestroyMediaKeysError";
  665. ErrorDetails["KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR"] = "keySystemDestroyCloseSessionError";
  666. ErrorDetails["KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR"] = "keySystemDestroyRemoveSessionError";
  667. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  668. ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
  669. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  670. ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
  671. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  672. ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
  673. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  674. ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
  675. // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: "no fragments found in level", level: index of the bad level }
  676. ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
  677. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  678. ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
  679. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  680. ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
  681. // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }
  682. ErrorDetails["LEVEL_PARSING_ERROR"] = "levelParsingError";
  683. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  684. ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
  685. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  686. ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
  687. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  688. ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
  689. // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  690. ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
  691. // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  692. ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
  693. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  694. ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
  695. // Identifier for fragment load timeout error - data: { frag : fragment object}
  696. ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
  697. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  698. ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
  699. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  700. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  701. ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
  702. // Identifier for a fragment or part load skipped because of a GAP tag or attribute
  703. ErrorDetails["FRAG_GAP"] = "fragGap";
  704. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  705. ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
  706. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  707. ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
  708. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  709. ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
  710. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }
  711. ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
  712. // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }
  713. ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
  714. // Identifier for a buffer append error - data: append error description
  715. ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
  716. // Identifier for a buffer appending error event - data: appending error description
  717. ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
  718. // Identifier for a buffer stalled error event
  719. ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
  720. // Identifier for a buffer full event
  721. ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
  722. // Identifier for a buffer seek over hole event
  723. ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
  724. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  725. ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
  726. // Identifier for a Interstitial Asset List load error - data: { url: faulty URL, response: { code: error code, text: error text } }
  727. ErrorDetails["ASSET_LIST_LOAD_ERROR"] = "assetListLoadError";
  728. // Identifier for a Interstitial Asset List load timeout - data: { url: faulty URL, response: { code: error code, text: error text } }
  729. ErrorDetails["ASSET_LIST_LOAD_TIMEOUT"] = "assetListLoadTimeout";
  730. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  731. ErrorDetails["ASSET_LIST_PARSING_ERROR"] = "assetListParsingError";
  732. // Identifier for a Interstitial Asset List parsing error - data: { url : faulty URL, reason : error reason, response : { code: error code, text: error text }}
  733. ErrorDetails["INTERSTITIAL_ASSET_ITEM_ERROR"] = "interstitialAssetItemError";
  734. // Identifier for an internal exception happening inside hls.js while handling an event
  735. ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
  736. // Identifier for an internal call to abort a loader
  737. ErrorDetails["INTERNAL_ABORTED"] = "aborted";
  738. // Triggered when attachMedia fails
  739. ErrorDetails["ATTACH_MEDIA_ERROR"] = "attachMediaError";
  740. // Uncategorized error
  741. ErrorDetails["UNKNOWN"] = "unknown";
  742. return ErrorDetails;
  743. }({});
  744. var Events = /*#__PURE__*/function (Events) {
  745. // Fired before MediaSource is attaching to media element
  746. Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
  747. // Fired when MediaSource has been successfully attached to media element
  748. Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
  749. // Fired before detaching MediaSource from media element
  750. Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
  751. // Fired when MediaSource has been detached from media element
  752. Events["MEDIA_DETACHED"] = "hlsMediaDetached";
  753. // Fired when HTMLMediaElement dispatches "ended" event, or stalls at end of VOD program
  754. Events["MEDIA_ENDED"] = "hlsMediaEnded";
  755. // Fired after playback stall is resolved with playing, seeked, or ended event following BUFFER_STALLED_ERROR
  756. Events["STALL_RESOLVED"] = "hlsStallResolved";
  757. // Fired when the buffer is going to be reset
  758. Events["BUFFER_RESET"] = "hlsBufferReset";
  759. // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  760. Events["BUFFER_CODECS"] = "hlsBufferCodecs";
  761. // fired when sourcebuffers have been created - data: { tracks : tracks }
  762. Events["BUFFER_CREATED"] = "hlsBufferCreated";
  763. // fired when we append a segment to the buffer - data: { segment: segment object }
  764. Events["BUFFER_APPENDING"] = "hlsBufferAppending";
  765. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  766. Events["BUFFER_APPENDED"] = "hlsBufferAppended";
  767. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  768. Events["BUFFER_EOS"] = "hlsBufferEos";
  769. // fired when all buffers are full to the end of the program, after calling MediaSource.endOfStream() (unless restricted)
  770. Events["BUFFERED_TO_END"] = "hlsBufferedToEnd";
  771. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  772. Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
  773. // fired when the media buffer has been flushed - data: { }
  774. Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
  775. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  776. Events["MANIFEST_LOADING"] = "hlsManifestLoading";
  777. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }
  778. Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
  779. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  780. Events["MANIFEST_PARSED"] = "hlsManifestParsed";
  781. // fired when a level switch is requested - data: { level : id of new level }
  782. Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
  783. // fired when a level switch is effective - data: { level : id of new level }
  784. Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
  785. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  786. Events["LEVEL_LOADING"] = "hlsLevelLoading";
  787. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }
  788. Events["LEVEL_LOADED"] = "hlsLevelLoaded";
  789. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  790. Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
  791. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  792. Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
  793. // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
  794. Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
  795. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  796. Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
  797. // fired when an audio track switching is requested - data: { id : audio track id }
  798. Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
  799. // fired when an audio track switch actually occurs - data: { id : audio track id }
  800. Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
  801. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  802. Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
  803. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }
  804. Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
  805. // fired when an audio tracks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  806. Events["AUDIO_TRACK_UPDATED"] = "hlsAudioTrackUpdated";
  807. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  808. Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
  809. // fired to notify that subtitle tracks were cleared as a result of stopping the media
  810. Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
  811. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  812. Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
  813. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  814. Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
  815. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }
  816. Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
  817. // fired when a subtitle racks's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, id : track id }
  818. Events["SUBTITLE_TRACK_UPDATED"] = "hlsSubtitleTrackUpdated";
  819. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  820. Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
  821. // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
  822. Events["CUES_PARSED"] = "hlsCuesParsed";
  823. // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
  824. Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
  825. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }
  826. Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
  827. // fired when a fragment loading starts - data: { frag : fragment object }
  828. Events["FRAG_LOADING"] = "hlsFragLoading";
  829. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  830. // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',
  831. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  832. Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
  833. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }
  834. Events["FRAG_LOADED"] = "hlsFragLoaded";
  835. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  836. Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
  837. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  838. Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
  839. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  840. Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
  841. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  842. Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
  843. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  844. // FRAG_PARSING_DATA = 'hlsFragParsingData',
  845. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  846. Events["FRAG_PARSED"] = "hlsFragParsed";
  847. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }
  848. Events["FRAG_BUFFERED"] = "hlsFragBuffered";
  849. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  850. Events["FRAG_CHANGED"] = "hlsFragChanged";
  851. // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }
  852. Events["FPS_DROP"] = "hlsFpsDrop";
  853. // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }
  854. Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
  855. // triggered when maxAutoLevel changes - data { autoLevelCapping, levels, maxAutoLevel, minAutoLevel, maxHdcpLevel }
  856. Events["MAX_AUTO_LEVEL_UPDATED"] = "hlsMaxAutoLevelUpdated";
  857. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  858. Events["ERROR"] = "hlsError";
  859. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  860. Events["DESTROYING"] = "hlsDestroying";
  861. // fired when a decrypt key loading starts - data: { frag : fragment object }
  862. Events["KEY_LOADING"] = "hlsKeyLoading";
  863. // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }
  864. Events["KEY_LOADED"] = "hlsKeyLoaded";
  865. // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }
  866. Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
  867. // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }
  868. Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
  869. // fired after steering manifest has been loaded - data: { steeringManifest: SteeringManifest object, url: steering manifest URL }
  870. Events["STEERING_MANIFEST_LOADED"] = "hlsSteeringManifestLoaded";
  871. // fired when asset list has begun loading
  872. Events["ASSET_LIST_LOADING"] = "hlsAssetListLoading";
  873. // fired when a valid asset list is loaded
  874. Events["ASSET_LIST_LOADED"] = "hlsAssetListLoaded";
  875. // fired when the list of Interstitial Events and Interstitial Schedule is updated
  876. Events["INTERSTITIALS_UPDATED"] = "hlsInterstitialsUpdated";
  877. // fired when the buffer reaches an Interstitial Schedule boundary (both Primary segments and Interstitial Assets)
  878. Events["INTERSTITIALS_BUFFERED_TO_BOUNDARY"] = "hlsInterstitialsBufferedToBoundary";
  879. // fired when a player instance for an Interstitial Asset has been created
  880. Events["INTERSTITIAL_ASSET_PLAYER_CREATED"] = "hlsInterstitialAssetPlayerCreated";
  881. // Interstitial playback started
  882. Events["INTERSTITIAL_STARTED"] = "hlsInterstitialStarted";
  883. // InterstitialAsset playback started
  884. Events["INTERSTITIAL_ASSET_STARTED"] = "hlsInterstitialAssetStarted";
  885. // InterstitialAsset playback ended
  886. Events["INTERSTITIAL_ASSET_ENDED"] = "hlsInterstitialAssetEnded";
  887. // InterstitialAsset playback errored
  888. Events["INTERSTITIAL_ASSET_ERROR"] = "hlsInterstitialAssetError";
  889. // Interstitial playback ended
  890. Events["INTERSTITIAL_ENDED"] = "hlsInterstitialEnded";
  891. // Interstitial schedule resumed primary playback
  892. Events["INTERSTITIALS_PRIMARY_RESUMED"] = "hlsInterstitialsPrimaryResumed";
  893. // Interstitial players dispatch this event when playout limit is reached
  894. Events["PLAYOUT_LIMIT_REACHED"] = "hlsPlayoutLimitReached";
  895. // Event DateRange cue "enter" event dispatched
  896. Events["EVENT_CUE_ENTER"] = "hlsEventCueEnter";
  897. return Events;
  898. }({});
  899. /**
  900. * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.
  901. */
  902. var PlaylistContextType = {
  903. MANIFEST: "manifest",
  904. LEVEL: "level",
  905. AUDIO_TRACK: "audioTrack",
  906. SUBTITLE_TRACK: "subtitleTrack"
  907. };
  908. var PlaylistLevelType = {
  909. MAIN: "main",
  910. AUDIO: "audio",
  911. SUBTITLE: "subtitle"
  912. };
  913. /*
  914. * compute an Exponential Weighted moving average
  915. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  916. * - heavily inspired from shaka-player
  917. */
  918. var EWMA = /*#__PURE__*/function () {
  919. // About half of the estimated value will be from the last |halfLife| samples by weight.
  920. function EWMA(halfLife, estimate, weight) {
  921. if (estimate === void 0) {
  922. estimate = 0;
  923. }
  924. if (weight === void 0) {
  925. weight = 0;
  926. }
  927. this.halfLife = void 0;
  928. this.alpha_ = void 0;
  929. this.estimate_ = void 0;
  930. this.totalWeight_ = void 0;
  931. this.halfLife = halfLife;
  932. // Larger values of alpha expire historical data more slowly.
  933. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  934. this.estimate_ = estimate;
  935. this.totalWeight_ = weight;
  936. }
  937. var _proto = EWMA.prototype;
  938. _proto.sample = function sample(weight, value) {
  939. var adjAlpha = Math.pow(this.alpha_, weight);
  940. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  941. this.totalWeight_ += weight;
  942. };
  943. _proto.getTotalWeight = function getTotalWeight() {
  944. return this.totalWeight_;
  945. };
  946. _proto.getEstimate = function getEstimate() {
  947. if (this.alpha_) {
  948. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  949. if (zeroFactor) {
  950. return this.estimate_ / zeroFactor;
  951. }
  952. }
  953. return this.estimate_;
  954. };
  955. return EWMA;
  956. }();
  957. var EwmaBandWidthEstimator = /*#__PURE__*/function () {
  958. function EwmaBandWidthEstimator(slow, fast, defaultEstimate, defaultTTFB) {
  959. if (defaultTTFB === void 0) {
  960. defaultTTFB = 100;
  961. }
  962. this.defaultEstimate_ = void 0;
  963. this.minWeight_ = void 0;
  964. this.minDelayMs_ = void 0;
  965. this.slow_ = void 0;
  966. this.fast_ = void 0;
  967. this.defaultTTFB_ = void 0;
  968. this.ttfb_ = void 0;
  969. this.defaultEstimate_ = defaultEstimate;
  970. this.minWeight_ = 0.001;
  971. this.minDelayMs_ = 50;
  972. this.slow_ = new EWMA(slow);
  973. this.fast_ = new EWMA(fast);
  974. this.defaultTTFB_ = defaultTTFB;
  975. this.ttfb_ = new EWMA(slow);
  976. }
  977. var _proto = EwmaBandWidthEstimator.prototype;
  978. _proto.update = function update(slow, fast) {
  979. var slow_ = this.slow_,
  980. fast_ = this.fast_,
  981. ttfb_ = this.ttfb_;
  982. if (slow_.halfLife !== slow) {
  983. this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());
  984. }
  985. if (fast_.halfLife !== fast) {
  986. this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());
  987. }
  988. if (ttfb_.halfLife !== slow) {
  989. this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());
  990. }
  991. };
  992. _proto.sample = function sample(durationMs, numBytes) {
  993. durationMs = Math.max(durationMs, this.minDelayMs_);
  994. var numBits = 8 * numBytes;
  995. // weight is duration in seconds
  996. var durationS = durationMs / 1000;
  997. // value is bandwidth in bits/s
  998. var bandwidthInBps = numBits / durationS;
  999. this.fast_.sample(durationS, bandwidthInBps);
  1000. this.slow_.sample(durationS, bandwidthInBps);
  1001. };
  1002. _proto.sampleTTFB = function sampleTTFB(ttfb) {
  1003. // weight is frequency curve applied to TTFB in seconds
  1004. // (longer times have less weight with expected input under 1 second)
  1005. var seconds = ttfb / 1000;
  1006. var weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);
  1007. this.ttfb_.sample(weight, Math.max(ttfb, 5));
  1008. };
  1009. _proto.canEstimate = function canEstimate() {
  1010. return this.fast_.getTotalWeight() >= this.minWeight_;
  1011. };
  1012. _proto.getEstimate = function getEstimate() {
  1013. if (this.canEstimate()) {
  1014. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  1015. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  1016. // Take the minimum of these two estimates. This should have the effect of
  1017. // adapting down quickly, but up more slowly.
  1018. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  1019. } else {
  1020. return this.defaultEstimate_;
  1021. }
  1022. };
  1023. _proto.getEstimateTTFB = function getEstimateTTFB() {
  1024. if (this.ttfb_.getTotalWeight() >= this.minWeight_) {
  1025. return this.ttfb_.getEstimate();
  1026. } else {
  1027. return this.defaultTTFB_;
  1028. }
  1029. };
  1030. _proto.destroy = function destroy() {};
  1031. return _createClass(EwmaBandWidthEstimator, [{
  1032. key: "defaultEstimate",
  1033. get: function get() {
  1034. return this.defaultEstimate_;
  1035. }
  1036. }]);
  1037. }();
  1038. var Logger = function Logger(label, logger) {
  1039. this.trace = void 0;
  1040. this.debug = void 0;
  1041. this.log = void 0;
  1042. this.warn = void 0;
  1043. this.info = void 0;
  1044. this.error = void 0;
  1045. var lb = "[" + label + "]:";
  1046. this.trace = noop;
  1047. this.debug = logger.debug.bind(null, lb);
  1048. this.log = logger.log.bind(null, lb);
  1049. this.warn = logger.warn.bind(null, lb);
  1050. this.info = logger.info.bind(null, lb);
  1051. this.error = logger.error.bind(null, lb);
  1052. };
  1053. var noop = function noop() {};
  1054. var fakeLogger = {
  1055. trace: noop,
  1056. debug: noop,
  1057. log: noop,
  1058. warn: noop,
  1059. info: noop,
  1060. error: noop
  1061. };
  1062. function createLogger() {
  1063. return _extends({}, fakeLogger);
  1064. }
  1065. // let lastCallTime;
  1066. // function formatMsgWithTimeInfo(type, msg) {
  1067. // const now = Date.now();
  1068. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  1069. // lastCallTime = now;
  1070. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  1071. // return msg;
  1072. // }
  1073. function consolePrintFn(type, id) {
  1074. var func = self.console[type];
  1075. return func ? func.bind(self.console, (id ? '[' + id + '] ' : '') + "[" + type + "] >") : noop;
  1076. }
  1077. function getLoggerFn(key, debugConfig, id) {
  1078. return debugConfig[key] ? debugConfig[key].bind(debugConfig) : consolePrintFn(key, id);
  1079. }
  1080. var exportedLogger = createLogger();
  1081. function enableLogs(debugConfig, context, id) {
  1082. // check that console is available
  1083. var newLogger = createLogger();
  1084. if (typeof console === 'object' && debugConfig === true || typeof debugConfig === 'object') {
  1085. var keys = [
  1086. // Remove out from list here to hard-disable a log-level
  1087. // 'trace',
  1088. 'debug', 'log', 'info', 'warn', 'error'];
  1089. keys.forEach(function (key) {
  1090. newLogger[key] = getLoggerFn(key, debugConfig, id);
  1091. });
  1092. // Some browsers don't allow to use bind on console object anyway
  1093. // fallback to default if needed
  1094. try {
  1095. newLogger.log("Debug logs enabled for \"" + context + "\" in hls.js version " + "1.6.7");
  1096. } catch (e) {
  1097. /* log fn threw an exception. All logger methods are no-ops. */
  1098. return createLogger();
  1099. }
  1100. // global exported logger uses the same functions as new logger without `id`
  1101. keys.forEach(function (key) {
  1102. exportedLogger[key] = getLoggerFn(key, debugConfig);
  1103. });
  1104. } else {
  1105. // Reset global exported logger
  1106. _extends(exportedLogger, newLogger);
  1107. }
  1108. return newLogger;
  1109. }
  1110. var logger = exportedLogger;
  1111. function getMediaSource(preferManagedMediaSource) {
  1112. if (preferManagedMediaSource === void 0) {
  1113. preferManagedMediaSource = true;
  1114. }
  1115. if (typeof self === 'undefined') return undefined;
  1116. var mms = (preferManagedMediaSource || !self.MediaSource) && self.ManagedMediaSource;
  1117. return mms || self.MediaSource || self.WebKitMediaSource;
  1118. }
  1119. function isManagedMediaSource(source) {
  1120. return typeof self !== 'undefined' && source === self.ManagedMediaSource;
  1121. }
  1122. function isCompatibleTrackChange(currentTracks, requiredTracks) {
  1123. var trackNames = Object.keys(currentTracks);
  1124. var requiredTrackNames = Object.keys(requiredTracks);
  1125. var trackCount = trackNames.length;
  1126. var requiredTrackCount = requiredTrackNames.length;
  1127. return !trackCount || !requiredTrackCount || trackCount === requiredTrackCount && !trackNames.some(function (name) {
  1128. return requiredTrackNames.indexOf(name) === -1;
  1129. });
  1130. }
  1131. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  1132. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  1133. /* utf.js - UTF-8 <=> UTF-16 convertion
  1134. *
  1135. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  1136. * Version: 1.0
  1137. * LastModified: Dec 25 1999
  1138. * This library is free. You can redistribute it and/or modify it.
  1139. */
  1140. /**
  1141. * Converts a UTF-8 array to a string.
  1142. *
  1143. * @param array - The UTF-8 array to convert
  1144. *
  1145. * @returns The string
  1146. *
  1147. * @group Utils
  1148. *
  1149. * @beta
  1150. */
  1151. function utf8ArrayToStr(array, exitOnNull) {
  1152. if (exitOnNull === void 0) {
  1153. exitOnNull = false;
  1154. }
  1155. if (typeof TextDecoder !== 'undefined') {
  1156. var decoder = new TextDecoder('utf-8');
  1157. var decoded = decoder.decode(array);
  1158. if (exitOnNull) {
  1159. // grab up to the first null
  1160. var idx = decoded.indexOf('\0');
  1161. return idx !== -1 ? decoded.substring(0, idx) : decoded;
  1162. }
  1163. // remove any null characters
  1164. return decoded.replace(/\0/g, '');
  1165. }
  1166. var len = array.length;
  1167. var c;
  1168. var char2;
  1169. var char3;
  1170. var out = '';
  1171. var i = 0;
  1172. while (i < len) {
  1173. c = array[i++];
  1174. if (c === 0x00 && exitOnNull) {
  1175. return out;
  1176. } else if (c === 0x00 || c === 0x03) {
  1177. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  1178. continue;
  1179. }
  1180. switch (c >> 4) {
  1181. case 0:
  1182. case 1:
  1183. case 2:
  1184. case 3:
  1185. case 4:
  1186. case 5:
  1187. case 6:
  1188. case 7:
  1189. // 0xxxxxxx
  1190. out += String.fromCharCode(c);
  1191. break;
  1192. case 12:
  1193. case 13:
  1194. // 110x xxxx 10xx xxxx
  1195. char2 = array[i++];
  1196. out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
  1197. break;
  1198. case 14:
  1199. // 1110 xxxx 10xx xxxx 10xx xxxx
  1200. char2 = array[i++];
  1201. char3 = array[i++];
  1202. out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
  1203. break;
  1204. }
  1205. }
  1206. return out;
  1207. }
  1208. /**
  1209. * hex dump helper class
  1210. */
  1211. var Hex = {
  1212. hexDump: function hexDump(array) {
  1213. var str = '';
  1214. for (var i = 0; i < array.length; i++) {
  1215. var h = array[i].toString(16);
  1216. if (h.length < 2) {
  1217. h = '0' + h;
  1218. }
  1219. str += h;
  1220. }
  1221. return str;
  1222. }
  1223. };
  1224. function hexToArrayBuffer(str) {
  1225. return Uint8Array.from(str.replace(/^0x/, '').replace(/([\da-fA-F]{2}) ?/g, '0x$1 ').replace(/ +$/, '').split(' ')).buffer;
  1226. }
  1227. var LoadStats = function LoadStats() {
  1228. this.aborted = false;
  1229. this.loaded = 0;
  1230. this.retry = 0;
  1231. this.total = 0;
  1232. this.chunkCount = 0;
  1233. this.bwEstimate = 0;
  1234. this.loading = {
  1235. start: 0,
  1236. first: 0,
  1237. end: 0
  1238. };
  1239. this.parsing = {
  1240. start: 0,
  1241. end: 0
  1242. };
  1243. this.buffering = {
  1244. start: 0,
  1245. first: 0,
  1246. end: 0
  1247. };
  1248. };
  1249. var ElementaryStreamTypes = {
  1250. AUDIO: "audio",
  1251. VIDEO: "video",
  1252. AUDIOVIDEO: "audiovideo"
  1253. };
  1254. var BaseSegment = /*#__PURE__*/function () {
  1255. function BaseSegment(base) {
  1256. this._byteRange = null;
  1257. this._url = null;
  1258. this._stats = null;
  1259. this._streams = null;
  1260. // baseurl is the URL to the playlist
  1261. this.base = void 0;
  1262. // relurl is the portion of the URL that comes from inside the playlist.
  1263. this.relurl = void 0;
  1264. if (typeof base === 'string') {
  1265. base = {
  1266. url: base
  1267. };
  1268. }
  1269. this.base = base;
  1270. makeEnumerable(this, 'stats');
  1271. }
  1272. // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
  1273. var _proto = BaseSegment.prototype;
  1274. _proto.setByteRange = function setByteRange(value, previous) {
  1275. var params = value.split('@', 2);
  1276. var start;
  1277. if (params.length === 1) {
  1278. start = (previous == null ? void 0 : previous.byteRangeEndOffset) || 0;
  1279. } else {
  1280. start = parseInt(params[1]);
  1281. }
  1282. this._byteRange = [start, parseInt(params[0]) + start];
  1283. };
  1284. _proto.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
  1285. var elementaryStreams = this.elementaryStreams;
  1286. elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
  1287. elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
  1288. elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
  1289. };
  1290. return _createClass(BaseSegment, [{
  1291. key: "baseurl",
  1292. get: function get() {
  1293. return this.base.url;
  1294. }
  1295. }, {
  1296. key: "byteRange",
  1297. get: function get() {
  1298. if (this._byteRange === null) {
  1299. return [];
  1300. }
  1301. return this._byteRange;
  1302. }
  1303. }, {
  1304. key: "byteRangeStartOffset",
  1305. get: function get() {
  1306. return this.byteRange[0];
  1307. }
  1308. }, {
  1309. key: "byteRangeEndOffset",
  1310. get: function get() {
  1311. return this.byteRange[1];
  1312. }
  1313. }, {
  1314. key: "elementaryStreams",
  1315. get: function get() {
  1316. if (this._streams === null) {
  1317. var _this$_streams;
  1318. this._streams = (_this$_streams = {}, _this$_streams[ElementaryStreamTypes.AUDIO] = null, _this$_streams[ElementaryStreamTypes.VIDEO] = null, _this$_streams[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$_streams);
  1319. }
  1320. return this._streams;
  1321. },
  1322. set: function set(value) {
  1323. this._streams = value;
  1324. }
  1325. }, {
  1326. key: "hasStats",
  1327. get: function get() {
  1328. return this._stats !== null;
  1329. }
  1330. }, {
  1331. key: "hasStreams",
  1332. get: function get() {
  1333. return this._streams !== null;
  1334. }
  1335. }, {
  1336. key: "stats",
  1337. get: function get() {
  1338. if (this._stats === null) {
  1339. this._stats = new LoadStats();
  1340. }
  1341. return this._stats;
  1342. },
  1343. set: function set(value) {
  1344. this._stats = value;
  1345. }
  1346. }, {
  1347. key: "url",
  1348. get: function get() {
  1349. if (!this._url && this.baseurl && this.relurl) {
  1350. this._url = urlToolkitExports.buildAbsoluteURL(this.baseurl, this.relurl, {
  1351. alwaysNormalize: true
  1352. });
  1353. }
  1354. return this._url || '';
  1355. },
  1356. set: function set(value) {
  1357. this._url = value;
  1358. }
  1359. }]);
  1360. }();
  1361. function isMediaFragment(frag) {
  1362. return frag.sn !== 'initSegment';
  1363. }
  1364. /**
  1365. * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.
  1366. */
  1367. var Fragment = /*#__PURE__*/function (_BaseSegment2) {
  1368. function Fragment(type, base) {
  1369. var _this;
  1370. _this = _BaseSegment2.call(this, base) || this;
  1371. _this._decryptdata = null;
  1372. _this._programDateTime = null;
  1373. _this._ref = null;
  1374. // Approximate bit rate of the fragment expressed in bits per second (bps) as indicated by the last EXT-X-BITRATE (kbps) tag
  1375. _this._bitrate = void 0;
  1376. _this.rawProgramDateTime = null;
  1377. _this.tagList = [];
  1378. // EXTINF has to be present for a m3u8 to be considered valid
  1379. _this.duration = 0;
  1380. // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
  1381. _this.sn = 0;
  1382. // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption
  1383. // core difference from the private field _decryptdata is the lack of the initialized IV
  1384. // _decryptdata will set the IV for this segment based on the segment number in the fragment
  1385. _this.levelkeys = void 0;
  1386. // A string representing the fragment type
  1387. _this.type = void 0;
  1388. // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
  1389. _this.loader = null;
  1390. // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading
  1391. _this.keyLoader = null;
  1392. // The level/track index to which the fragment belongs
  1393. _this.level = -1;
  1394. // The continuity counter of the fragment
  1395. _this.cc = 0;
  1396. // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  1397. _this.startPTS = void 0;
  1398. // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
  1399. _this.endPTS = void 0;
  1400. // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  1401. _this.startDTS = void 0;
  1402. // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
  1403. _this.endDTS = void 0;
  1404. // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
  1405. _this.start = 0;
  1406. // The offset time (seconds) of the fragment from the start of the Playlist
  1407. _this.playlistOffset = 0;
  1408. // Set by `updateFragPTSDTS` in level-helper
  1409. _this.deltaPTS = void 0;
  1410. // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  1411. _this.maxStartPTS = void 0;
  1412. // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
  1413. _this.minEndPTS = void 0;
  1414. // Init Segment bytes (unset for media segments)
  1415. _this.data = void 0;
  1416. // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
  1417. _this.bitrateTest = false;
  1418. // #EXTINF segment title
  1419. _this.title = null;
  1420. // The Media Initialization Section for this segment
  1421. _this.initSegment = null;
  1422. // Fragment is the last fragment in the media playlist
  1423. _this.endList = void 0;
  1424. // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded
  1425. _this.gap = void 0;
  1426. // Deprecated
  1427. _this.urlId = 0;
  1428. _this.type = type;
  1429. return _this;
  1430. }
  1431. _inheritsLoose(Fragment, _BaseSegment2);
  1432. var _proto2 = Fragment.prototype;
  1433. _proto2.addStart = function addStart(value) {
  1434. this.setStart(this.start + value);
  1435. };
  1436. _proto2.setStart = function setStart(value) {
  1437. this.start = value;
  1438. if (this._ref) {
  1439. this._ref.start = value;
  1440. }
  1441. };
  1442. _proto2.setDuration = function setDuration(value) {
  1443. this.duration = value;
  1444. if (this._ref) {
  1445. this._ref.duration = value;
  1446. }
  1447. };
  1448. _proto2.setKeyFormat = function setKeyFormat(keyFormat) {
  1449. if (this.levelkeys) {
  1450. var key = this.levelkeys[keyFormat];
  1451. if (key && !this._decryptdata) {
  1452. this._decryptdata = key.getDecryptData(this.sn);
  1453. }
  1454. }
  1455. };
  1456. _proto2.abortRequests = function abortRequests() {
  1457. var _this$loader, _this$keyLoader;
  1458. (_this$loader = this.loader) == null ? void 0 : _this$loader.abort();
  1459. (_this$keyLoader = this.keyLoader) == null ? void 0 : _this$keyLoader.abort();
  1460. };
  1461. _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
  1462. if (partial === void 0) {
  1463. partial = false;
  1464. }
  1465. var elementaryStreams = this.elementaryStreams;
  1466. var info = elementaryStreams[type];
  1467. if (!info) {
  1468. elementaryStreams[type] = {
  1469. startPTS: startPTS,
  1470. endPTS: endPTS,
  1471. startDTS: startDTS,
  1472. endDTS: endDTS,
  1473. partial: partial
  1474. };
  1475. return;
  1476. }
  1477. info.startPTS = Math.min(info.startPTS, startPTS);
  1478. info.endPTS = Math.max(info.endPTS, endPTS);
  1479. info.startDTS = Math.min(info.startDTS, startDTS);
  1480. info.endDTS = Math.max(info.endDTS, endDTS);
  1481. };
  1482. return _createClass(Fragment, [{
  1483. key: "byteLength",
  1484. get: function get() {
  1485. if (this.hasStats) {
  1486. var total = this.stats.total;
  1487. if (total) {
  1488. return total;
  1489. }
  1490. }
  1491. if (this.byteRange) {
  1492. var start = this.byteRange[0];
  1493. var end = this.byteRange[1];
  1494. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  1495. return end - start;
  1496. }
  1497. }
  1498. return null;
  1499. }
  1500. }, {
  1501. key: "bitrate",
  1502. get: function get() {
  1503. if (this.byteLength) {
  1504. return this.byteLength * 8 / this.duration;
  1505. }
  1506. if (this._bitrate) {
  1507. return this._bitrate;
  1508. }
  1509. return null;
  1510. },
  1511. set: function set(value) {
  1512. this._bitrate = value;
  1513. }
  1514. }, {
  1515. key: "decryptdata",
  1516. get: function get() {
  1517. var levelkeys = this.levelkeys;
  1518. if (!levelkeys && !this._decryptdata) {
  1519. return null;
  1520. }
  1521. if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {
  1522. var key = this.levelkeys.identity;
  1523. if (key) {
  1524. this._decryptdata = key.getDecryptData(this.sn);
  1525. } else {
  1526. var keyFormats = Object.keys(this.levelkeys);
  1527. if (keyFormats.length === 1) {
  1528. return this._decryptdata = this.levelkeys[keyFormats[0]].getDecryptData(this.sn);
  1529. }
  1530. }
  1531. }
  1532. return this._decryptdata;
  1533. }
  1534. }, {
  1535. key: "end",
  1536. get: function get() {
  1537. return this.start + this.duration;
  1538. }
  1539. }, {
  1540. key: "endProgramDateTime",
  1541. get: function get() {
  1542. if (this.programDateTime === null) {
  1543. return null;
  1544. }
  1545. var duration = !isFiniteNumber(this.duration) ? 0 : this.duration;
  1546. return this.programDateTime + duration * 1000;
  1547. }
  1548. }, {
  1549. key: "encrypted",
  1550. get: function get() {
  1551. var _this$_decryptdata;
  1552. // At the m3u8-parser level we need to add support for manifest signalled keyformats
  1553. // when we want the fragment to start reporting that it is encrypted.
  1554. // Currently, keyFormat will only be set for identity keys
  1555. if ((_this$_decryptdata = this._decryptdata) != null && _this$_decryptdata.encrypted) {
  1556. return true;
  1557. } else if (this.levelkeys) {
  1558. var keyFormats = Object.keys(this.levelkeys);
  1559. var len = keyFormats.length;
  1560. if (len > 1 || len === 1 && this.levelkeys[keyFormats[0]].encrypted) {
  1561. return true;
  1562. }
  1563. }
  1564. return false;
  1565. }
  1566. }, {
  1567. key: "programDateTime",
  1568. get: function get() {
  1569. if (this._programDateTime === null && this.rawProgramDateTime) {
  1570. this.programDateTime = Date.parse(this.rawProgramDateTime);
  1571. }
  1572. return this._programDateTime;
  1573. },
  1574. set: function set(value) {
  1575. if (!isFiniteNumber(value)) {
  1576. this._programDateTime = this.rawProgramDateTime = null;
  1577. return;
  1578. }
  1579. this._programDateTime = value;
  1580. }
  1581. }, {
  1582. key: "ref",
  1583. get: function get() {
  1584. if (!isMediaFragment(this)) {
  1585. return null;
  1586. }
  1587. if (!this._ref) {
  1588. this._ref = {
  1589. base: this.base,
  1590. start: this.start,
  1591. duration: this.duration,
  1592. sn: this.sn,
  1593. programDateTime: this.programDateTime
  1594. };
  1595. }
  1596. return this._ref;
  1597. }
  1598. }]);
  1599. }(BaseSegment);
  1600. /**
  1601. * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.
  1602. */
  1603. var Part = /*#__PURE__*/function (_BaseSegment3) {
  1604. function Part(partAttrs, frag, base, index, previous) {
  1605. var _this2;
  1606. _this2 = _BaseSegment3.call(this, base) || this;
  1607. _this2.fragOffset = 0;
  1608. _this2.duration = 0;
  1609. _this2.gap = false;
  1610. _this2.independent = false;
  1611. _this2.relurl = void 0;
  1612. _this2.fragment = void 0;
  1613. _this2.index = void 0;
  1614. _this2.duration = partAttrs.decimalFloatingPoint('DURATION');
  1615. _this2.gap = partAttrs.bool('GAP');
  1616. _this2.independent = partAttrs.bool('INDEPENDENT');
  1617. _this2.relurl = partAttrs.enumeratedString('URI');
  1618. _this2.fragment = frag;
  1619. _this2.index = index;
  1620. var byteRange = partAttrs.enumeratedString('BYTERANGE');
  1621. if (byteRange) {
  1622. _this2.setByteRange(byteRange, previous);
  1623. }
  1624. if (previous) {
  1625. _this2.fragOffset = previous.fragOffset + previous.duration;
  1626. }
  1627. return _this2;
  1628. }
  1629. _inheritsLoose(Part, _BaseSegment3);
  1630. return _createClass(Part, [{
  1631. key: "start",
  1632. get: function get() {
  1633. return this.fragment.start + this.fragOffset;
  1634. }
  1635. }, {
  1636. key: "end",
  1637. get: function get() {
  1638. return this.start + this.duration;
  1639. }
  1640. }, {
  1641. key: "loaded",
  1642. get: function get() {
  1643. var elementaryStreams = this.elementaryStreams;
  1644. return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
  1645. }
  1646. }]);
  1647. }(BaseSegment);
  1648. function getOwnPropertyDescriptorFromPrototypeChain(object, property) {
  1649. var prototype = Object.getPrototypeOf(object);
  1650. if (prototype) {
  1651. var propertyDescriptor = Object.getOwnPropertyDescriptor(prototype, property);
  1652. if (propertyDescriptor) {
  1653. return propertyDescriptor;
  1654. }
  1655. return getOwnPropertyDescriptorFromPrototypeChain(prototype, property);
  1656. }
  1657. }
  1658. function makeEnumerable(object, property) {
  1659. var d = getOwnPropertyDescriptorFromPrototypeChain(object, property);
  1660. if (d) {
  1661. d.enumerable = true;
  1662. Object.defineProperty(object, property, d);
  1663. }
  1664. }
  1665. var UINT32_MAX$1 = Math.pow(2, 32) - 1;
  1666. var push = [].push;
  1667. // We are using fixed track IDs for driving the MP4 remuxer
  1668. // instead of following the TS PIDs.
  1669. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  1670. // may not like if there are TrackID "switches"
  1671. // See https://github.com/video-dev/hls.js/issues/1331
  1672. // Here we are mapping our internal track types to constant MP4 track IDs
  1673. // With MSE currently one can only have one track of each, and we are muxing
  1674. // whatever video/audio rendition in them.
  1675. var RemuxerTrackIdConfig = {
  1676. video: 1,
  1677. audio: 2,
  1678. id3: 3,
  1679. text: 4
  1680. };
  1681. function bin2str(data) {
  1682. return String.fromCharCode.apply(null, data);
  1683. }
  1684. function readUint16(buffer, offset) {
  1685. var val = buffer[offset] << 8 | buffer[offset + 1];
  1686. return val < 0 ? 65536 + val : val;
  1687. }
  1688. function readUint32(buffer, offset) {
  1689. var val = readSint32(buffer, offset);
  1690. return val < 0 ? 4294967296 + val : val;
  1691. }
  1692. function readUint64(buffer, offset) {
  1693. var result = readUint32(buffer, offset);
  1694. result *= Math.pow(2, 32);
  1695. result += readUint32(buffer, offset + 4);
  1696. return result;
  1697. }
  1698. function readSint32(buffer, offset) {
  1699. return buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
  1700. }
  1701. // Find "moof" box
  1702. function hasMoofData(data) {
  1703. var end = data.byteLength;
  1704. for (var i = 0; i < end;) {
  1705. var size = readUint32(data, i);
  1706. if (size > 8 && data[i + 4] === 0x6d && data[i + 5] === 0x6f && data[i + 6] === 0x6f && data[i + 7] === 0x66) {
  1707. return true;
  1708. }
  1709. i = size > 1 ? i + size : end;
  1710. }
  1711. return false;
  1712. }
  1713. // Find the data for a box specified by its path
  1714. function findBox(data, path) {
  1715. var results = [];
  1716. if (!path.length) {
  1717. // short-circuit the search for empty paths
  1718. return results;
  1719. }
  1720. var end = data.byteLength;
  1721. for (var i = 0; i < end;) {
  1722. var size = readUint32(data, i);
  1723. var type = bin2str(data.subarray(i + 4, i + 8));
  1724. var endbox = size > 1 ? i + size : end;
  1725. if (type === path[0]) {
  1726. if (path.length === 1) {
  1727. // this is the end of the path and we've found the box we were
  1728. // looking for
  1729. results.push(data.subarray(i + 8, endbox));
  1730. } else {
  1731. // recursively search for the next box along the path
  1732. var subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));
  1733. if (subresults.length) {
  1734. push.apply(results, subresults);
  1735. }
  1736. }
  1737. }
  1738. i = endbox;
  1739. }
  1740. // we've finished searching all of data
  1741. return results;
  1742. }
  1743. function parseSegmentIndex(sidx) {
  1744. var references = [];
  1745. var version = sidx[0];
  1746. // set initial offset, we skip the reference ID (not needed)
  1747. var index = 8;
  1748. var timescale = readUint32(sidx, index);
  1749. index += 4;
  1750. var earliestPresentationTime = 0;
  1751. var firstOffset = 0;
  1752. if (version === 0) {
  1753. earliestPresentationTime = readUint32(sidx, index);
  1754. firstOffset = readUint32(sidx, index + 4);
  1755. index += 8;
  1756. } else {
  1757. earliestPresentationTime = readUint64(sidx, index);
  1758. firstOffset = readUint64(sidx, index + 8);
  1759. index += 16;
  1760. }
  1761. // skip reserved
  1762. index += 2;
  1763. var startByte = sidx.length + firstOffset;
  1764. var referencesCount = readUint16(sidx, index);
  1765. index += 2;
  1766. for (var i = 0; i < referencesCount; i++) {
  1767. var referenceIndex = index;
  1768. var referenceInfo = readUint32(sidx, referenceIndex);
  1769. referenceIndex += 4;
  1770. var referenceSize = referenceInfo & 0x7fffffff;
  1771. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  1772. if (referenceType === 1) {
  1773. logger.warn('SIDX has hierarchical references (not supported)');
  1774. return null;
  1775. }
  1776. var subsegmentDuration = readUint32(sidx, referenceIndex);
  1777. referenceIndex += 4;
  1778. references.push({
  1779. referenceSize: referenceSize,
  1780. subsegmentDuration: subsegmentDuration,
  1781. // unscaled
  1782. info: {
  1783. duration: subsegmentDuration / timescale,
  1784. start: startByte,
  1785. end: startByte + referenceSize - 1
  1786. }
  1787. });
  1788. startByte += referenceSize;
  1789. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  1790. // for |sapDelta|.
  1791. referenceIndex += 4;
  1792. // skip to next ref
  1793. index = referenceIndex;
  1794. }
  1795. return {
  1796. earliestPresentationTime: earliestPresentationTime,
  1797. timescale: timescale,
  1798. version: version,
  1799. referencesCount: referencesCount,
  1800. references: references
  1801. };
  1802. }
  1803. /**
  1804. * Parses an MP4 initialization segment and extracts stream type and
  1805. * timescale values for any declared tracks. Timescale values indicate the
  1806. * number of clock ticks per second to assume for time-based values
  1807. * elsewhere in the MP4.
  1808. *
  1809. * To determine the start time of an MP4, you need two pieces of
  1810. * information: the timescale unit and the earliest base media decode
  1811. * time. Multiple timescales can be specified within an MP4 but the
  1812. * base media decode time is always expressed in the timescale from
  1813. * the media header box for the track:
  1814. * ```
  1815. * moov > trak > mdia > mdhd.timescale
  1816. * moov > trak > mdia > hdlr
  1817. * ```
  1818. * @param initSegment the bytes of the init segment
  1819. * @returns a hash of track type to timescale values or null if
  1820. * the init segment is malformed.
  1821. */
  1822. function parseInitSegment(initSegment) {
  1823. var result = [];
  1824. var traks = findBox(initSegment, ['moov', 'trak']);
  1825. for (var i = 0; i < traks.length; i++) {
  1826. var trak = traks[i];
  1827. var tkhd = findBox(trak, ['tkhd'])[0];
  1828. if (tkhd) {
  1829. var version = tkhd[0];
  1830. var trackId = readUint32(tkhd, version === 0 ? 12 : 20);
  1831. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  1832. if (mdhd) {
  1833. version = mdhd[0];
  1834. var timescale = readUint32(mdhd, version === 0 ? 12 : 20);
  1835. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  1836. if (hdlr) {
  1837. var hdlrType = bin2str(hdlr.subarray(8, 12));
  1838. var type = {
  1839. soun: ElementaryStreamTypes.AUDIO,
  1840. vide: ElementaryStreamTypes.VIDEO
  1841. }[hdlrType];
  1842. // Parse codec details
  1843. var stsdBox = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1844. var stsd = parseStsd(stsdBox);
  1845. if (type) {
  1846. // Add 'audio', 'video', and 'audiovideo' track records that will map to SourceBuffers
  1847. result[trackId] = {
  1848. timescale: timescale,
  1849. type: type,
  1850. stsd: stsd
  1851. };
  1852. result[type] = _objectSpread2({
  1853. timescale: timescale,
  1854. id: trackId
  1855. }, stsd);
  1856. } else {
  1857. // Add 'meta' and other track records
  1858. result[trackId] = {
  1859. timescale: timescale,
  1860. type: hdlrType,
  1861. stsd: stsd
  1862. };
  1863. }
  1864. }
  1865. }
  1866. }
  1867. }
  1868. var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
  1869. trex.forEach(function (trex) {
  1870. var trackId = readUint32(trex, 4);
  1871. var track = result[trackId];
  1872. if (track) {
  1873. track.default = {
  1874. duration: readUint32(trex, 12),
  1875. flags: readUint32(trex, 20)
  1876. };
  1877. }
  1878. });
  1879. return result;
  1880. }
  1881. function parseStsd(stsd) {
  1882. var sampleEntries = stsd.subarray(8);
  1883. var sampleEntriesEnd = sampleEntries.subarray(8 + 78);
  1884. var fourCC = bin2str(sampleEntries.subarray(4, 8));
  1885. var codec = fourCC;
  1886. var supplemental;
  1887. var encrypted = fourCC === 'enca' || fourCC === 'encv';
  1888. if (encrypted) {
  1889. var encBox = findBox(sampleEntries, [fourCC])[0];
  1890. var encBoxChildren = encBox.subarray(fourCC === 'enca' ? 28 : 78);
  1891. var sinfs = findBox(encBoxChildren, ['sinf']);
  1892. sinfs.forEach(function (sinf) {
  1893. var schm = findBox(sinf, ['schm'])[0];
  1894. if (schm) {
  1895. var scheme = bin2str(schm.subarray(4, 8));
  1896. if (scheme === 'cbcs' || scheme === 'cenc') {
  1897. var frma = findBox(sinf, ['frma'])[0];
  1898. if (frma) {
  1899. // for encrypted content codec fourCC will be in frma
  1900. codec = bin2str(frma);
  1901. }
  1902. }
  1903. }
  1904. });
  1905. }
  1906. var codecFourCC = codec;
  1907. switch (codec) {
  1908. case 'avc1':
  1909. case 'avc2':
  1910. case 'avc3':
  1911. case 'avc4':
  1912. {
  1913. // extract profile + compatibility + level out of avcC box
  1914. var avcCBox = findBox(sampleEntriesEnd, ['avcC'])[0];
  1915. if (avcCBox && avcCBox.length > 3) {
  1916. codec += '.' + toHex(avcCBox[1]) + toHex(avcCBox[2]) + toHex(avcCBox[3]);
  1917. supplemental = parseSupplementalDoViCodec(codecFourCC === 'avc1' ? 'dva1' : 'dvav', sampleEntriesEnd);
  1918. }
  1919. break;
  1920. }
  1921. case 'mp4a':
  1922. {
  1923. var codecBox = findBox(sampleEntries, [fourCC])[0];
  1924. var esdsBox = findBox(codecBox.subarray(28), ['esds'])[0];
  1925. if (esdsBox && esdsBox.length > 7) {
  1926. var i = 4;
  1927. // ES Descriptor tag
  1928. if (esdsBox[i++] !== 0x03) {
  1929. break;
  1930. }
  1931. i = skipBERInteger(esdsBox, i);
  1932. i += 2; // skip es_id;
  1933. var flags = esdsBox[i++];
  1934. if (flags & 0x80) {
  1935. i += 2; // skip dependency es_id
  1936. }
  1937. if (flags & 0x40) {
  1938. i += esdsBox[i++]; // skip URL
  1939. }
  1940. // Decoder config descriptor
  1941. if (esdsBox[i++] !== 0x04) {
  1942. break;
  1943. }
  1944. i = skipBERInteger(esdsBox, i);
  1945. var objectType = esdsBox[i++];
  1946. if (objectType === 0x40) {
  1947. codec += '.' + toHex(objectType);
  1948. } else {
  1949. break;
  1950. }
  1951. i += 12;
  1952. // Decoder specific info
  1953. if (esdsBox[i++] !== 0x05) {
  1954. break;
  1955. }
  1956. i = skipBERInteger(esdsBox, i);
  1957. var firstByte = esdsBox[i++];
  1958. var audioObjectType = (firstByte & 0xf8) >> 3;
  1959. if (audioObjectType === 31) {
  1960. audioObjectType += 1 + ((firstByte & 0x7) << 3) + ((esdsBox[i] & 0xe0) >> 5);
  1961. }
  1962. codec += '.' + audioObjectType;
  1963. }
  1964. break;
  1965. }
  1966. case 'hvc1':
  1967. case 'hev1':
  1968. {
  1969. var hvcCBox = findBox(sampleEntriesEnd, ['hvcC'])[0];
  1970. if (hvcCBox && hvcCBox.length > 12) {
  1971. var profileByte = hvcCBox[1];
  1972. var profileSpace = ['', 'A', 'B', 'C'][profileByte >> 6];
  1973. var generalProfileIdc = profileByte & 0x1f;
  1974. var profileCompat = readUint32(hvcCBox, 2);
  1975. var tierFlag = (profileByte & 0x20) >> 5 ? 'H' : 'L';
  1976. var levelIDC = hvcCBox[12];
  1977. var constraintIndicator = hvcCBox.subarray(6, 12);
  1978. codec += '.' + profileSpace + generalProfileIdc;
  1979. codec += '.' + reverse32BitInt(profileCompat).toString(16).toUpperCase();
  1980. codec += '.' + tierFlag + levelIDC;
  1981. var constraintString = '';
  1982. for (var _i = constraintIndicator.length; _i--;) {
  1983. var _byte = constraintIndicator[_i];
  1984. if (_byte || constraintString) {
  1985. var encodedByte = _byte.toString(16).toUpperCase();
  1986. constraintString = '.' + encodedByte + constraintString;
  1987. }
  1988. }
  1989. codec += constraintString;
  1990. }
  1991. supplemental = parseSupplementalDoViCodec(codecFourCC == 'hev1' ? 'dvhe' : 'dvh1', sampleEntriesEnd);
  1992. break;
  1993. }
  1994. case 'dvh1':
  1995. case 'dvhe':
  1996. case 'dvav':
  1997. case 'dva1':
  1998. case 'dav1':
  1999. {
  2000. codec = parseSupplementalDoViCodec(codec, sampleEntriesEnd) || codec;
  2001. break;
  2002. }
  2003. case 'vp09':
  2004. {
  2005. var vpcCBox = findBox(sampleEntriesEnd, ['vpcC'])[0];
  2006. if (vpcCBox && vpcCBox.length > 6) {
  2007. var profile = vpcCBox[4];
  2008. var level = vpcCBox[5];
  2009. var bitDepth = vpcCBox[6] >> 4 & 0x0f;
  2010. codec += '.' + addLeadingZero(profile) + '.' + addLeadingZero(level) + '.' + addLeadingZero(bitDepth);
  2011. }
  2012. break;
  2013. }
  2014. case 'av01':
  2015. {
  2016. var av1CBox = findBox(sampleEntriesEnd, ['av1C'])[0];
  2017. if (av1CBox && av1CBox.length > 2) {
  2018. var _profile = av1CBox[1] >>> 5;
  2019. var _level = av1CBox[1] & 0x1f;
  2020. var _tierFlag = av1CBox[2] >>> 7 ? 'H' : 'M';
  2021. var highBitDepth = (av1CBox[2] & 0x40) >> 6;
  2022. var twelveBit = (av1CBox[2] & 0x20) >> 5;
  2023. var _bitDepth = _profile === 2 && highBitDepth ? twelveBit ? 12 : 10 : highBitDepth ? 10 : 8;
  2024. var monochrome = (av1CBox[2] & 0x10) >> 4;
  2025. var chromaSubsamplingX = (av1CBox[2] & 0x08) >> 3;
  2026. var chromaSubsamplingY = (av1CBox[2] & 0x04) >> 2;
  2027. var chromaSamplePosition = av1CBox[2] & 0x03;
  2028. // TODO: parse color_description_present_flag
  2029. // default it to BT.709/limited range for now
  2030. // more info https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
  2031. var colorPrimaries = 1;
  2032. var transferCharacteristics = 1;
  2033. var matrixCoefficients = 1;
  2034. var videoFullRangeFlag = 0;
  2035. codec += '.' + _profile + '.' + addLeadingZero(_level) + _tierFlag + '.' + addLeadingZero(_bitDepth) + '.' + monochrome + '.' + chromaSubsamplingX + chromaSubsamplingY + chromaSamplePosition + '.' + addLeadingZero(colorPrimaries) + '.' + addLeadingZero(transferCharacteristics) + '.' + addLeadingZero(matrixCoefficients) + '.' + videoFullRangeFlag;
  2036. supplemental = parseSupplementalDoViCodec('dav1', sampleEntriesEnd);
  2037. }
  2038. break;
  2039. }
  2040. }
  2041. return {
  2042. codec: codec,
  2043. encrypted: encrypted,
  2044. supplemental: supplemental
  2045. };
  2046. }
  2047. function parseSupplementalDoViCodec(fourCC, sampleEntriesEnd) {
  2048. var dvvCResult = findBox(sampleEntriesEnd, ['dvvC']); // used by DoVi Profile 8 to 10
  2049. var dvXCBox = dvvCResult.length ? dvvCResult[0] : findBox(sampleEntriesEnd, ['dvcC'])[0]; // used by DoVi Profiles up to 7 and 20
  2050. if (dvXCBox) {
  2051. var doViProfile = dvXCBox[2] >> 1 & 0x7f;
  2052. var doViLevel = dvXCBox[2] << 5 & 0x20 | dvXCBox[3] >> 3 & 0x1f;
  2053. return fourCC + '.' + addLeadingZero(doViProfile) + '.' + addLeadingZero(doViLevel);
  2054. }
  2055. }
  2056. function reverse32BitInt(val) {
  2057. var result = 0;
  2058. for (var i = 0; i < 32; i++) {
  2059. result |= (val >> i & 1) << 32 - 1 - i;
  2060. }
  2061. return result >>> 0;
  2062. }
  2063. function skipBERInteger(bytes, i) {
  2064. var limit = i + 5;
  2065. while (bytes[i++] & 0x80 && i < limit) {
  2066. /* do nothing */
  2067. }
  2068. return i;
  2069. }
  2070. function toHex(x) {
  2071. return ('0' + x.toString(16).toUpperCase()).slice(-2);
  2072. }
  2073. function addLeadingZero(num) {
  2074. return (num < 10 ? '0' : '') + num;
  2075. }
  2076. function patchEncyptionData(initSegment, decryptdata) {
  2077. if (!initSegment || !decryptdata) {
  2078. return initSegment;
  2079. }
  2080. var keyId = decryptdata.keyId;
  2081. if (keyId && decryptdata.isCommonEncryption) {
  2082. var traks = findBox(initSegment, ['moov', 'trak']);
  2083. traks.forEach(function (trak) {
  2084. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  2085. // skip the sample entry count
  2086. var sampleEntries = stsd.subarray(8);
  2087. var encBoxes = findBox(sampleEntries, ['enca']);
  2088. var isAudio = encBoxes.length > 0;
  2089. if (!isAudio) {
  2090. encBoxes = findBox(sampleEntries, ['encv']);
  2091. }
  2092. encBoxes.forEach(function (enc) {
  2093. var encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);
  2094. var sinfBoxes = findBox(encBoxChildren, ['sinf']);
  2095. sinfBoxes.forEach(function (sinf) {
  2096. var tenc = parseSinf(sinf);
  2097. if (tenc) {
  2098. // Look for default key id (keyID offset is always 8 within the tenc box):
  2099. var tencKeyId = tenc.subarray(8, 24);
  2100. if (!tencKeyId.some(function (b) {
  2101. return b !== 0;
  2102. })) {
  2103. logger.log("[eme] Patching keyId in 'enc" + (isAudio ? 'a' : 'v') + ">sinf>>tenc' box: " + Hex.hexDump(tencKeyId) + " -> " + Hex.hexDump(keyId));
  2104. tenc.set(keyId, 8);
  2105. }
  2106. }
  2107. });
  2108. });
  2109. });
  2110. }
  2111. return initSegment;
  2112. }
  2113. function parseSinf(sinf) {
  2114. var schm = findBox(sinf, ['schm'])[0];
  2115. if (schm) {
  2116. var scheme = bin2str(schm.subarray(4, 8));
  2117. if (scheme === 'cbcs' || scheme === 'cenc') {
  2118. return findBox(sinf, ['schi', 'tenc'])[0];
  2119. }
  2120. }
  2121. return null;
  2122. }
  2123. /*
  2124. For Reference:
  2125. aligned(8) class TrackFragmentHeaderBox
  2126. extends FullBox(‘tfhd’, 0, tf_flags){
  2127. unsigned int(32) track_ID;
  2128. // all the following are optional fields
  2129. unsigned int(64) base_data_offset;
  2130. unsigned int(32) sample_description_index;
  2131. unsigned int(32) default_sample_duration;
  2132. unsigned int(32) default_sample_size;
  2133. unsigned int(32) default_sample_flags
  2134. }
  2135. */
  2136. function getSampleData(data, initData, logger) {
  2137. var tracks = {};
  2138. var trafs = findBox(data, ['moof', 'traf']);
  2139. for (var i = 0; i < trafs.length; i++) {
  2140. var traf = trafs[i];
  2141. // There is only one tfhd & trun per traf
  2142. // This is true for CMAF style content, and we should perhaps check the ftyp
  2143. // and only look for a single trun then, but for ISOBMFF we should check
  2144. // for multiple track runs.
  2145. var tfhd = findBox(traf, ['tfhd'])[0];
  2146. // get the track id from the tfhd
  2147. var id = readUint32(tfhd, 4);
  2148. var track = initData[id];
  2149. if (!track) {
  2150. continue;
  2151. }
  2152. var trackTimes = tracks[id] || (tracks[id] = {
  2153. start: NaN,
  2154. duration: 0,
  2155. sampleCount: 0,
  2156. timescale: track.timescale,
  2157. type: track.type
  2158. });
  2159. // get start DTS
  2160. var tfdt = findBox(traf, ['tfdt'])[0];
  2161. if (tfdt) {
  2162. var version = tfdt[0];
  2163. var baseTime = readUint32(tfdt, 4);
  2164. if (version === 1) {
  2165. // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.
  2166. // This prevents large values from being used for initPTS, which can cause playlist sync issues.
  2167. // https://github.com/video-dev/hls.js/issues/5303
  2168. if (baseTime === UINT32_MAX$1) {
  2169. logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");
  2170. } else {
  2171. baseTime *= UINT32_MAX$1 + 1;
  2172. baseTime += readUint32(tfdt, 8);
  2173. }
  2174. }
  2175. if (isFiniteNumber(baseTime) && (!isFiniteNumber(trackTimes.start) || baseTime < trackTimes.start)) {
  2176. trackTimes.start = baseTime;
  2177. }
  2178. }
  2179. var trackDefault = track.default;
  2180. var tfhdFlags = readUint32(tfhd, 0) | (trackDefault == null ? void 0 : trackDefault.flags);
  2181. var defaultSampleDuration = (trackDefault == null ? void 0 : trackDefault.duration) || 0;
  2182. if (tfhdFlags & 0x000008) {
  2183. // 0x000008 indicates the presence of the default_sample_duration field
  2184. if (tfhdFlags & 0x000002) {
  2185. // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
  2186. // If present, the default_sample_duration exists at byte offset 12
  2187. defaultSampleDuration = readUint32(tfhd, 12);
  2188. } else {
  2189. // Otherwise, the duration is at byte offset 8
  2190. defaultSampleDuration = readUint32(tfhd, 8);
  2191. }
  2192. }
  2193. var truns = findBox(traf, ['trun']);
  2194. var sampleDTS = trackTimes.start || 0;
  2195. var rawDuration = 0;
  2196. var sampleDuration = defaultSampleDuration;
  2197. for (var j = 0; j < truns.length; j++) {
  2198. var trun = truns[j];
  2199. var sampleCount = readUint32(trun, 4);
  2200. var sampleIndex = trackTimes.sampleCount;
  2201. trackTimes.sampleCount += sampleCount;
  2202. // Get duration from samples
  2203. var dataOffsetPresent = trun[3] & 0x01;
  2204. var firstSampleFlagsPresent = trun[3] & 0x04;
  2205. var sampleDurationPresent = trun[2] & 0x01;
  2206. var sampleSizePresent = trun[2] & 0x02;
  2207. var sampleFlagsPresent = trun[2] & 0x04;
  2208. var sampleCompositionTimeOffsetPresent = trun[2] & 0x08;
  2209. var offset = 8;
  2210. var remaining = sampleCount;
  2211. if (dataOffsetPresent) {
  2212. offset += 4;
  2213. }
  2214. if (firstSampleFlagsPresent && sampleCount) {
  2215. var isNonSyncSample = trun[offset + 1] & 0x01;
  2216. if (!isNonSyncSample && trackTimes.keyFrameIndex === undefined) {
  2217. trackTimes.keyFrameIndex = sampleIndex;
  2218. }
  2219. offset += 4;
  2220. if (sampleDurationPresent) {
  2221. sampleDuration = readUint32(trun, offset);
  2222. offset += 4;
  2223. } else {
  2224. sampleDuration = defaultSampleDuration;
  2225. }
  2226. if (sampleSizePresent) {
  2227. offset += 4;
  2228. }
  2229. if (sampleCompositionTimeOffsetPresent) {
  2230. offset += 4;
  2231. }
  2232. sampleDTS += sampleDuration;
  2233. rawDuration += sampleDuration;
  2234. remaining--;
  2235. }
  2236. while (remaining--) {
  2237. if (sampleDurationPresent) {
  2238. sampleDuration = readUint32(trun, offset);
  2239. offset += 4;
  2240. } else {
  2241. sampleDuration = defaultSampleDuration;
  2242. }
  2243. if (sampleSizePresent) {
  2244. offset += 4;
  2245. }
  2246. if (sampleFlagsPresent) {
  2247. var _isNonSyncSample = trun[offset + 1] & 0x01;
  2248. if (!_isNonSyncSample) {
  2249. if (trackTimes.keyFrameIndex === undefined) {
  2250. trackTimes.keyFrameIndex = trackTimes.sampleCount - (remaining + 1);
  2251. trackTimes.keyFrameStart = sampleDTS;
  2252. }
  2253. }
  2254. offset += 4;
  2255. }
  2256. if (sampleCompositionTimeOffsetPresent) {
  2257. offset += 4;
  2258. }
  2259. sampleDTS += sampleDuration;
  2260. rawDuration += sampleDuration;
  2261. }
  2262. if (!rawDuration && defaultSampleDuration) {
  2263. rawDuration += defaultSampleDuration * sampleCount;
  2264. }
  2265. }
  2266. trackTimes.duration += rawDuration;
  2267. }
  2268. if (!Object.keys(tracks).some(function (trackId) {
  2269. return tracks[trackId].duration;
  2270. })) {
  2271. // If duration samples are not available in the traf use sidx subsegment_duration
  2272. var sidxMinStart = Infinity;
  2273. var sidxMaxEnd = 0;
  2274. var sidxs = findBox(data, ['sidx']);
  2275. for (var _i2 = 0; _i2 < sidxs.length; _i2++) {
  2276. var sidx = parseSegmentIndex(sidxs[_i2]);
  2277. if (sidx != null && sidx.references) {
  2278. sidxMinStart = Math.min(sidxMinStart, sidx.earliestPresentationTime / sidx.timescale);
  2279. var subSegmentDuration = sidx.references.reduce(function (dur, ref) {
  2280. return dur + ref.info.duration || 0;
  2281. }, 0);
  2282. sidxMaxEnd = Math.max(sidxMaxEnd, subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale);
  2283. }
  2284. }
  2285. if (sidxMaxEnd && isFiniteNumber(sidxMaxEnd)) {
  2286. Object.keys(tracks).forEach(function (trackId) {
  2287. if (!tracks[trackId].duration) {
  2288. tracks[trackId].duration = sidxMaxEnd * tracks[trackId].timescale - tracks[trackId].start;
  2289. }
  2290. });
  2291. }
  2292. }
  2293. return tracks;
  2294. }
  2295. // TODO: Check if the last moof+mdat pair is part of the valid range
  2296. function segmentValidRange(data) {
  2297. var segmentedRange = {
  2298. valid: null,
  2299. remainder: null
  2300. };
  2301. var moofs = findBox(data, ['moof']);
  2302. if (moofs.length < 2) {
  2303. segmentedRange.remainder = data;
  2304. return segmentedRange;
  2305. }
  2306. var last = moofs[moofs.length - 1];
  2307. // Offset by 8 bytes; findBox offsets the start by as much
  2308. segmentedRange.valid = data.slice(0, last.byteOffset - 8);
  2309. segmentedRange.remainder = data.slice(last.byteOffset - 8);
  2310. return segmentedRange;
  2311. }
  2312. function appendUint8Array(data1, data2) {
  2313. var temp = new Uint8Array(data1.length + data2.length);
  2314. temp.set(data1);
  2315. temp.set(data2, data1.length);
  2316. return temp;
  2317. }
  2318. function parseSamples(timeOffset, track) {
  2319. var seiSamples = [];
  2320. var videoData = track.samples;
  2321. var timescale = track.timescale;
  2322. var trackId = track.id;
  2323. var isHEVCFlavor = false;
  2324. var moofs = findBox(videoData, ['moof']);
  2325. moofs.map(function (moof) {
  2326. var moofOffset = moof.byteOffset - 8;
  2327. var trafs = findBox(moof, ['traf']);
  2328. trafs.map(function (traf) {
  2329. // get the base media decode time from the tfdt
  2330. var baseTime = findBox(traf, ['tfdt']).map(function (tfdt) {
  2331. var version = tfdt[0];
  2332. var result = readUint32(tfdt, 4);
  2333. if (version === 1) {
  2334. result *= Math.pow(2, 32);
  2335. result += readUint32(tfdt, 8);
  2336. }
  2337. return result / timescale;
  2338. })[0];
  2339. if (baseTime !== undefined) {
  2340. timeOffset = baseTime;
  2341. }
  2342. return findBox(traf, ['tfhd']).map(function (tfhd) {
  2343. var id = readUint32(tfhd, 4);
  2344. var tfhdFlags = readUint32(tfhd, 0) & 0xffffff;
  2345. var baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;
  2346. var sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;
  2347. var defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;
  2348. var defaultSampleDuration = 0;
  2349. var defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;
  2350. var defaultSampleSize = 0;
  2351. var defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;
  2352. var tfhdOffset = 8;
  2353. if (id === trackId) {
  2354. if (baseDataOffsetPresent) {
  2355. tfhdOffset += 8;
  2356. }
  2357. if (sampleDescriptionIndexPresent) {
  2358. tfhdOffset += 4;
  2359. }
  2360. if (defaultSampleDurationPresent) {
  2361. defaultSampleDuration = readUint32(tfhd, tfhdOffset);
  2362. tfhdOffset += 4;
  2363. }
  2364. if (defaultSampleSizePresent) {
  2365. defaultSampleSize = readUint32(tfhd, tfhdOffset);
  2366. tfhdOffset += 4;
  2367. }
  2368. if (defaultSampleFlagsPresent) {
  2369. tfhdOffset += 4;
  2370. }
  2371. if (track.type === 'video') {
  2372. isHEVCFlavor = isHEVC(track.codec);
  2373. }
  2374. findBox(traf, ['trun']).map(function (trun) {
  2375. var version = trun[0];
  2376. var flags = readUint32(trun, 0) & 0xffffff;
  2377. var dataOffsetPresent = (flags & 0x000001) !== 0;
  2378. var dataOffset = 0;
  2379. var firstSampleFlagsPresent = (flags & 0x000004) !== 0;
  2380. var sampleDurationPresent = (flags & 0x000100) !== 0;
  2381. var sampleDuration = 0;
  2382. var sampleSizePresent = (flags & 0x000200) !== 0;
  2383. var sampleSize = 0;
  2384. var sampleFlagsPresent = (flags & 0x000400) !== 0;
  2385. var sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;
  2386. var compositionOffset = 0;
  2387. var sampleCount = readUint32(trun, 4);
  2388. var trunOffset = 8; // past version, flags, and sample count
  2389. if (dataOffsetPresent) {
  2390. dataOffset = readUint32(trun, trunOffset);
  2391. trunOffset += 4;
  2392. }
  2393. if (firstSampleFlagsPresent) {
  2394. trunOffset += 4;
  2395. }
  2396. var sampleOffset = dataOffset + moofOffset;
  2397. for (var ix = 0; ix < sampleCount; ix++) {
  2398. if (sampleDurationPresent) {
  2399. sampleDuration = readUint32(trun, trunOffset);
  2400. trunOffset += 4;
  2401. } else {
  2402. sampleDuration = defaultSampleDuration;
  2403. }
  2404. if (sampleSizePresent) {
  2405. sampleSize = readUint32(trun, trunOffset);
  2406. trunOffset += 4;
  2407. } else {
  2408. sampleSize = defaultSampleSize;
  2409. }
  2410. if (sampleFlagsPresent) {
  2411. trunOffset += 4;
  2412. }
  2413. if (sampleCompositionOffsetsPresent) {
  2414. if (version === 0) {
  2415. compositionOffset = readUint32(trun, trunOffset);
  2416. } else {
  2417. compositionOffset = readSint32(trun, trunOffset);
  2418. }
  2419. trunOffset += 4;
  2420. }
  2421. if (track.type === ElementaryStreamTypes.VIDEO) {
  2422. var naluTotalSize = 0;
  2423. while (naluTotalSize < sampleSize) {
  2424. var naluSize = readUint32(videoData, sampleOffset);
  2425. sampleOffset += 4;
  2426. if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {
  2427. var data = videoData.subarray(sampleOffset, sampleOffset + naluSize);
  2428. parseSEIMessageFromNALu(data, isHEVCFlavor ? 2 : 1, timeOffset + compositionOffset / timescale, seiSamples);
  2429. }
  2430. sampleOffset += naluSize;
  2431. naluTotalSize += naluSize + 4;
  2432. }
  2433. }
  2434. timeOffset += sampleDuration / timescale;
  2435. }
  2436. });
  2437. }
  2438. });
  2439. });
  2440. });
  2441. return seiSamples;
  2442. }
  2443. function isHEVC(codec) {
  2444. if (!codec) {
  2445. return false;
  2446. }
  2447. var baseCodec = codec.substring(0, 4);
  2448. return baseCodec === 'hvc1' || baseCodec === 'hev1' ||
  2449. // Dolby Vision
  2450. baseCodec === 'dvh1' || baseCodec === 'dvhe';
  2451. }
  2452. function isSEIMessage(isHEVCFlavor, naluHeader) {
  2453. if (isHEVCFlavor) {
  2454. var naluType = naluHeader >> 1 & 0x3f;
  2455. return naluType === 39 || naluType === 40;
  2456. } else {
  2457. var _naluType = naluHeader & 0x1f;
  2458. return _naluType === 6;
  2459. }
  2460. }
  2461. function parseSEIMessageFromNALu(unescapedData, headerSize, pts, samples) {
  2462. var data = discardEPB(unescapedData);
  2463. var seiPtr = 0;
  2464. // skip nal header
  2465. seiPtr += headerSize;
  2466. var payloadType = 0;
  2467. var payloadSize = 0;
  2468. var b = 0;
  2469. while (seiPtr < data.length) {
  2470. payloadType = 0;
  2471. do {
  2472. if (seiPtr >= data.length) {
  2473. break;
  2474. }
  2475. b = data[seiPtr++];
  2476. payloadType += b;
  2477. } while (b === 0xff);
  2478. // Parse payload size.
  2479. payloadSize = 0;
  2480. do {
  2481. if (seiPtr >= data.length) {
  2482. break;
  2483. }
  2484. b = data[seiPtr++];
  2485. payloadSize += b;
  2486. } while (b === 0xff);
  2487. var leftOver = data.length - seiPtr;
  2488. // Create a variable to process the payload
  2489. var payPtr = seiPtr;
  2490. // Increment the seiPtr to the end of the payload
  2491. if (payloadSize < leftOver) {
  2492. seiPtr += payloadSize;
  2493. } else if (payloadSize > leftOver) {
  2494. // Some type of corruption has happened?
  2495. logger.error("Malformed SEI payload. " + payloadSize + " is too small, only " + leftOver + " bytes left to parse.");
  2496. // We might be able to parse some data, but let's be safe and ignore it.
  2497. break;
  2498. }
  2499. if (payloadType === 4) {
  2500. var countryCode = data[payPtr++];
  2501. if (countryCode === 181) {
  2502. var providerCode = readUint16(data, payPtr);
  2503. payPtr += 2;
  2504. if (providerCode === 49) {
  2505. var userStructure = readUint32(data, payPtr);
  2506. payPtr += 4;
  2507. if (userStructure === 0x47413934) {
  2508. var userDataType = data[payPtr++];
  2509. // Raw CEA-608 bytes wrapped in CEA-708 packet
  2510. if (userDataType === 3) {
  2511. var firstByte = data[payPtr++];
  2512. var totalCCs = 0x1f & firstByte;
  2513. var enabled = 0x40 & firstByte;
  2514. var totalBytes = enabled ? 2 + totalCCs * 3 : 0;
  2515. var byteArray = new Uint8Array(totalBytes);
  2516. if (enabled) {
  2517. byteArray[0] = firstByte;
  2518. for (var i = 1; i < totalBytes; i++) {
  2519. byteArray[i] = data[payPtr++];
  2520. }
  2521. }
  2522. samples.push({
  2523. type: userDataType,
  2524. payloadType: payloadType,
  2525. pts: pts,
  2526. bytes: byteArray
  2527. });
  2528. }
  2529. }
  2530. }
  2531. }
  2532. } else if (payloadType === 5) {
  2533. if (payloadSize > 16) {
  2534. var uuidStrArray = [];
  2535. for (var _i3 = 0; _i3 < 16; _i3++) {
  2536. var _b = data[payPtr++].toString(16);
  2537. uuidStrArray.push(_b.length == 1 ? '0' + _b : _b);
  2538. if (_i3 === 3 || _i3 === 5 || _i3 === 7 || _i3 === 9) {
  2539. uuidStrArray.push('-');
  2540. }
  2541. }
  2542. var length = payloadSize - 16;
  2543. var userDataBytes = new Uint8Array(length);
  2544. for (var _i4 = 0; _i4 < length; _i4++) {
  2545. userDataBytes[_i4] = data[payPtr++];
  2546. }
  2547. samples.push({
  2548. payloadType: payloadType,
  2549. pts: pts,
  2550. uuid: uuidStrArray.join(''),
  2551. userData: utf8ArrayToStr(userDataBytes),
  2552. userDataBytes: userDataBytes
  2553. });
  2554. }
  2555. }
  2556. }
  2557. }
  2558. /**
  2559. * remove Emulation Prevention bytes from a RBSP
  2560. */
  2561. function discardEPB(data) {
  2562. var length = data.byteLength;
  2563. var EPBPositions = [];
  2564. var i = 1;
  2565. // Find all `Emulation Prevention Bytes`
  2566. while (i < length - 2) {
  2567. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2568. EPBPositions.push(i + 2);
  2569. i += 2;
  2570. } else {
  2571. i++;
  2572. }
  2573. }
  2574. // If no Emulation Prevention Bytes were found just return the original
  2575. // array
  2576. if (EPBPositions.length === 0) {
  2577. return data;
  2578. }
  2579. // Create a new array to hold the NAL unit data
  2580. var newLength = length - EPBPositions.length;
  2581. var newData = new Uint8Array(newLength);
  2582. var sourceIndex = 0;
  2583. for (i = 0; i < newLength; sourceIndex++, i++) {
  2584. if (sourceIndex === EPBPositions[0]) {
  2585. // Skip this byte
  2586. sourceIndex++;
  2587. // Remove this position index
  2588. EPBPositions.shift();
  2589. }
  2590. newData[i] = data[sourceIndex];
  2591. }
  2592. return newData;
  2593. }
  2594. function parseEmsg(data) {
  2595. var version = data[0];
  2596. var schemeIdUri = '';
  2597. var value = '';
  2598. var timeScale = 0;
  2599. var presentationTimeDelta = 0;
  2600. var presentationTime = 0;
  2601. var eventDuration = 0;
  2602. var id = 0;
  2603. var offset = 0;
  2604. if (version === 0) {
  2605. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2606. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2607. offset += 1;
  2608. }
  2609. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2610. offset += 1;
  2611. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2612. value += bin2str(data.subarray(offset, offset + 1));
  2613. offset += 1;
  2614. }
  2615. value += bin2str(data.subarray(offset, offset + 1));
  2616. offset += 1;
  2617. timeScale = readUint32(data, 12);
  2618. presentationTimeDelta = readUint32(data, 16);
  2619. eventDuration = readUint32(data, 20);
  2620. id = readUint32(data, 24);
  2621. offset = 28;
  2622. } else if (version === 1) {
  2623. offset += 4;
  2624. timeScale = readUint32(data, offset);
  2625. offset += 4;
  2626. var leftPresentationTime = readUint32(data, offset);
  2627. offset += 4;
  2628. var rightPresentationTime = readUint32(data, offset);
  2629. offset += 4;
  2630. presentationTime = Math.pow(2, 32) * leftPresentationTime + rightPresentationTime;
  2631. if (!isSafeInteger(presentationTime)) {
  2632. presentationTime = Number.MAX_SAFE_INTEGER;
  2633. logger.warn('Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box');
  2634. }
  2635. eventDuration = readUint32(data, offset);
  2636. offset += 4;
  2637. id = readUint32(data, offset);
  2638. offset += 4;
  2639. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2640. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2641. offset += 1;
  2642. }
  2643. schemeIdUri += bin2str(data.subarray(offset, offset + 1));
  2644. offset += 1;
  2645. while (bin2str(data.subarray(offset, offset + 1)) !== '\0') {
  2646. value += bin2str(data.subarray(offset, offset + 1));
  2647. offset += 1;
  2648. }
  2649. value += bin2str(data.subarray(offset, offset + 1));
  2650. offset += 1;
  2651. }
  2652. var payload = data.subarray(offset, data.byteLength);
  2653. return {
  2654. schemeIdUri: schemeIdUri,
  2655. value: value,
  2656. timeScale: timeScale,
  2657. presentationTime: presentationTime,
  2658. presentationTimeDelta: presentationTimeDelta,
  2659. eventDuration: eventDuration,
  2660. id: id,
  2661. payload: payload
  2662. };
  2663. }
  2664. function mp4Box(type) {
  2665. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  2666. payload[_key - 1] = arguments[_key];
  2667. }
  2668. var len = payload.length;
  2669. var size = 8;
  2670. var i = len;
  2671. while (i--) {
  2672. size += payload[i].byteLength;
  2673. }
  2674. var result = new Uint8Array(size);
  2675. result[0] = size >> 24 & 0xff;
  2676. result[1] = size >> 16 & 0xff;
  2677. result[2] = size >> 8 & 0xff;
  2678. result[3] = size & 0xff;
  2679. result.set(type, 4);
  2680. for (i = 0, size = 8; i < len; i++) {
  2681. result.set(payload[i], size);
  2682. size += payload[i].byteLength;
  2683. }
  2684. return result;
  2685. }
  2686. function mp4pssh(systemId, keyids, data) {
  2687. if (systemId.byteLength !== 16) {
  2688. throw new RangeError('Invalid system id');
  2689. }
  2690. var version;
  2691. var kids;
  2692. {
  2693. version = 0;
  2694. kids = new Uint8Array();
  2695. }
  2696. var kidCount;
  2697. if (version > 0) {
  2698. kidCount = new Uint8Array(4);
  2699. if (keyids.length > 0) {
  2700. new DataView(kidCount.buffer).setUint32(0, keyids.length, false);
  2701. }
  2702. } else {
  2703. kidCount = new Uint8Array();
  2704. }
  2705. var dataSize = new Uint8Array(4);
  2706. if (data && data.byteLength > 0) {
  2707. new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);
  2708. }
  2709. return mp4Box([112, 115, 115, 104], new Uint8Array([version, 0x00, 0x00, 0x00 // Flags
  2710. ]), systemId,
  2711. // 16 bytes
  2712. kidCount, kids, dataSize, data || new Uint8Array());
  2713. }
  2714. var userAgentHevcSupportIsInaccurate = function userAgentHevcSupportIsInaccurate() {
  2715. return /\(Windows.+Firefox\//i.test(navigator.userAgent);
  2716. };
  2717. // from http://mp4ra.org/codecs.html
  2718. // values indicate codec selection preference (lower is higher priority)
  2719. var sampleEntryCodesISO = {
  2720. audio: {
  2721. a3ds: 1,
  2722. 'ac-3': 0.95,
  2723. 'ac-4': 1,
  2724. alac: 0.9,
  2725. alaw: 1,
  2726. dra1: 1,
  2727. 'dts+': 1,
  2728. 'dts-': 1,
  2729. dtsc: 1,
  2730. dtse: 1,
  2731. dtsh: 1,
  2732. 'ec-3': 0.9,
  2733. enca: 1,
  2734. fLaC: 0.9,
  2735. // MP4-RA listed codec entry for FLAC
  2736. flac: 0.9,
  2737. // legacy browser codec name for FLAC
  2738. FLAC: 0.9,
  2739. // some manifests may list "FLAC" with Apple's tools
  2740. g719: 1,
  2741. g726: 1,
  2742. m4ae: 1,
  2743. mha1: 1,
  2744. mha2: 1,
  2745. mhm1: 1,
  2746. mhm2: 1,
  2747. mlpa: 1,
  2748. mp4a: 1,
  2749. 'raw ': 1,
  2750. Opus: 1,
  2751. opus: 1,
  2752. // browsers expect this to be lowercase despite MP4RA says 'Opus'
  2753. samr: 1,
  2754. sawb: 1,
  2755. sawp: 1,
  2756. sevc: 1,
  2757. sqcp: 1,
  2758. ssmv: 1,
  2759. twos: 1,
  2760. ulaw: 1
  2761. },
  2762. video: {
  2763. avc1: 1,
  2764. avc2: 1,
  2765. avc3: 1,
  2766. avc4: 1,
  2767. avcp: 1,
  2768. av01: 0.8,
  2769. dav1: 0.8,
  2770. drac: 1,
  2771. dva1: 1,
  2772. dvav: 1,
  2773. dvh1: 0.7,
  2774. dvhe: 0.7,
  2775. encv: 1,
  2776. hev1: 0.75,
  2777. hvc1: 0.75,
  2778. mjp2: 1,
  2779. mp4v: 1,
  2780. mvc1: 1,
  2781. mvc2: 1,
  2782. mvc3: 1,
  2783. mvc4: 1,
  2784. resv: 1,
  2785. rv60: 1,
  2786. s263: 1,
  2787. svc1: 1,
  2788. svc2: 1,
  2789. 'vc-1': 1,
  2790. vp08: 1,
  2791. vp09: 0.9
  2792. },
  2793. text: {
  2794. stpp: 1,
  2795. wvtt: 1
  2796. }
  2797. };
  2798. function isCodecType(codec, type) {
  2799. var typeCodes = sampleEntryCodesISO[type];
  2800. return !!typeCodes && !!typeCodes[codec.slice(0, 4)];
  2801. }
  2802. function areCodecsMediaSourceSupported(codecs, type, preferManagedMediaSource) {
  2803. if (preferManagedMediaSource === void 0) {
  2804. preferManagedMediaSource = true;
  2805. }
  2806. return !codecs.split(',').some(function (codec) {
  2807. return !isCodecMediaSourceSupported(codec, type, preferManagedMediaSource);
  2808. });
  2809. }
  2810. function isCodecMediaSourceSupported(codec, type, preferManagedMediaSource) {
  2811. var _MediaSource$isTypeSu;
  2812. if (preferManagedMediaSource === void 0) {
  2813. preferManagedMediaSource = true;
  2814. }
  2815. var MediaSource = getMediaSource(preferManagedMediaSource);
  2816. return (_MediaSource$isTypeSu = MediaSource == null ? void 0 : MediaSource.isTypeSupported(mimeTypeForCodec(codec, type))) != null ? _MediaSource$isTypeSu : false;
  2817. }
  2818. function mimeTypeForCodec(codec, type) {
  2819. return type + "/mp4;codecs=" + codec;
  2820. }
  2821. function videoCodecPreferenceValue(videoCodec) {
  2822. if (videoCodec) {
  2823. var fourCC = videoCodec.substring(0, 4);
  2824. return sampleEntryCodesISO.video[fourCC];
  2825. }
  2826. return 2;
  2827. }
  2828. function codecsSetSelectionPreferenceValue(codecSet) {
  2829. var limitedHevcSupport = userAgentHevcSupportIsInaccurate();
  2830. return codecSet.split(',').reduce(function (num, fourCC) {
  2831. var lowerPriority = limitedHevcSupport && isHEVC(fourCC);
  2832. var preferenceValue = lowerPriority ? 9 : sampleEntryCodesISO.video[fourCC];
  2833. if (preferenceValue) {
  2834. return (preferenceValue * 2 + num) / (num ? 3 : 2);
  2835. }
  2836. return (sampleEntryCodesISO.audio[fourCC] + num) / (num ? 2 : 1);
  2837. }, 0);
  2838. }
  2839. var CODEC_COMPATIBLE_NAMES = {};
  2840. function getCodecCompatibleNameLower(lowerCaseCodec, preferManagedMediaSource) {
  2841. if (preferManagedMediaSource === void 0) {
  2842. preferManagedMediaSource = true;
  2843. }
  2844. if (CODEC_COMPATIBLE_NAMES[lowerCaseCodec]) {
  2845. return CODEC_COMPATIBLE_NAMES[lowerCaseCodec];
  2846. }
  2847. var codecsToCheck = {
  2848. // Idealy fLaC and Opus would be first (spec-compliant) but
  2849. // some browsers will report that fLaC is supported then fail.
  2850. // see: https://bugs.chromium.org/p/chromium/issues/detail?id=1422728
  2851. flac: ['flac', 'fLaC', 'FLAC'],
  2852. opus: ['opus', 'Opus'],
  2853. // Replace audio codec info if browser does not support mp4a.40.34,
  2854. // and demuxer can fallback to 'audio/mpeg' or 'audio/mp4;codecs="mp3"'
  2855. 'mp4a.40.34': ['mp3']
  2856. }[lowerCaseCodec];
  2857. for (var i = 0; i < codecsToCheck.length; i++) {
  2858. var _getMediaSource;
  2859. if (isCodecMediaSourceSupported(codecsToCheck[i], 'audio', preferManagedMediaSource)) {
  2860. CODEC_COMPATIBLE_NAMES[lowerCaseCodec] = codecsToCheck[i];
  2861. return codecsToCheck[i];
  2862. } else if (codecsToCheck[i] === 'mp3' && (_getMediaSource = getMediaSource(preferManagedMediaSource)) != null && _getMediaSource.isTypeSupported('audio/mpeg')) {
  2863. return '';
  2864. }
  2865. }
  2866. return lowerCaseCodec;
  2867. }
  2868. var AUDIO_CODEC_REGEXP = /flac|opus|mp4a\.40\.34/i;
  2869. function getCodecCompatibleName(codec, preferManagedMediaSource) {
  2870. if (preferManagedMediaSource === void 0) {
  2871. preferManagedMediaSource = true;
  2872. }
  2873. return codec.replace(AUDIO_CODEC_REGEXP, function (m) {
  2874. return getCodecCompatibleNameLower(m.toLowerCase(), preferManagedMediaSource);
  2875. });
  2876. }
  2877. function replaceVideoCodec(originalCodecs, newVideoCodec) {
  2878. var codecs = [];
  2879. if (originalCodecs) {
  2880. var allCodecs = originalCodecs.split(',');
  2881. for (var i = 0; i < allCodecs.length; i++) {
  2882. if (!isCodecType(allCodecs[i], 'video')) {
  2883. codecs.push(allCodecs[i]);
  2884. }
  2885. }
  2886. }
  2887. if (newVideoCodec) {
  2888. codecs.push(newVideoCodec);
  2889. }
  2890. return codecs.join(',');
  2891. }
  2892. function pickMostCompleteCodecName(parsedCodec, levelCodec) {
  2893. // Parsing of mp4a codecs strings in mp4-tools from media is incomplete as of d8c6c7a
  2894. // so use level codec is parsed codec is unavailable or incomplete
  2895. if (parsedCodec && (parsedCodec.length > 4 || ['ac-3', 'ec-3', 'alac', 'fLaC', 'Opus'].indexOf(parsedCodec) !== -1)) {
  2896. if (isCodecSupportedAsType(parsedCodec, 'audio') || isCodecSupportedAsType(parsedCodec, 'video')) {
  2897. return parsedCodec;
  2898. }
  2899. }
  2900. if (levelCodec) {
  2901. var levelCodecs = levelCodec.split(',');
  2902. if (levelCodecs.length > 1) {
  2903. if (parsedCodec) {
  2904. for (var i = levelCodecs.length; i--;) {
  2905. if (levelCodecs[i].substring(0, 4) === parsedCodec.substring(0, 4)) {
  2906. return levelCodecs[i];
  2907. }
  2908. }
  2909. }
  2910. return levelCodecs[0];
  2911. }
  2912. }
  2913. return levelCodec || parsedCodec;
  2914. }
  2915. function isCodecSupportedAsType(codec, type) {
  2916. return isCodecType(codec, type) && isCodecMediaSourceSupported(codec, type);
  2917. }
  2918. function convertAVC1ToAVCOTI(videoCodecs) {
  2919. // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
  2920. // Examples: avc1.66.30 to avc1.42001e and avc1.77.30,avc1.66.30 to avc1.4d001e,avc1.42001e.
  2921. var codecs = videoCodecs.split(',');
  2922. for (var i = 0; i < codecs.length; i++) {
  2923. var avcdata = codecs[i].split('.');
  2924. // only convert codec strings starting with avc1 (Examples: avc1.64001f,dvh1.05.07)
  2925. if (avcdata.length > 2 && avcdata[0] === 'avc1') {
  2926. codecs[i] = "avc1." + parseInt(avcdata[1]).toString(16) + ('000' + parseInt(avcdata[2]).toString(16)).slice(-4);
  2927. }
  2928. }
  2929. return codecs.join(',');
  2930. }
  2931. function fillInMissingAV01Params(videoCodec) {
  2932. // Used to fill in incomplete AV1 playlist CODECS strings for mediaCapabilities.decodingInfo queries
  2933. if (videoCodec.startsWith('av01.')) {
  2934. var av1params = videoCodec.split('.');
  2935. var placeholders = ['0', '111', '01', '01', '01', '0'];
  2936. for (var i = av1params.length; i > 4 && i < 10; i++) {
  2937. av1params[i] = placeholders[i - 4];
  2938. }
  2939. return av1params.join('.');
  2940. }
  2941. return videoCodec;
  2942. }
  2943. function getM2TSSupportedAudioTypes(preferManagedMediaSource) {
  2944. var MediaSource = getMediaSource(preferManagedMediaSource) || {
  2945. isTypeSupported: function isTypeSupported() {
  2946. return false;
  2947. }
  2948. };
  2949. return {
  2950. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  2951. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"'),
  2952. ac3: MediaSource.isTypeSupported('audio/mp4; codecs="ac-3"')
  2953. };
  2954. }
  2955. function getCodecsForMimeType(mimeType) {
  2956. return mimeType.replace(/^.+codecs=["']?([^"']+).*$/, '$1');
  2957. }
  2958. var SUPPORTED_INFO_DEFAULT = {
  2959. supported: true,
  2960. configurations: [],
  2961. decodingInfoResults: [{
  2962. supported: true,
  2963. powerEfficient: true,
  2964. smooth: true
  2965. }]
  2966. };
  2967. function getUnsupportedResult(error, configurations) {
  2968. return {
  2969. supported: false,
  2970. configurations: configurations,
  2971. decodingInfoResults: [{
  2972. supported: false,
  2973. smooth: false,
  2974. powerEfficient: false
  2975. }],
  2976. error: error
  2977. };
  2978. }
  2979. function requiresMediaCapabilitiesDecodingInfo(level, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference) {
  2980. // Only test support when configuration is exceeds minimum options
  2981. var videoCodecs = level.videoCodec;
  2982. var audioGroups = level.audioCodec ? level.audioGroups : null;
  2983. var audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  2984. var channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  2985. var maxChannels = channelsPreference ? parseInt(channelsPreference) : audioCodecPreference ? Infinity : 2;
  2986. var audioChannels = null;
  2987. if (audioGroups != null && audioGroups.length) {
  2988. try {
  2989. if (audioGroups.length === 1 && audioGroups[0]) {
  2990. audioChannels = audioTracksByGroup.groups[audioGroups[0]].channels;
  2991. } else {
  2992. audioChannels = audioGroups.reduce(function (acc, groupId) {
  2993. if (groupId) {
  2994. var audioTrackGroup = audioTracksByGroup.groups[groupId];
  2995. if (!audioTrackGroup) {
  2996. throw new Error("Audio track group " + groupId + " not found");
  2997. }
  2998. // Sum all channel key values
  2999. Object.keys(audioTrackGroup.channels).forEach(function (key) {
  3000. acc[key] = (acc[key] || 0) + audioTrackGroup.channels[key];
  3001. });
  3002. }
  3003. return acc;
  3004. }, {
  3005. 2: 0
  3006. });
  3007. }
  3008. } catch (error) {
  3009. return true;
  3010. }
  3011. }
  3012. return videoCodecs !== undefined && (
  3013. // Force media capabilities check for HEVC to avoid failure on Windows
  3014. videoCodecs.split(',').some(function (videoCodec) {
  3015. return isHEVC(videoCodec);
  3016. }) || level.width > 1920 && level.height > 1088 || level.height > 1920 && level.width > 1088 || level.frameRate > Math.max(currentFrameRate, 30) || level.videoRange !== 'SDR' && level.videoRange !== currentVideoRange || level.bitrate > Math.max(currentBw, 8e6)) || !!audioChannels && isFiniteNumber(maxChannels) && Object.keys(audioChannels).some(function (channels) {
  3017. return parseInt(channels) > maxChannels;
  3018. });
  3019. }
  3020. function getMediaDecodingInfoPromise(level, audioTracksByGroup, mediaCapabilities, cache) {
  3021. if (cache === void 0) {
  3022. cache = {};
  3023. }
  3024. var videoCodecs = level.videoCodec;
  3025. if (!videoCodecs && !level.audioCodec || !mediaCapabilities) {
  3026. return Promise.resolve(SUPPORTED_INFO_DEFAULT);
  3027. }
  3028. var configurations = [];
  3029. var videoDecodeList = makeVideoConfigurations(level);
  3030. var videoCount = videoDecodeList.length;
  3031. var audioDecodeList = makeAudioConfigurations(level, audioTracksByGroup, videoCount > 0);
  3032. var audioCount = audioDecodeList.length;
  3033. for (var i = videoCount || 1 * audioCount || 1; i--;) {
  3034. var configuration = {
  3035. type: 'media-source'
  3036. };
  3037. if (videoCount) {
  3038. configuration.video = videoDecodeList[i % videoCount];
  3039. }
  3040. if (audioCount) {
  3041. configuration.audio = audioDecodeList[i % audioCount];
  3042. var audioBitrate = configuration.audio.bitrate;
  3043. if (configuration.video && audioBitrate) {
  3044. configuration.video.bitrate -= audioBitrate;
  3045. }
  3046. }
  3047. configurations.push(configuration);
  3048. }
  3049. if (videoCodecs) {
  3050. // Override Windows Firefox HEVC MediaCapabilities result (https://github.com/video-dev/hls.js/issues/7046)
  3051. var ua = navigator.userAgent;
  3052. if (videoCodecs.split(',').some(function (videoCodec) {
  3053. return isHEVC(videoCodec);
  3054. }) && userAgentHevcSupportIsInaccurate()) {
  3055. return Promise.resolve(getUnsupportedResult(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (" + ua + ")"), configurations));
  3056. }
  3057. }
  3058. return Promise.all(configurations.map(function (configuration) {
  3059. // Cache MediaCapabilities promises
  3060. var decodingInfoKey = getMediaDecodingInfoKey(configuration);
  3061. return cache[decodingInfoKey] || (cache[decodingInfoKey] = mediaCapabilities.decodingInfo(configuration));
  3062. })).then(function (decodingInfoResults) {
  3063. return {
  3064. supported: !decodingInfoResults.some(function (info) {
  3065. return !info.supported;
  3066. }),
  3067. configurations: configurations,
  3068. decodingInfoResults: decodingInfoResults
  3069. };
  3070. }).catch(function (error) {
  3071. return {
  3072. supported: false,
  3073. configurations: configurations,
  3074. decodingInfoResults: [],
  3075. error: error
  3076. };
  3077. });
  3078. }
  3079. function makeVideoConfigurations(level) {
  3080. var _level$videoCodec;
  3081. var videoCodecs = (_level$videoCodec = level.videoCodec) == null ? void 0 : _level$videoCodec.split(',');
  3082. var bitrate = getVariantDecodingBitrate(level);
  3083. var width = level.width || 640;
  3084. var height = level.height || 480;
  3085. // Assume a framerate of 30fps since MediaCapabilities will not accept Level default of 0.
  3086. var framerate = level.frameRate || 30;
  3087. var videoRange = level.videoRange.toLowerCase();
  3088. return videoCodecs ? videoCodecs.map(function (videoCodec) {
  3089. var videoConfiguration = {
  3090. contentType: mimeTypeForCodec(fillInMissingAV01Params(videoCodec), 'video'),
  3091. width: width,
  3092. height: height,
  3093. bitrate: bitrate,
  3094. framerate: framerate
  3095. };
  3096. if (videoRange !== 'sdr') {
  3097. videoConfiguration.transferFunction = videoRange;
  3098. }
  3099. return videoConfiguration;
  3100. }) : [];
  3101. }
  3102. function makeAudioConfigurations(level, audioTracksByGroup, hasVideo) {
  3103. var _level$audioCodec;
  3104. var audioCodecs = (_level$audioCodec = level.audioCodec) == null ? void 0 : _level$audioCodec.split(',');
  3105. var combinedBitrate = getVariantDecodingBitrate(level);
  3106. if (audioCodecs && level.audioGroups) {
  3107. return level.audioGroups.reduce(function (configurations, audioGroupId) {
  3108. var _audioTracksByGroup$g;
  3109. var tracks = audioGroupId ? (_audioTracksByGroup$g = audioTracksByGroup.groups[audioGroupId]) == null ? void 0 : _audioTracksByGroup$g.tracks : null;
  3110. if (tracks) {
  3111. return tracks.reduce(function (configs, audioTrack) {
  3112. if (audioTrack.groupId === audioGroupId) {
  3113. var channelsNumber = parseFloat(audioTrack.channels || '');
  3114. audioCodecs.forEach(function (audioCodec) {
  3115. var audioConfiguration = {
  3116. contentType: mimeTypeForCodec(audioCodec, 'audio'),
  3117. bitrate: hasVideo ? estimatedAudioBitrate(audioCodec, combinedBitrate) : combinedBitrate
  3118. };
  3119. if (channelsNumber) {
  3120. audioConfiguration.channels = '' + channelsNumber;
  3121. }
  3122. configs.push(audioConfiguration);
  3123. });
  3124. }
  3125. return configs;
  3126. }, configurations);
  3127. }
  3128. return configurations;
  3129. }, []);
  3130. }
  3131. return [];
  3132. }
  3133. function estimatedAudioBitrate(audioCodec, levelBitrate) {
  3134. if (levelBitrate <= 1) {
  3135. return 1;
  3136. }
  3137. var audioBitrate = 128000;
  3138. if (audioCodec === 'ec-3') {
  3139. audioBitrate = 768000;
  3140. } else if (audioCodec === 'ac-3') {
  3141. audioBitrate = 640000;
  3142. }
  3143. return Math.min(levelBitrate / 2, audioBitrate); // Don't exceed some % of level bitrate
  3144. }
  3145. function getVariantDecodingBitrate(level) {
  3146. return Math.ceil(Math.max(level.bitrate * 0.9, level.averageBitrate) / 1000) * 1000 || 1;
  3147. }
  3148. function getMediaDecodingInfoKey(config) {
  3149. var key = '';
  3150. var audio = config.audio,
  3151. video = config.video;
  3152. if (video) {
  3153. var codec = getCodecsForMimeType(video.contentType);
  3154. key += codec + "_r" + video.height + "x" + video.width + "f" + Math.ceil(video.framerate) + (video.transferFunction || 'sd') + "_" + Math.ceil(video.bitrate / 1e5);
  3155. }
  3156. if (audio) {
  3157. var _codec = getCodecsForMimeType(audio.contentType);
  3158. key += "" + (video ? '_' : '') + _codec + "_c" + audio.channels;
  3159. }
  3160. return key;
  3161. }
  3162. var HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null];
  3163. function isHdcpLevel(value) {
  3164. return HdcpLevels.indexOf(value) > -1;
  3165. }
  3166. var VideoRangeValues = ['SDR', 'PQ', 'HLG'];
  3167. function isVideoRange(value) {
  3168. return !!value && VideoRangeValues.indexOf(value) > -1;
  3169. }
  3170. var HlsSkip = {
  3171. No: "",
  3172. Yes: "YES",
  3173. v2: "v2"
  3174. };
  3175. function getSkipValue(details) {
  3176. var canSkipUntil = details.canSkipUntil,
  3177. canSkipDateRanges = details.canSkipDateRanges,
  3178. age = details.age;
  3179. // A Client SHOULD NOT request a Playlist Delta Update unless it already
  3180. // has a version of the Playlist that is no older than one-half of the Skip Boundary.
  3181. // @see: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis#section-6.3.7
  3182. var playlistRecentEnough = age < canSkipUntil / 2;
  3183. if (canSkipUntil && playlistRecentEnough) {
  3184. if (canSkipDateRanges) {
  3185. return HlsSkip.v2;
  3186. }
  3187. return HlsSkip.Yes;
  3188. }
  3189. return HlsSkip.No;
  3190. }
  3191. var HlsUrlParameters = /*#__PURE__*/function () {
  3192. function HlsUrlParameters(msn, part, skip) {
  3193. this.msn = void 0;
  3194. this.part = void 0;
  3195. this.skip = void 0;
  3196. this.msn = msn;
  3197. this.part = part;
  3198. this.skip = skip;
  3199. }
  3200. var _proto = HlsUrlParameters.prototype;
  3201. _proto.addDirectives = function addDirectives(uri) {
  3202. var url = new self.URL(uri);
  3203. if (this.msn !== undefined) {
  3204. url.searchParams.set('_HLS_msn', this.msn.toString());
  3205. }
  3206. if (this.part !== undefined) {
  3207. url.searchParams.set('_HLS_part', this.part.toString());
  3208. }
  3209. if (this.skip) {
  3210. url.searchParams.set('_HLS_skip', this.skip);
  3211. }
  3212. return url.href;
  3213. };
  3214. return HlsUrlParameters;
  3215. }();
  3216. var Level = /*#__PURE__*/function () {
  3217. function Level(data) {
  3218. this._attrs = void 0;
  3219. this.audioCodec = void 0;
  3220. this.bitrate = void 0;
  3221. this.codecSet = void 0;
  3222. this.url = void 0;
  3223. this.frameRate = void 0;
  3224. this.height = void 0;
  3225. this.id = void 0;
  3226. this.name = void 0;
  3227. this.supplemental = void 0;
  3228. this.videoCodec = void 0;
  3229. this.width = void 0;
  3230. this.details = void 0;
  3231. this.fragmentError = 0;
  3232. this.loadError = 0;
  3233. this.loaded = void 0;
  3234. this.realBitrate = 0;
  3235. this.supportedPromise = void 0;
  3236. this.supportedResult = void 0;
  3237. this._avgBitrate = 0;
  3238. this._audioGroups = void 0;
  3239. this._subtitleGroups = void 0;
  3240. // Deprecated (retained for backwards compatibility)
  3241. this._urlId = 0;
  3242. this.url = [data.url];
  3243. this._attrs = [data.attrs];
  3244. this.bitrate = data.bitrate;
  3245. if (data.details) {
  3246. this.details = data.details;
  3247. }
  3248. this.id = data.id || 0;
  3249. this.name = data.name;
  3250. this.width = data.width || 0;
  3251. this.height = data.height || 0;
  3252. this.frameRate = data.attrs.optionalFloat('FRAME-RATE', 0);
  3253. this._avgBitrate = data.attrs.decimalInteger('AVERAGE-BANDWIDTH');
  3254. this.audioCodec = data.audioCodec;
  3255. this.videoCodec = data.videoCodec;
  3256. this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
  3257. return !!c;
  3258. }).map(function (s) {
  3259. return s.substring(0, 4);
  3260. }).join(',');
  3261. if ('supplemental' in data) {
  3262. var _data$supplemental;
  3263. this.supplemental = data.supplemental;
  3264. var supplementalVideo = (_data$supplemental = data.supplemental) == null ? void 0 : _data$supplemental.videoCodec;
  3265. if (supplementalVideo && supplementalVideo !== data.videoCodec) {
  3266. this.codecSet += "," + supplementalVideo.substring(0, 4);
  3267. }
  3268. }
  3269. this.addGroupId('audio', data.attrs.AUDIO);
  3270. this.addGroupId('text', data.attrs.SUBTITLES);
  3271. }
  3272. var _proto2 = Level.prototype;
  3273. _proto2.hasAudioGroup = function hasAudioGroup(groupId) {
  3274. return hasGroup(this._audioGroups, groupId);
  3275. };
  3276. _proto2.hasSubtitleGroup = function hasSubtitleGroup(groupId) {
  3277. return hasGroup(this._subtitleGroups, groupId);
  3278. };
  3279. _proto2.addGroupId = function addGroupId(type, groupId) {
  3280. if (!groupId) {
  3281. return;
  3282. }
  3283. if (type === 'audio') {
  3284. var audioGroups = this._audioGroups;
  3285. if (!audioGroups) {
  3286. audioGroups = this._audioGroups = [];
  3287. }
  3288. if (audioGroups.indexOf(groupId) === -1) {
  3289. audioGroups.push(groupId);
  3290. }
  3291. } else if (type === 'text') {
  3292. var subtitleGroups = this._subtitleGroups;
  3293. if (!subtitleGroups) {
  3294. subtitleGroups = this._subtitleGroups = [];
  3295. }
  3296. if (subtitleGroups.indexOf(groupId) === -1) {
  3297. subtitleGroups.push(groupId);
  3298. }
  3299. }
  3300. }
  3301. // Deprecated methods (retained for backwards compatibility)
  3302. ;
  3303. _proto2.addFallback = function addFallback() {};
  3304. return _createClass(Level, [{
  3305. key: "maxBitrate",
  3306. get: function get() {
  3307. return Math.max(this.realBitrate, this.bitrate);
  3308. }
  3309. }, {
  3310. key: "averageBitrate",
  3311. get: function get() {
  3312. return this._avgBitrate || this.realBitrate || this.bitrate;
  3313. }
  3314. }, {
  3315. key: "attrs",
  3316. get: function get() {
  3317. return this._attrs[0];
  3318. }
  3319. }, {
  3320. key: "codecs",
  3321. get: function get() {
  3322. return this.attrs.CODECS || '';
  3323. }
  3324. }, {
  3325. key: "pathwayId",
  3326. get: function get() {
  3327. return this.attrs['PATHWAY-ID'] || '.';
  3328. }
  3329. }, {
  3330. key: "videoRange",
  3331. get: function get() {
  3332. return this.attrs['VIDEO-RANGE'] || 'SDR';
  3333. }
  3334. }, {
  3335. key: "score",
  3336. get: function get() {
  3337. return this.attrs.optionalFloat('SCORE', 0);
  3338. }
  3339. }, {
  3340. key: "uri",
  3341. get: function get() {
  3342. return this.url[0] || '';
  3343. }
  3344. }, {
  3345. key: "audioGroups",
  3346. get: function get() {
  3347. return this._audioGroups;
  3348. }
  3349. }, {
  3350. key: "subtitleGroups",
  3351. get: function get() {
  3352. return this._subtitleGroups;
  3353. }
  3354. }, {
  3355. key: "urlId",
  3356. get: function get() {
  3357. return 0;
  3358. },
  3359. set: function set(value) {}
  3360. }, {
  3361. key: "audioGroupIds",
  3362. get: function get() {
  3363. return this.audioGroups ? [this.audioGroupId] : undefined;
  3364. }
  3365. }, {
  3366. key: "textGroupIds",
  3367. get: function get() {
  3368. return this.subtitleGroups ? [this.textGroupId] : undefined;
  3369. }
  3370. }, {
  3371. key: "audioGroupId",
  3372. get: function get() {
  3373. var _this$audioGroups;
  3374. return (_this$audioGroups = this.audioGroups) == null ? void 0 : _this$audioGroups[0];
  3375. }
  3376. }, {
  3377. key: "textGroupId",
  3378. get: function get() {
  3379. var _this$subtitleGroups;
  3380. return (_this$subtitleGroups = this.subtitleGroups) == null ? void 0 : _this$subtitleGroups[0];
  3381. }
  3382. }]);
  3383. }();
  3384. function hasGroup(groups, groupId) {
  3385. if (!groupId || !groups) {
  3386. return false;
  3387. }
  3388. return groups.indexOf(groupId) !== -1;
  3389. }
  3390. /**
  3391. * @returns Whether we can detect and validate HDR capability within the window context
  3392. */
  3393. function isHdrSupported() {
  3394. if (typeof matchMedia === 'function') {
  3395. var mediaQueryList = matchMedia('(dynamic-range: high)');
  3396. var badQuery = matchMedia('bad query');
  3397. if (mediaQueryList.media !== badQuery.media) {
  3398. return mediaQueryList.matches === true;
  3399. }
  3400. }
  3401. return false;
  3402. }
  3403. /**
  3404. * Sanitizes inputs to return the active video selection options for HDR/SDR.
  3405. * When both inputs are null:
  3406. *
  3407. * `{ preferHDR: false, allowedVideoRanges: [] }`
  3408. *
  3409. * When `currentVideoRange` non-null, maintain the active range:
  3410. *
  3411. * `{ preferHDR: currentVideoRange !== 'SDR', allowedVideoRanges: [currentVideoRange] }`
  3412. *
  3413. * When VideoSelectionOption non-null:
  3414. *
  3415. * - Allow all video ranges if `allowedVideoRanges` unspecified.
  3416. * - If `preferHDR` is non-null use the value to filter `allowedVideoRanges`.
  3417. * - Else check window for HDR support and set `preferHDR` to the result.
  3418. *
  3419. * @param currentVideoRange
  3420. * @param videoPreference
  3421. */
  3422. function getVideoSelectionOptions(currentVideoRange, videoPreference) {
  3423. var preferHDR = false;
  3424. var allowedVideoRanges = [];
  3425. if (currentVideoRange) {
  3426. preferHDR = currentVideoRange !== 'SDR';
  3427. allowedVideoRanges = [currentVideoRange];
  3428. }
  3429. if (videoPreference) {
  3430. allowedVideoRanges = videoPreference.allowedVideoRanges || VideoRangeValues.slice(0);
  3431. var allowAutoPreferHDR = allowedVideoRanges.join('') !== 'SDR' && !videoPreference.videoCodec;
  3432. preferHDR = videoPreference.preferHDR !== undefined ? videoPreference.preferHDR : allowAutoPreferHDR && isHdrSupported();
  3433. if (!preferHDR) {
  3434. allowedVideoRanges = ['SDR'];
  3435. }
  3436. }
  3437. return {
  3438. preferHDR: preferHDR,
  3439. allowedVideoRanges: allowedVideoRanges
  3440. };
  3441. }
  3442. var omitCircularRefsReplacer = function omitCircularRefsReplacer(replacer) {
  3443. var known = new WeakSet();
  3444. return function (_, value) {
  3445. if (replacer) {
  3446. value = replacer(_, value);
  3447. }
  3448. if (typeof value === 'object' && value !== null) {
  3449. if (known.has(value)) {
  3450. return;
  3451. }
  3452. known.add(value);
  3453. }
  3454. return value;
  3455. };
  3456. };
  3457. var stringify = function stringify(object, replacer) {
  3458. return JSON.stringify(object, omitCircularRefsReplacer(replacer));
  3459. };
  3460. function getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference) {
  3461. var codecSets = Object.keys(codecTiers);
  3462. var channelsPreference = audioPreference == null ? void 0 : audioPreference.channels;
  3463. var audioCodecPreference = audioPreference == null ? void 0 : audioPreference.audioCodec;
  3464. var videoCodecPreference = videoPreference == null ? void 0 : videoPreference.videoCodec;
  3465. var preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
  3466. // Use first level set to determine stereo, and minimum resolution and framerate
  3467. var hasStereo = false;
  3468. var hasCurrentVideoRange = false;
  3469. var minHeight = Infinity;
  3470. var minFramerate = Infinity;
  3471. var minBitrate = Infinity;
  3472. var minIndex = Infinity;
  3473. var selectedScore = 0;
  3474. var videoRanges = [];
  3475. var _getVideoSelectionOpt = getVideoSelectionOptions(currentVideoRange, videoPreference),
  3476. preferHDR = _getVideoSelectionOpt.preferHDR,
  3477. allowedVideoRanges = _getVideoSelectionOpt.allowedVideoRanges;
  3478. var _loop = function _loop() {
  3479. var tier = codecTiers[codecSets[i]];
  3480. hasStereo || (hasStereo = tier.channels[2] > 0);
  3481. minHeight = Math.min(minHeight, tier.minHeight);
  3482. minFramerate = Math.min(minFramerate, tier.minFramerate);
  3483. minBitrate = Math.min(minBitrate, tier.minBitrate);
  3484. var matchingVideoRanges = allowedVideoRanges.filter(function (range) {
  3485. return tier.videoRanges[range] > 0;
  3486. });
  3487. if (matchingVideoRanges.length > 0) {
  3488. hasCurrentVideoRange = true;
  3489. }
  3490. };
  3491. for (var i = codecSets.length; i--;) {
  3492. _loop();
  3493. }
  3494. minHeight = isFiniteNumber(minHeight) ? minHeight : 0;
  3495. minFramerate = isFiniteNumber(minFramerate) ? minFramerate : 0;
  3496. var maxHeight = Math.max(1080, minHeight);
  3497. var maxFramerate = Math.max(30, minFramerate);
  3498. minBitrate = isFiniteNumber(minBitrate) ? minBitrate : currentBw;
  3499. currentBw = Math.max(minBitrate, currentBw);
  3500. // If there are no variants with matching preference, set currentVideoRange to undefined
  3501. if (!hasCurrentVideoRange) {
  3502. currentVideoRange = undefined;
  3503. }
  3504. var hasMultipleSets = codecSets.length > 1;
  3505. var codecSet = codecSets.reduce(function (selected, candidate) {
  3506. // Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present
  3507. var candidateTier = codecTiers[candidate];
  3508. if (candidate === selected) {
  3509. return selected;
  3510. }
  3511. videoRanges = hasCurrentVideoRange ? allowedVideoRanges.filter(function (range) {
  3512. return candidateTier.videoRanges[range] > 0;
  3513. }) : [];
  3514. if (hasMultipleSets) {
  3515. if (candidateTier.minBitrate > currentBw) {
  3516. logStartCodecCandidateIgnored(candidate, "min bitrate of " + candidateTier.minBitrate + " > current estimate of " + currentBw);
  3517. return selected;
  3518. }
  3519. if (!candidateTier.hasDefaultAudio) {
  3520. logStartCodecCandidateIgnored(candidate, "no renditions with default or auto-select sound found");
  3521. return selected;
  3522. }
  3523. if (audioCodecPreference && candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0) {
  3524. logStartCodecCandidateIgnored(candidate, "audio codec preference \"" + audioCodecPreference + "\" not found");
  3525. return selected;
  3526. }
  3527. if (channelsPreference && !preferStereo) {
  3528. if (!candidateTier.channels[channelsPreference]) {
  3529. logStartCodecCandidateIgnored(candidate, "no renditions with " + channelsPreference + " channel sound found (channels options: " + Object.keys(candidateTier.channels) + ")");
  3530. return selected;
  3531. }
  3532. } else if ((!audioCodecPreference || preferStereo) && hasStereo && candidateTier.channels['2'] === 0) {
  3533. logStartCodecCandidateIgnored(candidate, "no renditions with stereo sound found");
  3534. return selected;
  3535. }
  3536. if (candidateTier.minHeight > maxHeight) {
  3537. logStartCodecCandidateIgnored(candidate, "min resolution of " + candidateTier.minHeight + " > maximum of " + maxHeight);
  3538. return selected;
  3539. }
  3540. if (candidateTier.minFramerate > maxFramerate) {
  3541. logStartCodecCandidateIgnored(candidate, "min framerate of " + candidateTier.minFramerate + " > maximum of " + maxFramerate);
  3542. return selected;
  3543. }
  3544. if (!videoRanges.some(function (range) {
  3545. return candidateTier.videoRanges[range] > 0;
  3546. })) {
  3547. logStartCodecCandidateIgnored(candidate, "no variants with VIDEO-RANGE of " + stringify(videoRanges) + " found");
  3548. return selected;
  3549. }
  3550. if (videoCodecPreference && candidate.indexOf(videoCodecPreference.substring(0, 4)) % 5 !== 0) {
  3551. logStartCodecCandidateIgnored(candidate, "video codec preference \"" + videoCodecPreference + "\" not found");
  3552. return selected;
  3553. }
  3554. if (candidateTier.maxScore < selectedScore) {
  3555. logStartCodecCandidateIgnored(candidate, "max score of " + candidateTier.maxScore + " < selected max of " + selectedScore);
  3556. return selected;
  3557. }
  3558. }
  3559. // Remove candiates with less preferred codecs or more errors
  3560. if (selected && (codecsSetSelectionPreferenceValue(candidate) >= codecsSetSelectionPreferenceValue(selected) || candidateTier.fragmentError > codecTiers[selected].fragmentError)) {
  3561. return selected;
  3562. }
  3563. minIndex = candidateTier.minIndex;
  3564. selectedScore = candidateTier.maxScore;
  3565. return candidate;
  3566. }, undefined);
  3567. return {
  3568. codecSet: codecSet,
  3569. videoRanges: videoRanges,
  3570. preferHDR: preferHDR,
  3571. minFramerate: minFramerate,
  3572. minBitrate: minBitrate,
  3573. minIndex: minIndex
  3574. };
  3575. }
  3576. function logStartCodecCandidateIgnored(codeSet, reason) {
  3577. logger.log("[abr] start candidates with \"" + codeSet + "\" ignored because " + reason);
  3578. }
  3579. function getAudioTracksByGroup(allAudioTracks) {
  3580. return allAudioTracks.reduce(function (audioTracksByGroup, track) {
  3581. var trackGroup = audioTracksByGroup.groups[track.groupId];
  3582. if (!trackGroup) {
  3583. trackGroup = audioTracksByGroup.groups[track.groupId] = {
  3584. tracks: [],
  3585. channels: {
  3586. 2: 0
  3587. },
  3588. hasDefault: false,
  3589. hasAutoSelect: false
  3590. };
  3591. }
  3592. trackGroup.tracks.push(track);
  3593. var channelsKey = track.channels || '2';
  3594. trackGroup.channels[channelsKey] = (trackGroup.channels[channelsKey] || 0) + 1;
  3595. trackGroup.hasDefault = trackGroup.hasDefault || track.default;
  3596. trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
  3597. if (trackGroup.hasDefault) {
  3598. audioTracksByGroup.hasDefaultAudio = true;
  3599. }
  3600. if (trackGroup.hasAutoSelect) {
  3601. audioTracksByGroup.hasAutoSelectAudio = true;
  3602. }
  3603. return audioTracksByGroup;
  3604. }, {
  3605. hasDefaultAudio: false,
  3606. hasAutoSelectAudio: false,
  3607. groups: {}
  3608. });
  3609. }
  3610. function getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel) {
  3611. return levels.slice(minAutoLevel, maxAutoLevel + 1).reduce(function (tiers, level, index) {
  3612. if (!level.codecSet) {
  3613. return tiers;
  3614. }
  3615. var audioGroups = level.audioGroups;
  3616. var tier = tiers[level.codecSet];
  3617. if (!tier) {
  3618. tiers[level.codecSet] = tier = {
  3619. minBitrate: Infinity,
  3620. minHeight: Infinity,
  3621. minFramerate: Infinity,
  3622. minIndex: index,
  3623. maxScore: 0,
  3624. videoRanges: {
  3625. SDR: 0
  3626. },
  3627. channels: {
  3628. '2': 0
  3629. },
  3630. hasDefaultAudio: !audioGroups,
  3631. fragmentError: 0
  3632. };
  3633. }
  3634. tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
  3635. var lesserWidthOrHeight = Math.min(level.height, level.width);
  3636. tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
  3637. tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
  3638. tier.minIndex = Math.min(tier.minIndex, index);
  3639. tier.maxScore = Math.max(tier.maxScore, level.score);
  3640. tier.fragmentError += level.fragmentError;
  3641. tier.videoRanges[level.videoRange] = (tier.videoRanges[level.videoRange] || 0) + 1;
  3642. if (audioGroups) {
  3643. audioGroups.forEach(function (audioGroupId) {
  3644. if (!audioGroupId) {
  3645. return;
  3646. }
  3647. var audioGroup = audioTracksByGroup.groups[audioGroupId];
  3648. if (!audioGroup) {
  3649. return;
  3650. }
  3651. // Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants
  3652. tier.hasDefaultAudio = tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio ? audioGroup.hasDefault : audioGroup.hasAutoSelect || !audioTracksByGroup.hasDefaultAudio && !audioTracksByGroup.hasAutoSelectAudio;
  3653. Object.keys(audioGroup.channels).forEach(function (channels) {
  3654. tier.channels[channels] = (tier.channels[channels] || 0) + audioGroup.channels[channels];
  3655. });
  3656. });
  3657. }
  3658. return tiers;
  3659. }, {});
  3660. }
  3661. function getBasicSelectionOption(option) {
  3662. if (!option) {
  3663. return option;
  3664. }
  3665. var _ref = option,
  3666. lang = _ref.lang,
  3667. assocLang = _ref.assocLang,
  3668. characteristics = _ref.characteristics,
  3669. channels = _ref.channels,
  3670. audioCodec = _ref.audioCodec;
  3671. return {
  3672. lang: lang,
  3673. assocLang: assocLang,
  3674. characteristics: characteristics,
  3675. channels: channels,
  3676. audioCodec: audioCodec
  3677. };
  3678. }
  3679. function findMatchingOption(option, tracks, matchPredicate) {
  3680. if ('attrs' in option) {
  3681. var index = tracks.indexOf(option);
  3682. if (index !== -1) {
  3683. return index;
  3684. }
  3685. }
  3686. for (var i = 0; i < tracks.length; i++) {
  3687. var track = tracks[i];
  3688. if (matchesOption(option, track, matchPredicate)) {
  3689. return i;
  3690. }
  3691. }
  3692. return -1;
  3693. }
  3694. function matchesOption(option, track, matchPredicate) {
  3695. var groupId = option.groupId,
  3696. name = option.name,
  3697. lang = option.lang,
  3698. assocLang = option.assocLang,
  3699. isDefault = option.default;
  3700. var forced = option.forced;
  3701. return (groupId === undefined || track.groupId === groupId) && (name === undefined || track.name === name) && (lang === undefined || languagesMatch(lang, track.lang)) && (lang === undefined || track.assocLang === assocLang) && (isDefault === undefined || track.default === isDefault) && (forced === undefined || track.forced === forced) && (!('characteristics' in option) || characteristicsMatch(option.characteristics || '', track.characteristics)) && (matchPredicate === undefined || matchPredicate(option, track));
  3702. }
  3703. function languagesMatch(languageA, languageB) {
  3704. if (languageB === void 0) {
  3705. languageB = '--';
  3706. }
  3707. if (languageA.length === languageB.length) {
  3708. return languageA === languageB;
  3709. }
  3710. return languageA.startsWith(languageB) || languageB.startsWith(languageA);
  3711. }
  3712. function characteristicsMatch(characteristicsA, characteristicsB) {
  3713. if (characteristicsB === void 0) {
  3714. characteristicsB = '';
  3715. }
  3716. var arrA = characteristicsA.split(',');
  3717. var arrB = characteristicsB.split(',');
  3718. // Expects each item to be unique:
  3719. return arrA.length === arrB.length && !arrA.some(function (el) {
  3720. return arrB.indexOf(el) === -1;
  3721. });
  3722. }
  3723. function audioMatchPredicate(option, track) {
  3724. var audioCodec = option.audioCodec,
  3725. channels = option.channels;
  3726. return (audioCodec === undefined || (track.audioCodec || '').substring(0, 4) === audioCodec.substring(0, 4)) && (channels === undefined || channels === (track.channels || '2'));
  3727. }
  3728. function findClosestLevelWithAudioGroup(option, levels, allAudioTracks, searchIndex, matchPredicate) {
  3729. var currentLevel = levels[searchIndex];
  3730. // Are there variants with same URI as current level?
  3731. // If so, find a match that does not require any level URI change
  3732. var variants = levels.reduce(function (variantMap, level, index) {
  3733. var uri = level.uri;
  3734. var renditions = variantMap[uri] || (variantMap[uri] = []);
  3735. renditions.push(index);
  3736. return variantMap;
  3737. }, {});
  3738. var renditions = variants[currentLevel.uri];
  3739. if (renditions.length > 1) {
  3740. searchIndex = Math.max.apply(Math, renditions);
  3741. }
  3742. // Find best match
  3743. var currentVideoRange = currentLevel.videoRange;
  3744. var currentFrameRate = currentLevel.frameRate;
  3745. var currentVideoCodec = currentLevel.codecSet.substring(0, 4);
  3746. var matchingVideo = searchDownAndUpList(levels, searchIndex, function (level) {
  3747. if (level.videoRange !== currentVideoRange || level.frameRate !== currentFrameRate || level.codecSet.substring(0, 4) !== currentVideoCodec) {
  3748. return false;
  3749. }
  3750. var audioGroups = level.audioGroups;
  3751. var tracks = allAudioTracks.filter(function (track) {
  3752. return !audioGroups || audioGroups.indexOf(track.groupId) !== -1;
  3753. });
  3754. return findMatchingOption(option, tracks, matchPredicate) > -1;
  3755. });
  3756. if (matchingVideo > -1) {
  3757. return matchingVideo;
  3758. }
  3759. return searchDownAndUpList(levels, searchIndex, function (level) {
  3760. var audioGroups = level.audioGroups;
  3761. var tracks = allAudioTracks.filter(function (track) {
  3762. return !audioGroups || audioGroups.indexOf(track.groupId) !== -1;
  3763. });
  3764. return findMatchingOption(option, tracks, matchPredicate) > -1;
  3765. });
  3766. }
  3767. function searchDownAndUpList(arr, searchIndex, predicate) {
  3768. for (var i = searchIndex; i > -1; i--) {
  3769. if (predicate(arr[i])) {
  3770. return i;
  3771. }
  3772. }
  3773. for (var _i = searchIndex + 1; _i < arr.length; _i++) {
  3774. if (predicate(arr[_i])) {
  3775. return _i;
  3776. }
  3777. }
  3778. return -1;
  3779. }
  3780. function useAlternateAudio(audioTrackUrl, hls) {
  3781. var _hls$loadLevelObj;
  3782. return !!audioTrackUrl && audioTrackUrl !== ((_hls$loadLevelObj = hls.loadLevelObj) == null ? void 0 : _hls$loadLevelObj.uri);
  3783. }
  3784. var AbrController = /*#__PURE__*/function (_Logger) {
  3785. function AbrController(_hls) {
  3786. var _this;
  3787. _this = _Logger.call(this, 'abr', _hls.logger) || this;
  3788. _this.hls = void 0;
  3789. _this.lastLevelLoadSec = 0;
  3790. _this.lastLoadedFragLevel = -1;
  3791. _this.firstSelection = -1;
  3792. _this._nextAutoLevel = -1;
  3793. _this.nextAutoLevelKey = '';
  3794. _this.audioTracksByGroup = null;
  3795. _this.codecTiers = null;
  3796. _this.timer = -1;
  3797. _this.fragCurrent = null;
  3798. _this.partCurrent = null;
  3799. _this.bitrateTestDelay = 0;
  3800. _this.rebufferNotice = -1;
  3801. _this.supportedCache = {};
  3802. _this.bwEstimator = void 0;
  3803. /*
  3804. This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
  3805. quickly enough to prevent underbuffering
  3806. */
  3807. _this._abandonRulesCheck = function (levelLoaded) {
  3808. var _ref;
  3809. var _this2 = _this,
  3810. frag = _this2.fragCurrent,
  3811. part = _this2.partCurrent,
  3812. hls = _this2.hls;
  3813. var autoLevelEnabled = hls.autoLevelEnabled,
  3814. media = hls.media;
  3815. if (!frag || !media) {
  3816. return;
  3817. }
  3818. var now = performance.now();
  3819. var stats = part ? part.stats : frag.stats;
  3820. var duration = part ? part.duration : frag.duration;
  3821. var timeLoading = now - stats.loading.start;
  3822. var minAutoLevel = hls.minAutoLevel;
  3823. var loadingFragForLevel = frag.level;
  3824. var currentAutoLevel = _this._nextAutoLevel;
  3825. // If frag loading is aborted, complete, or from lowest level, stop timer and return
  3826. if (stats.aborted || stats.loaded && stats.loaded === stats.total || loadingFragForLevel <= minAutoLevel) {
  3827. _this.clearTimer();
  3828. // reset forced auto level value so that next level will be selected
  3829. _this._nextAutoLevel = -1;
  3830. return;
  3831. }
  3832. // This check only runs if we're in ABR mode
  3833. if (!autoLevelEnabled) {
  3834. return;
  3835. }
  3836. // Must be loading/loaded a new level or be in a playing state
  3837. var fragBlockingSwitch = currentAutoLevel > -1 && currentAutoLevel !== loadingFragForLevel;
  3838. var levelChange = !!levelLoaded || fragBlockingSwitch;
  3839. if (!levelChange && (media.paused || !media.playbackRate || !media.readyState)) {
  3840. return;
  3841. }
  3842. var bufferInfo = hls.mainForwardBufferInfo;
  3843. if (!levelChange && bufferInfo === null) {
  3844. return;
  3845. }
  3846. var ttfbEstimate = _this.bwEstimator.getEstimateTTFB();
  3847. var playbackRate = Math.abs(media.playbackRate);
  3848. // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed
  3849. if (timeLoading <= Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))) {
  3850. return;
  3851. }
  3852. // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
  3853. var bufferStarvationDelay = bufferInfo ? bufferInfo.len / playbackRate : 0;
  3854. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  3855. var loadedFirstByte = stats.loaded && ttfb > -1;
  3856. var bwEstimate = _this.getBwEstimate();
  3857. var levels = hls.levels;
  3858. var level = levels[loadingFragForLevel];
  3859. var expectedLen = Math.max(stats.loaded, Math.round(duration * (frag.bitrate || level.averageBitrate) / 8));
  3860. var timeStreaming = loadedFirstByte ? timeLoading - ttfb : timeLoading;
  3861. if (timeStreaming < 1 && loadedFirstByte) {
  3862. timeStreaming = Math.min(timeLoading, stats.loaded * 8 / bwEstimate);
  3863. }
  3864. var loadRate = loadedFirstByte ? stats.loaded * 1000 / timeStreaming : 0;
  3865. // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment
  3866. var ttfbSeconds = ttfbEstimate / 1000;
  3867. var fragLoadedDelay = loadRate ? (expectedLen - stats.loaded) / loadRate : expectedLen * 8 / bwEstimate + ttfbSeconds;
  3868. // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left
  3869. if (fragLoadedDelay <= bufferStarvationDelay) {
  3870. return;
  3871. }
  3872. var bwe = loadRate ? loadRate * 8 : bwEstimate;
  3873. var live = ((_ref = (levelLoaded == null ? void 0 : levelLoaded.details) || _this.hls.latestLevelDetails) == null ? void 0 : _ref.live) === true;
  3874. var abrBandWidthUpFactor = _this.hls.config.abrBandWidthUpFactor;
  3875. var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
  3876. var nextLoadLevel;
  3877. // Iterate through lower level and try to find the largest one that avoids rebuffering
  3878. for (nextLoadLevel = loadingFragForLevel - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  3879. // compute time to load next fragment at lower level
  3880. // 8 = bits per byte (bps/Bps)
  3881. var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
  3882. var requiresLevelLoad = !levels[nextLoadLevel].details || live;
  3883. fragLevelNextLoadedDelay = _this.getTimeToLoadFrag(ttfbSeconds, bwe, duration * levelNextBitrate, requiresLevelLoad);
  3884. if (fragLevelNextLoadedDelay < Math.min(bufferStarvationDelay, duration + ttfbSeconds)) {
  3885. break;
  3886. }
  3887. }
  3888. // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
  3889. // to load the current one
  3890. if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
  3891. return;
  3892. }
  3893. // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down
  3894. if (fragLevelNextLoadedDelay > duration * 10) {
  3895. return;
  3896. }
  3897. if (loadedFirstByte) {
  3898. // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time
  3899. _this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  3900. } else {
  3901. // If there has been no loading progress, sample TTFB
  3902. _this.bwEstimator.sampleTTFB(timeLoading);
  3903. }
  3904. var nextLoadLevelBitrate = levels[nextLoadLevel].maxBitrate;
  3905. if (_this.getBwEstimate() * abrBandWidthUpFactor > nextLoadLevelBitrate) {
  3906. _this.resetEstimator(nextLoadLevelBitrate);
  3907. }
  3908. var bestSwitchLevel = _this.findBestLevel(nextLoadLevelBitrate, minAutoLevel, nextLoadLevel, 0, bufferStarvationDelay, 1, 1);
  3909. if (bestSwitchLevel > -1) {
  3910. nextLoadLevel = bestSwitchLevel;
  3911. }
  3912. _this.warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + loadingFragForLevel + " is loading too slowly;\n Fragment duration: " + frag.duration.toFixed(3) + "\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for down switch fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n TTFB estimate: " + (ttfb | 0) + " ms\n Current BW estimate: " + (isFiniteNumber(bwEstimate) ? bwEstimate | 0 : 'Unknown') + " bps\n New BW estimate: " + (_this.getBwEstimate() | 0) + " bps\n Switching to level " + nextLoadLevel + " @ " + (nextLoadLevelBitrate | 0) + " bps");
  3913. hls.nextLoadLevel = hls.nextAutoLevel = nextLoadLevel;
  3914. _this.clearTimer();
  3915. var abortAndSwitch = function abortAndSwitch() {
  3916. // Are nextLoadLevel details available or is stream-controller still in "WAITING_LEVEL" state?
  3917. _this.clearTimer();
  3918. if (_this.fragCurrent === frag && _this.hls.loadLevel === nextLoadLevel && nextLoadLevel > 0) {
  3919. var _bufferStarvationDelay = _this.getStarvationDelay();
  3920. _this.warn("Aborting inflight request " + (nextLoadLevel > 0 ? 'and switching down' : '') + "\n Fragment duration: " + frag.duration.toFixed(3) + " s\n Time to underbuffer: " + _bufferStarvationDelay.toFixed(3) + " s");
  3921. frag.abortRequests();
  3922. _this.fragCurrent = _this.partCurrent = null;
  3923. if (nextLoadLevel > minAutoLevel) {
  3924. var lowestSwitchLevel = _this.findBestLevel(_this.hls.levels[minAutoLevel].bitrate, minAutoLevel, nextLoadLevel, 0, _bufferStarvationDelay, 1, 1);
  3925. if (lowestSwitchLevel === -1) {
  3926. lowestSwitchLevel = minAutoLevel;
  3927. }
  3928. _this.hls.nextLoadLevel = _this.hls.nextAutoLevel = lowestSwitchLevel;
  3929. _this.resetEstimator(_this.hls.levels[lowestSwitchLevel].bitrate);
  3930. }
  3931. }
  3932. };
  3933. if (fragBlockingSwitch || fragLoadedDelay > fragLevelNextLoadedDelay * 2) {
  3934. abortAndSwitch();
  3935. } else {
  3936. _this.timer = self.setInterval(abortAndSwitch, fragLevelNextLoadedDelay * 1000);
  3937. }
  3938. hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, {
  3939. frag: frag,
  3940. part: part,
  3941. stats: stats
  3942. });
  3943. };
  3944. _this.hls = _hls;
  3945. _this.bwEstimator = _this.initEstimator();
  3946. _this.registerListeners();
  3947. return _this;
  3948. }
  3949. _inheritsLoose(AbrController, _Logger);
  3950. var _proto = AbrController.prototype;
  3951. _proto.resetEstimator = function resetEstimator(abrEwmaDefaultEstimate) {
  3952. if (abrEwmaDefaultEstimate) {
  3953. this.log("setting initial bwe to " + abrEwmaDefaultEstimate);
  3954. this.hls.config.abrEwmaDefaultEstimate = abrEwmaDefaultEstimate;
  3955. }
  3956. this.firstSelection = -1;
  3957. this.bwEstimator = this.initEstimator();
  3958. };
  3959. _proto.initEstimator = function initEstimator() {
  3960. var config = this.hls.config;
  3961. return new EwmaBandWidthEstimator(config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
  3962. };
  3963. _proto.registerListeners = function registerListeners() {
  3964. var hls = this.hls;
  3965. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3966. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  3967. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  3968. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3969. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3970. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3971. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3972. hls.on(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3973. hls.on(Events.ERROR, this.onError, this);
  3974. };
  3975. _proto.unregisterListeners = function unregisterListeners() {
  3976. var hls = this.hls;
  3977. if (!hls) {
  3978. return;
  3979. }
  3980. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  3981. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  3982. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  3983. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  3984. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  3985. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  3986. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  3987. hls.off(Events.MAX_AUTO_LEVEL_UPDATED, this.onMaxAutoLevelUpdated, this);
  3988. hls.off(Events.ERROR, this.onError, this);
  3989. };
  3990. _proto.destroy = function destroy() {
  3991. this.unregisterListeners();
  3992. this.clearTimer();
  3993. // @ts-ignore
  3994. this.hls = this._abandonRulesCheck = this.supportedCache = null;
  3995. this.fragCurrent = this.partCurrent = null;
  3996. };
  3997. _proto.onManifestLoading = function onManifestLoading(event, data) {
  3998. this.lastLoadedFragLevel = -1;
  3999. this.firstSelection = -1;
  4000. this.lastLevelLoadSec = 0;
  4001. this.supportedCache = {};
  4002. this.fragCurrent = this.partCurrent = null;
  4003. this.onLevelsUpdated();
  4004. this.clearTimer();
  4005. };
  4006. _proto.onLevelsUpdated = function onLevelsUpdated() {
  4007. if (this.lastLoadedFragLevel > -1 && this.fragCurrent) {
  4008. this.lastLoadedFragLevel = this.fragCurrent.level;
  4009. }
  4010. this._nextAutoLevel = -1;
  4011. this.onMaxAutoLevelUpdated();
  4012. this.codecTiers = null;
  4013. this.audioTracksByGroup = null;
  4014. };
  4015. _proto.onMaxAutoLevelUpdated = function onMaxAutoLevelUpdated() {
  4016. this.firstSelection = -1;
  4017. this.nextAutoLevelKey = '';
  4018. };
  4019. _proto.onFragLoading = function onFragLoading(event, data) {
  4020. var frag = data.frag;
  4021. if (this.ignoreFragment(frag)) {
  4022. return;
  4023. }
  4024. if (!frag.bitrateTest) {
  4025. var _data$part;
  4026. this.fragCurrent = frag;
  4027. this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
  4028. }
  4029. this.clearTimer();
  4030. this.timer = self.setInterval(this._abandonRulesCheck, 100);
  4031. };
  4032. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  4033. this.clearTimer();
  4034. };
  4035. _proto.onError = function onError(event, data) {
  4036. if (data.fatal) {
  4037. return;
  4038. }
  4039. switch (data.details) {
  4040. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  4041. case ErrorDetails.BUFFER_APPEND_ERROR:
  4042. // Reset last loaded level so that a new selection can be made after calling recoverMediaError
  4043. this.lastLoadedFragLevel = -1;
  4044. this.firstSelection = -1;
  4045. break;
  4046. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4047. {
  4048. var frag = data.frag;
  4049. var fragCurrent = this.fragCurrent,
  4050. part = this.partCurrent;
  4051. if (frag && fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level) {
  4052. var now = performance.now();
  4053. var stats = part ? part.stats : frag.stats;
  4054. var timeLoading = now - stats.loading.start;
  4055. var ttfb = stats.loading.first ? stats.loading.first - stats.loading.start : -1;
  4056. var loadedFirstByte = stats.loaded && ttfb > -1;
  4057. if (loadedFirstByte) {
  4058. var ttfbEstimate = this.bwEstimator.getEstimateTTFB();
  4059. this.bwEstimator.sample(timeLoading - Math.min(ttfbEstimate, ttfb), stats.loaded);
  4060. } else {
  4061. this.bwEstimator.sampleTTFB(timeLoading);
  4062. }
  4063. }
  4064. break;
  4065. }
  4066. }
  4067. };
  4068. _proto.getTimeToLoadFrag = function getTimeToLoadFrag(timeToFirstByteSec, bandwidth, fragSizeBits, isSwitch) {
  4069. var fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;
  4070. var playlistLoadSec = isSwitch ? timeToFirstByteSec + this.lastLevelLoadSec : 0;
  4071. return fragLoadSec + playlistLoadSec;
  4072. };
  4073. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  4074. var config = this.hls.config;
  4075. var loading = data.stats.loading;
  4076. var timeLoadingMs = loading.end - loading.first;
  4077. if (isFiniteNumber(timeLoadingMs)) {
  4078. this.lastLevelLoadSec = timeLoadingMs / 1000;
  4079. }
  4080. if (data.details.live) {
  4081. this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
  4082. } else {
  4083. this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
  4084. }
  4085. if (this.timer > -1) {
  4086. this._abandonRulesCheck(data.levelInfo);
  4087. }
  4088. };
  4089. _proto.onFragLoaded = function onFragLoaded(event, _ref2) {
  4090. var frag = _ref2.frag,
  4091. part = _ref2.part;
  4092. var stats = part ? part.stats : frag.stats;
  4093. if (frag.type === PlaylistLevelType.MAIN) {
  4094. this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);
  4095. }
  4096. if (this.ignoreFragment(frag)) {
  4097. return;
  4098. }
  4099. // stop monitoring bw once frag loaded
  4100. this.clearTimer();
  4101. // reset forced auto level value so that next level will be selected
  4102. if (frag.level === this._nextAutoLevel) {
  4103. this._nextAutoLevel = -1;
  4104. }
  4105. this.firstSelection = -1;
  4106. // compute level average bitrate
  4107. if (this.hls.config.abrMaxWithRealBitrate) {
  4108. var duration = part ? part.duration : frag.duration;
  4109. var level = this.hls.levels[frag.level];
  4110. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
  4111. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
  4112. level.loaded = {
  4113. bytes: loadedBytes,
  4114. duration: loadedDuration
  4115. };
  4116. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  4117. }
  4118. if (frag.bitrateTest) {
  4119. var fragBufferedData = {
  4120. stats: stats,
  4121. frag: frag,
  4122. part: part,
  4123. id: frag.type
  4124. };
  4125. this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);
  4126. frag.bitrateTest = false;
  4127. } else {
  4128. // store level id after successful fragment load for playback
  4129. this.lastLoadedFragLevel = frag.level;
  4130. }
  4131. };
  4132. _proto.onFragBuffered = function onFragBuffered(event, data) {
  4133. var frag = data.frag,
  4134. part = data.part;
  4135. var stats = part != null && part.stats.loaded ? part.stats : frag.stats;
  4136. if (stats.aborted) {
  4137. return;
  4138. }
  4139. if (this.ignoreFragment(frag)) {
  4140. return;
  4141. }
  4142. // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
  4143. // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
  4144. // is used. If we used buffering in that case, our BW estimate sample will be very large.
  4145. var processingMs = stats.parsing.end - stats.loading.start - Math.min(stats.loading.first - stats.loading.start, this.bwEstimator.getEstimateTTFB());
  4146. this.bwEstimator.sample(processingMs, stats.loaded);
  4147. stats.bwEstimate = this.getBwEstimate();
  4148. if (frag.bitrateTest) {
  4149. this.bitrateTestDelay = processingMs / 1000;
  4150. } else {
  4151. this.bitrateTestDelay = 0;
  4152. }
  4153. };
  4154. _proto.ignoreFragment = function ignoreFragment(frag) {
  4155. // Only count non-alt-audio frags which were actually buffered in our BW calculations
  4156. return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';
  4157. };
  4158. _proto.clearTimer = function clearTimer() {
  4159. if (this.timer > -1) {
  4160. self.clearInterval(this.timer);
  4161. this.timer = -1;
  4162. }
  4163. };
  4164. _proto.getAutoLevelKey = function getAutoLevelKey() {
  4165. return this.getBwEstimate() + "_" + this.getStarvationDelay().toFixed(2);
  4166. };
  4167. _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
  4168. var fragCurrent = this.fragCurrent,
  4169. partCurrent = this.partCurrent,
  4170. hls = this.hls;
  4171. if (hls.levels.length <= 1) {
  4172. return hls.loadLevel;
  4173. }
  4174. var maxAutoLevel = hls.maxAutoLevel,
  4175. config = hls.config,
  4176. minAutoLevel = hls.minAutoLevel;
  4177. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  4178. var avgbw = this.getBwEstimate();
  4179. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  4180. var bufferStarvationDelay = this.getStarvationDelay();
  4181. var bwFactor = config.abrBandWidthFactor;
  4182. var bwUpFactor = config.abrBandWidthUpFactor;
  4183. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  4184. if (bufferStarvationDelay) {
  4185. var _bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, 0, bwFactor, bwUpFactor);
  4186. if (_bestLevel >= 0) {
  4187. this.rebufferNotice = -1;
  4188. return _bestLevel;
  4189. }
  4190. }
  4191. // not possible to get rid of rebuffering... try to find level that will guarantee less than maxStarvationDelay of rebuffering
  4192. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
  4193. if (!bufferStarvationDelay) {
  4194. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  4195. var bitrateTestDelay = this.bitrateTestDelay;
  4196. if (bitrateTestDelay) {
  4197. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  4198. // max video loading delay used in automatic start level selection :
  4199. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  4200. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  4201. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  4202. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  4203. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  4204. this.info("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  4205. // don't use conservative factor on bitrate test
  4206. bwFactor = bwUpFactor = 1;
  4207. }
  4208. }
  4209. var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor);
  4210. if (this.rebufferNotice !== bestLevel) {
  4211. this.rebufferNotice = bestLevel;
  4212. this.info((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", optimal quality level " + bestLevel);
  4213. }
  4214. if (bestLevel > -1) {
  4215. return bestLevel;
  4216. }
  4217. // If no matching level found, see if min auto level would be a better option
  4218. var minLevel = hls.levels[minAutoLevel];
  4219. var autoLevel = hls.loadLevelObj;
  4220. if (autoLevel && (minLevel == null ? void 0 : minLevel.bitrate) < autoLevel.bitrate) {
  4221. return minAutoLevel;
  4222. }
  4223. // or if bitrate is not lower, continue to use loadLevel
  4224. return hls.loadLevel;
  4225. };
  4226. _proto.getStarvationDelay = function getStarvationDelay() {
  4227. var hls = this.hls;
  4228. var media = hls.media;
  4229. if (!media) {
  4230. return Infinity;
  4231. }
  4232. // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
  4233. // if we're playing back at the normal rate.
  4234. var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
  4235. var bufferInfo = hls.mainForwardBufferInfo;
  4236. return (bufferInfo ? bufferInfo.len : 0) / playbackRate;
  4237. };
  4238. _proto.getBwEstimate = function getBwEstimate() {
  4239. return this.bwEstimator.canEstimate() ? this.bwEstimator.getEstimate() : this.hls.config.abrEwmaDefaultEstimate;
  4240. };
  4241. _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, maxStarvationDelay, bwFactor, bwUpFactor) {
  4242. var _this$hls$latestLevel,
  4243. _this3 = this;
  4244. var maxFetchDuration = bufferStarvationDelay + maxStarvationDelay;
  4245. var lastLoadedFragLevel = this.lastLoadedFragLevel;
  4246. var selectionBaseLevel = lastLoadedFragLevel === -1 ? this.hls.firstLevel : lastLoadedFragLevel;
  4247. var fragCurrent = this.fragCurrent,
  4248. partCurrent = this.partCurrent;
  4249. var _this$hls = this.hls,
  4250. levels = _this$hls.levels,
  4251. allAudioTracks = _this$hls.allAudioTracks,
  4252. loadLevel = _this$hls.loadLevel,
  4253. config = _this$hls.config;
  4254. if (levels.length === 1) {
  4255. return 0;
  4256. }
  4257. var level = levels[selectionBaseLevel];
  4258. var live = !!((_this$hls$latestLevel = this.hls.latestLevelDetails) != null && _this$hls$latestLevel.live);
  4259. var firstSelection = loadLevel === -1 || lastLoadedFragLevel === -1;
  4260. var currentCodecSet;
  4261. var currentVideoRange = 'SDR';
  4262. var currentFrameRate = (level == null ? void 0 : level.frameRate) || 0;
  4263. var audioPreference = config.audioPreference,
  4264. videoPreference = config.videoPreference;
  4265. var audioTracksByGroup = this.audioTracksByGroup || (this.audioTracksByGroup = getAudioTracksByGroup(allAudioTracks));
  4266. var minStartIndex = -1;
  4267. if (firstSelection) {
  4268. if (this.firstSelection !== -1) {
  4269. return this.firstSelection;
  4270. }
  4271. var codecTiers = this.codecTiers || (this.codecTiers = getCodecTiers(levels, audioTracksByGroup, minAutoLevel, maxAutoLevel));
  4272. var startTier = getStartCodecTier(codecTiers, currentVideoRange, currentBw, audioPreference, videoPreference);
  4273. var codecSet = startTier.codecSet,
  4274. videoRanges = startTier.videoRanges,
  4275. minFramerate = startTier.minFramerate,
  4276. minBitrate = startTier.minBitrate,
  4277. minIndex = startTier.minIndex,
  4278. preferHDR = startTier.preferHDR;
  4279. minStartIndex = minIndex;
  4280. currentCodecSet = codecSet;
  4281. currentVideoRange = preferHDR ? videoRanges[videoRanges.length - 1] : videoRanges[0];
  4282. currentFrameRate = minFramerate;
  4283. currentBw = Math.max(currentBw, minBitrate);
  4284. this.log("picked start tier " + stringify(startTier));
  4285. } else {
  4286. currentCodecSet = level == null ? void 0 : level.codecSet;
  4287. currentVideoRange = level == null ? void 0 : level.videoRange;
  4288. }
  4289. var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
  4290. var ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;
  4291. var levelsSkipped = [];
  4292. var _loop = function _loop() {
  4293. var _levelInfo$supportedR, _levelInfo$supportedR2;
  4294. var levelInfo = levels[i];
  4295. var upSwitch = i > selectionBaseLevel;
  4296. if (!levelInfo) {
  4297. return 0; // continue
  4298. }
  4299. if (config.useMediaCapabilities && !levelInfo.supportedResult && !levelInfo.supportedPromise) {
  4300. var mediaCapabilities = navigator.mediaCapabilities;
  4301. if (typeof (mediaCapabilities == null ? void 0 : mediaCapabilities.decodingInfo) === 'function' && requiresMediaCapabilitiesDecodingInfo(levelInfo, audioTracksByGroup, currentVideoRange, currentFrameRate, currentBw, audioPreference)) {
  4302. levelInfo.supportedPromise = getMediaDecodingInfoPromise(levelInfo, audioTracksByGroup, mediaCapabilities, _this3.supportedCache);
  4303. levelInfo.supportedPromise.then(function (decodingInfo) {
  4304. if (!_this3.hls) {
  4305. return;
  4306. }
  4307. levelInfo.supportedResult = decodingInfo;
  4308. var levels = _this3.hls.levels;
  4309. var index = levels.indexOf(levelInfo);
  4310. if (decodingInfo.error) {
  4311. _this3.warn("MediaCapabilities decodingInfo error: \"" + decodingInfo.error + "\" for level " + index + " " + stringify(decodingInfo));
  4312. } else if (!decodingInfo.supported) {
  4313. _this3.warn("Unsupported MediaCapabilities decodingInfo result for level " + index + " " + stringify(decodingInfo));
  4314. if (index > -1 && levels.length > 1) {
  4315. _this3.log("Removing unsupported level " + index);
  4316. _this3.hls.removeLevel(index);
  4317. if (_this3.hls.loadLevel === -1) {
  4318. _this3.hls.nextLoadLevel = 0;
  4319. }
  4320. }
  4321. } else if (decodingInfo.decodingInfoResults.some(function (info) {
  4322. return info.smooth === false || info.powerEfficient === false;
  4323. })) {
  4324. _this3.log("MediaCapabilities decodingInfo for level " + index + " not smooth or powerEfficient: " + stringify(decodingInfo));
  4325. }
  4326. });
  4327. } else {
  4328. levelInfo.supportedResult = SUPPORTED_INFO_DEFAULT;
  4329. }
  4330. }
  4331. // skip candidates which change codec-family or video-range,
  4332. // and which decrease or increase frame-rate for up and down-switch respectfully
  4333. if (currentCodecSet && levelInfo.codecSet !== currentCodecSet || currentVideoRange && levelInfo.videoRange !== currentVideoRange || upSwitch && currentFrameRate > levelInfo.frameRate || !upSwitch && currentFrameRate > 0 && currentFrameRate < levelInfo.frameRate || (_levelInfo$supportedR = levelInfo.supportedResult) != null && (_levelInfo$supportedR2 = _levelInfo$supportedR.decodingInfoResults) != null && _levelInfo$supportedR2.some(function (info) {
  4334. return info.smooth === false;
  4335. })) {
  4336. if (!firstSelection || i !== minStartIndex) {
  4337. levelsSkipped.push(i);
  4338. return 0; // continue
  4339. }
  4340. }
  4341. var levelDetails = levelInfo.details;
  4342. var avgDuration = (partCurrent ? levelDetails == null ? void 0 : levelDetails.partTarget : levelDetails == null ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
  4343. var adjustedbw;
  4344. // follow algorithm captured from stagefright :
  4345. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  4346. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  4347. // consider only 80% of the available bandwidth, but if we are switching up,
  4348. // be even more conservative (70%) to avoid overestimating and immediately
  4349. // switching back.
  4350. if (!upSwitch) {
  4351. adjustedbw = bwFactor * currentBw;
  4352. } else {
  4353. adjustedbw = bwUpFactor * currentBw;
  4354. }
  4355. // Use average bitrate when starvation delay (buffer length) is gt or eq two segment durations and rebuffering is not expected (maxStarvationDelay > 0)
  4356. var bitrate = currentFragDuration && bufferStarvationDelay >= currentFragDuration * 2 && maxStarvationDelay === 0 ? levelInfo.averageBitrate : levelInfo.maxBitrate;
  4357. var fetchDuration = _this3.getTimeToLoadFrag(ttfbEstimateSec, adjustedbw, bitrate * avgDuration, levelDetails === undefined);
  4358. var canSwitchWithinTolerance =
  4359. // if adjusted bw is greater than level bitrate AND
  4360. adjustedbw >= bitrate && (
  4361. // no level change, or new level has no error history
  4362. i === lastLoadedFragLevel || levelInfo.loadError === 0 && levelInfo.fragmentError === 0) && (
  4363. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  4364. // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
  4365. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
  4366. fetchDuration <= ttfbEstimateSec || !isFiniteNumber(fetchDuration) || live && !_this3.bitrateTestDelay || fetchDuration < maxFetchDuration);
  4367. if (canSwitchWithinTolerance) {
  4368. var forcedAutoLevel = _this3.forcedAutoLevel;
  4369. if (i !== loadLevel && (forcedAutoLevel === -1 || forcedAutoLevel !== loadLevel)) {
  4370. if (levelsSkipped.length) {
  4371. _this3.trace("Skipped level(s) " + levelsSkipped.join(',') + " of " + maxAutoLevel + " max with CODECS and VIDEO-RANGE:\"" + levels[levelsSkipped[0]].codecs + "\" " + levels[levelsSkipped[0]].videoRange + "; not compatible with \"" + currentCodecSet + "\" " + currentVideoRange);
  4372. }
  4373. _this3.info("switch candidate:" + selectionBaseLevel + "->" + i + " adjustedbw(" + Math.round(adjustedbw) + ")-bitrate=" + Math.round(adjustedbw - bitrate) + " ttfb:" + ttfbEstimateSec.toFixed(1) + " avgDuration:" + avgDuration.toFixed(1) + " maxFetchDuration:" + maxFetchDuration.toFixed(1) + " fetchDuration:" + fetchDuration.toFixed(1) + " firstSelection:" + firstSelection + " codecSet:" + levelInfo.codecSet + " videoRange:" + levelInfo.videoRange + " hls.loadLevel:" + loadLevel);
  4374. }
  4375. if (firstSelection) {
  4376. _this3.firstSelection = i;
  4377. }
  4378. // as we are looping from highest to lowest, this will return the best achievable quality level
  4379. return {
  4380. v: i
  4381. };
  4382. }
  4383. },
  4384. _ret;
  4385. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  4386. _ret = _loop();
  4387. if (_ret === 0) continue;
  4388. if (_ret) return _ret.v;
  4389. }
  4390. // not enough time budget even with quality level 0 ... rebuffering might happen
  4391. return -1;
  4392. };
  4393. _proto.deriveNextAutoLevel = function deriveNextAutoLevel(nextLevel) {
  4394. var _this$hls2 = this.hls,
  4395. maxAutoLevel = _this$hls2.maxAutoLevel,
  4396. minAutoLevel = _this$hls2.minAutoLevel;
  4397. return Math.min(Math.max(nextLevel, minAutoLevel), maxAutoLevel);
  4398. };
  4399. return _createClass(AbrController, [{
  4400. key: "firstAutoLevel",
  4401. get: function get() {
  4402. var _this$hls3 = this.hls,
  4403. maxAutoLevel = _this$hls3.maxAutoLevel,
  4404. minAutoLevel = _this$hls3.minAutoLevel;
  4405. var bwEstimate = this.getBwEstimate();
  4406. var maxStartDelay = this.hls.config.maxStarvationDelay;
  4407. var abrAutoLevel = this.findBestLevel(bwEstimate, minAutoLevel, maxAutoLevel, 0, maxStartDelay, 1, 1);
  4408. if (abrAutoLevel > -1) {
  4409. return abrAutoLevel;
  4410. }
  4411. var firstLevel = this.hls.firstLevel;
  4412. var clamped = Math.min(Math.max(firstLevel, minAutoLevel), maxAutoLevel);
  4413. this.warn("Could not find best starting auto level. Defaulting to first in playlist " + firstLevel + " clamped to " + clamped);
  4414. return clamped;
  4415. }
  4416. }, {
  4417. key: "forcedAutoLevel",
  4418. get: function get() {
  4419. if (this.nextAutoLevelKey) {
  4420. return -1;
  4421. }
  4422. return this._nextAutoLevel;
  4423. }
  4424. // return next auto level
  4425. }, {
  4426. key: "nextAutoLevel",
  4427. get: function get() {
  4428. var forcedAutoLevel = this.forcedAutoLevel;
  4429. var bwEstimator = this.bwEstimator;
  4430. var useEstimate = bwEstimator.canEstimate();
  4431. var loadedFirstFrag = this.lastLoadedFragLevel > -1;
  4432. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  4433. if (forcedAutoLevel !== -1 && (!useEstimate || !loadedFirstFrag || this.nextAutoLevelKey === this.getAutoLevelKey())) {
  4434. return forcedAutoLevel;
  4435. }
  4436. // compute next level using ABR logic
  4437. var nextABRAutoLevel = useEstimate && loadedFirstFrag ? this.getNextABRAutoLevel() : this.firstAutoLevel;
  4438. // use forced auto level while it hasn't errored more than ABR selection
  4439. if (forcedAutoLevel !== -1) {
  4440. var levels = this.hls.levels;
  4441. if (levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) && levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError) {
  4442. return forcedAutoLevel;
  4443. }
  4444. }
  4445. // save result until state has changed
  4446. this._nextAutoLevel = nextABRAutoLevel;
  4447. this.nextAutoLevelKey = this.getAutoLevelKey();
  4448. return nextABRAutoLevel;
  4449. },
  4450. set: function set(nextLevel) {
  4451. var value = this.deriveNextAutoLevel(nextLevel);
  4452. if (this._nextAutoLevel !== value) {
  4453. this.nextAutoLevelKey = '';
  4454. this._nextAutoLevel = value;
  4455. }
  4456. }
  4457. }]);
  4458. }(Logger);
  4459. var BinarySearch = {
  4460. /**
  4461. * Searches for an item in an array which matches a certain condition.
  4462. * This requires the condition to only match one item in the array,
  4463. * and for the array to be ordered.
  4464. *
  4465. * @param list The array to search.
  4466. * @param comparisonFn
  4467. * Called and provided a candidate item as the first argument.
  4468. * Should return:
  4469. * > -1 if the item should be located at a lower index than the provided item.
  4470. * > 1 if the item should be located at a higher index than the provided item.
  4471. * > 0 if the item is the item you're looking for.
  4472. *
  4473. * @returns the object if found, otherwise returns null
  4474. */
  4475. search: function search(list, comparisonFn) {
  4476. var minIndex = 0;
  4477. var maxIndex = list.length - 1;
  4478. var currentIndex = null;
  4479. var currentElement = null;
  4480. while (minIndex <= maxIndex) {
  4481. currentIndex = (minIndex + maxIndex) / 2 | 0;
  4482. currentElement = list[currentIndex];
  4483. var comparisonResult = comparisonFn(currentElement);
  4484. if (comparisonResult > 0) {
  4485. minIndex = currentIndex + 1;
  4486. } else if (comparisonResult < 0) {
  4487. maxIndex = currentIndex - 1;
  4488. } else {
  4489. return currentElement;
  4490. }
  4491. }
  4492. return null;
  4493. }
  4494. };
  4495. /**
  4496. * Returns first fragment whose endPdt value exceeds the given PDT, or null.
  4497. * @param fragments - The array of candidate fragments
  4498. * @param PDTValue - The PDT value which must be exceeded
  4499. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4500. */
  4501. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  4502. if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !isFiniteNumber(PDTValue)) {
  4503. return null;
  4504. }
  4505. // if less than start
  4506. var startPDT = fragments[0].programDateTime;
  4507. if (PDTValue < (startPDT || 0)) {
  4508. return null;
  4509. }
  4510. var endPDT = fragments[fragments.length - 1].endProgramDateTime;
  4511. if (PDTValue >= (endPDT || 0)) {
  4512. return null;
  4513. }
  4514. for (var seg = 0; seg < fragments.length; ++seg) {
  4515. var frag = fragments[seg];
  4516. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  4517. return frag;
  4518. }
  4519. }
  4520. return null;
  4521. }
  4522. /**
  4523. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  4524. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  4525. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  4526. * @param fragPrevious - The last frag successfully appended
  4527. * @param fragments - The array of candidate fragments
  4528. * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within
  4529. * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4530. * @returns a matching fragment or null
  4531. */
  4532. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance, nextFragLookupTolerance) {
  4533. if (bufferEnd === void 0) {
  4534. bufferEnd = 0;
  4535. }
  4536. if (maxFragLookUpTolerance === void 0) {
  4537. maxFragLookUpTolerance = 0;
  4538. }
  4539. if (nextFragLookupTolerance === void 0) {
  4540. nextFragLookupTolerance = 0.005;
  4541. }
  4542. var fragNext = null;
  4543. if (fragPrevious) {
  4544. fragNext = fragments[1 + fragPrevious.sn - fragments[0].sn] || null;
  4545. // check for buffer-end rounding error
  4546. var bufferEdgeError = fragPrevious.endDTS - bufferEnd;
  4547. if (bufferEdgeError > 0 && bufferEdgeError < 0.0000015) {
  4548. bufferEnd += 0.0000015;
  4549. }
  4550. if (fragNext && fragPrevious.level !== fragNext.level && fragNext.end <= fragPrevious.end) {
  4551. fragNext = fragments[2 + fragPrevious.sn - fragments[0].sn] || null;
  4552. }
  4553. } else if (bufferEnd === 0 && fragments[0].start === 0) {
  4554. fragNext = fragments[0];
  4555. }
  4556. // Prefer the next fragment if it's within tolerance
  4557. if (fragNext && ((!fragPrevious || fragPrevious.level === fragNext.level) && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0 || fragmentWithinFastStartSwitch(fragNext, fragPrevious, Math.min(nextFragLookupTolerance, maxFragLookUpTolerance)))) {
  4558. return fragNext;
  4559. }
  4560. // We might be seeking past the tolerance so find the best match
  4561. var foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  4562. if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {
  4563. return foundFragment;
  4564. }
  4565. // If no match was found return the next fragment after fragPrevious, or null
  4566. return fragNext;
  4567. }
  4568. function fragmentWithinFastStartSwitch(fragNext, fragPrevious, nextFragLookupTolerance) {
  4569. if (fragPrevious && fragPrevious.start === 0 && fragPrevious.level < fragNext.level && (fragPrevious.endPTS || 0) > 0) {
  4570. var firstDuration = fragPrevious.tagList.reduce(function (duration, tag) {
  4571. if (tag[0] === 'INF') {
  4572. duration += parseFloat(tag[1]);
  4573. }
  4574. return duration;
  4575. }, nextFragLookupTolerance);
  4576. return fragNext.start <= firstDuration;
  4577. }
  4578. return false;
  4579. }
  4580. /**
  4581. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  4582. * @param candidate - The fragment to test
  4583. * @param bufferEnd - The end of the current buffered range the playhead is currently within
  4584. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4585. * @returns 0 if it matches, 1 if too low, -1 if too high
  4586. */
  4587. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  4588. if (bufferEnd === void 0) {
  4589. bufferEnd = 0;
  4590. }
  4591. if (maxFragLookUpTolerance === void 0) {
  4592. maxFragLookUpTolerance = 0;
  4593. }
  4594. // eagerly accept an accurate match (no tolerance)
  4595. if (candidate.start <= bufferEnd && candidate.start + candidate.duration > bufferEnd) {
  4596. return 0;
  4597. }
  4598. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  4599. // this is to cope with situations like
  4600. // bufferEnd = 9.991
  4601. // frag[Ø] : [0,10]
  4602. // frag[1] : [10,20]
  4603. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  4604. // frag start frag start+duration
  4605. // |-----------------------------|
  4606. // <---> <--->
  4607. // ...--------><-----------------------------><---------....
  4608. // previous frag matching fragment next frag
  4609. // return -1 return 0 return 1
  4610. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  4611. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  4612. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  4613. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  4614. return 1;
  4615. } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  4616. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  4617. return -1;
  4618. }
  4619. return 0;
  4620. }
  4621. /**
  4622. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  4623. * This function tests the candidate's program date time values, as represented in Unix time
  4624. * @param candidate - The fragment to test
  4625. * @param pdtBufferEnd - The Unix time representing the end of the current buffered range
  4626. * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous
  4627. * @returns true if contiguous, false otherwise
  4628. */
  4629. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  4630. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  4631. // endProgramDateTime can be null, default to zero
  4632. var endProgramDateTime = candidate.endProgramDateTime || 0;
  4633. return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  4634. }
  4635. function findNearestWithCC(details, cc, pos) {
  4636. if (details) {
  4637. if (details.startCC <= cc && details.endCC >= cc) {
  4638. var fragments = details.fragments;
  4639. var fragmentHint = details.fragmentHint;
  4640. if (fragmentHint) {
  4641. fragments = fragments.concat(fragmentHint);
  4642. }
  4643. var closest;
  4644. BinarySearch.search(fragments, function (candidate) {
  4645. if (candidate.cc < cc) {
  4646. return 1;
  4647. }
  4648. if (candidate.cc > cc) {
  4649. return -1;
  4650. }
  4651. closest = candidate;
  4652. if (candidate.end <= pos) {
  4653. return 1;
  4654. }
  4655. if (candidate.start > pos) {
  4656. return -1;
  4657. }
  4658. return 0;
  4659. });
  4660. return closest || null;
  4661. }
  4662. }
  4663. return null;
  4664. }
  4665. function isTimeoutError(error) {
  4666. switch (error.details) {
  4667. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4668. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4669. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4670. case ErrorDetails.MANIFEST_LOAD_TIMEOUT:
  4671. return true;
  4672. }
  4673. return false;
  4674. }
  4675. function getRetryConfig(loadPolicy, error) {
  4676. var isTimeout = isTimeoutError(error);
  4677. return loadPolicy.default[(isTimeout ? 'timeout' : 'error') + "Retry"];
  4678. }
  4679. function getRetryDelay(retryConfig, retryCount) {
  4680. // exponential backoff capped to max retry delay
  4681. var backoffFactor = retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);
  4682. return Math.min(backoffFactor * retryConfig.retryDelayMs, retryConfig.maxRetryDelayMs);
  4683. }
  4684. function getLoaderConfigWithoutReties(loderConfig) {
  4685. return _objectSpread2(_objectSpread2({}, loderConfig), {
  4686. errorRetry: null,
  4687. timeoutRetry: null
  4688. });
  4689. }
  4690. function shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse) {
  4691. if (!retryConfig) {
  4692. return false;
  4693. }
  4694. var httpStatus = loaderResponse == null ? void 0 : loaderResponse.code;
  4695. var retry = retryCount < retryConfig.maxNumRetry && (retryForHttpStatus(httpStatus) || !!isTimeout);
  4696. return retryConfig.shouldRetry ? retryConfig.shouldRetry(retryConfig, retryCount, isTimeout, loaderResponse, retry) : retry;
  4697. }
  4698. function retryForHttpStatus(httpStatus) {
  4699. // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)
  4700. return httpStatus === 0 && navigator.onLine === false || !!httpStatus && (httpStatus < 400 || httpStatus > 499);
  4701. }
  4702. var NetworkErrorAction = {
  4703. DoNothing: 0,
  4704. SendAlternateToPenaltyBox: 2,
  4705. RemoveAlternatePermanently: 3,
  4706. RetryRequest: 5
  4707. };
  4708. var ErrorActionFlags = {
  4709. None: 0,
  4710. MoveAllAlternatesMatchingHost: 1,
  4711. MoveAllAlternatesMatchingHDCP: 2};
  4712. var ErrorController = /*#__PURE__*/function (_Logger) {
  4713. function ErrorController(hls) {
  4714. var _this;
  4715. _this = _Logger.call(this, 'error-controller', hls.logger) || this;
  4716. _this.hls = void 0;
  4717. _this.playlistError = 0;
  4718. _this.penalizedRenditions = {};
  4719. _this.hls = hls;
  4720. _this.registerListeners();
  4721. return _this;
  4722. }
  4723. _inheritsLoose(ErrorController, _Logger);
  4724. var _proto = ErrorController.prototype;
  4725. _proto.registerListeners = function registerListeners() {
  4726. var hls = this.hls;
  4727. hls.on(Events.ERROR, this.onError, this);
  4728. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4729. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4730. };
  4731. _proto.unregisterListeners = function unregisterListeners() {
  4732. var hls = this.hls;
  4733. if (!hls) {
  4734. return;
  4735. }
  4736. hls.off(Events.ERROR, this.onError, this);
  4737. hls.off(Events.ERROR, this.onErrorOut, this);
  4738. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  4739. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  4740. };
  4741. _proto.destroy = function destroy() {
  4742. this.unregisterListeners();
  4743. // @ts-ignore
  4744. this.hls = null;
  4745. this.penalizedRenditions = {};
  4746. };
  4747. _proto.startLoad = function startLoad(startPosition) {};
  4748. _proto.stopLoad = function stopLoad() {
  4749. this.playlistError = 0;
  4750. };
  4751. _proto.getVariantLevelIndex = function getVariantLevelIndex(frag) {
  4752. return (frag == null ? void 0 : frag.type) === PlaylistLevelType.MAIN ? frag.level : this.hls.loadLevel;
  4753. };
  4754. _proto.onManifestLoading = function onManifestLoading() {
  4755. this.playlistError = 0;
  4756. this.penalizedRenditions = {};
  4757. };
  4758. _proto.onLevelUpdated = function onLevelUpdated() {
  4759. this.playlistError = 0;
  4760. };
  4761. _proto.onError = function onError(event, data) {
  4762. var _data$frag;
  4763. if (data.fatal) {
  4764. return;
  4765. }
  4766. var hls = this.hls;
  4767. var context = data.context;
  4768. switch (data.details) {
  4769. case ErrorDetails.FRAG_LOAD_ERROR:
  4770. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  4771. case ErrorDetails.KEY_LOAD_ERROR:
  4772. case ErrorDetails.KEY_LOAD_TIMEOUT:
  4773. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4774. return;
  4775. case ErrorDetails.FRAG_PARSING_ERROR:
  4776. // ignore empty segment errors marked as gap
  4777. if ((_data$frag = data.frag) != null && _data$frag.gap) {
  4778. data.errorAction = createDoNothingErrorAction();
  4779. return;
  4780. }
  4781. // falls through
  4782. case ErrorDetails.FRAG_GAP:
  4783. case ErrorDetails.FRAG_DECRYPT_ERROR:
  4784. {
  4785. // Switch level if possible, otherwise allow retry count to reach max error retries
  4786. data.errorAction = this.getFragRetryOrSwitchAction(data);
  4787. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4788. return;
  4789. }
  4790. case ErrorDetails.LEVEL_EMPTY_ERROR:
  4791. case ErrorDetails.LEVEL_PARSING_ERROR:
  4792. {
  4793. var _data$context, _data$context$levelDe;
  4794. // Only retry when empty and live
  4795. var levelIndex = data.parent === PlaylistLevelType.MAIN ? data.level : hls.loadLevel;
  4796. if (data.details === ErrorDetails.LEVEL_EMPTY_ERROR && !!((_data$context = data.context) != null && (_data$context$levelDe = _data$context.levelDetails) != null && _data$context$levelDe.live)) {
  4797. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, levelIndex);
  4798. } else {
  4799. // Escalate to fatal if not retrying or switching
  4800. data.levelRetry = false;
  4801. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4802. }
  4803. }
  4804. return;
  4805. case ErrorDetails.LEVEL_LOAD_ERROR:
  4806. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  4807. if (typeof (context == null ? void 0 : context.level) === 'number') {
  4808. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, context.level);
  4809. }
  4810. return;
  4811. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  4812. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  4813. case ErrorDetails.SUBTITLE_LOAD_ERROR:
  4814. case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:
  4815. if (context) {
  4816. var level = hls.loadLevelObj;
  4817. if (level && (context.type === PlaylistContextType.AUDIO_TRACK && level.hasAudioGroup(context.groupId) || context.type === PlaylistContextType.SUBTITLE_TRACK && level.hasSubtitleGroup(context.groupId))) {
  4818. // Perform Pathway switch or Redundant failover if possible for fastest recovery
  4819. // otherwise allow playlist retry count to reach max error retries
  4820. data.errorAction = this.getPlaylistRetryOrSwitchAction(data, hls.loadLevel);
  4821. data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;
  4822. data.errorAction.flags = ErrorActionFlags.MoveAllAlternatesMatchingHost;
  4823. return;
  4824. }
  4825. }
  4826. return;
  4827. case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:
  4828. {
  4829. var _level = hls.loadLevelObj;
  4830. var restrictedHdcpLevel = _level == null ? void 0 : _level.attrs['HDCP-LEVEL'];
  4831. if (restrictedHdcpLevel) {
  4832. data.errorAction = {
  4833. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  4834. flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,
  4835. hdcpLevel: restrictedHdcpLevel
  4836. };
  4837. } else {
  4838. this.keySystemError(data);
  4839. }
  4840. }
  4841. return;
  4842. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  4843. case ErrorDetails.REMUX_ALLOC_ERROR:
  4844. case ErrorDetails.BUFFER_APPEND_ERROR:
  4845. // Buffer-controller can set errorAction when append errors can be ignored or resolved locally
  4846. if (!data.errorAction) {
  4847. var _data$level;
  4848. data.errorAction = this.getLevelSwitchAction(data, (_data$level = data.level) != null ? _data$level : hls.loadLevel);
  4849. }
  4850. return;
  4851. case ErrorDetails.INTERNAL_EXCEPTION:
  4852. case ErrorDetails.BUFFER_APPENDING_ERROR:
  4853. case ErrorDetails.BUFFER_FULL_ERROR:
  4854. case ErrorDetails.LEVEL_SWITCH_ERROR:
  4855. case ErrorDetails.BUFFER_STALLED_ERROR:
  4856. case ErrorDetails.BUFFER_SEEK_OVER_HOLE:
  4857. case ErrorDetails.BUFFER_NUDGE_ON_STALL:
  4858. data.errorAction = createDoNothingErrorAction();
  4859. return;
  4860. }
  4861. if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {
  4862. this.keySystemError(data);
  4863. }
  4864. };
  4865. _proto.keySystemError = function keySystemError(data) {
  4866. var levelIndex = this.getVariantLevelIndex(data.frag);
  4867. // Do not retry level. Escalate to fatal if switching levels fails.
  4868. data.levelRetry = false;
  4869. data.errorAction = this.getLevelSwitchAction(data, levelIndex);
  4870. };
  4871. _proto.getPlaylistRetryOrSwitchAction = function getPlaylistRetryOrSwitchAction(data, levelIndex) {
  4872. var hls = this.hls;
  4873. var retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);
  4874. var retryCount = this.playlistError++;
  4875. var retry = shouldRetry(retryConfig, retryCount, isTimeoutError(data), data.response);
  4876. if (retry) {
  4877. return {
  4878. action: NetworkErrorAction.RetryRequest,
  4879. flags: ErrorActionFlags.None,
  4880. retryConfig: retryConfig,
  4881. retryCount: retryCount
  4882. };
  4883. }
  4884. var errorAction = this.getLevelSwitchAction(data, levelIndex);
  4885. if (retryConfig) {
  4886. errorAction.retryConfig = retryConfig;
  4887. errorAction.retryCount = retryCount;
  4888. }
  4889. return errorAction;
  4890. };
  4891. _proto.getFragRetryOrSwitchAction = function getFragRetryOrSwitchAction(data) {
  4892. var hls = this.hls;
  4893. // Share fragment error count accross media options (main, audio, subs)
  4894. // This allows for level based rendition switching when media option assets fail
  4895. var variantLevelIndex = this.getVariantLevelIndex(data.frag);
  4896. var level = hls.levels[variantLevelIndex];
  4897. var _hls$config = hls.config,
  4898. fragLoadPolicy = _hls$config.fragLoadPolicy,
  4899. keyLoadPolicy = _hls$config.keyLoadPolicy;
  4900. var retryConfig = getRetryConfig(data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy, data);
  4901. var fragmentErrors = hls.levels.reduce(function (acc, level) {
  4902. return acc + level.fragmentError;
  4903. }, 0);
  4904. // Switch levels when out of retried or level index out of bounds
  4905. if (level) {
  4906. if (data.details !== ErrorDetails.FRAG_GAP) {
  4907. level.fragmentError++;
  4908. }
  4909. var retry = shouldRetry(retryConfig, fragmentErrors, isTimeoutError(data), data.response);
  4910. if (retry) {
  4911. return {
  4912. action: NetworkErrorAction.RetryRequest,
  4913. flags: ErrorActionFlags.None,
  4914. retryConfig: retryConfig,
  4915. retryCount: fragmentErrors
  4916. };
  4917. }
  4918. }
  4919. // Reach max retry count, or Missing level reference
  4920. // Switch to valid index
  4921. var errorAction = this.getLevelSwitchAction(data, variantLevelIndex);
  4922. // Add retry details to allow skipping of FRAG_PARSING_ERROR
  4923. if (retryConfig) {
  4924. errorAction.retryConfig = retryConfig;
  4925. errorAction.retryCount = fragmentErrors;
  4926. }
  4927. return errorAction;
  4928. };
  4929. _proto.getLevelSwitchAction = function getLevelSwitchAction(data, levelIndex) {
  4930. var hls = this.hls;
  4931. if (levelIndex === null || levelIndex === undefined) {
  4932. levelIndex = hls.loadLevel;
  4933. }
  4934. var level = this.hls.levels[levelIndex];
  4935. if (level) {
  4936. var _data$frag2, _data$context2;
  4937. var errorDetails = data.details;
  4938. level.loadError++;
  4939. if (errorDetails === ErrorDetails.BUFFER_APPEND_ERROR) {
  4940. level.fragmentError++;
  4941. }
  4942. // Search for next level to retry
  4943. var nextLevel = -1;
  4944. var levels = hls.levels,
  4945. loadLevel = hls.loadLevel,
  4946. minAutoLevel = hls.minAutoLevel,
  4947. maxAutoLevel = hls.maxAutoLevel;
  4948. if (!hls.autoLevelEnabled && !hls.config.preserveManualLevelOnError) {
  4949. hls.loadLevel = -1;
  4950. }
  4951. var fragErrorType = (_data$frag2 = data.frag) == null ? void 0 : _data$frag2.type;
  4952. // Find alternate audio codec if available on audio codec error
  4953. var isAudioCodecError = fragErrorType === PlaylistLevelType.AUDIO && errorDetails === ErrorDetails.FRAG_PARSING_ERROR || data.sourceBufferName === 'audio' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4954. var findAudioCodecAlternate = isAudioCodecError && levels.some(function (_ref) {
  4955. var audioCodec = _ref.audioCodec;
  4956. return level.audioCodec !== audioCodec;
  4957. });
  4958. // Find alternate video codec if available on video codec error
  4959. var isVideoCodecError = data.sourceBufferName === 'video' && (errorDetails === ErrorDetails.BUFFER_ADD_CODEC_ERROR || errorDetails === ErrorDetails.BUFFER_APPEND_ERROR);
  4960. var findVideoCodecAlternate = isVideoCodecError && levels.some(function (_ref2) {
  4961. var codecSet = _ref2.codecSet,
  4962. audioCodec = _ref2.audioCodec;
  4963. return level.codecSet !== codecSet && level.audioCodec === audioCodec;
  4964. });
  4965. var _ref3 = (_data$context2 = data.context) != null ? _data$context2 : {},
  4966. playlistErrorType = _ref3.type,
  4967. playlistErrorGroupId = _ref3.groupId;
  4968. var _loop = function _loop() {
  4969. var candidate = (i + loadLevel) % levels.length;
  4970. if (candidate !== loadLevel && candidate >= minAutoLevel && candidate <= maxAutoLevel && levels[candidate].loadError === 0) {
  4971. var _level$audioGroups, _level$subtitleGroups;
  4972. var levelCandidate = levels[candidate];
  4973. // Skip level switch if GAP tag is found in next level at same position
  4974. if (errorDetails === ErrorDetails.FRAG_GAP && fragErrorType === PlaylistLevelType.MAIN && data.frag) {
  4975. var levelDetails = levels[candidate].details;
  4976. if (levelDetails) {
  4977. var fragCandidate = findFragmentByPTS(data.frag, levelDetails.fragments, data.frag.start);
  4978. if (fragCandidate != null && fragCandidate.gap) {
  4979. return 0; // continue
  4980. }
  4981. }
  4982. } else if (playlistErrorType === PlaylistContextType.AUDIO_TRACK && levelCandidate.hasAudioGroup(playlistErrorGroupId) || playlistErrorType === PlaylistContextType.SUBTITLE_TRACK && levelCandidate.hasSubtitleGroup(playlistErrorGroupId)) {
  4983. // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over
  4984. return 0; // continue
  4985. } else if (fragErrorType === PlaylistLevelType.AUDIO && (_level$audioGroups = level.audioGroups) != null && _level$audioGroups.some(function (groupId) {
  4986. return levelCandidate.hasAudioGroup(groupId);
  4987. }) || fragErrorType === PlaylistLevelType.SUBTITLE && (_level$subtitleGroups = level.subtitleGroups) != null && _level$subtitleGroups.some(function (groupId) {
  4988. return levelCandidate.hasSubtitleGroup(groupId);
  4989. }) || findAudioCodecAlternate && level.audioCodec === levelCandidate.audioCodec || !findAudioCodecAlternate && level.audioCodec !== levelCandidate.audioCodec || findVideoCodecAlternate && level.codecSet === levelCandidate.codecSet) {
  4990. // For video/audio/subs frag errors find another group ID or fallthrough to redundant fail-over
  4991. return 0; // continue
  4992. }
  4993. nextLevel = candidate;
  4994. return 1; // break
  4995. }
  4996. },
  4997. _ret;
  4998. for (var i = levels.length; i--;) {
  4999. _ret = _loop();
  5000. if (_ret === 0) continue;
  5001. if (_ret === 1) break;
  5002. }
  5003. if (nextLevel > -1 && hls.loadLevel !== nextLevel) {
  5004. data.levelRetry = true;
  5005. this.playlistError = 0;
  5006. return {
  5007. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5008. flags: ErrorActionFlags.None,
  5009. nextAutoLevel: nextLevel
  5010. };
  5011. }
  5012. }
  5013. // No levels to switch / Manual level selection / Level not found
  5014. // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level
  5015. return {
  5016. action: NetworkErrorAction.SendAlternateToPenaltyBox,
  5017. flags: ErrorActionFlags.MoveAllAlternatesMatchingHost
  5018. };
  5019. };
  5020. _proto.onErrorOut = function onErrorOut(event, data) {
  5021. var _data$errorAction;
  5022. switch ((_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.action) {
  5023. case NetworkErrorAction.DoNothing:
  5024. break;
  5025. case NetworkErrorAction.SendAlternateToPenaltyBox:
  5026. this.sendAlternateToPenaltyBox(data);
  5027. if (!data.errorAction.resolved && data.details !== ErrorDetails.FRAG_GAP) {
  5028. data.fatal = true;
  5029. } else if (/MediaSource readyState: ended/.test(data.error.message)) {
  5030. this.warn("MediaSource ended after \"" + data.sourceBufferName + "\" sourceBuffer append error. Attempting to recover from media error.");
  5031. this.hls.recoverMediaError();
  5032. }
  5033. break;
  5034. }
  5035. if (data.fatal) {
  5036. this.hls.stopLoad();
  5037. return;
  5038. }
  5039. };
  5040. _proto.sendAlternateToPenaltyBox = function sendAlternateToPenaltyBox(data) {
  5041. var hls = this.hls;
  5042. var errorAction = data.errorAction;
  5043. if (!errorAction) {
  5044. return;
  5045. }
  5046. var flags = errorAction.flags,
  5047. hdcpLevel = errorAction.hdcpLevel,
  5048. nextAutoLevel = errorAction.nextAutoLevel;
  5049. switch (flags) {
  5050. case ErrorActionFlags.None:
  5051. this.switchLevel(data, nextAutoLevel);
  5052. break;
  5053. case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:
  5054. if (hdcpLevel) {
  5055. hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];
  5056. errorAction.resolved = true;
  5057. }
  5058. this.warn("Restricting playback to HDCP-LEVEL of \"" + hls.maxHdcpLevel + "\" or lower");
  5059. break;
  5060. }
  5061. // If not resolved by previous actions try to switch to next level
  5062. if (!errorAction.resolved) {
  5063. this.switchLevel(data, nextAutoLevel);
  5064. }
  5065. };
  5066. _proto.switchLevel = function switchLevel(data, levelIndex) {
  5067. if (levelIndex !== undefined && data.errorAction) {
  5068. this.warn("switching to level " + levelIndex + " after " + data.details);
  5069. this.hls.nextAutoLevel = levelIndex;
  5070. data.errorAction.resolved = true;
  5071. // Stream controller is responsible for this but won't switch on false start
  5072. this.hls.nextLoadLevel = this.hls.nextAutoLevel;
  5073. if (data.details === ErrorDetails.BUFFER_ADD_CODEC_ERROR && data.mimeType && data.sourceBufferName !== 'audiovideo') {
  5074. var codec = getCodecsForMimeType(data.mimeType);
  5075. var levels = this.hls.levels;
  5076. for (var i = levels.length; i--;) {
  5077. if (levels[i][data.sourceBufferName + "Codec"] === codec) {
  5078. this.hls.removeLevel(i);
  5079. }
  5080. }
  5081. }
  5082. }
  5083. };
  5084. return ErrorController;
  5085. }(Logger);
  5086. function createDoNothingErrorAction(resolved) {
  5087. var errorAction = {
  5088. action: NetworkErrorAction.DoNothing,
  5089. flags: ErrorActionFlags.None
  5090. };
  5091. if (resolved) {
  5092. errorAction.resolved = true;
  5093. }
  5094. return errorAction;
  5095. }
  5096. var FragmentState = {
  5097. NOT_LOADED: "NOT_LOADED",
  5098. APPENDING: "APPENDING",
  5099. PARTIAL: "PARTIAL",
  5100. OK: "OK"
  5101. };
  5102. var FragmentTracker = /*#__PURE__*/function () {
  5103. function FragmentTracker(hls) {
  5104. this.activePartLists = Object.create(null);
  5105. this.endListFragments = Object.create(null);
  5106. this.fragments = Object.create(null);
  5107. this.timeRanges = Object.create(null);
  5108. this.bufferPadding = 0.2;
  5109. this.hls = void 0;
  5110. this.hasGaps = false;
  5111. this.hls = hls;
  5112. this._registerListeners();
  5113. }
  5114. var _proto = FragmentTracker.prototype;
  5115. _proto._registerListeners = function _registerListeners() {
  5116. var hls = this.hls;
  5117. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5118. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  5119. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  5120. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  5121. };
  5122. _proto._unregisterListeners = function _unregisterListeners() {
  5123. var hls = this.hls;
  5124. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  5125. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  5126. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  5127. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  5128. };
  5129. _proto.destroy = function destroy() {
  5130. this._unregisterListeners();
  5131. // @ts-ignore
  5132. this.fragments =
  5133. // @ts-ignore
  5134. this.activePartLists =
  5135. // @ts-ignore
  5136. this.endListFragments = this.timeRanges = null;
  5137. }
  5138. /**
  5139. * Return a Fragment or Part with an appended range that matches the position and levelType
  5140. * Otherwise, return null
  5141. */;
  5142. _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
  5143. var activeParts = this.activePartLists[levelType];
  5144. if (activeParts) {
  5145. for (var i = activeParts.length; i--;) {
  5146. var activePart = activeParts[i];
  5147. if (!activePart) {
  5148. break;
  5149. }
  5150. var appendedPTS = activePart.end;
  5151. if (activePart.start <= position && appendedPTS !== null && position <= appendedPTS) {
  5152. return activePart;
  5153. }
  5154. }
  5155. }
  5156. return this.getBufferedFrag(position, levelType);
  5157. }
  5158. /**
  5159. * Return a buffered Fragment that matches the position and levelType.
  5160. * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
  5161. * If not found any Fragment, return null
  5162. */;
  5163. _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
  5164. return this.getFragAtPos(position, levelType, true);
  5165. };
  5166. _proto.getFragAtPos = function getFragAtPos(position, levelType, buffered) {
  5167. var fragments = this.fragments;
  5168. var keys = Object.keys(fragments);
  5169. for (var i = keys.length; i--;) {
  5170. var fragmentEntity = fragments[keys[i]];
  5171. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === levelType && (!buffered || fragmentEntity.buffered)) {
  5172. var frag = fragmentEntity.body;
  5173. if (frag.start <= position && position <= frag.end) {
  5174. return frag;
  5175. }
  5176. }
  5177. }
  5178. return null;
  5179. }
  5180. /**
  5181. * Partial fragments effected by coded frame eviction will be removed
  5182. * The browser will unload parts of the buffer to free up memory for new buffer data
  5183. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  5184. */;
  5185. _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType, appendedPart, removeAppending) {
  5186. var _this = this;
  5187. if (this.timeRanges) {
  5188. this.timeRanges[elementaryStream] = timeRange;
  5189. }
  5190. // Check if any flagged fragments have been unloaded
  5191. // excluding anything newer than appendedPartSn
  5192. var appendedPartSn = (appendedPart == null ? void 0 : appendedPart.fragment.sn) || -1;
  5193. Object.keys(this.fragments).forEach(function (key) {
  5194. var fragmentEntity = _this.fragments[key];
  5195. if (!fragmentEntity) {
  5196. return;
  5197. }
  5198. if (appendedPartSn >= fragmentEntity.body.sn) {
  5199. return;
  5200. }
  5201. if (!fragmentEntity.buffered && (!fragmentEntity.loaded || removeAppending)) {
  5202. if (fragmentEntity.body.type === playlistType) {
  5203. _this.removeFragment(fragmentEntity.body);
  5204. }
  5205. return;
  5206. }
  5207. var esData = fragmentEntity.range[elementaryStream];
  5208. if (!esData) {
  5209. return;
  5210. }
  5211. if (esData.time.length === 0) {
  5212. _this.removeFragment(fragmentEntity.body);
  5213. return;
  5214. }
  5215. esData.time.some(function (time) {
  5216. var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
  5217. if (isNotBuffered) {
  5218. // Unregister partial fragment as it needs to load again to be reused
  5219. _this.removeFragment(fragmentEntity.body);
  5220. }
  5221. return isNotBuffered;
  5222. });
  5223. });
  5224. }
  5225. /**
  5226. * Checks if the fragment passed in is loaded in the buffer properly
  5227. * Partially loaded fragments will be registered as a partial fragment
  5228. */;
  5229. _proto.detectPartialFragments = function detectPartialFragments(data) {
  5230. var _this2 = this;
  5231. var timeRanges = this.timeRanges;
  5232. if (!timeRanges || data.frag.sn === 'initSegment') {
  5233. return;
  5234. }
  5235. var frag = data.frag;
  5236. var fragKey = getFragmentKey(frag);
  5237. var fragmentEntity = this.fragments[fragKey];
  5238. if (!fragmentEntity || fragmentEntity.buffered && frag.gap) {
  5239. return;
  5240. }
  5241. var isFragHint = !frag.relurl;
  5242. Object.keys(timeRanges).forEach(function (elementaryStream) {
  5243. var streamInfo = frag.elementaryStreams[elementaryStream];
  5244. if (!streamInfo) {
  5245. return;
  5246. }
  5247. var timeRange = timeRanges[elementaryStream];
  5248. var partial = isFragHint || streamInfo.partial === true;
  5249. fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, data.part, partial, timeRange);
  5250. });
  5251. fragmentEntity.loaded = null;
  5252. if (Object.keys(fragmentEntity.range).length) {
  5253. fragmentEntity.buffered = true;
  5254. var endList = fragmentEntity.body.endList = frag.endList || fragmentEntity.body.endList;
  5255. if (endList) {
  5256. this.endListFragments[fragmentEntity.body.type] = fragmentEntity;
  5257. }
  5258. if (!isPartial(fragmentEntity)) {
  5259. // Remove older fragment parts from lookup after frag is tracked as buffered
  5260. this.removeParts(frag.sn - 1, frag.type);
  5261. }
  5262. } else {
  5263. // remove fragment if nothing was appended
  5264. this.removeFragment(fragmentEntity.body);
  5265. }
  5266. };
  5267. _proto.removeParts = function removeParts(snToKeep, levelType) {
  5268. var activeParts = this.activePartLists[levelType];
  5269. if (!activeParts) {
  5270. return;
  5271. }
  5272. this.activePartLists[levelType] = filterParts(activeParts, function (part) {
  5273. return part.fragment.sn >= snToKeep;
  5274. });
  5275. };
  5276. _proto.fragBuffered = function fragBuffered(frag, force) {
  5277. var fragKey = getFragmentKey(frag);
  5278. var fragmentEntity = this.fragments[fragKey];
  5279. if (!fragmentEntity && force) {
  5280. fragmentEntity = this.fragments[fragKey] = {
  5281. body: frag,
  5282. appendedPTS: null,
  5283. loaded: null,
  5284. buffered: false,
  5285. range: Object.create(null)
  5286. };
  5287. if (frag.gap) {
  5288. this.hasGaps = true;
  5289. }
  5290. }
  5291. if (fragmentEntity) {
  5292. fragmentEntity.loaded = null;
  5293. fragmentEntity.buffered = true;
  5294. }
  5295. };
  5296. _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
  5297. var buffered = {
  5298. time: [],
  5299. partial: partial
  5300. };
  5301. var startPTS = fragment.start;
  5302. var endPTS = fragment.end;
  5303. var minEndPTS = fragment.minEndPTS || endPTS;
  5304. var maxStartPTS = fragment.maxStartPTS || startPTS;
  5305. for (var i = 0; i < timeRange.length; i++) {
  5306. var startTime = timeRange.start(i) - this.bufferPadding;
  5307. var endTime = timeRange.end(i) + this.bufferPadding;
  5308. if (maxStartPTS >= startTime && minEndPTS <= endTime) {
  5309. // Fragment is entirely contained in buffer
  5310. // No need to check the other timeRange times since it's completely playable
  5311. buffered.time.push({
  5312. startPTS: Math.max(startPTS, timeRange.start(i)),
  5313. endPTS: Math.min(endPTS, timeRange.end(i))
  5314. });
  5315. break;
  5316. } else if (startPTS < endTime && endPTS > startTime) {
  5317. var start = Math.max(startPTS, timeRange.start(i));
  5318. var end = Math.min(endPTS, timeRange.end(i));
  5319. if (end > start) {
  5320. buffered.partial = true;
  5321. // Check for intersection with buffer
  5322. // Get playable sections of the fragment
  5323. buffered.time.push({
  5324. startPTS: start,
  5325. endPTS: end
  5326. });
  5327. }
  5328. } else if (endPTS <= startTime) {
  5329. // No need to check the rest of the timeRange as it is in order
  5330. break;
  5331. }
  5332. }
  5333. return buffered;
  5334. }
  5335. /**
  5336. * Gets the partial fragment for a certain time
  5337. */;
  5338. _proto.getPartialFragment = function getPartialFragment(time) {
  5339. var bestFragment = null;
  5340. var timePadding;
  5341. var startTime;
  5342. var endTime;
  5343. var bestOverlap = 0;
  5344. var bufferPadding = this.bufferPadding,
  5345. fragments = this.fragments;
  5346. Object.keys(fragments).forEach(function (key) {
  5347. var fragmentEntity = fragments[key];
  5348. if (!fragmentEntity) {
  5349. return;
  5350. }
  5351. if (isPartial(fragmentEntity)) {
  5352. startTime = fragmentEntity.body.start - bufferPadding;
  5353. endTime = fragmentEntity.body.end + bufferPadding;
  5354. if (time >= startTime && time <= endTime) {
  5355. // Use the fragment that has the most padding from start and end time
  5356. timePadding = Math.min(time - startTime, endTime - time);
  5357. if (bestOverlap <= timePadding) {
  5358. bestFragment = fragmentEntity.body;
  5359. bestOverlap = timePadding;
  5360. }
  5361. }
  5362. }
  5363. });
  5364. return bestFragment;
  5365. };
  5366. _proto.isEndListAppended = function isEndListAppended(type) {
  5367. var lastFragmentEntity = this.endListFragments[type];
  5368. return lastFragmentEntity !== undefined && (lastFragmentEntity.buffered || isPartial(lastFragmentEntity));
  5369. };
  5370. _proto.getState = function getState(fragment) {
  5371. var fragKey = getFragmentKey(fragment);
  5372. var fragmentEntity = this.fragments[fragKey];
  5373. if (fragmentEntity) {
  5374. if (!fragmentEntity.buffered) {
  5375. return FragmentState.APPENDING;
  5376. } else if (isPartial(fragmentEntity)) {
  5377. return FragmentState.PARTIAL;
  5378. } else {
  5379. return FragmentState.OK;
  5380. }
  5381. }
  5382. return FragmentState.NOT_LOADED;
  5383. };
  5384. _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
  5385. var startTime;
  5386. var endTime;
  5387. for (var i = 0; i < timeRange.length; i++) {
  5388. startTime = timeRange.start(i) - this.bufferPadding;
  5389. endTime = timeRange.end(i) + this.bufferPadding;
  5390. if (startPTS >= startTime && endPTS <= endTime) {
  5391. return true;
  5392. }
  5393. if (endPTS <= startTime) {
  5394. // No need to check the rest of the timeRange as it is in order
  5395. return false;
  5396. }
  5397. }
  5398. return false;
  5399. };
  5400. _proto.onManifestLoading = function onManifestLoading() {
  5401. this.removeAllFragments();
  5402. };
  5403. _proto.onFragLoaded = function onFragLoaded(event, data) {
  5404. // don't track initsegment (for which sn is not a number)
  5405. // don't track frags used for bitrateTest, they're irrelevant.
  5406. if (data.frag.sn === 'initSegment' || data.frag.bitrateTest) {
  5407. return;
  5408. }
  5409. var frag = data.frag;
  5410. // Fragment entity `loaded` FragLoadedData is null when loading parts
  5411. var loaded = data.part ? null : data;
  5412. var fragKey = getFragmentKey(frag);
  5413. this.fragments[fragKey] = {
  5414. body: frag,
  5415. appendedPTS: null,
  5416. loaded: loaded,
  5417. buffered: false,
  5418. range: Object.create(null)
  5419. };
  5420. };
  5421. _proto.onBufferAppended = function onBufferAppended(event, data) {
  5422. var frag = data.frag,
  5423. part = data.part,
  5424. timeRanges = data.timeRanges,
  5425. type = data.type;
  5426. if (frag.sn === 'initSegment') {
  5427. return;
  5428. }
  5429. var playlistType = frag.type;
  5430. if (part) {
  5431. var activeParts = this.activePartLists[playlistType];
  5432. if (!activeParts) {
  5433. this.activePartLists[playlistType] = activeParts = [];
  5434. }
  5435. activeParts.push(part);
  5436. }
  5437. // Store the latest timeRanges loaded in the buffer
  5438. this.timeRanges = timeRanges;
  5439. var timeRange = timeRanges[type];
  5440. this.detectEvictedFragments(type, timeRange, playlistType, part);
  5441. };
  5442. _proto.onFragBuffered = function onFragBuffered(event, data) {
  5443. this.detectPartialFragments(data);
  5444. };
  5445. _proto.hasFragment = function hasFragment(fragment) {
  5446. var fragKey = getFragmentKey(fragment);
  5447. return !!this.fragments[fragKey];
  5448. };
  5449. _proto.hasFragments = function hasFragments(type) {
  5450. var fragments = this.fragments;
  5451. var keys = Object.keys(fragments);
  5452. if (!type) {
  5453. return keys.length > 0;
  5454. }
  5455. for (var i = keys.length; i--;) {
  5456. var fragmentEntity = fragments[keys[i]];
  5457. if ((fragmentEntity == null ? void 0 : fragmentEntity.body.type) === type) {
  5458. return true;
  5459. }
  5460. }
  5461. return false;
  5462. };
  5463. _proto.hasParts = function hasParts(type) {
  5464. var _this$activePartLists;
  5465. return !!((_this$activePartLists = this.activePartLists[type]) != null && _this$activePartLists.length);
  5466. };
  5467. _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType, withGapOnly, unbufferedOnly) {
  5468. var _this3 = this;
  5469. if (withGapOnly && !this.hasGaps) {
  5470. return;
  5471. }
  5472. Object.keys(this.fragments).forEach(function (key) {
  5473. var fragmentEntity = _this3.fragments[key];
  5474. if (!fragmentEntity) {
  5475. return;
  5476. }
  5477. var frag = fragmentEntity.body;
  5478. if (frag.type !== playlistType || withGapOnly && !frag.gap) {
  5479. return;
  5480. }
  5481. if (frag.start < end && frag.end > start && (fragmentEntity.buffered || unbufferedOnly)) {
  5482. _this3.removeFragment(frag);
  5483. }
  5484. });
  5485. };
  5486. _proto.removeFragment = function removeFragment(fragment) {
  5487. var fragKey = getFragmentKey(fragment);
  5488. fragment.clearElementaryStreamInfo();
  5489. var activeParts = this.activePartLists[fragment.type];
  5490. if (activeParts) {
  5491. var snToRemove = fragment.sn;
  5492. this.activePartLists[fragment.type] = filterParts(activeParts, function (part) {
  5493. return part.fragment.sn !== snToRemove;
  5494. });
  5495. }
  5496. delete this.fragments[fragKey];
  5497. if (fragment.endList) {
  5498. delete this.endListFragments[fragment.type];
  5499. }
  5500. };
  5501. _proto.removeAllFragments = function removeAllFragments() {
  5502. var _this$hls, _this$hls$latestLevel;
  5503. this.fragments = Object.create(null);
  5504. this.endListFragments = Object.create(null);
  5505. this.activePartLists = Object.create(null);
  5506. this.hasGaps = false;
  5507. var partlist = (_this$hls = this.hls) == null ? void 0 : (_this$hls$latestLevel = _this$hls.latestLevelDetails) == null ? void 0 : _this$hls$latestLevel.partList;
  5508. if (partlist) {
  5509. partlist.forEach(function (part) {
  5510. return part.clearElementaryStreamInfo();
  5511. });
  5512. }
  5513. };
  5514. return FragmentTracker;
  5515. }();
  5516. function isPartial(fragmentEntity) {
  5517. var _fragmentEntity$range, _fragmentEntity$range2, _fragmentEntity$range3;
  5518. return fragmentEntity.buffered && (fragmentEntity.body.gap || ((_fragmentEntity$range = fragmentEntity.range.video) == null ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) == null ? void 0 : _fragmentEntity$range2.partial) || ((_fragmentEntity$range3 = fragmentEntity.range.audiovideo) == null ? void 0 : _fragmentEntity$range3.partial));
  5519. }
  5520. function getFragmentKey(fragment) {
  5521. return fragment.type + "_" + fragment.level + "_" + fragment.sn;
  5522. }
  5523. function filterParts(partList, predicate) {
  5524. return partList.filter(function (part) {
  5525. var keep = predicate(part);
  5526. if (!keep) {
  5527. part.clearElementaryStreamInfo();
  5528. }
  5529. return keep;
  5530. });
  5531. }
  5532. var DecrypterAesMode = {
  5533. cbc: 0,
  5534. ctr: 1
  5535. };
  5536. var AESCrypto = /*#__PURE__*/function () {
  5537. function AESCrypto(subtle, iv, aesMode) {
  5538. this.subtle = void 0;
  5539. this.aesIV = void 0;
  5540. this.aesMode = void 0;
  5541. this.subtle = subtle;
  5542. this.aesIV = iv;
  5543. this.aesMode = aesMode;
  5544. }
  5545. var _proto = AESCrypto.prototype;
  5546. _proto.decrypt = function decrypt(data, key) {
  5547. switch (this.aesMode) {
  5548. case DecrypterAesMode.cbc:
  5549. return this.subtle.decrypt({
  5550. name: 'AES-CBC',
  5551. iv: this.aesIV
  5552. }, key, data);
  5553. case DecrypterAesMode.ctr:
  5554. return this.subtle.decrypt({
  5555. name: 'AES-CTR',
  5556. counter: this.aesIV,
  5557. length: 64
  5558. },
  5559. //64 : NIST SP800-38A standard suggests that the counter should occupy half of the counter block
  5560. key, data);
  5561. default:
  5562. throw new Error("[AESCrypto] invalid aes mode " + this.aesMode);
  5563. }
  5564. };
  5565. return AESCrypto;
  5566. }();
  5567. // PKCS7
  5568. function removePadding(array) {
  5569. var outputBytes = array.byteLength;
  5570. var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
  5571. if (paddingBytes) {
  5572. return array.slice(0, outputBytes - paddingBytes);
  5573. }
  5574. return array;
  5575. }
  5576. var AESDecryptor = /*#__PURE__*/function () {
  5577. function AESDecryptor() {
  5578. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  5579. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5580. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  5581. this.sBox = new Uint32Array(256);
  5582. this.invSBox = new Uint32Array(256);
  5583. this.key = new Uint32Array(0);
  5584. this.ksRows = 0;
  5585. this.keySize = 0;
  5586. this.keySchedule = void 0;
  5587. this.invKeySchedule = void 0;
  5588. this.initTable();
  5589. }
  5590. // Using view.getUint32() also swaps the byte order.
  5591. var _proto = AESDecryptor.prototype;
  5592. _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
  5593. var view = new DataView(arrayBuffer);
  5594. var newArray = new Uint32Array(4);
  5595. for (var i = 0; i < 4; i++) {
  5596. newArray[i] = view.getUint32(i * 4);
  5597. }
  5598. return newArray;
  5599. };
  5600. _proto.initTable = function initTable() {
  5601. var sBox = this.sBox;
  5602. var invSBox = this.invSBox;
  5603. var subMix = this.subMix;
  5604. var subMix0 = subMix[0];
  5605. var subMix1 = subMix[1];
  5606. var subMix2 = subMix[2];
  5607. var subMix3 = subMix[3];
  5608. var invSubMix = this.invSubMix;
  5609. var invSubMix0 = invSubMix[0];
  5610. var invSubMix1 = invSubMix[1];
  5611. var invSubMix2 = invSubMix[2];
  5612. var invSubMix3 = invSubMix[3];
  5613. var d = new Uint32Array(256);
  5614. var x = 0;
  5615. var xi = 0;
  5616. var i = 0;
  5617. for (i = 0; i < 256; i++) {
  5618. if (i < 128) {
  5619. d[i] = i << 1;
  5620. } else {
  5621. d[i] = i << 1 ^ 0x11b;
  5622. }
  5623. }
  5624. for (i = 0; i < 256; i++) {
  5625. var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
  5626. sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
  5627. sBox[x] = sx;
  5628. invSBox[sx] = x;
  5629. // Compute multiplication
  5630. var x2 = d[x];
  5631. var x4 = d[x2];
  5632. var x8 = d[x4];
  5633. // Compute sub/invSub bytes, mix columns tables
  5634. var t = d[sx] * 0x101 ^ sx * 0x1010100;
  5635. subMix0[x] = t << 24 | t >>> 8;
  5636. subMix1[x] = t << 16 | t >>> 16;
  5637. subMix2[x] = t << 8 | t >>> 24;
  5638. subMix3[x] = t;
  5639. // Compute inv sub bytes, inv mix columns tables
  5640. t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  5641. invSubMix0[sx] = t << 24 | t >>> 8;
  5642. invSubMix1[sx] = t << 16 | t >>> 16;
  5643. invSubMix2[sx] = t << 8 | t >>> 24;
  5644. invSubMix3[sx] = t;
  5645. // Compute next counter
  5646. if (!x) {
  5647. x = xi = 1;
  5648. } else {
  5649. x = x2 ^ d[d[d[x8 ^ x2]]];
  5650. xi ^= d[d[xi]];
  5651. }
  5652. }
  5653. };
  5654. _proto.expandKey = function expandKey(keyBuffer) {
  5655. // convert keyBuffer to Uint32Array
  5656. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  5657. var sameKey = true;
  5658. var offset = 0;
  5659. while (offset < key.length && sameKey) {
  5660. sameKey = key[offset] === this.key[offset];
  5661. offset++;
  5662. }
  5663. if (sameKey) {
  5664. return;
  5665. }
  5666. this.key = key;
  5667. var keySize = this.keySize = key.length;
  5668. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  5669. throw new Error('Invalid aes key size=' + keySize);
  5670. }
  5671. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  5672. var ksRow;
  5673. var invKsRow;
  5674. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  5675. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  5676. var sbox = this.sBox;
  5677. var rcon = this.rcon;
  5678. var invSubMix = this.invSubMix;
  5679. var invSubMix0 = invSubMix[0];
  5680. var invSubMix1 = invSubMix[1];
  5681. var invSubMix2 = invSubMix[2];
  5682. var invSubMix3 = invSubMix[3];
  5683. var prev;
  5684. var t;
  5685. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  5686. if (ksRow < keySize) {
  5687. prev = keySchedule[ksRow] = key[ksRow];
  5688. continue;
  5689. }
  5690. t = prev;
  5691. if (ksRow % keySize === 0) {
  5692. // Rot word
  5693. t = t << 8 | t >>> 24;
  5694. // Sub word
  5695. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5696. // Mix Rcon
  5697. t ^= rcon[ksRow / keySize | 0] << 24;
  5698. } else if (keySize > 6 && ksRow % keySize === 4) {
  5699. // Sub word
  5700. t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
  5701. }
  5702. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  5703. }
  5704. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  5705. ksRow = ksRows - invKsRow;
  5706. if (invKsRow & 3) {
  5707. t = keySchedule[ksRow];
  5708. } else {
  5709. t = keySchedule[ksRow - 4];
  5710. }
  5711. if (invKsRow < 4 || ksRow <= 4) {
  5712. invKeySchedule[invKsRow] = t;
  5713. } else {
  5714. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  5715. }
  5716. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  5717. }
  5718. }
  5719. // Adding this as a method greatly improves performance.
  5720. ;
  5721. _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
  5722. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  5723. };
  5724. _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
  5725. var nRounds = this.keySize + 6;
  5726. var invKeySchedule = this.invKeySchedule;
  5727. var invSBOX = this.invSBox;
  5728. var invSubMix = this.invSubMix;
  5729. var invSubMix0 = invSubMix[0];
  5730. var invSubMix1 = invSubMix[1];
  5731. var invSubMix2 = invSubMix[2];
  5732. var invSubMix3 = invSubMix[3];
  5733. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  5734. var initVector0 = initVector[0];
  5735. var initVector1 = initVector[1];
  5736. var initVector2 = initVector[2];
  5737. var initVector3 = initVector[3];
  5738. var inputInt32 = new Int32Array(inputArrayBuffer);
  5739. var outputInt32 = new Int32Array(inputInt32.length);
  5740. var t0, t1, t2, t3;
  5741. var s0, s1, s2, s3;
  5742. var inputWords0, inputWords1, inputWords2, inputWords3;
  5743. var ksRow, i;
  5744. var swapWord = this.networkToHostOrderSwap;
  5745. while (offset < inputInt32.length) {
  5746. inputWords0 = swapWord(inputInt32[offset]);
  5747. inputWords1 = swapWord(inputInt32[offset + 1]);
  5748. inputWords2 = swapWord(inputInt32[offset + 2]);
  5749. inputWords3 = swapWord(inputInt32[offset + 3]);
  5750. s0 = inputWords0 ^ invKeySchedule[0];
  5751. s1 = inputWords3 ^ invKeySchedule[1];
  5752. s2 = inputWords2 ^ invKeySchedule[2];
  5753. s3 = inputWords1 ^ invKeySchedule[3];
  5754. ksRow = 4;
  5755. // Iterate through the rounds of decryption
  5756. for (i = 1; i < nRounds; i++) {
  5757. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  5758. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5759. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5760. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5761. // Update state
  5762. s0 = t0;
  5763. s1 = t1;
  5764. s2 = t2;
  5765. s3 = t3;
  5766. ksRow = ksRow + 4;
  5767. }
  5768. // Shift rows, sub bytes, add round key
  5769. t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
  5770. t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  5771. t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  5772. t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  5773. // Write
  5774. outputInt32[offset] = swapWord(t0 ^ initVector0);
  5775. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  5776. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  5777. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  5778. // reset initVector to last 4 unsigned int
  5779. initVector0 = inputWords0;
  5780. initVector1 = inputWords1;
  5781. initVector2 = inputWords2;
  5782. initVector3 = inputWords3;
  5783. offset = offset + 4;
  5784. }
  5785. return outputInt32.buffer;
  5786. };
  5787. return AESDecryptor;
  5788. }();
  5789. var FastAESKey = /*#__PURE__*/function () {
  5790. function FastAESKey(subtle, key, aesMode) {
  5791. this.subtle = void 0;
  5792. this.key = void 0;
  5793. this.aesMode = void 0;
  5794. this.subtle = subtle;
  5795. this.key = key;
  5796. this.aesMode = aesMode;
  5797. }
  5798. var _proto = FastAESKey.prototype;
  5799. _proto.expandKey = function expandKey() {
  5800. var subtleAlgoName = getSubtleAlgoName(this.aesMode);
  5801. return this.subtle.importKey('raw', this.key, {
  5802. name: subtleAlgoName
  5803. }, false, ['encrypt', 'decrypt']);
  5804. };
  5805. return FastAESKey;
  5806. }();
  5807. function getSubtleAlgoName(aesMode) {
  5808. switch (aesMode) {
  5809. case DecrypterAesMode.cbc:
  5810. return 'AES-CBC';
  5811. case DecrypterAesMode.ctr:
  5812. return 'AES-CTR';
  5813. default:
  5814. throw new Error("[FastAESKey] invalid aes mode " + aesMode);
  5815. }
  5816. }
  5817. var CHUNK_SIZE = 16; // 16 bytes, 128 bits
  5818. var Decrypter = /*#__PURE__*/function () {
  5819. function Decrypter(config, _temp) {
  5820. var _ref = _temp === void 0 ? {} : _temp,
  5821. _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
  5822. removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
  5823. this.logEnabled = true;
  5824. this.removePKCS7Padding = void 0;
  5825. this.subtle = null;
  5826. this.softwareDecrypter = null;
  5827. this.key = null;
  5828. this.fastAesKey = null;
  5829. this.remainderData = null;
  5830. this.currentIV = null;
  5831. this.currentResult = null;
  5832. this.useSoftware = void 0;
  5833. this.enableSoftwareAES = void 0;
  5834. this.enableSoftwareAES = config.enableSoftwareAES;
  5835. this.removePKCS7Padding = removePKCS7Padding;
  5836. // built in decryptor expects PKCS7 padding
  5837. if (removePKCS7Padding) {
  5838. try {
  5839. var browserCrypto = self.crypto;
  5840. if (browserCrypto) {
  5841. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  5842. }
  5843. } catch (e) {
  5844. /* no-op */
  5845. }
  5846. }
  5847. this.useSoftware = !this.subtle;
  5848. }
  5849. var _proto = Decrypter.prototype;
  5850. _proto.destroy = function destroy() {
  5851. this.subtle = null;
  5852. this.softwareDecrypter = null;
  5853. this.key = null;
  5854. this.fastAesKey = null;
  5855. this.remainderData = null;
  5856. this.currentIV = null;
  5857. this.currentResult = null;
  5858. };
  5859. _proto.isSync = function isSync() {
  5860. return this.useSoftware;
  5861. };
  5862. _proto.flush = function flush() {
  5863. var currentResult = this.currentResult,
  5864. remainderData = this.remainderData;
  5865. if (!currentResult || remainderData) {
  5866. this.reset();
  5867. return null;
  5868. }
  5869. var data = new Uint8Array(currentResult);
  5870. this.reset();
  5871. if (this.removePKCS7Padding) {
  5872. return removePadding(data);
  5873. }
  5874. return data;
  5875. };
  5876. _proto.reset = function reset() {
  5877. this.currentResult = null;
  5878. this.currentIV = null;
  5879. this.remainderData = null;
  5880. if (this.softwareDecrypter) {
  5881. this.softwareDecrypter = null;
  5882. }
  5883. };
  5884. _proto.decrypt = function decrypt(data, key, iv, aesMode) {
  5885. var _this = this;
  5886. if (this.useSoftware) {
  5887. return new Promise(function (resolve, reject) {
  5888. var dataView = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  5889. _this.softwareDecrypt(dataView, key, iv, aesMode);
  5890. var decryptResult = _this.flush();
  5891. if (decryptResult) {
  5892. resolve(decryptResult.buffer);
  5893. } else {
  5894. reject(new Error('[softwareDecrypt] Failed to decrypt data'));
  5895. }
  5896. });
  5897. }
  5898. return this.webCryptoDecrypt(new Uint8Array(data), key, iv, aesMode);
  5899. }
  5900. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  5901. // data is handled in the flush() call
  5902. ;
  5903. _proto.softwareDecrypt = function softwareDecrypt(data, key, iv, aesMode) {
  5904. var currentIV = this.currentIV,
  5905. currentResult = this.currentResult,
  5906. remainderData = this.remainderData;
  5907. if (aesMode !== DecrypterAesMode.cbc || key.byteLength !== 16) {
  5908. logger.warn('SoftwareDecrypt: can only handle AES-128-CBC');
  5909. return null;
  5910. }
  5911. this.logOnce('JS AES decrypt');
  5912. // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
  5913. // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
  5914. // the end on flush(), but by that time we have already received all bytes for the segment.
  5915. // Progressive decryption does not work with WebCrypto
  5916. if (remainderData) {
  5917. data = appendUint8Array(remainderData, data);
  5918. this.remainderData = null;
  5919. }
  5920. // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
  5921. var currentChunk = this.getValidChunk(data);
  5922. if (!currentChunk.length) {
  5923. return null;
  5924. }
  5925. if (currentIV) {
  5926. iv = currentIV;
  5927. }
  5928. var softwareDecrypter = this.softwareDecrypter;
  5929. if (!softwareDecrypter) {
  5930. softwareDecrypter = this.softwareDecrypter = new AESDecryptor();
  5931. }
  5932. softwareDecrypter.expandKey(key);
  5933. var result = currentResult;
  5934. this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
  5935. this.currentIV = currentChunk.slice(-16).buffer;
  5936. if (!result) {
  5937. return null;
  5938. }
  5939. return result;
  5940. };
  5941. _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv, aesMode) {
  5942. var _this2 = this;
  5943. if (this.key !== key || !this.fastAesKey) {
  5944. if (!this.subtle) {
  5945. return Promise.resolve(this.onWebCryptoError(data, key, iv, aesMode));
  5946. }
  5947. this.key = key;
  5948. this.fastAesKey = new FastAESKey(this.subtle, key, aesMode);
  5949. }
  5950. return this.fastAesKey.expandKey().then(function (aesKey) {
  5951. // decrypt using web crypto
  5952. if (!_this2.subtle) {
  5953. return Promise.reject(new Error('web crypto not initialized'));
  5954. }
  5955. _this2.logOnce('WebCrypto AES decrypt');
  5956. var crypto = new AESCrypto(_this2.subtle, new Uint8Array(iv), aesMode);
  5957. return crypto.decrypt(data.buffer, aesKey);
  5958. }).catch(function (err) {
  5959. logger.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, " + err.name + ": " + err.message);
  5960. return _this2.onWebCryptoError(data, key, iv, aesMode);
  5961. });
  5962. };
  5963. _proto.onWebCryptoError = function onWebCryptoError(data, key, iv, aesMode) {
  5964. var enableSoftwareAES = this.enableSoftwareAES;
  5965. if (enableSoftwareAES) {
  5966. this.useSoftware = true;
  5967. this.logEnabled = true;
  5968. this.softwareDecrypt(data, key, iv, aesMode);
  5969. var decryptResult = this.flush();
  5970. if (decryptResult) {
  5971. return decryptResult.buffer;
  5972. }
  5973. }
  5974. throw new Error('WebCrypto' + (enableSoftwareAES ? ' and softwareDecrypt' : '') + ': failed to decrypt data');
  5975. };
  5976. _proto.getValidChunk = function getValidChunk(data) {
  5977. var currentChunk = data;
  5978. var splitPoint = data.length - data.length % CHUNK_SIZE;
  5979. if (splitPoint !== data.length) {
  5980. currentChunk = data.slice(0, splitPoint);
  5981. this.remainderData = data.slice(splitPoint);
  5982. }
  5983. return currentChunk;
  5984. };
  5985. _proto.logOnce = function logOnce(msg) {
  5986. if (!this.logEnabled) {
  5987. return;
  5988. }
  5989. logger.log("[decrypter]: " + msg);
  5990. this.logEnabled = false;
  5991. };
  5992. return Decrypter;
  5993. }();
  5994. var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
  5995. var FragmentLoader = /*#__PURE__*/function () {
  5996. function FragmentLoader(config) {
  5997. this.config = void 0;
  5998. this.loader = null;
  5999. this.partLoadTimeout = -1;
  6000. this.config = config;
  6001. }
  6002. var _proto = FragmentLoader.prototype;
  6003. _proto.destroy = function destroy() {
  6004. if (this.loader) {
  6005. this.loader.destroy();
  6006. this.loader = null;
  6007. }
  6008. };
  6009. _proto.abort = function abort() {
  6010. if (this.loader) {
  6011. // Abort the loader for current fragment. Only one may load at any given time
  6012. this.loader.abort();
  6013. }
  6014. };
  6015. _proto.load = function load(frag, onProgress) {
  6016. var _this = this;
  6017. var url = frag.url;
  6018. if (!url) {
  6019. return Promise.reject(new LoadError({
  6020. type: ErrorTypes.NETWORK_ERROR,
  6021. details: ErrorDetails.FRAG_LOAD_ERROR,
  6022. fatal: false,
  6023. frag: frag,
  6024. error: new Error("Fragment does not have a " + (url ? 'part list' : 'url')),
  6025. networkDetails: null
  6026. }));
  6027. }
  6028. this.abort();
  6029. var config = this.config;
  6030. var FragmentILoader = config.fLoader;
  6031. var DefaultILoader = config.loader;
  6032. return new Promise(function (resolve, reject) {
  6033. if (_this.loader) {
  6034. _this.loader.destroy();
  6035. }
  6036. if (frag.gap) {
  6037. if (frag.tagList.some(function (tags) {
  6038. return tags[0] === 'GAP';
  6039. })) {
  6040. reject(createGapLoadError(frag));
  6041. return;
  6042. } else {
  6043. // Reset temporary treatment as GAP tag
  6044. frag.gap = false;
  6045. }
  6046. }
  6047. var loader = _this.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  6048. var loaderContext = createLoaderContext(frag);
  6049. frag.loader = loader;
  6050. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  6051. var loaderConfig = {
  6052. loadPolicy: loadPolicy,
  6053. timeout: loadPolicy.maxLoadTimeMs,
  6054. maxRetry: 0,
  6055. retryDelay: 0,
  6056. maxRetryDelay: 0,
  6057. highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE
  6058. };
  6059. // Assign frag stats to the loader's stats reference
  6060. frag.stats = loader.stats;
  6061. var callbacks = {
  6062. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  6063. _this.resetLoader(frag, loader);
  6064. var payload = response.data;
  6065. if (context.resetIV && frag.decryptdata) {
  6066. frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));
  6067. payload = payload.slice(16);
  6068. }
  6069. resolve({
  6070. frag: frag,
  6071. part: null,
  6072. payload: payload,
  6073. networkDetails: networkDetails
  6074. });
  6075. },
  6076. onError: function onError(response, context, networkDetails, stats) {
  6077. _this.resetLoader(frag, loader);
  6078. reject(new LoadError({
  6079. type: ErrorTypes.NETWORK_ERROR,
  6080. details: ErrorDetails.FRAG_LOAD_ERROR,
  6081. fatal: false,
  6082. frag: frag,
  6083. response: _objectSpread2({
  6084. url: url,
  6085. data: undefined
  6086. }, response),
  6087. error: new Error("HTTP Error " + response.code + " " + response.text),
  6088. networkDetails: networkDetails,
  6089. stats: stats
  6090. }));
  6091. },
  6092. onAbort: function onAbort(stats, context, networkDetails) {
  6093. _this.resetLoader(frag, loader);
  6094. reject(new LoadError({
  6095. type: ErrorTypes.NETWORK_ERROR,
  6096. details: ErrorDetails.INTERNAL_ABORTED,
  6097. fatal: false,
  6098. frag: frag,
  6099. error: new Error('Aborted'),
  6100. networkDetails: networkDetails,
  6101. stats: stats
  6102. }));
  6103. },
  6104. onTimeout: function onTimeout(stats, context, networkDetails) {
  6105. _this.resetLoader(frag, loader);
  6106. reject(new LoadError({
  6107. type: ErrorTypes.NETWORK_ERROR,
  6108. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  6109. fatal: false,
  6110. frag: frag,
  6111. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  6112. networkDetails: networkDetails,
  6113. stats: stats
  6114. }));
  6115. }
  6116. };
  6117. if (onProgress) {
  6118. callbacks.onProgress = function (stats, context, data, networkDetails) {
  6119. return onProgress({
  6120. frag: frag,
  6121. part: null,
  6122. payload: data,
  6123. networkDetails: networkDetails
  6124. });
  6125. };
  6126. }
  6127. loader.load(loaderContext, loaderConfig, callbacks);
  6128. });
  6129. };
  6130. _proto.loadPart = function loadPart(frag, part, onProgress) {
  6131. var _this2 = this;
  6132. this.abort();
  6133. var config = this.config;
  6134. var FragmentILoader = config.fLoader;
  6135. var DefaultILoader = config.loader;
  6136. return new Promise(function (resolve, reject) {
  6137. if (_this2.loader) {
  6138. _this2.loader.destroy();
  6139. }
  6140. if (frag.gap || part.gap) {
  6141. reject(createGapLoadError(frag, part));
  6142. return;
  6143. }
  6144. var loader = _this2.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
  6145. var loaderContext = createLoaderContext(frag, part);
  6146. frag.loader = loader;
  6147. // Should we define another load policy for parts?
  6148. var loadPolicy = getLoaderConfigWithoutReties(config.fragLoadPolicy.default);
  6149. var loaderConfig = {
  6150. loadPolicy: loadPolicy,
  6151. timeout: loadPolicy.maxLoadTimeMs,
  6152. maxRetry: 0,
  6153. retryDelay: 0,
  6154. maxRetryDelay: 0,
  6155. highWaterMark: MIN_CHUNK_SIZE
  6156. };
  6157. // Assign part stats to the loader's stats reference
  6158. part.stats = loader.stats;
  6159. loader.load(loaderContext, loaderConfig, {
  6160. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  6161. _this2.resetLoader(frag, loader);
  6162. _this2.updateStatsFromPart(frag, part);
  6163. var partLoadedData = {
  6164. frag: frag,
  6165. part: part,
  6166. payload: response.data,
  6167. networkDetails: networkDetails
  6168. };
  6169. onProgress(partLoadedData);
  6170. resolve(partLoadedData);
  6171. },
  6172. onError: function onError(response, context, networkDetails, stats) {
  6173. _this2.resetLoader(frag, loader);
  6174. reject(new LoadError({
  6175. type: ErrorTypes.NETWORK_ERROR,
  6176. details: ErrorDetails.FRAG_LOAD_ERROR,
  6177. fatal: false,
  6178. frag: frag,
  6179. part: part,
  6180. response: _objectSpread2({
  6181. url: loaderContext.url,
  6182. data: undefined
  6183. }, response),
  6184. error: new Error("HTTP Error " + response.code + " " + response.text),
  6185. networkDetails: networkDetails,
  6186. stats: stats
  6187. }));
  6188. },
  6189. onAbort: function onAbort(stats, context, networkDetails) {
  6190. frag.stats.aborted = part.stats.aborted;
  6191. _this2.resetLoader(frag, loader);
  6192. reject(new LoadError({
  6193. type: ErrorTypes.NETWORK_ERROR,
  6194. details: ErrorDetails.INTERNAL_ABORTED,
  6195. fatal: false,
  6196. frag: frag,
  6197. part: part,
  6198. error: new Error('Aborted'),
  6199. networkDetails: networkDetails,
  6200. stats: stats
  6201. }));
  6202. },
  6203. onTimeout: function onTimeout(stats, context, networkDetails) {
  6204. _this2.resetLoader(frag, loader);
  6205. reject(new LoadError({
  6206. type: ErrorTypes.NETWORK_ERROR,
  6207. details: ErrorDetails.FRAG_LOAD_TIMEOUT,
  6208. fatal: false,
  6209. frag: frag,
  6210. part: part,
  6211. error: new Error("Timeout after " + loaderConfig.timeout + "ms"),
  6212. networkDetails: networkDetails,
  6213. stats: stats
  6214. }));
  6215. }
  6216. });
  6217. });
  6218. };
  6219. _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
  6220. var fragStats = frag.stats;
  6221. var partStats = part.stats;
  6222. var partTotal = partStats.total;
  6223. fragStats.loaded += partStats.loaded;
  6224. if (partTotal) {
  6225. var estTotalParts = Math.round(frag.duration / part.duration);
  6226. var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
  6227. var estRemainingParts = estTotalParts - estLoadedParts;
  6228. var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
  6229. fragStats.total = fragStats.loaded + estRemainingBytes;
  6230. } else {
  6231. fragStats.total = Math.max(fragStats.loaded, fragStats.total);
  6232. }
  6233. var fragLoading = fragStats.loading;
  6234. var partLoading = partStats.loading;
  6235. if (fragLoading.start) {
  6236. // add to fragment loader latency
  6237. fragLoading.first += partLoading.first - partLoading.start;
  6238. } else {
  6239. fragLoading.start = partLoading.start;
  6240. fragLoading.first = partLoading.first;
  6241. }
  6242. fragLoading.end = partLoading.end;
  6243. };
  6244. _proto.resetLoader = function resetLoader(frag, loader) {
  6245. frag.loader = null;
  6246. if (this.loader === loader) {
  6247. self.clearTimeout(this.partLoadTimeout);
  6248. this.loader = null;
  6249. }
  6250. loader.destroy();
  6251. };
  6252. return FragmentLoader;
  6253. }();
  6254. function createLoaderContext(frag, part) {
  6255. if (part === void 0) {
  6256. part = null;
  6257. }
  6258. var segment = part || frag;
  6259. var loaderContext = {
  6260. frag: frag,
  6261. part: part,
  6262. responseType: 'arraybuffer',
  6263. url: segment.url,
  6264. headers: {},
  6265. rangeStart: 0,
  6266. rangeEnd: 0
  6267. };
  6268. var start = segment.byteRangeStartOffset;
  6269. var end = segment.byteRangeEndOffset;
  6270. if (isFiniteNumber(start) && isFiniteNumber(end)) {
  6271. var _frag$decryptdata;
  6272. var byteRangeStart = start;
  6273. var byteRangeEnd = end;
  6274. if (frag.sn === 'initSegment' && isMethodFullSegmentAesCbc((_frag$decryptdata = frag.decryptdata) == null ? void 0 : _frag$decryptdata.method)) {
  6275. // MAP segment encrypted with method 'AES-128' or 'AES-256' (cbc), when served with HTTP Range,
  6276. // has the unencrypted size specified in the range.
  6277. // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6
  6278. var fragmentLen = end - start;
  6279. if (fragmentLen % 16) {
  6280. byteRangeEnd = end + (16 - fragmentLen % 16);
  6281. }
  6282. if (start !== 0) {
  6283. loaderContext.resetIV = true;
  6284. byteRangeStart = start - 16;
  6285. }
  6286. }
  6287. loaderContext.rangeStart = byteRangeStart;
  6288. loaderContext.rangeEnd = byteRangeEnd;
  6289. }
  6290. return loaderContext;
  6291. }
  6292. function createGapLoadError(frag, part) {
  6293. var error = new Error("GAP " + (frag.gap ? 'tag' : 'attribute') + " found");
  6294. var errorData = {
  6295. type: ErrorTypes.MEDIA_ERROR,
  6296. details: ErrorDetails.FRAG_GAP,
  6297. fatal: false,
  6298. frag: frag,
  6299. error: error,
  6300. networkDetails: null
  6301. };
  6302. if (part) {
  6303. errorData.part = part;
  6304. }
  6305. (part ? part : frag).stats.aborted = true;
  6306. return new LoadError(errorData);
  6307. }
  6308. function isMethodFullSegmentAesCbc(method) {
  6309. return method === 'AES-128' || method === 'AES-256';
  6310. }
  6311. var LoadError = /*#__PURE__*/function (_Error) {
  6312. function LoadError(data) {
  6313. var _this3;
  6314. _this3 = _Error.call(this, data.error.message) || this;
  6315. _this3.data = void 0;
  6316. _this3.data = data;
  6317. return _this3;
  6318. }
  6319. _inheritsLoose(LoadError, _Error);
  6320. return LoadError;
  6321. }(/*#__PURE__*/_wrapNativeSuper(Error));
  6322. /**
  6323. * @ignore
  6324. * Sub-class specialization of EventHandler base class.
  6325. *
  6326. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  6327. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  6328. *
  6329. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  6330. * using the `tick` method.
  6331. *
  6332. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  6333. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  6334. *
  6335. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  6336. * and cancelled with `clearNextTick`.
  6337. *
  6338. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  6339. *
  6340. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  6341. *
  6342. * Further explanations:
  6343. *
  6344. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  6345. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  6346. *
  6347. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  6348. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  6349. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  6350. */
  6351. var TaskLoop = /*#__PURE__*/function (_Logger) {
  6352. function TaskLoop(label, logger) {
  6353. var _this;
  6354. _this = _Logger.call(this, label, logger) || this;
  6355. _this._boundTick = void 0;
  6356. _this._tickTimer = null;
  6357. _this._tickInterval = null;
  6358. _this._tickCallCount = 0;
  6359. _this._boundTick = _this.tick.bind(_this);
  6360. return _this;
  6361. }
  6362. _inheritsLoose(TaskLoop, _Logger);
  6363. var _proto = TaskLoop.prototype;
  6364. _proto.destroy = function destroy() {
  6365. this.onHandlerDestroying();
  6366. this.onHandlerDestroyed();
  6367. };
  6368. _proto.onHandlerDestroying = function onHandlerDestroying() {
  6369. // clear all timers before unregistering from event bus
  6370. this.clearNextTick();
  6371. this.clearInterval();
  6372. };
  6373. _proto.onHandlerDestroyed = function onHandlerDestroyed() {};
  6374. _proto.hasInterval = function hasInterval() {
  6375. return !!this._tickInterval;
  6376. };
  6377. _proto.hasNextTick = function hasNextTick() {
  6378. return !!this._tickTimer;
  6379. }
  6380. /**
  6381. * @param millis - Interval time (ms)
  6382. * @eturns True when interval has been scheduled, false when already scheduled (no effect)
  6383. */;
  6384. _proto.setInterval = function setInterval(millis) {
  6385. if (!this._tickInterval) {
  6386. this._tickCallCount = 0;
  6387. this._tickInterval = self.setInterval(this._boundTick, millis);
  6388. return true;
  6389. }
  6390. return false;
  6391. }
  6392. /**
  6393. * @returns True when interval was cleared, false when none was set (no effect)
  6394. */;
  6395. _proto.clearInterval = function clearInterval() {
  6396. if (this._tickInterval) {
  6397. self.clearInterval(this._tickInterval);
  6398. this._tickInterval = null;
  6399. return true;
  6400. }
  6401. return false;
  6402. }
  6403. /**
  6404. * @returns True when timeout was cleared, false when none was set (no effect)
  6405. */;
  6406. _proto.clearNextTick = function clearNextTick() {
  6407. if (this._tickTimer) {
  6408. self.clearTimeout(this._tickTimer);
  6409. this._tickTimer = null;
  6410. return true;
  6411. }
  6412. return false;
  6413. }
  6414. /**
  6415. * Will call the subclass doTick implementation in this main loop tick
  6416. * or in the next one (via setTimeout(,0)) in case it has already been called
  6417. * in this tick (in case this is a re-entrant call).
  6418. */;
  6419. _proto.tick = function tick() {
  6420. this._tickCallCount++;
  6421. if (this._tickCallCount === 1) {
  6422. this.doTick();
  6423. // re-entrant call to tick from previous doTick call stack
  6424. // -> schedule a call on the next main loop iteration to process this task processing request
  6425. if (this._tickCallCount > 1) {
  6426. // make sure only one timer exists at any time at max
  6427. this.tickImmediate();
  6428. }
  6429. this._tickCallCount = 0;
  6430. }
  6431. };
  6432. _proto.tickImmediate = function tickImmediate() {
  6433. this.clearNextTick();
  6434. this._tickTimer = self.setTimeout(this._boundTick, 0);
  6435. }
  6436. /**
  6437. * For subclass to implement task logic
  6438. * @abstract
  6439. */;
  6440. _proto.doTick = function doTick() {};
  6441. return TaskLoop;
  6442. }(Logger);
  6443. var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
  6444. if (size === void 0) {
  6445. size = 0;
  6446. }
  6447. if (part === void 0) {
  6448. part = -1;
  6449. }
  6450. if (partial === void 0) {
  6451. partial = false;
  6452. }
  6453. this.level = void 0;
  6454. this.sn = void 0;
  6455. this.part = void 0;
  6456. this.id = void 0;
  6457. this.size = void 0;
  6458. this.partial = void 0;
  6459. this.transmuxing = getNewPerformanceTiming();
  6460. this.buffering = {
  6461. audio: getNewPerformanceTiming(),
  6462. video: getNewPerformanceTiming(),
  6463. audiovideo: getNewPerformanceTiming()
  6464. };
  6465. this.level = level;
  6466. this.sn = sn;
  6467. this.id = id;
  6468. this.size = size;
  6469. this.part = part;
  6470. this.partial = partial;
  6471. };
  6472. function getNewPerformanceTiming() {
  6473. return {
  6474. start: 0,
  6475. executeStart: 0,
  6476. executeEnd: 0,
  6477. end: 0
  6478. };
  6479. }
  6480. /**
  6481. * Provides methods dealing with buffer length retrieval for example.
  6482. *
  6483. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  6484. *
  6485. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  6486. */
  6487. var noopBuffered = {
  6488. length: 0,
  6489. start: function start() {
  6490. return 0;
  6491. },
  6492. end: function end() {
  6493. return 0;
  6494. }
  6495. };
  6496. var BufferHelper = /*#__PURE__*/function () {
  6497. function BufferHelper() {}
  6498. /**
  6499. * Return true if `media`'s buffered include `position`
  6500. */
  6501. BufferHelper.isBuffered = function isBuffered(media, position) {
  6502. if (media) {
  6503. var buffered = BufferHelper.getBuffered(media);
  6504. for (var i = buffered.length; i--;) {
  6505. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  6506. return true;
  6507. }
  6508. }
  6509. }
  6510. return false;
  6511. };
  6512. BufferHelper.bufferedRanges = function bufferedRanges(media) {
  6513. if (media) {
  6514. var timeRanges = BufferHelper.getBuffered(media);
  6515. return BufferHelper.timeRangesToArray(timeRanges);
  6516. }
  6517. return [];
  6518. };
  6519. BufferHelper.timeRangesToArray = function timeRangesToArray(timeRanges) {
  6520. var buffered = [];
  6521. for (var i = 0; i < timeRanges.length; i++) {
  6522. buffered.push({
  6523. start: timeRanges.start(i),
  6524. end: timeRanges.end(i)
  6525. });
  6526. }
  6527. return buffered;
  6528. };
  6529. BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
  6530. if (media) {
  6531. var buffered = BufferHelper.bufferedRanges(media);
  6532. if (buffered.length) {
  6533. return BufferHelper.bufferedInfo(buffered, pos, maxHoleDuration);
  6534. }
  6535. }
  6536. return {
  6537. len: 0,
  6538. start: pos,
  6539. end: pos,
  6540. bufferedIndex: -1
  6541. };
  6542. };
  6543. BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
  6544. pos = Math.max(0, pos);
  6545. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  6546. if (buffered.length > 1) {
  6547. buffered.sort(function (a, b) {
  6548. return a.start - b.start || b.end - a.end;
  6549. });
  6550. }
  6551. var bufferedIndex = -1;
  6552. var buffered2 = [];
  6553. if (maxHoleDuration) {
  6554. // there might be some small holes between buffer time range
  6555. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6556. // buffer time range representations that discards those holes
  6557. for (var i = 0; i < buffered.length; i++) {
  6558. if (pos >= buffered[i].start && pos <= buffered[i].end) {
  6559. bufferedIndex = i;
  6560. }
  6561. var buf2len = buffered2.length;
  6562. if (buf2len) {
  6563. var buf2end = buffered2[buf2len - 1].end;
  6564. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6565. if (buffered[i].start - buf2end < maxHoleDuration) {
  6566. // merge overlapping time ranges
  6567. // update lastRange.end only if smaller than item.end
  6568. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6569. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6570. if (buffered[i].end > buf2end) {
  6571. buffered2[buf2len - 1].end = buffered[i].end;
  6572. }
  6573. } else {
  6574. // big hole
  6575. buffered2.push(buffered[i]);
  6576. }
  6577. } else {
  6578. // first value
  6579. buffered2.push(buffered[i]);
  6580. }
  6581. }
  6582. } else {
  6583. buffered2 = buffered;
  6584. }
  6585. var bufferLen = 0;
  6586. var nextStart;
  6587. // bufferStart and bufferEnd are buffer boundaries around current playback position (pos)
  6588. var bufferStart = pos;
  6589. var bufferEnd = pos;
  6590. for (var _i = 0; _i < buffered2.length; _i++) {
  6591. var start = buffered2[_i].start;
  6592. var end = buffered2[_i].end;
  6593. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  6594. if (bufferedIndex === -1 && pos >= start && pos <= end) {
  6595. bufferedIndex = _i;
  6596. }
  6597. if (pos + maxHoleDuration >= start && pos < end) {
  6598. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  6599. bufferStart = start;
  6600. bufferEnd = end;
  6601. bufferLen = bufferEnd - pos;
  6602. } else if (pos + maxHoleDuration < start) {
  6603. nextStart = start;
  6604. break;
  6605. }
  6606. }
  6607. return {
  6608. len: bufferLen,
  6609. start: bufferStart || 0,
  6610. end: bufferEnd || 0,
  6611. nextStart: nextStart,
  6612. buffered: buffered,
  6613. bufferedIndex: bufferedIndex
  6614. };
  6615. }
  6616. /**
  6617. * Safe method to get buffered property.
  6618. * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
  6619. */;
  6620. BufferHelper.getBuffered = function getBuffered(media) {
  6621. try {
  6622. return media.buffered || noopBuffered;
  6623. } catch (e) {
  6624. logger.log('failed to get media.buffered', e);
  6625. return noopBuffered;
  6626. }
  6627. };
  6628. return BufferHelper;
  6629. }();
  6630. var VARIABLE_REPLACEMENT_REGEX = /\{\$([a-zA-Z0-9-_]+)\}/g;
  6631. function hasVariableReferences(str) {
  6632. return VARIABLE_REPLACEMENT_REGEX.test(str);
  6633. }
  6634. function substituteVariables(parsed, value) {
  6635. if (parsed.variableList !== null || parsed.hasVariableRefs) {
  6636. var variableList = parsed.variableList;
  6637. return value.replace(VARIABLE_REPLACEMENT_REGEX, function (variableReference) {
  6638. var variableName = variableReference.substring(2, variableReference.length - 1);
  6639. var variableValue = variableList == null ? void 0 : variableList[variableName];
  6640. if (variableValue === undefined) {
  6641. parsed.playlistParsingError || (parsed.playlistParsingError = new Error("Missing preceding EXT-X-DEFINE tag for Variable Reference: \"" + variableName + "\""));
  6642. return variableReference;
  6643. }
  6644. return variableValue;
  6645. });
  6646. }
  6647. return value;
  6648. }
  6649. function addVariableDefinition(parsed, attr, parentUrl) {
  6650. var variableList = parsed.variableList;
  6651. if (!variableList) {
  6652. parsed.variableList = variableList = {};
  6653. }
  6654. var NAME;
  6655. var VALUE;
  6656. if ('QUERYPARAM' in attr) {
  6657. NAME = attr.QUERYPARAM;
  6658. try {
  6659. var searchParams = new self.URL(parentUrl).searchParams;
  6660. if (searchParams.has(NAME)) {
  6661. VALUE = searchParams.get(NAME);
  6662. } else {
  6663. throw new Error("\"" + NAME + "\" does not match any query parameter in URI: \"" + parentUrl + "\"");
  6664. }
  6665. } catch (error) {
  6666. parsed.playlistParsingError || (parsed.playlistParsingError = new Error("EXT-X-DEFINE QUERYPARAM: " + error.message));
  6667. }
  6668. } else {
  6669. NAME = attr.NAME;
  6670. VALUE = attr.VALUE;
  6671. }
  6672. if (NAME in variableList) {
  6673. parsed.playlistParsingError || (parsed.playlistParsingError = new Error("EXT-X-DEFINE duplicate Variable Name declarations: \"" + NAME + "\""));
  6674. } else {
  6675. variableList[NAME] = VALUE || '';
  6676. }
  6677. }
  6678. function importVariableDefinition(parsed, attr, sourceVariableList) {
  6679. var IMPORT = attr.IMPORT;
  6680. if (sourceVariableList && IMPORT in sourceVariableList) {
  6681. var variableList = parsed.variableList;
  6682. if (!variableList) {
  6683. parsed.variableList = variableList = {};
  6684. }
  6685. variableList[IMPORT] = sourceVariableList[IMPORT];
  6686. } else {
  6687. parsed.playlistParsingError || (parsed.playlistParsingError = new Error("EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: \"" + IMPORT + "\""));
  6688. }
  6689. }
  6690. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/;
  6691. var ATTR_LIST_REGEX = /(.+?)=(".*?"|.*?)(?:,|$)/g;
  6692. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  6693. var AttrList = /*#__PURE__*/function () {
  6694. function AttrList(attrs, parsed) {
  6695. if (typeof attrs === 'string') {
  6696. attrs = AttrList.parseAttrList(attrs, parsed);
  6697. }
  6698. _extends(this, attrs);
  6699. }
  6700. var _proto = AttrList.prototype;
  6701. _proto.decimalInteger = function decimalInteger(attrName) {
  6702. var intValue = parseInt(this[attrName], 10);
  6703. if (intValue > Number.MAX_SAFE_INTEGER) {
  6704. return Infinity;
  6705. }
  6706. return intValue;
  6707. };
  6708. _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
  6709. if (this[attrName]) {
  6710. var stringValue = (this[attrName] || '0x').slice(2);
  6711. stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  6712. var value = new Uint8Array(stringValue.length / 2);
  6713. for (var i = 0; i < stringValue.length / 2; i++) {
  6714. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  6715. }
  6716. return value;
  6717. }
  6718. return null;
  6719. };
  6720. _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
  6721. var intValue = parseInt(this[attrName], 16);
  6722. if (intValue > Number.MAX_SAFE_INTEGER) {
  6723. return Infinity;
  6724. }
  6725. return intValue;
  6726. };
  6727. _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
  6728. return parseFloat(this[attrName]);
  6729. };
  6730. _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
  6731. var value = this[attrName];
  6732. return value ? parseFloat(value) : defaultValue;
  6733. };
  6734. _proto.enumeratedString = function enumeratedString(attrName) {
  6735. return this[attrName];
  6736. };
  6737. _proto.enumeratedStringList = function enumeratedStringList(attrName, dict) {
  6738. var attrValue = this[attrName];
  6739. return (attrValue ? attrValue.split(/[ ,]+/) : []).reduce(function (result, identifier) {
  6740. result[identifier.toLowerCase()] = true;
  6741. return result;
  6742. }, dict);
  6743. };
  6744. _proto.bool = function bool(attrName) {
  6745. return this[attrName] === 'YES';
  6746. };
  6747. _proto.decimalResolution = function decimalResolution(attrName) {
  6748. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  6749. if (res === null) {
  6750. return undefined;
  6751. }
  6752. return {
  6753. width: parseInt(res[1], 10),
  6754. height: parseInt(res[2], 10)
  6755. };
  6756. };
  6757. AttrList.parseAttrList = function parseAttrList(input, parsed) {
  6758. var match;
  6759. var attrs = {};
  6760. var quote = '"';
  6761. ATTR_LIST_REGEX.lastIndex = 0;
  6762. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  6763. var name = match[1].trim();
  6764. var value = match[2];
  6765. var quotedString = value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1;
  6766. var hexadecimalSequence = false;
  6767. if (quotedString) {
  6768. value = value.slice(1, -1);
  6769. } else {
  6770. switch (name) {
  6771. case 'IV':
  6772. case 'SCTE35-CMD':
  6773. case 'SCTE35-IN':
  6774. case 'SCTE35-OUT':
  6775. hexadecimalSequence = true;
  6776. }
  6777. }
  6778. if (parsed && (quotedString || hexadecimalSequence)) {
  6779. {
  6780. value = substituteVariables(parsed, value);
  6781. }
  6782. } else if (!hexadecimalSequence && !quotedString) {
  6783. switch (name) {
  6784. case 'CLOSED-CAPTIONS':
  6785. if (value === 'NONE') {
  6786. break;
  6787. }
  6788. // falls through
  6789. case 'ALLOWED-CPC':
  6790. case 'CLASS':
  6791. case 'ASSOC-LANGUAGE':
  6792. case 'AUDIO':
  6793. case 'BYTERANGE':
  6794. case 'CHANNELS':
  6795. case 'CHARACTERISTICS':
  6796. case 'CODECS':
  6797. case 'DATA-ID':
  6798. case 'END-DATE':
  6799. case 'GROUP-ID':
  6800. case 'ID':
  6801. case 'IMPORT':
  6802. case 'INSTREAM-ID':
  6803. case 'KEYFORMAT':
  6804. case 'KEYFORMATVERSIONS':
  6805. case 'LANGUAGE':
  6806. case 'NAME':
  6807. case 'PATHWAY-ID':
  6808. case 'QUERYPARAM':
  6809. case 'RECENTLY-REMOVED-DATERANGES':
  6810. case 'SERVER-URI':
  6811. case 'STABLE-RENDITION-ID':
  6812. case 'STABLE-VARIANT-ID':
  6813. case 'START-DATE':
  6814. case 'SUBTITLES':
  6815. case 'SUPPLEMENTAL-CODECS':
  6816. case 'URI':
  6817. case 'VALUE':
  6818. case 'VIDEO':
  6819. case 'X-ASSET-LIST':
  6820. case 'X-ASSET-URI':
  6821. // Since we are not checking tag:attribute combination, just warn rather than ignoring attribute
  6822. logger.warn(input + ": attribute " + name + " is missing quotes");
  6823. // continue;
  6824. }
  6825. }
  6826. attrs[name] = value;
  6827. }
  6828. return attrs;
  6829. };
  6830. return _createClass(AttrList, [{
  6831. key: "clientAttrs",
  6832. get: function get() {
  6833. return Object.keys(this).filter(function (attr) {
  6834. return attr.substring(0, 2) === 'X-';
  6835. });
  6836. }
  6837. }]);
  6838. }();
  6839. // Avoid exporting const enum so that these values can be inlined
  6840. var CLASS_INTERSTITIAL = 'com.apple.hls.interstitial';
  6841. function isDateRangeCueAttribute(attrName) {
  6842. return attrName !== "ID" && attrName !== "CLASS" && attrName !== "CUE" && attrName !== "START-DATE" && attrName !== "DURATION" && attrName !== "END-DATE" && attrName !== "END-ON-NEXT";
  6843. }
  6844. function isSCTE35Attribute(attrName) {
  6845. return attrName === "SCTE35-OUT" || attrName === "SCTE35-IN" || attrName === "SCTE35-CMD";
  6846. }
  6847. var DateRange = /*#__PURE__*/function () {
  6848. function DateRange(dateRangeAttr, dateRangeWithSameId, tagCount) {
  6849. var _dateRangeWithSameId$;
  6850. if (tagCount === void 0) {
  6851. tagCount = 0;
  6852. }
  6853. this.attr = void 0;
  6854. this.tagAnchor = void 0;
  6855. this.tagOrder = void 0;
  6856. this._startDate = void 0;
  6857. this._endDate = void 0;
  6858. this._dateAtEnd = void 0;
  6859. this._cue = void 0;
  6860. this._badValueForSameId = void 0;
  6861. this.tagAnchor = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagAnchor) || null;
  6862. this.tagOrder = (_dateRangeWithSameId$ = dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.tagOrder) != null ? _dateRangeWithSameId$ : tagCount;
  6863. if (dateRangeWithSameId) {
  6864. var previousAttr = dateRangeWithSameId.attr;
  6865. for (var key in previousAttr) {
  6866. if (Object.prototype.hasOwnProperty.call(dateRangeAttr, key) && dateRangeAttr[key] !== previousAttr[key]) {
  6867. logger.warn("DATERANGE tag attribute: \"" + key + "\" does not match for tags with ID: \"" + dateRangeAttr.ID + "\"");
  6868. this._badValueForSameId = key;
  6869. break;
  6870. }
  6871. }
  6872. // Merge DateRange tags with the same ID
  6873. dateRangeAttr = _extends(new AttrList({}), previousAttr, dateRangeAttr);
  6874. }
  6875. this.attr = dateRangeAttr;
  6876. if (dateRangeWithSameId) {
  6877. this._startDate = dateRangeWithSameId._startDate;
  6878. this._cue = dateRangeWithSameId._cue;
  6879. this._endDate = dateRangeWithSameId._endDate;
  6880. this._dateAtEnd = dateRangeWithSameId._dateAtEnd;
  6881. } else {
  6882. this._startDate = new Date(dateRangeAttr["START-DATE"]);
  6883. }
  6884. if ("END-DATE" in this.attr) {
  6885. var endDate = (dateRangeWithSameId == null ? void 0 : dateRangeWithSameId.endDate) || new Date(this.attr["END-DATE"]);
  6886. if (isFiniteNumber(endDate.getTime())) {
  6887. this._endDate = endDate;
  6888. }
  6889. }
  6890. }
  6891. return _createClass(DateRange, [{
  6892. key: "id",
  6893. get: function get() {
  6894. return this.attr.ID;
  6895. }
  6896. }, {
  6897. key: "class",
  6898. get: function get() {
  6899. return this.attr.CLASS;
  6900. }
  6901. }, {
  6902. key: "cue",
  6903. get: function get() {
  6904. var _cue = this._cue;
  6905. if (_cue === undefined) {
  6906. return this._cue = this.attr.enumeratedStringList(this.attr.CUE ? 'CUE' : 'X-CUE', {
  6907. pre: false,
  6908. post: false,
  6909. once: false
  6910. });
  6911. }
  6912. return _cue;
  6913. }
  6914. }, {
  6915. key: "startTime",
  6916. get: function get() {
  6917. var tagAnchor = this.tagAnchor;
  6918. // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
  6919. if (tagAnchor === null || tagAnchor.programDateTime === null) {
  6920. logger.warn("Expected tagAnchor Fragment with PDT set for DateRange \"" + this.id + "\": " + tagAnchor);
  6921. return NaN;
  6922. }
  6923. return tagAnchor.start + (this.startDate.getTime() - tagAnchor.programDateTime) / 1000;
  6924. }
  6925. }, {
  6926. key: "startDate",
  6927. get: function get() {
  6928. return this._startDate;
  6929. }
  6930. }, {
  6931. key: "endDate",
  6932. get: function get() {
  6933. var dateAtEnd = this._endDate || this._dateAtEnd;
  6934. if (dateAtEnd) {
  6935. return dateAtEnd;
  6936. }
  6937. var duration = this.duration;
  6938. if (duration !== null) {
  6939. return this._dateAtEnd = new Date(this._startDate.getTime() + duration * 1000);
  6940. }
  6941. return null;
  6942. }
  6943. }, {
  6944. key: "duration",
  6945. get: function get() {
  6946. if ("DURATION" in this.attr) {
  6947. var duration = this.attr.decimalFloatingPoint("DURATION");
  6948. if (isFiniteNumber(duration)) {
  6949. return duration;
  6950. }
  6951. } else if (this._endDate) {
  6952. return (this._endDate.getTime() - this._startDate.getTime()) / 1000;
  6953. }
  6954. return null;
  6955. }
  6956. }, {
  6957. key: "plannedDuration",
  6958. get: function get() {
  6959. if ("PLANNED-DURATION" in this.attr) {
  6960. return this.attr.decimalFloatingPoint("PLANNED-DURATION");
  6961. }
  6962. return null;
  6963. }
  6964. }, {
  6965. key: "endOnNext",
  6966. get: function get() {
  6967. return this.attr.bool("END-ON-NEXT");
  6968. }
  6969. }, {
  6970. key: "isInterstitial",
  6971. get: function get() {
  6972. return this.class === CLASS_INTERSTITIAL;
  6973. }
  6974. }, {
  6975. key: "isValid",
  6976. get: function get() {
  6977. return !!this.id && !this._badValueForSameId && isFiniteNumber(this.startDate.getTime()) && (this.duration === null || this.duration >= 0) && (!this.endOnNext || !!this.class) && (!this.attr.CUE || !this.cue.pre && !this.cue.post || this.cue.pre !== this.cue.post) && (!this.isInterstitial || 'X-ASSET-URI' in this.attr || 'X-ASSET-LIST' in this.attr);
  6978. }
  6979. }]);
  6980. }();
  6981. var DEFAULT_TARGET_DURATION = 10;
  6982. /**
  6983. * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.
  6984. */
  6985. var LevelDetails = /*#__PURE__*/function () {
  6986. function LevelDetails(baseUrl) {
  6987. this.PTSKnown = false;
  6988. this.alignedSliding = false;
  6989. this.averagetargetduration = void 0;
  6990. this.endCC = 0;
  6991. this.endSN = 0;
  6992. this.fragments = void 0;
  6993. this.fragmentHint = void 0;
  6994. this.partList = null;
  6995. this.dateRanges = void 0;
  6996. this.dateRangeTagCount = 0;
  6997. this.live = true;
  6998. this.requestScheduled = -1;
  6999. this.ageHeader = 0;
  7000. this.advancedDateTime = void 0;
  7001. this.updated = true;
  7002. this.advanced = true;
  7003. this.misses = 0;
  7004. this.startCC = 0;
  7005. this.startSN = 0;
  7006. this.startTimeOffset = null;
  7007. this.targetduration = 0;
  7008. this.totalduration = 0;
  7009. this.type = null;
  7010. this.url = void 0;
  7011. this.m3u8 = '';
  7012. this.version = null;
  7013. this.canBlockReload = false;
  7014. this.canSkipUntil = 0;
  7015. this.canSkipDateRanges = false;
  7016. this.skippedSegments = 0;
  7017. this.recentlyRemovedDateranges = void 0;
  7018. this.partHoldBack = 0;
  7019. this.holdBack = 0;
  7020. this.partTarget = 0;
  7021. this.preloadHint = void 0;
  7022. this.renditionReports = void 0;
  7023. this.tuneInGoal = 0;
  7024. this.deltaUpdateFailed = void 0;
  7025. this.driftStartTime = 0;
  7026. this.driftEndTime = 0;
  7027. this.driftStart = 0;
  7028. this.driftEnd = 0;
  7029. this.encryptedFragments = void 0;
  7030. this.playlistParsingError = null;
  7031. this.variableList = null;
  7032. this.hasVariableRefs = false;
  7033. this.appliedTimelineOffset = void 0;
  7034. this.fragments = [];
  7035. this.encryptedFragments = [];
  7036. this.dateRanges = {};
  7037. this.url = baseUrl;
  7038. }
  7039. var _proto = LevelDetails.prototype;
  7040. _proto.reloaded = function reloaded(previous) {
  7041. if (!previous) {
  7042. this.advanced = true;
  7043. this.updated = true;
  7044. return;
  7045. }
  7046. var partSnDiff = this.lastPartSn - previous.lastPartSn;
  7047. var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
  7048. this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff || !this.live;
  7049. this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
  7050. if (this.updated || this.advanced) {
  7051. this.misses = Math.floor(previous.misses * 0.6);
  7052. } else {
  7053. this.misses = previous.misses + 1;
  7054. }
  7055. };
  7056. return _createClass(LevelDetails, [{
  7057. key: "hasProgramDateTime",
  7058. get: function get() {
  7059. if (this.fragments.length) {
  7060. return isFiniteNumber(this.fragments[this.fragments.length - 1].programDateTime);
  7061. }
  7062. return false;
  7063. }
  7064. }, {
  7065. key: "levelTargetDuration",
  7066. get: function get() {
  7067. return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
  7068. }
  7069. }, {
  7070. key: "drift",
  7071. get: function get() {
  7072. var runTime = this.driftEndTime - this.driftStartTime;
  7073. if (runTime > 0) {
  7074. var runDuration = this.driftEnd - this.driftStart;
  7075. return runDuration * 1000 / runTime;
  7076. }
  7077. return 1;
  7078. }
  7079. }, {
  7080. key: "edge",
  7081. get: function get() {
  7082. return this.partEnd || this.fragmentEnd;
  7083. }
  7084. }, {
  7085. key: "partEnd",
  7086. get: function get() {
  7087. var _this$partList;
  7088. if ((_this$partList = this.partList) != null && _this$partList.length) {
  7089. return this.partList[this.partList.length - 1].end;
  7090. }
  7091. return this.fragmentEnd;
  7092. }
  7093. }, {
  7094. key: "fragmentEnd",
  7095. get: function get() {
  7096. var _this$fragments;
  7097. if ((_this$fragments = this.fragments) != null && _this$fragments.length) {
  7098. return this.fragments[this.fragments.length - 1].end;
  7099. }
  7100. return 0;
  7101. }
  7102. }, {
  7103. key: "fragmentStart",
  7104. get: function get() {
  7105. var _this$fragments2;
  7106. if ((_this$fragments2 = this.fragments) != null && _this$fragments2.length) {
  7107. return this.fragments[0].start;
  7108. }
  7109. return 0;
  7110. }
  7111. }, {
  7112. key: "age",
  7113. get: function get() {
  7114. if (this.advancedDateTime) {
  7115. return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
  7116. }
  7117. return 0;
  7118. }
  7119. }, {
  7120. key: "lastPartIndex",
  7121. get: function get() {
  7122. var _this$partList2;
  7123. if ((_this$partList2 = this.partList) != null && _this$partList2.length) {
  7124. return this.partList[this.partList.length - 1].index;
  7125. }
  7126. return -1;
  7127. }
  7128. }, {
  7129. key: "maxPartIndex",
  7130. get: function get() {
  7131. var partList = this.partList;
  7132. if (partList) {
  7133. var lastIndex = this.lastPartIndex;
  7134. if (lastIndex !== -1) {
  7135. for (var i = partList.length; i--;) {
  7136. if (partList[i].index > lastIndex) {
  7137. return partList[i].index;
  7138. }
  7139. }
  7140. return lastIndex;
  7141. }
  7142. }
  7143. return 0;
  7144. }
  7145. }, {
  7146. key: "lastPartSn",
  7147. get: function get() {
  7148. var _this$partList3;
  7149. if ((_this$partList3 = this.partList) != null && _this$partList3.length) {
  7150. return this.partList[this.partList.length - 1].fragment.sn;
  7151. }
  7152. return this.endSN;
  7153. }
  7154. }, {
  7155. key: "expired",
  7156. get: function get() {
  7157. if (this.live && this.age && this.misses < 3) {
  7158. var playlistWindowDuration = this.partEnd - this.fragmentStart;
  7159. return this.age > Math.max(playlistWindowDuration, this.totalduration) + this.levelTargetDuration;
  7160. }
  7161. return false;
  7162. }
  7163. }]);
  7164. }();
  7165. function isFullSegmentEncryption(method) {
  7166. return method === 'AES-128' || method === 'AES-256' || method === 'AES-256-CTR';
  7167. }
  7168. function getAesModeFromFullSegmentMethod(method) {
  7169. switch (method) {
  7170. case 'AES-128':
  7171. case 'AES-256':
  7172. return DecrypterAesMode.cbc;
  7173. case 'AES-256-CTR':
  7174. return DecrypterAesMode.ctr;
  7175. default:
  7176. throw new Error("invalid full segment method " + method);
  7177. }
  7178. }
  7179. function base64Decode(base64encodedStr) {
  7180. return Uint8Array.from(atob(base64encodedStr), function (c) {
  7181. return c.charCodeAt(0);
  7182. });
  7183. }
  7184. // breaking up those two types in order to clarify what is happening in the decoding path.
  7185. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  7186. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  7187. /* utf.js - UTF-8 <=> UTF-16 convertion
  7188. *
  7189. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  7190. * Version: 1.0
  7191. * LastModified: Dec 25 1999
  7192. * This library is free. You can redistribute it and/or modify it.
  7193. */
  7194. function strToUtf8array(str) {
  7195. return Uint8Array.from(unescape(encodeURIComponent(str)), function (c) {
  7196. return c.charCodeAt(0);
  7197. });
  7198. }
  7199. function getKeyIdBytes(str) {
  7200. var keyIdbytes = strToUtf8array(str).subarray(0, 16);
  7201. var paddedkeyIdbytes = new Uint8Array(16);
  7202. paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);
  7203. return paddedkeyIdbytes;
  7204. }
  7205. function changeEndianness(keyId) {
  7206. var swap = function swap(array, from, to) {
  7207. var cur = array[from];
  7208. array[from] = array[to];
  7209. array[to] = cur;
  7210. };
  7211. swap(keyId, 0, 3);
  7212. swap(keyId, 1, 2);
  7213. swap(keyId, 4, 5);
  7214. swap(keyId, 6, 7);
  7215. }
  7216. function convertDataUriToArrayBytes(uri) {
  7217. // data:[<media type][;attribute=value][;base64],<data>
  7218. var colonsplit = uri.split(':');
  7219. var keydata = null;
  7220. if (colonsplit[0] === 'data' && colonsplit.length === 2) {
  7221. var semicolonsplit = colonsplit[1].split(';');
  7222. var commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');
  7223. if (commasplit.length === 2) {
  7224. var isbase64 = commasplit[0] === 'base64';
  7225. var data = commasplit[1];
  7226. if (isbase64) {
  7227. semicolonsplit.splice(-1, 1); // remove from processing
  7228. keydata = base64Decode(data);
  7229. } else {
  7230. keydata = getKeyIdBytes(data);
  7231. }
  7232. }
  7233. }
  7234. return keydata;
  7235. }
  7236. /** returns `undefined` is `self` is missing, e.g. in node */
  7237. var optionalSelf = typeof self !== 'undefined' ? self : undefined;
  7238. /**
  7239. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  7240. */
  7241. var KeySystems = {
  7242. CLEARKEY: "org.w3.clearkey",
  7243. FAIRPLAY: "com.apple.fps",
  7244. PLAYREADY: "com.microsoft.playready",
  7245. WIDEVINE: "com.widevine.alpha"
  7246. };
  7247. // Playlist #EXT-X-KEY KEYFORMAT values
  7248. var KeySystemFormats = {
  7249. CLEARKEY: "org.w3.clearkey",
  7250. FAIRPLAY: "com.apple.streamingkeydelivery",
  7251. PLAYREADY: "com.microsoft.playready",
  7252. WIDEVINE: "urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"
  7253. };
  7254. function keySystemFormatToKeySystemDomain(format) {
  7255. switch (format) {
  7256. case KeySystemFormats.FAIRPLAY:
  7257. return KeySystems.FAIRPLAY;
  7258. case KeySystemFormats.PLAYREADY:
  7259. return KeySystems.PLAYREADY;
  7260. case KeySystemFormats.WIDEVINE:
  7261. return KeySystems.WIDEVINE;
  7262. case KeySystemFormats.CLEARKEY:
  7263. return KeySystems.CLEARKEY;
  7264. }
  7265. }
  7266. function keySystemDomainToKeySystemFormat(keySystem) {
  7267. switch (keySystem) {
  7268. case KeySystems.FAIRPLAY:
  7269. return KeySystemFormats.FAIRPLAY;
  7270. case KeySystems.PLAYREADY:
  7271. return KeySystemFormats.PLAYREADY;
  7272. case KeySystems.WIDEVINE:
  7273. return KeySystemFormats.WIDEVINE;
  7274. case KeySystems.CLEARKEY:
  7275. return KeySystemFormats.CLEARKEY;
  7276. }
  7277. }
  7278. function getKeySystemsForConfig(config) {
  7279. var drmSystems = config.drmSystems,
  7280. widevineLicenseUrl = config.widevineLicenseUrl;
  7281. var keySystemsToAttempt = drmSystems ? [KeySystems.FAIRPLAY, KeySystems.WIDEVINE, KeySystems.PLAYREADY, KeySystems.CLEARKEY].filter(function (keySystem) {
  7282. return !!drmSystems[keySystem];
  7283. }) : [];
  7284. if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {
  7285. keySystemsToAttempt.push(KeySystems.WIDEVINE);
  7286. }
  7287. return keySystemsToAttempt;
  7288. }
  7289. var requestMediaKeySystemAccess = function (_optionalSelf$navigat) {
  7290. if (optionalSelf != null && (_optionalSelf$navigat = optionalSelf.navigator) != null && _optionalSelf$navigat.requestMediaKeySystemAccess) {
  7291. return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
  7292. } else {
  7293. return null;
  7294. }
  7295. }();
  7296. /**
  7297. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  7298. */
  7299. function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
  7300. var initDataTypes;
  7301. switch (keySystem) {
  7302. case KeySystems.FAIRPLAY:
  7303. initDataTypes = ['cenc', 'sinf'];
  7304. break;
  7305. case KeySystems.WIDEVINE:
  7306. case KeySystems.PLAYREADY:
  7307. initDataTypes = ['cenc'];
  7308. break;
  7309. case KeySystems.CLEARKEY:
  7310. initDataTypes = ['cenc', 'keyids'];
  7311. break;
  7312. default:
  7313. throw new Error("Unknown key-system: " + keySystem);
  7314. }
  7315. return createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions);
  7316. }
  7317. function createMediaKeySystemConfigurations(initDataTypes, audioCodecs, videoCodecs, drmSystemOptions) {
  7318. var baseConfig = {
  7319. initDataTypes: initDataTypes,
  7320. persistentState: drmSystemOptions.persistentState || 'optional',
  7321. distinctiveIdentifier: drmSystemOptions.distinctiveIdentifier || 'optional',
  7322. sessionTypes: drmSystemOptions.sessionTypes || [drmSystemOptions.sessionType || 'temporary'],
  7323. audioCapabilities: audioCodecs.map(function (codec) {
  7324. return {
  7325. contentType: "audio/mp4; codecs=" + codec,
  7326. robustness: drmSystemOptions.audioRobustness || '',
  7327. encryptionScheme: drmSystemOptions.audioEncryptionScheme || null
  7328. };
  7329. }),
  7330. videoCapabilities: videoCodecs.map(function (codec) {
  7331. return {
  7332. contentType: "video/mp4; codecs=" + codec,
  7333. robustness: drmSystemOptions.videoRobustness || '',
  7334. encryptionScheme: drmSystemOptions.videoEncryptionScheme || null
  7335. };
  7336. })
  7337. };
  7338. return [baseConfig];
  7339. }
  7340. function isPersistentSessionType(drmSystemOptions) {
  7341. var _drmSystemOptions$ses;
  7342. return drmSystemOptions.sessionType === 'persistent-license' || !!((_drmSystemOptions$ses = drmSystemOptions.sessionTypes) != null && _drmSystemOptions$ses.some(function (type) {
  7343. return type === 'persistent-license';
  7344. }));
  7345. }
  7346. function parsePlayReadyWRM(keyBytes) {
  7347. var keyBytesUtf16 = new Uint16Array(keyBytes.buffer, keyBytes.byteOffset, keyBytes.byteLength / 2);
  7348. var keyByteStr = String.fromCharCode.apply(null, Array.from(keyBytesUtf16));
  7349. // Parse Playready WRMHeader XML
  7350. var xmlKeyBytes = keyByteStr.substring(keyByteStr.indexOf('<'), keyByteStr.length);
  7351. var parser = new DOMParser();
  7352. var xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');
  7353. var keyData = xmlDoc.getElementsByTagName('KID')[0];
  7354. if (keyData) {
  7355. var keyId = keyData.childNodes[0] ? keyData.childNodes[0].nodeValue : keyData.getAttribute('VALUE');
  7356. if (keyId) {
  7357. var keyIdArray = base64Decode(keyId).subarray(0, 16);
  7358. // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID
  7359. // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID
  7360. changeEndianness(keyIdArray);
  7361. return keyIdArray;
  7362. }
  7363. }
  7364. return null;
  7365. }
  7366. var keyUriToKeyIdMap = {};
  7367. var LevelKey = /*#__PURE__*/function () {
  7368. function LevelKey(method, uri, format, formatversions, iv, keyId) {
  7369. if (formatversions === void 0) {
  7370. formatversions = [1];
  7371. }
  7372. if (iv === void 0) {
  7373. iv = null;
  7374. }
  7375. this.uri = void 0;
  7376. this.method = void 0;
  7377. this.keyFormat = void 0;
  7378. this.keyFormatVersions = void 0;
  7379. this.encrypted = void 0;
  7380. this.isCommonEncryption = void 0;
  7381. this.iv = null;
  7382. this.key = null;
  7383. this.keyId = null;
  7384. this.pssh = null;
  7385. this.method = method;
  7386. this.uri = uri;
  7387. this.keyFormat = format;
  7388. this.keyFormatVersions = formatversions;
  7389. this.iv = iv;
  7390. this.encrypted = method ? method !== 'NONE' : false;
  7391. this.isCommonEncryption = this.encrypted && !isFullSegmentEncryption(method);
  7392. if (keyId != null && keyId.startsWith('0x')) {
  7393. this.keyId = new Uint8Array(hexToArrayBuffer(keyId));
  7394. }
  7395. }
  7396. LevelKey.clearKeyUriToKeyIdMap = function clearKeyUriToKeyIdMap() {
  7397. keyUriToKeyIdMap = {};
  7398. };
  7399. var _proto = LevelKey.prototype;
  7400. _proto.matches = function matches(key) {
  7401. var _key$iv, _this$iv;
  7402. return key.uri === this.uri && key.method === this.method && key.encrypted === this.encrypted && key.keyFormat === this.keyFormat && key.keyFormatVersions.join(',') === this.keyFormatVersions.join(',') && ((_key$iv = key.iv) == null ? void 0 : _key$iv.join(',')) === ((_this$iv = this.iv) == null ? void 0 : _this$iv.join(','));
  7403. };
  7404. _proto.isSupported = function isSupported() {
  7405. // If it's Segment encryption or No encryption, just select that key system
  7406. if (this.method) {
  7407. if (isFullSegmentEncryption(this.method) || this.method === 'NONE') {
  7408. return true;
  7409. }
  7410. if (this.keyFormat === 'identity') {
  7411. // Maintain support for clear SAMPLE-AES with MPEG-3 TS
  7412. return this.method === 'SAMPLE-AES';
  7413. } else {
  7414. switch (this.keyFormat) {
  7415. case KeySystemFormats.FAIRPLAY:
  7416. case KeySystemFormats.WIDEVINE:
  7417. case KeySystemFormats.PLAYREADY:
  7418. case KeySystemFormats.CLEARKEY:
  7419. return ['ISO-23001-7', 'SAMPLE-AES', 'SAMPLE-AES-CENC', 'SAMPLE-AES-CTR'].indexOf(this.method) !== -1;
  7420. }
  7421. }
  7422. }
  7423. return false;
  7424. };
  7425. _proto.getDecryptData = function getDecryptData(sn) {
  7426. if (!this.encrypted || !this.uri) {
  7427. return null;
  7428. }
  7429. if (isFullSegmentEncryption(this.method) && this.uri && !this.iv) {
  7430. if (typeof sn !== 'number') {
  7431. // We are fetching decryption data for a initialization segment
  7432. // If the segment was encrypted with AES-128/256
  7433. // It must have an IV defined. We cannot substitute the Segment Number in.
  7434. logger.warn("missing IV for initialization segment with method=\"" + this.method + "\" - compliance issue");
  7435. // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
  7436. sn = 0;
  7437. }
  7438. var iv = createInitializationVector(sn);
  7439. var decryptdata = new LevelKey(this.method, this.uri, 'identity', this.keyFormatVersions, iv);
  7440. return decryptdata;
  7441. }
  7442. if (this.pssh && this.keyId) {
  7443. return this;
  7444. }
  7445. // Initialize keyId if possible
  7446. var keyBytes = convertDataUriToArrayBytes(this.uri);
  7447. if (keyBytes) {
  7448. switch (this.keyFormat) {
  7449. case KeySystemFormats.WIDEVINE:
  7450. // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using
  7451. // the playlist-key before the "encrypted" event. (Comment out to only use "encrypted" path.)
  7452. this.pssh = keyBytes;
  7453. // In case of Widevine, if KEYID is not in the playlist, assume only two fields in the pssh KEY tag URI.
  7454. if (!this.keyId && keyBytes.length >= 22) {
  7455. var offset = keyBytes.length - 22;
  7456. this.keyId = keyBytes.subarray(offset, offset + 16);
  7457. }
  7458. break;
  7459. case KeySystemFormats.PLAYREADY:
  7460. {
  7461. var PlayReadyKeySystemUUID = new Uint8Array([0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6, 0x5b, 0xe0, 0x88, 0x5f, 0x95]);
  7462. // Setting `pssh` on this LevelKey/DecryptData allows HLS.js to generate a session using
  7463. // the playlist-key before the "encrypted" event. (Comment out to only use "encrypted" path.)
  7464. this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);
  7465. this.keyId = parsePlayReadyWRM(keyBytes);
  7466. break;
  7467. }
  7468. default:
  7469. {
  7470. var keydata = keyBytes.subarray(0, 16);
  7471. if (keydata.length !== 16) {
  7472. var padded = new Uint8Array(16);
  7473. padded.set(keydata, 16 - keydata.length);
  7474. keydata = padded;
  7475. }
  7476. this.keyId = keydata;
  7477. break;
  7478. }
  7479. }
  7480. }
  7481. // Default behavior: assign a new keyId for each uri
  7482. if (!this.keyId || this.keyId.byteLength !== 16) {
  7483. var keyId = keyUriToKeyIdMap[this.uri];
  7484. if (!keyId) {
  7485. var val = Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;
  7486. keyId = new Uint8Array(16);
  7487. var dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes
  7488. dv.setUint32(0, val);
  7489. keyUriToKeyIdMap[this.uri] = keyId;
  7490. }
  7491. this.keyId = keyId;
  7492. }
  7493. return this;
  7494. };
  7495. return LevelKey;
  7496. }();
  7497. function createInitializationVector(segmentNumber) {
  7498. var uint8View = new Uint8Array(16);
  7499. for (var i = 12; i < 16; i++) {
  7500. uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  7501. }
  7502. return uint8View;
  7503. }
  7504. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g;
  7505. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  7506. var IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)
  7507. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  7508. // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
  7509. /(?!#) *(\S[^\r\n]*)/.source,
  7510. // segment URI, group 3 => the URI (note newline is not eaten)
  7511. /#.*/.source // All other non-segment oriented tags will match with all groups empty
  7512. ].join('|'), 'g');
  7513. var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source, /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source, /#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
  7514. var M3U8Parser = /*#__PURE__*/function () {
  7515. function M3U8Parser() {}
  7516. M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
  7517. for (var i = 0; i < groups.length; i++) {
  7518. var group = groups[i];
  7519. if (group.id === mediaGroupId) {
  7520. return group;
  7521. }
  7522. }
  7523. };
  7524. M3U8Parser.resolve = function resolve(url, baseUrl) {
  7525. return urlToolkitExports.buildAbsoluteURL(baseUrl, url, {
  7526. alwaysNormalize: true
  7527. });
  7528. };
  7529. M3U8Parser.isMediaPlaylist = function isMediaPlaylist(str) {
  7530. return IS_MEDIA_PLAYLIST.test(str);
  7531. };
  7532. M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
  7533. var hasVariableRefs = hasVariableReferences(string) ;
  7534. var parsed = {
  7535. contentSteering: null,
  7536. levels: [],
  7537. playlistParsingError: null,
  7538. sessionData: null,
  7539. sessionKeys: null,
  7540. startTimeOffset: null,
  7541. variableList: null,
  7542. hasVariableRefs: hasVariableRefs
  7543. };
  7544. var levelsWithKnownCodecs = [];
  7545. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  7546. var result;
  7547. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  7548. if (result[1]) {
  7549. var _level$unknownCodecs;
  7550. // '#EXT-X-STREAM-INF' is found, parse level tag in group 1
  7551. var attrs = new AttrList(result[1], parsed);
  7552. var uri = substituteVariables(parsed, result[2]) ;
  7553. var level = {
  7554. attrs: attrs,
  7555. bitrate: attrs.decimalInteger('BANDWIDTH') || attrs.decimalInteger('AVERAGE-BANDWIDTH'),
  7556. name: attrs.NAME,
  7557. url: M3U8Parser.resolve(uri, baseurl)
  7558. };
  7559. var resolution = attrs.decimalResolution('RESOLUTION');
  7560. if (resolution) {
  7561. level.width = resolution.width;
  7562. level.height = resolution.height;
  7563. }
  7564. setCodecs(attrs.CODECS, level);
  7565. var supplementalCodecs = attrs['SUPPLEMENTAL-CODECS'];
  7566. if (supplementalCodecs) {
  7567. level.supplemental = {};
  7568. setCodecs(supplementalCodecs, level.supplemental);
  7569. }
  7570. if (!((_level$unknownCodecs = level.unknownCodecs) != null && _level$unknownCodecs.length)) {
  7571. levelsWithKnownCodecs.push(level);
  7572. }
  7573. parsed.levels.push(level);
  7574. } else if (result[3]) {
  7575. var tag = result[3];
  7576. var attributes = result[4];
  7577. switch (tag) {
  7578. case 'SESSION-DATA':
  7579. {
  7580. // #EXT-X-SESSION-DATA
  7581. var sessionAttrs = new AttrList(attributes, parsed);
  7582. var dataId = sessionAttrs['DATA-ID'];
  7583. if (dataId) {
  7584. if (parsed.sessionData === null) {
  7585. parsed.sessionData = {};
  7586. }
  7587. parsed.sessionData[dataId] = sessionAttrs;
  7588. }
  7589. break;
  7590. }
  7591. case 'SESSION-KEY':
  7592. {
  7593. // #EXT-X-SESSION-KEY
  7594. var sessionKey = parseKey(attributes, baseurl, parsed);
  7595. if (sessionKey.encrypted && sessionKey.isSupported()) {
  7596. if (parsed.sessionKeys === null) {
  7597. parsed.sessionKeys = [];
  7598. }
  7599. parsed.sessionKeys.push(sessionKey);
  7600. } else {
  7601. logger.warn("[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"" + attributes + "\"");
  7602. }
  7603. break;
  7604. }
  7605. case 'DEFINE':
  7606. {
  7607. // #EXT-X-DEFINE
  7608. {
  7609. var variableAttributes = new AttrList(attributes, parsed);
  7610. addVariableDefinition(parsed, variableAttributes, baseurl);
  7611. }
  7612. break;
  7613. }
  7614. case 'CONTENT-STEERING':
  7615. {
  7616. // #EXT-X-CONTENT-STEERING
  7617. var contentSteeringAttributes = new AttrList(attributes, parsed);
  7618. parsed.contentSteering = {
  7619. uri: M3U8Parser.resolve(contentSteeringAttributes['SERVER-URI'], baseurl),
  7620. pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.'
  7621. };
  7622. break;
  7623. }
  7624. case 'START':
  7625. {
  7626. // #EXT-X-START
  7627. parsed.startTimeOffset = parseStartTimeOffset(attributes);
  7628. break;
  7629. }
  7630. }
  7631. }
  7632. }
  7633. // Filter out levels with unknown codecs if it does not remove all levels
  7634. var stripUnknownCodecLevels = levelsWithKnownCodecs.length > 0 && levelsWithKnownCodecs.length < parsed.levels.length;
  7635. parsed.levels = stripUnknownCodecLevels ? levelsWithKnownCodecs : parsed.levels;
  7636. if (parsed.levels.length === 0) {
  7637. parsed.playlistParsingError = new Error('no levels found in manifest');
  7638. }
  7639. return parsed;
  7640. };
  7641. M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, parsed) {
  7642. var result;
  7643. var results = {};
  7644. var levels = parsed.levels;
  7645. var groupsByType = {
  7646. AUDIO: levels.map(function (level) {
  7647. return {
  7648. id: level.attrs.AUDIO,
  7649. audioCodec: level.audioCodec
  7650. };
  7651. }),
  7652. SUBTITLES: levels.map(function (level) {
  7653. return {
  7654. id: level.attrs.SUBTITLES,
  7655. textCodec: level.textCodec
  7656. };
  7657. }),
  7658. 'CLOSED-CAPTIONS': []
  7659. };
  7660. var id = 0;
  7661. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  7662. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  7663. var attrs = new AttrList(result[1], parsed);
  7664. var type = attrs.TYPE;
  7665. if (type) {
  7666. var groups = groupsByType[type];
  7667. var medias = results[type] || [];
  7668. results[type] = medias;
  7669. var lang = attrs.LANGUAGE;
  7670. var assocLang = attrs['ASSOC-LANGUAGE'];
  7671. var channels = attrs.CHANNELS;
  7672. var characteristics = attrs.CHARACTERISTICS;
  7673. var instreamId = attrs['INSTREAM-ID'];
  7674. var media = {
  7675. attrs: attrs,
  7676. bitrate: 0,
  7677. id: id++,
  7678. groupId: attrs['GROUP-ID'] || '',
  7679. name: attrs.NAME || lang || '',
  7680. type: type,
  7681. default: attrs.bool('DEFAULT'),
  7682. autoselect: attrs.bool('AUTOSELECT'),
  7683. forced: attrs.bool('FORCED'),
  7684. lang: lang,
  7685. url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
  7686. };
  7687. if (assocLang) {
  7688. media.assocLang = assocLang;
  7689. }
  7690. if (channels) {
  7691. media.channels = channels;
  7692. }
  7693. if (characteristics) {
  7694. media.characteristics = characteristics;
  7695. }
  7696. if (instreamId) {
  7697. media.instreamId = instreamId;
  7698. }
  7699. if (groups != null && groups.length) {
  7700. // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
  7701. // If we don't find the track signalled, lets use the first audio groups codec we have
  7702. // Acting as a best guess
  7703. var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
  7704. assignCodec(media, groupCodec, 'audioCodec');
  7705. assignCodec(media, groupCodec, 'textCodec');
  7706. }
  7707. medias.push(media);
  7708. }
  7709. }
  7710. return results;
  7711. };
  7712. M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId, multivariantVariableList) {
  7713. var _LEVEL_PLAYLIST_REGEX;
  7714. var base = {
  7715. url: baseurl
  7716. };
  7717. var level = new LevelDetails(baseurl);
  7718. var fragments = level.fragments;
  7719. var programDateTimes = [];
  7720. // The most recent init segment seen (applies to all subsequent segments)
  7721. var currentInitSegment = null;
  7722. var currentSN = 0;
  7723. var currentPart = 0;
  7724. var totalduration = 0;
  7725. var discontinuityCounter = 0;
  7726. var currentBitrate = 0;
  7727. var prevFrag = null;
  7728. var frag = new Fragment(type, base);
  7729. var result;
  7730. var i;
  7731. var levelkeys;
  7732. var firstPdtIndex = -1;
  7733. var createNextFrag = false;
  7734. var nextByteRange = null;
  7735. var serverControlAttrs;
  7736. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  7737. level.m3u8 = string;
  7738. level.hasVariableRefs = hasVariableReferences(string) ;
  7739. if (((_LEVEL_PLAYLIST_REGEX = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) == null ? void 0 : _LEVEL_PLAYLIST_REGEX[0]) !== '#EXTM3U') {
  7740. level.playlistParsingError = new Error('Missing format identifier #EXTM3U');
  7741. return level;
  7742. }
  7743. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  7744. if (createNextFrag) {
  7745. createNextFrag = false;
  7746. frag = new Fragment(type, base);
  7747. // setup the next fragment for part loading
  7748. frag.playlistOffset = totalduration;
  7749. frag.start = totalduration;
  7750. frag.sn = currentSN;
  7751. frag.cc = discontinuityCounter;
  7752. if (currentBitrate) {
  7753. frag.bitrate = currentBitrate;
  7754. }
  7755. frag.level = id;
  7756. if (currentInitSegment) {
  7757. frag.initSegment = currentInitSegment;
  7758. if (currentInitSegment.rawProgramDateTime) {
  7759. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7760. currentInitSegment.rawProgramDateTime = null;
  7761. }
  7762. if (nextByteRange) {
  7763. frag.setByteRange(nextByteRange);
  7764. nextByteRange = null;
  7765. }
  7766. }
  7767. }
  7768. var duration = result[1];
  7769. if (duration) {
  7770. // INF
  7771. frag.duration = parseFloat(duration);
  7772. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7773. var title = (' ' + result[2]).slice(1);
  7774. frag.title = title || null;
  7775. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  7776. } else if (result[3]) {
  7777. // url
  7778. if (isFiniteNumber(frag.duration)) {
  7779. frag.playlistOffset = totalduration;
  7780. frag.start = totalduration;
  7781. if (levelkeys) {
  7782. setFragLevelKeys(frag, levelkeys, level);
  7783. }
  7784. frag.sn = currentSN;
  7785. frag.level = id;
  7786. frag.cc = discontinuityCounter;
  7787. fragments.push(frag);
  7788. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7789. var uri = (' ' + result[3]).slice(1);
  7790. frag.relurl = substituteVariables(level, uri) ;
  7791. assignProgramDateTime(frag, prevFrag, programDateTimes);
  7792. prevFrag = frag;
  7793. totalduration += frag.duration;
  7794. currentSN++;
  7795. currentPart = 0;
  7796. createNextFrag = true;
  7797. }
  7798. } else {
  7799. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  7800. if (!result) {
  7801. logger.warn('No matches on slow regex match for level playlist!');
  7802. continue;
  7803. }
  7804. for (i = 1; i < result.length; i++) {
  7805. if (result[i] !== undefined) {
  7806. break;
  7807. }
  7808. }
  7809. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7810. var tag = (' ' + result[i]).slice(1);
  7811. var value1 = (' ' + result[i + 1]).slice(1);
  7812. var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : null;
  7813. switch (tag) {
  7814. case 'BYTERANGE':
  7815. if (prevFrag) {
  7816. frag.setByteRange(value1, prevFrag);
  7817. } else {
  7818. frag.setByteRange(value1);
  7819. }
  7820. break;
  7821. case 'PROGRAM-DATE-TIME':
  7822. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  7823. frag.rawProgramDateTime = value1;
  7824. frag.tagList.push(['PROGRAM-DATE-TIME', value1]);
  7825. if (firstPdtIndex === -1) {
  7826. firstPdtIndex = fragments.length;
  7827. }
  7828. break;
  7829. case 'PLAYLIST-TYPE':
  7830. if (level.type) {
  7831. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7832. }
  7833. level.type = value1.toUpperCase();
  7834. break;
  7835. case 'MEDIA-SEQUENCE':
  7836. if (level.startSN !== 0) {
  7837. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7838. } else if (fragments.length > 0) {
  7839. assignMustAppearBeforeSegmentsError(level, tag, result);
  7840. }
  7841. currentSN = level.startSN = parseInt(value1);
  7842. break;
  7843. case 'SKIP':
  7844. {
  7845. if (level.skippedSegments) {
  7846. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7847. }
  7848. var skipAttrs = new AttrList(value1, level);
  7849. var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
  7850. if (isFiniteNumber(skippedSegments)) {
  7851. level.skippedSegments += skippedSegments;
  7852. // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
  7853. for (var _i = skippedSegments; _i--;) {
  7854. fragments.push(null);
  7855. }
  7856. currentSN += skippedSegments;
  7857. }
  7858. var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
  7859. if (recentlyRemovedDateranges) {
  7860. level.recentlyRemovedDateranges = (level.recentlyRemovedDateranges || []).concat(recentlyRemovedDateranges.split('\t'));
  7861. }
  7862. break;
  7863. }
  7864. case 'TARGETDURATION':
  7865. if (level.targetduration !== 0) {
  7866. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7867. }
  7868. level.targetduration = Math.max(parseInt(value1), 1);
  7869. break;
  7870. case 'VERSION':
  7871. if (level.version !== null) {
  7872. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7873. }
  7874. level.version = parseInt(value1);
  7875. break;
  7876. case 'INDEPENDENT-SEGMENTS':
  7877. break;
  7878. case 'ENDLIST':
  7879. if (!level.live) {
  7880. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7881. }
  7882. level.live = false;
  7883. break;
  7884. case '#':
  7885. if (value1 || value2) {
  7886. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  7887. }
  7888. break;
  7889. case 'DISCONTINUITY':
  7890. discontinuityCounter++;
  7891. frag.tagList.push(['DIS']);
  7892. break;
  7893. case 'GAP':
  7894. frag.gap = true;
  7895. frag.tagList.push([tag]);
  7896. break;
  7897. case 'BITRATE':
  7898. frag.tagList.push([tag, value1]);
  7899. currentBitrate = parseInt(value1) * 1000;
  7900. if (isFiniteNumber(currentBitrate)) {
  7901. frag.bitrate = currentBitrate;
  7902. } else {
  7903. currentBitrate = 0;
  7904. }
  7905. break;
  7906. case 'DATERANGE':
  7907. {
  7908. var dateRangeAttr = new AttrList(value1, level);
  7909. var dateRange = new DateRange(dateRangeAttr, level.dateRanges[dateRangeAttr.ID], level.dateRangeTagCount);
  7910. level.dateRangeTagCount++;
  7911. if (dateRange.isValid || level.skippedSegments) {
  7912. level.dateRanges[dateRange.id] = dateRange;
  7913. } else {
  7914. logger.warn("Ignoring invalid DATERANGE tag: \"" + value1 + "\"");
  7915. }
  7916. // Add to fragment tag list for backwards compatibility (< v1.2.0)
  7917. frag.tagList.push(['EXT-X-DATERANGE', value1]);
  7918. break;
  7919. }
  7920. case 'DEFINE':
  7921. {
  7922. {
  7923. var variableAttributes = new AttrList(value1, level);
  7924. if ('IMPORT' in variableAttributes) {
  7925. importVariableDefinition(level, variableAttributes, multivariantVariableList);
  7926. } else {
  7927. addVariableDefinition(level, variableAttributes, baseurl);
  7928. }
  7929. }
  7930. break;
  7931. }
  7932. case 'DISCONTINUITY-SEQUENCE':
  7933. if (level.startCC !== 0) {
  7934. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  7935. } else if (fragments.length > 0) {
  7936. assignMustAppearBeforeSegmentsError(level, tag, result);
  7937. }
  7938. level.startCC = discontinuityCounter = parseInt(value1);
  7939. break;
  7940. case 'KEY':
  7941. {
  7942. var levelKey = parseKey(value1, baseurl, level);
  7943. if (levelKey.isSupported()) {
  7944. if (levelKey.method === 'NONE') {
  7945. levelkeys = undefined;
  7946. break;
  7947. }
  7948. if (!levelkeys) {
  7949. levelkeys = {};
  7950. }
  7951. var currentKey = levelkeys[levelKey.keyFormat];
  7952. // Ignore duplicate playlist KEY tags
  7953. if (!(currentKey != null && currentKey.matches(levelKey))) {
  7954. if (currentKey) {
  7955. levelkeys = _extends({}, levelkeys);
  7956. }
  7957. levelkeys[levelKey.keyFormat] = levelKey;
  7958. }
  7959. } else {
  7960. logger.warn("[Keys] Ignoring invalid EXT-X-KEY tag: \"" + value1 + "\"");
  7961. }
  7962. break;
  7963. }
  7964. case 'START':
  7965. level.startTimeOffset = parseStartTimeOffset(value1);
  7966. break;
  7967. case 'MAP':
  7968. {
  7969. var mapAttrs = new AttrList(value1, level);
  7970. if (frag.duration) {
  7971. // Initial segment tag is after segment duration tag.
  7972. // #EXTINF: 6.0
  7973. // #EXT-X-MAP:URI="init.mp4
  7974. var init = new Fragment(type, base);
  7975. setInitSegment(init, mapAttrs, id, levelkeys);
  7976. currentInitSegment = init;
  7977. frag.initSegment = currentInitSegment;
  7978. if (currentInitSegment.rawProgramDateTime && !frag.rawProgramDateTime) {
  7979. frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
  7980. }
  7981. } else {
  7982. // Initial segment tag is before segment duration tag
  7983. // Handle case where EXT-X-MAP is declared after EXT-X-BYTERANGE
  7984. var end = frag.byteRangeEndOffset;
  7985. if (end) {
  7986. var start = frag.byteRangeStartOffset;
  7987. nextByteRange = end - start + "@" + start;
  7988. } else {
  7989. nextByteRange = null;
  7990. }
  7991. setInitSegment(frag, mapAttrs, id, levelkeys);
  7992. currentInitSegment = frag;
  7993. createNextFrag = true;
  7994. }
  7995. currentInitSegment.cc = discontinuityCounter;
  7996. break;
  7997. }
  7998. case 'SERVER-CONTROL':
  7999. {
  8000. if (serverControlAttrs) {
  8001. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  8002. }
  8003. serverControlAttrs = new AttrList(value1);
  8004. level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
  8005. level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
  8006. level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
  8007. level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
  8008. level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
  8009. break;
  8010. }
  8011. case 'PART-INF':
  8012. {
  8013. if (level.partTarget) {
  8014. assignMultipleMediaPlaylistTagOccuranceError(level, tag, result);
  8015. }
  8016. var partInfAttrs = new AttrList(value1);
  8017. level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
  8018. break;
  8019. }
  8020. case 'PART':
  8021. {
  8022. var partList = level.partList;
  8023. if (!partList) {
  8024. partList = level.partList = [];
  8025. }
  8026. var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
  8027. var index = currentPart++;
  8028. var partAttrs = new AttrList(value1, level);
  8029. var part = new Part(partAttrs, frag, base, index, previousFragmentPart);
  8030. partList.push(part);
  8031. frag.duration += part.duration;
  8032. break;
  8033. }
  8034. case 'PRELOAD-HINT':
  8035. {
  8036. var preloadHintAttrs = new AttrList(value1, level);
  8037. level.preloadHint = preloadHintAttrs;
  8038. break;
  8039. }
  8040. case 'RENDITION-REPORT':
  8041. {
  8042. var renditionReportAttrs = new AttrList(value1, level);
  8043. level.renditionReports = level.renditionReports || [];
  8044. level.renditionReports.push(renditionReportAttrs);
  8045. break;
  8046. }
  8047. default:
  8048. logger.warn("line parsed but not handled: " + result);
  8049. break;
  8050. }
  8051. }
  8052. }
  8053. if (prevFrag && !prevFrag.relurl) {
  8054. fragments.pop();
  8055. totalduration -= prevFrag.duration;
  8056. if (level.partList) {
  8057. level.fragmentHint = prevFrag;
  8058. }
  8059. } else if (level.partList) {
  8060. assignProgramDateTime(frag, prevFrag, programDateTimes);
  8061. frag.cc = discontinuityCounter;
  8062. level.fragmentHint = frag;
  8063. if (levelkeys) {
  8064. setFragLevelKeys(frag, levelkeys, level);
  8065. }
  8066. }
  8067. if (!level.targetduration) {
  8068. level.playlistParsingError = new Error("#EXT-X-TARGETDURATION is required");
  8069. }
  8070. var fragmentLength = fragments.length;
  8071. var firstFragment = fragments[0];
  8072. var lastFragment = fragments[fragmentLength - 1];
  8073. totalduration += level.skippedSegments * level.targetduration;
  8074. if (totalduration > 0 && fragmentLength && lastFragment) {
  8075. level.averagetargetduration = totalduration / fragmentLength;
  8076. var lastSn = lastFragment.sn;
  8077. level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
  8078. if (!level.live) {
  8079. lastFragment.endList = true;
  8080. }
  8081. if (firstFragment && level.startCC === undefined) {
  8082. level.startCC = firstFragment.cc;
  8083. }
  8084. /**
  8085. * Backfill any missing PDT values
  8086. * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  8087. * one or more Media Segment URIs, the client SHOULD extrapolate
  8088. * backward from that tag (using EXTINF durations and/or media
  8089. * timestamps) to associate dates with those segments."
  8090. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  8091. * computed.
  8092. */
  8093. if (firstPdtIndex > 0) {
  8094. backfillProgramDateTimes(fragments, firstPdtIndex);
  8095. if (firstFragment) {
  8096. programDateTimes.unshift(firstFragment);
  8097. }
  8098. }
  8099. } else {
  8100. level.endSN = 0;
  8101. level.startCC = 0;
  8102. }
  8103. if (level.fragmentHint) {
  8104. totalduration += level.fragmentHint.duration;
  8105. }
  8106. level.totalduration = totalduration;
  8107. if (programDateTimes.length && level.dateRangeTagCount && firstFragment) {
  8108. mapDateRanges(programDateTimes, level);
  8109. }
  8110. level.endCC = discontinuityCounter;
  8111. return level;
  8112. };
  8113. return M3U8Parser;
  8114. }();
  8115. function mapDateRanges(programDateTimes, details) {
  8116. // Make sure DateRanges are mapped to a ProgramDateTime tag that applies a date to a segment that overlaps with its start date
  8117. var programDateTimeCount = programDateTimes.length;
  8118. if (!programDateTimeCount) {
  8119. return;
  8120. }
  8121. var lastProgramDateTime = programDateTimes[programDateTimeCount - 1];
  8122. var playlistEnd = details.live ? Infinity : details.totalduration;
  8123. var dateRangeIds = Object.keys(details.dateRanges);
  8124. for (var i = dateRangeIds.length; i--;) {
  8125. var dateRange = details.dateRanges[dateRangeIds[i]];
  8126. var startDateTime = dateRange.startDate.getTime();
  8127. dateRange.tagAnchor = lastProgramDateTime.ref;
  8128. for (var j = programDateTimeCount; j--;) {
  8129. var fragIndex = findFragmentWithStartDate(details, startDateTime, programDateTimes, j, playlistEnd);
  8130. if (fragIndex !== -1) {
  8131. dateRange.tagAnchor = details.fragments[fragIndex].ref;
  8132. break;
  8133. }
  8134. }
  8135. }
  8136. }
  8137. function findFragmentWithStartDate(details, startDateTime, programDateTimes, index, endTime) {
  8138. var pdtFragment = programDateTimes[index];
  8139. if (pdtFragment) {
  8140. // find matching range between PDT tags
  8141. var pdtStart = pdtFragment.programDateTime;
  8142. if (startDateTime >= pdtStart || index === 0) {
  8143. var _programDateTimes;
  8144. var durationBetweenPdt = (((_programDateTimes = programDateTimes[index + 1]) == null ? void 0 : _programDateTimes.start) || endTime) - pdtFragment.start;
  8145. if (startDateTime <= pdtStart + durationBetweenPdt * 1000) {
  8146. // map to fragment with date-time range
  8147. var startIndex = programDateTimes[index].sn - details.startSN;
  8148. var fragments = details.fragments;
  8149. if (fragments.length > programDateTimes.length) {
  8150. var endSegment = programDateTimes[index + 1] || fragments[fragments.length - 1];
  8151. var endIndex = endSegment.sn - details.startSN;
  8152. for (var i = endIndex; i > startIndex; i--) {
  8153. var fragStartDateTime = fragments[i].programDateTime;
  8154. if (startDateTime >= fragStartDateTime && startDateTime < fragStartDateTime + fragments[i].duration * 1000) {
  8155. return i;
  8156. }
  8157. }
  8158. }
  8159. return startIndex;
  8160. }
  8161. }
  8162. }
  8163. return -1;
  8164. }
  8165. function parseKey(keyTagAttributes, baseurl, parsed) {
  8166. var _keyAttrs$METHOD, _keyAttrs$KEYFORMAT;
  8167. // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
  8168. var keyAttrs = new AttrList(keyTagAttributes, parsed);
  8169. var decryptmethod = (_keyAttrs$METHOD = keyAttrs.METHOD) != null ? _keyAttrs$METHOD : '';
  8170. var decrypturi = keyAttrs.URI;
  8171. var decryptiv = keyAttrs.hexadecimalInteger('IV');
  8172. var decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;
  8173. // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
  8174. var decryptkeyformat = (_keyAttrs$KEYFORMAT = keyAttrs.KEYFORMAT) != null ? _keyAttrs$KEYFORMAT : 'identity';
  8175. if (decrypturi && keyAttrs.IV && !decryptiv) {
  8176. logger.error("Invalid IV: " + keyAttrs.IV);
  8177. }
  8178. // If decrypturi is a URI with a scheme, then baseurl will be ignored
  8179. // No uri is allowed when METHOD is NONE
  8180. var resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';
  8181. var keyFormatVersions = (decryptkeyformatversions ? decryptkeyformatversions : '1').split('/').map(Number).filter(Number.isFinite);
  8182. return new LevelKey(decryptmethod, resolvedUri, decryptkeyformat, keyFormatVersions, decryptiv, keyAttrs.KEYID);
  8183. }
  8184. function parseStartTimeOffset(startAttributes) {
  8185. var startAttrs = new AttrList(startAttributes);
  8186. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  8187. if (isFiniteNumber(startTimeOffset)) {
  8188. return startTimeOffset;
  8189. }
  8190. return null;
  8191. }
  8192. function setCodecs(codecsAttributeValue, level) {
  8193. var codecs = (codecsAttributeValue || '').split(/[ ,]+/).filter(function (c) {
  8194. return c;
  8195. });
  8196. ['video', 'audio', 'text'].forEach(function (type) {
  8197. var filtered = codecs.filter(function (codec) {
  8198. return isCodecType(codec, type);
  8199. });
  8200. if (filtered.length) {
  8201. // Comma separated list of all codecs for type
  8202. level[type + "Codec"] = filtered.map(function (c) {
  8203. return c.split('/')[0];
  8204. }).join(',');
  8205. // Remove known codecs so that only unknownCodecs are left after iterating through each type
  8206. codecs = codecs.filter(function (codec) {
  8207. return filtered.indexOf(codec) === -1;
  8208. });
  8209. }
  8210. });
  8211. level.unknownCodecs = codecs;
  8212. }
  8213. function assignCodec(media, groupItem, codecProperty) {
  8214. var codecValue = groupItem[codecProperty];
  8215. if (codecValue) {
  8216. media[codecProperty] = codecValue;
  8217. }
  8218. }
  8219. function backfillProgramDateTimes(fragments, firstPdtIndex) {
  8220. var fragPrev = fragments[firstPdtIndex];
  8221. for (var i = firstPdtIndex; i--;) {
  8222. var frag = fragments[i];
  8223. // Exit on delta-playlist skipped segments
  8224. if (!frag) {
  8225. return;
  8226. }
  8227. frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
  8228. fragPrev = frag;
  8229. }
  8230. }
  8231. function assignProgramDateTime(frag, prevFrag, programDateTimes) {
  8232. if (frag.rawProgramDateTime) {
  8233. programDateTimes.push(frag);
  8234. } else if (prevFrag != null && prevFrag.programDateTime) {
  8235. frag.programDateTime = prevFrag.endProgramDateTime;
  8236. }
  8237. }
  8238. function setInitSegment(frag, mapAttrs, id, levelkeys) {
  8239. frag.relurl = mapAttrs.URI;
  8240. if (mapAttrs.BYTERANGE) {
  8241. frag.setByteRange(mapAttrs.BYTERANGE);
  8242. }
  8243. frag.level = id;
  8244. frag.sn = 'initSegment';
  8245. if (levelkeys) {
  8246. frag.levelkeys = levelkeys;
  8247. }
  8248. frag.initSegment = null;
  8249. }
  8250. function setFragLevelKeys(frag, levelkeys, level) {
  8251. frag.levelkeys = levelkeys;
  8252. var encryptedFragments = level.encryptedFragments;
  8253. if ((!encryptedFragments.length || encryptedFragments[encryptedFragments.length - 1].levelkeys !== levelkeys) && Object.keys(levelkeys).some(function (format) {
  8254. return levelkeys[format].isCommonEncryption;
  8255. })) {
  8256. encryptedFragments.push(frag);
  8257. }
  8258. }
  8259. function assignMultipleMediaPlaylistTagOccuranceError(level, tag, result) {
  8260. level.playlistParsingError = new Error("#EXT-X-" + tag + " must not appear more than once (" + result[0] + ")");
  8261. }
  8262. function assignMustAppearBeforeSegmentsError(level, tag, result) {
  8263. level.playlistParsingError = new Error("#EXT-X-" + tag + " must appear before the first Media Segment (" + result[0] + ")");
  8264. }
  8265. function updateFromToPTS(fragFrom, fragTo) {
  8266. var fragToPTS = fragTo.startPTS;
  8267. // if we know startPTS[toIdx]
  8268. if (isFiniteNumber(fragToPTS)) {
  8269. // update fragment duration.
  8270. // it helps to fix drifts between playlist reported duration and fragment real duration
  8271. var duration = 0;
  8272. var frag;
  8273. if (fragTo.sn > fragFrom.sn) {
  8274. duration = fragToPTS - fragFrom.start;
  8275. frag = fragFrom;
  8276. } else {
  8277. duration = fragFrom.start - fragToPTS;
  8278. frag = fragTo;
  8279. }
  8280. if (frag.duration !== duration) {
  8281. frag.setDuration(duration);
  8282. }
  8283. // we dont know startPTS[toIdx]
  8284. } else if (fragTo.sn > fragFrom.sn) {
  8285. var contiguous = fragFrom.cc === fragTo.cc;
  8286. // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
  8287. if (contiguous && fragFrom.minEndPTS) {
  8288. fragTo.setStart(fragFrom.start + (fragFrom.minEndPTS - fragFrom.start));
  8289. } else {
  8290. fragTo.setStart(fragFrom.start + fragFrom.duration);
  8291. }
  8292. } else {
  8293. fragTo.setStart(Math.max(fragFrom.start - fragTo.duration, 0));
  8294. }
  8295. }
  8296. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  8297. var parsedMediaDuration = endPTS - startPTS;
  8298. if (parsedMediaDuration <= 0) {
  8299. logger.warn('Fragment should have a positive duration', frag);
  8300. endPTS = startPTS + frag.duration;
  8301. endDTS = startDTS + frag.duration;
  8302. }
  8303. var maxStartPTS = startPTS;
  8304. var minEndPTS = endPTS;
  8305. var fragStartPts = frag.startPTS;
  8306. var fragEndPts = frag.endPTS;
  8307. if (isFiniteNumber(fragStartPts)) {
  8308. // delta PTS between audio and video
  8309. var deltaPTS = Math.abs(fragStartPts - startPTS);
  8310. if (!isFiniteNumber(frag.deltaPTS)) {
  8311. frag.deltaPTS = deltaPTS;
  8312. } else {
  8313. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  8314. }
  8315. maxStartPTS = Math.max(startPTS, fragStartPts);
  8316. startPTS = Math.min(startPTS, fragStartPts);
  8317. startDTS = Math.min(startDTS, frag.startDTS);
  8318. minEndPTS = Math.min(endPTS, fragEndPts);
  8319. endPTS = Math.max(endPTS, fragEndPts);
  8320. endDTS = Math.max(endDTS, frag.endDTS);
  8321. }
  8322. var drift = startPTS - frag.start;
  8323. if (frag.start !== 0) {
  8324. frag.setStart(startPTS);
  8325. }
  8326. frag.setDuration(endPTS - frag.start);
  8327. frag.startPTS = startPTS;
  8328. frag.maxStartPTS = maxStartPTS;
  8329. frag.startDTS = startDTS;
  8330. frag.endPTS = endPTS;
  8331. frag.minEndPTS = minEndPTS;
  8332. frag.endDTS = endDTS;
  8333. var sn = frag.sn;
  8334. // exit if sn out of range
  8335. if (!details || sn < details.startSN || sn > details.endSN) {
  8336. return 0;
  8337. }
  8338. var i;
  8339. var fragIdx = sn - details.startSN;
  8340. var fragments = details.fragments;
  8341. // update frag reference in fragments array
  8342. // rationale is that fragments array might not contain this frag object.
  8343. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  8344. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  8345. // resulting in invalid sliding computation
  8346. fragments[fragIdx] = frag;
  8347. // adjust fragment PTS/duration from seqnum-1 to frag 0
  8348. for (i = fragIdx; i > 0; i--) {
  8349. updateFromToPTS(fragments[i], fragments[i - 1]);
  8350. }
  8351. // adjust fragment PTS/duration from seqnum to last frag
  8352. for (i = fragIdx; i < fragments.length - 1; i++) {
  8353. updateFromToPTS(fragments[i], fragments[i + 1]);
  8354. }
  8355. if (details.fragmentHint) {
  8356. updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
  8357. }
  8358. details.PTSKnown = details.alignedSliding = true;
  8359. return drift;
  8360. }
  8361. function mergeDetails(oldDetails, newDetails) {
  8362. if (oldDetails === newDetails) {
  8363. return;
  8364. }
  8365. // Track the last initSegment processed. Initialize it to the last one on the timeline.
  8366. var currentInitSegment = null;
  8367. var oldFragments = oldDetails.fragments;
  8368. for (var i = oldFragments.length - 1; i >= 0; i--) {
  8369. var oldInit = oldFragments[i].initSegment;
  8370. if (oldInit) {
  8371. currentInitSegment = oldInit;
  8372. break;
  8373. }
  8374. }
  8375. if (oldDetails.fragmentHint) {
  8376. // prevent PTS and duration from being adjusted on the next hint
  8377. delete oldDetails.fragmentHint.endPTS;
  8378. }
  8379. // check if old/new playlists have fragments in common
  8380. // loop through overlapping SN and update startPTS, cc, and duration if any found
  8381. var PTSFrag;
  8382. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag, newFragIndex, newFragments) {
  8383. if ((!newDetails.startCC || newDetails.skippedSegments) && newFrag.cc !== oldFrag.cc) {
  8384. var ccOffset = oldFrag.cc - newFrag.cc;
  8385. for (var _i = newFragIndex; _i < newFragments.length; _i++) {
  8386. newFragments[_i].cc += ccOffset;
  8387. }
  8388. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  8389. }
  8390. if (isFiniteNumber(oldFrag.startPTS) && isFiniteNumber(oldFrag.endPTS)) {
  8391. newFrag.setStart(newFrag.startPTS = oldFrag.startPTS);
  8392. newFrag.startDTS = oldFrag.startDTS;
  8393. newFrag.maxStartPTS = oldFrag.maxStartPTS;
  8394. newFrag.endPTS = oldFrag.endPTS;
  8395. newFrag.endDTS = oldFrag.endDTS;
  8396. newFrag.minEndPTS = oldFrag.minEndPTS;
  8397. newFrag.setDuration(oldFrag.endPTS - oldFrag.startPTS);
  8398. if (newFrag.duration) {
  8399. PTSFrag = newFrag;
  8400. }
  8401. // PTS is known when any segment has startPTS and endPTS
  8402. newDetails.PTSKnown = newDetails.alignedSliding = true;
  8403. }
  8404. if (oldFrag.hasStreams) {
  8405. newFrag.elementaryStreams = oldFrag.elementaryStreams;
  8406. }
  8407. newFrag.loader = oldFrag.loader;
  8408. if (oldFrag.hasStats) {
  8409. newFrag.stats = oldFrag.stats;
  8410. }
  8411. if (oldFrag.initSegment) {
  8412. newFrag.initSegment = oldFrag.initSegment;
  8413. currentInitSegment = oldFrag.initSegment;
  8414. }
  8415. });
  8416. var newFragments = newDetails.fragments;
  8417. var fragmentsToCheck = newDetails.fragmentHint ? newFragments.concat(newDetails.fragmentHint) : newFragments;
  8418. if (currentInitSegment) {
  8419. fragmentsToCheck.forEach(function (frag) {
  8420. var _currentInitSegment;
  8421. if (frag && (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) == null ? void 0 : _currentInitSegment.relurl))) {
  8422. frag.initSegment = currentInitSegment;
  8423. }
  8424. });
  8425. }
  8426. if (newDetails.skippedSegments) {
  8427. newDetails.deltaUpdateFailed = newFragments.some(function (frag) {
  8428. return !frag;
  8429. });
  8430. if (newDetails.deltaUpdateFailed) {
  8431. logger.warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
  8432. for (var _i2 = newDetails.skippedSegments; _i2--;) {
  8433. newFragments.shift();
  8434. }
  8435. newDetails.startSN = newFragments[0].sn;
  8436. } else {
  8437. if (newDetails.canSkipDateRanges) {
  8438. newDetails.dateRanges = mergeDateRanges(oldDetails.dateRanges, newDetails);
  8439. }
  8440. var programDateTimes = oldDetails.fragments.filter(function (frag) {
  8441. return frag.rawProgramDateTime;
  8442. });
  8443. if (oldDetails.hasProgramDateTime && !newDetails.hasProgramDateTime) {
  8444. for (var _i3 = 1; _i3 < fragmentsToCheck.length; _i3++) {
  8445. if (fragmentsToCheck[_i3].programDateTime === null) {
  8446. assignProgramDateTime(fragmentsToCheck[_i3], fragmentsToCheck[_i3 - 1], programDateTimes);
  8447. }
  8448. }
  8449. }
  8450. mapDateRanges(programDateTimes, newDetails);
  8451. }
  8452. newDetails.endCC = newFragments[newFragments.length - 1].cc;
  8453. }
  8454. if (!newDetails.startCC) {
  8455. var _fragPriorToNewStart$;
  8456. var fragPriorToNewStart = getFragmentWithSN(oldDetails, newDetails.startSN - 1);
  8457. newDetails.startCC = (_fragPriorToNewStart$ = fragPriorToNewStart == null ? void 0 : fragPriorToNewStart.cc) != null ? _fragPriorToNewStart$ : newFragments[0].cc;
  8458. }
  8459. // Merge parts
  8460. mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
  8461. newPart.elementaryStreams = oldPart.elementaryStreams;
  8462. newPart.stats = oldPart.stats;
  8463. });
  8464. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  8465. if (PTSFrag) {
  8466. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  8467. } else {
  8468. // ensure that delta is within oldFragments range
  8469. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  8470. // in that case we also need to adjust start offset of all fragments
  8471. adjustSliding(oldDetails, newDetails);
  8472. }
  8473. if (newFragments.length) {
  8474. newDetails.totalduration = newDetails.edge - newFragments[0].start;
  8475. }
  8476. newDetails.driftStartTime = oldDetails.driftStartTime;
  8477. newDetails.driftStart = oldDetails.driftStart;
  8478. var advancedDateTime = newDetails.advancedDateTime;
  8479. if (newDetails.advanced && advancedDateTime) {
  8480. var edge = newDetails.edge;
  8481. if (!newDetails.driftStart) {
  8482. newDetails.driftStartTime = advancedDateTime;
  8483. newDetails.driftStart = edge;
  8484. }
  8485. newDetails.driftEndTime = advancedDateTime;
  8486. newDetails.driftEnd = edge;
  8487. } else {
  8488. newDetails.driftEndTime = oldDetails.driftEndTime;
  8489. newDetails.driftEnd = oldDetails.driftEnd;
  8490. newDetails.advancedDateTime = oldDetails.advancedDateTime;
  8491. }
  8492. if (newDetails.requestScheduled === -1) {
  8493. newDetails.requestScheduled = oldDetails.requestScheduled;
  8494. }
  8495. }
  8496. function mergeDateRanges(oldDateRanges, newDetails) {
  8497. var deltaDateRanges = newDetails.dateRanges,
  8498. recentlyRemovedDateranges = newDetails.recentlyRemovedDateranges;
  8499. var dateRanges = _extends({}, oldDateRanges);
  8500. if (recentlyRemovedDateranges) {
  8501. recentlyRemovedDateranges.forEach(function (id) {
  8502. delete dateRanges[id];
  8503. });
  8504. }
  8505. var mergeIds = Object.keys(dateRanges);
  8506. var mergeCount = mergeIds.length;
  8507. if (mergeCount) {
  8508. Object.keys(deltaDateRanges).forEach(function (id) {
  8509. var mergedDateRange = dateRanges[id];
  8510. var dateRange = new DateRange(deltaDateRanges[id].attr, mergedDateRange);
  8511. if (dateRange.isValid) {
  8512. dateRanges[id] = dateRange;
  8513. if (!mergedDateRange) {
  8514. dateRange.tagOrder += mergeCount;
  8515. }
  8516. } else {
  8517. logger.warn("Ignoring invalid Playlist Delta Update DATERANGE tag: \"" + stringify(deltaDateRanges[id].attr) + "\"");
  8518. }
  8519. });
  8520. }
  8521. return dateRanges;
  8522. }
  8523. function mapPartIntersection(oldParts, newParts, intersectionFn) {
  8524. if (oldParts && newParts) {
  8525. var delta = 0;
  8526. for (var i = 0, len = oldParts.length; i <= len; i++) {
  8527. var _oldPart = oldParts[i];
  8528. var _newPart = newParts[i + delta];
  8529. if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
  8530. intersectionFn(_oldPart, _newPart);
  8531. } else {
  8532. delta--;
  8533. }
  8534. }
  8535. }
  8536. }
  8537. function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
  8538. var skippedSegments = newDetails.skippedSegments;
  8539. var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
  8540. var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
  8541. var delta = newDetails.startSN - oldDetails.startSN;
  8542. var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
  8543. var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
  8544. for (var i = start; i <= end; i++) {
  8545. var _oldFrag = oldFrags[delta + i];
  8546. var _newFrag = newFrags[i];
  8547. if (skippedSegments && !_newFrag && _oldFrag) {
  8548. // Fill in skipped segments in delta playlist
  8549. _newFrag = newDetails.fragments[i] = _oldFrag;
  8550. }
  8551. if (_oldFrag && _newFrag) {
  8552. intersectionFn(_oldFrag, _newFrag, i, newFrags);
  8553. if (_oldFrag.url && _oldFrag.url !== _newFrag.url) {
  8554. newDetails.playlistParsingError = getSequenceError("media sequence mismatch " + _newFrag.sn + ":", oldDetails, newDetails, _oldFrag, _newFrag);
  8555. return;
  8556. } else if (_oldFrag.cc !== _newFrag.cc) {
  8557. newDetails.playlistParsingError = getSequenceError("discontinuity sequence mismatch (" + _oldFrag.cc + "!=" + _newFrag.cc + ")", oldDetails, newDetails, _oldFrag, _newFrag);
  8558. return;
  8559. }
  8560. }
  8561. }
  8562. }
  8563. function getSequenceError(message, oldDetails, newDetails, oldFrag, newFrag) {
  8564. return new Error(message + " " + newFrag.url + "\nPlaylist starting @" + oldDetails.startSN + "\n" + oldDetails.m3u8 + "\n\nPlaylist starting @" + newDetails.startSN + "\n" + newDetails.m3u8);
  8565. }
  8566. function adjustSliding(oldDetails, newDetails, matchingStableVariantOrRendition) {
  8567. if (matchingStableVariantOrRendition === void 0) {
  8568. matchingStableVariantOrRendition = true;
  8569. }
  8570. var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
  8571. var oldFragments = oldDetails.fragments;
  8572. var advancedOrStable = delta >= 0;
  8573. var sliding = 0;
  8574. if (advancedOrStable && delta < oldFragments.length) {
  8575. sliding = oldFragments[delta].start;
  8576. } else if (advancedOrStable && newDetails.startSN === oldDetails.endSN + 1) {
  8577. sliding = oldDetails.fragmentEnd;
  8578. } else if (advancedOrStable && matchingStableVariantOrRendition) {
  8579. // align with expected position (updated playlist start sequence is past end sequence of last update)
  8580. sliding = oldDetails.fragmentStart + delta * newDetails.levelTargetDuration;
  8581. } else if (!newDetails.skippedSegments && newDetails.fragmentStart === 0) {
  8582. // align new start with old (playlist switch has a sequence with no overlap and should not be used for alignment)
  8583. sliding = oldDetails.fragmentStart;
  8584. } else {
  8585. // new details already has a sliding offset or has skipped segments
  8586. return;
  8587. }
  8588. addSliding(newDetails, sliding);
  8589. }
  8590. function addSliding(details, sliding) {
  8591. if (sliding) {
  8592. var fragments = details.fragments;
  8593. for (var i = details.skippedSegments; i < fragments.length; i++) {
  8594. fragments[i].addStart(sliding);
  8595. }
  8596. if (details.fragmentHint) {
  8597. details.fragmentHint.addStart(sliding);
  8598. }
  8599. }
  8600. }
  8601. function computeReloadInterval(newDetails, distanceToLiveEdgeMs) {
  8602. if (distanceToLiveEdgeMs === void 0) {
  8603. distanceToLiveEdgeMs = Infinity;
  8604. }
  8605. var reloadInterval = 1000 * newDetails.targetduration;
  8606. if (newDetails.updated) {
  8607. // Use last segment duration when shorter than target duration and near live edge
  8608. var fragments = newDetails.fragments;
  8609. var liveEdgeMaxTargetDurations = 4;
  8610. if (fragments.length && reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs) {
  8611. var lastSegmentDuration = fragments[fragments.length - 1].duration * 1000;
  8612. if (lastSegmentDuration < reloadInterval) {
  8613. reloadInterval = lastSegmentDuration;
  8614. }
  8615. }
  8616. } else {
  8617. // estimate = 'miss half average';
  8618. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  8619. // changed then it MUST wait for a period of one-half the target
  8620. // duration before retrying.
  8621. reloadInterval /= 2;
  8622. }
  8623. return Math.round(reloadInterval);
  8624. }
  8625. function getFragmentWithSN(details, sn, fragCurrent) {
  8626. if (!details) {
  8627. return null;
  8628. }
  8629. var fragment = details.fragments[sn - details.startSN];
  8630. if (fragment) {
  8631. return fragment;
  8632. }
  8633. fragment = details.fragmentHint;
  8634. if (fragment && fragment.sn === sn) {
  8635. return fragment;
  8636. }
  8637. if (sn < details.startSN && fragCurrent && fragCurrent.sn === sn) {
  8638. return fragCurrent;
  8639. }
  8640. return null;
  8641. }
  8642. function getPartWith(details, sn, partIndex) {
  8643. if (!details) {
  8644. return null;
  8645. }
  8646. return findPart(details.partList, sn, partIndex);
  8647. }
  8648. function findPart(partList, sn, partIndex) {
  8649. if (partList) {
  8650. for (var i = partList.length; i--;) {
  8651. var part = partList[i];
  8652. if (part.index === partIndex && part.fragment.sn === sn) {
  8653. return part;
  8654. }
  8655. }
  8656. }
  8657. return null;
  8658. }
  8659. function reassignFragmentLevelIndexes(levels) {
  8660. levels.forEach(function (level, index) {
  8661. var _level$details;
  8662. (_level$details = level.details) == null ? void 0 : _level$details.fragments.forEach(function (fragment) {
  8663. fragment.level = index;
  8664. if (fragment.initSegment) {
  8665. fragment.initSegment.level = index;
  8666. }
  8667. });
  8668. });
  8669. }
  8670. function findFirstFragWithCC(fragments, cc) {
  8671. for (var i = 0, len = fragments.length; i < len; i++) {
  8672. var _fragments$i;
  8673. if (((_fragments$i = fragments[i]) == null ? void 0 : _fragments$i.cc) === cc) {
  8674. return fragments[i];
  8675. }
  8676. }
  8677. return null;
  8678. }
  8679. function shouldAlignOnDiscontinuities(refDetails, details) {
  8680. if (refDetails) {
  8681. if (details.startCC < refDetails.endCC && details.endCC > refDetails.startCC) {
  8682. return true;
  8683. }
  8684. }
  8685. return false;
  8686. }
  8687. function adjustFragmentStart(frag, sliding) {
  8688. if (frag) {
  8689. var start = frag.start + sliding;
  8690. frag.start = frag.startPTS = start;
  8691. frag.endPTS = start + frag.duration;
  8692. }
  8693. }
  8694. function adjustSlidingStart(sliding, details) {
  8695. // Update segments
  8696. var fragments = details.fragments;
  8697. for (var i = 0, len = fragments.length; i < len; i++) {
  8698. adjustFragmentStart(fragments[i], sliding);
  8699. }
  8700. // Update LL-HLS parts at the end of the playlist
  8701. if (details.fragmentHint) {
  8702. adjustFragmentStart(details.fragmentHint, sliding);
  8703. }
  8704. details.alignedSliding = true;
  8705. }
  8706. /**
  8707. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  8708. * contiguous stream with the last fragments.
  8709. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  8710. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  8711. * and an extra download.
  8712. * @param lastLevel
  8713. * @param details
  8714. */
  8715. function alignStream(switchDetails, details) {
  8716. if (!switchDetails) {
  8717. return;
  8718. }
  8719. alignDiscontinuities(details, switchDetails);
  8720. if (!details.alignedSliding && switchDetails) {
  8721. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  8722. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  8723. // discontinuity sequence.
  8724. alignMediaPlaylistByPDT(details, switchDetails);
  8725. }
  8726. if (!details.alignedSliding && switchDetails && !details.skippedSegments) {
  8727. // Try to align on sn so that we pick a better start fragment.
  8728. // Do not perform this on playlists with delta updates as this is only to align levels on switch
  8729. // and adjustSliding only adjusts fragments after skippedSegments.
  8730. adjustSliding(switchDetails, details, false);
  8731. }
  8732. }
  8733. /**
  8734. * Ajust the start of fragments in `details` by the difference in time between fragments of the latest
  8735. * shared discontinuity sequence change.
  8736. * @param lastLevel - The details of the last loaded level
  8737. * @param details - The details of the new level
  8738. */
  8739. function alignDiscontinuities(details, refDetails) {
  8740. if (!shouldAlignOnDiscontinuities(refDetails, details)) {
  8741. return;
  8742. }
  8743. var targetCC = Math.min(refDetails.endCC, details.endCC);
  8744. var refFrag = findFirstFragWithCC(refDetails.fragments, targetCC);
  8745. var frag = findFirstFragWithCC(details.fragments, targetCC);
  8746. if (!refFrag || !frag) {
  8747. return;
  8748. }
  8749. logger.log("Aligning playlist at start of dicontinuity sequence " + targetCC);
  8750. var delta = refFrag.start - frag.start;
  8751. adjustSlidingStart(delta, details);
  8752. }
  8753. /**
  8754. * Ensures appropriate time-alignment between renditions based on PDT.
  8755. * This function assumes the timelines represented in `refDetails` are accurate, including the PDTs
  8756. * for the last discontinuity sequence number shared by both playlists when present,
  8757. * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
  8758. * times/timelines of `details` accordingly.
  8759. * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
  8760. * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
  8761. * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
  8762. * be consistent across playlists, per the HLS spec.
  8763. * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
  8764. * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
  8765. */
  8766. function alignMediaPlaylistByPDT(details, refDetails) {
  8767. if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
  8768. return;
  8769. }
  8770. var fragments = details.fragments;
  8771. var refFragments = refDetails.fragments;
  8772. if (!fragments.length || !refFragments.length) {
  8773. return;
  8774. }
  8775. // Calculate a delta to apply to all fragments according to the delta in PDT times and start times
  8776. // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.
  8777. // If a fragment of the same discontinuity was not found use the middle fragment of both.
  8778. var refFrag;
  8779. var frag;
  8780. var targetCC = Math.min(refDetails.endCC, details.endCC);
  8781. if (refDetails.startCC < targetCC && details.startCC < targetCC) {
  8782. refFrag = findFirstFragWithCC(refFragments, targetCC);
  8783. frag = findFirstFragWithCC(fragments, targetCC);
  8784. }
  8785. if (!refFrag || !frag) {
  8786. refFrag = refFragments[Math.floor(refFragments.length / 2)];
  8787. frag = findFirstFragWithCC(fragments, refFrag.cc) || fragments[Math.floor(fragments.length / 2)];
  8788. }
  8789. var refPDT = refFrag.programDateTime;
  8790. var targetPDT = frag.programDateTime;
  8791. if (!refPDT || !targetPDT) {
  8792. return;
  8793. }
  8794. var delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);
  8795. adjustSlidingStart(delta, details);
  8796. }
  8797. /**
  8798. * TimeRanges to string helper
  8799. */
  8800. var TimeRanges = {
  8801. toString: function toString(r) {
  8802. var log = '';
  8803. var len = r.length;
  8804. for (var i = 0; i < len; i++) {
  8805. log += "[" + r.start(i).toFixed(3) + "-" + r.end(i).toFixed(3) + "]";
  8806. }
  8807. return log;
  8808. }
  8809. };
  8810. var State = {
  8811. STOPPED: 'STOPPED',
  8812. IDLE: 'IDLE',
  8813. KEY_LOADING: 'KEY_LOADING',
  8814. FRAG_LOADING: 'FRAG_LOADING',
  8815. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  8816. WAITING_TRACK: 'WAITING_TRACK',
  8817. PARSING: 'PARSING',
  8818. PARSED: 'PARSED',
  8819. ENDED: 'ENDED',
  8820. ERROR: 'ERROR',
  8821. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  8822. WAITING_LEVEL: 'WAITING_LEVEL'
  8823. };
  8824. var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
  8825. function BaseStreamController(hls, fragmentTracker, keyLoader, logPrefix, playlistType) {
  8826. var _this;
  8827. _this = _TaskLoop.call(this, logPrefix, hls.logger) || this;
  8828. _this.hls = void 0;
  8829. _this.fragPrevious = null;
  8830. _this.fragCurrent = null;
  8831. _this.fragmentTracker = void 0;
  8832. _this.transmuxer = null;
  8833. _this._state = State.STOPPED;
  8834. _this.playlistType = void 0;
  8835. _this.media = null;
  8836. _this.mediaBuffer = null;
  8837. _this.config = void 0;
  8838. _this.bitrateTest = false;
  8839. _this.lastCurrentTime = 0;
  8840. _this.nextLoadPosition = 0;
  8841. _this.startPosition = 0;
  8842. _this.startTimeOffset = null;
  8843. _this.retryDate = 0;
  8844. _this.levels = null;
  8845. _this.fragmentLoader = void 0;
  8846. _this.keyLoader = void 0;
  8847. _this.levelLastLoaded = null;
  8848. _this.startFragRequested = false;
  8849. _this.decrypter = void 0;
  8850. _this.initPTS = [];
  8851. _this.buffering = true;
  8852. _this.loadingParts = false;
  8853. _this.loopSn = void 0;
  8854. _this.onMediaSeeking = function () {
  8855. var _this2 = _this,
  8856. config = _this2.config,
  8857. fragCurrent = _this2.fragCurrent,
  8858. media = _this2.media,
  8859. mediaBuffer = _this2.mediaBuffer,
  8860. state = _this2.state;
  8861. var currentTime = media ? media.currentTime : 0;
  8862. var bufferInfo = BufferHelper.bufferInfo(mediaBuffer ? mediaBuffer : media, currentTime, config.maxBufferHole);
  8863. var noFowardBuffer = !bufferInfo.len;
  8864. _this.log("Media seeking to " + (isFiniteNumber(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state + ", " + (noFowardBuffer ? 'out of' : 'in') + " buffer");
  8865. if (_this.state === State.ENDED) {
  8866. _this.resetLoadingState();
  8867. } else if (fragCurrent) {
  8868. // Seeking while frag load is in progress
  8869. var tolerance = config.maxFragLookUpTolerance;
  8870. var fragStartOffset = fragCurrent.start - tolerance;
  8871. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  8872. // if seeking out of buffered range or into new one
  8873. if (noFowardBuffer || fragEndOffset < bufferInfo.start || fragStartOffset > bufferInfo.end) {
  8874. var pastFragment = currentTime > fragEndOffset;
  8875. // if the seek position is outside the current fragment range
  8876. if (currentTime < fragStartOffset || pastFragment) {
  8877. if (pastFragment && fragCurrent.loader) {
  8878. _this.log("Cancelling fragment load for seek (sn: " + fragCurrent.sn + ")");
  8879. fragCurrent.abortRequests();
  8880. _this.resetLoadingState();
  8881. }
  8882. _this.fragPrevious = null;
  8883. }
  8884. }
  8885. }
  8886. if (media) {
  8887. // Remove gap fragments
  8888. _this.fragmentTracker.removeFragmentsInRange(currentTime, Infinity, _this.playlistType, true);
  8889. // Don't set lastCurrentTime with backward seeks (allows for frag selection with strict tolerances)
  8890. var lastCurrentTime = _this.lastCurrentTime;
  8891. if (currentTime > lastCurrentTime) {
  8892. _this.lastCurrentTime = currentTime;
  8893. }
  8894. if (!_this.loadingParts) {
  8895. var bufferEnd = Math.max(bufferInfo.end, currentTime);
  8896. var shouldLoadParts = _this.shouldLoadParts(_this.getLevelDetails(), bufferEnd);
  8897. if (shouldLoadParts) {
  8898. _this.log("LL-Part loading ON after seeking to " + currentTime.toFixed(2) + " with buffer @" + bufferEnd.toFixed(2));
  8899. _this.loadingParts = shouldLoadParts;
  8900. }
  8901. }
  8902. }
  8903. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  8904. if (!_this.hls.hasEnoughToStart) {
  8905. _this.log("Setting " + (noFowardBuffer ? 'startPosition' : 'nextLoadPosition') + " to " + currentTime + " for seek without enough to start");
  8906. _this.nextLoadPosition = currentTime;
  8907. if (noFowardBuffer) {
  8908. _this.startPosition = currentTime;
  8909. }
  8910. }
  8911. // Async tick to speed up processing
  8912. _this.tickImmediate();
  8913. };
  8914. _this.onMediaEnded = function () {
  8915. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  8916. _this.log("setting startPosition to 0 because media ended");
  8917. _this.startPosition = _this.lastCurrentTime = 0;
  8918. };
  8919. _this.playlistType = playlistType;
  8920. _this.hls = hls;
  8921. _this.fragmentLoader = new FragmentLoader(hls.config);
  8922. _this.keyLoader = keyLoader;
  8923. _this.fragmentTracker = fragmentTracker;
  8924. _this.config = hls.config;
  8925. _this.decrypter = new Decrypter(hls.config);
  8926. return _this;
  8927. }
  8928. _inheritsLoose(BaseStreamController, _TaskLoop);
  8929. var _proto = BaseStreamController.prototype;
  8930. _proto.registerListeners = function registerListeners() {
  8931. var hls = this.hls;
  8932. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  8933. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8934. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8935. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8936. hls.on(Events.ERROR, this.onError, this);
  8937. };
  8938. _proto.unregisterListeners = function unregisterListeners() {
  8939. var hls = this.hls;
  8940. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  8941. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  8942. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  8943. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  8944. hls.off(Events.ERROR, this.onError, this);
  8945. };
  8946. _proto.doTick = function doTick() {
  8947. this.onTickEnd();
  8948. };
  8949. _proto.onTickEnd = function onTickEnd() {};
  8950. _proto.startLoad = function startLoad(startPosition) {};
  8951. _proto.stopLoad = function stopLoad() {
  8952. if (this.state === State.STOPPED) {
  8953. return;
  8954. }
  8955. this.fragmentLoader.abort();
  8956. this.keyLoader.abort(this.playlistType);
  8957. var frag = this.fragCurrent;
  8958. if (frag != null && frag.loader) {
  8959. frag.abortRequests();
  8960. this.fragmentTracker.removeFragment(frag);
  8961. }
  8962. this.resetTransmuxer();
  8963. this.fragCurrent = null;
  8964. this.fragPrevious = null;
  8965. this.clearInterval();
  8966. this.clearNextTick();
  8967. this.state = State.STOPPED;
  8968. };
  8969. _proto.pauseBuffering = function pauseBuffering() {
  8970. this.buffering = false;
  8971. };
  8972. _proto.resumeBuffering = function resumeBuffering() {
  8973. this.buffering = true;
  8974. };
  8975. _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
  8976. // Stream is never "ended" when playlist is live or media is detached
  8977. if (levelDetails.live || !this.media) {
  8978. return false;
  8979. }
  8980. // Stream is not "ended" when nothing is buffered past the start
  8981. var bufferEnd = bufferInfo.end || 0;
  8982. var timelineStart = this.config.timelineOffset || 0;
  8983. if (bufferEnd <= timelineStart) {
  8984. return false;
  8985. }
  8986. // Stream is not "ended" when there is a second buffered range starting before the end of the playlist
  8987. var bufferedRanges = bufferInfo.buffered;
  8988. if (this.config.maxBufferHole && bufferedRanges && bufferedRanges.length > 1) {
  8989. // make sure bufferInfo accounts for any gaps
  8990. bufferInfo = BufferHelper.bufferedInfo(bufferedRanges, bufferInfo.start, 0);
  8991. }
  8992. var nextStart = bufferInfo.nextStart;
  8993. var hasSecondBufferedRange = nextStart && nextStart > timelineStart && nextStart < levelDetails.edge;
  8994. if (hasSecondBufferedRange) {
  8995. return false;
  8996. }
  8997. // Playhead is in unbuffered region. Marking EoS now could result in Safari failing to dispatch "ended" event following seek on start.
  8998. if (this.media.currentTime < bufferInfo.start) {
  8999. return false;
  9000. }
  9001. var partList = levelDetails.partList;
  9002. // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,
  9003. // check instead if the last part is buffered.
  9004. if (partList != null && partList.length) {
  9005. var lastPart = partList[partList.length - 1];
  9006. // Checking the midpoint of the part for potential margin of error and related issues.
  9007. // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)
  9008. // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream
  9009. // part mismatches for independent audio and video playlists/segments.
  9010. var lastPartBuffered = BufferHelper.isBuffered(this.media, lastPart.start + lastPart.duration / 2);
  9011. return lastPartBuffered;
  9012. }
  9013. var playlistType = levelDetails.fragments[levelDetails.fragments.length - 1].type;
  9014. return this.fragmentTracker.isEndListAppended(playlistType);
  9015. };
  9016. _proto.getLevelDetails = function getLevelDetails() {
  9017. if (this.levels && this.levelLastLoaded !== null) {
  9018. var _this$levelLastLoaded;
  9019. return (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details;
  9020. }
  9021. };
  9022. _proto.onMediaAttached = function onMediaAttached(event, data) {
  9023. var media = this.media = this.mediaBuffer = data.media;
  9024. media.removeEventListener('seeking', this.onMediaSeeking);
  9025. media.removeEventListener('ended', this.onMediaEnded);
  9026. media.addEventListener('seeking', this.onMediaSeeking);
  9027. media.addEventListener('ended', this.onMediaEnded);
  9028. var config = this.config;
  9029. if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
  9030. this.startLoad(config.startPosition);
  9031. }
  9032. };
  9033. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  9034. var transferringMedia = !!data.transferMedia;
  9035. var media = this.media;
  9036. if (media === null) {
  9037. return;
  9038. }
  9039. if (media.ended) {
  9040. this.log('MSE detaching and video ended, reset startPosition');
  9041. this.startPosition = this.lastCurrentTime = 0;
  9042. }
  9043. // remove video listeners
  9044. media.removeEventListener('seeking', this.onMediaSeeking);
  9045. media.removeEventListener('ended', this.onMediaEnded);
  9046. if (this.keyLoader && !transferringMedia) {
  9047. this.keyLoader.detach();
  9048. }
  9049. this.media = this.mediaBuffer = null;
  9050. this.loopSn = undefined;
  9051. if (transferringMedia) {
  9052. this.resetLoadingState();
  9053. this.resetTransmuxer();
  9054. return;
  9055. }
  9056. this.loadingParts = false;
  9057. this.fragmentTracker.removeAllFragments();
  9058. this.stopLoad();
  9059. };
  9060. _proto.onManifestLoading = function onManifestLoading() {
  9061. this.initPTS = [];
  9062. this.levels = this.levelLastLoaded = this.fragCurrent = null;
  9063. this.lastCurrentTime = this.startPosition = 0;
  9064. this.startFragRequested = false;
  9065. };
  9066. _proto.onError = function onError(event, data) {};
  9067. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  9068. this.startTimeOffset = data.startTimeOffset;
  9069. };
  9070. _proto.onHandlerDestroying = function onHandlerDestroying() {
  9071. this.stopLoad();
  9072. if (this.transmuxer) {
  9073. this.transmuxer.destroy();
  9074. this.transmuxer = null;
  9075. }
  9076. _TaskLoop.prototype.onHandlerDestroying.call(this);
  9077. // @ts-ignore
  9078. this.hls = this.onMediaSeeking = this.onMediaEnded = null;
  9079. };
  9080. _proto.onHandlerDestroyed = function onHandlerDestroyed() {
  9081. this.state = State.STOPPED;
  9082. if (this.fragmentLoader) {
  9083. this.fragmentLoader.destroy();
  9084. }
  9085. if (this.keyLoader) {
  9086. this.keyLoader.destroy();
  9087. }
  9088. if (this.decrypter) {
  9089. this.decrypter.destroy();
  9090. }
  9091. this.hls = this.log = this.warn = this.decrypter = this.keyLoader = this.fragmentLoader = this.fragmentTracker = null;
  9092. _TaskLoop.prototype.onHandlerDestroyed.call(this);
  9093. };
  9094. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  9095. this.startFragRequested = true;
  9096. this._loadFragForPlayback(frag, level, targetBufferTime);
  9097. };
  9098. _proto._loadFragForPlayback = function _loadFragForPlayback(fragment, level, targetBufferTime) {
  9099. var _this3 = this;
  9100. var progressCallback = function progressCallback(data) {
  9101. var frag = data.frag;
  9102. if (_this3.fragContextChanged(frag)) {
  9103. _this3.warn(frag.type + " sn: " + frag.sn + (data.part ? ' part: ' + data.part.index : '') + " of " + _this3.fragInfo(frag, false, data.part) + ") was dropped during download.");
  9104. _this3.fragmentTracker.removeFragment(frag);
  9105. return;
  9106. }
  9107. frag.stats.chunkCount++;
  9108. _this3._handleFragmentLoadProgress(data);
  9109. };
  9110. this._doFragLoad(fragment, level, targetBufferTime, progressCallback).then(function (data) {
  9111. if (!data) {
  9112. // if we're here we probably needed to backtrack or are waiting for more parts
  9113. return;
  9114. }
  9115. var state = _this3.state;
  9116. var frag = data.frag;
  9117. if (_this3.fragContextChanged(frag)) {
  9118. if (state === State.FRAG_LOADING || !_this3.fragCurrent && state === State.PARSING) {
  9119. _this3.fragmentTracker.removeFragment(frag);
  9120. _this3.state = State.IDLE;
  9121. }
  9122. return;
  9123. }
  9124. if ('payload' in data) {
  9125. _this3.log("Loaded " + frag.type + " sn: " + frag.sn + " of " + _this3.playlistLabel() + " " + frag.level);
  9126. _this3.hls.trigger(Events.FRAG_LOADED, data);
  9127. }
  9128. // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
  9129. _this3._handleFragmentLoadComplete(data);
  9130. }).catch(function (reason) {
  9131. if (_this3.state === State.STOPPED || _this3.state === State.ERROR) {
  9132. return;
  9133. }
  9134. _this3.warn("Frag error: " + ((reason == null ? void 0 : reason.message) || reason));
  9135. _this3.resetFragmentLoading(fragment);
  9136. });
  9137. };
  9138. _proto.clearTrackerIfNeeded = function clearTrackerIfNeeded(frag) {
  9139. var _this$mediaBuffer;
  9140. var fragmentTracker = this.fragmentTracker;
  9141. var fragState = fragmentTracker.getState(frag);
  9142. if (fragState === FragmentState.APPENDING) {
  9143. // Lower the max buffer length and try again
  9144. var playlistType = frag.type;
  9145. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  9146. var minForwardBufferLength = Math.max(frag.duration, bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength);
  9147. // If backtracking, always remove from the tracker without reducing max buffer length
  9148. var backtrackFragment = this.backtrackFragment;
  9149. var backtracked = backtrackFragment ? frag.sn - backtrackFragment.sn : 0;
  9150. if (backtracked === 1 || this.reduceMaxBufferLength(minForwardBufferLength, frag.duration)) {
  9151. fragmentTracker.removeFragment(frag);
  9152. }
  9153. } else if (((_this$mediaBuffer = this.mediaBuffer) == null ? void 0 : _this$mediaBuffer.buffered.length) === 0) {
  9154. // Stop gap for bad tracker / buffer flush behavior
  9155. fragmentTracker.removeAllFragments();
  9156. } else if (fragmentTracker.hasParts(frag.type)) {
  9157. // In low latency mode, remove fragments for which only some parts were buffered
  9158. fragmentTracker.detectPartialFragments({
  9159. frag: frag,
  9160. part: null,
  9161. stats: frag.stats,
  9162. id: frag.type
  9163. });
  9164. if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {
  9165. fragmentTracker.removeFragment(frag);
  9166. }
  9167. }
  9168. };
  9169. _proto.checkLiveUpdate = function checkLiveUpdate(details) {
  9170. if (details.updated && !details.live) {
  9171. // Live stream ended, update fragment tracker
  9172. var lastFragment = details.fragments[details.fragments.length - 1];
  9173. this.fragmentTracker.detectPartialFragments({
  9174. frag: lastFragment,
  9175. part: null,
  9176. stats: lastFragment.stats,
  9177. id: lastFragment.type
  9178. });
  9179. }
  9180. if (!details.fragments[0]) {
  9181. details.deltaUpdateFailed = true;
  9182. }
  9183. };
  9184. _proto.waitForLive = function waitForLive(levelInfo) {
  9185. var details = levelInfo.details;
  9186. return (details == null ? void 0 : details.live) && details.type !== 'EVENT' && (this.levelLastLoaded !== levelInfo || details.expired);
  9187. };
  9188. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
  9189. if (type === void 0) {
  9190. type = null;
  9191. }
  9192. if (!(startOffset - endOffset)) {
  9193. return;
  9194. }
  9195. // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
  9196. // passing a null type flushes both buffers
  9197. var flushScope = {
  9198. startOffset: startOffset,
  9199. endOffset: endOffset,
  9200. type: type
  9201. };
  9202. this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);
  9203. };
  9204. _proto._loadInitSegment = function _loadInitSegment(fragment, level) {
  9205. var _this4 = this;
  9206. this._doFragLoad(fragment, level).then(function (data) {
  9207. var frag = data == null ? void 0 : data.frag;
  9208. if (!frag || _this4.fragContextChanged(frag) || !_this4.levels) {
  9209. throw new Error('init load aborted');
  9210. }
  9211. return data;
  9212. }).then(function (data) {
  9213. var hls = _this4.hls;
  9214. var frag = data.frag,
  9215. payload = data.payload;
  9216. var decryptData = frag.decryptdata;
  9217. // check to see if the payload needs to be decrypted
  9218. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  9219. var startTime = self.performance.now();
  9220. // decrypt init segment data
  9221. return _this4.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(function (err) {
  9222. hls.trigger(Events.ERROR, {
  9223. type: ErrorTypes.MEDIA_ERROR,
  9224. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  9225. fatal: false,
  9226. error: err,
  9227. reason: err.message,
  9228. frag: frag
  9229. });
  9230. throw err;
  9231. }).then(function (decryptedData) {
  9232. var endTime = self.performance.now();
  9233. hls.trigger(Events.FRAG_DECRYPTED, {
  9234. frag: frag,
  9235. payload: decryptedData,
  9236. stats: {
  9237. tstart: startTime,
  9238. tdecrypt: endTime
  9239. }
  9240. });
  9241. data.payload = decryptedData;
  9242. return _this4.completeInitSegmentLoad(data);
  9243. });
  9244. }
  9245. return _this4.completeInitSegmentLoad(data);
  9246. }).catch(function (reason) {
  9247. if (_this4.state === State.STOPPED || _this4.state === State.ERROR) {
  9248. return;
  9249. }
  9250. _this4.warn(reason);
  9251. _this4.resetFragmentLoading(fragment);
  9252. });
  9253. };
  9254. _proto.completeInitSegmentLoad = function completeInitSegmentLoad(data) {
  9255. var levels = this.levels;
  9256. if (!levels) {
  9257. throw new Error('init load aborted, missing levels');
  9258. }
  9259. var stats = data.frag.stats;
  9260. if (this.state !== State.STOPPED) {
  9261. this.state = State.IDLE;
  9262. }
  9263. data.frag.data = new Uint8Array(data.payload);
  9264. stats.parsing.start = stats.buffering.start = self.performance.now();
  9265. stats.parsing.end = stats.buffering.end = self.performance.now();
  9266. this.tick();
  9267. };
  9268. _proto.fragContextChanged = function fragContextChanged(frag) {
  9269. var fragCurrent = this.fragCurrent;
  9270. return !frag || !fragCurrent || frag.sn !== fragCurrent.sn || frag.level !== fragCurrent.level;
  9271. };
  9272. _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
  9273. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  9274. this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + this.fragInfo(frag, false, part) + " > buffer:" + (media ? TimeRanges.toString(BufferHelper.getBuffered(media)) : '(detached)') + ")");
  9275. if (isMediaFragment(frag)) {
  9276. var _this$levels;
  9277. if (frag.type !== PlaylistLevelType.SUBTITLE) {
  9278. var el = frag.elementaryStreams;
  9279. if (!Object.keys(el).some(function (type) {
  9280. return !!el[type];
  9281. })) {
  9282. // empty segment
  9283. this.state = State.IDLE;
  9284. return;
  9285. }
  9286. }
  9287. var level = (_this$levels = this.levels) == null ? void 0 : _this$levels[frag.level];
  9288. if (level != null && level.fragmentError) {
  9289. this.log("Resetting level fragment error count of " + level.fragmentError + " on frag buffered");
  9290. level.fragmentError = 0;
  9291. }
  9292. }
  9293. this.state = State.IDLE;
  9294. };
  9295. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
  9296. var transmuxer = this.transmuxer;
  9297. if (!transmuxer) {
  9298. return;
  9299. }
  9300. var frag = fragLoadedEndData.frag,
  9301. part = fragLoadedEndData.part,
  9302. partsLoaded = fragLoadedEndData.partsLoaded;
  9303. // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
  9304. var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
  9305. return !fragLoaded;
  9306. });
  9307. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
  9308. transmuxer.flush(chunkMeta);
  9309. };
  9310. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
  9311. _proto._doFragLoad = function _doFragLoad(frag, level, targetBufferTime, progressCallback) {
  9312. var _frag$decryptdata,
  9313. _this5 = this;
  9314. if (targetBufferTime === void 0) {
  9315. targetBufferTime = null;
  9316. }
  9317. this.fragCurrent = frag;
  9318. var details = level == null ? void 0 : level.details;
  9319. if (!this.levels || !details) {
  9320. throw new Error("frag load aborted, missing level" + (details ? '' : ' detail') + "s");
  9321. }
  9322. var keyLoadingPromise = null;
  9323. if (frag.encrypted && !((_frag$decryptdata = frag.decryptdata) != null && _frag$decryptdata.key)) {
  9324. this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + this.playlistLabel() + " " + frag.level);
  9325. this.state = State.KEY_LOADING;
  9326. this.fragCurrent = frag;
  9327. keyLoadingPromise = this.keyLoader.load(frag).then(function (keyLoadedData) {
  9328. if (!_this5.fragContextChanged(keyLoadedData.frag)) {
  9329. _this5.hls.trigger(Events.KEY_LOADED, keyLoadedData);
  9330. if (_this5.state === State.KEY_LOADING) {
  9331. _this5.state = State.IDLE;
  9332. }
  9333. return keyLoadedData;
  9334. }
  9335. });
  9336. this.hls.trigger(Events.KEY_LOADING, {
  9337. frag: frag
  9338. });
  9339. if (this.fragCurrent === null) {
  9340. keyLoadingPromise = Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"));
  9341. }
  9342. } else if (!frag.encrypted) {
  9343. keyLoadingPromise = this.keyLoader.loadClear(frag, details.encryptedFragments, this.startFragRequested);
  9344. if (keyLoadingPromise) {
  9345. this.log("[eme] blocking frag load until media-keys acquired");
  9346. }
  9347. }
  9348. var fragPrevious = this.fragPrevious;
  9349. if (isMediaFragment(frag) && (!fragPrevious || frag.sn !== fragPrevious.sn)) {
  9350. var shouldLoadParts = this.shouldLoadParts(level.details, frag.end);
  9351. if (shouldLoadParts !== this.loadingParts) {
  9352. this.log("LL-Part loading " + (shouldLoadParts ? 'ON' : 'OFF') + " loading sn " + (fragPrevious == null ? void 0 : fragPrevious.sn) + "->" + frag.sn);
  9353. this.loadingParts = shouldLoadParts;
  9354. }
  9355. }
  9356. targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
  9357. if (this.loadingParts && isMediaFragment(frag)) {
  9358. var partList = details.partList;
  9359. if (partList && progressCallback) {
  9360. if (targetBufferTime > frag.end && details.fragmentHint) {
  9361. frag = details.fragmentHint;
  9362. }
  9363. var partIndex = this.getNextPart(partList, frag, targetBufferTime);
  9364. if (partIndex > -1) {
  9365. var part = partList[partIndex];
  9366. frag = this.fragCurrent = part.fragment;
  9367. this.log("Loading " + frag.type + " sn: " + frag.sn + " part: " + part.index + " (" + partIndex + "/" + (partList.length - 1) + ") of " + this.fragInfo(frag, false, part) + ") cc: " + frag.cc + " [" + details.startSN + "-" + details.endSN + "], target: " + parseFloat(targetBufferTime.toFixed(3)));
  9368. this.nextLoadPosition = part.start + part.duration;
  9369. this.state = State.FRAG_LOADING;
  9370. var _result;
  9371. if (keyLoadingPromise) {
  9372. _result = keyLoadingPromise.then(function (keyLoadedData) {
  9373. if (!keyLoadedData || _this5.fragContextChanged(keyLoadedData.frag)) {
  9374. return null;
  9375. }
  9376. return _this5.doFragPartsLoad(frag, part, level, progressCallback);
  9377. }).catch(function (error) {
  9378. return _this5.handleFragLoadError(error);
  9379. });
  9380. } else {
  9381. _result = this.doFragPartsLoad(frag, part, level, progressCallback).catch(function (error) {
  9382. return _this5.handleFragLoadError(error);
  9383. });
  9384. }
  9385. this.hls.trigger(Events.FRAG_LOADING, {
  9386. frag: frag,
  9387. part: part,
  9388. targetBufferTime: targetBufferTime
  9389. });
  9390. if (this.fragCurrent === null) {
  9391. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts"));
  9392. }
  9393. return _result;
  9394. } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
  9395. // Fragment hint has no parts
  9396. return Promise.resolve(null);
  9397. }
  9398. }
  9399. }
  9400. if (isMediaFragment(frag) && this.loadingParts) {
  9401. this.log("LL-Part loading OFF after next part miss @" + targetBufferTime.toFixed(2));
  9402. this.loadingParts = false;
  9403. } else if (!frag.url) {
  9404. // Selected fragment hint for part but not loading parts
  9405. return Promise.resolve(null);
  9406. }
  9407. this.log("Loading " + frag.type + " sn: " + frag.sn + " of " + this.fragInfo(frag, false) + ") cc: " + frag.cc + " " + (details ? '[' + details.startSN + '-' + details.endSN + ']' : '') + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
  9408. // Don't update nextLoadPosition for fragments which are not buffered
  9409. if (isFiniteNumber(frag.sn) && !this.bitrateTest) {
  9410. this.nextLoadPosition = frag.start + frag.duration;
  9411. }
  9412. this.state = State.FRAG_LOADING;
  9413. // Load key before streaming fragment data
  9414. var dataOnProgress = this.config.progressive;
  9415. var result;
  9416. if (dataOnProgress && keyLoadingPromise) {
  9417. result = keyLoadingPromise.then(function (keyLoadedData) {
  9418. if (!keyLoadedData || _this5.fragContextChanged(keyLoadedData == null ? void 0 : keyLoadedData.frag)) {
  9419. return null;
  9420. }
  9421. return _this5.fragmentLoader.load(frag, progressCallback);
  9422. }).catch(function (error) {
  9423. return _this5.handleFragLoadError(error);
  9424. });
  9425. } else {
  9426. // load unencrypted fragment data with progress event,
  9427. // or handle fragment result after key and fragment are finished loading
  9428. result = Promise.all([this.fragmentLoader.load(frag, dataOnProgress ? progressCallback : undefined), keyLoadingPromise]).then(function (_ref) {
  9429. var fragLoadedData = _ref[0];
  9430. if (!dataOnProgress && fragLoadedData && progressCallback) {
  9431. progressCallback(fragLoadedData);
  9432. }
  9433. return fragLoadedData;
  9434. }).catch(function (error) {
  9435. return _this5.handleFragLoadError(error);
  9436. });
  9437. }
  9438. this.hls.trigger(Events.FRAG_LOADING, {
  9439. frag: frag,
  9440. targetBufferTime: targetBufferTime
  9441. });
  9442. if (this.fragCurrent === null) {
  9443. return Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING"));
  9444. }
  9445. return result;
  9446. };
  9447. _proto.doFragPartsLoad = function doFragPartsLoad(frag, fromPart, level, progressCallback) {
  9448. var _this6 = this;
  9449. return new Promise(function (resolve, reject) {
  9450. var _level$details;
  9451. var partsLoaded = [];
  9452. var initialPartList = (_level$details = level.details) == null ? void 0 : _level$details.partList;
  9453. var _loadPart = function loadPart(part) {
  9454. _this6.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
  9455. partsLoaded[part.index] = partLoadedData;
  9456. var loadedPart = partLoadedData.part;
  9457. _this6.hls.trigger(Events.FRAG_LOADED, partLoadedData);
  9458. var nextPart = getPartWith(level.details, frag.sn, part.index + 1) || findPart(initialPartList, frag.sn, part.index + 1);
  9459. if (nextPart) {
  9460. _loadPart(nextPart);
  9461. } else {
  9462. return resolve({
  9463. frag: frag,
  9464. part: loadedPart,
  9465. partsLoaded: partsLoaded
  9466. });
  9467. }
  9468. }).catch(reject);
  9469. };
  9470. _loadPart(fromPart);
  9471. });
  9472. };
  9473. _proto.handleFragLoadError = function handleFragLoadError(error) {
  9474. if ('data' in error) {
  9475. var data = error.data;
  9476. if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {
  9477. this.handleFragLoadAborted(data.frag, data.part);
  9478. } else {
  9479. this.hls.trigger(Events.ERROR, data);
  9480. }
  9481. } else {
  9482. this.hls.trigger(Events.ERROR, {
  9483. type: ErrorTypes.OTHER_ERROR,
  9484. details: ErrorDetails.INTERNAL_EXCEPTION,
  9485. err: error,
  9486. error: error,
  9487. fatal: true
  9488. });
  9489. }
  9490. return null;
  9491. };
  9492. _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
  9493. var context = this.getCurrentContext(chunkMeta);
  9494. if (!context || this.state !== State.PARSING) {
  9495. if (!this.fragCurrent && this.state !== State.STOPPED && this.state !== State.ERROR) {
  9496. this.state = State.IDLE;
  9497. }
  9498. return;
  9499. }
  9500. var frag = context.frag,
  9501. part = context.part,
  9502. level = context.level;
  9503. var now = self.performance.now();
  9504. frag.stats.parsing.end = now;
  9505. if (part) {
  9506. part.stats.parsing.end = now;
  9507. }
  9508. // See if part loading should be disabled/enabled based on buffer and playback position.
  9509. var levelDetails = this.getLevelDetails();
  9510. var loadingPartsAtEdge = levelDetails && frag.sn > levelDetails.endSN;
  9511. var shouldLoadParts = loadingPartsAtEdge || this.shouldLoadParts(levelDetails, frag.end);
  9512. if (shouldLoadParts !== this.loadingParts) {
  9513. this.log("LL-Part loading " + (shouldLoadParts ? 'ON' : 'OFF') + " after parsing segment ending @" + frag.end.toFixed(2));
  9514. this.loadingParts = shouldLoadParts;
  9515. }
  9516. this.updateLevelTiming(frag, part, level, chunkMeta.partial);
  9517. };
  9518. _proto.shouldLoadParts = function shouldLoadParts(details, bufferEnd) {
  9519. if (this.config.lowLatencyMode) {
  9520. if (!details) {
  9521. return this.loadingParts;
  9522. }
  9523. if (details != null && details.partList) {
  9524. var _details$fragmentHint;
  9525. // Buffer must be ahead of first part + duration of parts after last segment
  9526. // and playback must be at or past segment adjacent to part list
  9527. var firstPart = details.partList[0];
  9528. var safePartStart = firstPart.end + (((_details$fragmentHint = details.fragmentHint) == null ? void 0 : _details$fragmentHint.duration) || 0);
  9529. if (bufferEnd >= safePartStart) {
  9530. var _this$media;
  9531. var playhead = this.hls.hasEnoughToStart ? ((_this$media = this.media) == null ? void 0 : _this$media.currentTime) || this.lastCurrentTime : this.getLoadPosition();
  9532. if (playhead > firstPart.start - firstPart.fragment.duration) {
  9533. return true;
  9534. }
  9535. }
  9536. }
  9537. }
  9538. return false;
  9539. };
  9540. _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
  9541. var levels = this.levels,
  9542. fragCurrent = this.fragCurrent;
  9543. var levelIndex = chunkMeta.level,
  9544. sn = chunkMeta.sn,
  9545. partIndex = chunkMeta.part;
  9546. if (!(levels != null && levels[levelIndex])) {
  9547. this.warn("Levels object was unset while buffering fragment " + sn + " of " + this.playlistLabel() + " " + levelIndex + ". The current chunk will not be buffered.");
  9548. return null;
  9549. }
  9550. var level = levels[levelIndex];
  9551. var levelDetails = level.details;
  9552. var part = partIndex > -1 ? getPartWith(levelDetails, sn, partIndex) : null;
  9553. var frag = part ? part.fragment : getFragmentWithSN(levelDetails, sn, fragCurrent);
  9554. if (!frag) {
  9555. return null;
  9556. }
  9557. if (fragCurrent && fragCurrent !== frag) {
  9558. frag.stats = fragCurrent.stats;
  9559. }
  9560. return {
  9561. frag: frag,
  9562. part: part,
  9563. level: level
  9564. };
  9565. };
  9566. _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta, noBacktracking) {
  9567. var _buffer;
  9568. if (!data || this.state !== State.PARSING) {
  9569. return;
  9570. }
  9571. var data1 = data.data1,
  9572. data2 = data.data2;
  9573. var buffer = data1;
  9574. if (data1 && data2) {
  9575. // Combine the moof + mdat so that we buffer with a single append
  9576. buffer = appendUint8Array(data1, data2);
  9577. }
  9578. if (!((_buffer = buffer) != null && _buffer.length)) {
  9579. return;
  9580. }
  9581. var offsetTimestamp = this.initPTS[frag.cc];
  9582. var offset = offsetTimestamp ? -offsetTimestamp.baseTime / offsetTimestamp.timescale : undefined;
  9583. var segment = {
  9584. type: data.type,
  9585. frag: frag,
  9586. part: part,
  9587. chunkMeta: chunkMeta,
  9588. offset: offset,
  9589. parent: frag.type,
  9590. data: buffer
  9591. };
  9592. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  9593. if (data.dropped && data.independent && !part) {
  9594. if (noBacktracking) {
  9595. return;
  9596. }
  9597. // Clear buffer so that we reload previous segments sequentially if required
  9598. this.flushBufferGap(frag);
  9599. }
  9600. };
  9601. _proto.flushBufferGap = function flushBufferGap(frag) {
  9602. var media = this.media;
  9603. if (!media) {
  9604. return;
  9605. }
  9606. // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
  9607. if (!BufferHelper.isBuffered(media, media.currentTime)) {
  9608. this.flushMainBuffer(0, frag.start);
  9609. return;
  9610. }
  9611. // Remove back-buffer without interrupting playback to allow back tracking
  9612. var currentTime = media.currentTime;
  9613. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  9614. var fragDuration = frag.duration;
  9615. var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
  9616. var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
  9617. if (frag.start - start > segmentFraction) {
  9618. this.flushMainBuffer(start, frag.start);
  9619. }
  9620. };
  9621. _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
  9622. var _this$media2;
  9623. var pos = this.getLoadPosition();
  9624. if (!isFiniteNumber(pos)) {
  9625. return null;
  9626. }
  9627. var backwardSeek = this.lastCurrentTime > pos;
  9628. var maxBufferHole = backwardSeek || (_this$media2 = this.media) != null && _this$media2.paused ? 0 : this.config.maxBufferHole;
  9629. return this.getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole);
  9630. };
  9631. _proto.getFwdBufferInfoAtPos = function getFwdBufferInfoAtPos(bufferable, pos, type, maxBufferHole) {
  9632. var bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);
  9633. // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
  9634. if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
  9635. var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
  9636. if (bufferedFragAtPos && (bufferInfo.nextStart <= bufferedFragAtPos.end || bufferedFragAtPos.gap)) {
  9637. var gapDuration = Math.max(Math.min(bufferInfo.nextStart, bufferedFragAtPos.end) - pos, maxBufferHole);
  9638. return BufferHelper.bufferInfo(bufferable, pos, gapDuration);
  9639. }
  9640. }
  9641. return bufferInfo;
  9642. };
  9643. _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
  9644. var config = this.config;
  9645. var maxBufLen;
  9646. if (levelBitrate) {
  9647. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  9648. } else {
  9649. maxBufLen = config.maxBufferLength;
  9650. }
  9651. return Math.min(maxBufLen, config.maxMaxBufferLength);
  9652. };
  9653. _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold, fragDuration) {
  9654. var config = this.config;
  9655. var minLength = Math.max(Math.min(threshold - fragDuration, config.maxBufferLength), fragDuration);
  9656. var reducedLength = Math.max(threshold - fragDuration * 3, config.maxMaxBufferLength / 2, minLength);
  9657. if (reducedLength >= minLength) {
  9658. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  9659. config.maxMaxBufferLength = reducedLength;
  9660. this.warn("Reduce max buffer length to " + reducedLength + "s");
  9661. return true;
  9662. }
  9663. return false;
  9664. };
  9665. _proto.getAppendedFrag = function getAppendedFrag(position, playlistType) {
  9666. var _this$fragmentTracker;
  9667. if (playlistType === void 0) {
  9668. playlistType = PlaylistLevelType.MAIN;
  9669. }
  9670. var fragOrPart = (_this$fragmentTracker = this.fragmentTracker) == null ? void 0 : _this$fragmentTracker.getAppendedFrag(position, playlistType);
  9671. if (fragOrPart && 'fragment' in fragOrPart) {
  9672. return fragOrPart.fragment;
  9673. }
  9674. return fragOrPart;
  9675. };
  9676. _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
  9677. var fragments = levelDetails.fragments;
  9678. var fragLen = fragments.length;
  9679. if (!fragLen) {
  9680. return null;
  9681. }
  9682. // find fragment index, contiguous with end of buffer position
  9683. var config = this.config;
  9684. var start = fragments[0].start;
  9685. var canLoadParts = config.lowLatencyMode && !!levelDetails.partList;
  9686. var frag = null;
  9687. if (levelDetails.live) {
  9688. var initialLiveManifestSize = config.initialLiveManifestSize;
  9689. if (fragLen < initialLiveManifestSize) {
  9690. this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
  9691. return null;
  9692. }
  9693. // The real fragment start times for a live stream are only known after the PTS range for that level is known.
  9694. // In order to discover the range, we load the best matching fragment for that level and demux it.
  9695. // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
  9696. // we get the fragment matching that start time
  9697. if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1 || pos < start) {
  9698. var _frag;
  9699. if (canLoadParts && !this.loadingParts) {
  9700. this.log("LL-Part loading ON for initial live fragment");
  9701. this.loadingParts = true;
  9702. }
  9703. frag = this.getInitialLiveFragment(levelDetails);
  9704. var mainStart = this.hls.startPosition;
  9705. var liveSyncPosition = this.hls.liveSyncPosition;
  9706. var startPosition = frag ? (mainStart !== -1 && mainStart >= start ? mainStart : liveSyncPosition) || frag.start : pos;
  9707. this.log("Setting startPosition to " + startPosition + " to match start frag at live edge. mainStart: " + mainStart + " liveSyncPosition: " + liveSyncPosition + " frag.start: " + ((_frag = frag) == null ? void 0 : _frag.start));
  9708. this.startPosition = this.nextLoadPosition = startPosition;
  9709. }
  9710. } else if (pos <= start) {
  9711. // VoD playlist: if loadPosition before start of playlist, load first fragment
  9712. frag = fragments[0];
  9713. }
  9714. // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
  9715. if (!frag) {
  9716. var end = this.loadingParts ? levelDetails.partEnd : levelDetails.fragmentEnd;
  9717. frag = this.getFragmentAtPosition(pos, end, levelDetails);
  9718. }
  9719. var programFrag = this.filterReplacedPrimary(frag, levelDetails);
  9720. if (!programFrag && frag) {
  9721. var curSNIdx = frag.sn - levelDetails.startSN;
  9722. programFrag = this.filterReplacedPrimary(fragments[curSNIdx + 1] || null, levelDetails);
  9723. }
  9724. return this.mapToInitFragWhenRequired(programFrag);
  9725. };
  9726. _proto.isLoopLoading = function isLoopLoading(frag, targetBufferTime) {
  9727. var trackerState = this.fragmentTracker.getState(frag);
  9728. return (trackerState === FragmentState.OK || trackerState === FragmentState.PARTIAL && !!frag.gap) && this.nextLoadPosition > targetBufferTime;
  9729. };
  9730. _proto.getNextFragmentLoopLoading = function getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, playlistType, maxBufLen) {
  9731. var nextFragment = null;
  9732. if (frag.gap) {
  9733. nextFragment = this.getNextFragment(this.nextLoadPosition, levelDetails);
  9734. if (nextFragment && !nextFragment.gap && bufferInfo.nextStart) {
  9735. // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length
  9736. var nextbufferInfo = this.getFwdBufferInfoAtPos(this.mediaBuffer ? this.mediaBuffer : this.media, bufferInfo.nextStart, playlistType, 0);
  9737. if (nextbufferInfo !== null && bufferInfo.len + nextbufferInfo.len >= maxBufLen) {
  9738. // Returning here might result in not finding an audio and video candiate to skip to
  9739. var sn = nextFragment.sn;
  9740. if (this.loopSn !== sn) {
  9741. this.log("buffer full after gaps in \"" + playlistType + "\" playlist starting at sn: " + sn);
  9742. this.loopSn = sn;
  9743. }
  9744. return null;
  9745. }
  9746. }
  9747. }
  9748. this.loopSn = undefined;
  9749. return nextFragment;
  9750. };
  9751. _proto.filterReplacedPrimary = function filterReplacedPrimary(frag, details) {
  9752. if (!frag) {
  9753. return frag;
  9754. }
  9755. if (interstitialsEnabled(this.hls.config) && frag.type !== PlaylistLevelType.SUBTITLE) {
  9756. // Do not load fragments outside the buffering schedule segment
  9757. var interstitials = this.hls.interstitialsManager;
  9758. var bufferingItem = interstitials == null ? void 0 : interstitials.bufferingItem;
  9759. if (bufferingItem) {
  9760. var bufferingInterstitial = bufferingItem.event;
  9761. if (bufferingInterstitial) {
  9762. // Do not stream fragments while buffering Interstitial Events (except for overlap at the start)
  9763. if (bufferingInterstitial.appendInPlace || Math.abs(frag.start - bufferingItem.start) > 1 || bufferingItem.start === 0) {
  9764. return null;
  9765. }
  9766. } else {
  9767. // Limit fragment loading to media in schedule item
  9768. if (frag.end <= bufferingItem.start && (details == null ? void 0 : details.live) === false) {
  9769. // fragment ends by schedule item start
  9770. // this.fragmentTracker.fragBuffered(frag, true);
  9771. return null;
  9772. }
  9773. if (frag.start > bufferingItem.end && bufferingItem.nextEvent) {
  9774. // fragment is past schedule item end
  9775. // allow some overflow when not appending in place to prevent stalls
  9776. if (bufferingItem.nextEvent.appendInPlace || frag.start - bufferingItem.end > 1) {
  9777. return null;
  9778. }
  9779. }
  9780. }
  9781. }
  9782. // Skip loading of fragments that overlap completely with appendInPlace interstitials
  9783. var playerQueue = interstitials == null ? void 0 : interstitials.playerQueue;
  9784. if (playerQueue) {
  9785. for (var i = playerQueue.length; i--;) {
  9786. var interstitial = playerQueue[i].interstitial;
  9787. if (interstitial.appendInPlace && frag.start >= interstitial.startTime && frag.end <= interstitial.resumeTime) {
  9788. return null;
  9789. }
  9790. }
  9791. }
  9792. }
  9793. return frag;
  9794. };
  9795. _proto.mapToInitFragWhenRequired = function mapToInitFragWhenRequired(frag) {
  9796. // If an initSegment is present, it must be buffered first
  9797. if (frag != null && frag.initSegment && !(frag != null && frag.initSegment.data) && !this.bitrateTest) {
  9798. return frag.initSegment;
  9799. }
  9800. return frag;
  9801. };
  9802. _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
  9803. var nextPart = -1;
  9804. var contiguous = false;
  9805. var independentAttrOmitted = true;
  9806. for (var i = 0, len = partList.length; i < len; i++) {
  9807. var part = partList[i];
  9808. independentAttrOmitted = independentAttrOmitted && !part.independent;
  9809. if (nextPart > -1 && targetBufferTime < part.start) {
  9810. break;
  9811. }
  9812. var loaded = part.loaded;
  9813. if (loaded) {
  9814. nextPart = -1;
  9815. } else if ((contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
  9816. nextPart = i;
  9817. }
  9818. contiguous = loaded;
  9819. }
  9820. return nextPart;
  9821. };
  9822. _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
  9823. var lastPart = partList[partList.length - 1];
  9824. return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
  9825. }
  9826. /*
  9827. This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
  9828. "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
  9829. start and end times for each fragment in the playlist (after which this method will not need to be called).
  9830. */;
  9831. _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails) {
  9832. var fragments = levelDetails.fragments;
  9833. var fragPrevious = this.fragPrevious;
  9834. var frag = null;
  9835. if (fragPrevious) {
  9836. if (levelDetails.hasProgramDateTime) {
  9837. // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
  9838. this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  9839. frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
  9840. }
  9841. if (!frag) {
  9842. // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
  9843. var targetSN = fragPrevious.sn + 1;
  9844. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  9845. var fragNext = fragments[targetSN - levelDetails.startSN];
  9846. // Ensure that we're staying within the continuity range, since PTS resets upon a new range
  9847. if (fragPrevious.cc === fragNext.cc) {
  9848. frag = fragNext;
  9849. this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
  9850. }
  9851. }
  9852. // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
  9853. // will have the wrong start times
  9854. if (!frag) {
  9855. frag = findNearestWithCC(levelDetails, fragPrevious.cc, fragPrevious.end);
  9856. if (frag) {
  9857. this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
  9858. }
  9859. }
  9860. }
  9861. } else {
  9862. // Find a new start fragment when fragPrevious is null
  9863. var liveStart = this.hls.liveSyncPosition;
  9864. if (liveStart !== null) {
  9865. frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
  9866. }
  9867. }
  9868. return frag;
  9869. }
  9870. /*
  9871. This method finds the best matching fragment given the provided position.
  9872. */;
  9873. _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
  9874. var config = this.config;
  9875. var fragPrevious = this.fragPrevious;
  9876. var fragments = levelDetails.fragments,
  9877. endSN = levelDetails.endSN;
  9878. var fragmentHint = levelDetails.fragmentHint;
  9879. var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  9880. var partList = levelDetails.partList;
  9881. var loadingParts = !!(this.loadingParts && partList != null && partList.length && fragmentHint);
  9882. if (loadingParts && fragmentHint && !this.bitrateTest && partList[partList.length - 1].fragment.sn === fragmentHint.sn) {
  9883. // Include incomplete fragment with parts at end
  9884. fragments = fragments.concat(fragmentHint);
  9885. endSN = fragmentHint.sn;
  9886. }
  9887. var frag;
  9888. if (bufferEnd < end) {
  9889. var _this$media3;
  9890. var backwardSeek = bufferEnd < this.lastCurrentTime;
  9891. var lookupTolerance = backwardSeek || bufferEnd > end - maxFragLookUpTolerance || (_this$media3 = this.media) != null && _this$media3.paused || !this.startFragRequested ? 0 : maxFragLookUpTolerance;
  9892. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  9893. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  9894. frag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  9895. } else {
  9896. // reach end of playlist
  9897. frag = fragments[fragments.length - 1];
  9898. }
  9899. if (frag) {
  9900. var curSNIdx = frag.sn - levelDetails.startSN;
  9901. // Move fragPrevious forward to support forcing the next fragment to load
  9902. // when the buffer catches up to a previously buffered range.
  9903. var fragState = this.fragmentTracker.getState(frag);
  9904. if (fragState === FragmentState.OK || fragState === FragmentState.PARTIAL && frag.gap) {
  9905. fragPrevious = frag;
  9906. }
  9907. if (fragPrevious && frag.sn === fragPrevious.sn && (!loadingParts || partList[0].fragment.sn > frag.sn || !levelDetails.live && !loadingParts)) {
  9908. // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
  9909. // non-uniform fragment durations
  9910. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  9911. if (sameLevel) {
  9912. var nextFrag = fragments[curSNIdx + 1];
  9913. if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== FragmentState.OK) {
  9914. frag = nextFrag;
  9915. } else {
  9916. frag = null;
  9917. }
  9918. }
  9919. }
  9920. }
  9921. return frag;
  9922. };
  9923. _proto.alignPlaylists = function alignPlaylists(details, previousDetails, switchDetails) {
  9924. // TODO: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
  9925. // this could all go in level-helper mergeDetails()
  9926. var length = details.fragments.length;
  9927. if (!length) {
  9928. this.warn("No fragments in live playlist");
  9929. return 0;
  9930. }
  9931. var slidingStart = details.fragmentStart;
  9932. var firstLevelLoad = !previousDetails;
  9933. var aligned = details.alignedSliding && isFiniteNumber(slidingStart);
  9934. if (firstLevelLoad || !aligned && !slidingStart) {
  9935. alignStream(switchDetails, details);
  9936. var alignedSlidingStart = details.fragmentStart;
  9937. this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " fragments: " + length);
  9938. return alignedSlidingStart;
  9939. }
  9940. return slidingStart;
  9941. };
  9942. _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
  9943. // Wait for Low-Latency CDN Tune-in to get an updated playlist
  9944. var advancePartLimit = 3;
  9945. return details.live && details.canBlockReload && details.partTarget && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
  9946. };
  9947. _proto.setStartPosition = function setStartPosition(details, sliding) {
  9948. // compute start position if set to -1. use it straight away if value is defined
  9949. var startPosition = this.startPosition;
  9950. if (startPosition < sliding) {
  9951. startPosition = -1;
  9952. }
  9953. var timelineOffset = this.timelineOffset;
  9954. if (startPosition === -1) {
  9955. // Use Playlist EXT-X-START:TIME-OFFSET when set
  9956. // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match
  9957. var offsetInMultivariantPlaylist = this.startTimeOffset !== null;
  9958. var startTimeOffset = offsetInMultivariantPlaylist ? this.startTimeOffset : details.startTimeOffset;
  9959. if (startTimeOffset !== null && isFiniteNumber(startTimeOffset)) {
  9960. startPosition = sliding + startTimeOffset;
  9961. if (startTimeOffset < 0) {
  9962. startPosition += details.edge;
  9963. }
  9964. startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
  9965. this.log("Setting startPosition to " + startPosition + " for start time offset " + startTimeOffset + " found in " + (offsetInMultivariantPlaylist ? 'multivariant' : 'media') + " playlist");
  9966. this.startPosition = startPosition;
  9967. } else if (details.live) {
  9968. // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
  9969. // not been specified via the config or an as an argument to startLoad (#3736).
  9970. startPosition = this.hls.liveSyncPosition || sliding;
  9971. this.log("Setting startPosition to -1 to start at live edge " + startPosition);
  9972. this.startPosition = -1;
  9973. } else {
  9974. this.log("setting startPosition to 0 by default");
  9975. this.startPosition = startPosition = 0;
  9976. }
  9977. this.lastCurrentTime = startPosition + timelineOffset;
  9978. }
  9979. this.nextLoadPosition = startPosition + timelineOffset;
  9980. };
  9981. _proto.getLoadPosition = function getLoadPosition() {
  9982. var _this$hls;
  9983. var media = this.media;
  9984. // if we have not yet loaded any fragment, start loading from start position
  9985. var pos = 0;
  9986. if ((_this$hls = this.hls) != null && _this$hls.hasEnoughToStart && media) {
  9987. pos = media.currentTime;
  9988. } else if (this.nextLoadPosition >= 0) {
  9989. pos = this.nextLoadPosition;
  9990. }
  9991. return pos;
  9992. };
  9993. _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
  9994. if (this.transmuxer && frag.type === this.playlistType && isMediaFragment(frag) && frag.stats.aborted) {
  9995. this.log("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of " + this.playlistLabel() + " " + frag.level + " was aborted");
  9996. this.resetFragmentLoading(frag);
  9997. }
  9998. };
  9999. _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
  10000. if (!this.fragCurrent || !this.fragContextChanged(frag) && this.state !== State.FRAG_LOADING_WAITING_RETRY) {
  10001. this.state = State.IDLE;
  10002. }
  10003. };
  10004. _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
  10005. if (data.chunkMeta && !data.frag) {
  10006. var context = this.getCurrentContext(data.chunkMeta);
  10007. if (context) {
  10008. data.frag = context.frag;
  10009. }
  10010. }
  10011. var frag = data.frag;
  10012. // Handle frag error related to caller's filterType
  10013. if (!frag || frag.type !== filterType || !this.levels) {
  10014. return;
  10015. }
  10016. if (this.fragContextChanged(frag)) {
  10017. var _this$fragCurrent;
  10018. this.warn("Frag load error must match current frag to retry " + frag.url + " > " + ((_this$fragCurrent = this.fragCurrent) == null ? void 0 : _this$fragCurrent.url));
  10019. return;
  10020. }
  10021. var gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;
  10022. if (gapTagEncountered) {
  10023. this.fragmentTracker.fragBuffered(frag, true);
  10024. }
  10025. // keep retrying until the limit will be reached
  10026. var errorAction = data.errorAction;
  10027. var _ref2 = errorAction || {},
  10028. action = _ref2.action,
  10029. flags = _ref2.flags,
  10030. _ref2$retryCount = _ref2.retryCount,
  10031. retryCount = _ref2$retryCount === void 0 ? 0 : _ref2$retryCount,
  10032. retryConfig = _ref2.retryConfig;
  10033. var couldRetry = !!errorAction && !!retryConfig;
  10034. var retry = couldRetry && action === NetworkErrorAction.RetryRequest;
  10035. var noAlternate = couldRetry && !errorAction.resolved && flags === ErrorActionFlags.MoveAllAlternatesMatchingHost;
  10036. if (!retry && noAlternate && isMediaFragment(frag) && !frag.endList) {
  10037. this.resetFragmentErrors(filterType);
  10038. this.treatAsGap(frag);
  10039. errorAction.resolved = true;
  10040. } else if ((retry || noAlternate) && retryCount < retryConfig.maxNumRetry) {
  10041. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10042. var delay = getRetryDelay(retryConfig, retryCount);
  10043. this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " errored with " + data.details + ", retrying loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " in " + delay + "ms");
  10044. errorAction.resolved = true;
  10045. this.retryDate = self.performance.now() + delay;
  10046. this.state = State.FRAG_LOADING_WAITING_RETRY;
  10047. } else if (retryConfig && errorAction) {
  10048. this.resetFragmentErrors(filterType);
  10049. if (retryCount < retryConfig.maxNumRetry) {
  10050. // Network retry is skipped when level switch is preferred
  10051. if (!gapTagEncountered && action !== NetworkErrorAction.RemoveAlternatePermanently) {
  10052. errorAction.resolved = true;
  10053. }
  10054. } else {
  10055. this.warn(data.details + " reached or exceeded max retry (" + retryCount + ")");
  10056. return;
  10057. }
  10058. } else if (action === NetworkErrorAction.SendAlternateToPenaltyBox) {
  10059. this.state = State.WAITING_LEVEL;
  10060. } else {
  10061. this.state = State.ERROR;
  10062. }
  10063. // Perform next async tick sooner to speed up error action resolution
  10064. this.tickImmediate();
  10065. };
  10066. _proto.reduceLengthAndFlushBuffer = function reduceLengthAndFlushBuffer(data) {
  10067. // if in appending state
  10068. if (this.state === State.PARSING || this.state === State.PARSED) {
  10069. var frag = data.frag;
  10070. var playlistType = data.parent;
  10071. var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, playlistType);
  10072. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  10073. // reduce max buf len if current position is buffered
  10074. var buffered = bufferedInfo && bufferedInfo.len > 0.5;
  10075. if (buffered) {
  10076. this.reduceMaxBufferLength(bufferedInfo.len, (frag == null ? void 0 : frag.duration) || 10);
  10077. }
  10078. var flushBuffer = !buffered;
  10079. if (flushBuffer) {
  10080. // current position is not buffered, but browser is still complaining about buffer full error
  10081. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  10082. // in that case flush the whole audio buffer to recover
  10083. this.warn("Buffer full error while media.currentTime is not buffered, flush " + playlistType + " buffer");
  10084. }
  10085. if (frag) {
  10086. this.fragmentTracker.removeFragment(frag);
  10087. this.nextLoadPosition = frag.start;
  10088. }
  10089. this.resetLoadingState();
  10090. return flushBuffer;
  10091. }
  10092. return false;
  10093. };
  10094. _proto.resetFragmentErrors = function resetFragmentErrors(filterType) {
  10095. if (filterType === PlaylistLevelType.AUDIO) {
  10096. // Reset current fragment since audio track audio is essential and may not have a fail-over track
  10097. this.fragCurrent = null;
  10098. }
  10099. // Fragment errors that result in a level switch or redundant fail-over
  10100. // should reset the stream controller state to idle
  10101. if (!this.hls.hasEnoughToStart) {
  10102. this.startFragRequested = false;
  10103. }
  10104. if (this.state !== State.STOPPED) {
  10105. this.state = State.IDLE;
  10106. }
  10107. };
  10108. _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
  10109. if (!media) {
  10110. return;
  10111. }
  10112. // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
  10113. // (so that we will check against video.buffered ranges in case of alt audio track)
  10114. var bufferedTimeRanges = BufferHelper.getBuffered(media);
  10115. this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
  10116. if (this.state === State.ENDED) {
  10117. this.resetLoadingState();
  10118. }
  10119. };
  10120. _proto.resetLoadingState = function resetLoadingState() {
  10121. this.log('Reset loading state');
  10122. this.fragCurrent = null;
  10123. this.fragPrevious = null;
  10124. if (this.state !== State.STOPPED) {
  10125. this.state = State.IDLE;
  10126. }
  10127. };
  10128. _proto.resetStartWhenNotLoaded = function resetStartWhenNotLoaded(level) {
  10129. // if loadedmetadata is not set, it means that first frag request failed
  10130. // in that case, reset startFragRequested flag
  10131. if (!this.hls.hasEnoughToStart) {
  10132. this.startFragRequested = false;
  10133. var details = level ? level.details : null;
  10134. if (details != null && details.live) {
  10135. // Update the start position and return to IDLE to recover live start
  10136. this.log("resetting startPosition for live start");
  10137. this.startPosition = -1;
  10138. this.setStartPosition(details, details.fragmentStart);
  10139. this.resetLoadingState();
  10140. } else {
  10141. this.nextLoadPosition = this.startPosition;
  10142. }
  10143. }
  10144. };
  10145. _proto.resetWhenMissingContext = function resetWhenMissingContext(chunkMeta) {
  10146. this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of " + this.playlistLabel() + " " + chunkMeta.level + ". This chunk will not be buffered.");
  10147. this.removeUnbufferedFrags();
  10148. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10149. this.resetLoadingState();
  10150. };
  10151. _proto.removeUnbufferedFrags = function removeUnbufferedFrags(start) {
  10152. if (start === void 0) {
  10153. start = 0;
  10154. }
  10155. this.fragmentTracker.removeFragmentsInRange(start, Infinity, this.playlistType, false, true);
  10156. };
  10157. _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
  10158. var _this7 = this;
  10159. var details = level.details;
  10160. if (!details) {
  10161. this.warn('level.details undefined');
  10162. return;
  10163. }
  10164. var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
  10165. var info = frag.elementaryStreams[type];
  10166. if (info) {
  10167. var parsedDuration = info.endPTS - info.startPTS;
  10168. if (parsedDuration <= 0) {
  10169. // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
  10170. // The new transmuxer will be configured with a time offset matching the next fragment start,
  10171. // preventing the timeline from shifting.
  10172. _this7.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ")");
  10173. return result || false;
  10174. }
  10175. var drift = partial ? 0 : updateFragPTSDTS(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
  10176. _this7.hls.trigger(Events.LEVEL_PTS_UPDATED, {
  10177. details: details,
  10178. level: level,
  10179. drift: drift,
  10180. type: type,
  10181. frag: frag,
  10182. start: info.startPTS,
  10183. end: info.endPTS
  10184. });
  10185. return true;
  10186. }
  10187. return result;
  10188. }, false);
  10189. if (!parsed) {
  10190. var _this$transmuxer;
  10191. if (level.fragmentError === 0) {
  10192. // Mark and track the odd empty segment as a gap to avoid reloading
  10193. this.treatAsGap(frag, level);
  10194. }
  10195. if (((_this$transmuxer = this.transmuxer) == null ? void 0 : _this$transmuxer.error) === null) {
  10196. var error = new Error("Found no media in fragment " + frag.sn + " of " + this.playlistLabel() + " " + frag.level + " resetting transmuxer to fallback to playlist timing");
  10197. this.warn(error.message);
  10198. this.hls.trigger(Events.ERROR, {
  10199. type: ErrorTypes.MEDIA_ERROR,
  10200. details: ErrorDetails.FRAG_PARSING_ERROR,
  10201. fatal: false,
  10202. error: error,
  10203. frag: frag,
  10204. reason: "Found no media in msn " + frag.sn + " of " + this.playlistLabel() + " \"" + level.url + "\""
  10205. });
  10206. if (!this.hls) {
  10207. return;
  10208. }
  10209. this.resetTransmuxer();
  10210. }
  10211. // For this error fallthrough. Marking parsed will allow advancing to next fragment.
  10212. }
  10213. this.state = State.PARSED;
  10214. this.log("Parsed " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + this.fragInfo(frag, false, part) + ")");
  10215. this.hls.trigger(Events.FRAG_PARSED, {
  10216. frag: frag,
  10217. part: part
  10218. });
  10219. };
  10220. _proto.playlistLabel = function playlistLabel() {
  10221. return this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track';
  10222. };
  10223. _proto.fragInfo = function fragInfo(frag, pts, part) {
  10224. var _ref3, _ref4;
  10225. if (pts === void 0) {
  10226. pts = true;
  10227. }
  10228. return this.playlistLabel() + " " + frag.level + " (" + (part ? 'part' : 'frag') + ":[" + ((_ref3 = pts && !part ? frag.startPTS : (part || frag).start) != null ? _ref3 : NaN).toFixed(3) + "-" + ((_ref4 = pts && !part ? frag.endPTS : (part || frag).end) != null ? _ref4 : NaN).toFixed(3) + "]" + (part && frag.type === 'main' ? 'INDEPENDENT=' + (part.independent ? 'YES' : 'NO') : '');
  10229. };
  10230. _proto.treatAsGap = function treatAsGap(frag, level) {
  10231. if (level) {
  10232. level.fragmentError++;
  10233. }
  10234. frag.gap = true;
  10235. this.fragmentTracker.removeFragment(frag);
  10236. this.fragmentTracker.fragBuffered(frag, true);
  10237. };
  10238. _proto.resetTransmuxer = function resetTransmuxer() {
  10239. var _this$transmuxer2;
  10240. (_this$transmuxer2 = this.transmuxer) == null ? void 0 : _this$transmuxer2.reset();
  10241. };
  10242. _proto.recoverWorkerError = function recoverWorkerError(data) {
  10243. if (data.event === 'demuxerWorker') {
  10244. this.fragmentTracker.removeAllFragments();
  10245. if (this.transmuxer) {
  10246. this.transmuxer.destroy();
  10247. this.transmuxer = null;
  10248. }
  10249. this.resetStartWhenNotLoaded(this.levelLastLoaded);
  10250. this.resetLoadingState();
  10251. }
  10252. };
  10253. return _createClass(BaseStreamController, [{
  10254. key: "startPositionValue",
  10255. get: function get() {
  10256. var nextLoadPosition = this.nextLoadPosition,
  10257. startPosition = this.startPosition;
  10258. if (startPosition === -1 && nextLoadPosition) {
  10259. return nextLoadPosition;
  10260. }
  10261. return startPosition;
  10262. }
  10263. }, {
  10264. key: "bufferingEnabled",
  10265. get: function get() {
  10266. return this.buffering;
  10267. }
  10268. }, {
  10269. key: "inFlightFrag",
  10270. get: function get() {
  10271. return {
  10272. frag: this.fragCurrent,
  10273. state: this.state
  10274. };
  10275. }
  10276. }, {
  10277. key: "timelineOffset",
  10278. get: function get() {
  10279. var configuredTimelineOffset = this.config.timelineOffset;
  10280. if (configuredTimelineOffset) {
  10281. var _this$getLevelDetails;
  10282. return ((_this$getLevelDetails = this.getLevelDetails()) == null ? void 0 : _this$getLevelDetails.appliedTimelineOffset) || configuredTimelineOffset;
  10283. }
  10284. return 0;
  10285. }
  10286. }, {
  10287. key: "primaryPrefetch",
  10288. get: function get() {
  10289. if (interstitialsEnabled(this.hls.config)) {
  10290. var _this$hls$interstitia, _this$hls$interstitia2;
  10291. var playingInterstitial = (_this$hls$interstitia = this.hls.interstitialsManager) == null ? void 0 : (_this$hls$interstitia2 = _this$hls$interstitia.playingItem) == null ? void 0 : _this$hls$interstitia2.event;
  10292. if (playingInterstitial) {
  10293. return true;
  10294. }
  10295. }
  10296. return false;
  10297. }
  10298. }, {
  10299. key: "state",
  10300. get: function get() {
  10301. return this._state;
  10302. },
  10303. set: function set(nextState) {
  10304. var previousState = this._state;
  10305. if (previousState !== nextState) {
  10306. this._state = nextState;
  10307. this.log(previousState + "->" + nextState);
  10308. }
  10309. }
  10310. }]);
  10311. }(TaskLoop);
  10312. function interstitialsEnabled(config) {
  10313. return !!config.interstitialsController && config.enableInterstitialPlayback !== false;
  10314. }
  10315. var ChunkCache = /*#__PURE__*/function () {
  10316. function ChunkCache() {
  10317. this.chunks = [];
  10318. this.dataLength = 0;
  10319. }
  10320. var _proto = ChunkCache.prototype;
  10321. _proto.push = function push(chunk) {
  10322. this.chunks.push(chunk);
  10323. this.dataLength += chunk.length;
  10324. };
  10325. _proto.flush = function flush() {
  10326. var chunks = this.chunks,
  10327. dataLength = this.dataLength;
  10328. var result;
  10329. if (!chunks.length) {
  10330. return new Uint8Array(0);
  10331. } else if (chunks.length === 1) {
  10332. result = chunks[0];
  10333. } else {
  10334. result = concatUint8Arrays(chunks, dataLength);
  10335. }
  10336. this.reset();
  10337. return result;
  10338. };
  10339. _proto.reset = function reset() {
  10340. this.chunks.length = 0;
  10341. this.dataLength = 0;
  10342. };
  10343. return ChunkCache;
  10344. }();
  10345. function concatUint8Arrays(chunks, dataLength) {
  10346. var result = new Uint8Array(dataLength);
  10347. var offset = 0;
  10348. for (var i = 0; i < chunks.length; i++) {
  10349. var chunk = chunks[i];
  10350. result.set(chunk, offset);
  10351. offset += chunk.length;
  10352. }
  10353. return result;
  10354. }
  10355. /**
  10356. * Returns true if an ID3 footer can be found at offset in data
  10357. *
  10358. * @param data - The data to search in
  10359. * @param offset - The offset at which to start searching
  10360. *
  10361. * @returns `true` if an ID3 footer is found
  10362. *
  10363. * @internal
  10364. *
  10365. * @group ID3
  10366. */
  10367. function isId3Footer(data, offset) {
  10368. /*
  10369. * The footer is a copy of the header, but with a different identifier
  10370. */
  10371. if (offset + 10 <= data.length) {
  10372. // look for '3DI' identifier
  10373. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  10374. // check version is within range
  10375. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  10376. // check size is within range
  10377. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  10378. return true;
  10379. }
  10380. }
  10381. }
  10382. }
  10383. return false;
  10384. }
  10385. /**
  10386. * Returns true if an ID3 header can be found at offset in data
  10387. *
  10388. * @param data - The data to search in
  10389. * @param offset - The offset at which to start searching
  10390. *
  10391. * @returns `true` if an ID3 header is found
  10392. *
  10393. * @internal
  10394. *
  10395. * @group ID3
  10396. */
  10397. function isId3Header(data, offset) {
  10398. /*
  10399. * http://id3.org/id3v2.3.0
  10400. * [0] = 'I'
  10401. * [1] = 'D'
  10402. * [2] = '3'
  10403. * [3,4] = {Version}
  10404. * [5] = {Flags}
  10405. * [6-9] = {ID3 Size}
  10406. *
  10407. * An ID3v2 tag can be detected with the following pattern:
  10408. * $49 44 33 yy yy xx zz zz zz zz
  10409. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  10410. */
  10411. if (offset + 10 <= data.length) {
  10412. // look for 'ID3' identifier
  10413. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  10414. // check version is within range
  10415. if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
  10416. // check size is within range
  10417. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  10418. return true;
  10419. }
  10420. }
  10421. }
  10422. }
  10423. return false;
  10424. }
  10425. /**
  10426. * Read ID3 size
  10427. *
  10428. * @param data - The data to read from
  10429. * @param offset - The offset at which to start reading
  10430. *
  10431. * @returns The size
  10432. *
  10433. * @internal
  10434. *
  10435. * @group ID3
  10436. */
  10437. function readId3Size(data, offset) {
  10438. var size = 0;
  10439. size = (data[offset] & 0x7f) << 21;
  10440. size |= (data[offset + 1] & 0x7f) << 14;
  10441. size |= (data[offset + 2] & 0x7f) << 7;
  10442. size |= data[offset + 3] & 0x7f;
  10443. return size;
  10444. }
  10445. /**
  10446. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  10447. *
  10448. * @param data - The data to search in
  10449. * @param offset - The offset at which to start searching
  10450. *
  10451. * @returns The block of data containing any ID3 tags found
  10452. * or `undefined` if no header is found at the starting offset
  10453. *
  10454. * @internal
  10455. *
  10456. * @group ID3
  10457. */
  10458. function getId3Data(data, offset) {
  10459. var front = offset;
  10460. var length = 0;
  10461. while (isId3Header(data, offset)) {
  10462. // ID3 header is 10 bytes
  10463. length += 10;
  10464. var size = readId3Size(data, offset + 6);
  10465. length += size;
  10466. if (isId3Footer(data, offset + 10)) {
  10467. // ID3 footer is 10 bytes
  10468. length += 10;
  10469. }
  10470. offset += length;
  10471. }
  10472. if (length > 0) {
  10473. return data.subarray(front, front + length);
  10474. }
  10475. return undefined;
  10476. }
  10477. function getAudioConfig(observer, data, offset, manifestCodec) {
  10478. var adtsSamplingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  10479. var byte2 = data[offset + 2];
  10480. var adtsSamplingIndex = byte2 >> 2 & 0xf;
  10481. if (adtsSamplingIndex > 12) {
  10482. var error = new Error("invalid ADTS sampling index:" + adtsSamplingIndex);
  10483. observer.emit(Events.ERROR, Events.ERROR, {
  10484. type: ErrorTypes.MEDIA_ERROR,
  10485. details: ErrorDetails.FRAG_PARSING_ERROR,
  10486. fatal: true,
  10487. error: error,
  10488. reason: error.message
  10489. });
  10490. return;
  10491. }
  10492. // MPEG-4 Audio Object Type (profile_ObjectType+1)
  10493. var adtsObjectType = (byte2 >> 6 & 0x3) + 1;
  10494. var channelCount = data[offset + 3] >> 6 & 0x3 | (byte2 & 1) << 2;
  10495. var codec = 'mp4a.40.' + adtsObjectType;
  10496. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  10497. ISO/IEC 14496-3 - Table 1.13 — Syntax of AudioSpecificConfig()
  10498. Audio Profile / Audio Object Type
  10499. 0: Null
  10500. 1: AAC Main
  10501. 2: AAC LC (Low Complexity)
  10502. 3: AAC SSR (Scalable Sample Rate)
  10503. 4: AAC LTP (Long Term Prediction)
  10504. 5: SBR (Spectral Band Replication)
  10505. 6: AAC Scalable
  10506. sampling freq
  10507. 0: 96000 Hz
  10508. 1: 88200 Hz
  10509. 2: 64000 Hz
  10510. 3: 48000 Hz
  10511. 4: 44100 Hz
  10512. 5: 32000 Hz
  10513. 6: 24000 Hz
  10514. 7: 22050 Hz
  10515. 8: 16000 Hz
  10516. 9: 12000 Hz
  10517. 10: 11025 Hz
  10518. 11: 8000 Hz
  10519. 12: 7350 Hz
  10520. 13: Reserved
  10521. 14: Reserved
  10522. 15: frequency is written explictly
  10523. Channel Configurations
  10524. These are the channel configurations:
  10525. 0: Defined in AOT Specifc Config
  10526. 1: 1 channel: front-center
  10527. 2: 2 channels: front-left, front-right
  10528. */
  10529. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  10530. var samplerate = adtsSamplingRates[adtsSamplingIndex];
  10531. var aacSampleIndex = adtsSamplingIndex;
  10532. if (adtsObjectType === 5 || adtsObjectType === 29) {
  10533. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  10534. // there is a factor 2 between frame sample rate and output sample rate
  10535. // multiply frequency by 2 (see table above, equivalent to substract 3)
  10536. aacSampleIndex -= 3;
  10537. }
  10538. var config = [adtsObjectType << 3 | (aacSampleIndex & 0x0e) >> 1, (aacSampleIndex & 0x01) << 7 | channelCount << 3];
  10539. logger.log("manifest codec:" + manifestCodec + ", parsed codec:" + codec + ", channels:" + channelCount + ", rate:" + samplerate + " (ADTS object type:" + adtsObjectType + " sampling index:" + adtsSamplingIndex + ")");
  10540. return {
  10541. config: config,
  10542. samplerate: samplerate,
  10543. channelCount: channelCount,
  10544. codec: codec,
  10545. parsedCodec: codec,
  10546. manifestCodec: manifestCodec
  10547. };
  10548. }
  10549. function isHeaderPattern$1(data, offset) {
  10550. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  10551. }
  10552. function getHeaderLength(data, offset) {
  10553. return data[offset + 1] & 0x01 ? 7 : 9;
  10554. }
  10555. function getFullFrameLength(data, offset) {
  10556. return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
  10557. }
  10558. function canGetFrameLength(data, offset) {
  10559. return offset + 5 < data.length;
  10560. }
  10561. function isHeader$1(data, offset) {
  10562. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  10563. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  10564. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  10565. return offset + 1 < data.length && isHeaderPattern$1(data, offset);
  10566. }
  10567. function canParse$1(data, offset) {
  10568. return canGetFrameLength(data, offset) && isHeaderPattern$1(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
  10569. }
  10570. function probe$1(data, offset) {
  10571. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  10572. // or end of data is reached
  10573. if (isHeader$1(data, offset)) {
  10574. // ADTS header Length
  10575. var headerLength = getHeaderLength(data, offset);
  10576. if (offset + headerLength >= data.length) {
  10577. return false;
  10578. }
  10579. // ADTS frame Length
  10580. var frameLength = getFullFrameLength(data, offset);
  10581. if (frameLength <= headerLength) {
  10582. return false;
  10583. }
  10584. var newOffset = offset + frameLength;
  10585. return newOffset === data.length || isHeader$1(data, newOffset);
  10586. }
  10587. return false;
  10588. }
  10589. function initTrackConfig(track, observer, data, offset, audioCodec) {
  10590. if (!track.samplerate) {
  10591. var config = getAudioConfig(observer, data, offset, audioCodec);
  10592. if (!config) {
  10593. return;
  10594. }
  10595. _extends(track, config);
  10596. }
  10597. }
  10598. function getFrameDuration(samplerate) {
  10599. return 1024 * 90000 / samplerate;
  10600. }
  10601. function parseFrameHeader(data, offset) {
  10602. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  10603. var headerLength = getHeaderLength(data, offset);
  10604. if (offset + headerLength <= data.length) {
  10605. // retrieve frame size
  10606. var frameLength = getFullFrameLength(data, offset) - headerLength;
  10607. if (frameLength > 0) {
  10608. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);
  10609. return {
  10610. headerLength: headerLength,
  10611. frameLength: frameLength
  10612. };
  10613. }
  10614. }
  10615. }
  10616. function appendFrame$1(track, data, offset, pts, frameIndex) {
  10617. var frameDuration = getFrameDuration(track.samplerate);
  10618. var stamp = pts + frameIndex * frameDuration;
  10619. var header = parseFrameHeader(data, offset);
  10620. var unit;
  10621. if (header) {
  10622. var frameLength = header.frameLength,
  10623. headerLength = header.headerLength;
  10624. var _length = headerLength + frameLength;
  10625. var missing = Math.max(0, offset + _length - data.length);
  10626. // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
  10627. if (missing) {
  10628. unit = new Uint8Array(_length - headerLength);
  10629. unit.set(data.subarray(offset + headerLength, data.length), 0);
  10630. } else {
  10631. unit = data.subarray(offset + headerLength, offset + _length);
  10632. }
  10633. var _sample = {
  10634. unit: unit,
  10635. pts: stamp
  10636. };
  10637. if (!missing) {
  10638. track.samples.push(_sample);
  10639. }
  10640. return {
  10641. sample: _sample,
  10642. length: _length,
  10643. missing: missing
  10644. };
  10645. }
  10646. // overflow incomplete header
  10647. var length = data.length - offset;
  10648. unit = new Uint8Array(length);
  10649. unit.set(data.subarray(offset, data.length), 0);
  10650. var sample = {
  10651. unit: unit,
  10652. pts: stamp
  10653. };
  10654. return {
  10655. sample: sample,
  10656. length: length,
  10657. missing: -1
  10658. };
  10659. }
  10660. /**
  10661. * Checks if the given data contains an ID3 tag.
  10662. *
  10663. * @param data - The data to check
  10664. * @param offset - The offset at which to start checking
  10665. *
  10666. * @returns `true` if an ID3 tag is found
  10667. *
  10668. * @group ID3
  10669. *
  10670. * @beta
  10671. */
  10672. function canParseId3(data, offset) {
  10673. return isId3Header(data, offset) && readId3Size(data, offset + 6) + 10 <= data.length - offset;
  10674. }
  10675. function toArrayBuffer(view) {
  10676. if (view instanceof ArrayBuffer) {
  10677. return view;
  10678. } else {
  10679. if (view.byteOffset == 0 && view.byteLength == view.buffer.byteLength) {
  10680. // This is a TypedArray over the whole buffer.
  10681. return view.buffer;
  10682. }
  10683. // This is a 'view' on the buffer. Create a new buffer that only contains
  10684. // the data. Note that since this isn't an ArrayBuffer, the 'new' call
  10685. // will allocate a new buffer to hold the copy.
  10686. return new Uint8Array(view).buffer;
  10687. }
  10688. }
  10689. function toUint8(data, offset, length) {
  10690. if (offset === void 0) {
  10691. offset = 0;
  10692. }
  10693. if (length === void 0) {
  10694. length = Infinity;
  10695. }
  10696. return view(data, offset, length, Uint8Array);
  10697. }
  10698. function view(data, offset, length, Type) {
  10699. var buffer = unsafeGetArrayBuffer(data);
  10700. var bytesPerElement = 1;
  10701. if ('BYTES_PER_ELEMENT' in Type) {
  10702. bytesPerElement = Type.BYTES_PER_ELEMENT;
  10703. }
  10704. // Absolute end of the |data| view within |buffer|.
  10705. var dataOffset = isArrayBufferView(data) ? data.byteOffset : 0;
  10706. var dataEnd = (dataOffset + data.byteLength) / bytesPerElement;
  10707. // Absolute start of the result within |buffer|.
  10708. var rawStart = (dataOffset + offset) / bytesPerElement;
  10709. var start = Math.floor(Math.max(0, Math.min(rawStart, dataEnd)));
  10710. // Absolute end of the result within |buffer|.
  10711. var end = Math.floor(Math.min(start + Math.max(length, 0), dataEnd));
  10712. return new Type(buffer, start, end - start);
  10713. }
  10714. function unsafeGetArrayBuffer(view) {
  10715. if (view instanceof ArrayBuffer) {
  10716. return view;
  10717. } else {
  10718. return view.buffer;
  10719. }
  10720. }
  10721. function isArrayBufferView(obj) {
  10722. return obj && obj.buffer instanceof ArrayBuffer && obj.byteLength !== undefined && obj.byteOffset !== undefined;
  10723. }
  10724. function decodeId3ImageFrame(frame) {
  10725. var metadataFrame = {
  10726. key: frame.type,
  10727. description: '',
  10728. data: '',
  10729. mimeType: null,
  10730. pictureType: null
  10731. };
  10732. var utf8Encoding = 0x03;
  10733. if (frame.size < 2) {
  10734. return undefined;
  10735. }
  10736. if (frame.data[0] !== utf8Encoding) {
  10737. console.log('Ignore frame with unrecognized character ' + 'encoding');
  10738. return undefined;
  10739. }
  10740. var mimeTypeEndIndex = frame.data.subarray(1).indexOf(0);
  10741. if (mimeTypeEndIndex === -1) {
  10742. return undefined;
  10743. }
  10744. var mimeType = utf8ArrayToStr(toUint8(frame.data, 1, mimeTypeEndIndex));
  10745. var pictureType = frame.data[2 + mimeTypeEndIndex];
  10746. var descriptionEndIndex = frame.data.subarray(3 + mimeTypeEndIndex).indexOf(0);
  10747. if (descriptionEndIndex === -1) {
  10748. return undefined;
  10749. }
  10750. var description = utf8ArrayToStr(toUint8(frame.data, 3 + mimeTypeEndIndex, descriptionEndIndex));
  10751. var data;
  10752. if (mimeType === '-->') {
  10753. data = utf8ArrayToStr(toUint8(frame.data, 4 + mimeTypeEndIndex + descriptionEndIndex));
  10754. } else {
  10755. data = toArrayBuffer(frame.data.subarray(4 + mimeTypeEndIndex + descriptionEndIndex));
  10756. }
  10757. metadataFrame.mimeType = mimeType;
  10758. metadataFrame.pictureType = pictureType;
  10759. metadataFrame.description = description;
  10760. metadataFrame.data = data;
  10761. return metadataFrame;
  10762. }
  10763. /**
  10764. * Decode an ID3 PRIV frame.
  10765. *
  10766. * @param frame - the ID3 PRIV frame
  10767. *
  10768. * @returns The decoded ID3 PRIV frame
  10769. *
  10770. * @internal
  10771. *
  10772. * @group ID3
  10773. */
  10774. function decodeId3PrivFrame(frame) {
  10775. /*
  10776. Format: <text string>\0<binary data>
  10777. */
  10778. if (frame.size < 2) {
  10779. return undefined;
  10780. }
  10781. var owner = utf8ArrayToStr(frame.data, true);
  10782. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  10783. return {
  10784. key: frame.type,
  10785. info: owner,
  10786. data: privateData.buffer
  10787. };
  10788. }
  10789. /**
  10790. * Decodes an ID3 text frame
  10791. *
  10792. * @param frame - the ID3 text frame
  10793. *
  10794. * @returns The decoded ID3 text frame
  10795. *
  10796. * @internal
  10797. *
  10798. * @group ID3
  10799. */
  10800. function decodeId3TextFrame(frame) {
  10801. if (frame.size < 2) {
  10802. return undefined;
  10803. }
  10804. if (frame.type === 'TXXX') {
  10805. /*
  10806. Format:
  10807. [0] = {Text Encoding}
  10808. [1-?] = {Description}\0{Value}
  10809. */
  10810. var index = 1;
  10811. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  10812. index += description.length + 1;
  10813. var value = utf8ArrayToStr(frame.data.subarray(index));
  10814. return {
  10815. key: frame.type,
  10816. info: description,
  10817. data: value
  10818. };
  10819. }
  10820. /*
  10821. Format:
  10822. [0] = {Text Encoding}
  10823. [1-?] = {Value}
  10824. */
  10825. var text = utf8ArrayToStr(frame.data.subarray(1));
  10826. return {
  10827. key: frame.type,
  10828. info: '',
  10829. data: text
  10830. };
  10831. }
  10832. /**
  10833. * Decode a URL frame
  10834. *
  10835. * @param frame - the ID3 URL frame
  10836. *
  10837. * @returns The decoded ID3 URL frame
  10838. *
  10839. * @internal
  10840. *
  10841. * @group ID3
  10842. */
  10843. function decodeId3UrlFrame(frame) {
  10844. if (frame.type === 'WXXX') {
  10845. /*
  10846. Format:
  10847. [0] = {Text Encoding}
  10848. [1-?] = {Description}\0{URL}
  10849. */
  10850. if (frame.size < 2) {
  10851. return undefined;
  10852. }
  10853. var index = 1;
  10854. var description = utf8ArrayToStr(frame.data.subarray(index), true);
  10855. index += description.length + 1;
  10856. var value = utf8ArrayToStr(frame.data.subarray(index));
  10857. return {
  10858. key: frame.type,
  10859. info: description,
  10860. data: value
  10861. };
  10862. }
  10863. /*
  10864. Format:
  10865. [0-?] = {URL}
  10866. */
  10867. var url = utf8ArrayToStr(frame.data);
  10868. return {
  10869. key: frame.type,
  10870. info: '',
  10871. data: url
  10872. };
  10873. }
  10874. /**
  10875. * Decode an ID3 frame.
  10876. *
  10877. * @param frame - the ID3 frame
  10878. *
  10879. * @returns The decoded ID3 frame
  10880. *
  10881. * @internal
  10882. *
  10883. * @group ID3
  10884. */
  10885. function decodeId3Frame(frame) {
  10886. if (frame.type === 'PRIV') {
  10887. return decodeId3PrivFrame(frame);
  10888. } else if (frame.type[0] === 'W') {
  10889. return decodeId3UrlFrame(frame);
  10890. } else if (frame.type === 'APIC') {
  10891. return decodeId3ImageFrame(frame);
  10892. }
  10893. return decodeId3TextFrame(frame);
  10894. }
  10895. /**
  10896. * Returns the data of an ID3 frame.
  10897. *
  10898. * @param data - The data to read from
  10899. *
  10900. * @returns The data of the ID3 frame
  10901. *
  10902. * @internal
  10903. *
  10904. * @group ID3
  10905. */
  10906. function getId3FrameData(data) {
  10907. /*
  10908. Frame ID $xx xx xx xx (four characters)
  10909. Size $xx xx xx xx
  10910. Flags $xx xx
  10911. */
  10912. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  10913. var size = readId3Size(data, 4);
  10914. // skip frame id, size, and flags
  10915. var offset = 10;
  10916. return {
  10917. type: type,
  10918. size: size,
  10919. data: data.subarray(offset, offset + size)
  10920. };
  10921. }
  10922. var HEADER_FOOTER_SIZE = 10;
  10923. var FRAME_SIZE = 10;
  10924. /**
  10925. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  10926. *
  10927. * @param id3Data - The ID3 data containing one or more ID3 tags
  10928. *
  10929. * @returns Array of ID3 frame objects
  10930. *
  10931. * @group ID3
  10932. *
  10933. * @beta
  10934. */
  10935. function getId3Frames(id3Data) {
  10936. var offset = 0;
  10937. var frames = [];
  10938. while (isId3Header(id3Data, offset)) {
  10939. var size = readId3Size(id3Data, offset + 6);
  10940. if (id3Data[offset + 5] >> 6 & 1) {
  10941. // skip extended header
  10942. offset += HEADER_FOOTER_SIZE;
  10943. }
  10944. // skip past ID3 header
  10945. offset += HEADER_FOOTER_SIZE;
  10946. var end = offset + size;
  10947. // loop through frames in the ID3 tag
  10948. while (offset + FRAME_SIZE < end) {
  10949. var frameData = getId3FrameData(id3Data.subarray(offset));
  10950. var frame = decodeId3Frame(frameData);
  10951. if (frame) {
  10952. frames.push(frame);
  10953. }
  10954. // skip frame header and frame data
  10955. offset += frameData.size + HEADER_FOOTER_SIZE;
  10956. }
  10957. if (isId3Footer(id3Data, offset)) {
  10958. offset += HEADER_FOOTER_SIZE;
  10959. }
  10960. }
  10961. return frames;
  10962. }
  10963. /**
  10964. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  10965. *
  10966. * @param frame - the ID3 frame
  10967. *
  10968. * @returns `true` if the ID3 frame is an Elementary Stream timestamp frame
  10969. *
  10970. * @internal
  10971. *
  10972. * @group ID3
  10973. */
  10974. function isId3TimestampFrame(frame) {
  10975. return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
  10976. }
  10977. /**
  10978. * Read a 33 bit timestamp from an ID3 frame.
  10979. *
  10980. * @param timeStampFrame - the ID3 frame
  10981. *
  10982. * @returns The timestamp
  10983. *
  10984. * @internal
  10985. *
  10986. * @group ID3
  10987. */
  10988. function readId3Timestamp(timeStampFrame) {
  10989. if (timeStampFrame.data.byteLength === 8) {
  10990. var data = new Uint8Array(timeStampFrame.data);
  10991. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  10992. // with the upper 31 bits set to zero.
  10993. var pts33Bit = data[3] & 0x1;
  10994. var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
  10995. timestamp /= 45;
  10996. if (pts33Bit) {
  10997. timestamp += 47721858.84;
  10998. } // 2^32 / 90
  10999. return Math.round(timestamp);
  11000. }
  11001. return undefined;
  11002. }
  11003. /**
  11004. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  11005. *
  11006. * @param data - Block of data containing one or more ID3 tags
  11007. *
  11008. * @returns The timestamp
  11009. *
  11010. * @group ID3
  11011. *
  11012. * @beta
  11013. */
  11014. function getId3Timestamp(data) {
  11015. var frames = getId3Frames(data);
  11016. for (var i = 0; i < frames.length; i++) {
  11017. var frame = frames[i];
  11018. if (isId3TimestampFrame(frame)) {
  11019. return readId3Timestamp(frame);
  11020. }
  11021. }
  11022. return undefined;
  11023. }
  11024. var MetadataSchema = /*#__PURE__*/function (MetadataSchema) {
  11025. MetadataSchema["audioId3"] = "org.id3";
  11026. MetadataSchema["dateRange"] = "com.apple.quicktime.HLS";
  11027. MetadataSchema["emsg"] = "https://aomedia.org/emsg/ID3";
  11028. MetadataSchema["misbklv"] = "urn:misb:KLV:bin:1910.1";
  11029. return MetadataSchema;
  11030. }({});
  11031. function dummyTrack(type, inputTimeScale) {
  11032. if (type === void 0) {
  11033. type = '';
  11034. }
  11035. if (inputTimeScale === void 0) {
  11036. inputTimeScale = 90000;
  11037. }
  11038. return {
  11039. type: type,
  11040. id: -1,
  11041. pid: -1,
  11042. inputTimeScale: inputTimeScale,
  11043. sequenceNumber: -1,
  11044. samples: [],
  11045. dropped: 0
  11046. };
  11047. }
  11048. var BaseAudioDemuxer = /*#__PURE__*/function () {
  11049. function BaseAudioDemuxer() {
  11050. this._audioTrack = void 0;
  11051. this._id3Track = void 0;
  11052. this.frameIndex = 0;
  11053. this.cachedData = null;
  11054. this.basePTS = null;
  11055. this.initPTS = null;
  11056. this.lastPTS = null;
  11057. }
  11058. var _proto = BaseAudioDemuxer.prototype;
  11059. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11060. this._id3Track = {
  11061. type: 'id3',
  11062. id: 3,
  11063. pid: -1,
  11064. inputTimeScale: 90000,
  11065. sequenceNumber: 0,
  11066. samples: [],
  11067. dropped: 0
  11068. };
  11069. };
  11070. _proto.resetTimeStamp = function resetTimeStamp(deaultTimestamp) {
  11071. this.initPTS = deaultTimestamp;
  11072. this.resetContiguity();
  11073. };
  11074. _proto.resetContiguity = function resetContiguity() {
  11075. this.basePTS = null;
  11076. this.lastPTS = null;
  11077. this.frameIndex = 0;
  11078. };
  11079. _proto.canParse = function canParse(data, offset) {
  11080. return false;
  11081. };
  11082. _proto.appendFrame = function appendFrame(track, data, offset) {}
  11083. // feed incoming data to the front of the parsing pipeline
  11084. ;
  11085. _proto.demux = function demux(data, timeOffset) {
  11086. if (this.cachedData) {
  11087. data = appendUint8Array(this.cachedData, data);
  11088. this.cachedData = null;
  11089. }
  11090. var id3Data = getId3Data(data, 0);
  11091. var offset = id3Data ? id3Data.length : 0;
  11092. var lastDataIndex;
  11093. var track = this._audioTrack;
  11094. var id3Track = this._id3Track;
  11095. var timestamp = id3Data ? getId3Timestamp(id3Data) : undefined;
  11096. var length = data.length;
  11097. if (this.basePTS === null || this.frameIndex === 0 && isFiniteNumber(timestamp)) {
  11098. this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);
  11099. this.lastPTS = this.basePTS;
  11100. }
  11101. if (this.lastPTS === null) {
  11102. this.lastPTS = this.basePTS;
  11103. }
  11104. // more expressive than alternative: id3Data?.length
  11105. if (id3Data && id3Data.length > 0) {
  11106. id3Track.samples.push({
  11107. pts: this.lastPTS,
  11108. dts: this.lastPTS,
  11109. data: id3Data,
  11110. type: MetadataSchema.audioId3,
  11111. duration: Number.POSITIVE_INFINITY
  11112. });
  11113. }
  11114. while (offset < length) {
  11115. if (this.canParse(data, offset)) {
  11116. var frame = this.appendFrame(track, data, offset);
  11117. if (frame) {
  11118. this.frameIndex++;
  11119. this.lastPTS = frame.sample.pts;
  11120. offset += frame.length;
  11121. lastDataIndex = offset;
  11122. } else {
  11123. offset = length;
  11124. }
  11125. } else if (canParseId3(data, offset)) {
  11126. // after a canParse, a call to getId3Data *should* always returns some data
  11127. id3Data = getId3Data(data, offset);
  11128. id3Track.samples.push({
  11129. pts: this.lastPTS,
  11130. dts: this.lastPTS,
  11131. data: id3Data,
  11132. type: MetadataSchema.audioId3,
  11133. duration: Number.POSITIVE_INFINITY
  11134. });
  11135. offset += id3Data.length;
  11136. lastDataIndex = offset;
  11137. } else {
  11138. offset++;
  11139. }
  11140. if (offset === length && lastDataIndex !== length) {
  11141. var partialData = data.slice(lastDataIndex);
  11142. if (this.cachedData) {
  11143. this.cachedData = appendUint8Array(this.cachedData, partialData);
  11144. } else {
  11145. this.cachedData = partialData;
  11146. }
  11147. }
  11148. }
  11149. return {
  11150. audioTrack: track,
  11151. videoTrack: dummyTrack(),
  11152. id3Track: id3Track,
  11153. textTrack: dummyTrack()
  11154. };
  11155. };
  11156. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  11157. return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
  11158. };
  11159. _proto.flush = function flush(timeOffset) {
  11160. // Parse cache in case of remaining frames.
  11161. var cachedData = this.cachedData;
  11162. if (cachedData) {
  11163. this.cachedData = null;
  11164. this.demux(cachedData, 0);
  11165. }
  11166. return {
  11167. audioTrack: this._audioTrack,
  11168. videoTrack: dummyTrack(),
  11169. id3Track: this._id3Track,
  11170. textTrack: dummyTrack()
  11171. };
  11172. };
  11173. _proto.destroy = function destroy() {
  11174. this.cachedData = null;
  11175. // @ts-ignore
  11176. this._audioTrack = this._id3Track = undefined;
  11177. };
  11178. return BaseAudioDemuxer;
  11179. }();
  11180. /**
  11181. * Initialize PTS
  11182. * <p>
  11183. * use timestamp unless it is undefined, NaN or Infinity
  11184. * </p>
  11185. */
  11186. var initPTSFn = function initPTSFn(timestamp, timeOffset, initPTS) {
  11187. if (isFiniteNumber(timestamp)) {
  11188. return timestamp * 90;
  11189. }
  11190. var init90kHz = initPTS ? initPTS.baseTime * 90000 / initPTS.timescale : 0;
  11191. return timeOffset * 90000 + init90kHz;
  11192. };
  11193. /**
  11194. * MPEG parser helper
  11195. */
  11196. var chromeVersion$1 = null;
  11197. var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
  11198. var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
  11199. var SamplesCoefficients = [
  11200. // MPEG 2.5
  11201. [0,
  11202. // Reserved
  11203. 72,
  11204. // Layer3
  11205. 144,
  11206. // Layer2
  11207. 12 // Layer1
  11208. ],
  11209. // Reserved
  11210. [0,
  11211. // Reserved
  11212. 0,
  11213. // Layer3
  11214. 0,
  11215. // Layer2
  11216. 0 // Layer1
  11217. ],
  11218. // MPEG 2
  11219. [0,
  11220. // Reserved
  11221. 72,
  11222. // Layer3
  11223. 144,
  11224. // Layer2
  11225. 12 // Layer1
  11226. ],
  11227. // MPEG 1
  11228. [0,
  11229. // Reserved
  11230. 144,
  11231. // Layer3
  11232. 144,
  11233. // Layer2
  11234. 12 // Layer1
  11235. ]];
  11236. var BytesInSlot = [0,
  11237. // Reserved
  11238. 1,
  11239. // Layer3
  11240. 1,
  11241. // Layer2
  11242. 4 // Layer1
  11243. ];
  11244. function appendFrame(track, data, offset, pts, frameIndex) {
  11245. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  11246. if (offset + 24 > data.length) {
  11247. return;
  11248. }
  11249. var header = parseHeader(data, offset);
  11250. if (header && offset + header.frameLength <= data.length) {
  11251. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  11252. var stamp = pts + frameIndex * frameDuration;
  11253. var sample = {
  11254. unit: data.subarray(offset, offset + header.frameLength),
  11255. pts: stamp,
  11256. dts: stamp
  11257. };
  11258. track.config = [];
  11259. track.channelCount = header.channelCount;
  11260. track.samplerate = header.sampleRate;
  11261. track.samples.push(sample);
  11262. return {
  11263. sample: sample,
  11264. length: header.frameLength,
  11265. missing: 0
  11266. };
  11267. }
  11268. }
  11269. function parseHeader(data, offset) {
  11270. var mpegVersion = data[offset + 1] >> 3 & 3;
  11271. var mpegLayer = data[offset + 1] >> 1 & 3;
  11272. var bitRateIndex = data[offset + 2] >> 4 & 15;
  11273. var sampleRateIndex = data[offset + 2] >> 2 & 3;
  11274. if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
  11275. var paddingBit = data[offset + 2] >> 1 & 1;
  11276. var channelMode = data[offset + 3] >> 6;
  11277. var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
  11278. var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
  11279. var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
  11280. var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
  11281. var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  11282. var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
  11283. var bytesInSlot = BytesInSlot[mpegLayer];
  11284. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  11285. var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
  11286. if (chromeVersion$1 === null) {
  11287. var userAgent = navigator.userAgent || '';
  11288. var result = userAgent.match(/Chrome\/(\d+)/i);
  11289. chromeVersion$1 = result ? parseInt(result[1]) : 0;
  11290. }
  11291. var needChromeFix = !!chromeVersion$1 && chromeVersion$1 <= 87;
  11292. if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
  11293. // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
  11294. data[offset + 3] = data[offset + 3] | 0x80;
  11295. }
  11296. return {
  11297. sampleRate: sampleRate,
  11298. channelCount: channelCount,
  11299. frameLength: frameLength,
  11300. samplesPerFrame: samplesPerFrame
  11301. };
  11302. }
  11303. }
  11304. function isHeaderPattern(data, offset) {
  11305. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  11306. }
  11307. function isHeader(data, offset) {
  11308. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  11309. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  11310. // More info http://www.mp3-tech.org/programmer/frame_header.html
  11311. return offset + 1 < data.length && isHeaderPattern(data, offset);
  11312. }
  11313. function canParse(data, offset) {
  11314. var headerSize = 4;
  11315. return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
  11316. }
  11317. function probe(data, offset) {
  11318. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  11319. // or end of data is reached
  11320. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  11321. // MPEG header Length
  11322. var headerLength = 4;
  11323. // MPEG frame Length
  11324. var header = parseHeader(data, offset);
  11325. var frameLength = headerLength;
  11326. if (header != null && header.frameLength) {
  11327. frameLength = header.frameLength;
  11328. }
  11329. var newOffset = offset + frameLength;
  11330. return newOffset === data.length || isHeader(data, newOffset);
  11331. }
  11332. return false;
  11333. }
  11334. var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  11335. function AACDemuxer(observer, config) {
  11336. var _this;
  11337. _this = _BaseAudioDemuxer.call(this) || this;
  11338. _this.observer = void 0;
  11339. _this.config = void 0;
  11340. _this.observer = observer;
  11341. _this.config = config;
  11342. return _this;
  11343. }
  11344. _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
  11345. var _proto = AACDemuxer.prototype;
  11346. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11347. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  11348. this._audioTrack = {
  11349. container: 'audio/adts',
  11350. type: 'audio',
  11351. id: 2,
  11352. pid: -1,
  11353. sequenceNumber: 0,
  11354. segmentCodec: 'aac',
  11355. samples: [],
  11356. manifestCodec: audioCodec,
  11357. duration: trackDuration,
  11358. inputTimeScale: 90000,
  11359. dropped: 0
  11360. };
  11361. }
  11362. // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
  11363. ;
  11364. AACDemuxer.probe = function probe$2(data, logger) {
  11365. if (!data) {
  11366. return false;
  11367. }
  11368. // Check for the ADTS sync word
  11369. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  11370. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  11371. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  11372. var id3Data = getId3Data(data, 0);
  11373. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  11374. if (probe(data, offset)) {
  11375. return false;
  11376. }
  11377. for (var length = data.length; offset < length; offset++) {
  11378. if (probe$1(data, offset)) {
  11379. logger.log('ADTS sync word found !');
  11380. return true;
  11381. }
  11382. }
  11383. return false;
  11384. };
  11385. _proto.canParse = function canParse(data, offset) {
  11386. return canParse$1(data, offset);
  11387. };
  11388. _proto.appendFrame = function appendFrame(track, data, offset) {
  11389. initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  11390. var frame = appendFrame$1(track, data, offset, this.basePTS, this.frameIndex);
  11391. if (frame && frame.missing === 0) {
  11392. return frame;
  11393. }
  11394. };
  11395. return AACDemuxer;
  11396. }(BaseAudioDemuxer);
  11397. var getAudioBSID = function getAudioBSID(data, offset) {
  11398. // check the bsid to confirm ac-3 | ec-3
  11399. var bsid = 0;
  11400. var numBits = 5;
  11401. offset += numBits;
  11402. var temp = new Uint32Array(1); // unsigned 32 bit for temporary storage
  11403. var mask = new Uint32Array(1); // unsigned 32 bit mask value
  11404. var _byte = new Uint8Array(1); // unsigned 8 bit for temporary storage
  11405. while (numBits > 0) {
  11406. _byte[0] = data[offset];
  11407. // read remaining bits, upto 8 bits at a time
  11408. var bits = Math.min(numBits, 8);
  11409. var shift = 8 - bits;
  11410. mask[0] = 0xff000000 >>> 24 + shift << shift;
  11411. temp[0] = (_byte[0] & mask[0]) >> shift;
  11412. bsid = !bsid ? temp[0] : bsid << bits | temp[0];
  11413. offset += 1;
  11414. numBits -= bits;
  11415. }
  11416. return bsid;
  11417. };
  11418. var AC3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  11419. function AC3Demuxer(observer) {
  11420. var _this;
  11421. _this = _BaseAudioDemuxer.call(this) || this;
  11422. _this.observer = void 0;
  11423. _this.observer = observer;
  11424. return _this;
  11425. }
  11426. _inheritsLoose(AC3Demuxer, _BaseAudioDemuxer);
  11427. var _proto = AC3Demuxer.prototype;
  11428. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11429. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  11430. this._audioTrack = {
  11431. container: 'audio/ac-3',
  11432. type: 'audio',
  11433. id: 2,
  11434. pid: -1,
  11435. sequenceNumber: 0,
  11436. segmentCodec: 'ac3',
  11437. samples: [],
  11438. manifestCodec: audioCodec,
  11439. duration: trackDuration,
  11440. inputTimeScale: 90000,
  11441. dropped: 0
  11442. };
  11443. };
  11444. _proto.canParse = function canParse(data, offset) {
  11445. return offset + 64 < data.length;
  11446. };
  11447. _proto.appendFrame = function appendFrame(track, data, offset) {
  11448. var frameLength = _appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  11449. if (frameLength !== -1) {
  11450. var sample = track.samples[track.samples.length - 1];
  11451. return {
  11452. sample: sample,
  11453. length: frameLength,
  11454. missing: 0
  11455. };
  11456. }
  11457. };
  11458. AC3Demuxer.probe = function probe(data) {
  11459. if (!data) {
  11460. return false;
  11461. }
  11462. var id3Data = getId3Data(data, 0);
  11463. if (!id3Data) {
  11464. return false;
  11465. }
  11466. // look for the ac-3 sync bytes
  11467. var offset = id3Data.length;
  11468. if (data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  11469. // check the bsid to confirm ac-3
  11470. getAudioBSID(data, offset) < 16) {
  11471. return true;
  11472. }
  11473. return false;
  11474. };
  11475. return AC3Demuxer;
  11476. }(BaseAudioDemuxer);
  11477. function _appendFrame(track, data, start, pts, frameIndex) {
  11478. if (start + 8 > data.length) {
  11479. return -1; // not enough bytes left
  11480. }
  11481. if (data[start] !== 0x0b || data[start + 1] !== 0x77) {
  11482. return -1; // invalid magic
  11483. }
  11484. // get sample rate
  11485. var samplingRateCode = data[start + 4] >> 6;
  11486. if (samplingRateCode >= 3) {
  11487. return -1; // invalid sampling rate
  11488. }
  11489. var samplingRateMap = [48000, 44100, 32000];
  11490. var sampleRate = samplingRateMap[samplingRateCode];
  11491. // get frame size
  11492. var frameSizeCode = data[start + 4] & 0x3f;
  11493. var frameSizeMap = [64, 69, 96, 64, 70, 96, 80, 87, 120, 80, 88, 120, 96, 104, 144, 96, 105, 144, 112, 121, 168, 112, 122, 168, 128, 139, 192, 128, 140, 192, 160, 174, 240, 160, 175, 240, 192, 208, 288, 192, 209, 288, 224, 243, 336, 224, 244, 336, 256, 278, 384, 256, 279, 384, 320, 348, 480, 320, 349, 480, 384, 417, 576, 384, 418, 576, 448, 487, 672, 448, 488, 672, 512, 557, 768, 512, 558, 768, 640, 696, 960, 640, 697, 960, 768, 835, 1152, 768, 836, 1152, 896, 975, 1344, 896, 976, 1344, 1024, 1114, 1536, 1024, 1115, 1536, 1152, 1253, 1728, 1152, 1254, 1728, 1280, 1393, 1920, 1280, 1394, 1920];
  11494. var frameLength = frameSizeMap[frameSizeCode * 3 + samplingRateCode] * 2;
  11495. if (start + frameLength > data.length) {
  11496. return -1;
  11497. }
  11498. // get channel count
  11499. var channelMode = data[start + 6] >> 5;
  11500. var skipCount = 0;
  11501. if (channelMode === 2) {
  11502. skipCount += 2;
  11503. } else {
  11504. if (channelMode & 1 && channelMode !== 1) {
  11505. skipCount += 2;
  11506. }
  11507. if (channelMode & 4) {
  11508. skipCount += 2;
  11509. }
  11510. }
  11511. var lfeon = (data[start + 6] << 8 | data[start + 7]) >> 12 - skipCount & 1;
  11512. var channelsMap = [2, 1, 2, 3, 3, 4, 4, 5];
  11513. var channelCount = channelsMap[channelMode] + lfeon;
  11514. // build dac3 box
  11515. var bsid = data[start + 5] >> 3;
  11516. var bsmod = data[start + 5] & 7;
  11517. var config = new Uint8Array([samplingRateCode << 6 | bsid << 1 | bsmod >> 2, (bsmod & 3) << 6 | channelMode << 3 | lfeon << 2 | frameSizeCode >> 4, frameSizeCode << 4 & 0xe0]);
  11518. var frameDuration = 1536 / sampleRate * 90000;
  11519. var stamp = pts + frameIndex * frameDuration;
  11520. var unit = data.subarray(start, start + frameLength);
  11521. track.config = config;
  11522. track.channelCount = channelCount;
  11523. track.samplerate = sampleRate;
  11524. track.samples.push({
  11525. unit: unit,
  11526. pts: stamp
  11527. });
  11528. return frameLength;
  11529. }
  11530. var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
  11531. function MP3Demuxer() {
  11532. return _BaseAudioDemuxer.apply(this, arguments) || this;
  11533. }
  11534. _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
  11535. var _proto = MP3Demuxer.prototype;
  11536. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11537. _BaseAudioDemuxer.prototype.resetInitSegment.call(this, initSegment, audioCodec, videoCodec, trackDuration);
  11538. this._audioTrack = {
  11539. container: 'audio/mpeg',
  11540. type: 'audio',
  11541. id: 2,
  11542. pid: -1,
  11543. sequenceNumber: 0,
  11544. segmentCodec: 'mp3',
  11545. samples: [],
  11546. manifestCodec: audioCodec,
  11547. duration: trackDuration,
  11548. inputTimeScale: 90000,
  11549. dropped: 0
  11550. };
  11551. };
  11552. MP3Demuxer.probe = function probe$1(data) {
  11553. if (!data) {
  11554. return false;
  11555. }
  11556. // check if data contains ID3 timestamp and MPEG sync word
  11557. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  11558. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  11559. // More info http://www.mp3-tech.org/programmer/frame_header.html
  11560. var id3Data = getId3Data(data, 0);
  11561. var offset = (id3Data == null ? void 0 : id3Data.length) || 0;
  11562. // Check for ac-3|ec-3 sync bytes and return false if present
  11563. if (id3Data && data[offset] === 0x0b && data[offset + 1] === 0x77 && getId3Timestamp(id3Data) !== undefined &&
  11564. // check the bsid to confirm ac-3 or ec-3 (not mp3)
  11565. getAudioBSID(data, offset) <= 16) {
  11566. return false;
  11567. }
  11568. for (var length = data.length; offset < length; offset++) {
  11569. if (probe(data, offset)) {
  11570. logger.log('MPEG Audio sync word found !');
  11571. return true;
  11572. }
  11573. }
  11574. return false;
  11575. };
  11576. _proto.canParse = function canParse$1(data, offset) {
  11577. return canParse(data, offset);
  11578. };
  11579. _proto.appendFrame = function appendFrame$1(track, data, offset) {
  11580. if (this.basePTS === null) {
  11581. return;
  11582. }
  11583. return appendFrame(track, data, offset, this.basePTS, this.frameIndex);
  11584. };
  11585. return MP3Demuxer;
  11586. }(BaseAudioDemuxer);
  11587. var emsgSchemePattern = /\/emsg[-/]ID3/i;
  11588. var MP4Demuxer = /*#__PURE__*/function () {
  11589. function MP4Demuxer(observer, config) {
  11590. this.remainderData = null;
  11591. this.timeOffset = 0;
  11592. this.config = void 0;
  11593. this.videoTrack = void 0;
  11594. this.audioTrack = void 0;
  11595. this.id3Track = void 0;
  11596. this.txtTrack = void 0;
  11597. this.config = config;
  11598. }
  11599. var _proto = MP4Demuxer.prototype;
  11600. _proto.resetTimeStamp = function resetTimeStamp() {};
  11601. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  11602. var videoTrack = this.videoTrack = dummyTrack('video', 1);
  11603. var audioTrack = this.audioTrack = dummyTrack('audio', 1);
  11604. var captionTrack = this.txtTrack = dummyTrack('text', 1);
  11605. this.id3Track = dummyTrack('id3', 1);
  11606. this.timeOffset = 0;
  11607. if (!(initSegment != null && initSegment.byteLength)) {
  11608. return;
  11609. }
  11610. var initData = parseInitSegment(initSegment);
  11611. if (initData.video) {
  11612. var _initData$video = initData.video,
  11613. id = _initData$video.id,
  11614. timescale = _initData$video.timescale,
  11615. codec = _initData$video.codec,
  11616. supplemental = _initData$video.supplemental;
  11617. videoTrack.id = id;
  11618. videoTrack.timescale = captionTrack.timescale = timescale;
  11619. videoTrack.codec = codec;
  11620. videoTrack.supplemental = supplemental;
  11621. }
  11622. if (initData.audio) {
  11623. var _initData$audio = initData.audio,
  11624. _id = _initData$audio.id,
  11625. _timescale = _initData$audio.timescale,
  11626. _codec = _initData$audio.codec;
  11627. audioTrack.id = _id;
  11628. audioTrack.timescale = _timescale;
  11629. audioTrack.codec = _codec;
  11630. }
  11631. captionTrack.id = RemuxerTrackIdConfig.text;
  11632. videoTrack.sampleDuration = 0;
  11633. videoTrack.duration = audioTrack.duration = trackDuration;
  11634. };
  11635. _proto.resetContiguity = function resetContiguity() {
  11636. this.remainderData = null;
  11637. };
  11638. MP4Demuxer.probe = function probe(data) {
  11639. return hasMoofData(data);
  11640. };
  11641. _proto.demux = function demux(data, timeOffset) {
  11642. this.timeOffset = timeOffset;
  11643. // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
  11644. var videoSamples = data;
  11645. var videoTrack = this.videoTrack;
  11646. var textTrack = this.txtTrack;
  11647. if (this.config.progressive) {
  11648. // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
  11649. // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
  11650. // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
  11651. if (this.remainderData) {
  11652. videoSamples = appendUint8Array(this.remainderData, data);
  11653. }
  11654. var segmentedData = segmentValidRange(videoSamples);
  11655. this.remainderData = segmentedData.remainder;
  11656. videoTrack.samples = segmentedData.valid || new Uint8Array();
  11657. } else {
  11658. videoTrack.samples = videoSamples;
  11659. }
  11660. var id3Track = this.extractID3Track(videoTrack, timeOffset);
  11661. textTrack.samples = parseSamples(timeOffset, videoTrack);
  11662. return {
  11663. videoTrack: videoTrack,
  11664. audioTrack: this.audioTrack,
  11665. id3Track: id3Track,
  11666. textTrack: this.txtTrack
  11667. };
  11668. };
  11669. _proto.flush = function flush() {
  11670. var timeOffset = this.timeOffset;
  11671. var videoTrack = this.videoTrack;
  11672. var textTrack = this.txtTrack;
  11673. videoTrack.samples = this.remainderData || new Uint8Array();
  11674. this.remainderData = null;
  11675. var id3Track = this.extractID3Track(videoTrack, this.timeOffset);
  11676. textTrack.samples = parseSamples(timeOffset, videoTrack);
  11677. return {
  11678. videoTrack: videoTrack,
  11679. audioTrack: dummyTrack(),
  11680. id3Track: id3Track,
  11681. textTrack: dummyTrack()
  11682. };
  11683. };
  11684. _proto.extractID3Track = function extractID3Track(videoTrack, timeOffset) {
  11685. var _this = this;
  11686. var id3Track = this.id3Track;
  11687. if (videoTrack.samples.length) {
  11688. var emsgs = findBox(videoTrack.samples, ['emsg']);
  11689. if (emsgs) {
  11690. emsgs.forEach(function (data) {
  11691. var emsgInfo = parseEmsg(data);
  11692. if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {
  11693. var pts = getEmsgStartTime(emsgInfo, timeOffset);
  11694. var duration = emsgInfo.eventDuration === 0xffffffff ? Number.POSITIVE_INFINITY : emsgInfo.eventDuration / emsgInfo.timeScale;
  11695. // Safari takes anything <= 0.001 seconds and maps it to Infinity
  11696. if (duration <= 0.001) {
  11697. duration = Number.POSITIVE_INFINITY;
  11698. }
  11699. var payload = emsgInfo.payload;
  11700. id3Track.samples.push({
  11701. data: payload,
  11702. len: payload.byteLength,
  11703. dts: pts,
  11704. pts: pts,
  11705. type: MetadataSchema.emsg,
  11706. duration: duration
  11707. });
  11708. } else if (_this.config.enableEmsgKLVMetadata && emsgInfo.schemeIdUri.startsWith('urn:misb:KLV:bin:1910.1')) {
  11709. var _pts = getEmsgStartTime(emsgInfo, timeOffset);
  11710. id3Track.samples.push({
  11711. data: emsgInfo.payload,
  11712. len: emsgInfo.payload.byteLength,
  11713. dts: _pts,
  11714. pts: _pts,
  11715. type: MetadataSchema.misbklv,
  11716. duration: Number.POSITIVE_INFINITY
  11717. });
  11718. }
  11719. });
  11720. }
  11721. }
  11722. return id3Track;
  11723. };
  11724. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  11725. return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
  11726. };
  11727. _proto.destroy = function destroy() {
  11728. // @ts-ignore
  11729. this.config = null;
  11730. this.remainderData = null;
  11731. this.videoTrack = this.audioTrack = this.id3Track = this.txtTrack = undefined;
  11732. };
  11733. return MP4Demuxer;
  11734. }();
  11735. function getEmsgStartTime(emsgInfo, timeOffset) {
  11736. return isFiniteNumber(emsgInfo.presentationTime) ? emsgInfo.presentationTime / emsgInfo.timeScale : timeOffset + emsgInfo.presentationTimeDelta / emsgInfo.timeScale;
  11737. }
  11738. /**
  11739. * SAMPLE-AES decrypter
  11740. */
  11741. var SampleAesDecrypter = /*#__PURE__*/function () {
  11742. function SampleAesDecrypter(observer, config, keyData) {
  11743. this.keyData = void 0;
  11744. this.decrypter = void 0;
  11745. this.keyData = keyData;
  11746. this.decrypter = new Decrypter(config, {
  11747. removePKCS7Padding: false
  11748. });
  11749. }
  11750. var _proto = SampleAesDecrypter.prototype;
  11751. _proto.decryptBuffer = function decryptBuffer(encryptedData) {
  11752. return this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, DecrypterAesMode.cbc);
  11753. }
  11754. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  11755. ;
  11756. _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback) {
  11757. var _this = this;
  11758. var curUnit = samples[sampleIndex].unit;
  11759. if (curUnit.length <= 16) {
  11760. // No encrypted portion in this sample (first 16 bytes is not
  11761. // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),
  11762. return;
  11763. }
  11764. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  11765. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  11766. this.decryptBuffer(encryptedBuffer).then(function (decryptedBuffer) {
  11767. var decryptedData = new Uint8Array(decryptedBuffer);
  11768. curUnit.set(decryptedData, 16);
  11769. if (!_this.decrypter.isSync()) {
  11770. _this.decryptAacSamples(samples, sampleIndex + 1, callback);
  11771. }
  11772. });
  11773. };
  11774. _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
  11775. for (;; sampleIndex++) {
  11776. if (sampleIndex >= samples.length) {
  11777. callback();
  11778. return;
  11779. }
  11780. if (samples[sampleIndex].unit.length < 32) {
  11781. continue;
  11782. }
  11783. this.decryptAacSample(samples, sampleIndex, callback);
  11784. if (!this.decrypter.isSync()) {
  11785. return;
  11786. }
  11787. }
  11788. }
  11789. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  11790. ;
  11791. _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
  11792. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  11793. var encryptedData = new Int8Array(encryptedDataLen);
  11794. var outputPos = 0;
  11795. for (var inputPos = 32; inputPos < decodedData.length - 16; inputPos += 160, outputPos += 16) {
  11796. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  11797. }
  11798. return encryptedData;
  11799. };
  11800. _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
  11801. var uint8DecryptedData = new Uint8Array(decryptedData);
  11802. var inputPos = 0;
  11803. for (var outputPos = 32; outputPos < decodedData.length - 16; outputPos += 160, inputPos += 16) {
  11804. decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
  11805. }
  11806. return decodedData;
  11807. };
  11808. _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit) {
  11809. var _this2 = this;
  11810. var decodedData = discardEPB(curUnit.data);
  11811. var encryptedData = this.getAvcEncryptedData(decodedData);
  11812. this.decryptBuffer(encryptedData.buffer).then(function (decryptedBuffer) {
  11813. curUnit.data = _this2.getAvcDecryptedUnit(decodedData, decryptedBuffer);
  11814. if (!_this2.decrypter.isSync()) {
  11815. _this2.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  11816. }
  11817. });
  11818. };
  11819. _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
  11820. if (samples instanceof Uint8Array) {
  11821. throw new Error('Cannot decrypt samples of type Uint8Array');
  11822. }
  11823. for (;; sampleIndex++, unitIndex = 0) {
  11824. if (sampleIndex >= samples.length) {
  11825. callback();
  11826. return;
  11827. }
  11828. var curUnits = samples[sampleIndex].units;
  11829. for (;; unitIndex++) {
  11830. if (unitIndex >= curUnits.length) {
  11831. break;
  11832. }
  11833. var curUnit = curUnits[unitIndex];
  11834. if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
  11835. continue;
  11836. }
  11837. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit);
  11838. if (!this.decrypter.isSync()) {
  11839. return;
  11840. }
  11841. }
  11842. }
  11843. };
  11844. return SampleAesDecrypter;
  11845. }();
  11846. var BaseVideoParser = /*#__PURE__*/function () {
  11847. function BaseVideoParser() {
  11848. this.VideoSample = null;
  11849. }
  11850. var _proto = BaseVideoParser.prototype;
  11851. _proto.createVideoSample = function createVideoSample(key, pts, dts) {
  11852. return {
  11853. key: key,
  11854. frame: false,
  11855. pts: pts,
  11856. dts: dts,
  11857. units: [],
  11858. length: 0
  11859. };
  11860. };
  11861. _proto.getLastNalUnit = function getLastNalUnit(samples) {
  11862. var _VideoSample;
  11863. var VideoSample = this.VideoSample;
  11864. var lastUnit;
  11865. // try to fallback to previous sample if current one is empty
  11866. if (!VideoSample || VideoSample.units.length === 0) {
  11867. VideoSample = samples[samples.length - 1];
  11868. }
  11869. if ((_VideoSample = VideoSample) != null && _VideoSample.units) {
  11870. var units = VideoSample.units;
  11871. lastUnit = units[units.length - 1];
  11872. }
  11873. return lastUnit;
  11874. };
  11875. _proto.pushAccessUnit = function pushAccessUnit(VideoSample, videoTrack) {
  11876. if (VideoSample.units.length && VideoSample.frame) {
  11877. // if sample does not have PTS/DTS, patch with last sample PTS/DTS
  11878. if (VideoSample.pts === undefined) {
  11879. var samples = videoTrack.samples;
  11880. var nbSamples = samples.length;
  11881. if (nbSamples) {
  11882. var lastSample = samples[nbSamples - 1];
  11883. VideoSample.pts = lastSample.pts;
  11884. VideoSample.dts = lastSample.dts;
  11885. } else {
  11886. // dropping samples, no timestamp found
  11887. videoTrack.dropped++;
  11888. return;
  11889. }
  11890. }
  11891. videoTrack.samples.push(VideoSample);
  11892. }
  11893. };
  11894. _proto.parseNALu = function parseNALu(track, array, endOfSegment) {
  11895. var len = array.byteLength;
  11896. var state = track.naluState || 0;
  11897. var lastState = state;
  11898. var units = [];
  11899. var i = 0;
  11900. var value;
  11901. var overflow;
  11902. var unitType;
  11903. var lastUnitStart = -1;
  11904. var lastUnitType = 0;
  11905. // logger.log('PES:' + Hex.hexDump(array));
  11906. if (state === -1) {
  11907. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  11908. lastUnitStart = 0;
  11909. // NALu type is value read from offset 0
  11910. lastUnitType = this.getNALuType(array, 0);
  11911. state = 0;
  11912. i = 1;
  11913. }
  11914. while (i < len) {
  11915. value = array[i++];
  11916. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  11917. if (!state) {
  11918. state = value ? 0 : 1;
  11919. continue;
  11920. }
  11921. if (state === 1) {
  11922. state = value ? 0 : 2;
  11923. continue;
  11924. }
  11925. // here we have state either equal to 2 or 3
  11926. if (!value) {
  11927. state = 3;
  11928. } else if (value === 1) {
  11929. overflow = i - state - 1;
  11930. if (lastUnitStart >= 0) {
  11931. var unit = {
  11932. data: array.subarray(lastUnitStart, overflow),
  11933. type: lastUnitType
  11934. };
  11935. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  11936. units.push(unit);
  11937. } else {
  11938. // lastUnitStart is undefined => this is the first start code found in this PES packet
  11939. // first check if start code delimiter is overlapping between 2 PES packets,
  11940. // ie it started in last packet (lastState not zero)
  11941. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  11942. var lastUnit = this.getLastNalUnit(track.samples);
  11943. if (lastUnit) {
  11944. if (lastState && i <= 4 - lastState) {
  11945. // start delimiter overlapping between PES packets
  11946. // strip start delimiter bytes from the end of last NAL unit
  11947. // check if lastUnit had a state different from zero
  11948. if (lastUnit.state) {
  11949. // strip last bytes
  11950. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  11951. }
  11952. }
  11953. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  11954. if (overflow > 0) {
  11955. // logger.log('first NALU found with overflow:' + overflow);
  11956. lastUnit.data = appendUint8Array(lastUnit.data, array.subarray(0, overflow));
  11957. lastUnit.state = 0;
  11958. }
  11959. }
  11960. }
  11961. // check if we can read unit type
  11962. if (i < len) {
  11963. unitType = this.getNALuType(array, i);
  11964. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  11965. lastUnitStart = i;
  11966. lastUnitType = unitType;
  11967. state = 0;
  11968. } else {
  11969. // not enough byte to read unit type. let's read it on next PES parsing
  11970. state = -1;
  11971. }
  11972. } else {
  11973. state = 0;
  11974. }
  11975. }
  11976. if (lastUnitStart >= 0 && state >= 0) {
  11977. var _unit = {
  11978. data: array.subarray(lastUnitStart, len),
  11979. type: lastUnitType,
  11980. state: state
  11981. };
  11982. units.push(_unit);
  11983. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  11984. }
  11985. // no NALu found
  11986. if (units.length === 0) {
  11987. // append pes.data to previous NAL unit
  11988. var _lastUnit = this.getLastNalUnit(track.samples);
  11989. if (_lastUnit) {
  11990. _lastUnit.data = appendUint8Array(_lastUnit.data, array);
  11991. }
  11992. }
  11993. track.naluState = state;
  11994. return units;
  11995. };
  11996. return BaseVideoParser;
  11997. }();
  11998. /**
  11999. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  12000. */
  12001. var ExpGolomb = /*#__PURE__*/function () {
  12002. function ExpGolomb(data) {
  12003. this.data = void 0;
  12004. this.bytesAvailable = void 0;
  12005. this.word = void 0;
  12006. this.bitsAvailable = void 0;
  12007. this.data = data;
  12008. // the number of bytes left to examine in this.data
  12009. this.bytesAvailable = data.byteLength;
  12010. // the current word being examined
  12011. this.word = 0; // :uint
  12012. // the number of bits left to examine in the current word
  12013. this.bitsAvailable = 0; // :uint
  12014. }
  12015. // ():void
  12016. var _proto = ExpGolomb.prototype;
  12017. _proto.loadWord = function loadWord() {
  12018. var data = this.data;
  12019. var bytesAvailable = this.bytesAvailable;
  12020. var position = data.byteLength - bytesAvailable;
  12021. var workingBytes = new Uint8Array(4);
  12022. var availableBytes = Math.min(4, bytesAvailable);
  12023. if (availableBytes === 0) {
  12024. throw new Error('no bytes available');
  12025. }
  12026. workingBytes.set(data.subarray(position, position + availableBytes));
  12027. this.word = new DataView(workingBytes.buffer).getUint32(0);
  12028. // track the amount of this.data that has been processed
  12029. this.bitsAvailable = availableBytes * 8;
  12030. this.bytesAvailable -= availableBytes;
  12031. }
  12032. // (count:int):void
  12033. ;
  12034. _proto.skipBits = function skipBits(count) {
  12035. var skipBytes; // :int
  12036. count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);
  12037. if (this.bitsAvailable > count) {
  12038. this.word <<= count;
  12039. this.bitsAvailable -= count;
  12040. } else {
  12041. count -= this.bitsAvailable;
  12042. skipBytes = count >> 3;
  12043. count -= skipBytes << 3;
  12044. this.bytesAvailable -= skipBytes;
  12045. this.loadWord();
  12046. this.word <<= count;
  12047. this.bitsAvailable -= count;
  12048. }
  12049. }
  12050. // (size:int):uint
  12051. ;
  12052. _proto.readBits = function readBits(size) {
  12053. var bits = Math.min(this.bitsAvailable, size); // :uint
  12054. var valu = this.word >>> 32 - bits; // :uint
  12055. if (size > 32) {
  12056. logger.error('Cannot read more than 32 bits at a time');
  12057. }
  12058. this.bitsAvailable -= bits;
  12059. if (this.bitsAvailable > 0) {
  12060. this.word <<= bits;
  12061. } else if (this.bytesAvailable > 0) {
  12062. this.loadWord();
  12063. } else {
  12064. throw new Error('no bits available');
  12065. }
  12066. bits = size - bits;
  12067. if (bits > 0 && this.bitsAvailable) {
  12068. return valu << bits | this.readBits(bits);
  12069. } else {
  12070. return valu;
  12071. }
  12072. }
  12073. // ():uint
  12074. ;
  12075. _proto.skipLZ = function skipLZ() {
  12076. var leadingZeroCount; // :uint
  12077. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  12078. if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
  12079. // the first bit of working word is 1
  12080. this.word <<= leadingZeroCount;
  12081. this.bitsAvailable -= leadingZeroCount;
  12082. return leadingZeroCount;
  12083. }
  12084. }
  12085. // we exhausted word and still have not found a 1
  12086. this.loadWord();
  12087. return leadingZeroCount + this.skipLZ();
  12088. }
  12089. // ():void
  12090. ;
  12091. _proto.skipUEG = function skipUEG() {
  12092. this.skipBits(1 + this.skipLZ());
  12093. }
  12094. // ():void
  12095. ;
  12096. _proto.skipEG = function skipEG() {
  12097. this.skipBits(1 + this.skipLZ());
  12098. }
  12099. // ():uint
  12100. ;
  12101. _proto.readUEG = function readUEG() {
  12102. var clz = this.skipLZ(); // :uint
  12103. return this.readBits(clz + 1) - 1;
  12104. }
  12105. // ():int
  12106. ;
  12107. _proto.readEG = function readEG() {
  12108. var valu = this.readUEG(); // :int
  12109. if (0x01 & valu) {
  12110. // the number is odd if the low order bit is set
  12111. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  12112. } else {
  12113. return -1 * (valu >>> 1); // divide by two then make it negative
  12114. }
  12115. }
  12116. // Some convenience functions
  12117. // :Boolean
  12118. ;
  12119. _proto.readBoolean = function readBoolean() {
  12120. return this.readBits(1) === 1;
  12121. }
  12122. // ():int
  12123. ;
  12124. _proto.readUByte = function readUByte() {
  12125. return this.readBits(8);
  12126. }
  12127. // ():int
  12128. ;
  12129. _proto.readUShort = function readUShort() {
  12130. return this.readBits(16);
  12131. }
  12132. // ():int
  12133. ;
  12134. _proto.readUInt = function readUInt() {
  12135. return this.readBits(32);
  12136. };
  12137. return ExpGolomb;
  12138. }();
  12139. var AvcVideoParser = /*#__PURE__*/function (_BaseVideoParser) {
  12140. function AvcVideoParser() {
  12141. return _BaseVideoParser.apply(this, arguments) || this;
  12142. }
  12143. _inheritsLoose(AvcVideoParser, _BaseVideoParser);
  12144. var _proto = AvcVideoParser.prototype;
  12145. _proto.parsePES = function parsePES(track, textTrack, pes, endOfSegment) {
  12146. var _this = this;
  12147. var units = this.parseNALu(track, pes.data, endOfSegment);
  12148. var VideoSample = this.VideoSample;
  12149. var push;
  12150. var spsfound = false;
  12151. // free pes.data to save up some memory
  12152. pes.data = null;
  12153. // if new NAL units found and last sample still there, let's push ...
  12154. // this helps parsing streams with missing AUD (only do this if AUD never found)
  12155. if (VideoSample && units.length && !track.audFound) {
  12156. this.pushAccessUnit(VideoSample, track);
  12157. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  12158. }
  12159. units.forEach(function (unit) {
  12160. var _VideoSample2, _VideoSample3;
  12161. switch (unit.type) {
  12162. // NDR
  12163. case 1:
  12164. {
  12165. var iskey = false;
  12166. push = true;
  12167. var data = unit.data;
  12168. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  12169. if (spsfound && data.length > 4) {
  12170. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  12171. var sliceType = _this.readSliceType(data);
  12172. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  12173. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  12174. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  12175. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  12176. // if (sliceType === 2 || sliceType === 7) {
  12177. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  12178. iskey = true;
  12179. }
  12180. }
  12181. if (iskey) {
  12182. var _VideoSample;
  12183. // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push
  12184. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  12185. _this.pushAccessUnit(VideoSample, track);
  12186. VideoSample = _this.VideoSample = null;
  12187. }
  12188. }
  12189. if (!VideoSample) {
  12190. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts);
  12191. }
  12192. VideoSample.frame = true;
  12193. VideoSample.key = iskey;
  12194. break;
  12195. // IDR
  12196. }
  12197. case 5:
  12198. push = true;
  12199. // handle PES not starting with AUD
  12200. // if we have frame data already, that cannot belong to the same frame, so force a push
  12201. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  12202. _this.pushAccessUnit(VideoSample, track);
  12203. VideoSample = _this.VideoSample = null;
  12204. }
  12205. if (!VideoSample) {
  12206. VideoSample = _this.VideoSample = _this.createVideoSample(true, pes.pts, pes.dts);
  12207. }
  12208. VideoSample.key = true;
  12209. VideoSample.frame = true;
  12210. break;
  12211. // SEI
  12212. case 6:
  12213. {
  12214. push = true;
  12215. parseSEIMessageFromNALu(unit.data, 1, pes.pts, textTrack.samples);
  12216. break;
  12217. // SPS
  12218. }
  12219. case 7:
  12220. {
  12221. var _track$pixelRatio, _track$pixelRatio2;
  12222. push = true;
  12223. spsfound = true;
  12224. var sps = unit.data;
  12225. var config = _this.readSPS(sps);
  12226. if (!track.sps || track.width !== config.width || track.height !== config.height || ((_track$pixelRatio = track.pixelRatio) == null ? void 0 : _track$pixelRatio[0]) !== config.pixelRatio[0] || ((_track$pixelRatio2 = track.pixelRatio) == null ? void 0 : _track$pixelRatio2[1]) !== config.pixelRatio[1]) {
  12227. track.width = config.width;
  12228. track.height = config.height;
  12229. track.pixelRatio = config.pixelRatio;
  12230. track.sps = [sps];
  12231. var codecarray = sps.subarray(1, 4);
  12232. var codecstring = 'avc1.';
  12233. for (var i = 0; i < 3; i++) {
  12234. var h = codecarray[i].toString(16);
  12235. if (h.length < 2) {
  12236. h = '0' + h;
  12237. }
  12238. codecstring += h;
  12239. }
  12240. track.codec = codecstring;
  12241. }
  12242. break;
  12243. }
  12244. // PPS
  12245. case 8:
  12246. push = true;
  12247. track.pps = [unit.data];
  12248. break;
  12249. // AUD
  12250. case 9:
  12251. push = true;
  12252. track.audFound = true;
  12253. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  12254. _this.pushAccessUnit(VideoSample, track);
  12255. VideoSample = null;
  12256. }
  12257. if (!VideoSample) {
  12258. VideoSample = _this.VideoSample = _this.createVideoSample(false, pes.pts, pes.dts);
  12259. }
  12260. break;
  12261. // Filler Data
  12262. case 12:
  12263. push = true;
  12264. break;
  12265. default:
  12266. push = false;
  12267. break;
  12268. }
  12269. if (VideoSample && push) {
  12270. var _units = VideoSample.units;
  12271. _units.push(unit);
  12272. }
  12273. });
  12274. // if last PES packet, push samples
  12275. if (endOfSegment && VideoSample) {
  12276. this.pushAccessUnit(VideoSample, track);
  12277. this.VideoSample = null;
  12278. }
  12279. };
  12280. _proto.getNALuType = function getNALuType(data, offset) {
  12281. return data[offset] & 0x1f;
  12282. };
  12283. _proto.readSliceType = function readSliceType(data) {
  12284. var eg = new ExpGolomb(data);
  12285. // skip NALu type
  12286. eg.readUByte();
  12287. // discard first_mb_in_slice
  12288. eg.readUEG();
  12289. // return slice_type
  12290. return eg.readUEG();
  12291. }
  12292. /**
  12293. * The scaling list is optionally transmitted as part of a sequence parameter
  12294. * set and is not relevant to transmuxing.
  12295. * @param count the number of entries in this scaling list
  12296. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  12297. */;
  12298. _proto.skipScalingList = function skipScalingList(count, reader) {
  12299. var lastScale = 8;
  12300. var nextScale = 8;
  12301. var deltaScale;
  12302. for (var j = 0; j < count; j++) {
  12303. if (nextScale !== 0) {
  12304. deltaScale = reader.readEG();
  12305. nextScale = (lastScale + deltaScale + 256) % 256;
  12306. }
  12307. lastScale = nextScale === 0 ? lastScale : nextScale;
  12308. }
  12309. }
  12310. /**
  12311. * Read a sequence parameter set and return some interesting video
  12312. * properties. A sequence parameter set is the H264 metadata that
  12313. * describes the properties of upcoming video frames.
  12314. * @returns an object with configuration parsed from the
  12315. * sequence parameter set, including the dimensions of the
  12316. * associated video frames.
  12317. */;
  12318. _proto.readSPS = function readSPS(sps) {
  12319. var eg = new ExpGolomb(sps);
  12320. var frameCropLeftOffset = 0;
  12321. var frameCropRightOffset = 0;
  12322. var frameCropTopOffset = 0;
  12323. var frameCropBottomOffset = 0;
  12324. var numRefFramesInPicOrderCntCycle;
  12325. var scalingListCount;
  12326. var i;
  12327. var readUByte = eg.readUByte.bind(eg);
  12328. var readBits = eg.readBits.bind(eg);
  12329. var readUEG = eg.readUEG.bind(eg);
  12330. var readBoolean = eg.readBoolean.bind(eg);
  12331. var skipBits = eg.skipBits.bind(eg);
  12332. var skipEG = eg.skipEG.bind(eg);
  12333. var skipUEG = eg.skipUEG.bind(eg);
  12334. var skipScalingList = this.skipScalingList.bind(this);
  12335. readUByte();
  12336. var profileIdc = readUByte(); // profile_idc
  12337. readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
  12338. skipBits(3); // reserved_zero_3bits u(3),
  12339. readUByte(); // level_idc u(8)
  12340. skipUEG(); // seq_parameter_set_id
  12341. // some profiles have more optional data we don't need
  12342. if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  12343. var chromaFormatIdc = readUEG();
  12344. if (chromaFormatIdc === 3) {
  12345. skipBits(1);
  12346. } // separate_colour_plane_flag
  12347. skipUEG(); // bit_depth_luma_minus8
  12348. skipUEG(); // bit_depth_chroma_minus8
  12349. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  12350. if (readBoolean()) {
  12351. // seq_scaling_matrix_present_flag
  12352. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  12353. for (i = 0; i < scalingListCount; i++) {
  12354. if (readBoolean()) {
  12355. // seq_scaling_list_present_flag[ i ]
  12356. if (i < 6) {
  12357. skipScalingList(16, eg);
  12358. } else {
  12359. skipScalingList(64, eg);
  12360. }
  12361. }
  12362. }
  12363. }
  12364. }
  12365. skipUEG(); // log2_max_frame_num_minus4
  12366. var picOrderCntType = readUEG();
  12367. if (picOrderCntType === 0) {
  12368. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  12369. } else if (picOrderCntType === 1) {
  12370. skipBits(1); // delta_pic_order_always_zero_flag
  12371. skipEG(); // offset_for_non_ref_pic
  12372. skipEG(); // offset_for_top_to_bottom_field
  12373. numRefFramesInPicOrderCntCycle = readUEG();
  12374. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  12375. skipEG();
  12376. } // offset_for_ref_frame[ i ]
  12377. }
  12378. skipUEG(); // max_num_ref_frames
  12379. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  12380. var picWidthInMbsMinus1 = readUEG();
  12381. var picHeightInMapUnitsMinus1 = readUEG();
  12382. var frameMbsOnlyFlag = readBits(1);
  12383. if (frameMbsOnlyFlag === 0) {
  12384. skipBits(1);
  12385. } // mb_adaptive_frame_field_flag
  12386. skipBits(1); // direct_8x8_inference_flag
  12387. if (readBoolean()) {
  12388. // frame_cropping_flag
  12389. frameCropLeftOffset = readUEG();
  12390. frameCropRightOffset = readUEG();
  12391. frameCropTopOffset = readUEG();
  12392. frameCropBottomOffset = readUEG();
  12393. }
  12394. var pixelRatio = [1, 1];
  12395. if (readBoolean()) {
  12396. // vui_parameters_present_flag
  12397. if (readBoolean()) {
  12398. // aspect_ratio_info_present_flag
  12399. var aspectRatioIdc = readUByte();
  12400. switch (aspectRatioIdc) {
  12401. case 1:
  12402. pixelRatio = [1, 1];
  12403. break;
  12404. case 2:
  12405. pixelRatio = [12, 11];
  12406. break;
  12407. case 3:
  12408. pixelRatio = [10, 11];
  12409. break;
  12410. case 4:
  12411. pixelRatio = [16, 11];
  12412. break;
  12413. case 5:
  12414. pixelRatio = [40, 33];
  12415. break;
  12416. case 6:
  12417. pixelRatio = [24, 11];
  12418. break;
  12419. case 7:
  12420. pixelRatio = [20, 11];
  12421. break;
  12422. case 8:
  12423. pixelRatio = [32, 11];
  12424. break;
  12425. case 9:
  12426. pixelRatio = [80, 33];
  12427. break;
  12428. case 10:
  12429. pixelRatio = [18, 11];
  12430. break;
  12431. case 11:
  12432. pixelRatio = [15, 11];
  12433. break;
  12434. case 12:
  12435. pixelRatio = [64, 33];
  12436. break;
  12437. case 13:
  12438. pixelRatio = [160, 99];
  12439. break;
  12440. case 14:
  12441. pixelRatio = [4, 3];
  12442. break;
  12443. case 15:
  12444. pixelRatio = [3, 2];
  12445. break;
  12446. case 16:
  12447. pixelRatio = [2, 1];
  12448. break;
  12449. case 255:
  12450. {
  12451. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  12452. break;
  12453. }
  12454. }
  12455. }
  12456. }
  12457. return {
  12458. width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
  12459. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
  12460. pixelRatio: pixelRatio
  12461. };
  12462. };
  12463. return AvcVideoParser;
  12464. }(BaseVideoParser);
  12465. var HevcVideoParser = /*#__PURE__*/function (_BaseVideoParser) {
  12466. function HevcVideoParser() {
  12467. var _this;
  12468. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  12469. args[_key] = arguments[_key];
  12470. }
  12471. _this = _BaseVideoParser.call.apply(_BaseVideoParser, [this].concat(args)) || this;
  12472. _this.initVPS = null;
  12473. return _this;
  12474. }
  12475. _inheritsLoose(HevcVideoParser, _BaseVideoParser);
  12476. var _proto = HevcVideoParser.prototype;
  12477. _proto.parsePES = function parsePES(track, textTrack, pes, endOfSegment) {
  12478. var _this2 = this;
  12479. var units = this.parseNALu(track, pes.data, endOfSegment);
  12480. var VideoSample = this.VideoSample;
  12481. var push;
  12482. var spsfound = false;
  12483. // free pes.data to save up some memory
  12484. pes.data = null;
  12485. // if new NAL units found and last sample still there, let's push ...
  12486. // this helps parsing streams with missing AUD (only do this if AUD never found)
  12487. if (VideoSample && units.length && !track.audFound) {
  12488. this.pushAccessUnit(VideoSample, track);
  12489. VideoSample = this.VideoSample = this.createVideoSample(false, pes.pts, pes.dts);
  12490. }
  12491. units.forEach(function (unit) {
  12492. var _VideoSample2, _VideoSample3;
  12493. switch (unit.type) {
  12494. // NON-IDR, NON RANDOM ACCESS SLICE
  12495. case 0:
  12496. case 1:
  12497. case 2:
  12498. case 3:
  12499. case 4:
  12500. case 5:
  12501. case 6:
  12502. case 7:
  12503. case 8:
  12504. case 9:
  12505. if (!VideoSample) {
  12506. VideoSample = _this2.VideoSample = _this2.createVideoSample(false, pes.pts, pes.dts);
  12507. }
  12508. VideoSample.frame = true;
  12509. push = true;
  12510. break;
  12511. // CRA, BLA (random access picture)
  12512. case 16:
  12513. case 17:
  12514. case 18:
  12515. case 21:
  12516. push = true;
  12517. if (spsfound) {
  12518. var _VideoSample;
  12519. // handle PES not starting with AUD
  12520. // if we have frame data already, that cannot belong to the same frame, so force a push
  12521. if ((_VideoSample = VideoSample) != null && _VideoSample.frame && !VideoSample.key) {
  12522. _this2.pushAccessUnit(VideoSample, track);
  12523. VideoSample = _this2.VideoSample = null;
  12524. }
  12525. }
  12526. if (!VideoSample) {
  12527. VideoSample = _this2.VideoSample = _this2.createVideoSample(true, pes.pts, pes.dts);
  12528. }
  12529. VideoSample.key = true;
  12530. VideoSample.frame = true;
  12531. break;
  12532. // IDR
  12533. case 19:
  12534. case 20:
  12535. push = true;
  12536. // handle PES not starting with AUD
  12537. // if we have frame data already, that cannot belong to the same frame, so force a push
  12538. if ((_VideoSample2 = VideoSample) != null && _VideoSample2.frame && !VideoSample.key) {
  12539. _this2.pushAccessUnit(VideoSample, track);
  12540. VideoSample = _this2.VideoSample = null;
  12541. }
  12542. if (!VideoSample) {
  12543. VideoSample = _this2.VideoSample = _this2.createVideoSample(true, pes.pts, pes.dts);
  12544. }
  12545. VideoSample.key = true;
  12546. VideoSample.frame = true;
  12547. break;
  12548. // SEI
  12549. case 39:
  12550. push = true;
  12551. parseSEIMessageFromNALu(unit.data, 2,
  12552. // NALu header size
  12553. pes.pts, textTrack.samples);
  12554. break;
  12555. // VPS
  12556. case 32:
  12557. push = true;
  12558. if (!track.vps) {
  12559. if (typeof track.params !== 'object') {
  12560. track.params = {};
  12561. }
  12562. track.params = _extends(track.params, _this2.readVPS(unit.data));
  12563. _this2.initVPS = unit.data;
  12564. }
  12565. track.vps = [unit.data];
  12566. break;
  12567. // SPS
  12568. case 33:
  12569. push = true;
  12570. spsfound = true;
  12571. if (track.vps !== undefined && track.vps[0] !== _this2.initVPS && track.sps !== undefined && !_this2.matchSPS(track.sps[0], unit.data)) {
  12572. _this2.initVPS = track.vps[0];
  12573. track.sps = track.pps = undefined;
  12574. }
  12575. if (!track.sps) {
  12576. var config = _this2.readSPS(unit.data);
  12577. track.width = config.width;
  12578. track.height = config.height;
  12579. track.pixelRatio = config.pixelRatio;
  12580. track.codec = config.codecString;
  12581. track.sps = [];
  12582. if (typeof track.params !== 'object') {
  12583. track.params = {};
  12584. }
  12585. for (var prop in config.params) {
  12586. track.params[prop] = config.params[prop];
  12587. }
  12588. }
  12589. _this2.pushParameterSet(track.sps, unit.data, track.vps);
  12590. if (!VideoSample) {
  12591. VideoSample = _this2.VideoSample = _this2.createVideoSample(true, pes.pts, pes.dts);
  12592. }
  12593. VideoSample.key = true;
  12594. break;
  12595. // PPS
  12596. case 34:
  12597. push = true;
  12598. if (typeof track.params === 'object') {
  12599. if (!track.pps) {
  12600. track.pps = [];
  12601. var _config = _this2.readPPS(unit.data);
  12602. for (var _prop in _config) {
  12603. track.params[_prop] = _config[_prop];
  12604. }
  12605. }
  12606. _this2.pushParameterSet(track.pps, unit.data, track.vps);
  12607. }
  12608. break;
  12609. // ACCESS UNIT DELIMITER
  12610. case 35:
  12611. push = true;
  12612. track.audFound = true;
  12613. if ((_VideoSample3 = VideoSample) != null && _VideoSample3.frame) {
  12614. _this2.pushAccessUnit(VideoSample, track);
  12615. VideoSample = null;
  12616. }
  12617. if (!VideoSample) {
  12618. VideoSample = _this2.VideoSample = _this2.createVideoSample(false, pes.pts, pes.dts);
  12619. }
  12620. break;
  12621. default:
  12622. push = false;
  12623. break;
  12624. }
  12625. if (VideoSample && push) {
  12626. var _units = VideoSample.units;
  12627. _units.push(unit);
  12628. }
  12629. });
  12630. // if last PES packet, push samples
  12631. if (endOfSegment && VideoSample) {
  12632. this.pushAccessUnit(VideoSample, track);
  12633. this.VideoSample = null;
  12634. }
  12635. };
  12636. _proto.pushParameterSet = function pushParameterSet(parameterSets, data, vps) {
  12637. if (vps && vps[0] === this.initVPS || !vps && !parameterSets.length) {
  12638. parameterSets.push(data);
  12639. }
  12640. };
  12641. _proto.getNALuType = function getNALuType(data, offset) {
  12642. return (data[offset] & 0x7e) >>> 1;
  12643. };
  12644. _proto.ebsp2rbsp = function ebsp2rbsp(arr) {
  12645. var dst = new Uint8Array(arr.byteLength);
  12646. var dstIdx = 0;
  12647. for (var i = 0; i < arr.byteLength; i++) {
  12648. if (i >= 2) {
  12649. // Unescape: Skip 0x03 after 00 00
  12650. if (arr[i] === 0x03 && arr[i - 1] === 0x00 && arr[i - 2] === 0x00) {
  12651. continue;
  12652. }
  12653. }
  12654. dst[dstIdx] = arr[i];
  12655. dstIdx++;
  12656. }
  12657. return new Uint8Array(dst.buffer, 0, dstIdx);
  12658. };
  12659. _proto.pushAccessUnit = function pushAccessUnit(VideoSample, videoTrack) {
  12660. _BaseVideoParser.prototype.pushAccessUnit.call(this, VideoSample, videoTrack);
  12661. if (this.initVPS) {
  12662. this.initVPS = null; // null initVPS to prevent possible track's sps/pps growth until next VPS
  12663. }
  12664. };
  12665. _proto.readVPS = function readVPS(vps) {
  12666. var eg = new ExpGolomb(vps);
  12667. // remove header
  12668. eg.readUByte();
  12669. eg.readUByte();
  12670. eg.readBits(4); // video_parameter_set_id
  12671. eg.skipBits(2);
  12672. eg.readBits(6); // max_layers_minus1
  12673. var max_sub_layers_minus1 = eg.readBits(3);
  12674. var temporal_id_nesting_flag = eg.readBoolean();
  12675. // ...vui fps can be here, but empty fps value is not critical for metadata
  12676. return {
  12677. numTemporalLayers: max_sub_layers_minus1 + 1,
  12678. temporalIdNested: temporal_id_nesting_flag
  12679. };
  12680. };
  12681. _proto.readSPS = function readSPS(sps) {
  12682. var eg = new ExpGolomb(this.ebsp2rbsp(sps));
  12683. eg.readUByte();
  12684. eg.readUByte();
  12685. eg.readBits(4); //video_parameter_set_id
  12686. var max_sub_layers_minus1 = eg.readBits(3);
  12687. eg.readBoolean(); // temporal_id_nesting_flag
  12688. // profile_tier_level
  12689. var general_profile_space = eg.readBits(2);
  12690. var general_tier_flag = eg.readBoolean();
  12691. var general_profile_idc = eg.readBits(5);
  12692. var general_profile_compatibility_flags_1 = eg.readUByte();
  12693. var general_profile_compatibility_flags_2 = eg.readUByte();
  12694. var general_profile_compatibility_flags_3 = eg.readUByte();
  12695. var general_profile_compatibility_flags_4 = eg.readUByte();
  12696. var general_constraint_indicator_flags_1 = eg.readUByte();
  12697. var general_constraint_indicator_flags_2 = eg.readUByte();
  12698. var general_constraint_indicator_flags_3 = eg.readUByte();
  12699. var general_constraint_indicator_flags_4 = eg.readUByte();
  12700. var general_constraint_indicator_flags_5 = eg.readUByte();
  12701. var general_constraint_indicator_flags_6 = eg.readUByte();
  12702. var general_level_idc = eg.readUByte();
  12703. var sub_layer_profile_present_flags = [];
  12704. var sub_layer_level_present_flags = [];
  12705. for (var i = 0; i < max_sub_layers_minus1; i++) {
  12706. sub_layer_profile_present_flags.push(eg.readBoolean());
  12707. sub_layer_level_present_flags.push(eg.readBoolean());
  12708. }
  12709. if (max_sub_layers_minus1 > 0) {
  12710. for (var _i = max_sub_layers_minus1; _i < 8; _i++) {
  12711. eg.readBits(2);
  12712. }
  12713. }
  12714. for (var _i2 = 0; _i2 < max_sub_layers_minus1; _i2++) {
  12715. if (sub_layer_profile_present_flags[_i2]) {
  12716. eg.readUByte(); // sub_layer_profile_space, sub_layer_tier_flag, sub_layer_profile_idc
  12717. eg.readUByte();
  12718. eg.readUByte();
  12719. eg.readUByte();
  12720. eg.readUByte(); // sub_layer_profile_compatibility_flag
  12721. eg.readUByte();
  12722. eg.readUByte();
  12723. eg.readUByte();
  12724. eg.readUByte();
  12725. eg.readUByte();
  12726. eg.readUByte();
  12727. }
  12728. if (sub_layer_level_present_flags[_i2]) {
  12729. eg.readUByte();
  12730. }
  12731. }
  12732. eg.readUEG(); // seq_parameter_set_id
  12733. var chroma_format_idc = eg.readUEG();
  12734. if (chroma_format_idc == 3) {
  12735. eg.skipBits(1); //separate_colour_plane_flag
  12736. }
  12737. var pic_width_in_luma_samples = eg.readUEG();
  12738. var pic_height_in_luma_samples = eg.readUEG();
  12739. var conformance_window_flag = eg.readBoolean();
  12740. var pic_left_offset = 0,
  12741. pic_right_offset = 0,
  12742. pic_top_offset = 0,
  12743. pic_bottom_offset = 0;
  12744. if (conformance_window_flag) {
  12745. pic_left_offset += eg.readUEG();
  12746. pic_right_offset += eg.readUEG();
  12747. pic_top_offset += eg.readUEG();
  12748. pic_bottom_offset += eg.readUEG();
  12749. }
  12750. var bit_depth_luma_minus8 = eg.readUEG();
  12751. var bit_depth_chroma_minus8 = eg.readUEG();
  12752. var log2_max_pic_order_cnt_lsb_minus4 = eg.readUEG();
  12753. var sub_layer_ordering_info_present_flag = eg.readBoolean();
  12754. for (var _i3 = sub_layer_ordering_info_present_flag ? 0 : max_sub_layers_minus1; _i3 <= max_sub_layers_minus1; _i3++) {
  12755. eg.skipUEG(); // max_dec_pic_buffering_minus1[i]
  12756. eg.skipUEG(); // max_num_reorder_pics[i]
  12757. eg.skipUEG(); // max_latency_increase_plus1[i]
  12758. }
  12759. eg.skipUEG(); // log2_min_luma_coding_block_size_minus3
  12760. eg.skipUEG(); // log2_diff_max_min_luma_coding_block_size
  12761. eg.skipUEG(); // log2_min_transform_block_size_minus2
  12762. eg.skipUEG(); // log2_diff_max_min_transform_block_size
  12763. eg.skipUEG(); // max_transform_hierarchy_depth_inter
  12764. eg.skipUEG(); // max_transform_hierarchy_depth_intra
  12765. var scaling_list_enabled_flag = eg.readBoolean();
  12766. if (scaling_list_enabled_flag) {
  12767. var sps_scaling_list_data_present_flag = eg.readBoolean();
  12768. if (sps_scaling_list_data_present_flag) {
  12769. for (var sizeId = 0; sizeId < 4; sizeId++) {
  12770. for (var matrixId = 0; matrixId < (sizeId === 3 ? 2 : 6); matrixId++) {
  12771. var scaling_list_pred_mode_flag = eg.readBoolean();
  12772. if (!scaling_list_pred_mode_flag) {
  12773. eg.readUEG(); // scaling_list_pred_matrix_id_delta
  12774. } else {
  12775. var coefNum = Math.min(64, 1 << 4 + (sizeId << 1));
  12776. if (sizeId > 1) {
  12777. eg.readEG();
  12778. }
  12779. for (var _i4 = 0; _i4 < coefNum; _i4++) {
  12780. eg.readEG();
  12781. }
  12782. }
  12783. }
  12784. }
  12785. }
  12786. }
  12787. eg.readBoolean(); // amp_enabled_flag
  12788. eg.readBoolean(); // sample_adaptive_offset_enabled_flag
  12789. var pcm_enabled_flag = eg.readBoolean();
  12790. if (pcm_enabled_flag) {
  12791. eg.readUByte();
  12792. eg.skipUEG();
  12793. eg.skipUEG();
  12794. eg.readBoolean();
  12795. }
  12796. var num_short_term_ref_pic_sets = eg.readUEG();
  12797. var num_delta_pocs = 0;
  12798. for (var _i5 = 0; _i5 < num_short_term_ref_pic_sets; _i5++) {
  12799. var inter_ref_pic_set_prediction_flag = false;
  12800. if (_i5 !== 0) {
  12801. inter_ref_pic_set_prediction_flag = eg.readBoolean();
  12802. }
  12803. if (inter_ref_pic_set_prediction_flag) {
  12804. if (_i5 === num_short_term_ref_pic_sets) {
  12805. eg.readUEG();
  12806. }
  12807. eg.readBoolean();
  12808. eg.readUEG();
  12809. var next_num_delta_pocs = 0;
  12810. for (var j = 0; j <= num_delta_pocs; j++) {
  12811. var used_by_curr_pic_flag = eg.readBoolean();
  12812. var use_delta_flag = false;
  12813. if (!used_by_curr_pic_flag) {
  12814. use_delta_flag = eg.readBoolean();
  12815. }
  12816. if (used_by_curr_pic_flag || use_delta_flag) {
  12817. next_num_delta_pocs++;
  12818. }
  12819. }
  12820. num_delta_pocs = next_num_delta_pocs;
  12821. } else {
  12822. var num_negative_pics = eg.readUEG();
  12823. var num_positive_pics = eg.readUEG();
  12824. num_delta_pocs = num_negative_pics + num_positive_pics;
  12825. for (var _j = 0; _j < num_negative_pics; _j++) {
  12826. eg.readUEG();
  12827. eg.readBoolean();
  12828. }
  12829. for (var _j2 = 0; _j2 < num_positive_pics; _j2++) {
  12830. eg.readUEG();
  12831. eg.readBoolean();
  12832. }
  12833. }
  12834. }
  12835. var long_term_ref_pics_present_flag = eg.readBoolean();
  12836. if (long_term_ref_pics_present_flag) {
  12837. var num_long_term_ref_pics_sps = eg.readUEG();
  12838. for (var _i6 = 0; _i6 < num_long_term_ref_pics_sps; _i6++) {
  12839. for (var _j3 = 0; _j3 < log2_max_pic_order_cnt_lsb_minus4 + 4; _j3++) {
  12840. eg.readBits(1);
  12841. }
  12842. eg.readBits(1);
  12843. }
  12844. }
  12845. var min_spatial_segmentation_idc = 0;
  12846. var sar_width = 1,
  12847. sar_height = 1;
  12848. var fps_fixed = true,
  12849. fps_den = 1,
  12850. fps_num = 0;
  12851. eg.readBoolean(); // sps_temporal_mvp_enabled_flag
  12852. eg.readBoolean(); // strong_intra_smoothing_enabled_flag
  12853. var default_display_window_flag = false;
  12854. var vui_parameters_present_flag = eg.readBoolean();
  12855. if (vui_parameters_present_flag) {
  12856. var aspect_ratio_info_present_flag = eg.readBoolean();
  12857. if (aspect_ratio_info_present_flag) {
  12858. var aspect_ratio_idc = eg.readUByte();
  12859. var sar_width_table = [1, 12, 10, 16, 40, 24, 20, 32, 80, 18, 15, 64, 160, 4, 3, 2];
  12860. var sar_height_table = [1, 11, 11, 11, 33, 11, 11, 11, 33, 11, 11, 33, 99, 3, 2, 1];
  12861. if (aspect_ratio_idc > 0 && aspect_ratio_idc < 16) {
  12862. sar_width = sar_width_table[aspect_ratio_idc - 1];
  12863. sar_height = sar_height_table[aspect_ratio_idc - 1];
  12864. } else if (aspect_ratio_idc === 255) {
  12865. sar_width = eg.readBits(16);
  12866. sar_height = eg.readBits(16);
  12867. }
  12868. }
  12869. var overscan_info_present_flag = eg.readBoolean();
  12870. if (overscan_info_present_flag) {
  12871. eg.readBoolean();
  12872. }
  12873. var video_signal_type_present_flag = eg.readBoolean();
  12874. if (video_signal_type_present_flag) {
  12875. eg.readBits(3);
  12876. eg.readBoolean();
  12877. var colour_description_present_flag = eg.readBoolean();
  12878. if (colour_description_present_flag) {
  12879. eg.readUByte();
  12880. eg.readUByte();
  12881. eg.readUByte();
  12882. }
  12883. }
  12884. var chroma_loc_info_present_flag = eg.readBoolean();
  12885. if (chroma_loc_info_present_flag) {
  12886. eg.readUEG();
  12887. eg.readUEG();
  12888. }
  12889. eg.readBoolean(); // neutral_chroma_indication_flag
  12890. eg.readBoolean(); // field_seq_flag
  12891. eg.readBoolean(); // frame_field_info_present_flag
  12892. default_display_window_flag = eg.readBoolean();
  12893. if (default_display_window_flag) {
  12894. pic_left_offset += eg.readUEG();
  12895. pic_right_offset += eg.readUEG();
  12896. pic_top_offset += eg.readUEG();
  12897. pic_bottom_offset += eg.readUEG();
  12898. }
  12899. var vui_timing_info_present_flag = eg.readBoolean();
  12900. if (vui_timing_info_present_flag) {
  12901. fps_den = eg.readBits(32);
  12902. fps_num = eg.readBits(32);
  12903. var vui_poc_proportional_to_timing_flag = eg.readBoolean();
  12904. if (vui_poc_proportional_to_timing_flag) {
  12905. eg.readUEG();
  12906. }
  12907. var vui_hrd_parameters_present_flag = eg.readBoolean();
  12908. if (vui_hrd_parameters_present_flag) {
  12909. //const commonInfPresentFlag = true;
  12910. //if (commonInfPresentFlag) {
  12911. var nal_hrd_parameters_present_flag = eg.readBoolean();
  12912. var vcl_hrd_parameters_present_flag = eg.readBoolean();
  12913. var sub_pic_hrd_params_present_flag = false;
  12914. if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) {
  12915. sub_pic_hrd_params_present_flag = eg.readBoolean();
  12916. if (sub_pic_hrd_params_present_flag) {
  12917. eg.readUByte();
  12918. eg.readBits(5);
  12919. eg.readBoolean();
  12920. eg.readBits(5);
  12921. }
  12922. eg.readBits(4); // bit_rate_scale
  12923. eg.readBits(4); // cpb_size_scale
  12924. if (sub_pic_hrd_params_present_flag) {
  12925. eg.readBits(4);
  12926. }
  12927. eg.readBits(5);
  12928. eg.readBits(5);
  12929. eg.readBits(5);
  12930. }
  12931. //}
  12932. for (var _i7 = 0; _i7 <= max_sub_layers_minus1; _i7++) {
  12933. fps_fixed = eg.readBoolean(); // fixed_pic_rate_general_flag
  12934. var fixed_pic_rate_within_cvs_flag = fps_fixed || eg.readBoolean();
  12935. var low_delay_hrd_flag = false;
  12936. if (fixed_pic_rate_within_cvs_flag) {
  12937. eg.readEG();
  12938. } else {
  12939. low_delay_hrd_flag = eg.readBoolean();
  12940. }
  12941. var cpb_cnt = low_delay_hrd_flag ? 1 : eg.readUEG() + 1;
  12942. if (nal_hrd_parameters_present_flag) {
  12943. for (var _j4 = 0; _j4 < cpb_cnt; _j4++) {
  12944. eg.readUEG();
  12945. eg.readUEG();
  12946. if (sub_pic_hrd_params_present_flag) {
  12947. eg.readUEG();
  12948. eg.readUEG();
  12949. }
  12950. eg.skipBits(1);
  12951. }
  12952. }
  12953. if (vcl_hrd_parameters_present_flag) {
  12954. for (var _j5 = 0; _j5 < cpb_cnt; _j5++) {
  12955. eg.readUEG();
  12956. eg.readUEG();
  12957. if (sub_pic_hrd_params_present_flag) {
  12958. eg.readUEG();
  12959. eg.readUEG();
  12960. }
  12961. eg.skipBits(1);
  12962. }
  12963. }
  12964. }
  12965. }
  12966. }
  12967. var bitstream_restriction_flag = eg.readBoolean();
  12968. if (bitstream_restriction_flag) {
  12969. eg.readBoolean(); // tiles_fixed_structure_flag
  12970. eg.readBoolean(); // motion_vectors_over_pic_boundaries_flag
  12971. eg.readBoolean(); // restricted_ref_pic_lists_flag
  12972. min_spatial_segmentation_idc = eg.readUEG();
  12973. }
  12974. }
  12975. var width = pic_width_in_luma_samples,
  12976. height = pic_height_in_luma_samples;
  12977. if (conformance_window_flag || default_display_window_flag) {
  12978. var chroma_scale_w = 1,
  12979. chroma_scale_h = 1;
  12980. if (chroma_format_idc === 1) {
  12981. // YUV 420
  12982. chroma_scale_w = chroma_scale_h = 2;
  12983. } else if (chroma_format_idc == 2) {
  12984. // YUV 422
  12985. chroma_scale_w = 2;
  12986. }
  12987. width = pic_width_in_luma_samples - chroma_scale_w * pic_right_offset - chroma_scale_w * pic_left_offset;
  12988. height = pic_height_in_luma_samples - chroma_scale_h * pic_bottom_offset - chroma_scale_h * pic_top_offset;
  12989. }
  12990. var profile_space_string = general_profile_space ? ['A', 'B', 'C'][general_profile_space] : '';
  12991. var profile_compatibility_buf = general_profile_compatibility_flags_1 << 24 | general_profile_compatibility_flags_2 << 16 | general_profile_compatibility_flags_3 << 8 | general_profile_compatibility_flags_4;
  12992. var profile_compatibility_rev = 0;
  12993. for (var _i8 = 0; _i8 < 32; _i8++) {
  12994. profile_compatibility_rev = (profile_compatibility_rev | (profile_compatibility_buf >> _i8 & 1) << 31 - _i8) >>> 0; // reverse bit position (and cast as UInt32)
  12995. }
  12996. var profile_compatibility_flags_string = profile_compatibility_rev.toString(16);
  12997. if (general_profile_idc === 1 && profile_compatibility_flags_string === '2') {
  12998. profile_compatibility_flags_string = '6';
  12999. }
  13000. var tier_flag_string = general_tier_flag ? 'H' : 'L';
  13001. return {
  13002. codecString: "hvc1." + profile_space_string + general_profile_idc + "." + profile_compatibility_flags_string + "." + tier_flag_string + general_level_idc + ".B0",
  13003. params: {
  13004. general_tier_flag: general_tier_flag,
  13005. general_profile_idc: general_profile_idc,
  13006. general_profile_space: general_profile_space,
  13007. general_profile_compatibility_flags: [general_profile_compatibility_flags_1, general_profile_compatibility_flags_2, general_profile_compatibility_flags_3, general_profile_compatibility_flags_4],
  13008. general_constraint_indicator_flags: [general_constraint_indicator_flags_1, general_constraint_indicator_flags_2, general_constraint_indicator_flags_3, general_constraint_indicator_flags_4, general_constraint_indicator_flags_5, general_constraint_indicator_flags_6],
  13009. general_level_idc: general_level_idc,
  13010. bit_depth: bit_depth_luma_minus8 + 8,
  13011. bit_depth_luma_minus8: bit_depth_luma_minus8,
  13012. bit_depth_chroma_minus8: bit_depth_chroma_minus8,
  13013. min_spatial_segmentation_idc: min_spatial_segmentation_idc,
  13014. chroma_format_idc: chroma_format_idc,
  13015. frame_rate: {
  13016. fixed: fps_fixed,
  13017. fps: fps_num / fps_den
  13018. }
  13019. },
  13020. width: width,
  13021. height: height,
  13022. pixelRatio: [sar_width, sar_height]
  13023. };
  13024. };
  13025. _proto.readPPS = function readPPS(pps) {
  13026. var eg = new ExpGolomb(this.ebsp2rbsp(pps));
  13027. eg.readUByte();
  13028. eg.readUByte();
  13029. eg.skipUEG(); // pic_parameter_set_id
  13030. eg.skipUEG(); // seq_parameter_set_id
  13031. eg.skipBits(2); // dependent_slice_segments_enabled_flag, output_flag_present_flag
  13032. eg.skipBits(3); // num_extra_slice_header_bits
  13033. eg.skipBits(2); // sign_data_hiding_enabled_flag, cabac_init_present_flag
  13034. eg.skipUEG();
  13035. eg.skipUEG();
  13036. eg.skipEG(); // init_qp_minus26
  13037. eg.skipBits(2); // constrained_intra_pred_flag, transform_skip_enabled_flag
  13038. var cu_qp_delta_enabled_flag = eg.readBoolean();
  13039. if (cu_qp_delta_enabled_flag) {
  13040. eg.skipUEG();
  13041. }
  13042. eg.skipEG(); // cb_qp_offset
  13043. eg.skipEG(); // cr_qp_offset
  13044. eg.skipBits(4); // pps_slice_chroma_qp_offsets_present_flag, weighted_pred_flag, weighted_bipred_flag, transquant_bypass_enabled_flag
  13045. var tiles_enabled_flag = eg.readBoolean();
  13046. var entropy_coding_sync_enabled_flag = eg.readBoolean();
  13047. var parallelismType = 1; // slice-based parallel decoding
  13048. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag) {
  13049. parallelismType = 0; // mixed-type parallel decoding
  13050. } else if (entropy_coding_sync_enabled_flag) {
  13051. parallelismType = 3; // wavefront-based parallel decoding
  13052. } else if (tiles_enabled_flag) {
  13053. parallelismType = 2; // tile-based parallel decoding
  13054. }
  13055. return {
  13056. parallelismType: parallelismType
  13057. };
  13058. };
  13059. _proto.matchSPS = function matchSPS(sps1, sps2) {
  13060. // compare without headers and VPS related params
  13061. return String.fromCharCode.apply(null, sps1).substr(3) === String.fromCharCode.apply(null, sps2).substr(3);
  13062. };
  13063. return HevcVideoParser;
  13064. }(BaseVideoParser);
  13065. var PACKET_LENGTH = 188;
  13066. var TSDemuxer = /*#__PURE__*/function () {
  13067. function TSDemuxer(observer, config, typeSupported, logger) {
  13068. this.logger = void 0;
  13069. this.observer = void 0;
  13070. this.config = void 0;
  13071. this.typeSupported = void 0;
  13072. this.sampleAes = null;
  13073. this.pmtParsed = false;
  13074. this.audioCodec = void 0;
  13075. this.videoCodec = void 0;
  13076. this._pmtId = -1;
  13077. this._videoTrack = void 0;
  13078. this._audioTrack = void 0;
  13079. this._id3Track = void 0;
  13080. this._txtTrack = void 0;
  13081. this.aacOverFlow = null;
  13082. this.remainderData = null;
  13083. this.videoParser = void 0;
  13084. this.observer = observer;
  13085. this.config = config;
  13086. this.typeSupported = typeSupported;
  13087. this.logger = logger;
  13088. this.videoParser = null;
  13089. }
  13090. TSDemuxer.probe = function probe(data, logger) {
  13091. var syncOffset = TSDemuxer.syncOffset(data);
  13092. if (syncOffset > 0) {
  13093. logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset);
  13094. }
  13095. return syncOffset !== -1;
  13096. };
  13097. TSDemuxer.syncOffset = function syncOffset(data) {
  13098. var length = data.length;
  13099. var scanwindow = Math.min(PACKET_LENGTH * 5, length - PACKET_LENGTH) + 1;
  13100. var i = 0;
  13101. while (i < scanwindow) {
  13102. // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47
  13103. var foundPat = false;
  13104. var packetStart = -1;
  13105. var tsPackets = 0;
  13106. for (var j = i; j < length; j += PACKET_LENGTH) {
  13107. if (data[j] === 0x47 && (length - j === PACKET_LENGTH || data[j + PACKET_LENGTH] === 0x47)) {
  13108. tsPackets++;
  13109. if (packetStart === -1) {
  13110. packetStart = j;
  13111. // First sync word found at offset, increase scan length (#5251)
  13112. if (packetStart !== 0) {
  13113. scanwindow = Math.min(packetStart + PACKET_LENGTH * 99, data.length - PACKET_LENGTH) + 1;
  13114. }
  13115. }
  13116. if (!foundPat) {
  13117. foundPat = parsePID(data, j) === 0;
  13118. }
  13119. // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)
  13120. if (foundPat && tsPackets > 1 && (packetStart === 0 && tsPackets > 2 || j + PACKET_LENGTH > scanwindow)) {
  13121. return packetStart;
  13122. }
  13123. } else if (tsPackets) {
  13124. // Exit if sync word found, but does not contain contiguous packets
  13125. return -1;
  13126. } else {
  13127. break;
  13128. }
  13129. }
  13130. i++;
  13131. }
  13132. return -1;
  13133. }
  13134. /**
  13135. * Creates a track model internal to demuxer used to drive remuxing input
  13136. */;
  13137. TSDemuxer.createTrack = function createTrack(type, duration) {
  13138. return {
  13139. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  13140. type: type,
  13141. id: RemuxerTrackIdConfig[type],
  13142. pid: -1,
  13143. inputTimeScale: 90000,
  13144. sequenceNumber: 0,
  13145. samples: [],
  13146. dropped: 0,
  13147. duration: type === 'audio' ? duration : undefined
  13148. };
  13149. }
  13150. /**
  13151. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  13152. * Resets all internal track instances of the demuxer.
  13153. */;
  13154. var _proto = TSDemuxer.prototype;
  13155. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration) {
  13156. this.pmtParsed = false;
  13157. this._pmtId = -1;
  13158. this._videoTrack = TSDemuxer.createTrack('video');
  13159. this._videoTrack.duration = trackDuration;
  13160. this._audioTrack = TSDemuxer.createTrack('audio', trackDuration);
  13161. this._id3Track = TSDemuxer.createTrack('id3');
  13162. this._txtTrack = TSDemuxer.createTrack('text');
  13163. this._audioTrack.segmentCodec = 'aac';
  13164. // flush any partial content
  13165. this.aacOverFlow = null;
  13166. this.remainderData = null;
  13167. this.audioCodec = audioCodec;
  13168. this.videoCodec = videoCodec;
  13169. };
  13170. _proto.resetTimeStamp = function resetTimeStamp() {};
  13171. _proto.resetContiguity = function resetContiguity() {
  13172. var _audioTrack = this._audioTrack,
  13173. _videoTrack = this._videoTrack,
  13174. _id3Track = this._id3Track;
  13175. if (_audioTrack) {
  13176. _audioTrack.pesData = null;
  13177. }
  13178. if (_videoTrack) {
  13179. _videoTrack.pesData = null;
  13180. }
  13181. if (_id3Track) {
  13182. _id3Track.pesData = null;
  13183. }
  13184. this.aacOverFlow = null;
  13185. this.remainderData = null;
  13186. };
  13187. _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
  13188. if (isSampleAes === void 0) {
  13189. isSampleAes = false;
  13190. }
  13191. if (flush === void 0) {
  13192. flush = false;
  13193. }
  13194. if (!isSampleAes) {
  13195. this.sampleAes = null;
  13196. }
  13197. var pes;
  13198. var videoTrack = this._videoTrack;
  13199. var audioTrack = this._audioTrack;
  13200. var id3Track = this._id3Track;
  13201. var textTrack = this._txtTrack;
  13202. var videoPid = videoTrack.pid;
  13203. var videoData = videoTrack.pesData;
  13204. var audioPid = audioTrack.pid;
  13205. var id3Pid = id3Track.pid;
  13206. var audioData = audioTrack.pesData;
  13207. var id3Data = id3Track.pesData;
  13208. var unknownPID = null;
  13209. var pmtParsed = this.pmtParsed;
  13210. var pmtId = this._pmtId;
  13211. var len = data.length;
  13212. if (this.remainderData) {
  13213. data = appendUint8Array(this.remainderData, data);
  13214. len = data.length;
  13215. this.remainderData = null;
  13216. }
  13217. if (len < PACKET_LENGTH && !flush) {
  13218. this.remainderData = data;
  13219. return {
  13220. audioTrack: audioTrack,
  13221. videoTrack: videoTrack,
  13222. id3Track: id3Track,
  13223. textTrack: textTrack
  13224. };
  13225. }
  13226. var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
  13227. len -= (len - syncOffset) % PACKET_LENGTH;
  13228. if (len < data.byteLength && !flush) {
  13229. this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
  13230. }
  13231. // loop through TS packets
  13232. var tsPacketErrors = 0;
  13233. for (var start = syncOffset; start < len; start += PACKET_LENGTH) {
  13234. if (data[start] === 0x47) {
  13235. var stt = !!(data[start + 1] & 0x40);
  13236. var pid = parsePID(data, start);
  13237. var atf = (data[start + 3] & 0x30) >> 4;
  13238. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  13239. var offset = void 0;
  13240. if (atf > 1) {
  13241. offset = start + 5 + data[start + 4];
  13242. // continue if there is only adaptation field
  13243. if (offset === start + PACKET_LENGTH) {
  13244. continue;
  13245. }
  13246. } else {
  13247. offset = start + 4;
  13248. }
  13249. switch (pid) {
  13250. case videoPid:
  13251. if (stt) {
  13252. if (videoData && (pes = parsePES(videoData, this.logger))) {
  13253. if (this.videoParser === null) {
  13254. switch (videoTrack.segmentCodec) {
  13255. case 'avc':
  13256. this.videoParser = new AvcVideoParser();
  13257. break;
  13258. case 'hevc':
  13259. {
  13260. this.videoParser = new HevcVideoParser();
  13261. }
  13262. break;
  13263. }
  13264. }
  13265. if (this.videoParser !== null) {
  13266. this.videoParser.parsePES(videoTrack, textTrack, pes, false);
  13267. }
  13268. }
  13269. videoData = {
  13270. data: [],
  13271. size: 0
  13272. };
  13273. }
  13274. if (videoData) {
  13275. videoData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  13276. videoData.size += start + PACKET_LENGTH - offset;
  13277. }
  13278. break;
  13279. case audioPid:
  13280. if (stt) {
  13281. if (audioData && (pes = parsePES(audioData, this.logger))) {
  13282. switch (audioTrack.segmentCodec) {
  13283. case 'aac':
  13284. this.parseAACPES(audioTrack, pes);
  13285. break;
  13286. case 'mp3':
  13287. this.parseMPEGPES(audioTrack, pes);
  13288. break;
  13289. case 'ac3':
  13290. {
  13291. this.parseAC3PES(audioTrack, pes);
  13292. }
  13293. break;
  13294. }
  13295. }
  13296. audioData = {
  13297. data: [],
  13298. size: 0
  13299. };
  13300. }
  13301. if (audioData) {
  13302. audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));
  13303. audioData.size += start + PACKET_LENGTH - offset;
  13304. }
  13305. break;
  13306. case id3Pid:
  13307. if (stt) {
  13308. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  13309. this.parseID3PES(id3Track, pes);
  13310. }
  13311. id3Data = {
  13312. data: [],
  13313. size: 0
  13314. };
  13315. }
  13316. if (id3Data) {
  13317. id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));
  13318. id3Data.size += start + PACKET_LENGTH - offset;
  13319. }
  13320. break;
  13321. case 0:
  13322. if (stt) {
  13323. offset += data[offset] + 1;
  13324. }
  13325. pmtId = this._pmtId = parsePAT(data, offset);
  13326. // this.logger.log('PMT PID:' + this._pmtId);
  13327. break;
  13328. case pmtId:
  13329. {
  13330. if (stt) {
  13331. offset += data[offset] + 1;
  13332. }
  13333. var parsedPIDs = parsePMT(data, offset, this.typeSupported, isSampleAes, this.observer, this.logger);
  13334. // only update track id if track PID found while parsing PMT
  13335. // this is to avoid resetting the PID to -1 in case
  13336. // track PID transiently disappears from the stream
  13337. // this could happen in case of transient missing audio samples for example
  13338. // NOTE this is only the PID of the track as found in TS,
  13339. // but we are not using this for MP4 track IDs.
  13340. videoPid = parsedPIDs.videoPid;
  13341. if (videoPid > 0) {
  13342. videoTrack.pid = videoPid;
  13343. videoTrack.segmentCodec = parsedPIDs.segmentVideoCodec;
  13344. }
  13345. audioPid = parsedPIDs.audioPid;
  13346. if (audioPid > 0) {
  13347. audioTrack.pid = audioPid;
  13348. audioTrack.segmentCodec = parsedPIDs.segmentAudioCodec;
  13349. }
  13350. id3Pid = parsedPIDs.id3Pid;
  13351. if (id3Pid > 0) {
  13352. id3Track.pid = id3Pid;
  13353. }
  13354. if (unknownPID !== null && !pmtParsed) {
  13355. this.logger.warn("MPEG-TS PMT found at " + start + " after unknown PID '" + unknownPID + "'. Backtracking to sync byte @" + syncOffset + " to parse all TS packets.");
  13356. unknownPID = null;
  13357. // we set it to -188, the += 188 in the for loop will reset start to 0
  13358. start = syncOffset - 188;
  13359. }
  13360. pmtParsed = this.pmtParsed = true;
  13361. break;
  13362. }
  13363. case 0x11:
  13364. case 0x1fff:
  13365. break;
  13366. default:
  13367. unknownPID = pid;
  13368. break;
  13369. }
  13370. } else {
  13371. tsPacketErrors++;
  13372. }
  13373. }
  13374. if (tsPacketErrors > 0) {
  13375. emitParsingError(this.observer, new Error("Found " + tsPacketErrors + " TS packet/s that do not start with 0x47"), undefined, this.logger);
  13376. }
  13377. videoTrack.pesData = videoData;
  13378. audioTrack.pesData = audioData;
  13379. id3Track.pesData = id3Data;
  13380. var demuxResult = {
  13381. audioTrack: audioTrack,
  13382. videoTrack: videoTrack,
  13383. id3Track: id3Track,
  13384. textTrack: textTrack
  13385. };
  13386. if (flush) {
  13387. this.extractRemainingSamples(demuxResult);
  13388. }
  13389. return demuxResult;
  13390. };
  13391. _proto.flush = function flush() {
  13392. var remainderData = this.remainderData;
  13393. this.remainderData = null;
  13394. var result;
  13395. if (remainderData) {
  13396. result = this.demux(remainderData, -1, false, true);
  13397. } else {
  13398. result = {
  13399. videoTrack: this._videoTrack,
  13400. audioTrack: this._audioTrack,
  13401. id3Track: this._id3Track,
  13402. textTrack: this._txtTrack
  13403. };
  13404. }
  13405. this.extractRemainingSamples(result);
  13406. if (this.sampleAes) {
  13407. return this.decrypt(result, this.sampleAes);
  13408. }
  13409. return result;
  13410. };
  13411. _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
  13412. var audioTrack = demuxResult.audioTrack,
  13413. videoTrack = demuxResult.videoTrack,
  13414. id3Track = demuxResult.id3Track,
  13415. textTrack = demuxResult.textTrack;
  13416. var videoData = videoTrack.pesData;
  13417. var audioData = audioTrack.pesData;
  13418. var id3Data = id3Track.pesData;
  13419. // try to parse last PES packets
  13420. var pes;
  13421. if (videoData && (pes = parsePES(videoData, this.logger))) {
  13422. if (this.videoParser === null) {
  13423. switch (videoTrack.segmentCodec) {
  13424. case 'avc':
  13425. this.videoParser = new AvcVideoParser();
  13426. break;
  13427. case 'hevc':
  13428. {
  13429. this.videoParser = new HevcVideoParser();
  13430. }
  13431. break;
  13432. }
  13433. }
  13434. if (this.videoParser !== null) {
  13435. this.videoParser.parsePES(videoTrack, textTrack, pes, true);
  13436. videoTrack.pesData = null;
  13437. }
  13438. } else {
  13439. // either avcData null or PES truncated, keep it for next frag parsing
  13440. videoTrack.pesData = videoData;
  13441. }
  13442. if (audioData && (pes = parsePES(audioData, this.logger))) {
  13443. switch (audioTrack.segmentCodec) {
  13444. case 'aac':
  13445. this.parseAACPES(audioTrack, pes);
  13446. break;
  13447. case 'mp3':
  13448. this.parseMPEGPES(audioTrack, pes);
  13449. break;
  13450. case 'ac3':
  13451. {
  13452. this.parseAC3PES(audioTrack, pes);
  13453. }
  13454. break;
  13455. }
  13456. audioTrack.pesData = null;
  13457. } else {
  13458. if (audioData != null && audioData.size) {
  13459. this.logger.log('last AAC PES packet truncated,might overlap between fragments');
  13460. }
  13461. // either audioData null or PES truncated, keep it for next frag parsing
  13462. audioTrack.pesData = audioData;
  13463. }
  13464. if (id3Data && (pes = parsePES(id3Data, this.logger))) {
  13465. this.parseID3PES(id3Track, pes);
  13466. id3Track.pesData = null;
  13467. } else {
  13468. // either id3Data null or PES truncated, keep it for next frag parsing
  13469. id3Track.pesData = id3Data;
  13470. }
  13471. };
  13472. _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
  13473. var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
  13474. var sampleAes = this.sampleAes = new SampleAesDecrypter(this.observer, this.config, keyData);
  13475. return this.decrypt(demuxResult, sampleAes);
  13476. };
  13477. _proto.decrypt = function decrypt(demuxResult, sampleAes) {
  13478. return new Promise(function (resolve) {
  13479. var audioTrack = demuxResult.audioTrack,
  13480. videoTrack = demuxResult.videoTrack;
  13481. if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {
  13482. sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  13483. if (videoTrack.samples) {
  13484. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  13485. resolve(demuxResult);
  13486. });
  13487. } else {
  13488. resolve(demuxResult);
  13489. }
  13490. });
  13491. } else if (videoTrack.samples) {
  13492. sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  13493. resolve(demuxResult);
  13494. });
  13495. }
  13496. });
  13497. };
  13498. _proto.destroy = function destroy() {
  13499. if (this.observer) {
  13500. this.observer.removeAllListeners();
  13501. }
  13502. // @ts-ignore
  13503. this.config = this.logger = this.observer = null;
  13504. this.aacOverFlow = this.videoParser = this.remainderData = this.sampleAes = null;
  13505. this._videoTrack = this._audioTrack = this._id3Track = this._txtTrack = undefined;
  13506. };
  13507. _proto.parseAACPES = function parseAACPES(track, pes) {
  13508. var startOffset = 0;
  13509. var aacOverFlow = this.aacOverFlow;
  13510. var data = pes.data;
  13511. if (aacOverFlow) {
  13512. this.aacOverFlow = null;
  13513. var frameMissingBytes = aacOverFlow.missing;
  13514. var sampleLength = aacOverFlow.sample.unit.byteLength;
  13515. // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);
  13516. if (frameMissingBytes === -1) {
  13517. data = appendUint8Array(aacOverFlow.sample.unit, data);
  13518. } else {
  13519. var frameOverflowBytes = sampleLength - frameMissingBytes;
  13520. aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
  13521. track.samples.push(aacOverFlow.sample);
  13522. startOffset = aacOverFlow.missing;
  13523. }
  13524. }
  13525. // look for ADTS header (0xFFFx)
  13526. var offset;
  13527. var len;
  13528. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  13529. if (isHeader$1(data, offset)) {
  13530. break;
  13531. }
  13532. }
  13533. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  13534. if (offset !== startOffset) {
  13535. var reason;
  13536. var recoverable = offset < len - 1;
  13537. if (recoverable) {
  13538. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  13539. } else {
  13540. reason = 'No ADTS header found in AAC PES';
  13541. }
  13542. emitParsingError(this.observer, new Error(reason), recoverable, this.logger);
  13543. if (!recoverable) {
  13544. return;
  13545. }
  13546. }
  13547. initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  13548. var pts;
  13549. if (pes.pts !== undefined) {
  13550. pts = pes.pts;
  13551. } else if (aacOverFlow) {
  13552. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  13553. // first sample PTS should be equal to last sample PTS + frameDuration
  13554. var frameDuration = getFrameDuration(track.samplerate);
  13555. pts = aacOverFlow.sample.pts + frameDuration;
  13556. } else {
  13557. this.logger.warn('[tsdemuxer]: AAC PES unknown PTS');
  13558. return;
  13559. }
  13560. // scan for aac samples
  13561. var frameIndex = 0;
  13562. var frame;
  13563. while (offset < len) {
  13564. frame = appendFrame$1(track, data, offset, pts, frameIndex);
  13565. offset += frame.length;
  13566. if (!frame.missing) {
  13567. frameIndex++;
  13568. for (; offset < len - 1; offset++) {
  13569. if (isHeader$1(data, offset)) {
  13570. break;
  13571. }
  13572. }
  13573. } else {
  13574. this.aacOverFlow = frame;
  13575. break;
  13576. }
  13577. }
  13578. };
  13579. _proto.parseMPEGPES = function parseMPEGPES(track, pes) {
  13580. var data = pes.data;
  13581. var length = data.length;
  13582. var frameIndex = 0;
  13583. var offset = 0;
  13584. var pts = pes.pts;
  13585. if (pts === undefined) {
  13586. this.logger.warn('[tsdemuxer]: MPEG PES unknown PTS');
  13587. return;
  13588. }
  13589. while (offset < length) {
  13590. if (isHeader(data, offset)) {
  13591. var frame = appendFrame(track, data, offset, pts, frameIndex);
  13592. if (frame) {
  13593. offset += frame.length;
  13594. frameIndex++;
  13595. } else {
  13596. // logger.log('Unable to parse Mpeg audio frame');
  13597. break;
  13598. }
  13599. } else {
  13600. // nothing found, keep looking
  13601. offset++;
  13602. }
  13603. }
  13604. };
  13605. _proto.parseAC3PES = function parseAC3PES(track, pes) {
  13606. {
  13607. var data = pes.data;
  13608. var pts = pes.pts;
  13609. if (pts === undefined) {
  13610. this.logger.warn('[tsdemuxer]: AC3 PES unknown PTS');
  13611. return;
  13612. }
  13613. var length = data.length;
  13614. var frameIndex = 0;
  13615. var offset = 0;
  13616. var parsed;
  13617. while (offset < length && (parsed = _appendFrame(track, data, offset, pts, frameIndex++)) > 0) {
  13618. offset += parsed;
  13619. }
  13620. }
  13621. };
  13622. _proto.parseID3PES = function parseID3PES(id3Track, pes) {
  13623. if (pes.pts === undefined) {
  13624. this.logger.warn('[tsdemuxer]: ID3 PES unknown PTS');
  13625. return;
  13626. }
  13627. var id3Sample = _extends({}, pes, {
  13628. type: this._videoTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,
  13629. duration: Number.POSITIVE_INFINITY
  13630. });
  13631. id3Track.samples.push(id3Sample);
  13632. };
  13633. return TSDemuxer;
  13634. }();
  13635. function parsePID(data, offset) {
  13636. // pid is a 13-bit field starting at the last bit of TS[1]
  13637. return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];
  13638. }
  13639. function parsePAT(data, offset) {
  13640. // skip the PSI header and parse the first PMT entry
  13641. return (data[offset + 10] & 0x1f) << 8 | data[offset + 11];
  13642. }
  13643. function parsePMT(data, offset, typeSupported, isSampleAes, observer, logger) {
  13644. var result = {
  13645. audioPid: -1,
  13646. videoPid: -1,
  13647. id3Pid: -1,
  13648. segmentVideoCodec: 'avc',
  13649. segmentAudioCodec: 'aac'
  13650. };
  13651. var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  13652. var tableEnd = offset + 3 + sectionLength - 4;
  13653. // to determine where the table is, we have to figure out how
  13654. // long the program info descriptors are
  13655. var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  13656. // advance the offset to the first entry in the mapping table
  13657. offset += 12 + programInfoLength;
  13658. while (offset < tableEnd) {
  13659. var pid = parsePID(data, offset);
  13660. var esInfoLength = (data[offset + 3] & 0x0f) << 8 | data[offset + 4];
  13661. switch (data[offset]) {
  13662. case 0xcf:
  13663. // SAMPLE-AES AAC
  13664. if (!isSampleAes) {
  13665. logEncryptedSamplesFoundInUnencryptedStream('ADTS AAC', logger);
  13666. break;
  13667. }
  13668. /* falls through */
  13669. case 0x0f:
  13670. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  13671. // logger.log('AAC PID:' + pid);
  13672. if (result.audioPid === -1) {
  13673. result.audioPid = pid;
  13674. }
  13675. break;
  13676. // Packetized metadata (ID3)
  13677. case 0x15:
  13678. // logger.log('ID3 PID:' + pid);
  13679. if (result.id3Pid === -1) {
  13680. result.id3Pid = pid;
  13681. }
  13682. break;
  13683. case 0xdb:
  13684. // SAMPLE-AES AVC
  13685. if (!isSampleAes) {
  13686. logEncryptedSamplesFoundInUnencryptedStream('H.264', logger);
  13687. break;
  13688. }
  13689. /* falls through */
  13690. case 0x1b:
  13691. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  13692. // logger.log('AVC PID:' + pid);
  13693. if (result.videoPid === -1) {
  13694. result.videoPid = pid;
  13695. }
  13696. break;
  13697. // ISO/IEC 11172-3 (MPEG-1 audio)
  13698. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  13699. case 0x03:
  13700. case 0x04:
  13701. // logger.log('MPEG PID:' + pid);
  13702. if (!typeSupported.mpeg && !typeSupported.mp3) {
  13703. logger.log('MPEG audio found, not supported in this browser');
  13704. } else if (result.audioPid === -1) {
  13705. result.audioPid = pid;
  13706. result.segmentAudioCodec = 'mp3';
  13707. }
  13708. break;
  13709. case 0xc1:
  13710. // SAMPLE-AES AC3
  13711. if (!isSampleAes) {
  13712. logEncryptedSamplesFoundInUnencryptedStream('AC-3', logger);
  13713. break;
  13714. }
  13715. /* falls through */
  13716. case 0x81:
  13717. {
  13718. if (!typeSupported.ac3) {
  13719. logger.log('AC-3 audio found, not supported in this browser');
  13720. } else if (result.audioPid === -1) {
  13721. result.audioPid = pid;
  13722. result.segmentAudioCodec = 'ac3';
  13723. }
  13724. }
  13725. break;
  13726. case 0x06:
  13727. // stream_type 6 can mean a lot of different things in case of DVB.
  13728. // We need to look at the descriptors. Right now, we're only interested
  13729. // in AC-3 audio, so we do the descriptor parsing only when we don't have
  13730. // an audio PID yet.
  13731. if (result.audioPid === -1 && esInfoLength > 0) {
  13732. var parsePos = offset + 5;
  13733. var remaining = esInfoLength;
  13734. while (remaining > 2) {
  13735. var descriptorId = data[parsePos];
  13736. switch (descriptorId) {
  13737. case 0x6a:
  13738. // DVB Descriptor for AC-3
  13739. {
  13740. if (typeSupported.ac3 !== true) {
  13741. logger.log('AC-3 audio found, not supported in this browser for now');
  13742. } else {
  13743. result.audioPid = pid;
  13744. result.segmentAudioCodec = 'ac3';
  13745. }
  13746. }
  13747. break;
  13748. }
  13749. var descriptorLen = data[parsePos + 1] + 2;
  13750. parsePos += descriptorLen;
  13751. remaining -= descriptorLen;
  13752. }
  13753. }
  13754. break;
  13755. case 0xc2: // SAMPLE-AES EC3
  13756. /* falls through */
  13757. case 0x87:
  13758. emitParsingError(observer, new Error('Unsupported EC-3 in M2TS found'), undefined, logger);
  13759. return result;
  13760. case 0x24:
  13761. // ITU-T Rec. H.265 and ISO/IEC 23008-2 (HEVC)
  13762. {
  13763. if (result.videoPid === -1) {
  13764. result.videoPid = pid;
  13765. result.segmentVideoCodec = 'hevc';
  13766. logger.log('HEVC in M2TS found');
  13767. }
  13768. }
  13769. break;
  13770. }
  13771. // move to the next table entry
  13772. // skip past the elementary stream descriptors, if present
  13773. offset += esInfoLength + 5;
  13774. }
  13775. return result;
  13776. }
  13777. function emitParsingError(observer, error, levelRetry, logger) {
  13778. logger.warn("parsing error: " + error.message);
  13779. observer.emit(Events.ERROR, Events.ERROR, {
  13780. type: ErrorTypes.MEDIA_ERROR,
  13781. details: ErrorDetails.FRAG_PARSING_ERROR,
  13782. fatal: false,
  13783. levelRetry: levelRetry,
  13784. error: error,
  13785. reason: error.message
  13786. });
  13787. }
  13788. function logEncryptedSamplesFoundInUnencryptedStream(type, logger) {
  13789. logger.log(type + " with AES-128-CBC encryption found in unencrypted stream");
  13790. }
  13791. function parsePES(stream, logger) {
  13792. var i = 0;
  13793. var frag;
  13794. var pesLen;
  13795. var pesHdrLen;
  13796. var pesPts;
  13797. var pesDts;
  13798. var data = stream.data;
  13799. // safety check
  13800. if (!stream || stream.size === 0) {
  13801. return null;
  13802. }
  13803. // we might need up to 19 bytes to read PES header
  13804. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  13805. // usually only one merge is needed (and this is rare ...)
  13806. while (data[0].length < 19 && data.length > 1) {
  13807. data[0] = appendUint8Array(data[0], data[1]);
  13808. data.splice(1, 1);
  13809. }
  13810. // retrieve PTS/DTS from first fragment
  13811. frag = data[0];
  13812. var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  13813. if (pesPrefix === 1) {
  13814. pesLen = (frag[4] << 8) + frag[5];
  13815. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  13816. // minus 6 : PES header size
  13817. if (pesLen && pesLen > stream.size - 6) {
  13818. return null;
  13819. }
  13820. var pesFlags = frag[7];
  13821. if (pesFlags & 0xc0) {
  13822. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  13823. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  13824. as Bitwise operators treat their operands as a sequence of 32 bits */
  13825. pesPts = (frag[9] & 0x0e) * 536870912 +
  13826. // 1 << 29
  13827. (frag[10] & 0xff) * 4194304 +
  13828. // 1 << 22
  13829. (frag[11] & 0xfe) * 16384 +
  13830. // 1 << 14
  13831. (frag[12] & 0xff) * 128 +
  13832. // 1 << 7
  13833. (frag[13] & 0xfe) / 2;
  13834. if (pesFlags & 0x40) {
  13835. pesDts = (frag[14] & 0x0e) * 536870912 +
  13836. // 1 << 29
  13837. (frag[15] & 0xff) * 4194304 +
  13838. // 1 << 22
  13839. (frag[16] & 0xfe) * 16384 +
  13840. // 1 << 14
  13841. (frag[17] & 0xff) * 128 +
  13842. // 1 << 7
  13843. (frag[18] & 0xfe) / 2;
  13844. if (pesPts - pesDts > 60 * 90000) {
  13845. logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  13846. pesPts = pesDts;
  13847. }
  13848. } else {
  13849. pesDts = pesPts;
  13850. }
  13851. }
  13852. pesHdrLen = frag[8];
  13853. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  13854. var payloadStartOffset = pesHdrLen + 9;
  13855. if (stream.size <= payloadStartOffset) {
  13856. return null;
  13857. }
  13858. stream.size -= payloadStartOffset;
  13859. // reassemble PES packet
  13860. var pesData = new Uint8Array(stream.size);
  13861. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  13862. frag = data[j];
  13863. var len = frag.byteLength;
  13864. if (payloadStartOffset) {
  13865. if (payloadStartOffset > len) {
  13866. // trim full frag if PES header bigger than frag
  13867. payloadStartOffset -= len;
  13868. continue;
  13869. } else {
  13870. // trim partial frag if PES header smaller than frag
  13871. frag = frag.subarray(payloadStartOffset);
  13872. len -= payloadStartOffset;
  13873. payloadStartOffset = 0;
  13874. }
  13875. }
  13876. pesData.set(frag, i);
  13877. i += len;
  13878. }
  13879. if (pesLen) {
  13880. // payload size : remove PES header + PES extension
  13881. pesLen -= pesHdrLen + 3;
  13882. }
  13883. return {
  13884. data: pesData,
  13885. pts: pesPts,
  13886. dts: pesDts,
  13887. len: pesLen
  13888. };
  13889. }
  13890. return null;
  13891. }
  13892. /**
  13893. * AAC helper
  13894. */
  13895. var AAC = /*#__PURE__*/function () {
  13896. function AAC() {}
  13897. AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
  13898. switch (codec) {
  13899. case 'mp4a.40.2':
  13900. if (channelCount === 1) {
  13901. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  13902. } else if (channelCount === 2) {
  13903. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  13904. } else if (channelCount === 3) {
  13905. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  13906. } else if (channelCount === 4) {
  13907. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  13908. } else if (channelCount === 5) {
  13909. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  13910. } else if (channelCount === 6) {
  13911. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
  13912. }
  13913. break;
  13914. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  13915. default:
  13916. if (channelCount === 1) {
  13917. // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13918. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13919. } else if (channelCount === 2) {
  13920. // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13921. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13922. } else if (channelCount === 3) {
  13923. // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13924. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13925. }
  13926. break;
  13927. }
  13928. return undefined;
  13929. };
  13930. return AAC;
  13931. }();
  13932. /**
  13933. * Generate MP4 Box
  13934. */
  13935. var UINT32_MAX = Math.pow(2, 32) - 1;
  13936. var MP4 = /*#__PURE__*/function () {
  13937. function MP4() {}
  13938. MP4.init = function init() {
  13939. MP4.types = {
  13940. avc1: [],
  13941. // codingname
  13942. avcC: [],
  13943. hvc1: [],
  13944. hvcC: [],
  13945. btrt: [],
  13946. dinf: [],
  13947. dref: [],
  13948. esds: [],
  13949. ftyp: [],
  13950. hdlr: [],
  13951. mdat: [],
  13952. mdhd: [],
  13953. mdia: [],
  13954. mfhd: [],
  13955. minf: [],
  13956. moof: [],
  13957. moov: [],
  13958. mp4a: [],
  13959. '.mp3': [],
  13960. dac3: [],
  13961. 'ac-3': [],
  13962. mvex: [],
  13963. mvhd: [],
  13964. pasp: [],
  13965. sdtp: [],
  13966. stbl: [],
  13967. stco: [],
  13968. stsc: [],
  13969. stsd: [],
  13970. stsz: [],
  13971. stts: [],
  13972. tfdt: [],
  13973. tfhd: [],
  13974. traf: [],
  13975. trak: [],
  13976. trun: [],
  13977. trex: [],
  13978. tkhd: [],
  13979. vmhd: [],
  13980. smhd: []
  13981. };
  13982. var i;
  13983. for (i in MP4.types) {
  13984. if (MP4.types.hasOwnProperty(i)) {
  13985. MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  13986. }
  13987. }
  13988. var videoHdlr = new Uint8Array([0x00,
  13989. // version 0
  13990. 0x00, 0x00, 0x00,
  13991. // flags
  13992. 0x00, 0x00, 0x00, 0x00,
  13993. // pre_defined
  13994. 0x76, 0x69, 0x64, 0x65,
  13995. // handler_type: 'vide'
  13996. 0x00, 0x00, 0x00, 0x00,
  13997. // reserved
  13998. 0x00, 0x00, 0x00, 0x00,
  13999. // reserved
  14000. 0x00, 0x00, 0x00, 0x00,
  14001. // reserved
  14002. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  14003. ]);
  14004. var audioHdlr = new Uint8Array([0x00,
  14005. // version 0
  14006. 0x00, 0x00, 0x00,
  14007. // flags
  14008. 0x00, 0x00, 0x00, 0x00,
  14009. // pre_defined
  14010. 0x73, 0x6f, 0x75, 0x6e,
  14011. // handler_type: 'soun'
  14012. 0x00, 0x00, 0x00, 0x00,
  14013. // reserved
  14014. 0x00, 0x00, 0x00, 0x00,
  14015. // reserved
  14016. 0x00, 0x00, 0x00, 0x00,
  14017. // reserved
  14018. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  14019. ]);
  14020. MP4.HDLR_TYPES = {
  14021. video: videoHdlr,
  14022. audio: audioHdlr
  14023. };
  14024. var dref = new Uint8Array([0x00,
  14025. // version 0
  14026. 0x00, 0x00, 0x00,
  14027. // flags
  14028. 0x00, 0x00, 0x00, 0x01,
  14029. // entry_count
  14030. 0x00, 0x00, 0x00, 0x0c,
  14031. // entry_size
  14032. 0x75, 0x72, 0x6c, 0x20,
  14033. // 'url' type
  14034. 0x00,
  14035. // version 0
  14036. 0x00, 0x00, 0x01 // entry_flags
  14037. ]);
  14038. var stco = new Uint8Array([0x00,
  14039. // version
  14040. 0x00, 0x00, 0x00,
  14041. // flags
  14042. 0x00, 0x00, 0x00, 0x00 // entry_count
  14043. ]);
  14044. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  14045. MP4.STSZ = new Uint8Array([0x00,
  14046. // version
  14047. 0x00, 0x00, 0x00,
  14048. // flags
  14049. 0x00, 0x00, 0x00, 0x00,
  14050. // sample_size
  14051. 0x00, 0x00, 0x00, 0x00 // sample_count
  14052. ]);
  14053. MP4.VMHD = new Uint8Array([0x00,
  14054. // version
  14055. 0x00, 0x00, 0x01,
  14056. // flags
  14057. 0x00, 0x00,
  14058. // graphicsmode
  14059. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  14060. ]);
  14061. MP4.SMHD = new Uint8Array([0x00,
  14062. // version
  14063. 0x00, 0x00, 0x00,
  14064. // flags
  14065. 0x00, 0x00,
  14066. // balance
  14067. 0x00, 0x00 // reserved
  14068. ]);
  14069. MP4.STSD = new Uint8Array([0x00,
  14070. // version 0
  14071. 0x00, 0x00, 0x00,
  14072. // flags
  14073. 0x00, 0x00, 0x00, 0x01]); // entry_count
  14074. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  14075. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  14076. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  14077. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  14078. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  14079. };
  14080. MP4.box = function box(type) {
  14081. var size = 8;
  14082. for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  14083. payload[_key - 1] = arguments[_key];
  14084. }
  14085. var i = payload.length;
  14086. var len = i;
  14087. // calculate the total size we need to allocate
  14088. while (i--) {
  14089. size += payload[i].byteLength;
  14090. }
  14091. var result = new Uint8Array(size);
  14092. result[0] = size >> 24 & 0xff;
  14093. result[1] = size >> 16 & 0xff;
  14094. result[2] = size >> 8 & 0xff;
  14095. result[3] = size & 0xff;
  14096. result.set(type, 4);
  14097. // copy the payload into the result
  14098. for (i = 0, size = 8; i < len; i++) {
  14099. // copy payload[i] array @ offset size
  14100. result.set(payload[i], size);
  14101. size += payload[i].byteLength;
  14102. }
  14103. return result;
  14104. };
  14105. MP4.hdlr = function hdlr(type) {
  14106. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  14107. };
  14108. MP4.mdat = function mdat(data) {
  14109. return MP4.box(MP4.types.mdat, data);
  14110. };
  14111. MP4.mdhd = function mdhd(timescale, duration) {
  14112. duration *= timescale;
  14113. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14114. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14115. return MP4.box(MP4.types.mdhd, new Uint8Array([0x01,
  14116. // version 1
  14117. 0x00, 0x00, 0x00,
  14118. // flags
  14119. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14120. // creation_time
  14121. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14122. // modification_time
  14123. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14124. // timescale
  14125. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4,
  14126. // 'und' language (undetermined)
  14127. 0x00, 0x00]));
  14128. };
  14129. MP4.mdia = function mdia(track) {
  14130. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale || 0, track.duration || 0), MP4.hdlr(track.type), MP4.minf(track));
  14131. };
  14132. MP4.mfhd = function mfhd(sequenceNumber) {
  14133. return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00,
  14134. // flags
  14135. sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
  14136. ]));
  14137. };
  14138. MP4.minf = function minf(track) {
  14139. if (track.type === 'audio') {
  14140. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  14141. } else {
  14142. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  14143. }
  14144. };
  14145. MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
  14146. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  14147. };
  14148. MP4.moov = function moov(tracks) {
  14149. var i = tracks.length;
  14150. var boxes = [];
  14151. while (i--) {
  14152. boxes[i] = MP4.trak(tracks[i]);
  14153. }
  14154. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale || 0, tracks[0].duration || 0)].concat(boxes).concat(MP4.mvex(tracks)));
  14155. };
  14156. MP4.mvex = function mvex(tracks) {
  14157. var i = tracks.length;
  14158. var boxes = [];
  14159. while (i--) {
  14160. boxes[i] = MP4.trex(tracks[i]);
  14161. }
  14162. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  14163. };
  14164. MP4.mvhd = function mvhd(timescale, duration) {
  14165. duration *= timescale;
  14166. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14167. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14168. var bytes = new Uint8Array([0x01,
  14169. // version 1
  14170. 0x00, 0x00, 0x00,
  14171. // flags
  14172. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14173. // creation_time
  14174. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14175. // modification_time
  14176. timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff,
  14177. // timescale
  14178. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00,
  14179. // 1.0 rate
  14180. 0x01, 0x00,
  14181. // 1.0 volume
  14182. 0x00, 0x00,
  14183. // reserved
  14184. 0x00, 0x00, 0x00, 0x00,
  14185. // reserved
  14186. 0x00, 0x00, 0x00, 0x00,
  14187. // reserved
  14188. 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,
  14189. // transformation: unity matrix
  14190. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14191. // pre_defined
  14192. 0xff, 0xff, 0xff, 0xff // next_track_ID
  14193. ]);
  14194. return MP4.box(MP4.types.mvhd, bytes);
  14195. };
  14196. MP4.sdtp = function sdtp(track) {
  14197. var samples = track.samples || [];
  14198. var bytes = new Uint8Array(4 + samples.length);
  14199. var i;
  14200. var flags;
  14201. // leave the full box header (4 bytes) all zero
  14202. // write the sample table
  14203. for (i = 0; i < samples.length; i++) {
  14204. flags = samples[i].flags;
  14205. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  14206. }
  14207. return MP4.box(MP4.types.sdtp, bytes);
  14208. };
  14209. MP4.stbl = function stbl(track) {
  14210. return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
  14211. };
  14212. MP4.avc1 = function avc1(track) {
  14213. var sps = [];
  14214. var pps = [];
  14215. var i;
  14216. var data;
  14217. var len;
  14218. // assemble the SPSs
  14219. for (i = 0; i < track.sps.length; i++) {
  14220. data = track.sps[i];
  14221. len = data.byteLength;
  14222. sps.push(len >>> 8 & 0xff);
  14223. sps.push(len & 0xff);
  14224. // SPS
  14225. sps = sps.concat(Array.prototype.slice.call(data));
  14226. }
  14227. // assemble the PPSs
  14228. for (i = 0; i < track.pps.length; i++) {
  14229. data = track.pps[i];
  14230. len = data.byteLength;
  14231. pps.push(len >>> 8 & 0xff);
  14232. pps.push(len & 0xff);
  14233. pps = pps.concat(Array.prototype.slice.call(data));
  14234. }
  14235. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01,
  14236. // version
  14237. sps[3],
  14238. // profile
  14239. sps[4],
  14240. // profile compat
  14241. sps[5],
  14242. // level
  14243. 0xfc | 3,
  14244. // lengthSizeMinusOne, hard-coded to 4 bytes
  14245. 0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  14246. ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  14247. ]).concat(pps))); // "PPS"
  14248. var width = track.width;
  14249. var height = track.height;
  14250. var hSpacing = track.pixelRatio[0];
  14251. var vSpacing = track.pixelRatio[1];
  14252. return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00,
  14253. // reserved
  14254. 0x00, 0x00, 0x00,
  14255. // reserved
  14256. 0x00, 0x01,
  14257. // data_reference_index
  14258. 0x00, 0x00,
  14259. // pre_defined
  14260. 0x00, 0x00,
  14261. // reserved
  14262. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14263. // pre_defined
  14264. width >> 8 & 0xff, width & 0xff,
  14265. // width
  14266. height >> 8 & 0xff, height & 0xff,
  14267. // height
  14268. 0x00, 0x48, 0x00, 0x00,
  14269. // horizresolution
  14270. 0x00, 0x48, 0x00, 0x00,
  14271. // vertresolution
  14272. 0x00, 0x00, 0x00, 0x00,
  14273. // reserved
  14274. 0x00, 0x01,
  14275. // frame_count
  14276. 0x12, 0x64, 0x61, 0x69, 0x6c,
  14277. // dailymotion/hls.js
  14278. 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14279. // compressorname
  14280. 0x00, 0x18,
  14281. // depth = 24
  14282. 0x11, 0x11]),
  14283. // pre_defined = -1
  14284. avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  14285. // bufferSizeDB
  14286. 0x00, 0x2d, 0xc6, 0xc0,
  14287. // maxBitrate
  14288. 0x00, 0x2d, 0xc6, 0xc0])),
  14289. // avgBitrate
  14290. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  14291. // hSpacing
  14292. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  14293. // vSpacing
  14294. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  14295. };
  14296. MP4.esds = function esds(track) {
  14297. var config = track.config;
  14298. return new Uint8Array([0x00,
  14299. // version 0
  14300. 0x00, 0x00, 0x00,
  14301. // flags
  14302. 0x03,
  14303. // descriptor_type
  14304. 0x19,
  14305. // length
  14306. 0x00, 0x01,
  14307. // es_id
  14308. 0x00,
  14309. // stream_priority
  14310. 0x04,
  14311. // descriptor_type
  14312. 0x11,
  14313. // length
  14314. 0x40,
  14315. // codec : mpeg4_audio
  14316. 0x15,
  14317. // stream_type
  14318. 0x00, 0x00, 0x00,
  14319. // buffer_size
  14320. 0x00, 0x00, 0x00, 0x00,
  14321. // maxBitrate
  14322. 0x00, 0x00, 0x00, 0x00,
  14323. // avgBitrate
  14324. 0x05,
  14325. // descriptor_type
  14326. 0x02].concat(config, [0x06, 0x01, 0x02 // GASpecificConfig)); // length + audio config descriptor
  14327. ]));
  14328. };
  14329. MP4.audioStsd = function audioStsd(track) {
  14330. var samplerate = track.samplerate || 0;
  14331. return new Uint8Array([0x00, 0x00, 0x00,
  14332. // reserved
  14333. 0x00, 0x00, 0x00,
  14334. // reserved
  14335. 0x00, 0x01,
  14336. // data_reference_index
  14337. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14338. // reserved
  14339. 0x00, track.channelCount || 0,
  14340. // channelcount
  14341. 0x00, 0x10,
  14342. // sampleSize:16bits
  14343. 0x00, 0x00, 0x00, 0x00,
  14344. // reserved2
  14345. samplerate >> 8 & 0xff, samplerate & 0xff,
  14346. //
  14347. 0x00, 0x00]);
  14348. };
  14349. MP4.mp4a = function mp4a(track) {
  14350. return MP4.box(MP4.types.mp4a, MP4.audioStsd(track), MP4.box(MP4.types.esds, MP4.esds(track)));
  14351. };
  14352. MP4.mp3 = function mp3(track) {
  14353. return MP4.box(MP4.types['.mp3'], MP4.audioStsd(track));
  14354. };
  14355. MP4.ac3 = function ac3(track) {
  14356. return MP4.box(MP4.types['ac-3'], MP4.audioStsd(track), MP4.box(MP4.types.dac3, track.config));
  14357. };
  14358. MP4.stsd = function stsd(track) {
  14359. var segmentCodec = track.segmentCodec;
  14360. if (track.type === 'audio') {
  14361. if (segmentCodec === 'aac') {
  14362. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  14363. }
  14364. if (segmentCodec === 'ac3' && track.config) {
  14365. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.ac3(track));
  14366. }
  14367. if (segmentCodec === 'mp3' && track.codec === 'mp3') {
  14368. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  14369. }
  14370. } else {
  14371. if (track.pps && track.sps) {
  14372. if (segmentCodec === 'avc') {
  14373. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  14374. }
  14375. if (segmentCodec === 'hevc' && track.vps) {
  14376. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.hvc1(track));
  14377. }
  14378. } else {
  14379. throw new Error("video track missing pps or sps");
  14380. }
  14381. }
  14382. throw new Error("unsupported " + track.type + " segment codec (" + segmentCodec + "/" + track.codec + ")");
  14383. };
  14384. MP4.tkhd = function tkhd(track) {
  14385. var id = track.id;
  14386. var duration = (track.duration || 0) * (track.timescale || 0);
  14387. var width = track.width || 0;
  14388. var height = track.height || 0;
  14389. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  14390. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  14391. return MP4.box(MP4.types.tkhd, new Uint8Array([0x01,
  14392. // version 1
  14393. 0x00, 0x00, 0x07,
  14394. // flags
  14395. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  14396. // creation_time
  14397. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  14398. // modification_time
  14399. id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14400. // track_ID
  14401. 0x00, 0x00, 0x00, 0x00,
  14402. // reserved
  14403. upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14404. // reserved
  14405. 0x00, 0x00,
  14406. // layer
  14407. 0x00, 0x00,
  14408. // alternate_group
  14409. 0x00, 0x00,
  14410. // non-audio track volume
  14411. 0x00, 0x00,
  14412. // reserved
  14413. 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,
  14414. // transformation: unity matrix
  14415. width >> 8 & 0xff, width & 0xff, 0x00, 0x00,
  14416. // width
  14417. height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
  14418. ]));
  14419. };
  14420. MP4.traf = function traf(track, baseMediaDecodeTime) {
  14421. var sampleDependencyTable = MP4.sdtp(track);
  14422. var id = track.id;
  14423. var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  14424. var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  14425. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00,
  14426. // version 0
  14427. 0x00, 0x00, 0x00,
  14428. // flags
  14429. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
  14430. ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01,
  14431. // version 1
  14432. 0x00, 0x00, 0x00,
  14433. // flags
  14434. upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 +
  14435. // tfhd
  14436. 20 +
  14437. // tfdt
  14438. 8 +
  14439. // traf header
  14440. 16 +
  14441. // mfhd
  14442. 8 +
  14443. // moof header
  14444. 8),
  14445. // mdat header
  14446. sampleDependencyTable);
  14447. }
  14448. /**
  14449. * Generate a track box.
  14450. * @param track a track definition
  14451. */;
  14452. MP4.trak = function trak(track) {
  14453. track.duration = track.duration || 0xffffffff;
  14454. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  14455. };
  14456. MP4.trex = function trex(track) {
  14457. var id = track.id;
  14458. return MP4.box(MP4.types.trex, new Uint8Array([0x00,
  14459. // version 0
  14460. 0x00, 0x00, 0x00,
  14461. // flags
  14462. id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff,
  14463. // track_ID
  14464. 0x00, 0x00, 0x00, 0x01,
  14465. // default_sample_description_index
  14466. 0x00, 0x00, 0x00, 0x00,
  14467. // default_sample_duration
  14468. 0x00, 0x00, 0x00, 0x00,
  14469. // default_sample_size
  14470. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  14471. ]));
  14472. };
  14473. MP4.trun = function trun(track, offset) {
  14474. var samples = track.samples || [];
  14475. var len = samples.length;
  14476. var arraylen = 12 + 16 * len;
  14477. var array = new Uint8Array(arraylen);
  14478. var i;
  14479. var sample;
  14480. var duration;
  14481. var size;
  14482. var flags;
  14483. var cts;
  14484. offset += 8 + arraylen;
  14485. array.set([track.type === 'video' ? 0x01 : 0x00,
  14486. // version 1 for video with signed-int sample_composition_time_offset
  14487. 0x00, 0x0f, 0x01,
  14488. // flags
  14489. len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff,
  14490. // sample_count
  14491. offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
  14492. ], 0);
  14493. for (i = 0; i < len; i++) {
  14494. sample = samples[i];
  14495. duration = sample.duration;
  14496. size = sample.size;
  14497. flags = sample.flags;
  14498. cts = sample.cts;
  14499. array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff,
  14500. // sample_duration
  14501. size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff,
  14502. // sample_size
  14503. flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f,
  14504. // sample_flags
  14505. cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
  14506. ], 12 + 16 * i);
  14507. }
  14508. return MP4.box(MP4.types.trun, array);
  14509. };
  14510. MP4.initSegment = function initSegment(tracks) {
  14511. if (!MP4.types) {
  14512. MP4.init();
  14513. }
  14514. var movie = MP4.moov(tracks);
  14515. var result = appendUint8Array(MP4.FTYP, movie);
  14516. return result;
  14517. };
  14518. MP4.hvc1 = function hvc1(track) {
  14519. var ps = track.params;
  14520. var units = [track.vps, track.sps, track.pps];
  14521. var NALuLengthSize = 4;
  14522. var config = new Uint8Array([0x01, ps.general_profile_space << 6 | (ps.general_tier_flag ? 32 : 0) | ps.general_profile_idc, ps.general_profile_compatibility_flags[0], ps.general_profile_compatibility_flags[1], ps.general_profile_compatibility_flags[2], ps.general_profile_compatibility_flags[3], ps.general_constraint_indicator_flags[0], ps.general_constraint_indicator_flags[1], ps.general_constraint_indicator_flags[2], ps.general_constraint_indicator_flags[3], ps.general_constraint_indicator_flags[4], ps.general_constraint_indicator_flags[5], ps.general_level_idc, 240 | ps.min_spatial_segmentation_idc >> 8, 255 & ps.min_spatial_segmentation_idc, 252 | ps.parallelismType, 252 | ps.chroma_format_idc, 248 | ps.bit_depth_luma_minus8, 248 | ps.bit_depth_chroma_minus8, 0x00, parseInt(ps.frame_rate.fps), NALuLengthSize - 1 | ps.temporal_id_nested << 2 | ps.num_temporal_layers << 3 | (ps.frame_rate.fixed ? 64 : 0), units.length]);
  14523. // compute hvcC size in bytes
  14524. var length = config.length;
  14525. for (var i = 0; i < units.length; i += 1) {
  14526. length += 3;
  14527. for (var j = 0; j < units[i].length; j += 1) {
  14528. length += 2 + units[i][j].length;
  14529. }
  14530. }
  14531. var hvcC = new Uint8Array(length);
  14532. hvcC.set(config, 0);
  14533. length = config.length;
  14534. // append parameter set units: one vps, one or more sps and pps
  14535. var iMax = units.length - 1;
  14536. for (var _i = 0; _i < units.length; _i += 1) {
  14537. hvcC.set(new Uint8Array([32 + _i | (_i === iMax ? 128 : 0), 0x00, units[_i].length]), length);
  14538. length += 3;
  14539. for (var _j = 0; _j < units[_i].length; _j += 1) {
  14540. hvcC.set(new Uint8Array([units[_i][_j].length >> 8, units[_i][_j].length & 255]), length);
  14541. length += 2;
  14542. hvcC.set(units[_i][_j], length);
  14543. length += units[_i][_j].length;
  14544. }
  14545. }
  14546. var hvcc = MP4.box(MP4.types.hvcC, hvcC);
  14547. var width = track.width;
  14548. var height = track.height;
  14549. var hSpacing = track.pixelRatio[0];
  14550. var vSpacing = track.pixelRatio[1];
  14551. return MP4.box(MP4.types.hvc1, new Uint8Array([0x00, 0x00, 0x00,
  14552. // reserved
  14553. 0x00, 0x00, 0x00,
  14554. // reserved
  14555. 0x00, 0x01,
  14556. // data_reference_index
  14557. 0x00, 0x00,
  14558. // pre_defined
  14559. 0x00, 0x00,
  14560. // reserved
  14561. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14562. // pre_defined
  14563. width >> 8 & 0xff, width & 0xff,
  14564. // width
  14565. height >> 8 & 0xff, height & 0xff,
  14566. // height
  14567. 0x00, 0x48, 0x00, 0x00,
  14568. // horizresolution
  14569. 0x00, 0x48, 0x00, 0x00,
  14570. // vertresolution
  14571. 0x00, 0x00, 0x00, 0x00,
  14572. // reserved
  14573. 0x00, 0x01,
  14574. // frame_count
  14575. 0x12, 0x64, 0x61, 0x69, 0x6c,
  14576. // dailymotion/hls.js
  14577. 0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  14578. // compressorname
  14579. 0x00, 0x18,
  14580. // depth = 24
  14581. 0x11, 0x11]),
  14582. // pre_defined = -1
  14583. hvcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80,
  14584. // bufferSizeDB
  14585. 0x00, 0x2d, 0xc6, 0xc0,
  14586. // maxBitrate
  14587. 0x00, 0x2d, 0xc6, 0xc0])),
  14588. // avgBitrate
  14589. MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24,
  14590. // hSpacing
  14591. hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24,
  14592. // vSpacing
  14593. vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
  14594. };
  14595. return MP4;
  14596. }();
  14597. MP4.types = void 0;
  14598. MP4.HDLR_TYPES = void 0;
  14599. MP4.STTS = void 0;
  14600. MP4.STSC = void 0;
  14601. MP4.STCO = void 0;
  14602. MP4.STSZ = void 0;
  14603. MP4.VMHD = void 0;
  14604. MP4.SMHD = void 0;
  14605. MP4.STSD = void 0;
  14606. MP4.FTYP = void 0;
  14607. MP4.DINF = void 0;
  14608. var MPEG_TS_CLOCK_FREQ_HZ = 90000;
  14609. function toTimescaleFromBase(baseTime, destScale, srcBase, round) {
  14610. if (srcBase === void 0) {
  14611. srcBase = 1;
  14612. }
  14613. if (round === void 0) {
  14614. round = false;
  14615. }
  14616. var result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
  14617. return round ? Math.round(result) : result;
  14618. }
  14619. function toTimescaleFromScale(baseTime, destScale, srcScale, round) {
  14620. if (srcScale === void 0) {
  14621. srcScale = 1;
  14622. }
  14623. if (round === void 0) {
  14624. round = false;
  14625. }
  14626. return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);
  14627. }
  14628. function toMsFromMpegTsClock(baseTime, round) {
  14629. return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
  14630. }
  14631. function toMpegTsClockFromTimescale(baseTime, srcScale) {
  14632. if (srcScale === void 0) {
  14633. srcScale = 1;
  14634. }
  14635. return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
  14636. }
  14637. var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
  14638. var AAC_SAMPLES_PER_FRAME = 1024;
  14639. var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
  14640. var AC3_SAMPLES_PER_FRAME = 1536;
  14641. var chromeVersion = null;
  14642. var safariWebkitVersion = null;
  14643. function createMp4Sample(isKeyframe, duration, size, cts) {
  14644. return {
  14645. duration: duration,
  14646. size: size,
  14647. cts: cts,
  14648. flags: {
  14649. isLeading: 0,
  14650. isDependedOn: 0,
  14651. hasRedundancy: 0,
  14652. degradPrio: 0,
  14653. dependsOn: isKeyframe ? 2 : 1,
  14654. isNonSync: isKeyframe ? 0 : 1
  14655. }
  14656. };
  14657. }
  14658. var MP4Remuxer = /*#__PURE__*/function (_Logger) {
  14659. function MP4Remuxer(observer, config, typeSupported, logger) {
  14660. var _this;
  14661. _this = _Logger.call(this, 'mp4-remuxer', logger) || this;
  14662. _this.observer = void 0;
  14663. _this.config = void 0;
  14664. _this.typeSupported = void 0;
  14665. _this.ISGenerated = false;
  14666. _this._initPTS = null;
  14667. _this._initDTS = null;
  14668. _this.nextVideoTs = null;
  14669. _this.nextAudioTs = null;
  14670. _this.videoSampleDuration = null;
  14671. _this.isAudioContiguous = false;
  14672. _this.isVideoContiguous = false;
  14673. _this.videoTrackConfig = void 0;
  14674. _this.observer = observer;
  14675. _this.config = config;
  14676. _this.typeSupported = typeSupported;
  14677. _this.ISGenerated = false;
  14678. if (chromeVersion === null) {
  14679. var userAgent = navigator.userAgent || '';
  14680. var result = userAgent.match(/Chrome\/(\d+)/i);
  14681. chromeVersion = result ? parseInt(result[1]) : 0;
  14682. }
  14683. if (safariWebkitVersion === null) {
  14684. var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
  14685. safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
  14686. }
  14687. return _this;
  14688. }
  14689. _inheritsLoose(MP4Remuxer, _Logger);
  14690. var _proto = MP4Remuxer.prototype;
  14691. _proto.destroy = function destroy() {
  14692. // @ts-ignore
  14693. this.config = this.videoTrackConfig = this._initPTS = this._initDTS = null;
  14694. };
  14695. _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
  14696. this.log('initPTS & initDTS reset');
  14697. this._initPTS = this._initDTS = defaultTimeStamp;
  14698. };
  14699. _proto.resetNextTimestamp = function resetNextTimestamp() {
  14700. this.log('reset next timestamp');
  14701. this.isVideoContiguous = false;
  14702. this.isAudioContiguous = false;
  14703. };
  14704. _proto.resetInitSegment = function resetInitSegment() {
  14705. this.log('ISGenerated flag reset');
  14706. this.ISGenerated = false;
  14707. this.videoTrackConfig = undefined;
  14708. };
  14709. _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
  14710. // Get the minimum PTS value relative to the first sample's PTS, normalized for 33-bit wrapping
  14711. var rolloverDetected = false;
  14712. var firstPts = videoSamples[0].pts;
  14713. var startPTS = videoSamples.reduce(function (minPTS, sample) {
  14714. var pts = sample.pts;
  14715. var delta = pts - minPTS;
  14716. if (delta < -4294967296) {
  14717. // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
  14718. rolloverDetected = true;
  14719. pts = normalizePts(pts, firstPts);
  14720. delta = pts - minPTS;
  14721. }
  14722. if (delta > 0) {
  14723. return minPTS;
  14724. }
  14725. return pts;
  14726. }, firstPts);
  14727. if (rolloverDetected) {
  14728. this.debug('PTS rollover detected');
  14729. }
  14730. return startPTS;
  14731. };
  14732. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
  14733. var video;
  14734. var audio;
  14735. var initSegment;
  14736. var text;
  14737. var id3;
  14738. var independent;
  14739. var audioTimeOffset = timeOffset;
  14740. var videoTimeOffset = timeOffset;
  14741. // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
  14742. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
  14743. // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
  14744. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
  14745. // then we can remux one track without waiting for the other.
  14746. var hasAudio = audioTrack.pid > -1;
  14747. var hasVideo = videoTrack.pid > -1;
  14748. var length = videoTrack.samples.length;
  14749. var enoughAudioSamples = audioTrack.samples.length > 0;
  14750. var enoughVideoSamples = flush && length > 0 || length > 1;
  14751. var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
  14752. if (canRemuxAvc) {
  14753. if (this.ISGenerated) {
  14754. var _videoTrack$pixelRati, _config$pixelRatio, _videoTrack$pixelRati2, _config$pixelRatio2;
  14755. var config = this.videoTrackConfig;
  14756. if (config && (videoTrack.width !== config.width || videoTrack.height !== config.height || ((_videoTrack$pixelRati = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati[0]) !== ((_config$pixelRatio = config.pixelRatio) == null ? void 0 : _config$pixelRatio[0]) || ((_videoTrack$pixelRati2 = videoTrack.pixelRatio) == null ? void 0 : _videoTrack$pixelRati2[1]) !== ((_config$pixelRatio2 = config.pixelRatio) == null ? void 0 : _config$pixelRatio2[1])) || !config && enoughVideoSamples || this.nextAudioTs === null && enoughAudioSamples) {
  14757. this.resetInitSegment();
  14758. }
  14759. }
  14760. if (!this.ISGenerated) {
  14761. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14762. }
  14763. var isVideoContiguous = this.isVideoContiguous;
  14764. var firstKeyFrameIndex = -1;
  14765. var firstKeyFramePTS;
  14766. if (enoughVideoSamples) {
  14767. firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
  14768. if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
  14769. independent = true;
  14770. if (firstKeyFrameIndex > 0) {
  14771. this.warn("Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
  14772. var startPTS = this.getVideoStartPts(videoTrack.samples);
  14773. videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
  14774. videoTrack.dropped += firstKeyFrameIndex;
  14775. videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / videoTrack.inputTimeScale;
  14776. firstKeyFramePTS = videoTimeOffset;
  14777. } else if (firstKeyFrameIndex === -1) {
  14778. this.warn("No keyframe found out of " + length + " video samples");
  14779. independent = false;
  14780. }
  14781. }
  14782. }
  14783. if (this.ISGenerated) {
  14784. if (enoughAudioSamples && enoughVideoSamples) {
  14785. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  14786. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  14787. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  14788. // drift between audio and video streams
  14789. var _startPTS = this.getVideoStartPts(videoTrack.samples);
  14790. var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
  14791. var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
  14792. audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
  14793. videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
  14794. }
  14795. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
  14796. if (enoughAudioSamples) {
  14797. // if initSegment was generated without audio samples, regenerate it again
  14798. if (!audioTrack.samplerate) {
  14799. this.warn('regenerate InitSegment as audio detected');
  14800. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14801. }
  14802. audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined);
  14803. if (enoughVideoSamples) {
  14804. var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;
  14805. // if initSegment was generated without video samples, regenerate it again
  14806. if (!videoTrack.inputTimeScale) {
  14807. this.warn('regenerate InitSegment as video detected');
  14808. initSegment = this.generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset);
  14809. }
  14810. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
  14811. }
  14812. } else if (enoughVideoSamples) {
  14813. video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
  14814. }
  14815. if (video) {
  14816. video.firstKeyFrame = firstKeyFrameIndex;
  14817. video.independent = firstKeyFrameIndex !== -1;
  14818. video.firstKeyFramePTS = firstKeyFramePTS;
  14819. }
  14820. }
  14821. }
  14822. // Allow ID3 and text to remux, even if more audio/video samples are required
  14823. if (this.ISGenerated && this._initPTS && this._initDTS) {
  14824. if (id3Track.samples.length) {
  14825. id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, this._initPTS, this._initDTS);
  14826. }
  14827. if (textTrack.samples.length) {
  14828. text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, this._initPTS);
  14829. }
  14830. }
  14831. return {
  14832. audio: audio,
  14833. video: video,
  14834. initSegment: initSegment,
  14835. independent: independent,
  14836. text: text,
  14837. id3: id3
  14838. };
  14839. };
  14840. _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset, accurateTimeOffset) {
  14841. var audioSamples = audioTrack.samples;
  14842. var videoSamples = videoTrack.samples;
  14843. var typeSupported = this.typeSupported;
  14844. var tracks = {};
  14845. var _initPTS = this._initPTS;
  14846. var computePTSDTS = !_initPTS || accurateTimeOffset;
  14847. var container = 'audio/mp4';
  14848. var initPTS;
  14849. var initDTS;
  14850. var timescale;
  14851. var trackId;
  14852. if (computePTSDTS) {
  14853. initPTS = initDTS = Infinity;
  14854. }
  14855. if (audioTrack.config && audioSamples.length) {
  14856. // let's use audio sampling rate as MP4 time scale.
  14857. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  14858. // using audio sampling rate here helps having an integer MP4 frame duration
  14859. // this avoids potential rounding issue and AV sync issue
  14860. audioTrack.timescale = audioTrack.samplerate;
  14861. switch (audioTrack.segmentCodec) {
  14862. case 'mp3':
  14863. if (typeSupported.mpeg) {
  14864. // Chrome and Safari
  14865. container = 'audio/mpeg';
  14866. audioTrack.codec = '';
  14867. } else if (typeSupported.mp3) {
  14868. // Firefox
  14869. audioTrack.codec = 'mp3';
  14870. }
  14871. break;
  14872. case 'ac3':
  14873. audioTrack.codec = 'ac-3';
  14874. break;
  14875. }
  14876. tracks.audio = {
  14877. id: 'audio',
  14878. container: container,
  14879. codec: audioTrack.codec,
  14880. initSegment: audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]),
  14881. metadata: {
  14882. channelCount: audioTrack.channelCount
  14883. }
  14884. };
  14885. if (computePTSDTS) {
  14886. trackId = audioTrack.id;
  14887. timescale = audioTrack.inputTimeScale;
  14888. if (!_initPTS || timescale !== _initPTS.timescale) {
  14889. // remember first PTS of this demuxing context. for audio, PTS = DTS
  14890. initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
  14891. } else {
  14892. computePTSDTS = false;
  14893. }
  14894. }
  14895. }
  14896. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  14897. // let's use input time scale as MP4 video timescale
  14898. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  14899. videoTrack.timescale = videoTrack.inputTimeScale;
  14900. tracks.video = {
  14901. id: 'main',
  14902. container: 'video/mp4',
  14903. codec: videoTrack.codec,
  14904. initSegment: MP4.initSegment([videoTrack]),
  14905. metadata: {
  14906. width: videoTrack.width,
  14907. height: videoTrack.height
  14908. }
  14909. };
  14910. if (computePTSDTS) {
  14911. trackId = videoTrack.id;
  14912. timescale = videoTrack.inputTimeScale;
  14913. if (!_initPTS || timescale !== _initPTS.timescale) {
  14914. var startPTS = this.getVideoStartPts(videoSamples);
  14915. var startOffset = Math.round(timescale * timeOffset);
  14916. initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
  14917. initPTS = Math.min(initPTS, startPTS - startOffset);
  14918. } else {
  14919. computePTSDTS = false;
  14920. }
  14921. }
  14922. this.videoTrackConfig = {
  14923. width: videoTrack.width,
  14924. height: videoTrack.height,
  14925. pixelRatio: videoTrack.pixelRatio
  14926. };
  14927. }
  14928. if (Object.keys(tracks).length) {
  14929. this.ISGenerated = true;
  14930. if (computePTSDTS) {
  14931. this._initPTS = {
  14932. baseTime: initPTS,
  14933. timescale: timescale
  14934. };
  14935. this._initDTS = {
  14936. baseTime: initDTS,
  14937. timescale: timescale
  14938. };
  14939. } else {
  14940. initPTS = timescale = undefined;
  14941. }
  14942. return {
  14943. tracks: tracks,
  14944. initPTS: initPTS,
  14945. timescale: timescale,
  14946. trackId: trackId
  14947. };
  14948. }
  14949. };
  14950. _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  14951. var timeScale = track.inputTimeScale;
  14952. var inputSamples = track.samples;
  14953. var outputSamples = [];
  14954. var nbSamples = inputSamples.length;
  14955. var initPTS = this._initPTS;
  14956. var initTime = initPTS.baseTime * timeScale / initPTS.timescale;
  14957. var nextVideoTs = this.nextVideoTs;
  14958. var offset = 8;
  14959. var mp4SampleDuration = this.videoSampleDuration;
  14960. var firstDTS;
  14961. var lastDTS;
  14962. var minPTS = Number.POSITIVE_INFINITY;
  14963. var maxPTS = Number.NEGATIVE_INFINITY;
  14964. var sortSamples = false;
  14965. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  14966. if (!contiguous || nextVideoTs === null) {
  14967. var pts = initTime + timeOffset * timeScale;
  14968. var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts);
  14969. if (chromeVersion && nextVideoTs !== null && Math.abs(pts - cts - (nextVideoTs + initTime)) < 15000) {
  14970. // treat as contigous to adjust samples that would otherwise produce video buffer gaps in Chrome
  14971. contiguous = true;
  14972. } else {
  14973. // if not contiguous, let's use target timeOffset
  14974. nextVideoTs = pts - cts - initTime;
  14975. }
  14976. }
  14977. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  14978. // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  14979. var nextVideoPts = nextVideoTs + initTime;
  14980. for (var i = 0; i < nbSamples; i++) {
  14981. var sample = inputSamples[i];
  14982. sample.pts = normalizePts(sample.pts, nextVideoPts);
  14983. sample.dts = normalizePts(sample.dts, nextVideoPts);
  14984. if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
  14985. sortSamples = true;
  14986. }
  14987. }
  14988. // sort video samples by DTS then PTS then demux id order
  14989. if (sortSamples) {
  14990. inputSamples.sort(function (a, b) {
  14991. var deltadts = a.dts - b.dts;
  14992. var deltapts = a.pts - b.pts;
  14993. return deltadts || deltapts;
  14994. });
  14995. }
  14996. // Get first/last DTS
  14997. firstDTS = inputSamples[0].dts;
  14998. lastDTS = inputSamples[inputSamples.length - 1].dts;
  14999. // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  15000. // set this constant duration as being the avg delta between consecutive DTS.
  15001. var inputDuration = lastDTS - firstDTS;
  15002. var averageSampleDuration = inputDuration ? Math.round(inputDuration / (nbSamples - 1)) : mp4SampleDuration || track.inputTimeScale / 30;
  15003. // if fragment are contiguous, detect hole/overlapping between fragments
  15004. if (contiguous) {
  15005. // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
  15006. var delta = firstDTS - nextVideoPts;
  15007. var foundHole = delta > averageSampleDuration;
  15008. var foundOverlap = delta < -1;
  15009. if (foundHole || foundOverlap) {
  15010. if (foundHole) {
  15011. this.warn((track.segmentCodec || '').toUpperCase() + ": " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected at " + timeOffset.toFixed(3));
  15012. } else {
  15013. this.warn((track.segmentCodec || '').toUpperCase() + ": " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected at " + timeOffset.toFixed(3));
  15014. }
  15015. if (!foundOverlap || nextVideoPts >= inputSamples[0].pts || chromeVersion) {
  15016. firstDTS = nextVideoPts;
  15017. var firstPTS = inputSamples[0].pts - delta;
  15018. if (foundHole) {
  15019. inputSamples[0].dts = firstDTS;
  15020. inputSamples[0].pts = firstPTS;
  15021. } else {
  15022. var isPTSOrderRetained = true;
  15023. for (var _i = 0; _i < inputSamples.length; _i++) {
  15024. if (inputSamples[_i].dts > firstPTS && isPTSOrderRetained) {
  15025. break;
  15026. }
  15027. var prevPTS = inputSamples[_i].pts;
  15028. inputSamples[_i].dts -= delta;
  15029. inputSamples[_i].pts -= delta;
  15030. // check to see if this sample's PTS order has changed
  15031. // relative to the next one
  15032. if (_i < inputSamples.length - 1) {
  15033. var nextSamplePTS = inputSamples[_i + 1].pts;
  15034. var currentSamplePTS = inputSamples[_i].pts;
  15035. var currentOrder = nextSamplePTS <= currentSamplePTS;
  15036. var prevOrder = nextSamplePTS <= prevPTS;
  15037. isPTSOrderRetained = currentOrder == prevOrder;
  15038. }
  15039. }
  15040. }
  15041. this.log("Video: Initial PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
  15042. }
  15043. }
  15044. }
  15045. firstDTS = Math.max(0, firstDTS);
  15046. var nbNalu = 0;
  15047. var naluLen = 0;
  15048. var dtsStep = firstDTS;
  15049. for (var _i2 = 0; _i2 < nbSamples; _i2++) {
  15050. // compute total/avc sample length and nb of NAL units
  15051. var _sample = inputSamples[_i2];
  15052. var units = _sample.units;
  15053. var nbUnits = units.length;
  15054. var sampleLen = 0;
  15055. for (var j = 0; j < nbUnits; j++) {
  15056. sampleLen += units[j].data.length;
  15057. }
  15058. naluLen += sampleLen;
  15059. nbNalu += nbUnits;
  15060. _sample.length = sampleLen;
  15061. // ensure sample monotonic DTS
  15062. if (_sample.dts < dtsStep) {
  15063. _sample.dts = dtsStep;
  15064. dtsStep += averageSampleDuration / 4 | 0 || 1;
  15065. } else {
  15066. dtsStep = _sample.dts;
  15067. }
  15068. minPTS = Math.min(_sample.pts, minPTS);
  15069. maxPTS = Math.max(_sample.pts, maxPTS);
  15070. }
  15071. lastDTS = inputSamples[nbSamples - 1].dts;
  15072. /* concatenate the video data and construct the mdat in place
  15073. (need 8 more bytes to fill length and mpdat type) */
  15074. var mdatSize = naluLen + 4 * nbNalu + 8;
  15075. var mdat;
  15076. try {
  15077. mdat = new Uint8Array(mdatSize);
  15078. } catch (err) {
  15079. this.observer.emit(Events.ERROR, Events.ERROR, {
  15080. type: ErrorTypes.MUX_ERROR,
  15081. details: ErrorDetails.REMUX_ALLOC_ERROR,
  15082. fatal: false,
  15083. error: err,
  15084. bytes: mdatSize,
  15085. reason: "fail allocating video mdat " + mdatSize
  15086. });
  15087. return;
  15088. }
  15089. var view = new DataView(mdat.buffer);
  15090. view.setUint32(0, mdatSize);
  15091. mdat.set(MP4.types.mdat, 4);
  15092. var stretchedLastFrame = false;
  15093. var minDtsDelta = Number.POSITIVE_INFINITY;
  15094. var minPtsDelta = Number.POSITIVE_INFINITY;
  15095. var maxDtsDelta = Number.NEGATIVE_INFINITY;
  15096. var maxPtsDelta = Number.NEGATIVE_INFINITY;
  15097. for (var _i3 = 0; _i3 < nbSamples; _i3++) {
  15098. var VideoSample = inputSamples[_i3];
  15099. var VideoSampleUnits = VideoSample.units;
  15100. var mp4SampleLength = 0;
  15101. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  15102. for (var _j = 0, _nbUnits = VideoSampleUnits.length; _j < _nbUnits; _j++) {
  15103. var unit = VideoSampleUnits[_j];
  15104. var unitData = unit.data;
  15105. var unitDataLen = unit.data.byteLength;
  15106. view.setUint32(offset, unitDataLen);
  15107. offset += 4;
  15108. mdat.set(unitData, offset);
  15109. offset += unitDataLen;
  15110. mp4SampleLength += 4 + unitDataLen;
  15111. }
  15112. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  15113. var ptsDelta = void 0;
  15114. if (_i3 < nbSamples - 1) {
  15115. mp4SampleDuration = inputSamples[_i3 + 1].dts - VideoSample.dts;
  15116. ptsDelta = inputSamples[_i3 + 1].pts - VideoSample.pts;
  15117. } else {
  15118. var config = this.config;
  15119. var lastFrameDuration = _i3 > 0 ? VideoSample.dts - inputSamples[_i3 - 1].dts : averageSampleDuration;
  15120. ptsDelta = _i3 > 0 ? VideoSample.pts - inputSamples[_i3 - 1].pts : averageSampleDuration;
  15121. if (config.stretchShortVideoTrack && this.nextAudioTs !== null) {
  15122. // In some cases, a segment's audio track duration may exceed the video track duration.
  15123. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  15124. // see if the delta to the next segment is longer than maxBufferHole.
  15125. // If so, playback would potentially get stuck, so we artificially inflate
  15126. // the duration of the last frame to minimize any potential gap between segments.
  15127. var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
  15128. var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioTs + initTime) - VideoSample.pts;
  15129. if (deltaToFrameEnd > gapTolerance) {
  15130. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  15131. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  15132. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  15133. if (mp4SampleDuration < 0) {
  15134. mp4SampleDuration = lastFrameDuration;
  15135. } else {
  15136. stretchedLastFrame = true;
  15137. }
  15138. this.log("It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  15139. } else {
  15140. mp4SampleDuration = lastFrameDuration;
  15141. }
  15142. } else {
  15143. mp4SampleDuration = lastFrameDuration;
  15144. }
  15145. }
  15146. var compositionTimeOffset = Math.round(VideoSample.pts - VideoSample.dts);
  15147. minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);
  15148. maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);
  15149. minPtsDelta = Math.min(minPtsDelta, ptsDelta);
  15150. maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);
  15151. outputSamples.push(createMp4Sample(VideoSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
  15152. }
  15153. if (outputSamples.length) {
  15154. if (chromeVersion) {
  15155. if (chromeVersion < 70) {
  15156. // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
  15157. // https://code.google.com/p/chromium/issues/detail?id=229412
  15158. var flags = outputSamples[0].flags;
  15159. flags.dependsOn = 2;
  15160. flags.isNonSync = 0;
  15161. }
  15162. } else if (safariWebkitVersion) {
  15163. // Fix for "CNN special report, with CC" in test-streams (Safari browser only)
  15164. // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.
  15165. if (maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta && averageSampleDuration / maxDtsDelta < 0.025 && outputSamples[0].cts === 0) {
  15166. this.warn('Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.');
  15167. var dts = firstDTS;
  15168. for (var _i4 = 0, len = outputSamples.length; _i4 < len; _i4++) {
  15169. var nextDts = dts + outputSamples[_i4].duration;
  15170. var _pts = dts + outputSamples[_i4].cts;
  15171. if (_i4 < len - 1) {
  15172. var nextPts = nextDts + outputSamples[_i4 + 1].cts;
  15173. outputSamples[_i4].duration = nextPts - _pts;
  15174. } else {
  15175. outputSamples[_i4].duration = _i4 ? outputSamples[_i4 - 1].duration : averageSampleDuration;
  15176. }
  15177. outputSamples[_i4].cts = 0;
  15178. dts = nextDts;
  15179. }
  15180. }
  15181. }
  15182. }
  15183. // next AVC/HEVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  15184. mp4SampleDuration = stretchedLastFrame || !mp4SampleDuration ? averageSampleDuration : mp4SampleDuration;
  15185. var endDTS = lastDTS + mp4SampleDuration;
  15186. this.nextVideoTs = nextVideoTs = endDTS - initTime;
  15187. this.videoSampleDuration = mp4SampleDuration;
  15188. this.isVideoContiguous = true;
  15189. var moof = MP4.moof(track.sequenceNumber++, firstDTS, _extends(track, {
  15190. samples: outputSamples
  15191. }));
  15192. var type = 'video';
  15193. var data = {
  15194. data1: moof,
  15195. data2: mdat,
  15196. startPTS: (minPTS - initTime) / timeScale,
  15197. endPTS: (maxPTS + mp4SampleDuration - initTime) / timeScale,
  15198. startDTS: (firstDTS - initTime) / timeScale,
  15199. endDTS: nextVideoTs / timeScale,
  15200. type: type,
  15201. hasAudio: false,
  15202. hasVideo: true,
  15203. nb: outputSamples.length,
  15204. dropped: track.dropped
  15205. };
  15206. track.samples = [];
  15207. track.dropped = 0;
  15208. return data;
  15209. };
  15210. _proto.getSamplesPerFrame = function getSamplesPerFrame(track) {
  15211. switch (track.segmentCodec) {
  15212. case 'mp3':
  15213. return MPEG_AUDIO_SAMPLE_PER_FRAME;
  15214. case 'ac3':
  15215. return AC3_SAMPLES_PER_FRAME;
  15216. default:
  15217. return AAC_SAMPLES_PER_FRAME;
  15218. }
  15219. };
  15220. _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
  15221. var inputTimeScale = track.inputTimeScale;
  15222. var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
  15223. var scaleFactor = inputTimeScale / mp4timeScale;
  15224. var mp4SampleDuration = this.getSamplesPerFrame(track);
  15225. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  15226. var initPTS = this._initPTS;
  15227. var rawMPEG = track.segmentCodec === 'mp3' && this.typeSupported.mpeg;
  15228. var outputSamples = [];
  15229. var alignedWithVideo = videoTimeOffset !== undefined;
  15230. var inputSamples = track.samples;
  15231. var offset = rawMPEG ? 0 : 8;
  15232. var nextAudioTs = this.nextAudioTs || -1;
  15233. // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
  15234. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  15235. // for sake of clarity:
  15236. // consecutive fragments are frags with
  15237. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  15238. // - less than 20 audio frames distance
  15239. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  15240. // this helps ensuring audio continuity
  15241. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  15242. var initTime = initPTS.baseTime * inputTimeScale / initPTS.timescale;
  15243. var timeOffsetMpegTS = initTime + timeOffset * inputTimeScale;
  15244. this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioTs > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - (nextAudioTs + initTime)) < 9000 || Math.abs(normalizePts(inputSamples[0].pts, timeOffsetMpegTS) - (nextAudioTs + initTime)) < 20 * inputSampleDuration);
  15245. // compute normalized PTS
  15246. inputSamples.forEach(function (sample) {
  15247. sample.pts = normalizePts(sample.pts, timeOffsetMpegTS);
  15248. });
  15249. if (!contiguous || nextAudioTs < 0) {
  15250. // filter out sample with negative PTS that are not playable anyway
  15251. // if we don't remove these negative samples, they will shift all audio samples forward.
  15252. // leading to audio overlap between current / next fragment
  15253. inputSamples = inputSamples.filter(function (sample) {
  15254. return sample.pts >= 0;
  15255. });
  15256. // in case all samples have negative PTS, and have been filtered out, return now
  15257. if (!inputSamples.length) {
  15258. return;
  15259. }
  15260. if (videoTimeOffset === 0) {
  15261. // Set the start to match video so that start gaps larger than inputSampleDuration are filled with silence
  15262. nextAudioTs = 0;
  15263. } else if (accurateTimeOffset && !alignedWithVideo) {
  15264. // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
  15265. nextAudioTs = Math.max(0, timeOffsetMpegTS - initTime);
  15266. } else {
  15267. // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  15268. nextAudioTs = inputSamples[0].pts - initTime;
  15269. }
  15270. }
  15271. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  15272. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  15273. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  15274. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  15275. // frame.
  15276. if (track.segmentCodec === 'aac') {
  15277. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  15278. for (var i = 0, nextPts = nextAudioTs + initTime; i < inputSamples.length; i++) {
  15279. // First, let's see how far off this frame is from where we expect it to be
  15280. var sample = inputSamples[i];
  15281. var pts = sample.pts;
  15282. var delta = pts - nextPts;
  15283. var duration = Math.abs(1000 * delta / inputTimeScale);
  15284. // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
  15285. if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
  15286. if (i === 0) {
  15287. this.warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps marker by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
  15288. this.nextAudioTs = nextAudioTs = pts - initTime;
  15289. nextPts = pts;
  15290. }
  15291. } // eslint-disable-line brace-style
  15292. // Insert missing frames if:
  15293. // 1: We're more than maxAudioFramesDrift frame away
  15294. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  15295. // 3: currentTime (aka nextPtsNorm) is not 0
  15296. // 4: remuxing with video (videoTimeOffset !== undefined)
  15297. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
  15298. var missing = Math.round(delta / inputSampleDuration);
  15299. // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
  15300. // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
  15301. nextPts = pts - missing * inputSampleDuration;
  15302. while (nextPts < 0 && missing && inputSampleDuration) {
  15303. missing--;
  15304. nextPts += inputSampleDuration;
  15305. }
  15306. if (i === 0) {
  15307. this.nextAudioTs = nextAudioTs = nextPts - initTime;
  15308. }
  15309. this.warn("Injecting " + missing + " audio frames @ " + ((nextPts - initTime) / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  15310. for (var j = 0; j < missing; j++) {
  15311. var fillFrame = AAC.getSilentFrame(track.parsedCodec || track.manifestCodec || track.codec, track.channelCount);
  15312. if (!fillFrame) {
  15313. this.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  15314. fillFrame = sample.unit.subarray();
  15315. }
  15316. inputSamples.splice(i, 0, {
  15317. unit: fillFrame,
  15318. pts: nextPts
  15319. });
  15320. nextPts += inputSampleDuration;
  15321. i++;
  15322. }
  15323. }
  15324. sample.pts = nextPts;
  15325. nextPts += inputSampleDuration;
  15326. }
  15327. }
  15328. var firstPTS = null;
  15329. var lastPTS = null;
  15330. var mdat;
  15331. var mdatSize = 0;
  15332. var sampleLength = inputSamples.length;
  15333. while (sampleLength--) {
  15334. mdatSize += inputSamples[sampleLength].unit.byteLength;
  15335. }
  15336. for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
  15337. var audioSample = inputSamples[_j2];
  15338. var unit = audioSample.unit;
  15339. var _pts2 = audioSample.pts;
  15340. if (lastPTS !== null) {
  15341. // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
  15342. // the previous sample
  15343. var prevSample = outputSamples[_j2 - 1];
  15344. prevSample.duration = Math.round((_pts2 - lastPTS) / scaleFactor);
  15345. } else {
  15346. if (contiguous && track.segmentCodec === 'aac') {
  15347. // set PTS/DTS to expected PTS/DTS
  15348. _pts2 = nextAudioTs + initTime;
  15349. }
  15350. // remember first PTS of our audioSamples
  15351. firstPTS = _pts2;
  15352. if (mdatSize > 0) {
  15353. /* concatenate the audio data and construct the mdat in place
  15354. (need 8 more bytes to fill length and mdat type) */
  15355. mdatSize += offset;
  15356. try {
  15357. mdat = new Uint8Array(mdatSize);
  15358. } catch (err) {
  15359. this.observer.emit(Events.ERROR, Events.ERROR, {
  15360. type: ErrorTypes.MUX_ERROR,
  15361. details: ErrorDetails.REMUX_ALLOC_ERROR,
  15362. fatal: false,
  15363. error: err,
  15364. bytes: mdatSize,
  15365. reason: "fail allocating audio mdat " + mdatSize
  15366. });
  15367. return;
  15368. }
  15369. if (!rawMPEG) {
  15370. var view = new DataView(mdat.buffer);
  15371. view.setUint32(0, mdatSize);
  15372. mdat.set(MP4.types.mdat, 4);
  15373. }
  15374. } else {
  15375. // no audio samples
  15376. return;
  15377. }
  15378. }
  15379. mdat.set(unit, offset);
  15380. var unitLen = unit.byteLength;
  15381. offset += unitLen;
  15382. // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
  15383. // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
  15384. // becomes the PTS diff with the previous sample
  15385. outputSamples.push(createMp4Sample(true, mp4SampleDuration, unitLen, 0));
  15386. lastPTS = _pts2;
  15387. }
  15388. // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
  15389. var nbSamples = outputSamples.length;
  15390. if (!nbSamples) {
  15391. return;
  15392. }
  15393. // The next audio sample PTS should be equal to last sample PTS + duration
  15394. var lastSample = outputSamples[outputSamples.length - 1];
  15395. nextAudioTs = lastPTS - initTime;
  15396. this.nextAudioTs = nextAudioTs + scaleFactor * lastSample.duration;
  15397. // Set the track samples from inputSamples to outputSamples before remuxing
  15398. var moof = rawMPEG ? new Uint8Array(0) : MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
  15399. samples: outputSamples
  15400. }));
  15401. // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
  15402. track.samples = [];
  15403. var start = (firstPTS - initTime) / inputTimeScale;
  15404. var end = nextAudioTs / inputTimeScale;
  15405. var type = 'audio';
  15406. var audioData = {
  15407. data1: moof,
  15408. data2: mdat,
  15409. startPTS: start,
  15410. endPTS: end,
  15411. startDTS: start,
  15412. endDTS: end,
  15413. type: type,
  15414. hasAudio: true,
  15415. hasVideo: false,
  15416. nb: nbSamples
  15417. };
  15418. this.isAudioContiguous = true;
  15419. return audioData;
  15420. };
  15421. return MP4Remuxer;
  15422. }(Logger);
  15423. function normalizePts(value, reference) {
  15424. var offset;
  15425. if (reference === null) {
  15426. return value;
  15427. }
  15428. if (reference < value) {
  15429. // - 2^33
  15430. offset = -8589934592;
  15431. } else {
  15432. // + 2^33
  15433. offset = 8589934592;
  15434. }
  15435. /* PTS is 33bit (from 0 to 2^33 -1)
  15436. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  15437. PTS looping occured. fill the gap */
  15438. while (Math.abs(value - reference) > 4294967296) {
  15439. value += offset;
  15440. }
  15441. return value;
  15442. }
  15443. function findKeyframeIndex(samples) {
  15444. for (var i = 0; i < samples.length; i++) {
  15445. if (samples[i].key) {
  15446. return i;
  15447. }
  15448. }
  15449. return -1;
  15450. }
  15451. function flushTextTrackMetadataCueSamples(track, timeOffset, initPTS, initDTS) {
  15452. var length = track.samples.length;
  15453. if (!length) {
  15454. return;
  15455. }
  15456. var inputTimeScale = track.inputTimeScale;
  15457. for (var index = 0; index < length; index++) {
  15458. var sample = track.samples[index];
  15459. // setting id3 pts, dts to relative time
  15460. // using this._initPTS and this._initDTS to calculate relative time
  15461. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15462. sample.dts = normalizePts(sample.dts - initDTS.baseTime * inputTimeScale / initDTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15463. }
  15464. var samples = track.samples;
  15465. track.samples = [];
  15466. return {
  15467. samples: samples
  15468. };
  15469. }
  15470. function flushTextTrackUserdataCueSamples(track, timeOffset, initPTS) {
  15471. var length = track.samples.length;
  15472. if (!length) {
  15473. return;
  15474. }
  15475. var inputTimeScale = track.inputTimeScale;
  15476. for (var index = 0; index < length; index++) {
  15477. var sample = track.samples[index];
  15478. // setting text pts, dts to relative time
  15479. // using this._initPTS and this._initDTS to calculate relative time
  15480. sample.pts = normalizePts(sample.pts - initPTS.baseTime * inputTimeScale / initPTS.timescale, timeOffset * inputTimeScale) / inputTimeScale;
  15481. }
  15482. track.samples.sort(function (a, b) {
  15483. return a.pts - b.pts;
  15484. });
  15485. var samples = track.samples;
  15486. track.samples = [];
  15487. return {
  15488. samples: samples
  15489. };
  15490. }
  15491. var PassThroughRemuxer = /*#__PURE__*/function (_Logger) {
  15492. function PassThroughRemuxer(observer, config, typeSupported, logger) {
  15493. var _this;
  15494. _this = _Logger.call(this, 'passthrough-remuxer', logger) || this;
  15495. _this.emitInitSegment = false;
  15496. _this.audioCodec = void 0;
  15497. _this.videoCodec = void 0;
  15498. _this.initData = void 0;
  15499. _this.initPTS = null;
  15500. _this.initTracks = void 0;
  15501. _this.lastEndTime = null;
  15502. _this.isVideoContiguous = false;
  15503. return _this;
  15504. }
  15505. _inheritsLoose(PassThroughRemuxer, _Logger);
  15506. var _proto = PassThroughRemuxer.prototype;
  15507. _proto.destroy = function destroy() {};
  15508. _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
  15509. this.lastEndTime = null;
  15510. var initPTS = this.initPTS;
  15511. if (initPTS && defaultInitPTS) {
  15512. if (initPTS.baseTime === defaultInitPTS.baseTime && initPTS.timescale === defaultInitPTS.timescale) {
  15513. return;
  15514. }
  15515. }
  15516. this.initPTS = defaultInitPTS;
  15517. };
  15518. _proto.resetNextTimestamp = function resetNextTimestamp() {
  15519. this.isVideoContiguous = false;
  15520. this.lastEndTime = null;
  15521. };
  15522. _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, decryptdata) {
  15523. this.audioCodec = audioCodec;
  15524. this.videoCodec = videoCodec;
  15525. this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));
  15526. this.emitInitSegment = true;
  15527. };
  15528. _proto.generateInitSegment = function generateInitSegment(initSegment) {
  15529. var audioCodec = this.audioCodec,
  15530. videoCodec = this.videoCodec;
  15531. if (!(initSegment != null && initSegment.byteLength)) {
  15532. this.initTracks = undefined;
  15533. this.initData = undefined;
  15534. return;
  15535. }
  15536. var initData = this.initData = parseInitSegment(initSegment);
  15537. // Get codec from initSegment
  15538. if (initData.audio) {
  15539. audioCodec = getParsedTrackCodec(initData.audio, ElementaryStreamTypes.AUDIO, this);
  15540. }
  15541. if (initData.video) {
  15542. videoCodec = getParsedTrackCodec(initData.video, ElementaryStreamTypes.VIDEO, this);
  15543. }
  15544. var tracks = {};
  15545. if (initData.audio && initData.video) {
  15546. tracks.audiovideo = {
  15547. container: 'video/mp4',
  15548. codec: audioCodec + ',' + videoCodec,
  15549. supplemental: initData.video.supplemental,
  15550. initSegment: initSegment,
  15551. id: 'main'
  15552. };
  15553. } else if (initData.audio) {
  15554. tracks.audio = {
  15555. container: 'audio/mp4',
  15556. codec: audioCodec,
  15557. initSegment: initSegment,
  15558. id: 'audio'
  15559. };
  15560. } else if (initData.video) {
  15561. tracks.video = {
  15562. container: 'video/mp4',
  15563. codec: videoCodec,
  15564. supplemental: initData.video.supplemental,
  15565. initSegment: initSegment,
  15566. id: 'main'
  15567. };
  15568. } else {
  15569. this.warn('initSegment does not contain moov or trak boxes.');
  15570. }
  15571. this.initTracks = tracks;
  15572. };
  15573. _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset) {
  15574. var _initData, _initData2;
  15575. var initPTS = this.initPTS,
  15576. lastEndTime = this.lastEndTime;
  15577. var result = {
  15578. audio: undefined,
  15579. video: undefined,
  15580. text: textTrack,
  15581. id3: id3Track,
  15582. initSegment: undefined
  15583. };
  15584. // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
  15585. // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
  15586. // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
  15587. if (!isFiniteNumber(lastEndTime)) {
  15588. lastEndTime = this.lastEndTime = timeOffset || 0;
  15589. }
  15590. // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
  15591. // audio or video (or both); adding it to video was an arbitrary choice.
  15592. var data = videoTrack.samples;
  15593. if (!(data != null && data.length)) {
  15594. return result;
  15595. }
  15596. var initSegment = {
  15597. initPTS: undefined,
  15598. timescale: undefined,
  15599. trackId: undefined
  15600. };
  15601. var initData = this.initData;
  15602. if (!((_initData = initData) != null && _initData.length)) {
  15603. this.generateInitSegment(data);
  15604. initData = this.initData;
  15605. }
  15606. if (!((_initData2 = initData) != null && _initData2.length)) {
  15607. // We can't remux if the initSegment could not be generated
  15608. this.warn('Failed to generate initSegment.');
  15609. return result;
  15610. }
  15611. if (this.emitInitSegment) {
  15612. initSegment.tracks = this.initTracks;
  15613. this.emitInitSegment = false;
  15614. }
  15615. var trackSampleData = getSampleData(data, initData, this);
  15616. var audioSampleTimestamps = initData.audio ? trackSampleData[initData.audio.id] : null;
  15617. var videoSampleTimestamps = initData.video ? trackSampleData[initData.video.id] : null;
  15618. var videoStartTime = toStartEndOrDefault(videoSampleTimestamps, Infinity);
  15619. var audioStartTime = toStartEndOrDefault(audioSampleTimestamps, Infinity);
  15620. var videoEndTime = toStartEndOrDefault(videoSampleTimestamps, 0, true);
  15621. var audioEndTime = toStartEndOrDefault(audioSampleTimestamps, 0, true);
  15622. var baseOffsetSamples;
  15623. var decodeTime = timeOffset;
  15624. var duration = 0;
  15625. if (audioSampleTimestamps && (!videoSampleTimestamps || !initPTS && audioStartTime < videoStartTime || initPTS && initPTS.trackId === initData.audio.id)) {
  15626. initSegment.trackId = initData.audio.id;
  15627. baseOffsetSamples = audioSampleTimestamps;
  15628. duration = audioEndTime - audioStartTime;
  15629. } else if (videoSampleTimestamps) {
  15630. initSegment.trackId = initData.video.id;
  15631. baseOffsetSamples = videoSampleTimestamps;
  15632. duration = videoEndTime - videoStartTime;
  15633. }
  15634. if (baseOffsetSamples) {
  15635. var timescale = baseOffsetSamples.timescale;
  15636. decodeTime = baseOffsetSamples.start / timescale;
  15637. initSegment.initPTS = baseOffsetSamples.start - timeOffset * timescale;
  15638. initSegment.timescale = timescale;
  15639. if (!initPTS) {
  15640. this.initPTS = initPTS = {
  15641. baseTime: initSegment.initPTS,
  15642. timescale: timescale,
  15643. trackId: initSegment.trackId
  15644. };
  15645. }
  15646. }
  15647. if ((accurateTimeOffset || !initPTS) && (isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) || initSegment.timescale !== initPTS.timescale)) {
  15648. initSegment.initPTS = decodeTime - timeOffset;
  15649. initSegment.timescale = 1;
  15650. if (initPTS && initPTS.timescale === 1) {
  15651. this.warn("Adjusting initPTS @" + timeOffset + " from " + initPTS.baseTime / initPTS.timescale + " to " + initSegment.initPTS);
  15652. }
  15653. this.initPTS = initPTS = {
  15654. baseTime: initSegment.initPTS,
  15655. timescale: 1
  15656. };
  15657. }
  15658. var startTime = audioTrack ? decodeTime - initPTS.baseTime / initPTS.timescale : lastEndTime;
  15659. var endTime = startTime + duration;
  15660. if (duration > 0) {
  15661. this.lastEndTime = endTime;
  15662. } else {
  15663. this.warn('Duration parsed from mp4 should be greater than zero');
  15664. this.resetNextTimestamp();
  15665. }
  15666. var hasAudio = !!initData.audio;
  15667. var hasVideo = !!initData.video;
  15668. var type = '';
  15669. if (hasAudio) {
  15670. type += 'audio';
  15671. }
  15672. if (hasVideo) {
  15673. type += 'video';
  15674. }
  15675. var track = {
  15676. data1: data,
  15677. startPTS: startTime,
  15678. startDTS: startTime,
  15679. endPTS: endTime,
  15680. endDTS: endTime,
  15681. type: type,
  15682. hasAudio: hasAudio,
  15683. hasVideo: hasVideo,
  15684. nb: 1,
  15685. dropped: 0
  15686. };
  15687. result.audio = hasAudio && !hasVideo ? track : undefined;
  15688. result.video = hasVideo ? track : undefined;
  15689. var videoSampleCount = videoSampleTimestamps == null ? void 0 : videoSampleTimestamps.sampleCount;
  15690. if (videoSampleCount) {
  15691. var firstKeyFrame = videoSampleTimestamps.keyFrameIndex;
  15692. var independent = firstKeyFrame !== -1;
  15693. track.nb = videoSampleCount;
  15694. track.dropped = firstKeyFrame === 0 || this.isVideoContiguous ? 0 : independent ? firstKeyFrame : videoSampleCount;
  15695. track.independent = independent;
  15696. track.firstKeyFrame = firstKeyFrame;
  15697. if (independent && videoSampleTimestamps.keyFrameStart) {
  15698. track.firstKeyFramePTS = (videoSampleTimestamps.keyFrameStart - initPTS.baseTime) / initPTS.timescale;
  15699. }
  15700. if (!this.isVideoContiguous) {
  15701. result.independent = independent;
  15702. }
  15703. this.isVideoContiguous || (this.isVideoContiguous = independent);
  15704. if (track.dropped) {
  15705. this.warn("fmp4 does not start with IDR: firstIDR " + firstKeyFrame + "/" + videoSampleCount + " dropped: " + track.dropped + " start: " + (track.firstKeyFramePTS || 'NA'));
  15706. }
  15707. }
  15708. result.initSegment = initSegment;
  15709. result.id3 = flushTextTrackMetadataCueSamples(id3Track, timeOffset, initPTS, initPTS);
  15710. if (textTrack.samples.length) {
  15711. result.text = flushTextTrackUserdataCueSamples(textTrack, timeOffset, initPTS);
  15712. }
  15713. return result;
  15714. };
  15715. return PassThroughRemuxer;
  15716. }(Logger);
  15717. function toStartEndOrDefault(trackTimes, defaultValue, end) {
  15718. if (end === void 0) {
  15719. end = false;
  15720. }
  15721. return (trackTimes == null ? void 0 : trackTimes.start) !== undefined ? (trackTimes.start + (end ? trackTimes.duration : 0)) / trackTimes.timescale : defaultValue;
  15722. }
  15723. function isInvalidInitPts(initPTS, startDTS, timeOffset, duration) {
  15724. if (initPTS === null) {
  15725. return true;
  15726. }
  15727. // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second
  15728. var minDuration = Math.max(duration, 1);
  15729. var startTime = startDTS - initPTS.baseTime / initPTS.timescale;
  15730. return Math.abs(startTime - timeOffset) > minDuration;
  15731. }
  15732. function getParsedTrackCodec(track, type, logger) {
  15733. var parsedCodec = track == null ? void 0 : track.codec;
  15734. if (parsedCodec && parsedCodec.length > 4) {
  15735. return parsedCodec;
  15736. }
  15737. if (type === ElementaryStreamTypes.AUDIO) {
  15738. if (parsedCodec === 'ec-3' || parsedCodec === 'ac-3' || parsedCodec === 'alac') {
  15739. return parsedCodec;
  15740. }
  15741. if (parsedCodec === 'fLaC' || parsedCodec === 'Opus') {
  15742. // Opting not to get `preferManagedMediaSource` from player config for isSupported() check for simplicity
  15743. var preferManagedMediaSource = false;
  15744. return getCodecCompatibleName(parsedCodec, preferManagedMediaSource);
  15745. }
  15746. logger.warn("Unhandled audio codec \"" + parsedCodec + "\" in mp4 MAP");
  15747. return parsedCodec || 'mp4a';
  15748. }
  15749. // Provide defaults based on codec type
  15750. // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
  15751. logger.warn("Unhandled video codec \"" + parsedCodec + "\" in mp4 MAP");
  15752. return parsedCodec || 'avc1';
  15753. }
  15754. var now;
  15755. // performance.now() not available on WebWorker, at least on Safari Desktop
  15756. try {
  15757. now = self.performance.now.bind(self.performance);
  15758. } catch (err) {
  15759. now = Date.now;
  15760. }
  15761. var muxConfig = [{
  15762. demux: MP4Demuxer,
  15763. remux: PassThroughRemuxer
  15764. }, {
  15765. demux: TSDemuxer,
  15766. remux: MP4Remuxer
  15767. }, {
  15768. demux: AACDemuxer,
  15769. remux: MP4Remuxer
  15770. }, {
  15771. demux: MP3Demuxer,
  15772. remux: MP4Remuxer
  15773. }];
  15774. {
  15775. muxConfig.splice(2, 0, {
  15776. demux: AC3Demuxer,
  15777. remux: MP4Remuxer
  15778. });
  15779. }
  15780. var Transmuxer = /*#__PURE__*/function () {
  15781. function Transmuxer(observer, typeSupported, config, vendor, id, logger) {
  15782. this.asyncResult = false;
  15783. this.logger = void 0;
  15784. this.observer = void 0;
  15785. this.typeSupported = void 0;
  15786. this.config = void 0;
  15787. this.id = void 0;
  15788. this.demuxer = void 0;
  15789. this.remuxer = void 0;
  15790. this.decrypter = void 0;
  15791. this.probe = void 0;
  15792. this.decryptionPromise = null;
  15793. this.transmuxConfig = void 0;
  15794. this.currentTransmuxState = void 0;
  15795. this.observer = observer;
  15796. this.typeSupported = typeSupported;
  15797. this.config = config;
  15798. this.id = id;
  15799. this.logger = logger;
  15800. }
  15801. var _proto = Transmuxer.prototype;
  15802. _proto.configure = function configure(transmuxConfig) {
  15803. this.transmuxConfig = transmuxConfig;
  15804. if (this.decrypter) {
  15805. this.decrypter.reset();
  15806. }
  15807. };
  15808. _proto.push = function push(data, decryptdata, chunkMeta, state) {
  15809. var _this = this;
  15810. var stats = chunkMeta.transmuxing;
  15811. stats.executeStart = now();
  15812. var uintData = new Uint8Array(data);
  15813. var currentTransmuxState = this.currentTransmuxState,
  15814. transmuxConfig = this.transmuxConfig;
  15815. if (state) {
  15816. this.currentTransmuxState = state;
  15817. }
  15818. var _ref = state || currentTransmuxState,
  15819. contiguous = _ref.contiguous,
  15820. discontinuity = _ref.discontinuity,
  15821. trackSwitch = _ref.trackSwitch,
  15822. accurateTimeOffset = _ref.accurateTimeOffset,
  15823. timeOffset = _ref.timeOffset,
  15824. initSegmentChange = _ref.initSegmentChange;
  15825. var audioCodec = transmuxConfig.audioCodec,
  15826. videoCodec = transmuxConfig.videoCodec,
  15827. defaultInitPts = transmuxConfig.defaultInitPts,
  15828. duration = transmuxConfig.duration,
  15829. initSegmentData = transmuxConfig.initSegmentData;
  15830. var keyData = getEncryptionType(uintData, decryptdata);
  15831. if (keyData && isFullSegmentEncryption(keyData.method)) {
  15832. var decrypter = this.getDecrypter();
  15833. var aesMode = getAesModeFromFullSegmentMethod(keyData.method);
  15834. // Software decryption is synchronous; webCrypto is not
  15835. if (decrypter.isSync()) {
  15836. // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
  15837. // data is handled in the flush() call
  15838. var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode);
  15839. // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress
  15840. var loadingParts = chunkMeta.part > -1;
  15841. if (loadingParts) {
  15842. var _data = decrypter.flush();
  15843. decryptedData = _data ? _data.buffer : _data;
  15844. }
  15845. if (!decryptedData) {
  15846. stats.executeEnd = now();
  15847. return emptyResult(chunkMeta);
  15848. }
  15849. uintData = new Uint8Array(decryptedData);
  15850. } else {
  15851. this.asyncResult = true;
  15852. this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer, aesMode).then(function (decryptedData) {
  15853. // Calling push here is important; if flush() is called while this is still resolving, this ensures that
  15854. // the decrypted data has been transmuxed
  15855. var result = _this.push(decryptedData, null, chunkMeta);
  15856. _this.decryptionPromise = null;
  15857. return result;
  15858. });
  15859. return this.decryptionPromise;
  15860. }
  15861. }
  15862. var resetMuxers = this.needsProbing(discontinuity, trackSwitch);
  15863. if (resetMuxers) {
  15864. var error = this.configureTransmuxer(uintData);
  15865. if (error) {
  15866. this.logger.warn("[transmuxer] " + error.message);
  15867. this.observer.emit(Events.ERROR, Events.ERROR, {
  15868. type: ErrorTypes.MEDIA_ERROR,
  15869. details: ErrorDetails.FRAG_PARSING_ERROR,
  15870. fatal: false,
  15871. error: error,
  15872. reason: error.message
  15873. });
  15874. stats.executeEnd = now();
  15875. return emptyResult(chunkMeta);
  15876. }
  15877. }
  15878. if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {
  15879. this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration, decryptdata);
  15880. }
  15881. if (discontinuity || initSegmentChange || resetMuxers) {
  15882. this.resetInitialTimestamp(defaultInitPts);
  15883. }
  15884. if (!contiguous) {
  15885. this.resetContiguity();
  15886. }
  15887. var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  15888. this.asyncResult = isPromise(result);
  15889. var currentState = this.currentTransmuxState;
  15890. currentState.contiguous = true;
  15891. currentState.discontinuity = false;
  15892. currentState.trackSwitch = false;
  15893. stats.executeEnd = now();
  15894. return result;
  15895. }
  15896. // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
  15897. ;
  15898. _proto.flush = function flush(chunkMeta) {
  15899. var _this2 = this;
  15900. var stats = chunkMeta.transmuxing;
  15901. stats.executeStart = now();
  15902. var decrypter = this.decrypter,
  15903. currentTransmuxState = this.currentTransmuxState,
  15904. decryptionPromise = this.decryptionPromise;
  15905. if (decryptionPromise) {
  15906. this.asyncResult = true;
  15907. // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
  15908. // only flushing is required for async decryption
  15909. return decryptionPromise.then(function () {
  15910. return _this2.flush(chunkMeta);
  15911. });
  15912. }
  15913. var transmuxResults = [];
  15914. var timeOffset = currentTransmuxState.timeOffset;
  15915. if (decrypter) {
  15916. // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
  15917. // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
  15918. // or for progressive downloads with small segments)
  15919. var decryptedData = decrypter.flush();
  15920. if (decryptedData) {
  15921. // Push always returns a TransmuxerResult if decryptdata is null
  15922. transmuxResults.push(this.push(decryptedData.buffer, null, chunkMeta));
  15923. }
  15924. }
  15925. var demuxer = this.demuxer,
  15926. remuxer = this.remuxer;
  15927. if (!demuxer || !remuxer) {
  15928. // If probing failed, then Hls.js has been given content its not able to handle
  15929. stats.executeEnd = now();
  15930. var emptyResults = [emptyResult(chunkMeta)];
  15931. if (this.asyncResult) {
  15932. return Promise.resolve(emptyResults);
  15933. }
  15934. return emptyResults;
  15935. }
  15936. var demuxResultOrPromise = demuxer.flush(timeOffset);
  15937. if (isPromise(demuxResultOrPromise)) {
  15938. this.asyncResult = true;
  15939. // Decrypt final SAMPLE-AES samples
  15940. return demuxResultOrPromise.then(function (demuxResult) {
  15941. _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
  15942. return transmuxResults;
  15943. });
  15944. }
  15945. this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
  15946. if (this.asyncResult) {
  15947. return Promise.resolve(transmuxResults);
  15948. }
  15949. return transmuxResults;
  15950. };
  15951. _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
  15952. var audioTrack = demuxResult.audioTrack,
  15953. videoTrack = demuxResult.videoTrack,
  15954. id3Track = demuxResult.id3Track,
  15955. textTrack = demuxResult.textTrack;
  15956. var _this$currentTransmux = this.currentTransmuxState,
  15957. accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
  15958. timeOffset = _this$currentTransmux.timeOffset;
  15959. this.logger.log("[transmuxer.ts]: Flushed " + this.id + " sn: " + chunkMeta.sn + (chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : '') + " of " + (this.id === PlaylistLevelType.MAIN ? 'level' : 'track') + " " + chunkMeta.level);
  15960. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
  15961. transmuxResults.push({
  15962. remuxResult: remuxResult,
  15963. chunkMeta: chunkMeta
  15964. });
  15965. chunkMeta.transmuxing.executeEnd = now();
  15966. };
  15967. _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
  15968. var demuxer = this.demuxer,
  15969. remuxer = this.remuxer;
  15970. if (!demuxer || !remuxer) {
  15971. return;
  15972. }
  15973. demuxer.resetTimeStamp(defaultInitPts);
  15974. remuxer.resetTimeStamp(defaultInitPts);
  15975. };
  15976. _proto.resetContiguity = function resetContiguity() {
  15977. var demuxer = this.demuxer,
  15978. remuxer = this.remuxer;
  15979. if (!demuxer || !remuxer) {
  15980. return;
  15981. }
  15982. demuxer.resetContiguity();
  15983. remuxer.resetNextTimestamp();
  15984. };
  15985. _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration, decryptdata) {
  15986. var demuxer = this.demuxer,
  15987. remuxer = this.remuxer;
  15988. if (!demuxer || !remuxer) {
  15989. return;
  15990. }
  15991. demuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, trackDuration);
  15992. remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec, decryptdata);
  15993. };
  15994. _proto.destroy = function destroy() {
  15995. if (this.demuxer) {
  15996. this.demuxer.destroy();
  15997. this.demuxer = undefined;
  15998. }
  15999. if (this.remuxer) {
  16000. this.remuxer.destroy();
  16001. this.remuxer = undefined;
  16002. }
  16003. };
  16004. _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
  16005. var result;
  16006. if (keyData && keyData.method === 'SAMPLE-AES') {
  16007. result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
  16008. } else {
  16009. result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
  16010. }
  16011. return result;
  16012. };
  16013. _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
  16014. var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
  16015. audioTrack = _demux.audioTrack,
  16016. videoTrack = _demux.videoTrack,
  16017. id3Track = _demux.id3Track,
  16018. textTrack = _demux.textTrack;
  16019. var remuxResult = this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
  16020. return {
  16021. remuxResult: remuxResult,
  16022. chunkMeta: chunkMeta
  16023. };
  16024. };
  16025. _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
  16026. var _this3 = this;
  16027. return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
  16028. var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.videoTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
  16029. return {
  16030. remuxResult: remuxResult,
  16031. chunkMeta: chunkMeta
  16032. };
  16033. });
  16034. };
  16035. _proto.configureTransmuxer = function configureTransmuxer(data) {
  16036. var config = this.config,
  16037. observer = this.observer,
  16038. typeSupported = this.typeSupported;
  16039. // probe for content type
  16040. var mux;
  16041. for (var i = 0, len = muxConfig.length; i < len; i++) {
  16042. var _muxConfig$i$demux;
  16043. if ((_muxConfig$i$demux = muxConfig[i].demux) != null && _muxConfig$i$demux.probe(data, this.logger)) {
  16044. mux = muxConfig[i];
  16045. break;
  16046. }
  16047. }
  16048. if (!mux) {
  16049. return new Error('Failed to find demuxer by probing fragment data');
  16050. }
  16051. // so let's check that current remuxer and demuxer are still valid
  16052. var demuxer = this.demuxer;
  16053. var remuxer = this.remuxer;
  16054. var Remuxer = mux.remux;
  16055. var Demuxer = mux.demux;
  16056. if (!remuxer || !(remuxer instanceof Remuxer)) {
  16057. this.remuxer = new Remuxer(observer, config, typeSupported, this.logger);
  16058. }
  16059. if (!demuxer || !(demuxer instanceof Demuxer)) {
  16060. this.demuxer = new Demuxer(observer, config, typeSupported, this.logger);
  16061. this.probe = Demuxer.probe;
  16062. }
  16063. };
  16064. _proto.needsProbing = function needsProbing(discontinuity, trackSwitch) {
  16065. // in case of continuity change, or track switch
  16066. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  16067. return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
  16068. };
  16069. _proto.getDecrypter = function getDecrypter() {
  16070. var decrypter = this.decrypter;
  16071. if (!decrypter) {
  16072. decrypter = this.decrypter = new Decrypter(this.config);
  16073. }
  16074. return decrypter;
  16075. };
  16076. return Transmuxer;
  16077. }();
  16078. function getEncryptionType(data, decryptData) {
  16079. var encryptionType = null;
  16080. if (data.byteLength > 0 && (decryptData == null ? void 0 : decryptData.key) != null && decryptData.iv !== null && decryptData.method != null) {
  16081. encryptionType = decryptData;
  16082. }
  16083. return encryptionType;
  16084. }
  16085. var emptyResult = function emptyResult(chunkMeta) {
  16086. return {
  16087. remuxResult: {},
  16088. chunkMeta: chunkMeta
  16089. };
  16090. };
  16091. function isPromise(p) {
  16092. return 'then' in p && p.then instanceof Function;
  16093. }
  16094. var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
  16095. this.audioCodec = void 0;
  16096. this.videoCodec = void 0;
  16097. this.initSegmentData = void 0;
  16098. this.duration = void 0;
  16099. this.defaultInitPts = void 0;
  16100. this.audioCodec = audioCodec;
  16101. this.videoCodec = videoCodec;
  16102. this.initSegmentData = initSegmentData;
  16103. this.duration = duration;
  16104. this.defaultInitPts = defaultInitPts || null;
  16105. };
  16106. var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange) {
  16107. this.discontinuity = void 0;
  16108. this.contiguous = void 0;
  16109. this.accurateTimeOffset = void 0;
  16110. this.trackSwitch = void 0;
  16111. this.timeOffset = void 0;
  16112. this.initSegmentChange = void 0;
  16113. this.discontinuity = discontinuity;
  16114. this.contiguous = contiguous;
  16115. this.accurateTimeOffset = accurateTimeOffset;
  16116. this.trackSwitch = trackSwitch;
  16117. this.timeOffset = timeOffset;
  16118. this.initSegmentChange = initSegmentChange;
  16119. };
  16120. var transmuxers = [];
  16121. if (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {
  16122. startWorker();
  16123. }
  16124. function startWorker() {
  16125. self.addEventListener('message', function (ev) {
  16126. var data = ev.data;
  16127. var instanceNo = data.instanceNo;
  16128. if (instanceNo === undefined) {
  16129. return;
  16130. }
  16131. var transmuxer = transmuxers[instanceNo];
  16132. if (data.cmd === 'reset') {
  16133. delete transmuxers[data.resetNo];
  16134. if (transmuxer) {
  16135. transmuxer.destroy();
  16136. }
  16137. data.cmd = 'init';
  16138. }
  16139. if (data.cmd === 'init') {
  16140. var config = JSON.parse(data.config);
  16141. var observer = new EventEmitter();
  16142. observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  16143. observer.on(Events.ERROR, forwardMessage);
  16144. var logger = enableLogs(config.debug, data.id);
  16145. forwardWorkerLogs(logger, instanceNo);
  16146. transmuxers[instanceNo] = new Transmuxer(observer, data.typeSupported, config, '', data.id, logger);
  16147. forwardMessage('init', null, instanceNo);
  16148. return;
  16149. }
  16150. if (!transmuxer) {
  16151. return;
  16152. }
  16153. switch (data.cmd) {
  16154. case 'configure':
  16155. {
  16156. transmuxer.configure(data.config);
  16157. break;
  16158. }
  16159. case 'demux':
  16160. {
  16161. var transmuxResult = transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
  16162. if (isPromise(transmuxResult)) {
  16163. transmuxResult.then(function (data) {
  16164. emitTransmuxComplete(self, data, instanceNo);
  16165. }).catch(function (error) {
  16166. forwardMessage(Events.ERROR, {
  16167. instanceNo: instanceNo,
  16168. type: ErrorTypes.MEDIA_ERROR,
  16169. details: ErrorDetails.FRAG_PARSING_ERROR,
  16170. chunkMeta: data.chunkMeta,
  16171. fatal: false,
  16172. error: error,
  16173. err: error,
  16174. reason: "transmuxer-worker push error"
  16175. }, instanceNo);
  16176. });
  16177. } else {
  16178. emitTransmuxComplete(self, transmuxResult, instanceNo);
  16179. }
  16180. break;
  16181. }
  16182. case 'flush':
  16183. {
  16184. var chunkMeta = data.chunkMeta;
  16185. var _transmuxResult = transmuxer.flush(chunkMeta);
  16186. if (isPromise(_transmuxResult)) {
  16187. _transmuxResult.then(function (results) {
  16188. handleFlushResult(self, results, chunkMeta, instanceNo);
  16189. }).catch(function (error) {
  16190. forwardMessage(Events.ERROR, {
  16191. type: ErrorTypes.MEDIA_ERROR,
  16192. details: ErrorDetails.FRAG_PARSING_ERROR,
  16193. chunkMeta: data.chunkMeta,
  16194. fatal: false,
  16195. error: error,
  16196. err: error,
  16197. reason: "transmuxer-worker flush error"
  16198. }, instanceNo);
  16199. });
  16200. } else {
  16201. handleFlushResult(self, _transmuxResult, chunkMeta, instanceNo);
  16202. }
  16203. break;
  16204. }
  16205. }
  16206. });
  16207. }
  16208. function emitTransmuxComplete(self, transmuxResult, instanceNo) {
  16209. if (isEmptyResult(transmuxResult.remuxResult)) {
  16210. return false;
  16211. }
  16212. var transferable = [];
  16213. var _transmuxResult$remux = transmuxResult.remuxResult,
  16214. audio = _transmuxResult$remux.audio,
  16215. video = _transmuxResult$remux.video;
  16216. if (audio) {
  16217. addToTransferable(transferable, audio);
  16218. }
  16219. if (video) {
  16220. addToTransferable(transferable, video);
  16221. }
  16222. self.postMessage({
  16223. event: 'transmuxComplete',
  16224. data: transmuxResult,
  16225. instanceNo: instanceNo
  16226. }, transferable);
  16227. return true;
  16228. }
  16229. // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
  16230. // in order to minimize message passing overhead
  16231. function addToTransferable(transferable, track) {
  16232. if (track.data1) {
  16233. transferable.push(track.data1.buffer);
  16234. }
  16235. if (track.data2) {
  16236. transferable.push(track.data2.buffer);
  16237. }
  16238. }
  16239. function handleFlushResult(self, results, chunkMeta, instanceNo) {
  16240. var parsed = results.reduce(function (parsed, result) {
  16241. return emitTransmuxComplete(self, result, instanceNo) || parsed;
  16242. }, false);
  16243. if (!parsed) {
  16244. // Emit at least one "transmuxComplete" message even if media is not found to update stream-controller state to PARSING
  16245. self.postMessage({
  16246. event: 'transmuxComplete',
  16247. data: results[0],
  16248. instanceNo: instanceNo
  16249. });
  16250. }
  16251. self.postMessage({
  16252. event: 'flush',
  16253. data: chunkMeta,
  16254. instanceNo: instanceNo
  16255. });
  16256. }
  16257. function forwardMessage(event, data, instanceNo) {
  16258. self.postMessage({
  16259. event: event,
  16260. data: data,
  16261. instanceNo: instanceNo
  16262. });
  16263. }
  16264. function forwardWorkerLogs(logger, instanceNo) {
  16265. var _loop = function _loop(logFn) {
  16266. logger[logFn] = function () {
  16267. var message = Array.prototype.join.call(arguments, ' ');
  16268. forwardMessage('workerLog', {
  16269. logType: logFn,
  16270. message: message
  16271. }, instanceNo);
  16272. };
  16273. };
  16274. for (var logFn in logger) {
  16275. _loop(logFn);
  16276. }
  16277. }
  16278. function isEmptyResult(remuxResult) {
  16279. return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
  16280. }
  16281. var version = "1.6.7";
  16282. // ensure the worker ends up in the bundle
  16283. // If the worker should not be included this gets aliased to empty.js
  16284. var workerStore = {};
  16285. function hasUMDWorker() {
  16286. return typeof __HLS_WORKER_BUNDLE__ === 'function';
  16287. }
  16288. function injectWorker() {
  16289. var workerContext = workerStore[version];
  16290. if (workerContext) {
  16291. workerContext.clientCount++;
  16292. return workerContext;
  16293. }
  16294. var blob = new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(" + __HLS_WORKER_BUNDLE__.toString() + ")(true);"], {
  16295. type: 'text/javascript'
  16296. });
  16297. var objectURL = self.URL.createObjectURL(blob);
  16298. var worker = new self.Worker(objectURL);
  16299. var result = {
  16300. worker: worker,
  16301. objectURL: objectURL,
  16302. clientCount: 1
  16303. };
  16304. workerStore[version] = result;
  16305. return result;
  16306. }
  16307. function loadWorker(path) {
  16308. var workerContext = workerStore[path];
  16309. if (workerContext) {
  16310. workerContext.clientCount++;
  16311. return workerContext;
  16312. }
  16313. var scriptURL = new self.URL(path, self.location.href).href;
  16314. var worker = new self.Worker(scriptURL);
  16315. var result = {
  16316. worker: worker,
  16317. scriptURL: scriptURL,
  16318. clientCount: 1
  16319. };
  16320. workerStore[path] = result;
  16321. return result;
  16322. }
  16323. function removeWorkerFromStore(path) {
  16324. var workerContext = workerStore[path || version];
  16325. if (workerContext) {
  16326. var clientCount = workerContext.clientCount--;
  16327. if (clientCount === 1) {
  16328. var worker = workerContext.worker,
  16329. objectURL = workerContext.objectURL;
  16330. delete workerStore[path || version];
  16331. if (objectURL) {
  16332. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  16333. self.URL.revokeObjectURL(objectURL);
  16334. }
  16335. worker.terminate();
  16336. }
  16337. }
  16338. }
  16339. var transmuxerInstanceCount = 0;
  16340. var TransmuxerInterface = /*#__PURE__*/function () {
  16341. function TransmuxerInterface(_hls, id, onTransmuxComplete, onFlush) {
  16342. var _this = this;
  16343. this.error = null;
  16344. this.hls = void 0;
  16345. this.id = void 0;
  16346. this.instanceNo = transmuxerInstanceCount++;
  16347. this.observer = void 0;
  16348. this.frag = null;
  16349. this.part = null;
  16350. this.useWorker = void 0;
  16351. this.workerContext = null;
  16352. this.transmuxer = null;
  16353. this.onTransmuxComplete = void 0;
  16354. this.onFlush = void 0;
  16355. this.onWorkerMessage = function (event) {
  16356. var data = event.data;
  16357. var hls = _this.hls;
  16358. if (!hls || !(data != null && data.event) || data.instanceNo !== _this.instanceNo) {
  16359. return;
  16360. }
  16361. switch (data.event) {
  16362. case 'init':
  16363. {
  16364. var _this$workerContext;
  16365. var objectURL = (_this$workerContext = _this.workerContext) == null ? void 0 : _this$workerContext.objectURL;
  16366. if (objectURL) {
  16367. // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
  16368. self.URL.revokeObjectURL(objectURL);
  16369. }
  16370. break;
  16371. }
  16372. case 'transmuxComplete':
  16373. {
  16374. _this.handleTransmuxComplete(data.data);
  16375. break;
  16376. }
  16377. case 'flush':
  16378. {
  16379. _this.onFlush(data.data);
  16380. break;
  16381. }
  16382. // pass logs from the worker thread to the main logger
  16383. case 'workerLog':
  16384. {
  16385. if (hls.logger[data.data.logType]) {
  16386. hls.logger[data.data.logType](data.data.message);
  16387. }
  16388. break;
  16389. }
  16390. default:
  16391. {
  16392. data.data = data.data || {};
  16393. data.data.frag = _this.frag;
  16394. data.data.part = _this.part;
  16395. data.data.id = _this.id;
  16396. hls.trigger(data.event, data.data);
  16397. break;
  16398. }
  16399. }
  16400. };
  16401. this.onWorkerError = function (event) {
  16402. if (!_this.hls) {
  16403. return;
  16404. }
  16405. var error = new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
  16406. _this.hls.config.enableWorker = false;
  16407. _this.hls.logger.warn("Error in \"" + _this.id + "\" Web Worker, fallback to inline");
  16408. _this.hls.trigger(Events.ERROR, {
  16409. type: ErrorTypes.OTHER_ERROR,
  16410. details: ErrorDetails.INTERNAL_EXCEPTION,
  16411. fatal: false,
  16412. event: 'demuxerWorker',
  16413. error: error
  16414. });
  16415. };
  16416. var config = _hls.config;
  16417. this.hls = _hls;
  16418. this.id = id;
  16419. this.useWorker = !!config.enableWorker;
  16420. this.onTransmuxComplete = onTransmuxComplete;
  16421. this.onFlush = onFlush;
  16422. var forwardMessage = function forwardMessage(ev, data) {
  16423. data = data || {};
  16424. data.frag = _this.frag || undefined;
  16425. if (ev === Events.ERROR) {
  16426. data = data;
  16427. data.parent = _this.id;
  16428. data.part = _this.part;
  16429. _this.error = data.error;
  16430. }
  16431. _this.hls.trigger(ev, data);
  16432. };
  16433. // forward events to main thread
  16434. this.observer = new EventEmitter();
  16435. this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);
  16436. this.observer.on(Events.ERROR, forwardMessage);
  16437. var m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  16438. if (this.useWorker && typeof Worker !== 'undefined') {
  16439. var logger = this.hls.logger;
  16440. var canCreateWorker = config.workerPath || hasUMDWorker();
  16441. if (canCreateWorker) {
  16442. try {
  16443. if (config.workerPath) {
  16444. logger.log("loading Web Worker " + config.workerPath + " for \"" + id + "\"");
  16445. this.workerContext = loadWorker(config.workerPath);
  16446. } else {
  16447. logger.log("injecting Web Worker for \"" + id + "\"");
  16448. this.workerContext = injectWorker();
  16449. }
  16450. var worker = this.workerContext.worker;
  16451. worker.addEventListener('message', this.onWorkerMessage);
  16452. worker.addEventListener('error', this.onWorkerError);
  16453. worker.postMessage({
  16454. instanceNo: this.instanceNo,
  16455. cmd: 'init',
  16456. typeSupported: m2tsTypeSupported,
  16457. id: id,
  16458. config: stringify(config)
  16459. });
  16460. } catch (err) {
  16461. logger.warn("Error setting up \"" + id + "\" Web Worker, fallback to inline", err);
  16462. this.terminateWorker();
  16463. this.error = null;
  16464. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  16465. }
  16466. return;
  16467. }
  16468. }
  16469. this.transmuxer = new Transmuxer(this.observer, m2tsTypeSupported, config, '', id, _hls.logger);
  16470. }
  16471. var _proto = TransmuxerInterface.prototype;
  16472. _proto.reset = function reset() {
  16473. this.frag = null;
  16474. this.part = null;
  16475. if (this.workerContext) {
  16476. var instanceNo = this.instanceNo;
  16477. this.instanceNo = transmuxerInstanceCount++;
  16478. var config = this.hls.config;
  16479. var m2tsTypeSupported = getM2TSSupportedAudioTypes(config.preferManagedMediaSource);
  16480. this.workerContext.worker.postMessage({
  16481. instanceNo: this.instanceNo,
  16482. cmd: 'reset',
  16483. resetNo: instanceNo,
  16484. typeSupported: m2tsTypeSupported,
  16485. id: this.id,
  16486. config: stringify(config)
  16487. });
  16488. }
  16489. };
  16490. _proto.terminateWorker = function terminateWorker() {
  16491. if (this.workerContext) {
  16492. var worker = this.workerContext.worker;
  16493. this.workerContext = null;
  16494. worker.removeEventListener('message', this.onWorkerMessage);
  16495. worker.removeEventListener('error', this.onWorkerError);
  16496. removeWorkerFromStore(this.hls.config.workerPath);
  16497. }
  16498. };
  16499. _proto.destroy = function destroy() {
  16500. if (this.workerContext) {
  16501. this.terminateWorker();
  16502. // @ts-ignore
  16503. this.onWorkerMessage = this.onWorkerError = null;
  16504. } else {
  16505. var transmuxer = this.transmuxer;
  16506. if (transmuxer) {
  16507. transmuxer.destroy();
  16508. this.transmuxer = null;
  16509. }
  16510. }
  16511. var observer = this.observer;
  16512. if (observer) {
  16513. observer.removeAllListeners();
  16514. }
  16515. this.frag = null;
  16516. this.part = null;
  16517. // @ts-ignore
  16518. this.observer = null;
  16519. // @ts-ignore
  16520. this.hls = null;
  16521. };
  16522. _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
  16523. var _frag$initSegment,
  16524. _lastFrag$initSegment,
  16525. _this2 = this;
  16526. chunkMeta.transmuxing.start = self.performance.now();
  16527. var instanceNo = this.instanceNo,
  16528. transmuxer = this.transmuxer;
  16529. var timeOffset = part ? part.start : frag.start;
  16530. // TODO: push "clear-lead" decrypt data for unencrypted fragments in streams with encrypted ones
  16531. var decryptdata = frag.decryptdata;
  16532. var lastFrag = this.frag;
  16533. var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
  16534. var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
  16535. var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
  16536. var partDiff = this.part ? chunkMeta.part - this.part.index : -1;
  16537. var progressive = snDiff === 0 && chunkMeta.id > 1 && chunkMeta.id === (lastFrag == null ? void 0 : lastFrag.stats.chunkCount);
  16538. var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && (partDiff === 1 || progressive && partDiff <= 0));
  16539. var now = self.performance.now();
  16540. if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
  16541. frag.stats.parsing.start = now;
  16542. }
  16543. if (part && (partDiff || !contiguous)) {
  16544. part.stats.parsing.start = now;
  16545. }
  16546. var initSegmentChange = !(lastFrag && ((_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.url) === ((_lastFrag$initSegment = lastFrag.initSegment) == null ? void 0 : _lastFrag$initSegment.url));
  16547. var state = new TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset, initSegmentChange);
  16548. if (!contiguous || discontinuity || initSegmentChange) {
  16549. this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for " + frag.type + " sn: " + chunkMeta.sn + (chunkMeta.part > -1 ? ' part: ' + chunkMeta.part : '') + " " + (this.id === PlaylistLevelType.MAIN ? 'level' : 'track') + ": " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset + "\n initSegmentChange: " + initSegmentChange);
  16550. var config = new TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
  16551. this.configureTransmuxer(config);
  16552. }
  16553. this.frag = frag;
  16554. this.part = part;
  16555. // Frags with sn of 'initSegment' are not transmuxed
  16556. if (this.workerContext) {
  16557. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  16558. this.workerContext.worker.postMessage({
  16559. instanceNo: instanceNo,
  16560. cmd: 'demux',
  16561. data: data,
  16562. decryptdata: decryptdata,
  16563. chunkMeta: chunkMeta,
  16564. state: state
  16565. }, data instanceof ArrayBuffer ? [data] : []);
  16566. } else if (transmuxer) {
  16567. var transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
  16568. if (isPromise(transmuxResult)) {
  16569. transmuxResult.then(function (data) {
  16570. _this2.handleTransmuxComplete(data);
  16571. }).catch(function (error) {
  16572. _this2.transmuxerError(error, chunkMeta, 'transmuxer-interface push error');
  16573. });
  16574. } else {
  16575. this.handleTransmuxComplete(transmuxResult);
  16576. }
  16577. }
  16578. };
  16579. _proto.flush = function flush(chunkMeta) {
  16580. var _this3 = this;
  16581. chunkMeta.transmuxing.start = self.performance.now();
  16582. var instanceNo = this.instanceNo,
  16583. transmuxer = this.transmuxer;
  16584. if (this.workerContext) {
  16585. this.workerContext.worker.postMessage({
  16586. instanceNo: instanceNo,
  16587. cmd: 'flush',
  16588. chunkMeta: chunkMeta
  16589. });
  16590. } else if (transmuxer) {
  16591. var transmuxResult = transmuxer.flush(chunkMeta);
  16592. if (isPromise(transmuxResult)) {
  16593. transmuxResult.then(function (data) {
  16594. _this3.handleFlushResult(data, chunkMeta);
  16595. }).catch(function (error) {
  16596. _this3.transmuxerError(error, chunkMeta, 'transmuxer-interface flush error');
  16597. });
  16598. } else {
  16599. this.handleFlushResult(transmuxResult, chunkMeta);
  16600. }
  16601. }
  16602. };
  16603. _proto.transmuxerError = function transmuxerError(error, chunkMeta, reason) {
  16604. if (!this.hls) {
  16605. return;
  16606. }
  16607. this.error = error;
  16608. this.hls.trigger(Events.ERROR, {
  16609. type: ErrorTypes.MEDIA_ERROR,
  16610. details: ErrorDetails.FRAG_PARSING_ERROR,
  16611. chunkMeta: chunkMeta,
  16612. frag: this.frag || undefined,
  16613. part: this.part || undefined,
  16614. fatal: false,
  16615. error: error,
  16616. err: error,
  16617. reason: reason
  16618. });
  16619. };
  16620. _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
  16621. var _this4 = this;
  16622. results.forEach(function (result) {
  16623. _this4.handleTransmuxComplete(result);
  16624. });
  16625. this.onFlush(chunkMeta);
  16626. };
  16627. _proto.configureTransmuxer = function configureTransmuxer(config) {
  16628. var instanceNo = this.instanceNo,
  16629. transmuxer = this.transmuxer;
  16630. if (this.workerContext) {
  16631. this.workerContext.worker.postMessage({
  16632. instanceNo: instanceNo,
  16633. cmd: 'configure',
  16634. config: config
  16635. });
  16636. } else if (transmuxer) {
  16637. transmuxer.configure(config);
  16638. }
  16639. };
  16640. _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
  16641. result.chunkMeta.transmuxing.end = self.performance.now();
  16642. this.onTransmuxComplete(result);
  16643. };
  16644. return TransmuxerInterface;
  16645. }();
  16646. var TICK_INTERVAL$3 = 100; // how often to tick in ms
  16647. var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
  16648. function AudioStreamController(hls, fragmentTracker, keyLoader) {
  16649. var _this;
  16650. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, 'audio-stream-controller', PlaylistLevelType.AUDIO) || this;
  16651. _this.mainAnchor = null;
  16652. _this.mainFragLoading = null;
  16653. _this.audioOnly = false;
  16654. _this.bufferedTrack = null;
  16655. _this.switchingTrack = null;
  16656. _this.trackId = -1;
  16657. _this.waitingData = null;
  16658. _this.mainDetails = null;
  16659. _this.flushing = false;
  16660. _this.bufferFlushed = false;
  16661. _this.cachedTrackLoadedData = null;
  16662. _this.registerListeners();
  16663. return _this;
  16664. }
  16665. _inheritsLoose(AudioStreamController, _BaseStreamController);
  16666. var _proto = AudioStreamController.prototype;
  16667. _proto.onHandlerDestroying = function onHandlerDestroying() {
  16668. this.unregisterListeners();
  16669. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  16670. this.resetItem();
  16671. };
  16672. _proto.resetItem = function resetItem() {
  16673. this.mainDetails = this.mainAnchor = this.mainFragLoading = this.bufferedTrack = this.switchingTrack = this.waitingData = this.cachedTrackLoadedData = null;
  16674. };
  16675. _proto.registerListeners = function registerListeners() {
  16676. _BaseStreamController.prototype.registerListeners.call(this);
  16677. var hls = this.hls;
  16678. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16679. hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  16680. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  16681. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16682. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  16683. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  16684. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16685. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  16686. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  16687. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  16688. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16689. };
  16690. _proto.unregisterListeners = function unregisterListeners() {
  16691. var hls = this.hls;
  16692. if (!hls) {
  16693. return;
  16694. }
  16695. _BaseStreamController.prototype.unregisterListeners.call(this);
  16696. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  16697. hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
  16698. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  16699. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  16700. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  16701. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  16702. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  16703. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  16704. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  16705. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  16706. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  16707. }
  16708. // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
  16709. ;
  16710. _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
  16711. var frag = _ref.frag,
  16712. id = _ref.id,
  16713. initPTS = _ref.initPTS,
  16714. timescale = _ref.timescale;
  16715. // Always update the new INIT PTS
  16716. // Can change due level switch
  16717. if (id === PlaylistLevelType.MAIN) {
  16718. var cc = frag.cc;
  16719. var inFlightFrag = this.fragCurrent;
  16720. this.initPTS[cc] = {
  16721. baseTime: initPTS,
  16722. timescale: timescale
  16723. };
  16724. this.log("InitPTS for cc: " + cc + " found from main: " + initPTS + "/" + timescale);
  16725. this.mainAnchor = frag;
  16726. // If we are waiting, tick immediately to unblock audio fragment transmuxing
  16727. if (this.state === State.WAITING_INIT_PTS) {
  16728. var waitingData = this.waitingData;
  16729. if (!waitingData && !this.loadingParts || waitingData && waitingData.frag.cc !== cc) {
  16730. this.syncWithAnchor(frag, waitingData == null ? void 0 : waitingData.frag);
  16731. }
  16732. } else if (!this.hls.hasEnoughToStart && inFlightFrag && inFlightFrag.cc !== cc) {
  16733. inFlightFrag.abortRequests();
  16734. this.syncWithAnchor(frag, inFlightFrag);
  16735. } else if (this.state === State.IDLE) {
  16736. this.tick();
  16737. }
  16738. }
  16739. };
  16740. _proto.getLoadPosition = function getLoadPosition() {
  16741. if (!this.startFragRequested && this.nextLoadPosition >= 0) {
  16742. return this.nextLoadPosition;
  16743. }
  16744. return _BaseStreamController.prototype.getLoadPosition.call(this);
  16745. };
  16746. _proto.syncWithAnchor = function syncWithAnchor(mainAnchor, waitingToAppend) {
  16747. var _this$mainFragLoading;
  16748. // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
  16749. var mainFragLoading = ((_this$mainFragLoading = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading.frag) || null;
  16750. if (waitingToAppend) {
  16751. if ((mainFragLoading == null ? void 0 : mainFragLoading.cc) === waitingToAppend.cc) {
  16752. // Wait for loading frag to complete and INIT_PTS_FOUND
  16753. return;
  16754. }
  16755. }
  16756. var targetDiscontinuity = (mainFragLoading || mainAnchor).cc;
  16757. var trackDetails = this.getLevelDetails();
  16758. var pos = this.getLoadPosition();
  16759. var syncFrag = findNearestWithCC(trackDetails, targetDiscontinuity, pos);
  16760. // Only stop waiting for audioFrag.cc if an audio segment of the same discontinuity domain (cc) is found
  16761. if (syncFrag) {
  16762. this.log("Syncing with main frag at " + syncFrag.start + " cc " + syncFrag.cc);
  16763. this.startFragRequested = false;
  16764. this.nextLoadPosition = syncFrag.start;
  16765. this.resetLoadingState();
  16766. if (this.state === State.IDLE) {
  16767. this.doTickIdle();
  16768. }
  16769. }
  16770. };
  16771. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  16772. if (!this.levels) {
  16773. this.startPosition = startPosition;
  16774. this.state = State.STOPPED;
  16775. return;
  16776. }
  16777. var lastCurrentTime = this.lastCurrentTime;
  16778. this.stopLoad();
  16779. this.setInterval(TICK_INTERVAL$3);
  16780. if (lastCurrentTime > 0 && startPosition === -1) {
  16781. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  16782. startPosition = lastCurrentTime;
  16783. this.state = State.IDLE;
  16784. } else {
  16785. this.state = State.WAITING_TRACK;
  16786. }
  16787. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  16788. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  16789. this.tick();
  16790. };
  16791. _proto.doTick = function doTick() {
  16792. switch (this.state) {
  16793. case State.IDLE:
  16794. this.doTickIdle();
  16795. break;
  16796. case State.WAITING_TRACK:
  16797. {
  16798. var levels = this.levels,
  16799. trackId = this.trackId;
  16800. var currenTrack = levels == null ? void 0 : levels[trackId];
  16801. var details = currenTrack == null ? void 0 : currenTrack.details;
  16802. if (details && !this.waitForLive(currenTrack)) {
  16803. if (this.waitForCdnTuneIn(details)) {
  16804. break;
  16805. }
  16806. this.state = State.WAITING_INIT_PTS;
  16807. }
  16808. break;
  16809. }
  16810. case State.FRAG_LOADING_WAITING_RETRY:
  16811. {
  16812. var _this$media;
  16813. var now = performance.now();
  16814. var retryDate = this.retryDate;
  16815. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  16816. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  16817. var _levels = this.levels,
  16818. _trackId = this.trackId;
  16819. this.log('RetryDate reached, switch back to IDLE state');
  16820. this.resetStartWhenNotLoaded((_levels == null ? void 0 : _levels[_trackId]) || null);
  16821. this.state = State.IDLE;
  16822. }
  16823. break;
  16824. }
  16825. case State.WAITING_INIT_PTS:
  16826. {
  16827. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  16828. var waitingData = this.waitingData;
  16829. if (waitingData) {
  16830. var frag = waitingData.frag,
  16831. part = waitingData.part,
  16832. cache = waitingData.cache,
  16833. complete = waitingData.complete;
  16834. var mainAnchor = this.mainAnchor;
  16835. if (this.initPTS[frag.cc] !== undefined) {
  16836. this.waitingData = null;
  16837. this.state = State.FRAG_LOADING;
  16838. var payload = cache.flush().buffer;
  16839. var data = {
  16840. frag: frag,
  16841. part: part,
  16842. payload: payload,
  16843. networkDetails: null
  16844. };
  16845. this._handleFragmentLoadProgress(data);
  16846. if (complete) {
  16847. _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);
  16848. }
  16849. } else if (mainAnchor && mainAnchor.cc !== waitingData.frag.cc) {
  16850. this.syncWithAnchor(mainAnchor, waitingData.frag);
  16851. }
  16852. } else {
  16853. this.state = State.IDLE;
  16854. }
  16855. }
  16856. }
  16857. this.onTickEnd();
  16858. };
  16859. _proto.resetLoadingState = function resetLoadingState() {
  16860. var waitingData = this.waitingData;
  16861. if (waitingData) {
  16862. this.fragmentTracker.removeFragment(waitingData.frag);
  16863. this.waitingData = null;
  16864. }
  16865. _BaseStreamController.prototype.resetLoadingState.call(this);
  16866. };
  16867. _proto.onTickEnd = function onTickEnd() {
  16868. var media = this.media;
  16869. if (!(media != null && media.readyState)) {
  16870. // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
  16871. return;
  16872. }
  16873. this.lastCurrentTime = media.currentTime;
  16874. };
  16875. _proto.doTickIdle = function doTickIdle() {
  16876. var _this$mainFragLoading2;
  16877. var hls = this.hls,
  16878. levels = this.levels,
  16879. media = this.media,
  16880. trackId = this.trackId;
  16881. var config = hls.config;
  16882. // 1. if buffering is suspended
  16883. // 2. if video not attached AND
  16884. // start fragment already requested OR start frag prefetch not enabled
  16885. // 3. if tracks or track not loaded and selected
  16886. // then exit loop
  16887. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  16888. if (!this.buffering || !media && !this.primaryPrefetch && (this.startFragRequested || !config.startFragPrefetch) || !(levels != null && levels[trackId])) {
  16889. return;
  16890. }
  16891. var levelInfo = levels[trackId];
  16892. var trackDetails = levelInfo.details;
  16893. if (!trackDetails || this.waitForLive(levelInfo) || this.waitForCdnTuneIn(trackDetails)) {
  16894. this.state = State.WAITING_TRACK;
  16895. this.startFragRequested = false;
  16896. return;
  16897. }
  16898. var bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;
  16899. if (this.bufferFlushed && bufferable) {
  16900. this.bufferFlushed = false;
  16901. this.afterBufferFlushed(bufferable, ElementaryStreamTypes.AUDIO, PlaylistLevelType.AUDIO);
  16902. }
  16903. var bufferInfo = this.getFwdBufferInfo(bufferable, PlaylistLevelType.AUDIO);
  16904. if (bufferInfo === null) {
  16905. return;
  16906. }
  16907. if (!this.switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {
  16908. hls.trigger(Events.BUFFER_EOS, {
  16909. type: 'audio'
  16910. });
  16911. this.state = State.ENDED;
  16912. return;
  16913. }
  16914. var bufferLen = bufferInfo.len;
  16915. var maxBufLen = hls.maxBufferLength;
  16916. var fragments = trackDetails.fragments;
  16917. var start = fragments[0].start;
  16918. var loadPosition = this.getLoadPosition();
  16919. var targetBufferTime = this.flushing ? loadPosition : bufferInfo.end;
  16920. if (this.switchingTrack && media) {
  16921. var pos = loadPosition;
  16922. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  16923. if (trackDetails.PTSKnown && pos < start) {
  16924. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  16925. if (bufferInfo.end > start || bufferInfo.nextStart) {
  16926. this.log('Alt audio track ahead of main track, seek to start of alt audio track');
  16927. media.currentTime = start + 0.05;
  16928. }
  16929. }
  16930. }
  16931. // if buffer length is less than maxBufLen, or near the end, find a fragment to load
  16932. if (bufferLen >= maxBufLen && !this.switchingTrack && targetBufferTime < fragments[fragments.length - 1].start) {
  16933. return;
  16934. }
  16935. var frag = this.getNextFragment(targetBufferTime, trackDetails);
  16936. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  16937. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  16938. frag = this.getNextFragmentLoopLoading(frag, trackDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  16939. }
  16940. if (!frag) {
  16941. this.bufferFlushed = true;
  16942. return;
  16943. }
  16944. // Request audio segments up to one fragment ahead of main stream-controller
  16945. var mainFragLoading = ((_this$mainFragLoading2 = this.mainFragLoading) == null ? void 0 : _this$mainFragLoading2.frag) || null;
  16946. if (!this.audioOnly && this.startFragRequested && mainFragLoading && isMediaFragment(frag) && !frag.endList && (!trackDetails.live || !this.loadingParts && targetBufferTime < this.hls.liveSyncPosition)) {
  16947. if (this.fragmentTracker.getState(mainFragLoading) === FragmentState.OK) {
  16948. this.mainFragLoading = mainFragLoading = null;
  16949. }
  16950. if (mainFragLoading && isMediaFragment(mainFragLoading)) {
  16951. if (frag.start > mainFragLoading.end) {
  16952. // Get buffered frag at target position from tracker (loaded out of sequence)
  16953. var mainFragAtPos = this.fragmentTracker.getFragAtPos(targetBufferTime, PlaylistLevelType.MAIN);
  16954. if (mainFragAtPos && mainFragAtPos.end > mainFragLoading.end) {
  16955. mainFragLoading = mainFragAtPos;
  16956. this.mainFragLoading = {
  16957. frag: mainFragAtPos,
  16958. targetBufferTime: null
  16959. };
  16960. }
  16961. }
  16962. var atBufferSyncLimit = frag.start > mainFragLoading.end;
  16963. if (atBufferSyncLimit) {
  16964. return;
  16965. }
  16966. }
  16967. }
  16968. this.loadFragment(frag, levelInfo, targetBufferTime);
  16969. };
  16970. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  16971. this.bufferFlushed = this.flushing = false;
  16972. _BaseStreamController.prototype.onMediaDetaching.call(this, event, data);
  16973. };
  16974. _proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {
  16975. var audioTracks = _ref2.audioTracks;
  16976. // Reset tranxmuxer is essential for large context switches (Content Steering)
  16977. this.resetTransmuxer();
  16978. this.levels = audioTracks.map(function (mediaPlaylist) {
  16979. return new Level(mediaPlaylist);
  16980. });
  16981. };
  16982. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  16983. // if any URL found on new audio track, it is an alternate audio track
  16984. var altAudio = !!data.url;
  16985. this.trackId = data.id;
  16986. var fragCurrent = this.fragCurrent;
  16987. if (fragCurrent) {
  16988. fragCurrent.abortRequests();
  16989. this.removeUnbufferedFrags(fragCurrent.start);
  16990. }
  16991. this.resetLoadingState();
  16992. // should we switch tracks ?
  16993. if (altAudio) {
  16994. this.switchingTrack = data;
  16995. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  16996. this.flushAudioIfNeeded(data);
  16997. if (this.state !== State.STOPPED) {
  16998. // switching to audio track, start timer if not already started
  16999. this.setInterval(TICK_INTERVAL$3);
  17000. this.state = State.IDLE;
  17001. this.tick();
  17002. }
  17003. } else {
  17004. // destroy useless transmuxer when switching audio to main
  17005. this.resetTransmuxer();
  17006. this.switchingTrack = null;
  17007. this.bufferedTrack = data;
  17008. this.clearInterval();
  17009. }
  17010. };
  17011. _proto.onManifestLoading = function onManifestLoading() {
  17012. _BaseStreamController.prototype.onManifestLoading.call(this);
  17013. this.bufferFlushed = this.flushing = this.audioOnly = false;
  17014. this.resetItem();
  17015. this.trackId = -1;
  17016. };
  17017. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  17018. this.mainDetails = data.details;
  17019. var cachedTrackLoadedData = this.cachedTrackLoadedData;
  17020. if (cachedTrackLoadedData) {
  17021. this.cachedTrackLoadedData = null;
  17022. this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED, cachedTrackLoadedData);
  17023. }
  17024. };
  17025. _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
  17026. var _trackLevel$details;
  17027. var levels = this.levels;
  17028. var newDetails = data.details,
  17029. trackId = data.id,
  17030. groupId = data.groupId,
  17031. track = data.track;
  17032. if (!levels) {
  17033. this.warn("Audio tracks reset while loading track " + trackId + " \"" + track.name + "\" of \"" + groupId + "\"");
  17034. return;
  17035. }
  17036. var mainDetails = this.mainDetails;
  17037. if (!mainDetails || newDetails.endCC > mainDetails.endCC || mainDetails.expired) {
  17038. this.cachedTrackLoadedData = data;
  17039. if (this.state !== State.STOPPED) {
  17040. this.state = State.WAITING_TRACK;
  17041. }
  17042. return;
  17043. }
  17044. this.cachedTrackLoadedData = null;
  17045. this.log("Audio track " + trackId + " \"" + track.name + "\" of \"" + groupId + "\" loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ",duration:" + newDetails.totalduration);
  17046. var trackLevel = levels[trackId];
  17047. var sliding = 0;
  17048. if (newDetails.live || (_trackLevel$details = trackLevel.details) != null && _trackLevel$details.live) {
  17049. this.checkLiveUpdate(newDetails);
  17050. if (newDetails.deltaUpdateFailed) {
  17051. return;
  17052. }
  17053. if (trackLevel.details) {
  17054. var _this$levelLastLoaded;
  17055. sliding = this.alignPlaylists(newDetails, trackLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  17056. }
  17057. if (!newDetails.alignedSliding) {
  17058. // Align audio rendition with the "main" playlist on discontinuity change
  17059. // or program-date-time (PDT)
  17060. alignDiscontinuities(newDetails, mainDetails);
  17061. if (!newDetails.alignedSliding) {
  17062. alignMediaPlaylistByPDT(newDetails, mainDetails);
  17063. }
  17064. sliding = newDetails.fragmentStart;
  17065. }
  17066. }
  17067. trackLevel.details = newDetails;
  17068. this.levelLastLoaded = trackLevel;
  17069. // compute start position if we are aligned with the main playlist
  17070. if (!this.startFragRequested) {
  17071. this.setStartPosition(mainDetails, sliding);
  17072. }
  17073. this.hls.trigger(Events.AUDIO_TRACK_UPDATED, {
  17074. details: newDetails,
  17075. id: trackId,
  17076. groupId: data.groupId
  17077. });
  17078. // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
  17079. if (this.state === State.WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
  17080. this.state = State.IDLE;
  17081. }
  17082. // trigger handler right now
  17083. this.tick();
  17084. };
  17085. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  17086. var _frag$initSegment;
  17087. var frag = data.frag;
  17088. var part = data.part,
  17089. payload = data.payload;
  17090. var config = this.config,
  17091. trackId = this.trackId,
  17092. levels = this.levels;
  17093. if (!levels) {
  17094. this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  17095. return;
  17096. }
  17097. var track = levels[trackId];
  17098. if (!track) {
  17099. this.warn('Audio track is undefined on fragment load progress');
  17100. return;
  17101. }
  17102. var details = track.details;
  17103. if (!details) {
  17104. this.warn('Audio track details undefined on fragment load progress');
  17105. this.removeUnbufferedFrags(frag.start);
  17106. return;
  17107. }
  17108. var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
  17109. var transmuxer = this.transmuxer;
  17110. if (!transmuxer) {
  17111. transmuxer = this.transmuxer = new TransmuxerInterface(this.hls, PlaylistLevelType.AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  17112. }
  17113. // Check if we have video initPTS
  17114. // If not we need to wait for it
  17115. var initPTS = this.initPTS[frag.cc];
  17116. var initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  17117. if (initPTS !== undefined) {
  17118. // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
  17119. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  17120. var accurateTimeOffset = false; // details.PTSKnown || !details.live;
  17121. var partIndex = part ? part.index : -1;
  17122. var partial = partIndex !== -1;
  17123. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  17124. transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  17125. } else {
  17126. this.log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
  17127. var _this$waitingData = this.waitingData = this.waitingData || {
  17128. frag: frag,
  17129. part: part,
  17130. cache: new ChunkCache(),
  17131. complete: false
  17132. },
  17133. cache = _this$waitingData.cache;
  17134. cache.push(new Uint8Array(payload));
  17135. if (this.state !== State.STOPPED) {
  17136. this.state = State.WAITING_INIT_PTS;
  17137. }
  17138. }
  17139. };
  17140. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
  17141. if (this.waitingData) {
  17142. this.waitingData.complete = true;
  17143. return;
  17144. }
  17145. _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);
  17146. };
  17147. _proto.onBufferReset = function onBufferReset(/* event: Events.BUFFER_RESET */
  17148. ) {
  17149. // reset reference to sourcebuffers
  17150. this.mediaBuffer = null;
  17151. };
  17152. _proto.onBufferCreated = function onBufferCreated(event, data) {
  17153. this.bufferFlushed = this.flushing = false;
  17154. var audioTrack = data.tracks.audio;
  17155. if (audioTrack) {
  17156. this.mediaBuffer = audioTrack.buffer || null;
  17157. }
  17158. };
  17159. _proto.onFragLoading = function onFragLoading(event, data) {
  17160. if (!this.audioOnly && data.frag.type === PlaylistLevelType.MAIN && isMediaFragment(data.frag)) {
  17161. this.mainFragLoading = data;
  17162. if (this.state === State.IDLE) {
  17163. this.tick();
  17164. }
  17165. }
  17166. };
  17167. _proto.onFragBuffered = function onFragBuffered(event, data) {
  17168. var frag = data.frag,
  17169. part = data.part;
  17170. if (frag.type !== PlaylistLevelType.AUDIO) {
  17171. if (!this.audioOnly && frag.type === PlaylistLevelType.MAIN && !frag.elementaryStreams.video && !frag.elementaryStreams.audiovideo) {
  17172. this.audioOnly = true;
  17173. this.mainFragLoading = null;
  17174. }
  17175. return;
  17176. }
  17177. if (this.fragContextChanged(frag)) {
  17178. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  17179. // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
  17180. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + (this.switchingTrack ? this.switchingTrack.name : 'false'));
  17181. return;
  17182. }
  17183. if (isMediaFragment(frag)) {
  17184. this.fragPrevious = frag;
  17185. var track = this.switchingTrack;
  17186. if (track) {
  17187. this.bufferedTrack = track;
  17188. this.switchingTrack = null;
  17189. this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, track));
  17190. }
  17191. }
  17192. this.fragBufferedComplete(frag, part);
  17193. if (this.media) {
  17194. this.tick();
  17195. }
  17196. };
  17197. _proto.onError = function onError(event, data) {
  17198. var _data$context;
  17199. if (data.fatal) {
  17200. this.state = State.ERROR;
  17201. return;
  17202. }
  17203. switch (data.details) {
  17204. case ErrorDetails.FRAG_GAP:
  17205. case ErrorDetails.FRAG_PARSING_ERROR:
  17206. case ErrorDetails.FRAG_DECRYPT_ERROR:
  17207. case ErrorDetails.FRAG_LOAD_ERROR:
  17208. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  17209. case ErrorDetails.KEY_LOAD_ERROR:
  17210. case ErrorDetails.KEY_LOAD_TIMEOUT:
  17211. this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);
  17212. break;
  17213. case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  17214. case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  17215. case ErrorDetails.LEVEL_PARSING_ERROR:
  17216. // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE
  17217. if (!data.levelRetry && this.state === State.WAITING_TRACK && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.AUDIO_TRACK) {
  17218. this.state = State.IDLE;
  17219. }
  17220. break;
  17221. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  17222. case ErrorDetails.BUFFER_APPEND_ERROR:
  17223. if (data.parent !== 'audio') {
  17224. return;
  17225. }
  17226. if (!this.reduceLengthAndFlushBuffer(data)) {
  17227. this.resetLoadingState();
  17228. }
  17229. break;
  17230. case ErrorDetails.BUFFER_FULL_ERROR:
  17231. if (data.parent !== 'audio') {
  17232. return;
  17233. }
  17234. if (this.reduceLengthAndFlushBuffer(data)) {
  17235. this.bufferedTrack = null;
  17236. _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
  17237. }
  17238. break;
  17239. case ErrorDetails.INTERNAL_EXCEPTION:
  17240. this.recoverWorkerError(data);
  17241. break;
  17242. }
  17243. };
  17244. _proto.onBufferFlushing = function onBufferFlushing(event, _ref3) {
  17245. var type = _ref3.type;
  17246. if (type !== ElementaryStreamTypes.VIDEO) {
  17247. this.flushing = true;
  17248. }
  17249. };
  17250. _proto.onBufferFlushed = function onBufferFlushed(event, _ref4) {
  17251. var type = _ref4.type;
  17252. if (type !== ElementaryStreamTypes.VIDEO) {
  17253. this.flushing = false;
  17254. this.bufferFlushed = true;
  17255. if (this.state === State.ENDED) {
  17256. this.state = State.IDLE;
  17257. }
  17258. var mediaBuffer = this.mediaBuffer || this.media;
  17259. if (mediaBuffer) {
  17260. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.AUDIO);
  17261. this.tick();
  17262. }
  17263. }
  17264. };
  17265. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  17266. var _id3$samples;
  17267. var id = 'audio';
  17268. var hls = this.hls;
  17269. var remuxResult = transmuxResult.remuxResult,
  17270. chunkMeta = transmuxResult.chunkMeta;
  17271. var context = this.getCurrentContext(chunkMeta);
  17272. if (!context) {
  17273. this.resetWhenMissingContext(chunkMeta);
  17274. return;
  17275. }
  17276. var frag = context.frag,
  17277. part = context.part,
  17278. level = context.level;
  17279. var details = level.details;
  17280. var audio = remuxResult.audio,
  17281. text = remuxResult.text,
  17282. id3 = remuxResult.id3,
  17283. initSegment = remuxResult.initSegment;
  17284. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  17285. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  17286. if (this.fragContextChanged(frag) || !details) {
  17287. this.fragmentTracker.removeFragment(frag);
  17288. return;
  17289. }
  17290. this.state = State.PARSING;
  17291. if (this.switchingTrack && audio) {
  17292. this.completeAudioSwitch(this.switchingTrack);
  17293. }
  17294. if (initSegment != null && initSegment.tracks) {
  17295. var mapFragment = frag.initSegment || frag;
  17296. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  17297. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  17298. frag: mapFragment,
  17299. id: id,
  17300. tracks: initSegment.tracks
  17301. });
  17302. // Only flush audio from old audio tracks when PTS is known on new audio track
  17303. }
  17304. if (audio) {
  17305. var startPTS = audio.startPTS,
  17306. endPTS = audio.endPTS,
  17307. startDTS = audio.startDTS,
  17308. endDTS = audio.endDTS;
  17309. if (part) {
  17310. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  17311. startPTS: startPTS,
  17312. endPTS: endPTS,
  17313. startDTS: startDTS,
  17314. endDTS: endDTS
  17315. };
  17316. }
  17317. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, startPTS, endPTS, startDTS, endDTS);
  17318. this.bufferFragmentData(audio, frag, part, chunkMeta);
  17319. }
  17320. if (id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  17321. var emittedID3 = _extends({
  17322. id: id,
  17323. frag: frag,
  17324. details: details
  17325. }, id3);
  17326. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  17327. }
  17328. if (text) {
  17329. var emittedText = _extends({
  17330. id: id,
  17331. frag: frag,
  17332. details: details
  17333. }, text);
  17334. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  17335. }
  17336. };
  17337. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  17338. if (this.state !== State.PARSING) {
  17339. return;
  17340. }
  17341. // delete any video track found on audio transmuxer
  17342. if (tracks.video) {
  17343. delete tracks.video;
  17344. }
  17345. if (tracks.audiovideo) {
  17346. delete tracks.audiovideo;
  17347. }
  17348. // include levelCodec in audio and video tracks
  17349. if (!tracks.audio) {
  17350. return;
  17351. }
  17352. var track = tracks.audio;
  17353. track.id = PlaylistLevelType.AUDIO;
  17354. var variantAudioCodecs = currentLevel.audioCodec;
  17355. this.log("Init audio buffer, container:" + track.container + ", codecs[level/parsed]=[" + variantAudioCodecs + "/" + track.codec + "]");
  17356. // SourceBuffer will use track.levelCodec if defined
  17357. if (variantAudioCodecs && variantAudioCodecs.split(',').length === 1) {
  17358. track.levelCodec = variantAudioCodecs;
  17359. }
  17360. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  17361. var initSegment = track.initSegment;
  17362. if (initSegment != null && initSegment.byteLength) {
  17363. var segment = {
  17364. type: 'audio',
  17365. frag: frag,
  17366. part: null,
  17367. chunkMeta: chunkMeta,
  17368. parent: frag.type,
  17369. data: initSegment
  17370. };
  17371. this.hls.trigger(Events.BUFFER_APPENDING, segment);
  17372. }
  17373. // trigger handler right now
  17374. this.tickImmediate();
  17375. };
  17376. _proto.loadFragment = function loadFragment(frag, track, targetBufferTime) {
  17377. // only load if fragment is not loaded or if in audio switch
  17378. var fragState = this.fragmentTracker.getState(frag);
  17379. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  17380. if (this.switchingTrack || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  17381. var _track$details;
  17382. if (!isMediaFragment(frag)) {
  17383. this._loadInitSegment(frag, track);
  17384. } else if ((_track$details = track.details) != null && _track$details.live && !this.initPTS[frag.cc]) {
  17385. this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId);
  17386. this.state = State.WAITING_INIT_PTS;
  17387. var mainDetails = this.mainDetails;
  17388. if (mainDetails && mainDetails.fragmentStart !== track.details.fragmentStart) {
  17389. alignMediaPlaylistByPDT(track.details, mainDetails);
  17390. }
  17391. } else {
  17392. _BaseStreamController.prototype.loadFragment.call(this, frag, track, targetBufferTime);
  17393. }
  17394. } else {
  17395. this.clearTrackerIfNeeded(frag);
  17396. }
  17397. };
  17398. _proto.flushAudioIfNeeded = function flushAudioIfNeeded(switchingTrack) {
  17399. if (this.media && this.bufferedTrack) {
  17400. var _this$bufferedTrack = this.bufferedTrack,
  17401. name = _this$bufferedTrack.name,
  17402. lang = _this$bufferedTrack.lang,
  17403. assocLang = _this$bufferedTrack.assocLang,
  17404. characteristics = _this$bufferedTrack.characteristics,
  17405. audioCodec = _this$bufferedTrack.audioCodec,
  17406. channels = _this$bufferedTrack.channels;
  17407. if (!matchesOption({
  17408. name: name,
  17409. lang: lang,
  17410. assocLang: assocLang,
  17411. characteristics: characteristics,
  17412. audioCodec: audioCodec,
  17413. channels: channels
  17414. }, switchingTrack, audioMatchPredicate)) {
  17415. if (useAlternateAudio(switchingTrack.url, this.hls)) {
  17416. this.log('Switching audio track : flushing all audio');
  17417. _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
  17418. this.bufferedTrack = null;
  17419. } else {
  17420. // Main is being buffered. Set bufferedTrack so that it is flushed when switching back to alt-audio
  17421. this.bufferedTrack = switchingTrack;
  17422. }
  17423. }
  17424. }
  17425. };
  17426. _proto.completeAudioSwitch = function completeAudioSwitch(switchingTrack) {
  17427. var hls = this.hls;
  17428. this.flushAudioIfNeeded(switchingTrack);
  17429. this.bufferedTrack = switchingTrack;
  17430. this.switchingTrack = null;
  17431. hls.trigger(Events.AUDIO_TRACK_SWITCHED, _objectSpread2({}, switchingTrack));
  17432. };
  17433. return AudioStreamController;
  17434. }(BaseStreamController);
  17435. var BasePlaylistController = /*#__PURE__*/function (_Logger) {
  17436. function BasePlaylistController(hls, logPrefix) {
  17437. var _this;
  17438. _this = _Logger.call(this, logPrefix, hls.logger) || this;
  17439. _this.hls = void 0;
  17440. _this.canLoad = false;
  17441. _this.timer = -1;
  17442. _this.hls = hls;
  17443. return _this;
  17444. }
  17445. _inheritsLoose(BasePlaylistController, _Logger);
  17446. var _proto = BasePlaylistController.prototype;
  17447. _proto.destroy = function destroy() {
  17448. this.clearTimer();
  17449. // @ts-ignore
  17450. this.hls = this.log = this.warn = null;
  17451. };
  17452. _proto.clearTimer = function clearTimer() {
  17453. if (this.timer !== -1) {
  17454. self.clearTimeout(this.timer);
  17455. this.timer = -1;
  17456. }
  17457. };
  17458. _proto.startLoad = function startLoad() {
  17459. this.canLoad = true;
  17460. this.loadPlaylist();
  17461. };
  17462. _proto.stopLoad = function stopLoad() {
  17463. this.canLoad = false;
  17464. this.clearTimer();
  17465. };
  17466. _proto.switchParams = function switchParams(playlistUri, previous, current) {
  17467. var renditionReports = previous == null ? void 0 : previous.renditionReports;
  17468. if (renditionReports) {
  17469. var foundIndex = -1;
  17470. for (var i = 0; i < renditionReports.length; i++) {
  17471. var attr = renditionReports[i];
  17472. var uri = void 0;
  17473. try {
  17474. uri = new self.URL(attr.URI, previous.url).href;
  17475. } catch (error) {
  17476. this.warn("Could not construct new URL for Rendition Report: " + error);
  17477. uri = attr.URI || '';
  17478. }
  17479. // Use exact match. Otherwise, the last partial match, if any, will be used
  17480. // (Playlist URI includes a query string that the Rendition Report does not)
  17481. if (uri === playlistUri) {
  17482. foundIndex = i;
  17483. break;
  17484. } else if (uri === playlistUri.substring(0, uri.length)) {
  17485. foundIndex = i;
  17486. }
  17487. }
  17488. if (foundIndex !== -1) {
  17489. var _attr = renditionReports[foundIndex];
  17490. var msn = parseInt(_attr['LAST-MSN']) || (previous == null ? void 0 : previous.lastPartSn);
  17491. var part = parseInt(_attr['LAST-PART']) || (previous == null ? void 0 : previous.lastPartIndex);
  17492. if (this.hls.config.lowLatencyMode) {
  17493. var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
  17494. if (part >= 0 && currentGoal > previous.partTarget) {
  17495. part += 1;
  17496. }
  17497. }
  17498. var skip = current && getSkipValue(current);
  17499. return new HlsUrlParameters(msn, part >= 0 ? part : undefined, skip);
  17500. }
  17501. }
  17502. };
  17503. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  17504. // Loading is handled by the subclasses
  17505. this.clearTimer();
  17506. };
  17507. _proto.loadingPlaylist = function loadingPlaylist(playlist, hlsUrlParameters) {
  17508. // Loading is handled by the subclasses
  17509. this.clearTimer();
  17510. };
  17511. _proto.shouldLoadPlaylist = function shouldLoadPlaylist(playlist) {
  17512. return this.canLoad && !!playlist && !!playlist.url && (!playlist.details || playlist.details.live);
  17513. };
  17514. _proto.getUrlWithDirectives = function getUrlWithDirectives(uri, hlsUrlParameters) {
  17515. if (hlsUrlParameters) {
  17516. try {
  17517. return hlsUrlParameters.addDirectives(uri);
  17518. } catch (error) {
  17519. this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
  17520. }
  17521. }
  17522. return uri;
  17523. };
  17524. _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
  17525. var details = data.details,
  17526. stats = data.stats;
  17527. // Set last updated date-time
  17528. var now = self.performance.now();
  17529. var elapsed = stats.loading.first ? Math.max(0, now - stats.loading.first) : 0;
  17530. details.advancedDateTime = Date.now() - elapsed;
  17531. // shift fragment starts with timelineOffset
  17532. var timelineOffset = this.hls.config.timelineOffset;
  17533. if (timelineOffset !== details.appliedTimelineOffset) {
  17534. var offset = Math.max(timelineOffset || 0, 0);
  17535. details.appliedTimelineOffset = offset;
  17536. details.fragments.forEach(function (frag) {
  17537. frag.start = frag.playlistOffset + offset;
  17538. });
  17539. }
  17540. // if current playlist is a live playlist, arm a timer to reload it
  17541. if (details.live || previousDetails != null && previousDetails.live) {
  17542. var levelOrTrack = 'levelInfo' in data ? data.levelInfo : data.track;
  17543. details.reloaded(previousDetails);
  17544. // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
  17545. if (previousDetails && details.fragments.length > 0) {
  17546. mergeDetails(previousDetails, details);
  17547. var error = details.playlistParsingError;
  17548. if (error) {
  17549. this.warn(error);
  17550. var hls = this.hls;
  17551. if (!hls.config.ignorePlaylistParsingErrors) {
  17552. var _details$fragments$;
  17553. var networkDetails = data.networkDetails;
  17554. hls.trigger(Events.ERROR, {
  17555. type: ErrorTypes.NETWORK_ERROR,
  17556. details: ErrorDetails.LEVEL_PARSING_ERROR,
  17557. fatal: false,
  17558. url: details.url,
  17559. error: error,
  17560. reason: error.message,
  17561. level: data.level || undefined,
  17562. parent: (_details$fragments$ = details.fragments[0]) == null ? void 0 : _details$fragments$.type,
  17563. networkDetails: networkDetails,
  17564. stats: stats
  17565. });
  17566. return;
  17567. }
  17568. details.playlistParsingError = null;
  17569. }
  17570. }
  17571. if (details.requestScheduled === -1) {
  17572. details.requestScheduled = stats.loading.start;
  17573. }
  17574. var bufferInfo = this.hls.mainForwardBufferInfo;
  17575. var position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;
  17576. var distanceToLiveEdgeMs = (details.edge - position) * 1000;
  17577. var reloadInterval = computeReloadInterval(details, distanceToLiveEdgeMs);
  17578. if (details.requestScheduled + reloadInterval < now) {
  17579. details.requestScheduled = now;
  17580. } else {
  17581. details.requestScheduled += reloadInterval;
  17582. }
  17583. this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : details.updated ? 'UPDATED' : 'MISSED'));
  17584. if (!this.canLoad || !details.live) {
  17585. return;
  17586. }
  17587. var deliveryDirectives;
  17588. var msn = undefined;
  17589. var part = undefined;
  17590. if (details.canBlockReload && details.endSN && details.advanced) {
  17591. // Load level with LL-HLS delivery directives
  17592. var lowLatencyMode = this.hls.config.lowLatencyMode;
  17593. var lastPartSn = details.lastPartSn;
  17594. var endSn = details.endSN;
  17595. var lastPartIndex = details.lastPartIndex;
  17596. var hasParts = lastPartIndex !== -1;
  17597. var atLastPartOfSegment = lastPartSn === endSn;
  17598. if (hasParts) {
  17599. // When low latency mode is disabled, request the last part of the next segment
  17600. if (atLastPartOfSegment) {
  17601. msn = endSn + 1;
  17602. part = lowLatencyMode ? 0 : lastPartIndex;
  17603. } else {
  17604. msn = lastPartSn;
  17605. part = lowLatencyMode ? lastPartIndex + 1 : details.maxPartIndex;
  17606. }
  17607. } else {
  17608. msn = endSn + 1;
  17609. }
  17610. // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
  17611. // Update directives to obtain the Playlist that has the estimated additional duration of media
  17612. var lastAdvanced = details.age;
  17613. var cdnAge = lastAdvanced + details.ageHeader;
  17614. var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
  17615. if (currentGoal > 0) {
  17616. if (cdnAge > details.targetduration * 3) {
  17617. // Omit segment and part directives when the last response was more than 3 target durations ago,
  17618. this.log("Playlist last advanced " + lastAdvanced.toFixed(2) + "s ago. Omitting segment and part directives.");
  17619. msn = undefined;
  17620. part = undefined;
  17621. } else if (previousDetails != null && previousDetails.tuneInGoal && cdnAge - details.partTarget > previousDetails.tuneInGoal) {
  17622. // If we attempted to get the next or latest playlist update, but currentGoal increased,
  17623. // then we either can't catchup, or the "age" header cannot be trusted.
  17624. this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
  17625. currentGoal = 0;
  17626. } else {
  17627. var segments = Math.floor(currentGoal / details.targetduration);
  17628. msn += segments;
  17629. if (part !== undefined) {
  17630. var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
  17631. part += parts;
  17632. }
  17633. this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
  17634. }
  17635. details.tuneInGoal = currentGoal;
  17636. }
  17637. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  17638. if (lowLatencyMode || !atLastPartOfSegment) {
  17639. details.requestScheduled = now;
  17640. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17641. return;
  17642. }
  17643. } else if (details.canBlockReload || details.canSkipUntil) {
  17644. deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
  17645. }
  17646. if (deliveryDirectives && msn !== undefined && details.canBlockReload) {
  17647. details.requestScheduled = stats.loading.first + Math.max(reloadInterval - elapsed * 2, reloadInterval / 2);
  17648. }
  17649. this.scheduleLoading(levelOrTrack, deliveryDirectives, details);
  17650. } else {
  17651. this.clearTimer();
  17652. }
  17653. };
  17654. _proto.scheduleLoading = function scheduleLoading(levelOrTrack, deliveryDirectives, updatedDetails) {
  17655. var _this2 = this;
  17656. var details = updatedDetails || levelOrTrack.details;
  17657. if (!details) {
  17658. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17659. return;
  17660. }
  17661. var now = self.performance.now();
  17662. var requestScheduled = details.requestScheduled;
  17663. if (now >= requestScheduled) {
  17664. this.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17665. return;
  17666. }
  17667. var estimatedTimeUntilUpdate = requestScheduled - now;
  17668. this.log("reload live playlist " + (levelOrTrack.name || levelOrTrack.bitrate + 'bps') + " in " + Math.round(estimatedTimeUntilUpdate) + " ms");
  17669. this.clearTimer();
  17670. this.timer = self.setTimeout(function () {
  17671. return _this2.loadingPlaylist(levelOrTrack, deliveryDirectives);
  17672. }, estimatedTimeUntilUpdate);
  17673. };
  17674. _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
  17675. var skip = getSkipValue(details);
  17676. if (previousDeliveryDirectives != null && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
  17677. msn = previousDeliveryDirectives.msn;
  17678. part = previousDeliveryDirectives.part;
  17679. skip = HlsSkip.No;
  17680. }
  17681. return new HlsUrlParameters(msn, part, skip);
  17682. };
  17683. _proto.checkRetry = function checkRetry(errorEvent) {
  17684. var _this3 = this;
  17685. var errorDetails = errorEvent.details;
  17686. var isTimeout = isTimeoutError(errorEvent);
  17687. var errorAction = errorEvent.errorAction;
  17688. var _ref = errorAction || {},
  17689. action = _ref.action,
  17690. _ref$retryCount = _ref.retryCount,
  17691. retryCount = _ref$retryCount === void 0 ? 0 : _ref$retryCount,
  17692. retryConfig = _ref.retryConfig;
  17693. var retry = !!errorAction && !!retryConfig && (action === NetworkErrorAction.RetryRequest || !errorAction.resolved && action === NetworkErrorAction.SendAlternateToPenaltyBox);
  17694. if (retry) {
  17695. var _errorEvent$context;
  17696. if (retryCount >= retryConfig.maxNumRetry) {
  17697. return false;
  17698. }
  17699. if (isTimeout && (_errorEvent$context = errorEvent.context) != null && _errorEvent$context.deliveryDirectives) {
  17700. // The LL-HLS request already timed out so retry immediately
  17701. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" without delivery-directives");
  17702. this.loadPlaylist();
  17703. } else {
  17704. var delay = getRetryDelay(retryConfig, retryCount);
  17705. // Schedule level/track reload
  17706. this.clearTimer();
  17707. this.timer = self.setTimeout(function () {
  17708. return _this3.loadPlaylist();
  17709. }, delay);
  17710. this.warn("Retrying playlist loading " + (retryCount + 1) + "/" + retryConfig.maxNumRetry + " after \"" + errorDetails + "\" in " + delay + "ms");
  17711. }
  17712. // `levelRetry = true` used to inform other controllers that a retry is happening
  17713. errorEvent.levelRetry = true;
  17714. errorAction.resolved = true;
  17715. }
  17716. return retry;
  17717. };
  17718. return BasePlaylistController;
  17719. }(Logger);
  17720. function subtitleOptionsIdentical(trackList1, trackList2) {
  17721. if (trackList1.length !== trackList2.length) {
  17722. return false;
  17723. }
  17724. for (var i = 0; i < trackList1.length; i++) {
  17725. if (!mediaAttributesIdentical(trackList1[i].attrs, trackList2[i].attrs)) {
  17726. return false;
  17727. }
  17728. }
  17729. return true;
  17730. }
  17731. function mediaAttributesIdentical(attrs1, attrs2, customAttributes) {
  17732. // Media options with the same rendition ID must be bit identical
  17733. var stableRenditionId = attrs1['STABLE-RENDITION-ID'];
  17734. if (stableRenditionId && !customAttributes) {
  17735. return stableRenditionId === attrs2['STABLE-RENDITION-ID'];
  17736. }
  17737. // When rendition ID is not present, compare attributes
  17738. return !(customAttributes || ['LANGUAGE', 'NAME', 'CHARACTERISTICS', 'AUTOSELECT', 'DEFAULT', 'FORCED', 'ASSOC-LANGUAGE']).some(function (subtitleAttribute) {
  17739. return attrs1[subtitleAttribute] !== attrs2[subtitleAttribute];
  17740. });
  17741. }
  17742. function subtitleTrackMatchesTextTrack(subtitleTrack, textTrack) {
  17743. return textTrack.label.toLowerCase() === subtitleTrack.name.toLowerCase() && (!textTrack.language || textTrack.language.toLowerCase() === (subtitleTrack.lang || '').toLowerCase());
  17744. }
  17745. var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
  17746. function AudioTrackController(hls) {
  17747. var _this;
  17748. _this = _BasePlaylistControll.call(this, hls, 'audio-track-controller') || this;
  17749. _this.tracks = [];
  17750. _this.groupIds = null;
  17751. _this.tracksInGroup = [];
  17752. _this.trackId = -1;
  17753. _this.currentTrack = null;
  17754. _this.selectDefaultTrack = true;
  17755. _this.registerListeners();
  17756. return _this;
  17757. }
  17758. _inheritsLoose(AudioTrackController, _BasePlaylistControll);
  17759. var _proto = AudioTrackController.prototype;
  17760. _proto.registerListeners = function registerListeners() {
  17761. var hls = this.hls;
  17762. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17763. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17764. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  17765. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  17766. hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  17767. hls.on(Events.ERROR, this.onError, this);
  17768. };
  17769. _proto.unregisterListeners = function unregisterListeners() {
  17770. var hls = this.hls;
  17771. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  17772. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  17773. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  17774. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  17775. hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
  17776. hls.off(Events.ERROR, this.onError, this);
  17777. };
  17778. _proto.destroy = function destroy() {
  17779. this.unregisterListeners();
  17780. this.tracks.length = 0;
  17781. this.tracksInGroup.length = 0;
  17782. this.currentTrack = null;
  17783. _BasePlaylistControll.prototype.destroy.call(this);
  17784. };
  17785. _proto.onManifestLoading = function onManifestLoading() {
  17786. this.tracks = [];
  17787. this.tracksInGroup = [];
  17788. this.groupIds = null;
  17789. this.currentTrack = null;
  17790. this.trackId = -1;
  17791. this.selectDefaultTrack = true;
  17792. };
  17793. _proto.onManifestParsed = function onManifestParsed(event, data) {
  17794. this.tracks = data.audioTracks || [];
  17795. };
  17796. _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
  17797. var id = data.id,
  17798. groupId = data.groupId,
  17799. details = data.details;
  17800. var trackInActiveGroup = this.tracksInGroup[id];
  17801. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  17802. this.warn("Audio track with id:" + id + " and group:" + groupId + " not found in active group " + (trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId));
  17803. return;
  17804. }
  17805. var curDetails = trackInActiveGroup.details;
  17806. trackInActiveGroup.details = data.details;
  17807. this.log("Audio track " + id + " \"" + trackInActiveGroup.name + "\" lang:" + trackInActiveGroup.lang + " group:" + groupId + " loaded [" + details.startSN + "-" + details.endSN + "]");
  17808. if (id === this.trackId) {
  17809. this.playlistLoaded(id, data, curDetails);
  17810. }
  17811. };
  17812. _proto.onLevelLoading = function onLevelLoading(event, data) {
  17813. this.switchLevel(data.level);
  17814. };
  17815. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  17816. this.switchLevel(data.level);
  17817. };
  17818. _proto.switchLevel = function switchLevel(levelIndex) {
  17819. var levelInfo = this.hls.levels[levelIndex];
  17820. if (!levelInfo) {
  17821. return;
  17822. }
  17823. var audioGroups = levelInfo.audioGroups || null;
  17824. var currentGroups = this.groupIds;
  17825. var currentTrack = this.currentTrack;
  17826. if (!audioGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (audioGroups == null ? void 0 : audioGroups.length) || audioGroups != null && audioGroups.some(function (groupId) {
  17827. return (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1;
  17828. })) {
  17829. this.groupIds = audioGroups;
  17830. this.trackId = -1;
  17831. this.currentTrack = null;
  17832. var audioTracks = this.tracks.filter(function (track) {
  17833. return !audioGroups || audioGroups.indexOf(track.groupId) !== -1;
  17834. });
  17835. if (audioTracks.length) {
  17836. // Disable selectDefaultTrack if there are no default tracks
  17837. if (this.selectDefaultTrack && !audioTracks.some(function (track) {
  17838. return track.default;
  17839. })) {
  17840. this.selectDefaultTrack = false;
  17841. }
  17842. // track.id should match hls.audioTracks index
  17843. audioTracks.forEach(function (track, i) {
  17844. track.id = i;
  17845. });
  17846. } else if (!currentTrack && !this.tracksInGroup.length) {
  17847. // Do not dispatch AUDIO_TRACKS_UPDATED when there were and are no tracks
  17848. return;
  17849. }
  17850. this.tracksInGroup = audioTracks;
  17851. // Find preferred track
  17852. var audioPreference = this.hls.config.audioPreference;
  17853. if (!currentTrack && audioPreference) {
  17854. var groupIndex = findMatchingOption(audioPreference, audioTracks, audioMatchPredicate);
  17855. if (groupIndex > -1) {
  17856. currentTrack = audioTracks[groupIndex];
  17857. } else {
  17858. var allIndex = findMatchingOption(audioPreference, this.tracks);
  17859. currentTrack = this.tracks[allIndex];
  17860. }
  17861. }
  17862. // Select initial track
  17863. var trackId = this.findTrackId(currentTrack);
  17864. if (trackId === -1 && currentTrack) {
  17865. trackId = this.findTrackId(null);
  17866. }
  17867. // Dispatch events and load track if needed
  17868. var audioTracksUpdated = {
  17869. audioTracks: audioTracks
  17870. };
  17871. this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in group(s): " + (audioGroups == null ? void 0 : audioGroups.join(',')));
  17872. this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);
  17873. var selectedTrackId = this.trackId;
  17874. if (trackId !== -1 && selectedTrackId === -1) {
  17875. this.setAudioTrack(trackId);
  17876. } else if (audioTracks.length && selectedTrackId === -1) {
  17877. var _this$groupIds;
  17878. var error = new Error("No audio track selected for current audio group-ID(s): " + ((_this$groupIds = this.groupIds) == null ? void 0 : _this$groupIds.join(',')) + " track count: " + audioTracks.length);
  17879. this.warn(error.message);
  17880. this.hls.trigger(Events.ERROR, {
  17881. type: ErrorTypes.MEDIA_ERROR,
  17882. details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  17883. fatal: true,
  17884. error: error
  17885. });
  17886. }
  17887. }
  17888. };
  17889. _proto.onError = function onError(event, data) {
  17890. if (data.fatal || !data.context) {
  17891. return;
  17892. }
  17893. if (data.context.type === PlaylistContextType.AUDIO_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  17894. this.checkRetry(data);
  17895. }
  17896. };
  17897. _proto.setAudioOption = function setAudioOption(audioOption) {
  17898. var hls = this.hls;
  17899. hls.config.audioPreference = audioOption;
  17900. if (audioOption) {
  17901. var allAudioTracks = this.allAudioTracks;
  17902. this.selectDefaultTrack = false;
  17903. if (allAudioTracks.length) {
  17904. // First see if current option matches (no switch op)
  17905. var currentTrack = this.currentTrack;
  17906. if (currentTrack && matchesOption(audioOption, currentTrack, audioMatchPredicate)) {
  17907. return currentTrack;
  17908. }
  17909. // Find option in available tracks (tracksInGroup)
  17910. var groupIndex = findMatchingOption(audioOption, this.tracksInGroup, audioMatchPredicate);
  17911. if (groupIndex > -1) {
  17912. var track = this.tracksInGroup[groupIndex];
  17913. this.setAudioTrack(groupIndex);
  17914. return track;
  17915. } else if (currentTrack) {
  17916. // Find option in nearest level audio group
  17917. var searchIndex = hls.loadLevel;
  17918. if (searchIndex === -1) {
  17919. searchIndex = hls.firstAutoLevel;
  17920. }
  17921. var switchIndex = findClosestLevelWithAudioGroup(audioOption, hls.levels, allAudioTracks, searchIndex, audioMatchPredicate);
  17922. if (switchIndex === -1) {
  17923. // could not find matching variant
  17924. return null;
  17925. }
  17926. // and switch level to acheive the audio group switch
  17927. hls.nextLoadLevel = switchIndex;
  17928. }
  17929. if (audioOption.channels || audioOption.audioCodec) {
  17930. // Could not find a match with codec / channels predicate
  17931. // Find a match without channels or codec
  17932. var withoutCodecAndChannelsMatch = findMatchingOption(audioOption, allAudioTracks);
  17933. if (withoutCodecAndChannelsMatch > -1) {
  17934. return allAudioTracks[withoutCodecAndChannelsMatch];
  17935. }
  17936. }
  17937. }
  17938. }
  17939. return null;
  17940. };
  17941. _proto.setAudioTrack = function setAudioTrack(newId) {
  17942. var tracks = this.tracksInGroup;
  17943. // check if level idx is valid
  17944. if (newId < 0 || newId >= tracks.length) {
  17945. this.warn("Invalid audio track id: " + newId);
  17946. return;
  17947. }
  17948. this.selectDefaultTrack = false;
  17949. var lastTrack = this.currentTrack;
  17950. var track = tracks[newId];
  17951. var trackLoaded = track.details && !track.details.live;
  17952. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  17953. return;
  17954. }
  17955. this.log("Switching to audio-track " + newId + " \"" + track.name + "\" lang:" + track.lang + " group:" + track.groupId + " channels:" + track.channels);
  17956. this.trackId = newId;
  17957. this.currentTrack = track;
  17958. this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, _objectSpread2({}, track));
  17959. // Do not reload track unless live
  17960. if (trackLoaded) {
  17961. return;
  17962. }
  17963. var hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  17964. this.loadPlaylist(hlsUrlParameters);
  17965. };
  17966. _proto.findTrackId = function findTrackId(currentTrack) {
  17967. var audioTracks = this.tracksInGroup;
  17968. for (var i = 0; i < audioTracks.length; i++) {
  17969. var track = audioTracks[i];
  17970. if (this.selectDefaultTrack && !track.default) {
  17971. continue;
  17972. }
  17973. if (!currentTrack || matchesOption(currentTrack, track, audioMatchPredicate)) {
  17974. return i;
  17975. }
  17976. }
  17977. if (currentTrack) {
  17978. var name = currentTrack.name,
  17979. lang = currentTrack.lang,
  17980. assocLang = currentTrack.assocLang,
  17981. characteristics = currentTrack.characteristics,
  17982. audioCodec = currentTrack.audioCodec,
  17983. channels = currentTrack.channels;
  17984. for (var _i = 0; _i < audioTracks.length; _i++) {
  17985. var _track = audioTracks[_i];
  17986. if (matchesOption({
  17987. name: name,
  17988. lang: lang,
  17989. assocLang: assocLang,
  17990. characteristics: characteristics,
  17991. audioCodec: audioCodec,
  17992. channels: channels
  17993. }, _track, audioMatchPredicate)) {
  17994. return _i;
  17995. }
  17996. }
  17997. for (var _i2 = 0; _i2 < audioTracks.length; _i2++) {
  17998. var _track2 = audioTracks[_i2];
  17999. if (mediaAttributesIdentical(currentTrack.attrs, _track2.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  18000. return _i2;
  18001. }
  18002. }
  18003. for (var _i3 = 0; _i3 < audioTracks.length; _i3++) {
  18004. var _track3 = audioTracks[_i3];
  18005. if (mediaAttributesIdentical(currentTrack.attrs, _track3.attrs, ['LANGUAGE'])) {
  18006. return _i3;
  18007. }
  18008. }
  18009. }
  18010. return -1;
  18011. };
  18012. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  18013. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  18014. var audioTrack = this.currentTrack;
  18015. if (!this.shouldLoadPlaylist(audioTrack)) {
  18016. return;
  18017. }
  18018. // Do not load audio rendition with URI matching main variant URI
  18019. if (useAlternateAudio(audioTrack.url, this.hls)) {
  18020. this.scheduleLoading(audioTrack, hlsUrlParameters);
  18021. }
  18022. };
  18023. _proto.loadingPlaylist = function loadingPlaylist(audioTrack, hlsUrlParameters) {
  18024. _BasePlaylistControll.prototype.loadingPlaylist.call(this, audioTrack, hlsUrlParameters);
  18025. var id = audioTrack.id;
  18026. var groupId = audioTrack.groupId;
  18027. var url = this.getUrlWithDirectives(audioTrack.url, hlsUrlParameters);
  18028. var details = audioTrack.details;
  18029. var age = details == null ? void 0 : details.age;
  18030. this.log("Loading audio-track " + id + " \"" + audioTrack.name + "\" lang:" + audioTrack.lang + " group:" + groupId + ((hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + (age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : '') + " " + url);
  18031. this.hls.trigger(Events.AUDIO_TRACK_LOADING, {
  18032. url: url,
  18033. id: id,
  18034. groupId: groupId,
  18035. deliveryDirectives: hlsUrlParameters || null,
  18036. track: audioTrack
  18037. });
  18038. };
  18039. return _createClass(AudioTrackController, [{
  18040. key: "allAudioTracks",
  18041. get: function get() {
  18042. return this.tracks;
  18043. }
  18044. }, {
  18045. key: "audioTracks",
  18046. get: function get() {
  18047. return this.tracksInGroup;
  18048. }
  18049. }, {
  18050. key: "audioTrack",
  18051. get: function get() {
  18052. return this.trackId;
  18053. },
  18054. set: function set(newId) {
  18055. // If audio track is selected from API then don't choose from the manifest default track
  18056. this.selectDefaultTrack = false;
  18057. this.setAudioTrack(newId);
  18058. }
  18059. }]);
  18060. }(BasePlaylistController);
  18061. var BufferOperationQueue = /*#__PURE__*/function () {
  18062. function BufferOperationQueue(sourceBufferReference) {
  18063. this.tracks = void 0;
  18064. this.queues = {
  18065. video: [],
  18066. audio: [],
  18067. audiovideo: []
  18068. };
  18069. this.tracks = sourceBufferReference;
  18070. }
  18071. var _proto = BufferOperationQueue.prototype;
  18072. _proto.destroy = function destroy() {
  18073. this.tracks = this.queues = null;
  18074. };
  18075. _proto.append = function append(operation, type, pending) {
  18076. if (this.queues === null || this.tracks === null) {
  18077. return;
  18078. }
  18079. var queue = this.queues[type];
  18080. queue.push(operation);
  18081. if (queue.length === 1 && !pending) {
  18082. this.executeNext(type);
  18083. }
  18084. };
  18085. _proto.appendBlocker = function appendBlocker(type) {
  18086. var _this = this;
  18087. return new Promise(function (resolve) {
  18088. var operation = {
  18089. label: 'async-blocker',
  18090. execute: resolve,
  18091. onStart: function onStart() {},
  18092. onComplete: function onComplete() {},
  18093. onError: function onError() {}
  18094. };
  18095. _this.append(operation, type);
  18096. });
  18097. };
  18098. _proto.prependBlocker = function prependBlocker(type) {
  18099. var _this2 = this;
  18100. return new Promise(function (resolve) {
  18101. if (_this2.queues) {
  18102. var operation = {
  18103. label: 'async-blocker-prepend',
  18104. execute: resolve,
  18105. onStart: function onStart() {},
  18106. onComplete: function onComplete() {},
  18107. onError: function onError() {}
  18108. };
  18109. _this2.queues[type].unshift(operation);
  18110. }
  18111. });
  18112. };
  18113. _proto.removeBlockers = function removeBlockers() {
  18114. if (this.queues === null) {
  18115. return;
  18116. }
  18117. [this.queues.video, this.queues.audio, this.queues.audiovideo].forEach(function (queue) {
  18118. var _queue$;
  18119. var label = (_queue$ = queue[0]) == null ? void 0 : _queue$.label;
  18120. if (label === 'async-blocker' || label === 'async-blocker-prepend') {
  18121. queue[0].execute();
  18122. queue.splice(0, 1);
  18123. }
  18124. });
  18125. };
  18126. _proto.unblockAudio = function unblockAudio(op) {
  18127. if (this.queues === null) {
  18128. return;
  18129. }
  18130. var queue = this.queues.audio;
  18131. if (queue[0] === op) {
  18132. this.shiftAndExecuteNext('audio');
  18133. }
  18134. };
  18135. _proto.executeNext = function executeNext(type) {
  18136. if (this.queues === null || this.tracks === null) {
  18137. return;
  18138. }
  18139. var queue = this.queues[type];
  18140. if (queue.length) {
  18141. var operation = queue[0];
  18142. try {
  18143. // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
  18144. // which do not end with this event must call _onSBUpdateEnd manually
  18145. operation.execute();
  18146. } catch (error) {
  18147. var _this$tracks$type;
  18148. operation.onError(error);
  18149. if (this.queues === null || this.tracks === null) {
  18150. return;
  18151. }
  18152. // Only shift the current operation off, otherwise the updateend handler will do this for us
  18153. var sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  18154. if (!(sb != null && sb.updating)) {
  18155. this.shiftAndExecuteNext(type);
  18156. }
  18157. }
  18158. }
  18159. };
  18160. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  18161. if (this.queues === null) {
  18162. return;
  18163. }
  18164. this.queues[type].shift();
  18165. this.executeNext(type);
  18166. };
  18167. _proto.current = function current(type) {
  18168. var _this$queues;
  18169. return ((_this$queues = this.queues) == null ? void 0 : _this$queues[type][0]) || null;
  18170. };
  18171. _proto.toString = function toString() {
  18172. var queues = this.queues,
  18173. tracks = this.tracks;
  18174. if (queues === null || tracks === null) {
  18175. return "<destroyed>";
  18176. }
  18177. return "\n" + this.list('video') + "\n" + this.list('audio') + "\n" + this.list('audiovideo') + "}";
  18178. };
  18179. _proto.list = function list(type) {
  18180. var _this$queues2, _this$tracks;
  18181. return (_this$queues2 = this.queues) != null && _this$queues2[type] || (_this$tracks = this.tracks) != null && _this$tracks[type] ? type + ": (" + this.listSbInfo(type) + ") " + this.listOps(type) : '';
  18182. };
  18183. _proto.listSbInfo = function listSbInfo(type) {
  18184. var _this$tracks2;
  18185. var track = (_this$tracks2 = this.tracks) == null ? void 0 : _this$tracks2[type];
  18186. var sb = track == null ? void 0 : track.buffer;
  18187. if (!sb) {
  18188. return 'none';
  18189. }
  18190. return "SourceBuffer" + (sb.updating ? ' updating' : '') + (track.ended ? ' ended' : '') + (track.ending ? ' ending' : '');
  18191. };
  18192. _proto.listOps = function listOps(type) {
  18193. var _this$queues3;
  18194. return ((_this$queues3 = this.queues) == null ? void 0 : _this$queues3[type].map(function (op) {
  18195. return op.label;
  18196. }).join(', ')) || '';
  18197. };
  18198. return BufferOperationQueue;
  18199. }();
  18200. var VIDEO_CODEC_PROFILE_REPLACE = /(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;
  18201. var TRACK_REMOVED_ERROR_NAME = 'HlsJsTrackRemovedError';
  18202. var HlsJsTrackRemovedError = /*#__PURE__*/function (_Error) {
  18203. function HlsJsTrackRemovedError(message) {
  18204. var _this;
  18205. _this = _Error.call(this, message) || this;
  18206. _this.name = TRACK_REMOVED_ERROR_NAME;
  18207. return _this;
  18208. }
  18209. _inheritsLoose(HlsJsTrackRemovedError, _Error);
  18210. return HlsJsTrackRemovedError;
  18211. }(/*#__PURE__*/_wrapNativeSuper(Error));
  18212. var BufferController = /*#__PURE__*/function (_Logger) {
  18213. function BufferController(hls, fragmentTracker) {
  18214. var _this2;
  18215. _this2 = _Logger.call(this, 'buffer-controller', hls.logger) || this;
  18216. _this2.hls = void 0;
  18217. _this2.fragmentTracker = void 0;
  18218. // The level details used to determine duration, target-duration and live
  18219. _this2.details = null;
  18220. // cache the self generated object url to detect hijack of video tag
  18221. _this2._objectUrl = null;
  18222. // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
  18223. _this2.operationQueue = null;
  18224. // The total number track codecs expected before any sourceBuffers are created (2: audio and video or 1: audiovideo | audio | video)
  18225. _this2.bufferCodecEventsTotal = 0;
  18226. // A reference to the attached media element
  18227. _this2.media = null;
  18228. // A reference to the active media source
  18229. _this2.mediaSource = null;
  18230. // Last MP3 audio chunk appended
  18231. _this2.lastMpegAudioChunk = null;
  18232. // Audio fragment blocked from appending until corresponding video appends or context changes
  18233. _this2.blockedAudioAppend = null;
  18234. // Keep track of video append position for unblocking audio
  18235. _this2.lastVideoAppendEnd = 0;
  18236. // Whether or not to use ManagedMediaSource API and append source element to media element.
  18237. _this2.appendSource = void 0;
  18238. // Transferred MediaSource information used to detmerine if duration end endstream may be appended
  18239. _this2.transferData = void 0;
  18240. // Directives used to override default MediaSource handling
  18241. _this2.overrides = void 0;
  18242. // Error counters
  18243. _this2.appendErrors = {
  18244. audio: 0,
  18245. video: 0,
  18246. audiovideo: 0
  18247. };
  18248. // Record of required or created buffers by type. SourceBuffer is stored in Track.buffer once created.
  18249. _this2.tracks = {};
  18250. // Array of SourceBuffer type and SourceBuffer (or null). One entry per TrackSet in this.tracks.
  18251. _this2.sourceBuffers = [[null, null], [null, null]];
  18252. _this2._onEndStreaming = function (event) {
  18253. var _this2$mediaSource;
  18254. if (!_this2.hls) {
  18255. return;
  18256. }
  18257. if (((_this2$mediaSource = _this2.mediaSource) == null ? void 0 : _this2$mediaSource.readyState) !== 'open') {
  18258. return;
  18259. }
  18260. _this2.hls.pauseBuffering();
  18261. };
  18262. _this2._onStartStreaming = function (event) {
  18263. if (!_this2.hls) {
  18264. return;
  18265. }
  18266. _this2.hls.resumeBuffering();
  18267. };
  18268. // Keep as arrow functions so that we can directly reference these functions directly as event listeners
  18269. _this2._onMediaSourceOpen = function (e) {
  18270. var _this3 = _this2,
  18271. media = _this3.media,
  18272. mediaSource = _this3.mediaSource;
  18273. if (e) {
  18274. _this2.log('Media source opened');
  18275. }
  18276. if (!media || !mediaSource) {
  18277. return;
  18278. }
  18279. // once received, don't listen anymore to sourceopen event
  18280. mediaSource.removeEventListener('sourceopen', _this2._onMediaSourceOpen);
  18281. media.removeEventListener('emptied', _this2._onMediaEmptied);
  18282. _this2.updateDuration();
  18283. _this2.hls.trigger(Events.MEDIA_ATTACHED, {
  18284. media: media,
  18285. mediaSource: mediaSource
  18286. });
  18287. if (_this2.mediaSource !== null) {
  18288. _this2.checkPendingTracks();
  18289. }
  18290. };
  18291. _this2._onMediaSourceClose = function () {
  18292. _this2.log('Media source closed');
  18293. };
  18294. _this2._onMediaSourceEnded = function () {
  18295. _this2.log('Media source ended');
  18296. };
  18297. _this2._onMediaEmptied = function () {
  18298. var _this4 = _this2,
  18299. mediaSrc = _this4.mediaSrc,
  18300. _objectUrl = _this4._objectUrl;
  18301. if (mediaSrc !== _objectUrl) {
  18302. _this2.error("Media element src was set while attaching MediaSource (" + _objectUrl + " > " + mediaSrc + ")");
  18303. }
  18304. };
  18305. _this2.hls = hls;
  18306. _this2.fragmentTracker = fragmentTracker;
  18307. _this2.appendSource = isManagedMediaSource(getMediaSource(hls.config.preferManagedMediaSource));
  18308. _this2.initTracks();
  18309. _this2.registerListeners();
  18310. return _this2;
  18311. }
  18312. _inheritsLoose(BufferController, _Logger);
  18313. var _proto = BufferController.prototype;
  18314. _proto.hasSourceTypes = function hasSourceTypes() {
  18315. return Object.keys(this.tracks).length > 0;
  18316. };
  18317. _proto.destroy = function destroy() {
  18318. this.unregisterListeners();
  18319. this.details = null;
  18320. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  18321. this.transferData = this.overrides = undefined;
  18322. if (this.operationQueue) {
  18323. this.operationQueue.destroy();
  18324. this.operationQueue = null;
  18325. }
  18326. // @ts-ignore
  18327. this.hls = this.fragmentTracker = null;
  18328. // @ts-ignore
  18329. this._onMediaSourceOpen = this._onMediaSourceClose = null;
  18330. // @ts-ignore
  18331. this._onMediaSourceEnded = null;
  18332. // @ts-ignore
  18333. this._onStartStreaming = this._onEndStreaming = null;
  18334. };
  18335. _proto.registerListeners = function registerListeners() {
  18336. var hls = this.hls;
  18337. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18338. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18339. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18340. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18341. hls.on(Events.BUFFER_RESET, this.onBufferReset, this);
  18342. hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  18343. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  18344. hls.on(Events.BUFFER_EOS, this.onBufferEos, this);
  18345. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18346. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18347. hls.on(Events.FRAG_PARSED, this.onFragParsed, this);
  18348. hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);
  18349. hls.on(Events.ERROR, this.onError, this);
  18350. };
  18351. _proto.unregisterListeners = function unregisterListeners() {
  18352. var hls = this.hls;
  18353. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  18354. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  18355. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  18356. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  18357. hls.off(Events.BUFFER_RESET, this.onBufferReset, this);
  18358. hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);
  18359. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  18360. hls.off(Events.BUFFER_EOS, this.onBufferEos, this);
  18361. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  18362. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  18363. hls.off(Events.FRAG_PARSED, this.onFragParsed, this);
  18364. hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);
  18365. hls.off(Events.ERROR, this.onError, this);
  18366. };
  18367. _proto.transferMedia = function transferMedia() {
  18368. var _this5 = this;
  18369. var media = this.media,
  18370. mediaSource = this.mediaSource;
  18371. if (!media) {
  18372. return null;
  18373. }
  18374. var tracks = {};
  18375. if (this.operationQueue) {
  18376. var updating = this.isUpdating();
  18377. if (!updating) {
  18378. this.operationQueue.removeBlockers();
  18379. }
  18380. var queued = this.isQueued();
  18381. if (updating || queued) {
  18382. this.warn("Transfering MediaSource with" + (queued ? ' operations in queue' : '') + (updating ? ' updating SourceBuffer(s)' : '') + " " + this.operationQueue);
  18383. }
  18384. this.operationQueue.destroy();
  18385. }
  18386. var transferData = this.transferData;
  18387. if (!this.sourceBufferCount && transferData && transferData.mediaSource === mediaSource) {
  18388. _extends(tracks, transferData.tracks);
  18389. } else {
  18390. this.sourceBuffers.forEach(function (tuple) {
  18391. var type = tuple[0];
  18392. if (type) {
  18393. tracks[type] = _extends({}, _this5.tracks[type]);
  18394. _this5.removeBuffer(type);
  18395. }
  18396. tuple[0] = tuple[1] = null;
  18397. });
  18398. }
  18399. return {
  18400. media: media,
  18401. mediaSource: mediaSource,
  18402. tracks: tracks
  18403. };
  18404. };
  18405. _proto.initTracks = function initTracks() {
  18406. var tracks = {};
  18407. this.sourceBuffers = [[null, null], [null, null]];
  18408. this.tracks = tracks;
  18409. this.resetQueue();
  18410. this.resetAppendErrors();
  18411. this.lastMpegAudioChunk = this.blockedAudioAppend = null;
  18412. this.lastVideoAppendEnd = 0;
  18413. };
  18414. _proto.onManifestLoading = function onManifestLoading() {
  18415. this.bufferCodecEventsTotal = 0;
  18416. this.details = null;
  18417. };
  18418. _proto.onManifestParsed = function onManifestParsed(event, data) {
  18419. var _this$transferData;
  18420. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  18421. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  18422. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  18423. // it will contain the expected nb of source buffers, no need to compute it
  18424. var codecEvents = 2;
  18425. if (data.audio && !data.video || !data.altAudio) {
  18426. codecEvents = 1;
  18427. }
  18428. this.bufferCodecEventsTotal = codecEvents;
  18429. this.log(codecEvents + " bufferCodec event(s) expected.");
  18430. if ((_this$transferData = this.transferData) != null && _this$transferData.mediaSource && this.sourceBufferCount && codecEvents) {
  18431. this.bufferCreated();
  18432. }
  18433. };
  18434. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  18435. var media = this.media = data.media;
  18436. var MediaSource = getMediaSource(this.appendSource);
  18437. this.transferData = this.overrides = undefined;
  18438. if (media && MediaSource) {
  18439. var transferringMedia = !!data.mediaSource;
  18440. if (transferringMedia || data.overrides) {
  18441. this.transferData = data;
  18442. this.overrides = data.overrides;
  18443. }
  18444. var ms = this.mediaSource = data.mediaSource || new MediaSource();
  18445. this.assignMediaSource(ms);
  18446. if (transferringMedia) {
  18447. this._objectUrl = media.src;
  18448. this.attachTransferred();
  18449. } else {
  18450. // cache the locally generated object url
  18451. var objectUrl = this._objectUrl = self.URL.createObjectURL(ms);
  18452. // link video and media Source
  18453. if (this.appendSource) {
  18454. try {
  18455. media.removeAttribute('src');
  18456. // ManagedMediaSource will not open without disableRemotePlayback set to false or source alternatives
  18457. var MMS = self.ManagedMediaSource;
  18458. media.disableRemotePlayback = media.disableRemotePlayback || MMS && ms instanceof MMS;
  18459. removeSourceChildren(media);
  18460. addSource(media, objectUrl);
  18461. media.load();
  18462. } catch (error) {
  18463. media.src = objectUrl;
  18464. }
  18465. } else {
  18466. media.src = objectUrl;
  18467. }
  18468. }
  18469. media.addEventListener('emptied', this._onMediaEmptied);
  18470. }
  18471. };
  18472. _proto.assignMediaSource = function assignMediaSource(ms) {
  18473. var _this$transferData2, _ms$constructor;
  18474. this.log((((_this$transferData2 = this.transferData) == null ? void 0 : _this$transferData2.mediaSource) === ms ? 'transferred' : 'created') + " media source: " + ((_ms$constructor = ms.constructor) == null ? void 0 : _ms$constructor.name));
  18475. // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
  18476. ms.addEventListener('sourceopen', this._onMediaSourceOpen);
  18477. ms.addEventListener('sourceended', this._onMediaSourceEnded);
  18478. ms.addEventListener('sourceclose', this._onMediaSourceClose);
  18479. if (this.appendSource) {
  18480. ms.addEventListener('startstreaming', this._onStartStreaming);
  18481. ms.addEventListener('endstreaming', this._onEndStreaming);
  18482. }
  18483. };
  18484. _proto.attachTransferred = function attachTransferred() {
  18485. var _this6 = this;
  18486. var media = this.media;
  18487. var data = this.transferData;
  18488. if (!data || !media) {
  18489. return;
  18490. }
  18491. var requiredTracks = this.tracks;
  18492. var transferredTracks = data.tracks;
  18493. var trackNames = transferredTracks ? Object.keys(transferredTracks) : null;
  18494. var trackCount = trackNames ? trackNames.length : 0;
  18495. var mediaSourceOpenCallback = function mediaSourceOpenCallback() {
  18496. if (_this6.media && _this6.mediaSourceOpenOrEnded) {
  18497. _this6._onMediaSourceOpen();
  18498. }
  18499. };
  18500. if (transferredTracks && trackNames && trackCount) {
  18501. if (!this.tracksReady) {
  18502. // Wait for CODECS event(s)
  18503. this.hls.config.startFragPrefetch = true;
  18504. this.log("attachTransferred: waiting for SourceBuffer track info");
  18505. return;
  18506. }
  18507. this.log("attachTransferred: (bufferCodecEventsTotal " + this.bufferCodecEventsTotal + ")\nrequired tracks: " + stringify(requiredTracks, function (key, value) {
  18508. return key === 'initSegment' ? undefined : value;
  18509. }) + ";\ntransfer tracks: " + stringify(transferredTracks, function (key, value) {
  18510. return key === 'initSegment' ? undefined : value;
  18511. }) + "}");
  18512. if (!isCompatibleTrackChange(transferredTracks, requiredTracks)) {
  18513. // destroy attaching media source
  18514. data.mediaSource = null;
  18515. data.tracks = undefined;
  18516. var currentTime = media.currentTime;
  18517. var details = this.details;
  18518. var startTime = Math.max(currentTime, (details == null ? void 0 : details.fragments[0].start) || 0);
  18519. if (startTime - currentTime > 1) {
  18520. this.log("attachTransferred: waiting for playback to reach new tracks start time " + currentTime + " -> " + startTime);
  18521. return;
  18522. }
  18523. this.warn("attachTransferred: resetting MediaSource for incompatible tracks (\"" + Object.keys(transferredTracks) + "\"->\"" + Object.keys(requiredTracks) + "\") start time: " + startTime + " currentTime: " + currentTime);
  18524. this.onMediaDetaching(Events.MEDIA_DETACHING, {});
  18525. this.onMediaAttaching(Events.MEDIA_ATTACHING, data);
  18526. media.currentTime = startTime;
  18527. return;
  18528. }
  18529. this.transferData = undefined;
  18530. trackNames.forEach(function (trackName) {
  18531. var type = trackName;
  18532. var track = transferredTracks[type];
  18533. if (track) {
  18534. var sb = track.buffer;
  18535. if (sb) {
  18536. // Purge fragment tracker of ejected segments for existing buffer
  18537. var fragmentTracker = _this6.fragmentTracker;
  18538. var playlistType = track.id;
  18539. if (fragmentTracker.hasFragments(playlistType) || fragmentTracker.hasParts(playlistType)) {
  18540. var bufferedTimeRanges = BufferHelper.getBuffered(sb);
  18541. fragmentTracker.detectEvictedFragments(type, bufferedTimeRanges, playlistType, null, true);
  18542. }
  18543. // Transfer SourceBuffer
  18544. var sbIndex = sourceBufferNameToIndex(type);
  18545. var sbTuple = [type, sb];
  18546. _this6.sourceBuffers[sbIndex] = sbTuple;
  18547. if (sb.updating && _this6.operationQueue) {
  18548. _this6.operationQueue.prependBlocker(type);
  18549. }
  18550. _this6.trackSourceBuffer(type, track);
  18551. }
  18552. }
  18553. });
  18554. mediaSourceOpenCallback();
  18555. this.bufferCreated();
  18556. } else {
  18557. this.log("attachTransferred: MediaSource w/o SourceBuffers");
  18558. mediaSourceOpenCallback();
  18559. }
  18560. };
  18561. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  18562. var _this7 = this;
  18563. var transferringMedia = !!data.transferMedia;
  18564. this.transferData = this.overrides = undefined;
  18565. var media = this.media,
  18566. mediaSource = this.mediaSource,
  18567. _objectUrl = this._objectUrl;
  18568. if (mediaSource) {
  18569. this.log("media source " + (transferringMedia ? 'transferring' : 'detaching'));
  18570. if (transferringMedia) {
  18571. // Detach SourceBuffers without removing from MediaSource
  18572. // and leave `tracks` (required SourceBuffers configuration)
  18573. this.sourceBuffers.forEach(function (_ref) {
  18574. var type = _ref[0];
  18575. if (type) {
  18576. _this7.removeBuffer(type);
  18577. }
  18578. });
  18579. this.resetQueue();
  18580. } else {
  18581. if (this.mediaSourceOpenOrEnded) {
  18582. var open = mediaSource.readyState === 'open';
  18583. try {
  18584. var sourceBuffers = mediaSource.sourceBuffers;
  18585. for (var i = sourceBuffers.length; i--;) {
  18586. if (open) {
  18587. sourceBuffers[i].abort();
  18588. }
  18589. mediaSource.removeSourceBuffer(sourceBuffers[i]);
  18590. }
  18591. if (open) {
  18592. // endOfStream could trigger exception if any sourcebuffer is in updating state
  18593. // we don't really care about checking sourcebuffer state here,
  18594. // as we are anyway detaching the MediaSource
  18595. // let's just avoid this exception to propagate
  18596. mediaSource.endOfStream();
  18597. }
  18598. } catch (err) {
  18599. this.warn("onMediaDetaching: " + err.message + " while calling endOfStream");
  18600. }
  18601. }
  18602. // Clean up the SourceBuffers by invoking onBufferReset
  18603. if (this.sourceBufferCount) {
  18604. this.onBufferReset();
  18605. }
  18606. }
  18607. mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
  18608. mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
  18609. mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);
  18610. if (this.appendSource) {
  18611. mediaSource.removeEventListener('startstreaming', this._onStartStreaming);
  18612. mediaSource.removeEventListener('endstreaming', this._onEndStreaming);
  18613. }
  18614. this.mediaSource = null;
  18615. this._objectUrl = null;
  18616. }
  18617. // Detach properly the MediaSource from the HTMLMediaElement as
  18618. // suggested in https://github.com/w3c/media-source/issues/53.
  18619. if (media) {
  18620. media.removeEventListener('emptied', this._onMediaEmptied);
  18621. if (!transferringMedia) {
  18622. if (_objectUrl) {
  18623. self.URL.revokeObjectURL(_objectUrl);
  18624. }
  18625. // clean up video tag src only if it's our own url. some external libraries might
  18626. // hijack the video tag and change its 'src' without destroying the Hls instance first
  18627. if (this.mediaSrc === _objectUrl) {
  18628. media.removeAttribute('src');
  18629. if (this.appendSource) {
  18630. removeSourceChildren(media);
  18631. }
  18632. media.load();
  18633. } else {
  18634. this.warn('media|source.src was changed by a third party - skip cleanup');
  18635. }
  18636. }
  18637. this.media = null;
  18638. }
  18639. this.hls.trigger(Events.MEDIA_DETACHED, data);
  18640. };
  18641. _proto.onBufferReset = function onBufferReset() {
  18642. var _this8 = this;
  18643. this.sourceBuffers.forEach(function (_ref2) {
  18644. var type = _ref2[0];
  18645. if (type) {
  18646. _this8.resetBuffer(type);
  18647. }
  18648. });
  18649. this.initTracks();
  18650. };
  18651. _proto.resetBuffer = function resetBuffer(type) {
  18652. var _this$tracks$type;
  18653. var sb = (_this$tracks$type = this.tracks[type]) == null ? void 0 : _this$tracks$type.buffer;
  18654. this.removeBuffer(type);
  18655. if (sb) {
  18656. try {
  18657. var _this$mediaSource;
  18658. if ((_this$mediaSource = this.mediaSource) != null && _this$mediaSource.sourceBuffers.length) {
  18659. this.mediaSource.removeSourceBuffer(sb);
  18660. }
  18661. } catch (err) {
  18662. this.warn("onBufferReset " + type, err);
  18663. }
  18664. }
  18665. delete this.tracks[type];
  18666. };
  18667. _proto.removeBuffer = function removeBuffer(type) {
  18668. this.removeBufferListeners(type);
  18669. this.sourceBuffers[sourceBufferNameToIndex(type)] = [null, null];
  18670. var track = this.tracks[type];
  18671. if (track) {
  18672. track.buffer = undefined;
  18673. }
  18674. };
  18675. _proto.resetQueue = function resetQueue() {
  18676. if (this.operationQueue) {
  18677. this.operationQueue.destroy();
  18678. }
  18679. this.operationQueue = new BufferOperationQueue(this.tracks);
  18680. };
  18681. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  18682. var _this9 = this;
  18683. var tracks = this.tracks;
  18684. var trackNames = Object.keys(data);
  18685. this.log("BUFFER_CODECS: \"" + trackNames + "\" (current SB count " + this.sourceBufferCount + ")");
  18686. var unmuxedToMuxed = 'audiovideo' in data && (tracks.audio || tracks.video) || tracks.audiovideo && ('audio' in data || 'video' in data);
  18687. var muxedToUnmuxed = !unmuxedToMuxed && this.sourceBufferCount && this.media && trackNames.some(function (sbName) {
  18688. return !tracks[sbName];
  18689. });
  18690. if (unmuxedToMuxed || muxedToUnmuxed) {
  18691. this.warn("Unsupported transition between \"" + Object.keys(tracks) + "\" and \"" + trackNames + "\" SourceBuffers");
  18692. // Do not add incompatible track ('audiovideo' <-> 'video'/'audio').
  18693. // Allow following onBufferAppending handle to trigger BUFFER_APPEND_ERROR.
  18694. // This will either be resolved by level switch or could be handled with recoverMediaError().
  18695. return;
  18696. }
  18697. trackNames.forEach(function (trackName) {
  18698. var _this9$transferData, _this9$transferData$t, _trackCodec;
  18699. var parsedTrack = data[trackName];
  18700. var id = parsedTrack.id,
  18701. codec = parsedTrack.codec,
  18702. levelCodec = parsedTrack.levelCodec,
  18703. container = parsedTrack.container,
  18704. metadata = parsedTrack.metadata,
  18705. supplemental = parsedTrack.supplemental;
  18706. var track = tracks[trackName];
  18707. var transferredTrack = (_this9$transferData = _this9.transferData) == null ? void 0 : (_this9$transferData$t = _this9$transferData.tracks) == null ? void 0 : _this9$transferData$t[trackName];
  18708. var sbTrack = transferredTrack != null && transferredTrack.buffer ? transferredTrack : track;
  18709. var sbCodec = (sbTrack == null ? void 0 : sbTrack.pendingCodec) || (sbTrack == null ? void 0 : sbTrack.codec);
  18710. var trackLevelCodec = sbTrack == null ? void 0 : sbTrack.levelCodec;
  18711. if (!track) {
  18712. track = tracks[trackName] = {
  18713. buffer: undefined,
  18714. listeners: [],
  18715. codec: codec,
  18716. supplemental: supplemental,
  18717. container: container,
  18718. levelCodec: levelCodec,
  18719. metadata: metadata,
  18720. id: id
  18721. };
  18722. }
  18723. // check if SourceBuffer codec needs to change
  18724. var currentCodecFull = pickMostCompleteCodecName(sbCodec, trackLevelCodec);
  18725. var currentCodec = currentCodecFull == null ? void 0 : currentCodecFull.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  18726. var trackCodec = pickMostCompleteCodecName(codec, levelCodec);
  18727. var nextCodec = (_trackCodec = trackCodec) == null ? void 0 : _trackCodec.replace(VIDEO_CODEC_PROFILE_REPLACE, '$1');
  18728. if (trackCodec && currentCodecFull && currentCodec !== nextCodec) {
  18729. if (trackName.slice(0, 5) === 'audio') {
  18730. trackCodec = getCodecCompatibleName(trackCodec, _this9.appendSource);
  18731. }
  18732. _this9.log("switching codec " + sbCodec + " to " + trackCodec);
  18733. if (trackCodec !== (track.pendingCodec || track.codec)) {
  18734. track.pendingCodec = trackCodec;
  18735. }
  18736. track.container = container;
  18737. _this9.appendChangeType(trackName, container, trackCodec);
  18738. }
  18739. });
  18740. if (this.tracksReady || this.sourceBufferCount) {
  18741. data.tracks = this.sourceBufferTracks;
  18742. }
  18743. // if sourcebuffers already created, do nothing ...
  18744. if (this.sourceBufferCount) {
  18745. return;
  18746. }
  18747. if (this.mediaSourceOpenOrEnded) {
  18748. this.checkPendingTracks();
  18749. }
  18750. };
  18751. _proto.appendChangeType = function appendChangeType(type, container, codec) {
  18752. var _this0 = this;
  18753. var mimeType = container + ";codecs=" + codec;
  18754. var operation = {
  18755. label: "change-type=" + mimeType,
  18756. execute: function execute() {
  18757. var track = _this0.tracks[type];
  18758. if (track) {
  18759. var sb = track.buffer;
  18760. if (sb != null && sb.changeType) {
  18761. _this0.log("changing " + type + " sourceBuffer type to " + mimeType);
  18762. sb.changeType(mimeType);
  18763. track.codec = codec;
  18764. track.container = container;
  18765. }
  18766. }
  18767. _this0.shiftAndExecuteNext(type);
  18768. },
  18769. onStart: function onStart() {},
  18770. onComplete: function onComplete() {},
  18771. onError: function onError(error) {
  18772. _this0.warn("Failed to change " + type + " SourceBuffer type", error);
  18773. }
  18774. };
  18775. this.append(operation, type, this.isPending(this.tracks[type]));
  18776. };
  18777. _proto.blockAudio = function blockAudio(partOrFrag) {
  18778. var _this$fragmentTracker,
  18779. _this1 = this;
  18780. var pStart = partOrFrag.start;
  18781. var pTime = pStart + partOrFrag.duration * 0.05;
  18782. var atGap = ((_this$fragmentTracker = this.fragmentTracker.getAppendedFrag(pStart, PlaylistLevelType.MAIN)) == null ? void 0 : _this$fragmentTracker.gap) === true;
  18783. if (atGap) {
  18784. return;
  18785. }
  18786. var op = {
  18787. label: 'block-audio',
  18788. execute: function execute() {
  18789. var _this1$fragmentTracke;
  18790. var videoTrack = _this1.tracks.video;
  18791. if (_this1.lastVideoAppendEnd > pTime || videoTrack != null && videoTrack.buffer && BufferHelper.isBuffered(videoTrack.buffer, pTime) || ((_this1$fragmentTracke = _this1.fragmentTracker.getAppendedFrag(pTime, PlaylistLevelType.MAIN)) == null ? void 0 : _this1$fragmentTracke.gap) === true) {
  18792. _this1.blockedAudioAppend = null;
  18793. _this1.shiftAndExecuteNext('audio');
  18794. }
  18795. },
  18796. onStart: function onStart() {},
  18797. onComplete: function onComplete() {},
  18798. onError: function onError(error) {
  18799. _this1.warn('Error executing block-audio operation', error);
  18800. }
  18801. };
  18802. this.blockedAudioAppend = {
  18803. op: op,
  18804. frag: partOrFrag
  18805. };
  18806. this.append(op, 'audio', true);
  18807. };
  18808. _proto.unblockAudio = function unblockAudio() {
  18809. var blockedAudioAppend = this.blockedAudioAppend,
  18810. operationQueue = this.operationQueue;
  18811. if (blockedAudioAppend && operationQueue) {
  18812. this.blockedAudioAppend = null;
  18813. operationQueue.unblockAudio(blockedAudioAppend.op);
  18814. }
  18815. };
  18816. _proto.onBufferAppending = function onBufferAppending(event, eventData) {
  18817. var _this10 = this;
  18818. var tracks = this.tracks;
  18819. var data = eventData.data,
  18820. type = eventData.type,
  18821. parent = eventData.parent,
  18822. frag = eventData.frag,
  18823. part = eventData.part,
  18824. chunkMeta = eventData.chunkMeta,
  18825. offset = eventData.offset;
  18826. var chunkStats = chunkMeta.buffering[type];
  18827. var sn = frag.sn,
  18828. cc = frag.cc;
  18829. var bufferAppendingStart = self.performance.now();
  18830. chunkStats.start = bufferAppendingStart;
  18831. var fragBuffering = frag.stats.buffering;
  18832. var partBuffering = part ? part.stats.buffering : null;
  18833. if (fragBuffering.start === 0) {
  18834. fragBuffering.start = bufferAppendingStart;
  18835. }
  18836. if (partBuffering && partBuffering.start === 0) {
  18837. partBuffering.start = bufferAppendingStart;
  18838. }
  18839. // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
  18840. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  18841. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  18842. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
  18843. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  18844. var audioTrack = tracks.audio;
  18845. var checkTimestampOffset = false;
  18846. if (type === 'audio' && (audioTrack == null ? void 0 : audioTrack.container) === 'audio/mpeg') {
  18847. checkTimestampOffset = !this.lastMpegAudioChunk || chunkMeta.id === 1 || this.lastMpegAudioChunk.sn !== chunkMeta.sn;
  18848. this.lastMpegAudioChunk = chunkMeta;
  18849. }
  18850. // Block audio append until overlapping video append
  18851. var videoTrack = tracks.video;
  18852. var videoSb = videoTrack == null ? void 0 : videoTrack.buffer;
  18853. if (videoSb && sn !== 'initSegment') {
  18854. var partOrFrag = part || frag;
  18855. var blockedAudioAppend = this.blockedAudioAppend;
  18856. if (type === 'audio' && parent !== 'main' && !this.blockedAudioAppend) {
  18857. var pStart = partOrFrag.start;
  18858. var pTime = pStart + partOrFrag.duration * 0.05;
  18859. var vbuffered = videoSb.buffered;
  18860. var vappending = this.currentOp('video');
  18861. if (!vbuffered.length && !vappending) {
  18862. // wait for video before appending audio
  18863. this.blockAudio(partOrFrag);
  18864. } else if (!vappending && !BufferHelper.isBuffered(videoSb, pTime) && this.lastVideoAppendEnd < pTime) {
  18865. // audio is ahead of video
  18866. this.blockAudio(partOrFrag);
  18867. }
  18868. } else if (type === 'video') {
  18869. var videoAppendEnd = partOrFrag.end;
  18870. if (blockedAudioAppend) {
  18871. var audioStart = blockedAudioAppend.frag.start;
  18872. if (videoAppendEnd > audioStart || videoAppendEnd < this.lastVideoAppendEnd || BufferHelper.isBuffered(videoSb, audioStart)) {
  18873. this.unblockAudio();
  18874. }
  18875. }
  18876. this.lastVideoAppendEnd = videoAppendEnd;
  18877. }
  18878. }
  18879. var fragStart = (part || frag).start;
  18880. var operation = {
  18881. label: "append-" + type,
  18882. execute: function execute() {
  18883. var _this10$tracks$type;
  18884. chunkStats.executeStart = self.performance.now();
  18885. var sb = (_this10$tracks$type = _this10.tracks[type]) == null ? void 0 : _this10$tracks$type.buffer;
  18886. if (sb) {
  18887. if (checkTimestampOffset) {
  18888. _this10.updateTimestampOffset(sb, fragStart, 0.1, type, sn, cc);
  18889. } else if (offset !== undefined && isFiniteNumber(offset)) {
  18890. _this10.updateTimestampOffset(sb, offset, 0.000001, type, sn, cc);
  18891. }
  18892. }
  18893. _this10.appendExecutor(data, type);
  18894. },
  18895. onStart: function onStart() {
  18896. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
  18897. },
  18898. onComplete: function onComplete() {
  18899. // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
  18900. var end = self.performance.now();
  18901. chunkStats.executeEnd = chunkStats.end = end;
  18902. if (fragBuffering.first === 0) {
  18903. fragBuffering.first = end;
  18904. }
  18905. if (partBuffering && partBuffering.first === 0) {
  18906. partBuffering.first = end;
  18907. }
  18908. var timeRanges = {};
  18909. _this10.sourceBuffers.forEach(function (_ref3) {
  18910. var type = _ref3[0],
  18911. sb = _ref3[1];
  18912. if (type) {
  18913. timeRanges[type] = BufferHelper.getBuffered(sb);
  18914. }
  18915. });
  18916. _this10.appendErrors[type] = 0;
  18917. if (type === 'audio' || type === 'video') {
  18918. _this10.appendErrors.audiovideo = 0;
  18919. } else {
  18920. _this10.appendErrors.audio = 0;
  18921. _this10.appendErrors.video = 0;
  18922. }
  18923. _this10.hls.trigger(Events.BUFFER_APPENDED, {
  18924. type: type,
  18925. frag: frag,
  18926. part: part,
  18927. chunkMeta: chunkMeta,
  18928. parent: frag.type,
  18929. timeRanges: timeRanges
  18930. });
  18931. },
  18932. onError: function onError(error) {
  18933. var _this10$media;
  18934. // in case any error occured while appending, put back segment in segments table
  18935. var event = {
  18936. type: ErrorTypes.MEDIA_ERROR,
  18937. parent: frag.type,
  18938. details: ErrorDetails.BUFFER_APPEND_ERROR,
  18939. sourceBufferName: type,
  18940. frag: frag,
  18941. part: part,
  18942. chunkMeta: chunkMeta,
  18943. error: error,
  18944. err: error,
  18945. fatal: false
  18946. };
  18947. var mediaError = (_this10$media = _this10.media) == null ? void 0 : _this10$media.error;
  18948. if (error.code === DOMException.QUOTA_EXCEEDED_ERR || error.name == 'QuotaExceededError' || "quota" in error) {
  18949. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  18950. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  18951. event.details = ErrorDetails.BUFFER_FULL_ERROR;
  18952. } else if (error.code === DOMException.INVALID_STATE_ERR && _this10.mediaSourceOpenOrEnded && !mediaError) {
  18953. // Allow retry for "Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing" errors
  18954. event.errorAction = createDoNothingErrorAction(true);
  18955. } else if (error.name === TRACK_REMOVED_ERROR_NAME && _this10.sourceBufferCount === 0) {
  18956. // Do nothing if sourceBuffers were removed (media is detached and append was not aborted)
  18957. event.errorAction = createDoNothingErrorAction(true);
  18958. } else {
  18959. var appendErrorCount = ++_this10.appendErrors[type];
  18960. /* with UHD content, we could get loop of quota exceeded error until
  18961. browser is able to evict some data from sourcebuffer. Retrying can help recover.
  18962. */
  18963. _this10.warn("Failed " + appendErrorCount + "/" + _this10.hls.config.appendErrorMaxRetry + " times to append segment in \"" + type + "\" sourceBuffer (" + (mediaError ? mediaError : 'no media error') + ")");
  18964. if (appendErrorCount >= _this10.hls.config.appendErrorMaxRetry || !!mediaError) {
  18965. event.fatal = true;
  18966. }
  18967. }
  18968. _this10.hls.trigger(Events.ERROR, event);
  18969. }
  18970. };
  18971. this.append(operation, type, this.isPending(this.tracks[type]));
  18972. };
  18973. _proto.getFlushOp = function getFlushOp(type, start, end) {
  18974. var _this11 = this;
  18975. this.log("queuing \"" + type + "\" remove " + start + "-" + end);
  18976. return {
  18977. label: 'remove',
  18978. execute: function execute() {
  18979. _this11.removeExecutor(type, start, end);
  18980. },
  18981. onStart: function onStart() {
  18982. // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  18983. },
  18984. onComplete: function onComplete() {
  18985. // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
  18986. _this11.hls.trigger(Events.BUFFER_FLUSHED, {
  18987. type: type
  18988. });
  18989. },
  18990. onError: function onError(error) {
  18991. _this11.warn("Failed to remove " + start + "-" + end + " from \"" + type + "\" SourceBuffer", error);
  18992. }
  18993. };
  18994. };
  18995. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  18996. var _this12 = this;
  18997. var type = data.type,
  18998. startOffset = data.startOffset,
  18999. endOffset = data.endOffset;
  19000. if (type) {
  19001. this.append(this.getFlushOp(type, startOffset, endOffset), type);
  19002. } else {
  19003. this.sourceBuffers.forEach(function (_ref4) {
  19004. var type = _ref4[0];
  19005. if (type) {
  19006. _this12.append(_this12.getFlushOp(type, startOffset, endOffset), type);
  19007. }
  19008. });
  19009. }
  19010. };
  19011. _proto.onFragParsed = function onFragParsed(event, data) {
  19012. var _this13 = this;
  19013. var frag = data.frag,
  19014. part = data.part;
  19015. var buffersAppendedTo = [];
  19016. var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
  19017. if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {
  19018. buffersAppendedTo.push('audiovideo');
  19019. } else {
  19020. if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {
  19021. buffersAppendedTo.push('audio');
  19022. }
  19023. if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {
  19024. buffersAppendedTo.push('video');
  19025. }
  19026. }
  19027. var onUnblocked = function onUnblocked() {
  19028. var now = self.performance.now();
  19029. frag.stats.buffering.end = now;
  19030. if (part) {
  19031. part.stats.buffering.end = now;
  19032. }
  19033. var stats = part ? part.stats : frag.stats;
  19034. _this13.hls.trigger(Events.FRAG_BUFFERED, {
  19035. frag: frag,
  19036. part: part,
  19037. stats: stats,
  19038. id: frag.type
  19039. });
  19040. };
  19041. if (buffersAppendedTo.length === 0) {
  19042. this.warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
  19043. }
  19044. this.blockBuffers(onUnblocked, buffersAppendedTo).catch(function (error) {
  19045. _this13.warn("Fragment buffered callback " + error);
  19046. _this13.stepOperationQueue(_this13.sourceBufferTypes);
  19047. });
  19048. };
  19049. _proto.onFragChanged = function onFragChanged(event, data) {
  19050. this.trimBuffers();
  19051. };
  19052. // on BUFFER_EOS mark matching sourcebuffer(s) as "ending" and "ended" and queue endOfStream after remaining operations(s)
  19053. // an undefined data.type will mark all buffers as EOS.
  19054. _proto.onBufferEos = function onBufferEos(event, data) {
  19055. var _this14 = this,
  19056. _this$overrides;
  19057. this.sourceBuffers.forEach(function (_ref5) {
  19058. var type = _ref5[0];
  19059. if (type) {
  19060. var track = _this14.tracks[type];
  19061. if (!data.type || data.type === type) {
  19062. track.ending = true;
  19063. if (!track.ended) {
  19064. track.ended = true;
  19065. _this14.log(type + " buffer reached EOS");
  19066. }
  19067. }
  19068. }
  19069. });
  19070. var allowEndOfStream = ((_this$overrides = this.overrides) == null ? void 0 : _this$overrides.endOfStream) !== false;
  19071. var allTracksEnding = this.sourceBufferCount > 0 && !this.sourceBuffers.some(function (_ref6) {
  19072. var _this14$tracks$type;
  19073. var type = _ref6[0];
  19074. return type && !((_this14$tracks$type = _this14.tracks[type]) != null && _this14$tracks$type.ended);
  19075. });
  19076. if (allTracksEnding) {
  19077. if (allowEndOfStream) {
  19078. this.log("Queueing EOS");
  19079. this.blockUntilOpen(function () {
  19080. _this14.tracksEnded();
  19081. var mediaSource = _this14.mediaSource;
  19082. if (!mediaSource || mediaSource.readyState !== 'open') {
  19083. if (mediaSource) {
  19084. _this14.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: " + mediaSource.readyState);
  19085. }
  19086. return;
  19087. }
  19088. _this14.log("Calling mediaSource.endOfStream()");
  19089. // Allow this to throw and be caught by the enqueueing function
  19090. mediaSource.endOfStream();
  19091. _this14.hls.trigger(Events.BUFFERED_TO_END, undefined);
  19092. });
  19093. } else {
  19094. this.tracksEnded();
  19095. this.hls.trigger(Events.BUFFERED_TO_END, undefined);
  19096. }
  19097. }
  19098. };
  19099. _proto.tracksEnded = function tracksEnded() {
  19100. var _this15 = this;
  19101. this.sourceBuffers.forEach(function (_ref7) {
  19102. var type = _ref7[0];
  19103. if (type !== null) {
  19104. var track = _this15.tracks[type];
  19105. if (track) {
  19106. track.ending = false;
  19107. }
  19108. }
  19109. });
  19110. };
  19111. _proto.onLevelUpdated = function onLevelUpdated(event, _ref8) {
  19112. var details = _ref8.details;
  19113. if (!details.fragments.length) {
  19114. return;
  19115. }
  19116. this.details = details;
  19117. this.updateDuration();
  19118. };
  19119. _proto.updateDuration = function updateDuration() {
  19120. var _this16 = this;
  19121. this.blockUntilOpen(function () {
  19122. var durationAndRange = _this16.getDurationAndRange();
  19123. if (!durationAndRange) {
  19124. return;
  19125. }
  19126. _this16.updateMediaSource(durationAndRange);
  19127. });
  19128. };
  19129. _proto.onError = function onError(event, data) {
  19130. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && data.frag) {
  19131. var _data$errorAction;
  19132. var nextAutoLevel = (_data$errorAction = data.errorAction) == null ? void 0 : _data$errorAction.nextAutoLevel;
  19133. if (isFiniteNumber(nextAutoLevel) && nextAutoLevel !== data.frag.level) {
  19134. this.resetAppendErrors();
  19135. }
  19136. }
  19137. };
  19138. _proto.resetAppendErrors = function resetAppendErrors() {
  19139. this.appendErrors = {
  19140. audio: 0,
  19141. video: 0,
  19142. audiovideo: 0
  19143. };
  19144. };
  19145. _proto.trimBuffers = function trimBuffers() {
  19146. var hls = this.hls,
  19147. details = this.details,
  19148. media = this.media;
  19149. if (!media || details === null) {
  19150. return;
  19151. }
  19152. if (!this.sourceBufferCount) {
  19153. return;
  19154. }
  19155. var config = hls.config;
  19156. var currentTime = media.currentTime;
  19157. var targetDuration = details.levelTargetDuration;
  19158. // Support for deprecated liveBackBufferLength
  19159. var backBufferLength = details.live && config.liveBackBufferLength !== null ? config.liveBackBufferLength : config.backBufferLength;
  19160. if (isFiniteNumber(backBufferLength) && backBufferLength >= 0) {
  19161. var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
  19162. var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
  19163. this.flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition);
  19164. }
  19165. if (isFiniteNumber(config.frontBufferFlushThreshold) && config.frontBufferFlushThreshold > 0) {
  19166. var frontBufferLength = Math.max(config.maxBufferLength, config.frontBufferFlushThreshold);
  19167. var maxFrontBufferLength = Math.max(frontBufferLength, targetDuration);
  19168. var targetFrontBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration + maxFrontBufferLength;
  19169. this.flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition);
  19170. }
  19171. };
  19172. _proto.flushBackBuffer = function flushBackBuffer(currentTime, targetDuration, targetBackBufferPosition) {
  19173. var _this17 = this;
  19174. this.sourceBuffers.forEach(function (_ref9) {
  19175. var type = _ref9[0],
  19176. sb = _ref9[1];
  19177. if (sb) {
  19178. var buffered = BufferHelper.getBuffered(sb);
  19179. // when target buffer start exceeds actual buffer start
  19180. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  19181. var _this17$details;
  19182. _this17.hls.trigger(Events.BACK_BUFFER_REACHED, {
  19183. bufferEnd: targetBackBufferPosition
  19184. });
  19185. // Support for deprecated event:
  19186. var track = _this17.tracks[type];
  19187. if ((_this17$details = _this17.details) != null && _this17$details.live) {
  19188. _this17.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {
  19189. bufferEnd: targetBackBufferPosition
  19190. });
  19191. } else if (track != null && track.ended) {
  19192. _this17.log("Cannot flush " + type + " back buffer while SourceBuffer is in ended state");
  19193. return;
  19194. }
  19195. _this17.hls.trigger(Events.BUFFER_FLUSHING, {
  19196. startOffset: 0,
  19197. endOffset: targetBackBufferPosition,
  19198. type: type
  19199. });
  19200. }
  19201. }
  19202. });
  19203. };
  19204. _proto.flushFrontBuffer = function flushFrontBuffer(currentTime, targetDuration, targetFrontBufferPosition) {
  19205. var _this18 = this;
  19206. this.sourceBuffers.forEach(function (_ref0) {
  19207. var type = _ref0[0],
  19208. sb = _ref0[1];
  19209. if (sb) {
  19210. var buffered = BufferHelper.getBuffered(sb);
  19211. var numBufferedRanges = buffered.length;
  19212. // The buffer is either empty or contiguous
  19213. if (numBufferedRanges < 2) {
  19214. return;
  19215. }
  19216. var bufferStart = buffered.start(numBufferedRanges - 1);
  19217. var bufferEnd = buffered.end(numBufferedRanges - 1);
  19218. // No flush if we can tolerate the current buffer length or the current buffer range we would flush is contiguous with current position
  19219. if (targetFrontBufferPosition > bufferStart || currentTime >= bufferStart && currentTime <= bufferEnd) {
  19220. return;
  19221. }
  19222. _this18.hls.trigger(Events.BUFFER_FLUSHING, {
  19223. startOffset: bufferStart,
  19224. endOffset: Infinity,
  19225. type: type
  19226. });
  19227. }
  19228. });
  19229. }
  19230. /**
  19231. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  19232. * 'liveDurationInfinity` is set to `true`
  19233. * More details: https://github.com/video-dev/hls.js/issues/355
  19234. */;
  19235. _proto.getDurationAndRange = function getDurationAndRange() {
  19236. var _this$overrides2;
  19237. var details = this.details,
  19238. mediaSource = this.mediaSource;
  19239. if (!details || !this.media || (mediaSource == null ? void 0 : mediaSource.readyState) !== 'open') {
  19240. return null;
  19241. }
  19242. var playlistEnd = details.edge;
  19243. if (details.live && this.hls.config.liveDurationInfinity) {
  19244. var len = details.fragments.length;
  19245. if (len && details.live && !!mediaSource.setLiveSeekableRange) {
  19246. var start = Math.max(0, details.fragmentStart);
  19247. var end = Math.max(start, playlistEnd);
  19248. return {
  19249. duration: Infinity,
  19250. start: start,
  19251. end: end
  19252. };
  19253. }
  19254. return {
  19255. duration: Infinity
  19256. };
  19257. }
  19258. var overrideDuration = (_this$overrides2 = this.overrides) == null ? void 0 : _this$overrides2.duration;
  19259. if (overrideDuration) {
  19260. if (!isFiniteNumber(overrideDuration)) {
  19261. return null;
  19262. }
  19263. return {
  19264. duration: overrideDuration
  19265. };
  19266. }
  19267. var mediaDuration = this.media.duration;
  19268. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : 0;
  19269. if (playlistEnd > msDuration && playlistEnd > mediaDuration || !isFiniteNumber(mediaDuration)) {
  19270. return {
  19271. duration: playlistEnd
  19272. };
  19273. }
  19274. return null;
  19275. };
  19276. _proto.updateMediaSource = function updateMediaSource(_ref1) {
  19277. var duration = _ref1.duration,
  19278. start = _ref1.start,
  19279. end = _ref1.end;
  19280. var mediaSource = this.mediaSource;
  19281. if (!this.media || !mediaSource || mediaSource.readyState !== 'open') {
  19282. return;
  19283. }
  19284. if (mediaSource.duration !== duration) {
  19285. if (isFiniteNumber(duration)) {
  19286. this.log("Updating MediaSource duration to " + duration.toFixed(3));
  19287. }
  19288. mediaSource.duration = duration;
  19289. }
  19290. if (start !== undefined && end !== undefined) {
  19291. this.log("MediaSource duration is set to " + mediaSource.duration + ". Setting seekable range to " + start + "-" + end + ".");
  19292. mediaSource.setLiveSeekableRange(start, end);
  19293. }
  19294. };
  19295. _proto.checkPendingTracks = function checkPendingTracks() {
  19296. var bufferCodecEventsTotal = this.bufferCodecEventsTotal,
  19297. pendingTrackCount = this.pendingTrackCount,
  19298. tracks = this.tracks;
  19299. this.log("checkPendingTracks (pending: " + pendingTrackCount + " codec events expected: " + bufferCodecEventsTotal + ") " + stringify(tracks));
  19300. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  19301. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  19302. // data has been appended to existing ones.
  19303. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  19304. if (this.tracksReady) {
  19305. var _this$transferData3;
  19306. var transferredTracks = (_this$transferData3 = this.transferData) == null ? void 0 : _this$transferData3.tracks;
  19307. if (transferredTracks && Object.keys(transferredTracks).length) {
  19308. this.attachTransferred();
  19309. } else {
  19310. // ok, let's create them now !
  19311. this.createSourceBuffers();
  19312. }
  19313. }
  19314. };
  19315. _proto.bufferCreated = function bufferCreated() {
  19316. var _this19 = this;
  19317. if (this.sourceBufferCount) {
  19318. var tracks = {};
  19319. this.sourceBuffers.forEach(function (_ref10) {
  19320. var type = _ref10[0],
  19321. buffer = _ref10[1];
  19322. if (type) {
  19323. var track = _this19.tracks[type];
  19324. tracks[type] = {
  19325. buffer: buffer,
  19326. container: track.container,
  19327. codec: track.codec,
  19328. supplemental: track.supplemental,
  19329. levelCodec: track.levelCodec,
  19330. id: track.id,
  19331. metadata: track.metadata
  19332. };
  19333. }
  19334. });
  19335. this.hls.trigger(Events.BUFFER_CREATED, {
  19336. tracks: tracks
  19337. });
  19338. this.log("SourceBuffers created. Running queue: " + this.operationQueue);
  19339. this.sourceBuffers.forEach(function (_ref11) {
  19340. var type = _ref11[0];
  19341. _this19.executeNext(type);
  19342. });
  19343. } else {
  19344. var error = new Error('could not create source buffer for media codec(s)');
  19345. this.hls.trigger(Events.ERROR, {
  19346. type: ErrorTypes.MEDIA_ERROR,
  19347. details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,
  19348. fatal: true,
  19349. error: error,
  19350. reason: error.message
  19351. });
  19352. }
  19353. };
  19354. _proto.createSourceBuffers = function createSourceBuffers() {
  19355. var tracks = this.tracks,
  19356. sourceBuffers = this.sourceBuffers,
  19357. mediaSource = this.mediaSource;
  19358. if (!mediaSource) {
  19359. throw new Error('createSourceBuffers called when mediaSource was null');
  19360. }
  19361. for (var trackName in tracks) {
  19362. var type = trackName;
  19363. var track = tracks[type];
  19364. if (this.isPending(track)) {
  19365. var codec = this.getTrackCodec(track, type);
  19366. var mimeType = track.container + ";codecs=" + codec;
  19367. track.codec = codec;
  19368. this.log("creating sourceBuffer(" + mimeType + ")" + (this.currentOp(type) ? ' Queued' : '') + " " + stringify(track));
  19369. try {
  19370. var sb = mediaSource.addSourceBuffer(mimeType);
  19371. var sbIndex = sourceBufferNameToIndex(type);
  19372. var sbTuple = [type, sb];
  19373. sourceBuffers[sbIndex] = sbTuple;
  19374. track.buffer = sb;
  19375. } catch (error) {
  19376. var _this$operationQueue;
  19377. this.error("error while trying to add sourceBuffer: " + error.message);
  19378. // remove init segment from queue and delete track info
  19379. this.shiftAndExecuteNext(type);
  19380. (_this$operationQueue = this.operationQueue) == null ? void 0 : _this$operationQueue.removeBlockers();
  19381. delete this.tracks[type];
  19382. this.hls.trigger(Events.ERROR, {
  19383. type: ErrorTypes.MEDIA_ERROR,
  19384. details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,
  19385. fatal: false,
  19386. error: error,
  19387. sourceBufferName: type,
  19388. mimeType: mimeType,
  19389. parent: track.id
  19390. });
  19391. return;
  19392. }
  19393. this.trackSourceBuffer(type, track);
  19394. }
  19395. }
  19396. this.bufferCreated();
  19397. };
  19398. _proto.getTrackCodec = function getTrackCodec(track, trackName) {
  19399. // Use supplemental video codec when supported when adding SourceBuffer (#5558)
  19400. var supplementalCodec = track.supplemental;
  19401. var trackCodec = track.codec;
  19402. if (supplementalCodec && (trackName === 'video' || trackName === 'audiovideo') && areCodecsMediaSourceSupported(supplementalCodec, 'video')) {
  19403. trackCodec = replaceVideoCodec(trackCodec, supplementalCodec);
  19404. }
  19405. var codec = pickMostCompleteCodecName(trackCodec, track.levelCodec);
  19406. if (codec) {
  19407. if (trackName.slice(0, 5) === 'audio') {
  19408. return getCodecCompatibleName(codec, this.appendSource);
  19409. }
  19410. return codec;
  19411. }
  19412. return '';
  19413. };
  19414. _proto.trackSourceBuffer = function trackSourceBuffer(type, track) {
  19415. var _this20 = this;
  19416. var buffer = track.buffer;
  19417. if (!buffer) {
  19418. return;
  19419. }
  19420. var codec = this.getTrackCodec(track, type);
  19421. this.tracks[type] = {
  19422. buffer: buffer,
  19423. codec: codec,
  19424. container: track.container,
  19425. levelCodec: track.levelCodec,
  19426. supplemental: track.supplemental,
  19427. metadata: track.metadata,
  19428. id: track.id,
  19429. listeners: []
  19430. };
  19431. this.removeBufferListeners(type);
  19432. this.addBufferListener(type, 'updatestart', this.onSBUpdateStart);
  19433. this.addBufferListener(type, 'updateend', this.onSBUpdateEnd);
  19434. this.addBufferListener(type, 'error', this.onSBUpdateError);
  19435. // ManagedSourceBuffer bufferedchange event
  19436. if (this.appendSource) {
  19437. this.addBufferListener(type, 'bufferedchange', function (type, event) {
  19438. // If media was ejected check for a change. Added ranges are redundant with changes on 'updateend' event.
  19439. var removedRanges = event.removedRanges;
  19440. if (removedRanges != null && removedRanges.length) {
  19441. _this20.hls.trigger(Events.BUFFER_FLUSHED, {
  19442. type: type
  19443. });
  19444. }
  19445. });
  19446. }
  19447. };
  19448. _proto.onSBUpdateStart = function onSBUpdateStart(type) {
  19449. var operation = this.currentOp(type);
  19450. if (!operation) {
  19451. return;
  19452. }
  19453. operation.onStart();
  19454. };
  19455. _proto.onSBUpdateEnd = function onSBUpdateEnd(type) {
  19456. var _this$mediaSource2;
  19457. if (((_this$mediaSource2 = this.mediaSource) == null ? void 0 : _this$mediaSource2.readyState) === 'closed') {
  19458. this.resetBuffer(type);
  19459. return;
  19460. }
  19461. var operation = this.currentOp(type);
  19462. if (!operation) {
  19463. return;
  19464. }
  19465. operation.onComplete();
  19466. this.shiftAndExecuteNext(type);
  19467. };
  19468. _proto.onSBUpdateError = function onSBUpdateError(type, event) {
  19469. var _this$mediaSource3;
  19470. var error = new Error(type + " SourceBuffer error. MediaSource readyState: " + ((_this$mediaSource3 = this.mediaSource) == null ? void 0 : _this$mediaSource3.readyState));
  19471. this.error("" + error, event);
  19472. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  19473. // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
  19474. this.hls.trigger(Events.ERROR, {
  19475. type: ErrorTypes.MEDIA_ERROR,
  19476. details: ErrorDetails.BUFFER_APPENDING_ERROR,
  19477. sourceBufferName: type,
  19478. error: error,
  19479. fatal: false
  19480. });
  19481. // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
  19482. var operation = this.currentOp(type);
  19483. if (operation) {
  19484. operation.onError(error);
  19485. }
  19486. };
  19487. _proto.updateTimestampOffset = function updateTimestampOffset(sb, timestampOffset, tolerance, type, sn, cc) {
  19488. var delta = timestampOffset - sb.timestampOffset;
  19489. if (Math.abs(delta) >= tolerance) {
  19490. this.log("Updating " + type + " SourceBuffer timestampOffset to " + timestampOffset + " (sn: " + sn + " cc: " + cc + ")");
  19491. sb.timestampOffset = timestampOffset;
  19492. }
  19493. }
  19494. // This method must result in an updateend event; if remove is not called, onSBUpdateEnd must be called manually
  19495. ;
  19496. _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
  19497. var media = this.media,
  19498. mediaSource = this.mediaSource;
  19499. var track = this.tracks[type];
  19500. var sb = track == null ? void 0 : track.buffer;
  19501. if (!media || !mediaSource || !sb) {
  19502. this.warn("Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
  19503. this.shiftAndExecuteNext(type);
  19504. return;
  19505. }
  19506. var mediaDuration = isFiniteNumber(media.duration) ? media.duration : Infinity;
  19507. var msDuration = isFiniteNumber(mediaSource.duration) ? mediaSource.duration : Infinity;
  19508. var removeStart = Math.max(0, startOffset);
  19509. var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
  19510. if (removeEnd > removeStart && (!track.ending || track.ended)) {
  19511. track.ended = false;
  19512. this.log("Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
  19513. sb.remove(removeStart, removeEnd);
  19514. } else {
  19515. // Cycle the queue
  19516. this.shiftAndExecuteNext(type);
  19517. }
  19518. }
  19519. // This method must result in an updateend event; if append is not called, onSBUpdateEnd must be called manually
  19520. ;
  19521. _proto.appendExecutor = function appendExecutor(data, type) {
  19522. var track = this.tracks[type];
  19523. var sb = track == null ? void 0 : track.buffer;
  19524. if (!sb) {
  19525. throw new HlsJsTrackRemovedError("Attempting to append to the " + type + " SourceBuffer, but it does not exist");
  19526. }
  19527. track.ending = false;
  19528. track.ended = false;
  19529. sb.appendBuffer(data);
  19530. };
  19531. _proto.blockUntilOpen = function blockUntilOpen(callback) {
  19532. var _this21 = this;
  19533. if (this.isUpdating() || this.isQueued()) {
  19534. this.blockBuffers(callback).catch(function (error) {
  19535. _this21.warn("SourceBuffer blocked callback " + error);
  19536. _this21.stepOperationQueue(_this21.sourceBufferTypes);
  19537. });
  19538. } else {
  19539. try {
  19540. callback();
  19541. } catch (error) {
  19542. this.warn("Callback run without blocking " + this.operationQueue + " " + error);
  19543. }
  19544. }
  19545. };
  19546. _proto.isUpdating = function isUpdating() {
  19547. return this.sourceBuffers.some(function (_ref12) {
  19548. var type = _ref12[0],
  19549. sb = _ref12[1];
  19550. return type && sb.updating;
  19551. });
  19552. };
  19553. _proto.isQueued = function isQueued() {
  19554. var _this22 = this;
  19555. return this.sourceBuffers.some(function (_ref13) {
  19556. var type = _ref13[0];
  19557. return type && !!_this22.currentOp(type);
  19558. });
  19559. };
  19560. _proto.isPending = function isPending(track) {
  19561. return !!track && !track.buffer;
  19562. }
  19563. // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
  19564. // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
  19565. // upon completion, since we already do it here
  19566. ;
  19567. _proto.blockBuffers = function blockBuffers(onUnblocked, bufferNames) {
  19568. var _this23 = this;
  19569. if (bufferNames === void 0) {
  19570. bufferNames = this.sourceBufferTypes;
  19571. }
  19572. if (!bufferNames.length) {
  19573. this.log('Blocking operation requested, but no SourceBuffers exist');
  19574. return Promise.resolve().then(onUnblocked);
  19575. }
  19576. var operationQueue = this.operationQueue;
  19577. // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
  19578. var blockingOperations = bufferNames.map(function (type) {
  19579. return _this23.appendBlocker(type);
  19580. });
  19581. var audioBlocked = bufferNames.length > 1 && !!this.blockedAudioAppend;
  19582. if (audioBlocked) {
  19583. this.unblockAudio();
  19584. }
  19585. return Promise.all(blockingOperations).then(function (result) {
  19586. if (operationQueue !== _this23.operationQueue) {
  19587. return;
  19588. }
  19589. // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
  19590. onUnblocked();
  19591. _this23.stepOperationQueue(_this23.sourceBufferTypes);
  19592. });
  19593. };
  19594. _proto.stepOperationQueue = function stepOperationQueue(bufferNames) {
  19595. var _this24 = this;
  19596. bufferNames.forEach(function (type) {
  19597. var _this24$tracks$type;
  19598. var sb = (_this24$tracks$type = _this24.tracks[type]) == null ? void 0 : _this24$tracks$type.buffer;
  19599. // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
  19600. // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
  19601. // While this is a workaround, it's probably useful to have around
  19602. if (!sb || sb.updating) {
  19603. return;
  19604. }
  19605. _this24.shiftAndExecuteNext(type);
  19606. });
  19607. };
  19608. _proto.append = function append(operation, type, pending) {
  19609. if (this.operationQueue) {
  19610. this.operationQueue.append(operation, type, pending);
  19611. }
  19612. };
  19613. _proto.appendBlocker = function appendBlocker(type) {
  19614. if (this.operationQueue) {
  19615. return this.operationQueue.appendBlocker(type);
  19616. }
  19617. };
  19618. _proto.currentOp = function currentOp(type) {
  19619. if (this.operationQueue) {
  19620. return this.operationQueue.current(type);
  19621. }
  19622. return null;
  19623. };
  19624. _proto.executeNext = function executeNext(type) {
  19625. if (type && this.operationQueue) {
  19626. this.operationQueue.executeNext(type);
  19627. }
  19628. };
  19629. _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
  19630. if (this.operationQueue) {
  19631. this.operationQueue.shiftAndExecuteNext(type);
  19632. }
  19633. };
  19634. _proto.addBufferListener = function addBufferListener(type, event, fn) {
  19635. var track = this.tracks[type];
  19636. if (!track) {
  19637. return;
  19638. }
  19639. var buffer = track.buffer;
  19640. if (!buffer) {
  19641. return;
  19642. }
  19643. var listener = fn.bind(this, type);
  19644. track.listeners.push({
  19645. event: event,
  19646. listener: listener
  19647. });
  19648. buffer.addEventListener(event, listener);
  19649. };
  19650. _proto.removeBufferListeners = function removeBufferListeners(type) {
  19651. var track = this.tracks[type];
  19652. if (!track) {
  19653. return;
  19654. }
  19655. var buffer = track.buffer;
  19656. if (!buffer) {
  19657. return;
  19658. }
  19659. track.listeners.forEach(function (l) {
  19660. buffer.removeEventListener(l.event, l.listener);
  19661. });
  19662. track.listeners.length = 0;
  19663. };
  19664. return _createClass(BufferController, [{
  19665. key: "mediaSourceOpenOrEnded",
  19666. get: function get() {
  19667. var _this$mediaSource4;
  19668. var readyState = (_this$mediaSource4 = this.mediaSource) == null ? void 0 : _this$mediaSource4.readyState;
  19669. return readyState === 'open' || readyState === 'ended';
  19670. }
  19671. }, {
  19672. key: "sourceBufferTracks",
  19673. get: function get() {
  19674. var _this25 = this;
  19675. return Object.keys(this.tracks).reduce(function (baseTracks, type) {
  19676. var track = _this25.tracks[type];
  19677. baseTracks[type] = {
  19678. id: track.id,
  19679. container: track.container,
  19680. codec: track.codec,
  19681. levelCodec: track.levelCodec
  19682. };
  19683. return baseTracks;
  19684. }, {});
  19685. }
  19686. }, {
  19687. key: "bufferedToEnd",
  19688. get: function get() {
  19689. var _this26 = this;
  19690. return this.sourceBufferCount > 0 && !this.sourceBuffers.some(function (_ref14) {
  19691. var _this26$tracks$type, _this26$tracks$type2;
  19692. var type = _ref14[0];
  19693. return type && (!((_this26$tracks$type = _this26.tracks[type]) != null && _this26$tracks$type.ended) || ((_this26$tracks$type2 = _this26.tracks[type]) == null ? void 0 : _this26$tracks$type2.ending));
  19694. });
  19695. }
  19696. }, {
  19697. key: "tracksReady",
  19698. get: function get() {
  19699. var pendingTrackCount = this.pendingTrackCount;
  19700. return pendingTrackCount > 0 && (pendingTrackCount >= this.bufferCodecEventsTotal || this.isPending(this.tracks.audiovideo));
  19701. }
  19702. }, {
  19703. key: "mediaSrc",
  19704. get: function get() {
  19705. var _this$media, _this$media$querySele;
  19706. var media = ((_this$media = this.media) == null ? void 0 : (_this$media$querySele = _this$media.querySelector) == null ? void 0 : _this$media$querySele.call(_this$media, 'source')) || this.media;
  19707. return media == null ? void 0 : media.src;
  19708. }
  19709. }, {
  19710. key: "pendingTrackCount",
  19711. get: function get() {
  19712. var _this27 = this;
  19713. return Object.keys(this.tracks).reduce(function (acc, type) {
  19714. return acc + (_this27.isPending(_this27.tracks[type]) ? 1 : 0);
  19715. }, 0);
  19716. }
  19717. }, {
  19718. key: "sourceBufferCount",
  19719. get: function get() {
  19720. return this.sourceBuffers.reduce(function (acc, _ref15) {
  19721. var type = _ref15[0];
  19722. return acc + (type ? 1 : 0);
  19723. }, 0);
  19724. }
  19725. }, {
  19726. key: "sourceBufferTypes",
  19727. get: function get() {
  19728. return this.sourceBuffers.map(function (_ref16) {
  19729. var type = _ref16[0];
  19730. return type;
  19731. }).filter(function (type) {
  19732. return !!type;
  19733. });
  19734. }
  19735. }]);
  19736. }(Logger);
  19737. function removeSourceChildren(node) {
  19738. var sourceChildren = node.querySelectorAll('source');
  19739. [].slice.call(sourceChildren).forEach(function (source) {
  19740. node.removeChild(source);
  19741. });
  19742. }
  19743. function addSource(media, url) {
  19744. var source = self.document.createElement('source');
  19745. source.type = 'video/mp4';
  19746. source.src = url;
  19747. media.appendChild(source);
  19748. }
  19749. function sourceBufferNameToIndex(type) {
  19750. return type === 'audio' ? 1 : 0;
  19751. }
  19752. var CapLevelController = /*#__PURE__*/function () {
  19753. function CapLevelController(hls) {
  19754. this.hls = void 0;
  19755. this.autoLevelCapping = void 0;
  19756. this.firstLevel = void 0;
  19757. this.media = void 0;
  19758. this.restrictedLevels = void 0;
  19759. this.timer = void 0;
  19760. this.clientRect = void 0;
  19761. this.streamController = void 0;
  19762. this.hls = hls;
  19763. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19764. this.firstLevel = -1;
  19765. this.media = null;
  19766. this.restrictedLevels = [];
  19767. this.timer = undefined;
  19768. this.clientRect = null;
  19769. this.registerListeners();
  19770. }
  19771. var _proto = CapLevelController.prototype;
  19772. _proto.setStreamController = function setStreamController(streamController) {
  19773. this.streamController = streamController;
  19774. };
  19775. _proto.destroy = function destroy() {
  19776. if (this.hls) {
  19777. this.unregisterListener();
  19778. }
  19779. if (this.timer) {
  19780. this.stopCapping();
  19781. }
  19782. this.media = null;
  19783. this.clientRect = null;
  19784. // @ts-ignore
  19785. this.hls = this.streamController = null;
  19786. };
  19787. _proto.registerListeners = function registerListeners() {
  19788. var hls = this.hls;
  19789. hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  19790. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19791. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19792. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19793. hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  19794. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19795. };
  19796. _proto.unregisterListener = function unregisterListener() {
  19797. var hls = this.hls;
  19798. hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
  19799. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  19800. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  19801. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  19802. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  19803. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  19804. };
  19805. _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
  19806. // Don't add a restricted level more than once
  19807. var level = this.hls.levels[data.droppedLevel];
  19808. if (this.isLevelAllowed(level)) {
  19809. this.restrictedLevels.push({
  19810. bitrate: level.bitrate,
  19811. height: level.height,
  19812. width: level.width
  19813. });
  19814. }
  19815. };
  19816. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  19817. this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  19818. this.clientRect = null;
  19819. if (this.timer && this.hls.levels.length) {
  19820. this.detectPlayerSize();
  19821. }
  19822. };
  19823. _proto.onManifestParsed = function onManifestParsed(event, data) {
  19824. var hls = this.hls;
  19825. this.restrictedLevels = [];
  19826. this.firstLevel = data.firstLevel;
  19827. if (hls.config.capLevelToPlayerSize && data.video) {
  19828. // Start capping immediately if the manifest has signaled video codecs
  19829. this.startCapping();
  19830. }
  19831. };
  19832. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  19833. if (this.timer && isFiniteNumber(this.autoLevelCapping)) {
  19834. this.detectPlayerSize();
  19835. }
  19836. }
  19837. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  19838. // to the first level
  19839. ;
  19840. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  19841. var hls = this.hls;
  19842. if (hls.config.capLevelToPlayerSize && data.video) {
  19843. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  19844. this.startCapping();
  19845. }
  19846. };
  19847. _proto.onMediaDetaching = function onMediaDetaching() {
  19848. this.stopCapping();
  19849. this.media = null;
  19850. };
  19851. _proto.detectPlayerSize = function detectPlayerSize() {
  19852. if (this.media) {
  19853. if (this.mediaHeight <= 0 || this.mediaWidth <= 0) {
  19854. this.clientRect = null;
  19855. return;
  19856. }
  19857. var levels = this.hls.levels;
  19858. if (levels.length) {
  19859. var hls = this.hls;
  19860. var maxLevel = this.getMaxLevel(levels.length - 1);
  19861. if (maxLevel !== this.autoLevelCapping) {
  19862. hls.logger.log("Setting autoLevelCapping to " + maxLevel + ": " + levels[maxLevel].height + "p@" + levels[maxLevel].bitrate + " for media " + this.mediaWidth + "x" + this.mediaHeight);
  19863. }
  19864. hls.autoLevelCapping = maxLevel;
  19865. if (hls.autoLevelEnabled && hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
  19866. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  19867. // usually happen when the user go to the fullscreen mode.
  19868. this.streamController.nextLevelSwitch();
  19869. }
  19870. this.autoLevelCapping = hls.autoLevelCapping;
  19871. }
  19872. }
  19873. }
  19874. /*
  19875. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  19876. */;
  19877. _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
  19878. var _this = this;
  19879. var levels = this.hls.levels;
  19880. if (!levels.length) {
  19881. return -1;
  19882. }
  19883. var validLevels = levels.filter(function (level, index) {
  19884. return _this.isLevelAllowed(level) && index <= capLevelIndex;
  19885. });
  19886. this.clientRect = null;
  19887. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  19888. };
  19889. _proto.startCapping = function startCapping() {
  19890. if (this.timer) {
  19891. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  19892. return;
  19893. }
  19894. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19895. self.clearInterval(this.timer);
  19896. this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
  19897. this.detectPlayerSize();
  19898. };
  19899. _proto.stopCapping = function stopCapping() {
  19900. this.restrictedLevels = [];
  19901. this.firstLevel = -1;
  19902. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  19903. if (this.timer) {
  19904. self.clearInterval(this.timer);
  19905. this.timer = undefined;
  19906. }
  19907. };
  19908. _proto.getDimensions = function getDimensions() {
  19909. if (this.clientRect) {
  19910. return this.clientRect;
  19911. }
  19912. var media = this.media;
  19913. var boundsRect = {
  19914. width: 0,
  19915. height: 0
  19916. };
  19917. if (media) {
  19918. var clientRect = media.getBoundingClientRect();
  19919. boundsRect.width = clientRect.width;
  19920. boundsRect.height = clientRect.height;
  19921. if (!boundsRect.width && !boundsRect.height) {
  19922. // When the media element has no width or height (equivalent to not being in the DOM),
  19923. // then use its width and height attributes (media.width, media.height)
  19924. boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
  19925. boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
  19926. }
  19927. }
  19928. this.clientRect = boundsRect;
  19929. return boundsRect;
  19930. };
  19931. _proto.isLevelAllowed = function isLevelAllowed(level) {
  19932. var restrictedLevels = this.restrictedLevels;
  19933. return !restrictedLevels.some(function (restrictedLevel) {
  19934. return level.bitrate === restrictedLevel.bitrate && level.width === restrictedLevel.width && level.height === restrictedLevel.height;
  19935. });
  19936. };
  19937. CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
  19938. if (!(levels != null && levels.length)) {
  19939. return -1;
  19940. }
  19941. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  19942. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  19943. var atGreatestBandwidth = function atGreatestBandwidth(curLevel, nextLevel) {
  19944. if (!nextLevel) {
  19945. return true;
  19946. }
  19947. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  19948. };
  19949. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  19950. // the max level
  19951. var maxLevelIndex = levels.length - 1;
  19952. // Prevent changes in aspect-ratio from causing capping to toggle back and forth
  19953. var squareSize = Math.max(width, height);
  19954. for (var i = 0; i < levels.length; i += 1) {
  19955. var level = levels[i];
  19956. if ((level.width >= squareSize || level.height >= squareSize) && atGreatestBandwidth(level, levels[i + 1])) {
  19957. maxLevelIndex = i;
  19958. break;
  19959. }
  19960. }
  19961. return maxLevelIndex;
  19962. };
  19963. return _createClass(CapLevelController, [{
  19964. key: "mediaWidth",
  19965. get: function get() {
  19966. return this.getDimensions().width * this.contentScaleFactor;
  19967. }
  19968. }, {
  19969. key: "mediaHeight",
  19970. get: function get() {
  19971. return this.getDimensions().height * this.contentScaleFactor;
  19972. }
  19973. }, {
  19974. key: "contentScaleFactor",
  19975. get: function get() {
  19976. var pixelRatio = 1;
  19977. if (!this.hls.config.ignoreDevicePixelRatio) {
  19978. try {
  19979. pixelRatio = self.devicePixelRatio;
  19980. } catch (e) {
  19981. /* no-op */
  19982. }
  19983. }
  19984. return Math.min(pixelRatio, this.hls.config.maxDevicePixelRatio);
  19985. }
  19986. }]);
  19987. }();
  19988. /**
  19989. * Common Media Object Type
  19990. *
  19991. * @internal
  19992. */
  19993. var CmObjectType = {
  19994. /**
  19995. * text file, such as a manifest or playlist
  19996. */
  19997. MANIFEST: 'm',
  19998. /**
  19999. * audio only
  20000. */
  20001. AUDIO: 'a',
  20002. /**
  20003. * video only
  20004. */
  20005. VIDEO: 'v',
  20006. /**
  20007. * muxed audio and video
  20008. */
  20009. MUXED: 'av',
  20010. /**
  20011. * init segment
  20012. */
  20013. INIT: 'i',
  20014. /**
  20015. * caption or subtitle
  20016. */
  20017. CAPTION: 'c',
  20018. /**
  20019. * ISOBMFF timed text track
  20020. */
  20021. TIMED_TEXT: 'tt',
  20022. /**
  20023. * cryptographic key, license or certificate.
  20024. */
  20025. KEY: 'k',
  20026. /**
  20027. * other
  20028. */
  20029. OTHER: 'o'
  20030. };
  20031. /**
  20032. * Common Media Client Data Object Type
  20033. *
  20034. * @group CMCD
  20035. *
  20036. * @beta
  20037. *
  20038. * @enum
  20039. */
  20040. var CmcdObjectType = CmObjectType;
  20041. /**
  20042. * Common Media Streaming Format
  20043. *
  20044. * @internal
  20045. */
  20046. var CmStreamingFormat = {
  20047. /**
  20048. * HTTP Live Streaming (HLS)
  20049. */
  20050. HLS: 'h'};
  20051. /**
  20052. * Common Media Client Data Streaming Format
  20053. *
  20054. * @group CMCD
  20055. *
  20056. * @enum
  20057. *
  20058. * @beta
  20059. */
  20060. var CmcdStreamingFormat = CmStreamingFormat;
  20061. /**
  20062. * CMCD object header name.
  20063. *
  20064. * @group CMCD
  20065. *
  20066. * @beta
  20067. */
  20068. var CMCD_OBJECT = 'CMCD-Object';
  20069. /**
  20070. * CMCD request header name.
  20071. *
  20072. * @group CMCD
  20073. *
  20074. * @beta
  20075. */
  20076. var CMCD_REQUEST = 'CMCD-Request';
  20077. /**
  20078. * CMCD session header name.
  20079. *
  20080. * @group CMCD
  20081. *
  20082. * @beta
  20083. */
  20084. var CMCD_SESSION = 'CMCD-Session';
  20085. /**
  20086. * CMCD status header name.
  20087. *
  20088. * @group CMCD
  20089. *
  20090. * @beta
  20091. */
  20092. var CMCD_STATUS = 'CMCD-Status';
  20093. /**
  20094. * CMCD header fields.
  20095. *
  20096. * @group CMCD
  20097. *
  20098. * @enum
  20099. *
  20100. * @beta
  20101. */
  20102. var CmcdHeaderField = {
  20103. /**
  20104. * keys whose values vary with the object being requested.
  20105. */
  20106. OBJECT: CMCD_OBJECT,
  20107. /**
  20108. * keys whose values vary with each request.
  20109. */
  20110. REQUEST: CMCD_REQUEST,
  20111. /**
  20112. * keys whose values are expected to be invariant over the life of the session.
  20113. */
  20114. SESSION: CMCD_SESSION,
  20115. /**
  20116. * keys whose values do not vary with every request or object.
  20117. */
  20118. STATUS: CMCD_STATUS
  20119. };
  20120. var _CmcdHeaderMap;
  20121. /**
  20122. * The map of CMCD header fields to official CMCD keys.
  20123. *
  20124. * @internal
  20125. *
  20126. * @group CMCD
  20127. */
  20128. var CmcdHeaderMap = (_CmcdHeaderMap = {}, _CmcdHeaderMap[CmcdHeaderField.OBJECT] = ['br', 'ab', 'd', 'ot', 'tb', 'tpb', 'lb', 'tab', 'lab', 'url'], _CmcdHeaderMap[CmcdHeaderField.REQUEST] = ['pb', 'bl', 'tbl', 'dl', 'ltc', 'mtp', 'nor', 'nrr', 'rc', 'sn', 'sta', 'su', 'ttfb', 'ttfbb', 'ttlb', 'cmsdd', 'cmsds', 'smrt', 'df', 'cs'], _CmcdHeaderMap[CmcdHeaderField.SESSION] = ['cid', 'pr', 'sf', 'sid', 'st', 'v', 'msd'], _CmcdHeaderMap[CmcdHeaderField.STATUS] = ['bs', 'bsd', 'cdn', 'rtp', 'bg', 'pt', 'ec', 'e'], _CmcdHeaderMap);
  20129. /**
  20130. * Structured Field Item
  20131. *
  20132. * @group Structured Field
  20133. *
  20134. * @beta
  20135. */
  20136. var SfItem = function SfItem(value, params) {
  20137. if (Array.isArray(value)) {
  20138. value = value.map(function (v) {
  20139. return v instanceof SfItem ? v : new SfItem(v);
  20140. });
  20141. }
  20142. this.value = value;
  20143. this.params = params;
  20144. };
  20145. var DICT = 'Dict';
  20146. function format(value) {
  20147. if (Array.isArray(value)) {
  20148. return JSON.stringify(value);
  20149. }
  20150. if (value instanceof Map) {
  20151. return 'Map{}';
  20152. }
  20153. if (value instanceof Set) {
  20154. return 'Set{}';
  20155. }
  20156. if (typeof value === 'object') {
  20157. return JSON.stringify(value);
  20158. }
  20159. return String(value);
  20160. }
  20161. function throwError(action, src, type, cause) {
  20162. return new Error("failed to " + action + " \"" + format(src) + "\" as " + type, {
  20163. cause: cause
  20164. });
  20165. }
  20166. function serializeError(src, type, cause) {
  20167. return throwError('serialize', src, type, cause);
  20168. }
  20169. /**
  20170. * A class to represent structured field tokens when `Symbol` is not available.
  20171. *
  20172. * @group Structured Field
  20173. *
  20174. * @beta
  20175. */
  20176. var SfToken = function SfToken(description) {
  20177. this.description = description;
  20178. };
  20179. var BARE_ITEM = 'Bare Item';
  20180. var BOOLEAN = 'Boolean';
  20181. // 4.1.9. Serializing a Boolean
  20182. //
  20183. // Given a Boolean as input_boolean, return an ASCII string suitable for
  20184. // use in a HTTP field value.
  20185. //
  20186. // 1. If input_boolean is not a boolean, fail serialization.
  20187. //
  20188. // 2. Let output be an empty string.
  20189. //
  20190. // 3. Append "?" to output.
  20191. //
  20192. // 4. If input_boolean is true, append "1" to output.
  20193. //
  20194. // 5. If input_boolean is false, append "0" to output.
  20195. //
  20196. // 6. Return output.
  20197. function serializeBoolean(value) {
  20198. if (typeof value !== 'boolean') {
  20199. throw serializeError(value, BOOLEAN);
  20200. }
  20201. return value ? '?1' : '?0';
  20202. }
  20203. /**
  20204. * Encodes binary data to base64
  20205. *
  20206. * @param binary - The binary data to encode
  20207. * @returns The base64 encoded string
  20208. *
  20209. * @group Utils
  20210. *
  20211. * @beta
  20212. */
  20213. function encodeBase64(binary) {
  20214. return btoa(String.fromCharCode.apply(String, binary));
  20215. }
  20216. var BYTES = 'Byte Sequence';
  20217. // 4.1.8. Serializing a Byte Sequence
  20218. //
  20219. // Given a Byte Sequence as input_bytes, return an ASCII string suitable
  20220. // for use in a HTTP field value.
  20221. //
  20222. // 1. If input_bytes is not a sequence of bytes, fail serialization.
  20223. //
  20224. // 2. Let output be an empty string.
  20225. //
  20226. // 3. Append ":" to output.
  20227. //
  20228. // 4. Append the result of base64-encoding input_bytes as per
  20229. // [RFC4648], Section 4, taking account of the requirements below.
  20230. //
  20231. // 5. Append ":" to output.
  20232. //
  20233. // 6. Return output.
  20234. //
  20235. // The encoded data is required to be padded with "=", as per [RFC4648],
  20236. // Section 3.2.
  20237. //
  20238. // Likewise, encoded data SHOULD have pad bits set to zero, as per
  20239. // [RFC4648], Section 3.5, unless it is not possible to do so due to
  20240. // implementation constraints.
  20241. function serializeByteSequence(value) {
  20242. if (ArrayBuffer.isView(value) === false) {
  20243. throw serializeError(value, BYTES);
  20244. }
  20245. return ":" + encodeBase64(value) + ":";
  20246. }
  20247. var INTEGER = 'Integer';
  20248. function isInvalidInt(value) {
  20249. return value < -999999999999999 || 999999999999999 < value;
  20250. }
  20251. // 4.1.4. Serializing an Integer
  20252. //
  20253. // Given an Integer as input_integer, return an ASCII string suitable
  20254. // for use in a HTTP field value.
  20255. //
  20256. // 1. If input_integer is not an integer in the range of
  20257. // -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
  20258. // serialization.
  20259. //
  20260. // 2. Let output be an empty string.
  20261. //
  20262. // 3. If input_integer is less than (but not equal to) 0, append "-" to
  20263. // output.
  20264. //
  20265. // 4. Append input_integer's numeric value represented in base 10 using
  20266. // only decimal digits to output.
  20267. //
  20268. // 5. Return output.
  20269. function serializeInteger(value) {
  20270. if (isInvalidInt(value)) {
  20271. throw serializeError(value, INTEGER);
  20272. }
  20273. return value.toString();
  20274. }
  20275. // 4.1.10. Serializing a Date
  20276. //
  20277. // Given a Date as input_integer, return an ASCII string suitable for
  20278. // use in an HTTP field value.
  20279. // 1. Let output be "@".
  20280. // 2. Append to output the result of running Serializing an Integer
  20281. // with input_date (Section 4.1.4).
  20282. // 3. Return output.
  20283. function serializeDate(value) {
  20284. return "@" + serializeInteger(value.getTime() / 1000);
  20285. }
  20286. /**
  20287. * This implements the rounding procedure described in step 2 of the "Serializing a Decimal" specification.
  20288. * This rounding style is known as "even rounding", "banker's rounding", or "commercial rounding".
  20289. *
  20290. * @param value - The value to round
  20291. * @param precision - The number of decimal places to round to
  20292. * @returns The rounded value
  20293. *
  20294. * @group Utils
  20295. *
  20296. * @beta
  20297. */
  20298. function roundToEven(value, precision) {
  20299. if (value < 0) {
  20300. return -roundToEven(-value, precision);
  20301. }
  20302. var decimalShift = Math.pow(10, precision);
  20303. var isEquidistant = Math.abs(value * decimalShift % 1 - 0.5) < Number.EPSILON;
  20304. if (isEquidistant) {
  20305. // If the tail of the decimal place is 'equidistant' we round to the nearest even value
  20306. var flooredValue = Math.floor(value * decimalShift);
  20307. return (flooredValue % 2 === 0 ? flooredValue : flooredValue + 1) / decimalShift;
  20308. } else {
  20309. // Otherwise, proceed as normal
  20310. return Math.round(value * decimalShift) / decimalShift;
  20311. }
  20312. }
  20313. var DECIMAL = 'Decimal';
  20314. // 4.1.5. Serializing a Decimal
  20315. //
  20316. // Given a decimal number as input_decimal, return an ASCII string
  20317. // suitable for use in a HTTP field value.
  20318. //
  20319. // 1. If input_decimal is not a decimal number, fail serialization.
  20320. //
  20321. // 2. If input_decimal has more than three significant digits to the
  20322. // right of the decimal point, round it to three decimal places,
  20323. // rounding the final digit to the nearest value, or to the even
  20324. // value if it is equidistant.
  20325. //
  20326. // 3. If input_decimal has more than 12 significant digits to the left
  20327. // of the decimal point after rounding, fail serialization.
  20328. //
  20329. // 4. Let output be an empty string.
  20330. //
  20331. // 5. If input_decimal is less than (but not equal to) 0, append "-"
  20332. // to output.
  20333. //
  20334. // 6. Append input_decimal's integer component represented in base 10
  20335. // (using only decimal digits) to output; if it is zero, append
  20336. // "0".
  20337. //
  20338. // 7. Append "." to output.
  20339. //
  20340. // 8. If input_decimal's fractional component is zero, append "0" to
  20341. // output.
  20342. //
  20343. // 9. Otherwise, append the significant digits of input_decimal's
  20344. // fractional component represented in base 10 (using only decimal
  20345. // digits) to output.
  20346. //
  20347. // 10. Return output.
  20348. function serializeDecimal(value) {
  20349. var roundedValue = roundToEven(value, 3); // round to 3 decimal places
  20350. if (Math.floor(Math.abs(roundedValue)).toString().length > 12) {
  20351. throw serializeError(value, DECIMAL);
  20352. }
  20353. var stringValue = roundedValue.toString();
  20354. return stringValue.includes('.') ? stringValue : stringValue + ".0";
  20355. }
  20356. var STRING = 'String';
  20357. var STRING_REGEX = /[\x00-\x1f\x7f]+/;
  20358. // 4.1.6. Serializing a String
  20359. //
  20360. // Given a String as input_string, return an ASCII string suitable for
  20361. // use in a HTTP field value.
  20362. //
  20363. // 1. Convert input_string into a sequence of ASCII characters; if
  20364. // conversion fails, fail serialization.
  20365. //
  20366. // 2. If input_string contains characters in the range %x00-1f or %x7f
  20367. // (i.e., not in VCHAR or SP), fail serialization.
  20368. //
  20369. // 3. Let output be the string DQUOTE.
  20370. //
  20371. // 4. For each character char in input_string:
  20372. //
  20373. // 1. If char is "\" or DQUOTE:
  20374. //
  20375. // 1. Append "\" to output.
  20376. //
  20377. // 2. Append char to output.
  20378. //
  20379. // 5. Append DQUOTE to output.
  20380. //
  20381. // 6. Return output.
  20382. function serializeString(value) {
  20383. if (STRING_REGEX.test(value)) {
  20384. throw serializeError(value, STRING);
  20385. }
  20386. return "\"" + value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
  20387. }
  20388. /**
  20389. * Converts a symbol to a string.
  20390. *
  20391. * @param symbol - The symbol to convert.
  20392. *
  20393. * @returns The string representation of the symbol.
  20394. *
  20395. * @internal
  20396. */
  20397. function symbolToStr(symbol) {
  20398. return symbol.description || symbol.toString().slice(7, -1);
  20399. }
  20400. var TOKEN = 'Token';
  20401. function serializeToken(token) {
  20402. var value = symbolToStr(token);
  20403. if (/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(value) === false) {
  20404. throw serializeError(value, TOKEN);
  20405. }
  20406. return value;
  20407. }
  20408. // 4.1.3.1. Serializing a Bare Item
  20409. //
  20410. // Given an Item as input_item, return an ASCII string suitable for use
  20411. // in a HTTP field value.
  20412. //
  20413. // 1. If input_item is an Integer, return the result of running
  20414. // Serializing an Integer (Section 4.1.4) with input_item.
  20415. //
  20416. // 2. If input_item is a Decimal, return the result of running
  20417. // Serializing a Decimal (Section 4.1.5) with input_item.
  20418. //
  20419. // 3. If input_item is a String, return the result of running
  20420. // Serializing a String (Section 4.1.6) with input_item.
  20421. //
  20422. // 4. If input_item is a Token, return the result of running
  20423. // Serializing a Token (Section 4.1.7) with input_item.
  20424. //
  20425. // 5. If input_item is a Boolean, return the result of running
  20426. // Serializing a Boolean (Section 4.1.9) with input_item.
  20427. //
  20428. // 6. If input_item is a Byte Sequence, return the result of running
  20429. // Serializing a Byte Sequence (Section 4.1.8) with input_item.
  20430. //
  20431. // 7. If input_item is a Date, return the result of running Serializing
  20432. // a Date (Section 4.1.10) with input_item.
  20433. //
  20434. // 8. Otherwise, fail serialization.
  20435. function serializeBareItem(value) {
  20436. switch (typeof value) {
  20437. case 'number':
  20438. if (!isFiniteNumber(value)) {
  20439. throw serializeError(value, BARE_ITEM);
  20440. }
  20441. if (Number.isInteger(value)) {
  20442. return serializeInteger(value);
  20443. }
  20444. return serializeDecimal(value);
  20445. case 'string':
  20446. return serializeString(value);
  20447. case 'symbol':
  20448. return serializeToken(value);
  20449. case 'boolean':
  20450. return serializeBoolean(value);
  20451. case 'object':
  20452. if (value instanceof Date) {
  20453. return serializeDate(value);
  20454. }
  20455. if (value instanceof Uint8Array) {
  20456. return serializeByteSequence(value);
  20457. }
  20458. if (value instanceof SfToken) {
  20459. return serializeToken(value);
  20460. }
  20461. default:
  20462. // fail
  20463. throw serializeError(value, BARE_ITEM);
  20464. }
  20465. }
  20466. var KEY = 'Key';
  20467. // 4.1.1.3. Serializing a Key
  20468. //
  20469. // Given a key as input_key, return an ASCII string suitable for use in
  20470. // a HTTP field value.
  20471. //
  20472. // 1. Convert input_key into a sequence of ASCII characters; if
  20473. // conversion fails, fail serialization.
  20474. //
  20475. // 2. If input_key contains characters not in lcalpha, DIGIT, "_", "-",
  20476. // ".", or "*" fail serialization.
  20477. //
  20478. // 3. If the first character of input_key is not lcalpha or "*", fail
  20479. // serialization.
  20480. //
  20481. // 4. Let output be an empty string.
  20482. //
  20483. // 5. Append input_key to output.
  20484. //
  20485. // 6. Return output.
  20486. function serializeKey(value) {
  20487. if (/^[a-z*][a-z0-9\-_.*]*$/.test(value) === false) {
  20488. throw serializeError(value, KEY);
  20489. }
  20490. return value;
  20491. }
  20492. // 4.1.1.2. Serializing Parameters
  20493. //
  20494. // Given an ordered Dictionary as input_parameters (each member having a
  20495. // param_name and a param_value), return an ASCII string suitable for
  20496. // use in a HTTP field value.
  20497. //
  20498. // 1. Let output be an empty string.
  20499. //
  20500. // 2. For each param_name with a value of param_value in
  20501. // input_parameters:
  20502. //
  20503. // 1. Append ";" to output.
  20504. //
  20505. // 2. Append the result of running Serializing a Key
  20506. // (Section 4.1.1.3) with param_name to output.
  20507. //
  20508. // 3. If param_value is not Boolean true:
  20509. //
  20510. // 1. Append "=" to output.
  20511. //
  20512. // 2. Append the result of running Serializing a bare Item
  20513. // (Section 4.1.3.1) with param_value to output.
  20514. //
  20515. // 3. Return output.
  20516. function serializeParams(params) {
  20517. if (params == null) {
  20518. return '';
  20519. }
  20520. return Object.entries(params).map(function (_ref) {
  20521. var key = _ref[0],
  20522. value = _ref[1];
  20523. if (value === true) {
  20524. return ";" + serializeKey(key); // omit true
  20525. }
  20526. return ";" + serializeKey(key) + "=" + serializeBareItem(value);
  20527. }).join('');
  20528. }
  20529. // 4.1.3. Serializing an Item
  20530. //
  20531. // Given an Item as bare_item and Parameters as item_parameters, return
  20532. // an ASCII string suitable for use in a HTTP field value.
  20533. //
  20534. // 1. Let output be an empty string.
  20535. //
  20536. // 2. Append the result of running Serializing a Bare Item
  20537. // Section 4.1.3.1 with bare_item to output.
  20538. //
  20539. // 3. Append the result of running Serializing Parameters
  20540. // Section 4.1.1.2 with item_parameters to output.
  20541. //
  20542. // 4. Return output.
  20543. function serializeItem(value) {
  20544. if (value instanceof SfItem) {
  20545. return "" + serializeBareItem(value.value) + serializeParams(value.params);
  20546. } else {
  20547. return serializeBareItem(value);
  20548. }
  20549. }
  20550. // 4.1.1.1. Serializing an Inner List
  20551. //
  20552. // Given an array of (member_value, parameters) tuples as inner_list,
  20553. // and parameters as list_parameters, return an ASCII string suitable
  20554. // for use in a HTTP field value.
  20555. //
  20556. // 1. Let output be the string "(".
  20557. //
  20558. // 2. For each (member_value, parameters) of inner_list:
  20559. //
  20560. // 1. Append the result of running Serializing an Item
  20561. // (Section 4.1.3) with (member_value, parameters) to output.
  20562. //
  20563. // 2. If more values remain in inner_list, append a single SP to
  20564. // output.
  20565. //
  20566. // 3. Append ")" to output.
  20567. //
  20568. // 4. Append the result of running Serializing Parameters
  20569. // (Section 4.1.1.2) with list_parameters to output.
  20570. //
  20571. // 5. Return output.
  20572. function serializeInnerList(value) {
  20573. return "(" + value.value.map(serializeItem).join(' ') + ")" + serializeParams(value.params);
  20574. }
  20575. // 4.1.2. Serializing a Dictionary
  20576. //
  20577. // Given an ordered Dictionary as input_dictionary (each member having a
  20578. // member_name and a tuple value of (member_value, parameters)), return
  20579. // an ASCII string suitable for use in a HTTP field value.
  20580. //
  20581. // 1. Let output be an empty string.
  20582. //
  20583. // 2. For each member_name with a value of (member_value, parameters)
  20584. // in input_dictionary:
  20585. //
  20586. // 1. Append the result of running Serializing a Key
  20587. // (Section 4.1.1.3) with member's member_name to output.
  20588. //
  20589. // 2. If member_value is Boolean true:
  20590. //
  20591. // 1. Append the result of running Serializing Parameters
  20592. // (Section 4.1.1.2) with parameters to output.
  20593. //
  20594. // 3. Otherwise:
  20595. //
  20596. // 1. Append "=" to output.
  20597. //
  20598. // 2. If member_value is an array, append the result of running
  20599. // Serializing an Inner List (Section 4.1.1.1) with
  20600. // (member_value, parameters) to output.
  20601. //
  20602. // 3. Otherwise, append the result of running Serializing an
  20603. // Item (Section 4.1.3) with (member_value, parameters) to
  20604. // output.
  20605. //
  20606. // 4. If more members remain in input_dictionary:
  20607. //
  20608. // 1. Append "," to output.
  20609. //
  20610. // 2. Append a single SP to output.
  20611. //
  20612. // 3. Return output.
  20613. function serializeDict(dict, options) {
  20614. if (options === void 0) {
  20615. options = {
  20616. whitespace: true
  20617. };
  20618. }
  20619. if (typeof dict !== 'object') {
  20620. throw serializeError(dict, DICT);
  20621. }
  20622. var entries = dict instanceof Map ? dict.entries() : Object.entries(dict);
  20623. var optionalWhiteSpace = (options === null || options === void 0 ? void 0 : options.whitespace) ? ' ' : '';
  20624. return Array.from(entries).map(function (_ref) {
  20625. var key = _ref[0],
  20626. item = _ref[1];
  20627. if (item instanceof SfItem === false) {
  20628. item = new SfItem(item);
  20629. }
  20630. var output = serializeKey(key);
  20631. if (item.value === true) {
  20632. output += serializeParams(item.params);
  20633. } else {
  20634. output += '=';
  20635. if (Array.isArray(item.value)) {
  20636. output += serializeInnerList(item);
  20637. } else {
  20638. output += serializeItem(item);
  20639. }
  20640. }
  20641. return output;
  20642. }).join("," + optionalWhiteSpace);
  20643. }
  20644. /**
  20645. * Encode an object into a structured field dictionary
  20646. *
  20647. * @param value - The structured field dictionary to encode
  20648. * @param options - Encoding options
  20649. *
  20650. * @returns The structured field string
  20651. *
  20652. * @group Structured Field
  20653. *
  20654. * @beta
  20655. */
  20656. function encodeSfDict(value, options) {
  20657. return serializeDict(value, options);
  20658. }
  20659. /**
  20660. * Checks if the given key is a token field.
  20661. *
  20662. * @param key - The key to check.
  20663. *
  20664. * @returns `true` if the key is a token field.
  20665. *
  20666. * @internal
  20667. */
  20668. function isTokenField(key) {
  20669. return ['ot', 'sf', 'st', 'e', 'sta'].includes(key);
  20670. }
  20671. /**
  20672. * Checks if the given value is valid
  20673. *
  20674. * @param value - The value to check.
  20675. *
  20676. * @returns `true` if the key is a value is valid.
  20677. *
  20678. * @internal
  20679. */
  20680. function isValid(value) {
  20681. if (typeof value === 'number') {
  20682. return isFiniteNumber(value);
  20683. }
  20684. return value != null && value !== '' && value !== false;
  20685. }
  20686. /**
  20687. * Constructs a relative path from a URL.
  20688. *
  20689. * @param url - The destination URL
  20690. * @param base - The base URL
  20691. * @returns The relative path
  20692. *
  20693. * @group Utils
  20694. *
  20695. * @beta
  20696. */
  20697. function urlToRelativePath(url, base) {
  20698. var to = new URL(url);
  20699. var from = new URL(base);
  20700. if (to.origin !== from.origin) {
  20701. return url;
  20702. }
  20703. var toPath = to.pathname.split('/').slice(1);
  20704. var fromPath = from.pathname.split('/').slice(1, -1);
  20705. // remove common parents
  20706. while (toPath[0] === fromPath[0]) {
  20707. toPath.shift();
  20708. fromPath.shift();
  20709. }
  20710. // add back paths
  20711. while (fromPath.length) {
  20712. fromPath.shift();
  20713. toPath.unshift('..');
  20714. }
  20715. return toPath.join('/');
  20716. }
  20717. var toRounded = function toRounded(value) {
  20718. return Math.round(value);
  20719. };
  20720. var toUrlSafe = function toUrlSafe(value, options) {
  20721. if (options === null || options === void 0 ? void 0 : options.baseUrl) {
  20722. value = urlToRelativePath(value, options.baseUrl);
  20723. }
  20724. return encodeURIComponent(value);
  20725. };
  20726. var toHundred = function toHundred(value) {
  20727. return toRounded(value / 100) * 100;
  20728. };
  20729. /**
  20730. * The default formatters for CMCD values.
  20731. *
  20732. * @group CMCD
  20733. *
  20734. * @beta
  20735. */
  20736. var CmcdFormatters = {
  20737. /**
  20738. * Bitrate (kbps) rounded integer
  20739. */
  20740. br: toRounded,
  20741. /**
  20742. * Duration (milliseconds) rounded integer
  20743. */
  20744. d: toRounded,
  20745. /**
  20746. * Buffer Length (milliseconds) rounded nearest 100ms
  20747. */
  20748. bl: toHundred,
  20749. /**
  20750. * Deadline (milliseconds) rounded nearest 100ms
  20751. */
  20752. dl: toHundred,
  20753. /**
  20754. * Measured Throughput (kbps) rounded nearest 100kbps
  20755. */
  20756. mtp: toHundred,
  20757. /**
  20758. * Next Object Request URL encoded
  20759. */
  20760. nor: toUrlSafe,
  20761. /**
  20762. * Requested maximum throughput (kbps) rounded nearest 100kbps
  20763. */
  20764. rtp: toHundred,
  20765. /**
  20766. * Top Bitrate (kbps) rounded integer
  20767. */
  20768. tb: toRounded
  20769. };
  20770. /**
  20771. * Internal CMCD processing function.
  20772. *
  20773. * @param obj - The CMCD object to process.
  20774. * @param map - The mapping function to use.
  20775. * @param options - Options for encoding.
  20776. *
  20777. * @internal
  20778. *
  20779. * @group CMCD
  20780. */
  20781. function processCmcd(obj, options) {
  20782. var results = {};
  20783. if (obj == null || typeof obj !== 'object') {
  20784. return results;
  20785. }
  20786. var keys = Object.keys(obj).sort();
  20787. var formatters = _extends({}, CmcdFormatters, options === null || options === void 0 ? void 0 : options.formatters);
  20788. var filter = options === null || options === void 0 ? void 0 : options.filter;
  20789. keys.forEach(function (key) {
  20790. if ((filter === null || filter === void 0 ? void 0 : filter(key)) === false) {
  20791. return;
  20792. }
  20793. var value = obj[key];
  20794. var formatter = formatters[key];
  20795. if (formatter) {
  20796. value = formatter(value, options);
  20797. }
  20798. // Version should only be reported if not equal to 1.
  20799. if (key === 'v' && value === 1) {
  20800. return;
  20801. }
  20802. // Playback rate should only be sent if not equal to 1.
  20803. if (key == 'pr' && value === 1) {
  20804. return;
  20805. }
  20806. // ignore invalid values
  20807. if (!isValid(value)) {
  20808. return;
  20809. }
  20810. if (isTokenField(key) && typeof value === 'string') {
  20811. value = new SfToken(value);
  20812. }
  20813. results[key] = value;
  20814. });
  20815. return results;
  20816. }
  20817. /**
  20818. * Encode a CMCD object to a string.
  20819. *
  20820. * @param cmcd - The CMCD object to encode.
  20821. * @param options - Options for encoding.
  20822. *
  20823. * @returns The encoded CMCD string.
  20824. *
  20825. * @group CMCD
  20826. *
  20827. * @beta
  20828. */
  20829. function encodeCmcd(cmcd, options) {
  20830. if (options === void 0) {
  20831. options = {};
  20832. }
  20833. if (!cmcd) {
  20834. return '';
  20835. }
  20836. return encodeSfDict(processCmcd(cmcd, options), _extends({
  20837. whitespace: false
  20838. }, options));
  20839. }
  20840. /**
  20841. * Convert a CMCD data object to request headers
  20842. *
  20843. * @param cmcd - The CMCD data object to convert.
  20844. * @param options - Options for encoding the CMCD object.
  20845. *
  20846. * @returns The CMCD header shards.
  20847. *
  20848. * @group CMCD
  20849. *
  20850. * @beta
  20851. */
  20852. function toCmcdHeaders(cmcd, options) {
  20853. if (options === void 0) {
  20854. options = {};
  20855. }
  20856. var result = {};
  20857. if (!cmcd) {
  20858. return result;
  20859. }
  20860. var entries = Object.entries(cmcd);
  20861. var headerMap = Object.entries(CmcdHeaderMap).concat(Object.entries((options === null || options === void 0 ? void 0 : options.customHeaderMap) || {}));
  20862. var shards = entries.reduce(function (acc, entry) {
  20863. var _a, _b;
  20864. var key = entry[0],
  20865. value = entry[1];
  20866. var field = ((_a = headerMap.find(function (entry) {
  20867. return entry[1].includes(key);
  20868. })) === null || _a === void 0 ? void 0 : _a[0]) || CmcdHeaderField.REQUEST;
  20869. (_b = acc[field]) !== null && _b !== void 0 ? _b : acc[field] = {};
  20870. acc[field][key] = value;
  20871. return acc;
  20872. }, {});
  20873. return Object.entries(shards).reduce(function (acc, _ref) {
  20874. var field = _ref[0],
  20875. value = _ref[1];
  20876. acc[field] = encodeCmcd(value, options);
  20877. return acc;
  20878. }, result);
  20879. }
  20880. /**
  20881. * Append CMCD query args to a header object.
  20882. *
  20883. * @param headers - The headers to append to.
  20884. * @param cmcd - The CMCD object to append.
  20885. * @param options - Encode options.
  20886. *
  20887. * @returns The headers with the CMCD header shards appended.
  20888. *
  20889. * @group CMCD
  20890. *
  20891. * @beta
  20892. */
  20893. function appendCmcdHeaders(headers, cmcd, options) {
  20894. return _extends(headers, toCmcdHeaders(cmcd, options));
  20895. }
  20896. /**
  20897. * CMCD parameter name.
  20898. *
  20899. * @group CMCD
  20900. *
  20901. * @beta
  20902. */
  20903. var CMCD_PARAM = 'CMCD';
  20904. /**
  20905. * Convert a CMCD data object to a query arg.
  20906. *
  20907. * @param cmcd - The CMCD object to convert.
  20908. * @param options - Options for encoding the CMCD object.
  20909. *
  20910. * @returns The CMCD query arg.
  20911. *
  20912. * @group CMCD
  20913. *
  20914. * @beta
  20915. */
  20916. function toCmcdQuery(cmcd, options) {
  20917. if (options === void 0) {
  20918. options = {};
  20919. }
  20920. if (!cmcd) {
  20921. return '';
  20922. }
  20923. var params = encodeCmcd(cmcd, options);
  20924. return CMCD_PARAM + "=" + encodeURIComponent(params);
  20925. }
  20926. var REGEX = /CMCD=[^&#]+/;
  20927. /**
  20928. * Append CMCD query args to a URL.
  20929. *
  20930. * @param url - The URL to append to.
  20931. * @param cmcd - The CMCD object to append.
  20932. * @param options - Options for encoding the CMCD object.
  20933. *
  20934. * @returns The URL with the CMCD query args appended.
  20935. *
  20936. * @group CMCD
  20937. *
  20938. * @beta
  20939. */
  20940. function appendCmcdQuery(url, cmcd, options) {
  20941. // TODO: Replace with URLSearchParams once we drop Safari < 10.1 & Chrome < 49 support.
  20942. // https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
  20943. var query = toCmcdQuery(cmcd, options);
  20944. if (!query) {
  20945. return url;
  20946. }
  20947. if (REGEX.test(url)) {
  20948. return url.replace(REGEX, query);
  20949. }
  20950. var separator = url.includes('?') ? '&' : '?';
  20951. return "" + url + separator + query;
  20952. }
  20953. /**
  20954. * Controller to deal with Common Media Client Data (CMCD)
  20955. * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
  20956. */
  20957. var CMCDController = /*#__PURE__*/function () {
  20958. function CMCDController(hls) {
  20959. var _this = this;
  20960. this.hls = void 0;
  20961. this.config = void 0;
  20962. this.media = void 0;
  20963. this.sid = void 0;
  20964. this.cid = void 0;
  20965. this.useHeaders = false;
  20966. this.includeKeys = void 0;
  20967. this.initialized = false;
  20968. this.starved = false;
  20969. this.buffering = true;
  20970. this.audioBuffer = void 0;
  20971. this.videoBuffer = void 0;
  20972. this.onWaiting = function () {
  20973. if (_this.initialized) {
  20974. _this.starved = true;
  20975. }
  20976. _this.buffering = true;
  20977. };
  20978. this.onPlaying = function () {
  20979. if (!_this.initialized) {
  20980. _this.initialized = true;
  20981. }
  20982. _this.buffering = false;
  20983. };
  20984. /**
  20985. * Apply CMCD data to a manifest request.
  20986. */
  20987. this.applyPlaylistData = function (context) {
  20988. try {
  20989. _this.apply(context, {
  20990. ot: CmcdObjectType.MANIFEST,
  20991. su: !_this.initialized
  20992. });
  20993. } catch (error) {
  20994. _this.hls.logger.warn('Could not generate manifest CMCD data.', error);
  20995. }
  20996. };
  20997. /**
  20998. * Apply CMCD data to a segment request
  20999. */
  21000. this.applyFragmentData = function (context) {
  21001. try {
  21002. var frag = context.frag,
  21003. part = context.part;
  21004. var level = _this.hls.levels[frag.level];
  21005. var ot = _this.getObjectType(frag);
  21006. var data = {
  21007. d: (part || frag).duration * 1000,
  21008. ot: ot
  21009. };
  21010. if (ot === CmcdObjectType.VIDEO || ot === CmcdObjectType.AUDIO || ot == CmcdObjectType.MUXED) {
  21011. data.br = level.bitrate / 1000;
  21012. data.tb = _this.getTopBandwidth(ot) / 1000;
  21013. data.bl = _this.getBufferLength(ot);
  21014. }
  21015. var next = part ? _this.getNextPart(part) : _this.getNextFrag(frag);
  21016. if (next != null && next.url && next.url !== frag.url) {
  21017. data.nor = next.url;
  21018. }
  21019. _this.apply(context, data);
  21020. } catch (error) {
  21021. _this.hls.logger.warn('Could not generate segment CMCD data.', error);
  21022. }
  21023. };
  21024. this.hls = hls;
  21025. var config = this.config = hls.config;
  21026. var cmcd = config.cmcd;
  21027. if (cmcd != null) {
  21028. config.pLoader = this.createPlaylistLoader();
  21029. config.fLoader = this.createFragmentLoader();
  21030. this.sid = cmcd.sessionId || hls.sessionId;
  21031. this.cid = cmcd.contentId;
  21032. this.useHeaders = cmcd.useHeaders === true;
  21033. this.includeKeys = cmcd.includeKeys;
  21034. this.registerListeners();
  21035. }
  21036. }
  21037. var _proto = CMCDController.prototype;
  21038. _proto.registerListeners = function registerListeners() {
  21039. var hls = this.hls;
  21040. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21041. hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21042. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  21043. };
  21044. _proto.unregisterListeners = function unregisterListeners() {
  21045. var hls = this.hls;
  21046. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21047. hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21048. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  21049. };
  21050. _proto.destroy = function destroy() {
  21051. this.unregisterListeners();
  21052. this.onMediaDetached();
  21053. // @ts-ignore
  21054. this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
  21055. // @ts-ignore
  21056. this.onWaiting = this.onPlaying = this.media = null;
  21057. };
  21058. _proto.onMediaAttached = function onMediaAttached(event, data) {
  21059. this.media = data.media;
  21060. this.media.addEventListener('waiting', this.onWaiting);
  21061. this.media.addEventListener('playing', this.onPlaying);
  21062. };
  21063. _proto.onMediaDetached = function onMediaDetached() {
  21064. if (!this.media) {
  21065. return;
  21066. }
  21067. this.media.removeEventListener('waiting', this.onWaiting);
  21068. this.media.removeEventListener('playing', this.onPlaying);
  21069. // @ts-ignore
  21070. this.media = null;
  21071. };
  21072. _proto.onBufferCreated = function onBufferCreated(event, data) {
  21073. var _data$tracks$audio, _data$tracks$video;
  21074. this.audioBuffer = (_data$tracks$audio = data.tracks.audio) == null ? void 0 : _data$tracks$audio.buffer;
  21075. this.videoBuffer = (_data$tracks$video = data.tracks.video) == null ? void 0 : _data$tracks$video.buffer;
  21076. };
  21077. /**
  21078. * Create baseline CMCD data
  21079. */
  21080. _proto.createData = function createData() {
  21081. var _this$media;
  21082. return {
  21083. v: 1,
  21084. sf: CmcdStreamingFormat.HLS,
  21085. sid: this.sid,
  21086. cid: this.cid,
  21087. pr: (_this$media = this.media) == null ? void 0 : _this$media.playbackRate,
  21088. mtp: this.hls.bandwidthEstimate / 1000
  21089. };
  21090. }
  21091. /**
  21092. * Apply CMCD data to a request.
  21093. */;
  21094. _proto.apply = function apply(context, data) {
  21095. if (data === void 0) {
  21096. data = {};
  21097. }
  21098. // apply baseline data
  21099. _extends(data, this.createData());
  21100. var isVideo = data.ot === CmcdObjectType.INIT || data.ot === CmcdObjectType.VIDEO || data.ot === CmcdObjectType.MUXED;
  21101. if (this.starved && isVideo) {
  21102. data.bs = true;
  21103. data.su = true;
  21104. this.starved = false;
  21105. }
  21106. if (data.su == null) {
  21107. data.su = this.buffering;
  21108. }
  21109. // TODO: Implement rtp, nrr, dl
  21110. var includeKeys = this.includeKeys;
  21111. if (includeKeys) {
  21112. data = Object.keys(data).reduce(function (acc, key) {
  21113. includeKeys.includes(key) && (acc[key] = data[key]);
  21114. return acc;
  21115. }, {});
  21116. }
  21117. var options = {
  21118. baseUrl: context.url
  21119. };
  21120. if (this.useHeaders) {
  21121. if (!context.headers) {
  21122. context.headers = {};
  21123. }
  21124. appendCmcdHeaders(context.headers, data, options);
  21125. } else {
  21126. context.url = appendCmcdQuery(context.url, data, options);
  21127. }
  21128. };
  21129. _proto.getNextFrag = function getNextFrag(fragment) {
  21130. var _this$hls$levels$frag;
  21131. var levelDetails = (_this$hls$levels$frag = this.hls.levels[fragment.level]) == null ? void 0 : _this$hls$levels$frag.details;
  21132. if (levelDetails) {
  21133. var index = fragment.sn - levelDetails.startSN;
  21134. return levelDetails.fragments[index + 1];
  21135. }
  21136. return undefined;
  21137. };
  21138. _proto.getNextPart = function getNextPart(part) {
  21139. var _this$hls$levels$frag2, _this$hls$levels$frag3;
  21140. var index = part.index,
  21141. fragment = part.fragment;
  21142. var partList = (_this$hls$levels$frag2 = this.hls.levels[fragment.level]) == null ? void 0 : (_this$hls$levels$frag3 = _this$hls$levels$frag2.details) == null ? void 0 : _this$hls$levels$frag3.partList;
  21143. if (partList) {
  21144. var sn = fragment.sn;
  21145. for (var i = partList.length - 1; i >= 0; i--) {
  21146. var p = partList[i];
  21147. if (p.index === index && p.fragment.sn === sn) {
  21148. return partList[i + 1];
  21149. }
  21150. }
  21151. }
  21152. return undefined;
  21153. }
  21154. /**
  21155. * The CMCD object type.
  21156. */;
  21157. _proto.getObjectType = function getObjectType(fragment) {
  21158. var type = fragment.type;
  21159. if (type === 'subtitle') {
  21160. return CmcdObjectType.TIMED_TEXT;
  21161. }
  21162. if (fragment.sn === 'initSegment') {
  21163. return CmcdObjectType.INIT;
  21164. }
  21165. if (type === 'audio') {
  21166. return CmcdObjectType.AUDIO;
  21167. }
  21168. if (type === 'main') {
  21169. if (!this.hls.audioTracks.length) {
  21170. return CmcdObjectType.MUXED;
  21171. }
  21172. return CmcdObjectType.VIDEO;
  21173. }
  21174. return undefined;
  21175. }
  21176. /**
  21177. * Get the highest bitrate.
  21178. */;
  21179. _proto.getTopBandwidth = function getTopBandwidth(type) {
  21180. var bitrate = 0;
  21181. var levels;
  21182. var hls = this.hls;
  21183. if (type === CmcdObjectType.AUDIO) {
  21184. levels = hls.audioTracks;
  21185. } else {
  21186. var max = hls.maxAutoLevel;
  21187. var len = max > -1 ? max + 1 : hls.levels.length;
  21188. levels = hls.levels.slice(0, len);
  21189. }
  21190. levels.forEach(function (level) {
  21191. if (level.bitrate > bitrate) {
  21192. bitrate = level.bitrate;
  21193. }
  21194. });
  21195. return bitrate > 0 ? bitrate : NaN;
  21196. }
  21197. /**
  21198. * Get the buffer length for a media type in milliseconds
  21199. */;
  21200. _proto.getBufferLength = function getBufferLength(type) {
  21201. var media = this.media;
  21202. var buffer = type === CmcdObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;
  21203. if (!buffer || !media) {
  21204. return NaN;
  21205. }
  21206. var info = BufferHelper.bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
  21207. return info.len * 1000;
  21208. }
  21209. /**
  21210. * Create a playlist loader
  21211. */;
  21212. _proto.createPlaylistLoader = function createPlaylistLoader() {
  21213. var pLoader = this.config.pLoader;
  21214. var apply = this.applyPlaylistData;
  21215. var Ctor = pLoader || this.config.loader;
  21216. return /*#__PURE__*/function () {
  21217. function CmcdPlaylistLoader(config) {
  21218. this.loader = void 0;
  21219. this.loader = new Ctor(config);
  21220. }
  21221. var _proto2 = CmcdPlaylistLoader.prototype;
  21222. _proto2.destroy = function destroy() {
  21223. this.loader.destroy();
  21224. };
  21225. _proto2.abort = function abort() {
  21226. this.loader.abort();
  21227. };
  21228. _proto2.load = function load(context, config, callbacks) {
  21229. apply(context);
  21230. this.loader.load(context, config, callbacks);
  21231. };
  21232. return _createClass(CmcdPlaylistLoader, [{
  21233. key: "stats",
  21234. get: function get() {
  21235. return this.loader.stats;
  21236. }
  21237. }, {
  21238. key: "context",
  21239. get: function get() {
  21240. return this.loader.context;
  21241. }
  21242. }]);
  21243. }();
  21244. }
  21245. /**
  21246. * Create a playlist loader
  21247. */;
  21248. _proto.createFragmentLoader = function createFragmentLoader() {
  21249. var fLoader = this.config.fLoader;
  21250. var apply = this.applyFragmentData;
  21251. var Ctor = fLoader || this.config.loader;
  21252. return /*#__PURE__*/function () {
  21253. function CmcdFragmentLoader(config) {
  21254. this.loader = void 0;
  21255. this.loader = new Ctor(config);
  21256. }
  21257. var _proto3 = CmcdFragmentLoader.prototype;
  21258. _proto3.destroy = function destroy() {
  21259. this.loader.destroy();
  21260. };
  21261. _proto3.abort = function abort() {
  21262. this.loader.abort();
  21263. };
  21264. _proto3.load = function load(context, config, callbacks) {
  21265. apply(context);
  21266. this.loader.load(context, config, callbacks);
  21267. };
  21268. return _createClass(CmcdFragmentLoader, [{
  21269. key: "stats",
  21270. get: function get() {
  21271. return this.loader.stats;
  21272. }
  21273. }, {
  21274. key: "context",
  21275. get: function get() {
  21276. return this.loader.context;
  21277. }
  21278. }]);
  21279. }();
  21280. };
  21281. return CMCDController;
  21282. }();
  21283. var PATHWAY_PENALTY_DURATION_MS = 300000;
  21284. var ContentSteeringController = /*#__PURE__*/function (_Logger) {
  21285. function ContentSteeringController(hls) {
  21286. var _this;
  21287. _this = _Logger.call(this, 'content-steering', hls.logger) || this;
  21288. _this.hls = void 0;
  21289. _this.loader = null;
  21290. _this.uri = null;
  21291. _this.pathwayId = '.';
  21292. _this._pathwayPriority = null;
  21293. _this.timeToLoad = 300;
  21294. _this.reloadTimer = -1;
  21295. _this.updated = 0;
  21296. _this.started = false;
  21297. _this.enabled = true;
  21298. _this.levels = null;
  21299. _this.audioTracks = null;
  21300. _this.subtitleTracks = null;
  21301. _this.penalizedPathways = {};
  21302. _this.hls = hls;
  21303. _this.registerListeners();
  21304. return _this;
  21305. }
  21306. _inheritsLoose(ContentSteeringController, _Logger);
  21307. var _proto = ContentSteeringController.prototype;
  21308. _proto.registerListeners = function registerListeners() {
  21309. var hls = this.hls;
  21310. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21311. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21312. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21313. hls.on(Events.ERROR, this.onError, this);
  21314. };
  21315. _proto.unregisterListeners = function unregisterListeners() {
  21316. var hls = this.hls;
  21317. if (!hls) {
  21318. return;
  21319. }
  21320. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21321. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21322. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  21323. hls.off(Events.ERROR, this.onError, this);
  21324. };
  21325. _proto.pathways = function pathways() {
  21326. return (this.levels || []).reduce(function (pathways, level) {
  21327. if (pathways.indexOf(level.pathwayId) === -1) {
  21328. pathways.push(level.pathwayId);
  21329. }
  21330. return pathways;
  21331. }, []);
  21332. };
  21333. _proto.startLoad = function startLoad() {
  21334. this.started = true;
  21335. this.clearTimeout();
  21336. if (this.enabled && this.uri) {
  21337. if (this.updated) {
  21338. var ttl = this.timeToLoad * 1000 - (performance.now() - this.updated);
  21339. if (ttl > 0) {
  21340. this.scheduleRefresh(this.uri, ttl);
  21341. return;
  21342. }
  21343. }
  21344. this.loadSteeringManifest(this.uri);
  21345. }
  21346. };
  21347. _proto.stopLoad = function stopLoad() {
  21348. this.started = false;
  21349. if (this.loader) {
  21350. this.loader.destroy();
  21351. this.loader = null;
  21352. }
  21353. this.clearTimeout();
  21354. };
  21355. _proto.clearTimeout = function clearTimeout() {
  21356. if (this.reloadTimer !== -1) {
  21357. self.clearTimeout(this.reloadTimer);
  21358. this.reloadTimer = -1;
  21359. }
  21360. };
  21361. _proto.destroy = function destroy() {
  21362. this.unregisterListeners();
  21363. this.stopLoad();
  21364. // @ts-ignore
  21365. this.hls = null;
  21366. this.levels = this.audioTracks = this.subtitleTracks = null;
  21367. };
  21368. _proto.removeLevel = function removeLevel(levelToRemove) {
  21369. var levels = this.levels;
  21370. if (levels) {
  21371. this.levels = levels.filter(function (level) {
  21372. return level !== levelToRemove;
  21373. });
  21374. }
  21375. };
  21376. _proto.onManifestLoading = function onManifestLoading() {
  21377. this.stopLoad();
  21378. this.enabled = true;
  21379. this.timeToLoad = 300;
  21380. this.updated = 0;
  21381. this.uri = null;
  21382. this.pathwayId = '.';
  21383. this.levels = this.audioTracks = this.subtitleTracks = null;
  21384. };
  21385. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  21386. var contentSteering = data.contentSteering;
  21387. if (contentSteering === null) {
  21388. return;
  21389. }
  21390. this.pathwayId = contentSteering.pathwayId;
  21391. this.uri = contentSteering.uri;
  21392. if (this.started) {
  21393. this.startLoad();
  21394. }
  21395. };
  21396. _proto.onManifestParsed = function onManifestParsed(event, data) {
  21397. this.audioTracks = data.audioTracks;
  21398. this.subtitleTracks = data.subtitleTracks;
  21399. };
  21400. _proto.onError = function onError(event, data) {
  21401. var errorAction = data.errorAction;
  21402. if ((errorAction == null ? void 0 : errorAction.action) === NetworkErrorAction.SendAlternateToPenaltyBox && errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost) {
  21403. var levels = this.levels;
  21404. var pathwayPriority = this._pathwayPriority;
  21405. var errorPathway = this.pathwayId;
  21406. if (data.context) {
  21407. var _data$context = data.context,
  21408. groupId = _data$context.groupId,
  21409. pathwayId = _data$context.pathwayId,
  21410. type = _data$context.type;
  21411. if (groupId && levels) {
  21412. errorPathway = this.getPathwayForGroupId(groupId, type, errorPathway);
  21413. } else if (pathwayId) {
  21414. errorPathway = pathwayId;
  21415. }
  21416. }
  21417. if (!(errorPathway in this.penalizedPathways)) {
  21418. this.penalizedPathways[errorPathway] = performance.now();
  21419. }
  21420. if (!pathwayPriority && levels) {
  21421. // If PATHWAY-PRIORITY was not provided, list pathways for error handling
  21422. pathwayPriority = this.pathways();
  21423. }
  21424. if (pathwayPriority && pathwayPriority.length > 1) {
  21425. this.updatePathwayPriority(pathwayPriority);
  21426. errorAction.resolved = this.pathwayId !== errorPathway;
  21427. }
  21428. if (data.details === ErrorDetails.BUFFER_APPEND_ERROR && !data.fatal) {
  21429. // Error will become fatal in buffer-controller when reaching `appendErrorMaxRetry`
  21430. // Stream-controllers are expected to reduce buffer length even if this is not deemed a QuotaExceededError
  21431. errorAction.resolved = true;
  21432. } else if (!errorAction.resolved) {
  21433. this.warn("Could not resolve " + data.details + " (\"" + data.error.message + "\") with content-steering for Pathway: " + errorPathway + " levels: " + (levels ? levels.length : levels) + " priorities: " + stringify(pathwayPriority) + " penalized: " + stringify(this.penalizedPathways));
  21434. }
  21435. }
  21436. };
  21437. _proto.filterParsedLevels = function filterParsedLevels(levels) {
  21438. // Filter levels to only include those that are in the initial pathway
  21439. this.levels = levels;
  21440. var pathwayLevels = this.getLevelsForPathway(this.pathwayId);
  21441. if (pathwayLevels.length === 0) {
  21442. var pathwayId = levels[0].pathwayId;
  21443. this.log("No levels found in Pathway " + this.pathwayId + ". Setting initial Pathway to \"" + pathwayId + "\"");
  21444. pathwayLevels = this.getLevelsForPathway(pathwayId);
  21445. this.pathwayId = pathwayId;
  21446. }
  21447. if (pathwayLevels.length !== levels.length) {
  21448. this.log("Found " + pathwayLevels.length + "/" + levels.length + " levels in Pathway \"" + this.pathwayId + "\"");
  21449. }
  21450. return pathwayLevels;
  21451. };
  21452. _proto.getLevelsForPathway = function getLevelsForPathway(pathwayId) {
  21453. if (this.levels === null) {
  21454. return [];
  21455. }
  21456. return this.levels.filter(function (level) {
  21457. return pathwayId === level.pathwayId;
  21458. });
  21459. };
  21460. _proto.updatePathwayPriority = function updatePathwayPriority(pathwayPriority) {
  21461. this._pathwayPriority = pathwayPriority;
  21462. var levels;
  21463. // Evaluate if we should remove the pathway from the penalized list
  21464. var penalizedPathways = this.penalizedPathways;
  21465. var now = performance.now();
  21466. Object.keys(penalizedPathways).forEach(function (pathwayId) {
  21467. if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {
  21468. delete penalizedPathways[pathwayId];
  21469. }
  21470. });
  21471. for (var i = 0; i < pathwayPriority.length; i++) {
  21472. var pathwayId = pathwayPriority[i];
  21473. if (pathwayId in penalizedPathways) {
  21474. continue;
  21475. }
  21476. if (pathwayId === this.pathwayId) {
  21477. return;
  21478. }
  21479. var selectedIndex = this.hls.nextLoadLevel;
  21480. var selectedLevel = this.hls.levels[selectedIndex];
  21481. levels = this.getLevelsForPathway(pathwayId);
  21482. if (levels.length > 0) {
  21483. this.log("Setting Pathway to \"" + pathwayId + "\"");
  21484. this.pathwayId = pathwayId;
  21485. reassignFragmentLevelIndexes(levels);
  21486. this.hls.trigger(Events.LEVELS_UPDATED, {
  21487. levels: levels
  21488. });
  21489. // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed
  21490. var levelAfterChange = this.hls.levels[selectedIndex];
  21491. if (selectedLevel && levelAfterChange && this.levels) {
  21492. if (levelAfterChange.attrs['STABLE-VARIANT-ID'] !== selectedLevel.attrs['STABLE-VARIANT-ID'] && levelAfterChange.bitrate !== selectedLevel.bitrate) {
  21493. this.log("Unstable Pathways change from bitrate " + selectedLevel.bitrate + " to " + levelAfterChange.bitrate);
  21494. }
  21495. this.hls.nextLoadLevel = selectedIndex;
  21496. }
  21497. break;
  21498. }
  21499. }
  21500. };
  21501. _proto.getPathwayForGroupId = function getPathwayForGroupId(groupId, type, defaultPathway) {
  21502. var levels = this.getLevelsForPathway(defaultPathway).concat(this.levels || []);
  21503. for (var i = 0; i < levels.length; i++) {
  21504. if (type === PlaylistContextType.AUDIO_TRACK && levels[i].hasAudioGroup(groupId) || type === PlaylistContextType.SUBTITLE_TRACK && levels[i].hasSubtitleGroup(groupId)) {
  21505. return levels[i].pathwayId;
  21506. }
  21507. }
  21508. return defaultPathway;
  21509. };
  21510. _proto.clonePathways = function clonePathways(pathwayClones) {
  21511. var _this2 = this;
  21512. var levels = this.levels;
  21513. if (!levels) {
  21514. return;
  21515. }
  21516. var audioGroupCloneMap = {};
  21517. var subtitleGroupCloneMap = {};
  21518. pathwayClones.forEach(function (pathwayClone) {
  21519. var cloneId = pathwayClone.ID,
  21520. baseId = pathwayClone['BASE-ID'],
  21521. uriReplacement = pathwayClone['URI-REPLACEMENT'];
  21522. if (levels.some(function (level) {
  21523. return level.pathwayId === cloneId;
  21524. })) {
  21525. return;
  21526. }
  21527. var clonedVariants = _this2.getLevelsForPathway(baseId).map(function (baseLevel) {
  21528. var attributes = new AttrList(baseLevel.attrs);
  21529. attributes['PATHWAY-ID'] = cloneId;
  21530. var clonedAudioGroupId = attributes.AUDIO && attributes.AUDIO + "_clone_" + cloneId;
  21531. var clonedSubtitleGroupId = attributes.SUBTITLES && attributes.SUBTITLES + "_clone_" + cloneId;
  21532. if (clonedAudioGroupId) {
  21533. audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;
  21534. attributes.AUDIO = clonedAudioGroupId;
  21535. }
  21536. if (clonedSubtitleGroupId) {
  21537. subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;
  21538. attributes.SUBTITLES = clonedSubtitleGroupId;
  21539. }
  21540. var url = performUriReplacement(baseLevel.uri, attributes['STABLE-VARIANT-ID'], 'PER-VARIANT-URIS', uriReplacement);
  21541. var clonedLevel = new Level({
  21542. attrs: attributes,
  21543. audioCodec: baseLevel.audioCodec,
  21544. bitrate: baseLevel.bitrate,
  21545. height: baseLevel.height,
  21546. name: baseLevel.name,
  21547. url: url,
  21548. videoCodec: baseLevel.videoCodec,
  21549. width: baseLevel.width
  21550. });
  21551. if (baseLevel.audioGroups) {
  21552. for (var i = 1; i < baseLevel.audioGroups.length; i++) {
  21553. clonedLevel.addGroupId('audio', baseLevel.audioGroups[i] + "_clone_" + cloneId);
  21554. }
  21555. }
  21556. if (baseLevel.subtitleGroups) {
  21557. for (var _i = 1; _i < baseLevel.subtitleGroups.length; _i++) {
  21558. clonedLevel.addGroupId('text', baseLevel.subtitleGroups[_i] + "_clone_" + cloneId);
  21559. }
  21560. }
  21561. return clonedLevel;
  21562. });
  21563. levels.push.apply(levels, clonedVariants);
  21564. cloneRenditionGroups(_this2.audioTracks, audioGroupCloneMap, uriReplacement, cloneId);
  21565. cloneRenditionGroups(_this2.subtitleTracks, subtitleGroupCloneMap, uriReplacement, cloneId);
  21566. });
  21567. };
  21568. _proto.loadSteeringManifest = function loadSteeringManifest(uri) {
  21569. var _this3 = this;
  21570. var config = this.hls.config;
  21571. var Loader = config.loader;
  21572. if (this.loader) {
  21573. this.loader.destroy();
  21574. }
  21575. this.loader = new Loader(config);
  21576. var url;
  21577. try {
  21578. url = new self.URL(uri);
  21579. } catch (error) {
  21580. this.enabled = false;
  21581. this.log("Failed to parse Steering Manifest URI: " + uri);
  21582. return;
  21583. }
  21584. if (url.protocol !== 'data:') {
  21585. var throughput = (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;
  21586. url.searchParams.set('_HLS_pathway', this.pathwayId);
  21587. url.searchParams.set('_HLS_throughput', '' + throughput);
  21588. }
  21589. var context = {
  21590. responseType: 'json',
  21591. url: url.href
  21592. };
  21593. var loadPolicy = config.steeringManifestLoadPolicy.default;
  21594. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  21595. var loaderConfig = {
  21596. loadPolicy: loadPolicy,
  21597. timeout: loadPolicy.maxLoadTimeMs,
  21598. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  21599. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  21600. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  21601. };
  21602. var callbacks = {
  21603. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  21604. _this3.log("Loaded steering manifest: \"" + url + "\"");
  21605. var steeringData = response.data;
  21606. if ((steeringData == null ? void 0 : steeringData.VERSION) !== 1) {
  21607. _this3.log("Steering VERSION " + steeringData.VERSION + " not supported!");
  21608. return;
  21609. }
  21610. _this3.updated = performance.now();
  21611. _this3.timeToLoad = steeringData.TTL;
  21612. var reloadUri = steeringData['RELOAD-URI'],
  21613. pathwayClones = steeringData['PATHWAY-CLONES'],
  21614. pathwayPriority = steeringData['PATHWAY-PRIORITY'];
  21615. if (reloadUri) {
  21616. try {
  21617. _this3.uri = new self.URL(reloadUri, url).href;
  21618. } catch (error) {
  21619. _this3.enabled = false;
  21620. _this3.log("Failed to parse Steering Manifest RELOAD-URI: " + reloadUri);
  21621. return;
  21622. }
  21623. }
  21624. _this3.scheduleRefresh(_this3.uri || context.url);
  21625. if (pathwayClones) {
  21626. _this3.clonePathways(pathwayClones);
  21627. }
  21628. var loadedSteeringData = {
  21629. steeringManifest: steeringData,
  21630. url: url.toString()
  21631. };
  21632. _this3.hls.trigger(Events.STEERING_MANIFEST_LOADED, loadedSteeringData);
  21633. if (pathwayPriority) {
  21634. _this3.updatePathwayPriority(pathwayPriority);
  21635. }
  21636. },
  21637. onError: function onError(error, context, networkDetails, stats) {
  21638. _this3.log("Error loading steering manifest: " + error.code + " " + error.text + " (" + context.url + ")");
  21639. _this3.stopLoad();
  21640. if (error.code === 410) {
  21641. _this3.enabled = false;
  21642. _this3.log("Steering manifest " + context.url + " no longer available");
  21643. return;
  21644. }
  21645. var ttl = _this3.timeToLoad * 1000;
  21646. if (error.code === 429) {
  21647. var loader = _this3.loader;
  21648. if (typeof (loader == null ? void 0 : loader.getResponseHeader) === 'function') {
  21649. var retryAfter = loader.getResponseHeader('Retry-After');
  21650. if (retryAfter) {
  21651. ttl = parseFloat(retryAfter) * 1000;
  21652. }
  21653. }
  21654. _this3.log("Steering manifest " + context.url + " rate limited");
  21655. return;
  21656. }
  21657. _this3.scheduleRefresh(_this3.uri || context.url, ttl);
  21658. },
  21659. onTimeout: function onTimeout(stats, context, networkDetails) {
  21660. _this3.log("Timeout loading steering manifest (" + context.url + ")");
  21661. _this3.scheduleRefresh(_this3.uri || context.url);
  21662. }
  21663. };
  21664. this.log("Requesting steering manifest: " + url);
  21665. this.loader.load(context, loaderConfig, callbacks);
  21666. };
  21667. _proto.scheduleRefresh = function scheduleRefresh(uri, ttlMs) {
  21668. var _this4 = this;
  21669. if (ttlMs === void 0) {
  21670. ttlMs = this.timeToLoad * 1000;
  21671. }
  21672. this.clearTimeout();
  21673. this.reloadTimer = self.setTimeout(function () {
  21674. var _this4$hls;
  21675. var media = (_this4$hls = _this4.hls) == null ? void 0 : _this4$hls.media;
  21676. if (media && !media.ended) {
  21677. _this4.loadSteeringManifest(uri);
  21678. return;
  21679. }
  21680. _this4.scheduleRefresh(uri, _this4.timeToLoad * 1000);
  21681. }, ttlMs);
  21682. };
  21683. return _createClass(ContentSteeringController, [{
  21684. key: "pathwayPriority",
  21685. get: function get() {
  21686. return this._pathwayPriority;
  21687. },
  21688. set: function set(pathwayPriority) {
  21689. this.updatePathwayPriority(pathwayPriority);
  21690. }
  21691. }]);
  21692. }(Logger);
  21693. function cloneRenditionGroups(tracks, groupCloneMap, uriReplacement, cloneId) {
  21694. if (!tracks) {
  21695. return;
  21696. }
  21697. Object.keys(groupCloneMap).forEach(function (audioGroupId) {
  21698. var clonedTracks = tracks.filter(function (track) {
  21699. return track.groupId === audioGroupId;
  21700. }).map(function (track) {
  21701. var clonedTrack = _extends({}, track);
  21702. clonedTrack.details = undefined;
  21703. clonedTrack.attrs = new AttrList(clonedTrack.attrs);
  21704. clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(track.url, track.attrs['STABLE-RENDITION-ID'], 'PER-RENDITION-URIS', uriReplacement);
  21705. clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] = groupCloneMap[audioGroupId];
  21706. clonedTrack.attrs['PATHWAY-ID'] = cloneId;
  21707. return clonedTrack;
  21708. });
  21709. tracks.push.apply(tracks, clonedTracks);
  21710. });
  21711. }
  21712. function performUriReplacement(uri, stableId, perOptionKey, uriReplacement) {
  21713. var host = uriReplacement.HOST,
  21714. params = uriReplacement.PARAMS,
  21715. perOptionUris = uriReplacement[perOptionKey];
  21716. var perVariantUri;
  21717. if (stableId) {
  21718. perVariantUri = perOptionUris == null ? void 0 : perOptionUris[stableId];
  21719. if (perVariantUri) {
  21720. uri = perVariantUri;
  21721. }
  21722. }
  21723. var url = new self.URL(uri);
  21724. if (host && !perVariantUri) {
  21725. url.host = host;
  21726. }
  21727. if (params) {
  21728. Object.keys(params).sort().forEach(function (key) {
  21729. if (key) {
  21730. url.searchParams.set(key, params[key]);
  21731. }
  21732. });
  21733. }
  21734. return url.href;
  21735. }
  21736. function addEventListener(el, type, listener) {
  21737. removeEventListener(el, type, listener);
  21738. el.addEventListener(type, listener);
  21739. }
  21740. function removeEventListener(el, type, listener) {
  21741. el.removeEventListener(type, listener);
  21742. }
  21743. /**
  21744. * Controller to deal with encrypted media extensions (EME)
  21745. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  21746. *
  21747. * @class
  21748. * @constructor
  21749. */
  21750. var EMEController = /*#__PURE__*/function (_Logger) {
  21751. function EMEController(hls) {
  21752. var _this;
  21753. _this = _Logger.call(this, 'eme', hls.logger) || this;
  21754. _this.hls = void 0;
  21755. _this.config = void 0;
  21756. _this.media = null;
  21757. _this.keyFormatPromise = null;
  21758. _this.keySystemAccessPromises = {};
  21759. _this._requestLicenseFailureCount = 0;
  21760. _this.mediaKeySessions = [];
  21761. _this.keyIdToKeySessionPromise = {};
  21762. _this.mediaKeys = null;
  21763. _this.setMediaKeysQueue = EMEController.CDMCleanupPromise ? [EMEController.CDMCleanupPromise] : [];
  21764. _this.onWaitingForKey = function (event) {
  21765. _this.log("\"" + event.type + "\" event");
  21766. };
  21767. _this.hls = hls;
  21768. _this.config = hls.config;
  21769. _this.registerListeners();
  21770. return _this;
  21771. }
  21772. _inheritsLoose(EMEController, _Logger);
  21773. var _proto = EMEController.prototype;
  21774. _proto.destroy = function destroy() {
  21775. this.onDestroying();
  21776. this.onMediaDetached();
  21777. // Remove any references that could be held in config options or callbacks
  21778. var config = this.config;
  21779. config.requestMediaKeySystemAccessFunc = null;
  21780. config.licenseXhrSetup = config.licenseResponseCallback = undefined;
  21781. config.drmSystems = config.drmSystemOptions = {};
  21782. // @ts-ignore
  21783. this.hls = this.config = this.keyIdToKeySessionPromise = null;
  21784. // @ts-ignore
  21785. this.onWaitingForKey = null;
  21786. };
  21787. _proto.registerListeners = function registerListeners() {
  21788. this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21789. this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21790. this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21791. this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21792. this.hls.on(Events.DESTROYING, this.onDestroying, this);
  21793. };
  21794. _proto.unregisterListeners = function unregisterListeners() {
  21795. this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  21796. this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);
  21797. this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  21798. this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  21799. this.hls.off(Events.DESTROYING, this.onDestroying, this);
  21800. };
  21801. _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
  21802. var _this$config = this.config,
  21803. drmSystems = _this$config.drmSystems,
  21804. widevineLicenseUrl = _this$config.widevineLicenseUrl;
  21805. var keySystemConfiguration = drmSystems[keySystem];
  21806. if (keySystemConfiguration) {
  21807. return keySystemConfiguration.licenseUrl;
  21808. }
  21809. // For backward compatibility
  21810. if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {
  21811. return widevineLicenseUrl;
  21812. }
  21813. };
  21814. _proto.getLicenseServerUrlOrThrow = function getLicenseServerUrlOrThrow(keySystem) {
  21815. var url = this.getLicenseServerUrl(keySystem);
  21816. if (url === undefined) {
  21817. throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
  21818. }
  21819. return url;
  21820. };
  21821. _proto.getServerCertificateUrl = function getServerCertificateUrl(keySystem) {
  21822. var drmSystems = this.config.drmSystems;
  21823. var keySystemConfiguration = drmSystems[keySystem];
  21824. if (keySystemConfiguration) {
  21825. return keySystemConfiguration.serverCertificateUrl;
  21826. } else {
  21827. this.log("No Server Certificate in config.drmSystems[\"" + keySystem + "\"]");
  21828. }
  21829. };
  21830. _proto.attemptKeySystemAccess = function attemptKeySystemAccess(keySystemsToAttempt) {
  21831. var _this2 = this;
  21832. var levels = this.hls.levels;
  21833. var uniqueCodec = function uniqueCodec(value, i, a) {
  21834. return !!value && a.indexOf(value) === i;
  21835. };
  21836. var audioCodecs = levels.map(function (level) {
  21837. return level.audioCodec;
  21838. }).filter(uniqueCodec);
  21839. var videoCodecs = levels.map(function (level) {
  21840. return level.videoCodec;
  21841. }).filter(uniqueCodec);
  21842. if (audioCodecs.length + videoCodecs.length === 0) {
  21843. videoCodecs.push('avc1.42e01e');
  21844. }
  21845. return new Promise(function (resolve, reject) {
  21846. var _attempt = function attempt(keySystems) {
  21847. var keySystem = keySystems.shift();
  21848. _this2.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs).then(function (mediaKeys) {
  21849. return resolve({
  21850. keySystem: keySystem,
  21851. mediaKeys: mediaKeys
  21852. });
  21853. }).catch(function (error) {
  21854. if (keySystems.length) {
  21855. _attempt(keySystems);
  21856. } else if (error instanceof EMEKeyError) {
  21857. reject(error);
  21858. } else {
  21859. reject(new EMEKeyError({
  21860. type: ErrorTypes.KEY_SYSTEM_ERROR,
  21861. details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  21862. error: error,
  21863. fatal: true
  21864. }, error.message));
  21865. }
  21866. });
  21867. };
  21868. _attempt(keySystemsToAttempt);
  21869. });
  21870. };
  21871. _proto.requestMediaKeySystemAccess = function requestMediaKeySystemAccess$1(keySystem, supportedConfigurations) {
  21872. var requestMediaKeySystemAccessFunc = this.config.requestMediaKeySystemAccessFunc;
  21873. if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {
  21874. var errMessage = "Configured requestMediaKeySystemAccess is not a function " + requestMediaKeySystemAccessFunc;
  21875. if (requestMediaKeySystemAccess === null && self.location.protocol === 'http:') {
  21876. errMessage = "navigator.requestMediaKeySystemAccess is not available over insecure protocol " + location.protocol;
  21877. }
  21878. return Promise.reject(new Error(errMessage));
  21879. }
  21880. return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);
  21881. };
  21882. _proto.getMediaKeysPromise = function getMediaKeysPromise(keySystem, audioCodecs, videoCodecs) {
  21883. var _this3 = this;
  21884. // This can throw, but is caught in event handler callpath
  21885. var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this.config.drmSystemOptions);
  21886. var keySystemAccessPromises = this.keySystemAccessPromises[keySystem];
  21887. var keySystemAccess = keySystemAccessPromises == null ? void 0 : keySystemAccessPromises.keySystemAccess;
  21888. if (!keySystemAccess) {
  21889. this.log("Requesting encrypted media \"" + keySystem + "\" key-system access with config: " + stringify(mediaKeySystemConfigs));
  21890. keySystemAccess = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
  21891. var _keySystemAccessPromises = this.keySystemAccessPromises[keySystem] = {
  21892. keySystemAccess: keySystemAccess
  21893. };
  21894. keySystemAccess.catch(function (error) {
  21895. _this3.log("Failed to obtain access to key-system \"" + keySystem + "\": " + error);
  21896. });
  21897. return keySystemAccess.then(function (mediaKeySystemAccess) {
  21898. _this3.log("Access for key-system \"" + mediaKeySystemAccess.keySystem + "\" obtained");
  21899. var certificateRequest = _this3.fetchServerCertificate(keySystem);
  21900. _this3.log("Create media-keys for \"" + keySystem + "\"");
  21901. _keySystemAccessPromises.mediaKeys = mediaKeySystemAccess.createMediaKeys().then(function (mediaKeys) {
  21902. _this3.log("Media-keys created for \"" + keySystem + "\"");
  21903. _keySystemAccessPromises.hasMediaKeys = true;
  21904. return certificateRequest.then(function (certificate) {
  21905. if (certificate) {
  21906. return _this3.setMediaKeysServerCertificate(mediaKeys, keySystem, certificate);
  21907. }
  21908. return mediaKeys;
  21909. });
  21910. });
  21911. _keySystemAccessPromises.mediaKeys.catch(function (error) {
  21912. _this3.error("Failed to create media-keys for \"" + keySystem + "\"}: " + error);
  21913. });
  21914. return _keySystemAccessPromises.mediaKeys;
  21915. });
  21916. }
  21917. return keySystemAccess.then(function () {
  21918. return keySystemAccessPromises.mediaKeys;
  21919. });
  21920. };
  21921. _proto.createMediaKeySessionContext = function createMediaKeySessionContext(_ref) {
  21922. var decryptdata = _ref.decryptdata,
  21923. keySystem = _ref.keySystem,
  21924. mediaKeys = _ref.mediaKeys;
  21925. this.log("Creating key-system session \"" + keySystem + "\" keyId: " + Hex.hexDump(decryptdata.keyId || []));
  21926. var mediaKeysSession = mediaKeys.createSession();
  21927. var mediaKeySessionContext = {
  21928. decryptdata: decryptdata,
  21929. keySystem: keySystem,
  21930. mediaKeys: mediaKeys,
  21931. mediaKeysSession: mediaKeysSession,
  21932. keyStatus: 'status-pending'
  21933. };
  21934. this.mediaKeySessions.push(mediaKeySessionContext);
  21935. return mediaKeySessionContext;
  21936. };
  21937. _proto.renewKeySession = function renewKeySession(mediaKeySessionContext) {
  21938. var decryptdata = mediaKeySessionContext.decryptdata;
  21939. if (decryptdata.pssh) {
  21940. var keySessionContext = this.createMediaKeySessionContext(mediaKeySessionContext);
  21941. var keyId = this.getKeyIdString(decryptdata);
  21942. var scheme = 'cenc';
  21943. this.keyIdToKeySessionPromise[keyId] = this.generateRequestWithPreferredKeySession(keySessionContext, scheme, decryptdata.pssh.buffer, 'expired');
  21944. } else {
  21945. this.warn("Could not renew expired session. Missing pssh initData.");
  21946. }
  21947. this.removeSession(mediaKeySessionContext);
  21948. };
  21949. _proto.getKeyIdString = function getKeyIdString(decryptdata) {
  21950. if (!decryptdata) {
  21951. throw new Error('Could not read keyId of undefined decryptdata');
  21952. }
  21953. if (decryptdata.keyId === null) {
  21954. throw new Error('keyId is null');
  21955. }
  21956. return Hex.hexDump(decryptdata.keyId);
  21957. };
  21958. _proto.updateKeySession = function updateKeySession(mediaKeySessionContext, data) {
  21959. var _mediaKeySessionConte;
  21960. var keySession = mediaKeySessionContext.mediaKeysSession;
  21961. this.log("Updating key-session \"" + keySession.sessionId + "\" for keyID " + Hex.hexDump(((_mediaKeySessionConte = mediaKeySessionContext.decryptdata) == null ? void 0 : _mediaKeySessionConte.keyId) || []) + "\n } (data length: " + (data ? data.byteLength : data) + ")");
  21962. return keySession.update(data);
  21963. };
  21964. _proto.getSelectedKeySystemFormats = function getSelectedKeySystemFormats() {
  21965. var _this4 = this;
  21966. return Object.keys(this.keySystemAccessPromises).map(function (keySystem) {
  21967. return {
  21968. keySystem: keySystem,
  21969. hasMediaKeys: _this4.keySystemAccessPromises[keySystem].hasMediaKeys
  21970. };
  21971. }).filter(function (_ref2) {
  21972. var hasMediaKeys = _ref2.hasMediaKeys;
  21973. return !!hasMediaKeys;
  21974. }).map(function (_ref3) {
  21975. var keySystem = _ref3.keySystem;
  21976. return keySystemDomainToKeySystemFormat(keySystem);
  21977. }).filter(function (keySystem) {
  21978. return !!keySystem;
  21979. });
  21980. };
  21981. _proto.getKeySystemAccess = function getKeySystemAccess(keySystemsToAttempt) {
  21982. var _this5 = this;
  21983. return this.getKeySystemSelectionPromise(keySystemsToAttempt).then(function (_ref4) {
  21984. var keySystem = _ref4.keySystem,
  21985. mediaKeys = _ref4.mediaKeys;
  21986. return _this5.attemptSetMediaKeys(keySystem, mediaKeys);
  21987. });
  21988. };
  21989. _proto.selectKeySystem = function selectKeySystem(keySystemsToAttempt) {
  21990. var _this6 = this;
  21991. return new Promise(function (resolve, reject) {
  21992. return _this6.getKeySystemSelectionPromise(keySystemsToAttempt).then(function (_ref5) {
  21993. var keySystem = _ref5.keySystem;
  21994. var keySystemFormat = keySystemDomainToKeySystemFormat(keySystem);
  21995. if (keySystemFormat) {
  21996. resolve(keySystemFormat);
  21997. } else {
  21998. reject(new Error("Unable to find format for key-system \"" + keySystem + "\""));
  21999. }
  22000. }).catch(reject);
  22001. });
  22002. };
  22003. _proto.selectKeySystemFormat = function selectKeySystemFormat(frag) {
  22004. var keyFormats = Object.keys(frag.levelkeys || {});
  22005. if (!this.keyFormatPromise) {
  22006. this.log("Selecting key-system from fragment (sn: " + frag.sn + " " + frag.type + ": " + frag.level + ") key formats " + keyFormats.join(', '));
  22007. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  22008. }
  22009. return this.keyFormatPromise;
  22010. };
  22011. _proto.getKeyFormatPromise = function getKeyFormatPromise(keyFormats) {
  22012. var keySystemsInConfig = getKeySystemsForConfig(this.config);
  22013. var keySystemsToAttempt = keyFormats.map(keySystemFormatToKeySystemDomain).filter(function (value) {
  22014. return !!value && keySystemsInConfig.indexOf(value) !== -1;
  22015. });
  22016. return this.selectKeySystem(keySystemsToAttempt);
  22017. };
  22018. _proto.loadKey = function loadKey(data) {
  22019. var _this7 = this;
  22020. var decryptdata = data.keyInfo.decryptdata;
  22021. var keyId = this.getKeyIdString(decryptdata);
  22022. var keyDetails = "(keyId: " + keyId + " format: \"" + decryptdata.keyFormat + "\" method: " + decryptdata.method + " uri: " + decryptdata.uri + ")";
  22023. this.log("Starting session for key " + keyDetails);
  22024. var keyContextPromise = this.keyIdToKeySessionPromise[keyId];
  22025. if (!keyContextPromise) {
  22026. keyContextPromise = this.getKeySystemForKeyPromise(decryptdata).then(function (_ref6) {
  22027. var keySystem = _ref6.keySystem,
  22028. mediaKeys = _ref6.mediaKeys;
  22029. _this7.throwIfDestroyed();
  22030. _this7.log("Handle encrypted media sn: " + data.frag.sn + " " + data.frag.type + ": " + data.frag.level + " using key " + keyDetails);
  22031. return _this7.attemptSetMediaKeys(keySystem, mediaKeys).then(function () {
  22032. _this7.throwIfDestroyed();
  22033. return _this7.createMediaKeySessionContext({
  22034. keySystem: keySystem,
  22035. mediaKeys: mediaKeys,
  22036. decryptdata: decryptdata
  22037. });
  22038. });
  22039. });
  22040. var keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] = keyContextPromise.then(function (keySessionContext) {
  22041. var scheme = 'cenc';
  22042. var initData = decryptdata.pssh ? decryptdata.pssh.buffer : null;
  22043. return _this7.generateRequestWithPreferredKeySession(keySessionContext, scheme, initData, 'playlist-key');
  22044. });
  22045. keySessionContextPromise.catch(function (error) {
  22046. return _this7.handleError(error);
  22047. });
  22048. }
  22049. return keyContextPromise;
  22050. };
  22051. _proto.throwIfDestroyed = function throwIfDestroyed(message) {
  22052. if (!this.hls) {
  22053. throw new Error('invalid state');
  22054. }
  22055. };
  22056. _proto.handleError = function handleError(error) {
  22057. if (!this.hls) {
  22058. return;
  22059. }
  22060. this.error(error.message);
  22061. if (error instanceof EMEKeyError) {
  22062. this.hls.trigger(Events.ERROR, error.data);
  22063. } else {
  22064. this.hls.trigger(Events.ERROR, {
  22065. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22066. details: ErrorDetails.KEY_SYSTEM_NO_KEYS,
  22067. error: error,
  22068. fatal: true
  22069. });
  22070. }
  22071. };
  22072. _proto.getKeySystemForKeyPromise = function getKeySystemForKeyPromise(decryptdata) {
  22073. var keyId = this.getKeyIdString(decryptdata);
  22074. var mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];
  22075. if (!mediaKeySessionContext) {
  22076. var keySystem = keySystemFormatToKeySystemDomain(decryptdata.keyFormat);
  22077. var keySystemsToAttempt = keySystem ? [keySystem] : getKeySystemsForConfig(this.config);
  22078. return this.attemptKeySystemAccess(keySystemsToAttempt);
  22079. }
  22080. return mediaKeySessionContext;
  22081. };
  22082. _proto.getKeySystemSelectionPromise = function getKeySystemSelectionPromise(keySystemsToAttempt) {
  22083. if (!keySystemsToAttempt.length) {
  22084. keySystemsToAttempt = getKeySystemsForConfig(this.config);
  22085. }
  22086. if (keySystemsToAttempt.length === 0) {
  22087. throw new EMEKeyError({
  22088. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22089. details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,
  22090. fatal: true
  22091. }, "Missing key-system license configuration options " + stringify({
  22092. drmSystems: this.config.drmSystems
  22093. }));
  22094. }
  22095. return this.attemptKeySystemAccess(keySystemsToAttempt);
  22096. };
  22097. _proto.attemptSetMediaKeys = function attemptSetMediaKeys(keySystem, mediaKeys) {
  22098. var _this8 = this;
  22099. if (this.mediaKeys === mediaKeys) {
  22100. return Promise.resolve();
  22101. }
  22102. var queue = this.setMediaKeysQueue.slice();
  22103. this.log("Setting media-keys for \"" + keySystem + "\"");
  22104. // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations
  22105. // can be queued for execution for multiple key sessions.
  22106. var setMediaKeysPromise = Promise.all(queue).then(function () {
  22107. if (!_this8.media) {
  22108. _this8.mediaKeys = null;
  22109. throw new Error('Attempted to set mediaKeys without media element attached');
  22110. }
  22111. return _this8.media.setMediaKeys(mediaKeys);
  22112. });
  22113. this.mediaKeys = mediaKeys;
  22114. this.setMediaKeysQueue.push(setMediaKeysPromise);
  22115. return setMediaKeysPromise.then(function () {
  22116. _this8.log("Media-keys set for \"" + keySystem + "\"");
  22117. queue.push(setMediaKeysPromise);
  22118. _this8.setMediaKeysQueue = _this8.setMediaKeysQueue.filter(function (p) {
  22119. return queue.indexOf(p) === -1;
  22120. });
  22121. });
  22122. };
  22123. _proto.generateRequestWithPreferredKeySession = function generateRequestWithPreferredKeySession(context, initDataType, initData, reason) {
  22124. var _this$config$drmSyste,
  22125. _this$config$drmSyste2,
  22126. _this9 = this;
  22127. var generateRequestFilter = (_this$config$drmSyste = this.config.drmSystems) == null ? void 0 : (_this$config$drmSyste2 = _this$config$drmSyste[context.keySystem]) == null ? void 0 : _this$config$drmSyste2.generateRequest;
  22128. if (generateRequestFilter) {
  22129. try {
  22130. var mappedInitData = generateRequestFilter.call(this.hls, initDataType, initData, context);
  22131. if (!mappedInitData) {
  22132. throw new Error('Invalid response from configured generateRequest filter');
  22133. }
  22134. initDataType = mappedInitData.initDataType;
  22135. initData = mappedInitData.initData ? mappedInitData.initData : null;
  22136. context.decryptdata.pssh = initData ? new Uint8Array(initData) : null;
  22137. } catch (error) {
  22138. var _this$hls;
  22139. this.warn(error.message);
  22140. if ((_this$hls = this.hls) != null && _this$hls.config.debug) {
  22141. throw error;
  22142. }
  22143. }
  22144. }
  22145. if (initData === null) {
  22146. this.log("Skipping key-session request for \"" + reason + "\" (no initData)");
  22147. return Promise.resolve(context);
  22148. }
  22149. var keyId = this.getKeyIdString(context.decryptdata);
  22150. this.log("Generating key-session request for \"" + reason + "\": " + keyId + " (init data type: " + initDataType + " length: " + (initData ? initData.byteLength : null) + ")");
  22151. var licenseStatus = new EventEmitter();
  22152. var onmessage = context._onmessage = function (event) {
  22153. var keySession = context.mediaKeysSession;
  22154. if (!keySession) {
  22155. licenseStatus.emit('error', new Error('invalid state'));
  22156. return;
  22157. }
  22158. var messageType = event.messageType,
  22159. message = event.message;
  22160. _this9.log("\"" + messageType + "\" message event for session \"" + keySession.sessionId + "\" message size: " + message.byteLength);
  22161. if (messageType === 'license-request' || messageType === 'license-renewal') {
  22162. _this9.renewLicense(context, message).catch(function (error) {
  22163. if (licenseStatus.eventNames().length) {
  22164. licenseStatus.emit('error', error);
  22165. } else {
  22166. _this9.handleError(error);
  22167. }
  22168. });
  22169. } else if (messageType === 'license-release') {
  22170. if (context.keySystem === KeySystems.FAIRPLAY) {
  22171. _this9.updateKeySession(context, strToUtf8array('acknowledged'));
  22172. _this9.removeSession(context);
  22173. }
  22174. } else {
  22175. _this9.warn("unhandled media key message type \"" + messageType + "\"");
  22176. }
  22177. };
  22178. var onkeystatuseschange = context._onkeystatuseschange = function (event) {
  22179. var keySession = context.mediaKeysSession;
  22180. if (!keySession) {
  22181. licenseStatus.emit('error', new Error('invalid state'));
  22182. return;
  22183. }
  22184. _this9.onKeyStatusChange(context);
  22185. var keyStatus = context.keyStatus;
  22186. licenseStatus.emit('keyStatus', keyStatus);
  22187. if (keyStatus === 'expired') {
  22188. _this9.warn(context.keySystem + " expired for key " + keyId);
  22189. _this9.renewKeySession(context);
  22190. }
  22191. };
  22192. addEventListener(context.mediaKeysSession, 'message', onmessage);
  22193. addEventListener(context.mediaKeysSession, 'keystatuseschange', onkeystatuseschange);
  22194. var keyUsablePromise = new Promise(function (resolve, reject) {
  22195. licenseStatus.on('error', reject);
  22196. licenseStatus.on('keyStatus', function (keyStatus) {
  22197. if (keyStatus.startsWith('usable')) {
  22198. resolve();
  22199. } else if (keyStatus === 'output-restricted') {
  22200. reject(new EMEKeyError({
  22201. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22202. details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,
  22203. fatal: false
  22204. }, 'HDCP level output restricted'));
  22205. } else if (keyStatus === 'internal-error') {
  22206. reject(new EMEKeyError({
  22207. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22208. details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,
  22209. fatal: true
  22210. }, "key status changed to \"" + keyStatus + "\""));
  22211. } else if (keyStatus === 'expired') {
  22212. reject(new Error('key expired while generating request'));
  22213. } else {
  22214. _this9.warn("unhandled key status change \"" + keyStatus + "\"");
  22215. }
  22216. });
  22217. });
  22218. return context.mediaKeysSession.generateRequest(initDataType, initData).then(function () {
  22219. var _context$mediaKeysSes;
  22220. _this9.log("Request generated for key-session \"" + ((_context$mediaKeysSes = context.mediaKeysSession) == null ? void 0 : _context$mediaKeysSes.sessionId) + "\" keyId: " + keyId);
  22221. }).catch(function (error) {
  22222. throw new EMEKeyError({
  22223. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22224. details: ErrorDetails.KEY_SYSTEM_NO_SESSION,
  22225. error: error,
  22226. fatal: false
  22227. }, "Error generating key-session request: " + error);
  22228. }).then(function () {
  22229. return keyUsablePromise;
  22230. }).catch(function (error) {
  22231. licenseStatus.removeAllListeners();
  22232. _this9.removeSession(context);
  22233. throw error;
  22234. }).then(function () {
  22235. licenseStatus.removeAllListeners();
  22236. return context;
  22237. });
  22238. };
  22239. _proto.onKeyStatusChange = function onKeyStatusChange(mediaKeySessionContext) {
  22240. var _this0 = this;
  22241. mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach(function (status, keyId) {
  22242. // keyStatuses.forEach is not standard API so the callback value looks weird on xboxone
  22243. // xboxone callback(keyId, status) so we need to exchange them
  22244. if (typeof keyId === 'string' && typeof status === 'object') {
  22245. var temp = keyId;
  22246. keyId = status;
  22247. status = temp;
  22248. }
  22249. _this0.log("key status change \"" + status + "\" for keyStatuses keyId: " + Hex.hexDump('buffer' in keyId ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength) : new Uint8Array(keyId)) + " session keyId: " + Hex.hexDump(new Uint8Array(mediaKeySessionContext.decryptdata.keyId || [])) + " uri: " + mediaKeySessionContext.decryptdata.uri);
  22250. mediaKeySessionContext.keyStatus = status;
  22251. });
  22252. };
  22253. _proto.fetchServerCertificate = function fetchServerCertificate(keySystem) {
  22254. var config = this.config;
  22255. var Loader = config.loader;
  22256. var certLoader = new Loader(config);
  22257. var url = this.getServerCertificateUrl(keySystem);
  22258. if (!url) {
  22259. return Promise.resolve();
  22260. }
  22261. this.log("Fetching server certificate for \"" + keySystem + "\"");
  22262. return new Promise(function (resolve, reject) {
  22263. var loaderContext = {
  22264. responseType: 'arraybuffer',
  22265. url: url
  22266. };
  22267. var loadPolicy = config.certLoadPolicy.default;
  22268. var loaderConfig = {
  22269. loadPolicy: loadPolicy,
  22270. timeout: loadPolicy.maxLoadTimeMs,
  22271. maxRetry: 0,
  22272. retryDelay: 0,
  22273. maxRetryDelay: 0
  22274. };
  22275. var loaderCallbacks = {
  22276. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  22277. resolve(response.data);
  22278. },
  22279. onError: function onError(response, contex, networkDetails, stats) {
  22280. reject(new EMEKeyError({
  22281. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22282. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  22283. fatal: true,
  22284. networkDetails: networkDetails,
  22285. response: _objectSpread2({
  22286. url: loaderContext.url,
  22287. data: undefined
  22288. }, response)
  22289. }, "\"" + keySystem + "\" certificate request failed (" + url + "). Status: " + response.code + " (" + response.text + ")"));
  22290. },
  22291. onTimeout: function onTimeout(stats, context, networkDetails) {
  22292. reject(new EMEKeyError({
  22293. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22294. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,
  22295. fatal: true,
  22296. networkDetails: networkDetails,
  22297. response: {
  22298. url: loaderContext.url,
  22299. data: undefined
  22300. }
  22301. }, "\"" + keySystem + "\" certificate request timed out (" + url + ")"));
  22302. },
  22303. onAbort: function onAbort(stats, context, networkDetails) {
  22304. reject(new Error('aborted'));
  22305. }
  22306. };
  22307. certLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  22308. });
  22309. };
  22310. _proto.setMediaKeysServerCertificate = function setMediaKeysServerCertificate(mediaKeys, keySystem, cert) {
  22311. var _this1 = this;
  22312. return new Promise(function (resolve, reject) {
  22313. mediaKeys.setServerCertificate(cert).then(function (success) {
  22314. _this1.log("setServerCertificate " + (success ? 'success' : 'not supported by CDM') + " (" + (cert == null ? void 0 : cert.byteLength) + ") on \"" + keySystem + "\"");
  22315. resolve(mediaKeys);
  22316. }).catch(function (error) {
  22317. reject(new EMEKeyError({
  22318. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22319. details: ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,
  22320. error: error,
  22321. fatal: true
  22322. }, error.message));
  22323. });
  22324. });
  22325. };
  22326. _proto.renewLicense = function renewLicense(context, keyMessage) {
  22327. var _this10 = this;
  22328. return this.requestLicense(context, new Uint8Array(keyMessage)).then(function (data) {
  22329. return _this10.updateKeySession(context, new Uint8Array(data)).catch(function (error) {
  22330. throw new EMEKeyError({
  22331. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22332. details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,
  22333. error: error,
  22334. fatal: true
  22335. }, error.message);
  22336. });
  22337. });
  22338. };
  22339. _proto.unpackPlayReadyKeyMessage = function unpackPlayReadyKeyMessage(xhr, licenseChallenge) {
  22340. // On Edge, the raw license message is UTF-16-encoded XML. We need
  22341. // to unpack the Challenge element (base64-encoded string containing the
  22342. // actual license request) and any HttpHeader elements (sent as request
  22343. // headers).
  22344. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  22345. var xmlString = String.fromCharCode.apply(null, new Uint16Array(licenseChallenge.buffer));
  22346. if (!xmlString.includes('PlayReadyKeyMessage')) {
  22347. // This does not appear to be a wrapped message as on Edge. Some
  22348. // clients do not need this unwrapping, so we will assume this is one of
  22349. // them. Note that "xml" at this point probably looks like random
  22350. // garbage, since we interpreted UTF-8 as UTF-16.
  22351. xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
  22352. return licenseChallenge;
  22353. }
  22354. var keyMessageXml = new DOMParser().parseFromString(xmlString, 'application/xml');
  22355. // Set request headers.
  22356. var headers = keyMessageXml.querySelectorAll('HttpHeader');
  22357. if (headers.length > 0) {
  22358. var header;
  22359. for (var i = 0, len = headers.length; i < len; i++) {
  22360. var _header$querySelector, _header$querySelector2;
  22361. header = headers[i];
  22362. var name = (_header$querySelector = header.querySelector('name')) == null ? void 0 : _header$querySelector.textContent;
  22363. var value = (_header$querySelector2 = header.querySelector('value')) == null ? void 0 : _header$querySelector2.textContent;
  22364. if (name && value) {
  22365. xhr.setRequestHeader(name, value);
  22366. }
  22367. }
  22368. }
  22369. var challengeElement = keyMessageXml.querySelector('Challenge');
  22370. var challengeText = challengeElement == null ? void 0 : challengeElement.textContent;
  22371. if (!challengeText) {
  22372. throw new Error("Cannot find <Challenge> in key message");
  22373. }
  22374. return strToUtf8array(atob(challengeText));
  22375. };
  22376. _proto.setupLicenseXHR = function setupLicenseXHR(xhr, url, keysListItem, licenseChallenge) {
  22377. var _this11 = this;
  22378. var licenseXhrSetup = this.config.licenseXhrSetup;
  22379. if (!licenseXhrSetup) {
  22380. xhr.open('POST', url, true);
  22381. return Promise.resolve({
  22382. xhr: xhr,
  22383. licenseChallenge: licenseChallenge
  22384. });
  22385. }
  22386. return Promise.resolve().then(function () {
  22387. if (!keysListItem.decryptdata) {
  22388. throw new Error('Key removed');
  22389. }
  22390. return licenseXhrSetup.call(_this11.hls, xhr, url, keysListItem, licenseChallenge);
  22391. }).catch(function (error) {
  22392. if (!keysListItem.decryptdata) {
  22393. // Key session removed. Cancel license request.
  22394. throw error;
  22395. }
  22396. // let's try to open before running setup
  22397. xhr.open('POST', url, true);
  22398. return licenseXhrSetup.call(_this11.hls, xhr, url, keysListItem, licenseChallenge);
  22399. }).then(function (licenseXhrSetupResult) {
  22400. // if licenseXhrSetup did not yet call open, let's do it now
  22401. if (!xhr.readyState) {
  22402. xhr.open('POST', url, true);
  22403. }
  22404. var finalLicenseChallenge = licenseXhrSetupResult ? licenseXhrSetupResult : licenseChallenge;
  22405. return {
  22406. xhr: xhr,
  22407. licenseChallenge: finalLicenseChallenge
  22408. };
  22409. });
  22410. };
  22411. _proto.requestLicense = function requestLicense(keySessionContext, licenseChallenge) {
  22412. var _this12 = this;
  22413. var keyLoadPolicy = this.config.keyLoadPolicy.default;
  22414. return new Promise(function (resolve, reject) {
  22415. var url = _this12.getLicenseServerUrlOrThrow(keySessionContext.keySystem);
  22416. _this12.log("Sending license request to URL: " + url);
  22417. var xhr = new XMLHttpRequest();
  22418. xhr.responseType = 'arraybuffer';
  22419. xhr.onreadystatechange = function () {
  22420. if (!_this12.hls || !keySessionContext.mediaKeysSession) {
  22421. return reject(new Error('invalid state'));
  22422. }
  22423. if (xhr.readyState === 4) {
  22424. if (xhr.status === 200) {
  22425. _this12._requestLicenseFailureCount = 0;
  22426. var data = xhr.response;
  22427. _this12.log("License received " + (data instanceof ArrayBuffer ? data.byteLength : data));
  22428. var licenseResponseCallback = _this12.config.licenseResponseCallback;
  22429. if (licenseResponseCallback) {
  22430. try {
  22431. data = licenseResponseCallback.call(_this12.hls, xhr, url, keySessionContext);
  22432. } catch (error) {
  22433. _this12.error(error);
  22434. }
  22435. }
  22436. resolve(data);
  22437. } else {
  22438. var retryConfig = keyLoadPolicy.errorRetry;
  22439. var maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;
  22440. _this12._requestLicenseFailureCount++;
  22441. if (_this12._requestLicenseFailureCount > maxNumRetry || xhr.status >= 400 && xhr.status < 500) {
  22442. reject(new EMEKeyError({
  22443. type: ErrorTypes.KEY_SYSTEM_ERROR,
  22444. details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  22445. fatal: true,
  22446. networkDetails: xhr,
  22447. response: {
  22448. url: url,
  22449. data: undefined,
  22450. code: xhr.status,
  22451. text: xhr.statusText
  22452. }
  22453. }, "License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")"));
  22454. } else {
  22455. var attemptsLeft = maxNumRetry - _this12._requestLicenseFailureCount + 1;
  22456. _this12.warn("Retrying license request, " + attemptsLeft + " attempts left");
  22457. _this12.requestLicense(keySessionContext, licenseChallenge).then(resolve, reject);
  22458. }
  22459. }
  22460. }
  22461. };
  22462. if (keySessionContext.licenseXhr && keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22463. keySessionContext.licenseXhr.abort();
  22464. }
  22465. keySessionContext.licenseXhr = xhr;
  22466. _this12.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(function (_ref7) {
  22467. var xhr = _ref7.xhr,
  22468. licenseChallenge = _ref7.licenseChallenge;
  22469. if (keySessionContext.keySystem == KeySystems.PLAYREADY) {
  22470. licenseChallenge = _this12.unpackPlayReadyKeyMessage(xhr, licenseChallenge);
  22471. }
  22472. xhr.send(licenseChallenge);
  22473. });
  22474. });
  22475. };
  22476. _proto.onDestroying = function onDestroying() {
  22477. this.unregisterListeners();
  22478. this._clear();
  22479. };
  22480. _proto.onMediaAttached = function onMediaAttached(event, data) {
  22481. if (!this.config.emeEnabled) {
  22482. return;
  22483. }
  22484. var media = data.media;
  22485. // keep reference of media
  22486. this.media = media;
  22487. addEventListener(media, 'waitingforkey', this.onWaitingForKey);
  22488. };
  22489. _proto.onMediaDetached = function onMediaDetached() {
  22490. var media = this.media;
  22491. if (media) {
  22492. removeEventListener(media, 'waitingforkey', this.onWaitingForKey);
  22493. this.media = null;
  22494. this.mediaKeys = null;
  22495. }
  22496. };
  22497. _proto._clear = function _clear() {
  22498. var _this13 = this,
  22499. _media$setMediaKeys;
  22500. this._requestLicenseFailureCount = 0;
  22501. this.keyIdToKeySessionPromise = {};
  22502. if (!this.mediaKeys && !this.mediaKeySessions.length) {
  22503. return;
  22504. }
  22505. var media = this.media;
  22506. var mediaKeysList = this.mediaKeySessions.slice();
  22507. this.mediaKeySessions = [];
  22508. this.mediaKeys = null;
  22509. LevelKey.clearKeyUriToKeyIdMap();
  22510. // Close all sessions and remove media keys from the video element.
  22511. var keySessionCount = mediaKeysList.length;
  22512. EMEController.CDMCleanupPromise = Promise.all(mediaKeysList.map(function (mediaKeySessionContext) {
  22513. return _this13.removeSession(mediaKeySessionContext);
  22514. }).concat(media == null ? void 0 : (_media$setMediaKeys = media.setMediaKeys(null)) == null ? void 0 : _media$setMediaKeys.catch(function (error) {
  22515. var _this13$hls;
  22516. _this13.log("Could not clear media keys: " + error);
  22517. (_this13$hls = _this13.hls) == null ? void 0 : _this13$hls.trigger(Events.ERROR, {
  22518. type: ErrorTypes.OTHER_ERROR,
  22519. details: ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,
  22520. fatal: false,
  22521. error: new Error("Could not clear media keys: " + error)
  22522. });
  22523. }))).catch(function (error) {
  22524. var _this13$hls2;
  22525. _this13.log("Could not close sessions and clear media keys: " + error);
  22526. (_this13$hls2 = _this13.hls) == null ? void 0 : _this13$hls2.trigger(Events.ERROR, {
  22527. type: ErrorTypes.OTHER_ERROR,
  22528. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  22529. fatal: false,
  22530. error: new Error("Could not close sessions and clear media keys: " + error)
  22531. });
  22532. }).then(function () {
  22533. if (keySessionCount) {
  22534. _this13.log('finished closing key sessions and clearing media keys');
  22535. }
  22536. });
  22537. };
  22538. _proto.onManifestLoading = function onManifestLoading() {
  22539. this.keyFormatPromise = null;
  22540. };
  22541. _proto.onManifestLoaded = function onManifestLoaded(event, _ref8) {
  22542. var sessionKeys = _ref8.sessionKeys;
  22543. if (!sessionKeys || !this.config.emeEnabled) {
  22544. return;
  22545. }
  22546. if (!this.keyFormatPromise) {
  22547. var keyFormats = sessionKeys.reduce(function (formats, sessionKey) {
  22548. if (formats.indexOf(sessionKey.keyFormat) === -1) {
  22549. formats.push(sessionKey.keyFormat);
  22550. }
  22551. return formats;
  22552. }, []);
  22553. this.log("Selecting key-system from session-keys " + keyFormats.join(', '));
  22554. this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);
  22555. }
  22556. };
  22557. _proto.removeSession = function removeSession(mediaKeySessionContext) {
  22558. var _this14 = this;
  22559. var mediaKeysSession = mediaKeySessionContext.mediaKeysSession,
  22560. licenseXhr = mediaKeySessionContext.licenseXhr;
  22561. if (mediaKeysSession) {
  22562. this.log("Remove licenses and keys and close session " + mediaKeysSession.sessionId);
  22563. if (mediaKeySessionContext._onmessage) {
  22564. mediaKeysSession.removeEventListener('message', mediaKeySessionContext._onmessage);
  22565. mediaKeySessionContext._onmessage = undefined;
  22566. }
  22567. if (mediaKeySessionContext._onkeystatuseschange) {
  22568. mediaKeysSession.removeEventListener('keystatuseschange', mediaKeySessionContext._onkeystatuseschange);
  22569. mediaKeySessionContext._onkeystatuseschange = undefined;
  22570. }
  22571. if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {
  22572. licenseXhr.abort();
  22573. }
  22574. mediaKeySessionContext.mediaKeysSession = mediaKeySessionContext.decryptdata = mediaKeySessionContext.licenseXhr = undefined;
  22575. var index = this.mediaKeySessions.indexOf(mediaKeySessionContext);
  22576. if (index > -1) {
  22577. this.mediaKeySessions.splice(index, 1);
  22578. }
  22579. var drmSystemOptions = this.config.drmSystemOptions;
  22580. var removePromise = isPersistentSessionType(drmSystemOptions) ? new Promise(function (resolve, reject) {
  22581. self.setTimeout(function () {
  22582. return reject(new Error("MediaKeySession.remove() timeout"));
  22583. }, 8000);
  22584. mediaKeysSession.remove().then(resolve);
  22585. }) : Promise.resolve();
  22586. return removePromise.catch(function (error) {
  22587. var _this14$hls;
  22588. _this14.log("Could not remove session: " + error);
  22589. (_this14$hls = _this14.hls) == null ? void 0 : _this14$hls.trigger(Events.ERROR, {
  22590. type: ErrorTypes.OTHER_ERROR,
  22591. details: ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,
  22592. fatal: false,
  22593. error: new Error("Could not remove session: " + error)
  22594. });
  22595. }).then(function () {
  22596. return mediaKeysSession.close();
  22597. }).catch(function (error) {
  22598. var _this14$hls2;
  22599. _this14.log("Could not close session: " + error);
  22600. (_this14$hls2 = _this14.hls) == null ? void 0 : _this14$hls2.trigger(Events.ERROR, {
  22601. type: ErrorTypes.OTHER_ERROR,
  22602. details: ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,
  22603. fatal: false,
  22604. error: new Error("Could not close session: " + error)
  22605. });
  22606. });
  22607. }
  22608. };
  22609. return EMEController;
  22610. }(Logger);
  22611. EMEController.CDMCleanupPromise = void 0;
  22612. var EMEKeyError = /*#__PURE__*/function (_Error) {
  22613. function EMEKeyError(data, message) {
  22614. var _this15;
  22615. _this15 = _Error.call(this, message) || this;
  22616. _this15.data = void 0;
  22617. data.error || (data.error = new Error(message));
  22618. _this15.data = data;
  22619. data.err = data.error;
  22620. return _this15;
  22621. }
  22622. _inheritsLoose(EMEKeyError, _Error);
  22623. return EMEKeyError;
  22624. }(/*#__PURE__*/_wrapNativeSuper(Error));
  22625. var FPSController = /*#__PURE__*/function () {
  22626. function FPSController(hls) {
  22627. this.hls = void 0;
  22628. this.isVideoPlaybackQualityAvailable = false;
  22629. this.timer = void 0;
  22630. this.media = null;
  22631. this.lastTime = void 0;
  22632. this.lastDroppedFrames = 0;
  22633. this.lastDecodedFrames = 0;
  22634. // stream controller must be provided as a dependency!
  22635. this.streamController = void 0;
  22636. this.hls = hls;
  22637. this.registerListeners();
  22638. }
  22639. var _proto = FPSController.prototype;
  22640. _proto.setStreamController = function setStreamController(streamController) {
  22641. this.streamController = streamController;
  22642. };
  22643. _proto.registerListeners = function registerListeners() {
  22644. this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22645. this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22646. };
  22647. _proto.unregisterListeners = function unregisterListeners() {
  22648. this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  22649. this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  22650. };
  22651. _proto.destroy = function destroy() {
  22652. if (this.timer) {
  22653. clearInterval(this.timer);
  22654. }
  22655. this.unregisterListeners();
  22656. this.isVideoPlaybackQualityAvailable = false;
  22657. this.media = null;
  22658. };
  22659. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  22660. var config = this.hls.config;
  22661. if (config.capLevelOnFPSDrop) {
  22662. var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
  22663. this.media = media;
  22664. if (media && typeof media.getVideoPlaybackQuality === 'function') {
  22665. this.isVideoPlaybackQualityAvailable = true;
  22666. }
  22667. self.clearInterval(this.timer);
  22668. this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  22669. }
  22670. };
  22671. _proto.onMediaDetaching = function onMediaDetaching() {
  22672. this.media = null;
  22673. };
  22674. _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
  22675. var currentTime = performance.now();
  22676. if (decodedFrames) {
  22677. if (this.lastTime) {
  22678. var currentPeriod = currentTime - this.lastTime;
  22679. var currentDropped = droppedFrames - this.lastDroppedFrames;
  22680. var currentDecoded = decodedFrames - this.lastDecodedFrames;
  22681. var droppedFPS = 1000 * currentDropped / currentPeriod;
  22682. var hls = this.hls;
  22683. hls.trigger(Events.FPS_DROP, {
  22684. currentDropped: currentDropped,
  22685. currentDecoded: currentDecoded,
  22686. totalDroppedFrames: droppedFrames
  22687. });
  22688. if (droppedFPS > 0) {
  22689. // hls.logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  22690. if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  22691. var currentLevel = hls.currentLevel;
  22692. hls.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  22693. if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
  22694. currentLevel = currentLevel - 1;
  22695. hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {
  22696. level: currentLevel,
  22697. droppedLevel: hls.currentLevel
  22698. });
  22699. hls.autoLevelCapping = currentLevel;
  22700. this.streamController.nextLevelSwitch();
  22701. }
  22702. }
  22703. }
  22704. }
  22705. this.lastTime = currentTime;
  22706. this.lastDroppedFrames = droppedFrames;
  22707. this.lastDecodedFrames = decodedFrames;
  22708. }
  22709. };
  22710. _proto.checkFPSInterval = function checkFPSInterval() {
  22711. var video = this.media;
  22712. if (video) {
  22713. if (this.isVideoPlaybackQualityAvailable) {
  22714. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  22715. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  22716. } else {
  22717. // HTMLVideoElement doesn't include the webkit types
  22718. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  22719. }
  22720. }
  22721. };
  22722. return FPSController;
  22723. }();
  22724. // From https://github.com/darkskyapp/string-hash
  22725. function hash(text) {
  22726. var hash = 5381;
  22727. var i = text.length;
  22728. while (i) {
  22729. hash = hash * 33 ^ text.charCodeAt(--i);
  22730. }
  22731. return (hash >>> 0).toString();
  22732. }
  22733. var ALIGNED_END_THRESHOLD_SECONDS = 0.025;
  22734. var TimelineOccupancy = /*#__PURE__*/function (TimelineOccupancy) {
  22735. TimelineOccupancy[TimelineOccupancy["Point"] = 0] = "Point";
  22736. TimelineOccupancy[TimelineOccupancy["Range"] = 1] = "Range";
  22737. return TimelineOccupancy;
  22738. }({});
  22739. function generateAssetIdentifier(interstitial, uri, assetListIndex) {
  22740. return interstitial.identifier + "-" + (assetListIndex + 1) + "-" + hash(uri);
  22741. }
  22742. var InterstitialEvent = /*#__PURE__*/function () {
  22743. function InterstitialEvent(dateRange, base) {
  22744. this.base = void 0;
  22745. this._duration = null;
  22746. this._timelineStart = null;
  22747. this.appendInPlaceDisabled = void 0;
  22748. this.appendInPlaceStarted = void 0;
  22749. this.dateRange = void 0;
  22750. this.hasPlayed = false;
  22751. this.cumulativeDuration = 0;
  22752. this.resumeOffset = NaN;
  22753. this.playoutLimit = NaN;
  22754. this.restrictions = {
  22755. skip: false,
  22756. jump: false
  22757. };
  22758. this.snapOptions = {
  22759. out: false,
  22760. in: false
  22761. };
  22762. this.assetList = [];
  22763. this.assetListLoader = void 0;
  22764. this.assetListResponse = null;
  22765. this.resumeAnchor = void 0;
  22766. this.error = void 0;
  22767. this.resetOnResume = void 0;
  22768. this.base = base;
  22769. this.dateRange = dateRange;
  22770. this.setDateRange(dateRange);
  22771. }
  22772. var _proto = InterstitialEvent.prototype;
  22773. _proto.setDateRange = function setDateRange(dateRange) {
  22774. this.dateRange = dateRange;
  22775. this.resumeOffset = dateRange.attr.optionalFloat('X-RESUME-OFFSET', this.resumeOffset);
  22776. this.playoutLimit = dateRange.attr.optionalFloat('X-PLAYOUT-LIMIT', this.playoutLimit);
  22777. this.restrictions = dateRange.attr.enumeratedStringList('X-RESTRICT', this.restrictions);
  22778. this.snapOptions = dateRange.attr.enumeratedStringList('X-SNAP', this.snapOptions);
  22779. };
  22780. _proto.reset = function reset() {
  22781. var _this$assetListLoader;
  22782. this.appendInPlaceStarted = false;
  22783. (_this$assetListLoader = this.assetListLoader) == null ? void 0 : _this$assetListLoader.destroy();
  22784. this.assetListLoader = undefined;
  22785. if (!this.supplementsPrimary) {
  22786. this.assetListResponse = null;
  22787. this.assetList = [];
  22788. this._duration = null;
  22789. }
  22790. // `error?` is reset when seeking back over interstitial `startOffset`
  22791. // using `schedule.resetErrorsInRange(start, end)`.
  22792. };
  22793. _proto.isAssetPastPlayoutLimit = function isAssetPastPlayoutLimit(assetIndex) {
  22794. var _this$assetList$asset;
  22795. if (assetIndex > 0 && assetIndex >= this.assetList.length) {
  22796. return true;
  22797. }
  22798. var playoutLimit = this.playoutLimit;
  22799. if (assetIndex <= 0 || isNaN(playoutLimit)) {
  22800. return false;
  22801. }
  22802. if (playoutLimit === 0) {
  22803. return true;
  22804. }
  22805. var assetOffset = ((_this$assetList$asset = this.assetList[assetIndex]) == null ? void 0 : _this$assetList$asset.startOffset) || 0;
  22806. return assetOffset > playoutLimit;
  22807. };
  22808. _proto.findAssetIndex = function findAssetIndex(asset) {
  22809. var index = this.assetList.indexOf(asset);
  22810. return index;
  22811. };
  22812. _proto.toString = function toString() {
  22813. return eventToString(this);
  22814. };
  22815. return _createClass(InterstitialEvent, [{
  22816. key: "identifier",
  22817. get: function get() {
  22818. return this.dateRange.id;
  22819. }
  22820. }, {
  22821. key: "startDate",
  22822. get: function get() {
  22823. return this.dateRange.startDate;
  22824. }
  22825. }, {
  22826. key: "startTime",
  22827. get: function get() {
  22828. // Primary media timeline start time
  22829. var startTime = this.dateRange.startTime;
  22830. if (this.snapOptions.out) {
  22831. var frag = this.dateRange.tagAnchor;
  22832. if (frag) {
  22833. return getSnapToFragmentTime(startTime, frag);
  22834. }
  22835. }
  22836. return startTime;
  22837. }
  22838. }, {
  22839. key: "startOffset",
  22840. get: function get() {
  22841. return this.cue.pre ? 0 : this.startTime;
  22842. }
  22843. }, {
  22844. key: "startIsAligned",
  22845. get: function get() {
  22846. if (this.startTime === 0 || this.snapOptions.out) {
  22847. return true;
  22848. }
  22849. var frag = this.dateRange.tagAnchor;
  22850. if (frag) {
  22851. var startTime = this.dateRange.startTime;
  22852. var snappedStart = getSnapToFragmentTime(startTime, frag);
  22853. return startTime - snappedStart < 0.1;
  22854. }
  22855. return false;
  22856. }
  22857. }, {
  22858. key: "resumptionOffset",
  22859. get: function get() {
  22860. var resumeOffset = this.resumeOffset;
  22861. var offset = isFiniteNumber(resumeOffset) ? resumeOffset : this.duration;
  22862. return this.cumulativeDuration + offset;
  22863. }
  22864. }, {
  22865. key: "resumeTime",
  22866. get: function get() {
  22867. // Primary media timeline resumption time
  22868. var resumeTime = this.startOffset + this.resumptionOffset;
  22869. if (this.snapOptions.in) {
  22870. var frag = this.resumeAnchor;
  22871. if (frag) {
  22872. return getSnapToFragmentTime(resumeTime, frag);
  22873. }
  22874. }
  22875. return resumeTime;
  22876. }
  22877. }, {
  22878. key: "appendInPlace",
  22879. get: function get() {
  22880. if (this.appendInPlaceStarted) {
  22881. return true;
  22882. }
  22883. if (this.appendInPlaceDisabled) {
  22884. return false;
  22885. }
  22886. if (!this.cue.once && !this.cue.pre &&
  22887. // preroll starts at startPosition before startPosition is known (live)
  22888. this.startIsAligned && (isNaN(this.playoutLimit) && isNaN(this.resumeOffset) || this.resumeOffset && this.duration && Math.abs(this.resumeOffset - this.duration) < ALIGNED_END_THRESHOLD_SECONDS)) {
  22889. return true;
  22890. }
  22891. return false;
  22892. },
  22893. set: function set(value) {
  22894. if (this.appendInPlaceStarted) {
  22895. this.resetOnResume = !value;
  22896. return;
  22897. }
  22898. this.appendInPlaceDisabled = !value;
  22899. }
  22900. // Extended timeline start time
  22901. }, {
  22902. key: "timelineStart",
  22903. get: function get() {
  22904. if (this._timelineStart !== null) {
  22905. return this._timelineStart;
  22906. }
  22907. return this.startTime;
  22908. },
  22909. set: function set(value) {
  22910. this._timelineStart = value;
  22911. }
  22912. }, {
  22913. key: "duration",
  22914. get: function get() {
  22915. var playoutLimit = this.playoutLimit;
  22916. var duration;
  22917. if (this._duration !== null) {
  22918. duration = this._duration;
  22919. } else if (this.dateRange.duration) {
  22920. duration = this.dateRange.duration;
  22921. } else {
  22922. duration = this.dateRange.plannedDuration || 0;
  22923. }
  22924. if (!isNaN(playoutLimit) && playoutLimit < duration) {
  22925. duration = playoutLimit;
  22926. }
  22927. return duration;
  22928. },
  22929. set: function set(value) {
  22930. this._duration = value;
  22931. }
  22932. }, {
  22933. key: "cue",
  22934. get: function get() {
  22935. return this.dateRange.cue;
  22936. }
  22937. }, {
  22938. key: "timelineOccupancy",
  22939. get: function get() {
  22940. if (this.dateRange.attr['X-TIMELINE-OCCUPIES'] === 'RANGE') {
  22941. return TimelineOccupancy.Range;
  22942. }
  22943. return TimelineOccupancy.Point;
  22944. }
  22945. }, {
  22946. key: "supplementsPrimary",
  22947. get: function get() {
  22948. return this.dateRange.attr['X-TIMELINE-STYLE'] === 'PRIMARY';
  22949. }
  22950. }, {
  22951. key: "contentMayVary",
  22952. get: function get() {
  22953. return this.dateRange.attr['X-CONTENT-MAY-VARY'] !== 'NO';
  22954. }
  22955. }, {
  22956. key: "assetUrl",
  22957. get: function get() {
  22958. return this.dateRange.attr['X-ASSET-URI'];
  22959. }
  22960. }, {
  22961. key: "assetListUrl",
  22962. get: function get() {
  22963. return this.dateRange.attr['X-ASSET-LIST'];
  22964. }
  22965. }, {
  22966. key: "baseUrl",
  22967. get: function get() {
  22968. return this.base.url;
  22969. }
  22970. }, {
  22971. key: "assetListLoaded",
  22972. get: function get() {
  22973. return this.assetList.length > 0 || this.assetListResponse !== null;
  22974. }
  22975. }]);
  22976. }();
  22977. function getSnapToFragmentTime(time, frag) {
  22978. return time - frag.start < frag.duration / 2 && !(Math.abs(time - (frag.start + frag.duration)) < ALIGNED_END_THRESHOLD_SECONDS) ? frag.start : frag.start + frag.duration;
  22979. }
  22980. function getInterstitialUrl(uri, sessionId, baseUrl) {
  22981. var url = new self.URL(uri, baseUrl);
  22982. if (url.protocol !== 'data:') {
  22983. url.searchParams.set('_HLS_primary_id', sessionId);
  22984. }
  22985. return url;
  22986. }
  22987. function getNextAssetIndex(interstitial, assetListIndex) {
  22988. while ((_interstitial$assetLi = interstitial.assetList[++assetListIndex]) != null && _interstitial$assetLi.error) {
  22989. var _interstitial$assetLi;
  22990. } /* no-op */
  22991. return assetListIndex;
  22992. }
  22993. function eventToString(interstitial) {
  22994. return "[\"" + interstitial.identifier + "\" " + (interstitial.cue.pre ? '<pre>' : interstitial.cue.post ? '<post>' : '') + interstitial.timelineStart.toFixed(2) + "-" + interstitial.resumeTime.toFixed(2) + "]";
  22995. }
  22996. function eventAssetToString(asset) {
  22997. var start = asset.timelineStart;
  22998. var duration = asset.duration || 0;
  22999. return "[\"" + asset.identifier + "\" " + start.toFixed(2) + "-" + (start + duration).toFixed(2) + "]";
  23000. }
  23001. var HlsAssetPlayer = /*#__PURE__*/function () {
  23002. function HlsAssetPlayer(HlsPlayerClass, userConfig, interstitial, assetItem) {
  23003. var _this = this;
  23004. this.hls = void 0;
  23005. this.interstitial = void 0;
  23006. this.assetItem = void 0;
  23007. this.tracks = null;
  23008. this.hasDetails = false;
  23009. this.mediaAttached = null;
  23010. this._currentTime = void 0;
  23011. this._bufferedEosTime = void 0;
  23012. this.checkPlayout = function () {
  23013. if (_this.reachedPlayout(_this.currentTime)) {
  23014. _this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED, {});
  23015. }
  23016. };
  23017. var hls = this.hls = new HlsPlayerClass(userConfig);
  23018. this.interstitial = interstitial;
  23019. this.assetItem = assetItem;
  23020. var uri = assetItem.uri;
  23021. try {
  23022. uri = getInterstitialUrl(uri, userConfig.primarySessionId).href;
  23023. } catch (error) {
  23024. // Ignore error parsing ASSET_URI or adding _HLS_primary_id to it. The
  23025. // issue should surface as an INTERSTITIAL_ASSET_ERROR loading the asset.
  23026. }
  23027. hls.loadSource(uri);
  23028. var detailsLoaded = function detailsLoaded() {
  23029. _this.hasDetails = true;
  23030. };
  23031. hls.once(Events.LEVEL_LOADED, detailsLoaded);
  23032. hls.once(Events.AUDIO_TRACK_LOADED, detailsLoaded);
  23033. hls.once(Events.SUBTITLE_TRACK_LOADED, detailsLoaded);
  23034. hls.on(Events.MEDIA_ATTACHING, function (name, _ref) {
  23035. var media = _ref.media;
  23036. _this.removeMediaListeners();
  23037. _this.mediaAttached = media;
  23038. var event = _this.interstitial;
  23039. if (event.playoutLimit) {
  23040. media.addEventListener('timeupdate', _this.checkPlayout);
  23041. if (_this.appendInPlace) {
  23042. hls.on(Events.BUFFER_APPENDED, function () {
  23043. var bufferedEnd = _this.bufferedEnd;
  23044. if (_this.reachedPlayout(bufferedEnd)) {
  23045. _this._bufferedEosTime = bufferedEnd;
  23046. hls.trigger(Events.BUFFERED_TO_END, undefined);
  23047. }
  23048. });
  23049. }
  23050. }
  23051. });
  23052. }
  23053. var _proto = HlsAssetPlayer.prototype;
  23054. _proto.bufferedInPlaceToEnd = function bufferedInPlaceToEnd(media) {
  23055. var _this$hls;
  23056. if (!this.appendInPlace) {
  23057. return false;
  23058. }
  23059. if ((_this$hls = this.hls) != null && _this$hls.bufferedToEnd) {
  23060. return true;
  23061. }
  23062. if (!media || !this._bufferedEosTime) {
  23063. return false;
  23064. }
  23065. var start = this.timelineOffset;
  23066. var bufferInfo = BufferHelper.bufferInfo(media, start, 0);
  23067. var bufferedEnd = this.getAssetTime(bufferInfo.end);
  23068. return bufferedEnd >= this._bufferedEosTime - 0.02;
  23069. };
  23070. _proto.reachedPlayout = function reachedPlayout(time) {
  23071. var interstitial = this.interstitial;
  23072. var playoutLimit = interstitial.playoutLimit;
  23073. return this.startOffset + time >= playoutLimit;
  23074. };
  23075. _proto.getAssetTime = function getAssetTime(time) {
  23076. var timelineOffset = this.timelineOffset;
  23077. var duration = this.duration;
  23078. return Math.min(Math.max(0, time - timelineOffset), duration);
  23079. };
  23080. _proto.removeMediaListeners = function removeMediaListeners() {
  23081. var media = this.mediaAttached;
  23082. if (media) {
  23083. this._currentTime = media.currentTime;
  23084. this.bufferSnapShot();
  23085. media.removeEventListener('timeupdate', this.checkPlayout);
  23086. }
  23087. };
  23088. _proto.bufferSnapShot = function bufferSnapShot() {
  23089. if (this.mediaAttached) {
  23090. var _this$hls2;
  23091. if ((_this$hls2 = this.hls) != null && _this$hls2.bufferedToEnd) {
  23092. this._bufferedEosTime = this.bufferedEnd;
  23093. }
  23094. }
  23095. };
  23096. _proto.destroy = function destroy() {
  23097. this.removeMediaListeners();
  23098. this.hls.destroy();
  23099. // @ts-ignore
  23100. this.hls = this.interstitial = null;
  23101. // @ts-ignore
  23102. this.tracks = this.mediaAttached = this.checkPlayout = null;
  23103. };
  23104. _proto.attachMedia = function attachMedia(data) {
  23105. this.hls.attachMedia(data);
  23106. };
  23107. _proto.detachMedia = function detachMedia() {
  23108. this.removeMediaListeners();
  23109. this.mediaAttached = null;
  23110. this.hls.detachMedia();
  23111. };
  23112. _proto.resumeBuffering = function resumeBuffering() {
  23113. this.hls.resumeBuffering();
  23114. };
  23115. _proto.pauseBuffering = function pauseBuffering() {
  23116. this.hls.pauseBuffering();
  23117. };
  23118. _proto.transferMedia = function transferMedia() {
  23119. this.bufferSnapShot();
  23120. return this.hls.transferMedia();
  23121. };
  23122. _proto.resetDetails = function resetDetails() {
  23123. var hls = this.hls;
  23124. if (this.hasDetails) {
  23125. hls.stopLoad();
  23126. var deleteDetails = function deleteDetails(obj) {
  23127. return delete obj.details;
  23128. };
  23129. hls.levels.forEach(deleteDetails);
  23130. hls.allAudioTracks.forEach(deleteDetails);
  23131. hls.allSubtitleTracks.forEach(deleteDetails);
  23132. this.hasDetails = false;
  23133. }
  23134. };
  23135. _proto.on = function on(event, listener, context) {
  23136. this.hls.on(event, listener);
  23137. };
  23138. _proto.once = function once(event, listener, context) {
  23139. this.hls.once(event, listener);
  23140. };
  23141. _proto.off = function off(event, listener, context) {
  23142. this.hls.off(event, listener);
  23143. };
  23144. _proto.toString = function toString() {
  23145. var _this$hls3;
  23146. return "HlsAssetPlayer: " + eventAssetToString(this.assetItem) + " " + ((_this$hls3 = this.hls) == null ? void 0 : _this$hls3.sessionId) + " " + (this.appendInPlace ? 'append-in-place' : '');
  23147. };
  23148. return _createClass(HlsAssetPlayer, [{
  23149. key: "appendInPlace",
  23150. get: function get() {
  23151. var _this$interstitial;
  23152. return ((_this$interstitial = this.interstitial) == null ? void 0 : _this$interstitial.appendInPlace) || false;
  23153. }
  23154. }, {
  23155. key: "destroyed",
  23156. get: function get() {
  23157. var _this$hls4;
  23158. return !((_this$hls4 = this.hls) != null && _this$hls4.userConfig);
  23159. }
  23160. }, {
  23161. key: "assetId",
  23162. get: function get() {
  23163. return this.assetItem.identifier;
  23164. }
  23165. }, {
  23166. key: "interstitialId",
  23167. get: function get() {
  23168. return this.assetItem.parentIdentifier;
  23169. }
  23170. }, {
  23171. key: "media",
  23172. get: function get() {
  23173. var _this$hls5;
  23174. return ((_this$hls5 = this.hls) == null ? void 0 : _this$hls5.media) || null;
  23175. }
  23176. }, {
  23177. key: "bufferedEnd",
  23178. get: function get() {
  23179. var media = this.media || this.mediaAttached;
  23180. if (!media) {
  23181. if (this._bufferedEosTime) {
  23182. return this._bufferedEosTime;
  23183. }
  23184. return this.currentTime;
  23185. }
  23186. var bufferInfo = BufferHelper.bufferInfo(media, media.currentTime, 0.001);
  23187. return this.getAssetTime(bufferInfo.end);
  23188. }
  23189. }, {
  23190. key: "currentTime",
  23191. get: function get() {
  23192. var media = this.media || this.mediaAttached;
  23193. if (!media) {
  23194. return this._currentTime || 0;
  23195. }
  23196. return this.getAssetTime(media.currentTime);
  23197. }
  23198. }, {
  23199. key: "duration",
  23200. get: function get() {
  23201. var duration = this.assetItem.duration;
  23202. if (!duration) {
  23203. return 0;
  23204. }
  23205. return duration;
  23206. }
  23207. }, {
  23208. key: "remaining",
  23209. get: function get() {
  23210. var duration = this.duration;
  23211. if (!duration) {
  23212. return 0;
  23213. }
  23214. return Math.max(0, duration - this.currentTime);
  23215. }
  23216. }, {
  23217. key: "startOffset",
  23218. get: function get() {
  23219. return this.assetItem.startOffset;
  23220. }
  23221. }, {
  23222. key: "timelineOffset",
  23223. get: function get() {
  23224. var _this$hls6;
  23225. return ((_this$hls6 = this.hls) == null ? void 0 : _this$hls6.config.timelineOffset) || 0;
  23226. },
  23227. set: function set(value) {
  23228. var timelineOffset = this.timelineOffset;
  23229. if (value !== timelineOffset) {
  23230. var diff = value - timelineOffset;
  23231. if (Math.abs(diff) > 1 / 90000) {
  23232. if (this.hasDetails) {
  23233. throw new Error("Cannot set timelineOffset after playlists are loaded");
  23234. }
  23235. this.hls.config.timelineOffset = value;
  23236. }
  23237. }
  23238. }
  23239. }]);
  23240. }();
  23241. var ABUTTING_THRESHOLD_SECONDS = 0.033;
  23242. var InterstitialsSchedule = /*#__PURE__*/function (_Logger) {
  23243. function InterstitialsSchedule(onScheduleUpdate, logger) {
  23244. var _this;
  23245. _this = _Logger.call(this, 'interstitials-sched', logger) || this;
  23246. _this.onScheduleUpdate = void 0;
  23247. _this.eventMap = {};
  23248. _this.events = null;
  23249. _this.items = null;
  23250. _this.durations = {
  23251. primary: 0,
  23252. playout: 0,
  23253. integrated: 0
  23254. };
  23255. _this.onScheduleUpdate = onScheduleUpdate;
  23256. return _this;
  23257. }
  23258. _inheritsLoose(InterstitialsSchedule, _Logger);
  23259. var _proto = InterstitialsSchedule.prototype;
  23260. _proto.destroy = function destroy() {
  23261. this.reset();
  23262. // @ts-ignore
  23263. this.onScheduleUpdate = null;
  23264. };
  23265. _proto.reset = function reset() {
  23266. this.eventMap = {};
  23267. this.setDurations(0, 0, 0);
  23268. if (this.events) {
  23269. this.events.forEach(function (interstitial) {
  23270. return interstitial.reset();
  23271. });
  23272. }
  23273. this.events = this.items = null;
  23274. };
  23275. _proto.resetErrorsInRange = function resetErrorsInRange(start, end) {
  23276. if (this.events) {
  23277. return this.events.reduce(function (count, interstitial) {
  23278. if (start <= interstitial.startOffset && end > interstitial.startOffset) {
  23279. delete interstitial.error;
  23280. return count + 1;
  23281. }
  23282. return count;
  23283. }, 0);
  23284. }
  23285. return 0;
  23286. };
  23287. _proto.getEvent = function getEvent(identifier) {
  23288. return identifier ? this.eventMap[identifier] || null : null;
  23289. };
  23290. _proto.hasEvent = function hasEvent(identifier) {
  23291. return identifier in this.eventMap;
  23292. };
  23293. _proto.findItemIndex = function findItemIndex(item, time) {
  23294. if (item.event) {
  23295. // Find Event Item
  23296. return this.findEventIndex(item.event.identifier);
  23297. }
  23298. // Find Primary Item
  23299. var index = -1;
  23300. if (item.nextEvent) {
  23301. index = this.findEventIndex(item.nextEvent.identifier) - 1;
  23302. } else if (item.previousEvent) {
  23303. index = this.findEventIndex(item.previousEvent.identifier) + 1;
  23304. }
  23305. var items = this.items;
  23306. if (items) {
  23307. if (!items[index]) {
  23308. if (time === undefined) {
  23309. time = item.start;
  23310. }
  23311. index = this.findItemIndexAtTime(time);
  23312. }
  23313. // Only return index of a Primary Item
  23314. while (index >= 0 && (_items$index = items[index]) != null && _items$index.event) {
  23315. var _items$index;
  23316. // If index found is an interstitial it is not a valid result as it should have been matched up top
  23317. // decrement until result is negative (not found) or a primary segment
  23318. index--;
  23319. }
  23320. }
  23321. return index;
  23322. };
  23323. _proto.findItemIndexAtTime = function findItemIndexAtTime(timelinePos, timelineType) {
  23324. var items = this.items;
  23325. if (items) {
  23326. for (var i = 0; i < items.length; i++) {
  23327. var timeRange = items[i];
  23328. if (timelineType && timelineType !== 'primary') {
  23329. timeRange = timeRange[timelineType];
  23330. }
  23331. if (timelinePos === timeRange.start || timelinePos > timeRange.start && timelinePos < timeRange.end) {
  23332. return i;
  23333. }
  23334. }
  23335. }
  23336. return -1;
  23337. };
  23338. _proto.findJumpRestrictedIndex = function findJumpRestrictedIndex(startIndex, endIndex) {
  23339. var items = this.items;
  23340. if (items) {
  23341. for (var i = startIndex; i <= endIndex; i++) {
  23342. if (!items[i]) {
  23343. break;
  23344. }
  23345. var event = items[i].event;
  23346. if (event != null && event.restrictions.jump && !event.appendInPlace) {
  23347. return i;
  23348. }
  23349. }
  23350. }
  23351. return -1;
  23352. };
  23353. _proto.findEventIndex = function findEventIndex(identifier) {
  23354. var items = this.items;
  23355. if (items) {
  23356. for (var i = items.length; i--;) {
  23357. var _items$i$event;
  23358. if (((_items$i$event = items[i].event) == null ? void 0 : _items$i$event.identifier) === identifier) {
  23359. return i;
  23360. }
  23361. }
  23362. }
  23363. return -1;
  23364. };
  23365. _proto.findAssetIndex = function findAssetIndex(event, timelinePos) {
  23366. var assetList = event.assetList;
  23367. var length = assetList.length;
  23368. if (length > 1) {
  23369. for (var i = 0; i < length; i++) {
  23370. var asset = assetList[i];
  23371. if (!asset.error) {
  23372. var timelineStart = asset.timelineStart;
  23373. if (timelinePos === timelineStart || timelinePos > timelineStart && timelinePos < timelineStart + (asset.duration || 0)) {
  23374. return i;
  23375. }
  23376. }
  23377. }
  23378. }
  23379. return 0;
  23380. };
  23381. _proto.parseInterstitialDateRanges = function parseInterstitialDateRanges(mediaSelection, enableAppendInPlace) {
  23382. var _this2 = this;
  23383. var details = mediaSelection.main.details;
  23384. var dateRanges = details.dateRanges;
  23385. var previousInterstitialEvents = this.events;
  23386. var interstitialEvents = this.parseDateRanges(dateRanges, {
  23387. url: details.url
  23388. }, enableAppendInPlace);
  23389. var ids = Object.keys(dateRanges);
  23390. var removedInterstitials = previousInterstitialEvents ? previousInterstitialEvents.filter(function (event) {
  23391. return !ids.includes(event.identifier);
  23392. }) : [];
  23393. if (interstitialEvents.length) {
  23394. // pre-rolls, post-rolls, and events with the same start time are played in playlist tag order
  23395. // all other events are ordered by start time
  23396. interstitialEvents.sort(function (a, b) {
  23397. var aPre = a.cue.pre;
  23398. var aPost = a.cue.post;
  23399. var bPre = b.cue.pre;
  23400. var bPost = b.cue.post;
  23401. if (aPre && !bPre) {
  23402. return -1;
  23403. }
  23404. if (bPre && !aPre) {
  23405. return 1;
  23406. }
  23407. if (aPost && !bPost) {
  23408. return 1;
  23409. }
  23410. if (bPost && !aPost) {
  23411. return -1;
  23412. }
  23413. if (!aPre && !bPre && !aPost && !bPost) {
  23414. var startA = a.startTime;
  23415. var startB = b.startTime;
  23416. if (startA !== startB) {
  23417. return startA - startB;
  23418. }
  23419. }
  23420. return a.dateRange.tagOrder - b.dateRange.tagOrder;
  23421. });
  23422. }
  23423. this.events = interstitialEvents;
  23424. // Clear removed DateRanges from buffered list (kills playback of active Interstitials)
  23425. removedInterstitials.forEach(function (interstitial) {
  23426. _this2.removeEvent(interstitial);
  23427. });
  23428. this.updateSchedule(mediaSelection, removedInterstitials);
  23429. };
  23430. _proto.updateSchedule = function updateSchedule(mediaSelection, removedInterstitials) {
  23431. if (removedInterstitials === void 0) {
  23432. removedInterstitials = [];
  23433. }
  23434. var events = this.events || [];
  23435. if (events.length || removedInterstitials.length || this.length < 2) {
  23436. var currentItems = this.items;
  23437. var updatedItems = this.parseSchedule(events, mediaSelection);
  23438. var updated = removedInterstitials.length || (currentItems == null ? void 0 : currentItems.length) !== updatedItems.length || updatedItems.some(function (item, i) {
  23439. return Math.abs(item.playout.start - currentItems[i].playout.start) > 0.005 || Math.abs(item.playout.end - currentItems[i].playout.end) > 0.005;
  23440. });
  23441. if (updated) {
  23442. this.items = updatedItems;
  23443. // call interstitials-controller onScheduleUpdated()
  23444. this.onScheduleUpdate(removedInterstitials, currentItems);
  23445. }
  23446. }
  23447. };
  23448. _proto.parseDateRanges = function parseDateRanges(dateRanges, baseData, enableAppendInPlace) {
  23449. var interstitialEvents = [];
  23450. var ids = Object.keys(dateRanges);
  23451. for (var i = 0; i < ids.length; i++) {
  23452. var id = ids[i];
  23453. var dateRange = dateRanges[id];
  23454. if (dateRange.isInterstitial) {
  23455. var interstitial = this.eventMap[id];
  23456. if (interstitial) {
  23457. // Update InterstitialEvent already parsed and mapped
  23458. // This retains already loaded duration and loaded asset list info
  23459. interstitial.setDateRange(dateRange);
  23460. } else {
  23461. interstitial = new InterstitialEvent(dateRange, baseData);
  23462. this.eventMap[id] = interstitial;
  23463. if (enableAppendInPlace === false) {
  23464. interstitial.appendInPlace = enableAppendInPlace;
  23465. }
  23466. }
  23467. interstitialEvents.push(interstitial);
  23468. }
  23469. }
  23470. return interstitialEvents;
  23471. };
  23472. _proto.parseSchedule = function parseSchedule(interstitialEvents, mediaSelection) {
  23473. var schedule = [];
  23474. var details = mediaSelection.main.details;
  23475. var primaryDuration = details.live ? Infinity : details.edge;
  23476. var playoutDuration = 0;
  23477. // Filter events that have errored from the schedule (Primary fallback)
  23478. interstitialEvents = interstitialEvents.filter(function (event) {
  23479. return !event.error && !(event.cue.once && event.hasPlayed);
  23480. });
  23481. if (interstitialEvents.length) {
  23482. // Update Schedule
  23483. this.resolveOffsets(interstitialEvents, mediaSelection);
  23484. // Populate Schedule with Interstitial Event and Primary Segment Items
  23485. var primaryPosition = 0;
  23486. var integratedTime = 0;
  23487. interstitialEvents.forEach(function (interstitial, i) {
  23488. var preroll = interstitial.cue.pre;
  23489. var postroll = interstitial.cue.post;
  23490. var previousEvent = interstitialEvents[i - 1] || null;
  23491. var appendInPlace = interstitial.appendInPlace;
  23492. var eventStart = postroll ? primaryDuration : interstitial.startOffset;
  23493. var interstitialDuration = interstitial.duration;
  23494. var timelineDuration = interstitial.timelineOccupancy === TimelineOccupancy.Range ? interstitialDuration : 0;
  23495. var resumptionOffset = interstitial.resumptionOffset;
  23496. var inSameStartTimeSequence = (previousEvent == null ? void 0 : previousEvent.startTime) === eventStart;
  23497. var start = eventStart + interstitial.cumulativeDuration;
  23498. var end = appendInPlace ? start + interstitialDuration : eventStart + resumptionOffset;
  23499. if (preroll || !postroll && eventStart <= 0) {
  23500. // preroll or in-progress midroll
  23501. var integratedStart = integratedTime;
  23502. integratedTime += timelineDuration;
  23503. interstitial.timelineStart = start;
  23504. var playoutStart = playoutDuration;
  23505. playoutDuration += interstitialDuration;
  23506. schedule.push({
  23507. event: interstitial,
  23508. start: start,
  23509. end: end,
  23510. playout: {
  23511. start: playoutStart,
  23512. end: playoutDuration
  23513. },
  23514. integrated: {
  23515. start: integratedStart,
  23516. end: integratedTime
  23517. }
  23518. });
  23519. } else if (eventStart <= primaryDuration) {
  23520. if (!inSameStartTimeSequence) {
  23521. var segmentDuration = eventStart - primaryPosition;
  23522. // Do not schedule a primary segment if interstitials are abutting by less than ABUTTING_THRESHOLD_SECONDS
  23523. if (segmentDuration > ABUTTING_THRESHOLD_SECONDS) {
  23524. // primary segment
  23525. var timelineStart = primaryPosition;
  23526. var _integratedStart = integratedTime;
  23527. integratedTime += segmentDuration;
  23528. var _playoutStart = playoutDuration;
  23529. playoutDuration += segmentDuration;
  23530. var primarySegment = {
  23531. previousEvent: interstitialEvents[i - 1] || null,
  23532. nextEvent: interstitial,
  23533. start: timelineStart,
  23534. end: timelineStart + segmentDuration,
  23535. playout: {
  23536. start: _playoutStart,
  23537. end: playoutDuration
  23538. },
  23539. integrated: {
  23540. start: _integratedStart,
  23541. end: integratedTime
  23542. }
  23543. };
  23544. schedule.push(primarySegment);
  23545. } else if (segmentDuration > 0 && previousEvent) {
  23546. // Add previous event `resumeTime` (based on duration or resumeOffset) so that it ends aligned with this one
  23547. previousEvent.cumulativeDuration += segmentDuration;
  23548. schedule[schedule.length - 1].end = eventStart;
  23549. }
  23550. }
  23551. // midroll / postroll
  23552. if (postroll) {
  23553. end = start;
  23554. }
  23555. interstitial.timelineStart = start;
  23556. var _integratedStart2 = integratedTime;
  23557. integratedTime += timelineDuration;
  23558. var _playoutStart2 = playoutDuration;
  23559. playoutDuration += interstitialDuration;
  23560. schedule.push({
  23561. event: interstitial,
  23562. start: start,
  23563. end: end,
  23564. playout: {
  23565. start: _playoutStart2,
  23566. end: playoutDuration
  23567. },
  23568. integrated: {
  23569. start: _integratedStart2,
  23570. end: integratedTime
  23571. }
  23572. });
  23573. } else {
  23574. // Interstitial starts after end of primary VOD - not included in schedule
  23575. return;
  23576. }
  23577. var resumeTime = interstitial.resumeTime;
  23578. if (postroll || resumeTime > primaryDuration) {
  23579. primaryPosition = primaryDuration;
  23580. } else {
  23581. primaryPosition = resumeTime;
  23582. }
  23583. });
  23584. if (primaryPosition < primaryDuration) {
  23585. var _schedule;
  23586. // last primary segment
  23587. var timelineStart = primaryPosition;
  23588. var integratedStart = integratedTime;
  23589. var segmentDuration = primaryDuration - primaryPosition;
  23590. integratedTime += segmentDuration;
  23591. var playoutStart = playoutDuration;
  23592. playoutDuration += segmentDuration;
  23593. schedule.push({
  23594. previousEvent: ((_schedule = schedule[schedule.length - 1]) == null ? void 0 : _schedule.event) || null,
  23595. nextEvent: null,
  23596. start: primaryPosition,
  23597. end: timelineStart + segmentDuration,
  23598. playout: {
  23599. start: playoutStart,
  23600. end: playoutDuration
  23601. },
  23602. integrated: {
  23603. start: integratedStart,
  23604. end: integratedTime
  23605. }
  23606. });
  23607. }
  23608. this.setDurations(primaryDuration, playoutDuration, integratedTime);
  23609. } else {
  23610. // no interstials - schedule is one primary segment
  23611. var start = 0;
  23612. schedule.push({
  23613. previousEvent: null,
  23614. nextEvent: null,
  23615. start: start,
  23616. end: primaryDuration,
  23617. playout: {
  23618. start: start,
  23619. end: primaryDuration
  23620. },
  23621. integrated: {
  23622. start: start,
  23623. end: primaryDuration
  23624. }
  23625. });
  23626. this.setDurations(primaryDuration, primaryDuration, primaryDuration);
  23627. }
  23628. return schedule;
  23629. };
  23630. _proto.setDurations = function setDurations(primary, playout, integrated) {
  23631. this.durations = {
  23632. primary: primary,
  23633. playout: playout,
  23634. integrated: integrated
  23635. };
  23636. };
  23637. _proto.resolveOffsets = function resolveOffsets(interstitialEvents, mediaSelection) {
  23638. var _this3 = this;
  23639. var details = mediaSelection.main.details;
  23640. var primaryDuration = details.live ? Infinity : details.edge;
  23641. // First resolve cumulative resumption offsets for Interstitials that start at the same DateTime
  23642. var cumulativeDuration = 0;
  23643. var lastScheduledStart = -1;
  23644. interstitialEvents.forEach(function (interstitial, i) {
  23645. var preroll = interstitial.cue.pre;
  23646. var postroll = interstitial.cue.post;
  23647. var eventStart = preroll ? 0 : postroll ? primaryDuration : interstitial.startTime;
  23648. _this3.updateAssetDurations(interstitial);
  23649. // X-RESUME-OFFSET values of interstitials scheduled at the same time are cumulative
  23650. var inSameStartTimeSequence = lastScheduledStart === eventStart;
  23651. if (inSameStartTimeSequence) {
  23652. interstitial.cumulativeDuration = cumulativeDuration;
  23653. } else {
  23654. cumulativeDuration = 0;
  23655. lastScheduledStart = eventStart;
  23656. }
  23657. if (!postroll && interstitial.snapOptions.in) {
  23658. // FIXME: Include audio playlist in snapping
  23659. interstitial.resumeAnchor = findFragmentByPTS(null, details.fragments, interstitial.startOffset + interstitial.resumptionOffset, 0, 0) || undefined;
  23660. }
  23661. // Check if primary fragments align with resumption offset and disable appendInPlace if they do not
  23662. if (interstitial.appendInPlace && !interstitial.appendInPlaceStarted) {
  23663. var alignedSegmentStart = _this3.primaryCanResumeInPlaceAt(interstitial, mediaSelection);
  23664. if (!alignedSegmentStart) {
  23665. interstitial.appendInPlace = false;
  23666. }
  23667. }
  23668. if (!interstitial.appendInPlace && i + 1 < interstitialEvents.length) {
  23669. // abutting Interstitials must use the same MediaSource strategy, this applies to all whether or not they are back to back:
  23670. var timeBetween = interstitialEvents[i + 1].startTime - interstitialEvents[i].resumeTime;
  23671. if (timeBetween < ABUTTING_THRESHOLD_SECONDS) {
  23672. interstitialEvents[i + 1].appendInPlace = false;
  23673. if (interstitialEvents[i + 1].appendInPlace) {
  23674. _this3.warn("Could not change append strategy for abutting event " + interstitial);
  23675. }
  23676. }
  23677. }
  23678. // Update cumulativeDuration for next abutting interstitial with the same start date
  23679. var resumeOffset = isFiniteNumber(interstitial.resumeOffset) ? interstitial.resumeOffset : interstitial.duration;
  23680. cumulativeDuration += resumeOffset;
  23681. });
  23682. };
  23683. _proto.primaryCanResumeInPlaceAt = function primaryCanResumeInPlaceAt(interstitial, mediaSelection) {
  23684. var _this4 = this;
  23685. var resumeTime = interstitial.resumeTime;
  23686. var resumesInPlaceAt = interstitial.startTime + interstitial.resumptionOffset;
  23687. if (Math.abs(resumeTime - resumesInPlaceAt) > ALIGNED_END_THRESHOLD_SECONDS) {
  23688. this.log("\"" + interstitial.identifier + "\" resumption " + resumeTime + " not aligned with estimated timeline end " + resumesInPlaceAt);
  23689. return false;
  23690. }
  23691. if (!mediaSelection) {
  23692. this.log("\"" + interstitial.identifier + "\" resumption " + resumeTime + " can not be aligned with media (none selected)");
  23693. return false;
  23694. }
  23695. var playlists = Object.keys(mediaSelection);
  23696. return !playlists.some(function (playlistType) {
  23697. var details = mediaSelection[playlistType].details;
  23698. var playlistEnd = details.edge;
  23699. if (resumeTime >= playlistEnd) {
  23700. // Live playback - resumption segments are not yet available
  23701. _this4.log("\"" + interstitial.identifier + "\" resumption " + resumeTime + " past " + playlistType + " playlist end " + playlistEnd);
  23702. // Assume alignment is possible (or reset can take place)
  23703. return false;
  23704. }
  23705. var startFragment = findFragmentByPTS(null, details.fragments, resumeTime);
  23706. if (!startFragment) {
  23707. _this4.log("\"" + interstitial.identifier + "\" resumption " + resumeTime + " does not align with any fragments in " + playlistType + " playlist (" + details.fragStart + "-" + details.fragmentEnd + ")");
  23708. return true;
  23709. }
  23710. var allowance = playlistType === 'audio' ? 0.175 : 0;
  23711. var alignedWithSegment = Math.abs(startFragment.start - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance || Math.abs(startFragment.end - resumeTime) < ALIGNED_END_THRESHOLD_SECONDS + allowance;
  23712. if (!alignedWithSegment) {
  23713. _this4.log("\"" + interstitial.identifier + "\" resumption " + resumeTime + " not aligned with " + playlistType + " fragment bounds (" + startFragment.start + "-" + startFragment.end + " sn: " + startFragment.sn + " cc: " + startFragment.cc + ")");
  23714. return true;
  23715. }
  23716. return false;
  23717. });
  23718. };
  23719. _proto.updateAssetDurations = function updateAssetDurations(interstitial) {
  23720. if (!interstitial.assetListLoaded) {
  23721. return;
  23722. }
  23723. var eventStart = interstitial.timelineStart;
  23724. var sumDuration = 0;
  23725. var hasUnknownDuration = false;
  23726. var hasErrors = false;
  23727. interstitial.assetList.forEach(function (asset, i) {
  23728. var timelineStart = eventStart + sumDuration;
  23729. asset.startOffset = sumDuration;
  23730. asset.timelineStart = timelineStart;
  23731. hasUnknownDuration || (hasUnknownDuration = asset.duration === null);
  23732. hasErrors || (hasErrors = !!asset.error);
  23733. var duration = asset.error ? 0 : asset.duration || 0;
  23734. sumDuration += duration;
  23735. });
  23736. // Use the sum of known durations when it is greater than the stated duration
  23737. if (hasUnknownDuration && !hasErrors) {
  23738. interstitial.duration = Math.max(sumDuration, interstitial.duration);
  23739. } else {
  23740. interstitial.duration = sumDuration;
  23741. }
  23742. };
  23743. _proto.removeEvent = function removeEvent(interstitial) {
  23744. interstitial.reset();
  23745. delete this.eventMap[interstitial.identifier];
  23746. };
  23747. return _createClass(InterstitialsSchedule, [{
  23748. key: "duration",
  23749. get: function get() {
  23750. var items = this.items;
  23751. return items ? items[items.length - 1].end : 0;
  23752. }
  23753. }, {
  23754. key: "length",
  23755. get: function get() {
  23756. return this.items ? this.items.length : 0;
  23757. }
  23758. }, {
  23759. key: "assetIdAtEnd",
  23760. get: function get() {
  23761. var _this$items, _this$items2;
  23762. var interstitialAtEnd = (_this$items = this.items) == null ? void 0 : (_this$items2 = _this$items[this.length - 1]) == null ? void 0 : _this$items2.event;
  23763. if (interstitialAtEnd) {
  23764. var assetList = interstitialAtEnd.assetList;
  23765. var assetAtEnd = assetList[assetList.length - 1];
  23766. if (assetAtEnd) {
  23767. return assetAtEnd.identifier;
  23768. }
  23769. }
  23770. return null;
  23771. }
  23772. }]);
  23773. }(Logger);
  23774. function segmentToString(segment) {
  23775. return "[" + (segment.event ? '"' + segment.event.identifier + '"' : 'primary') + ": " + segment.start.toFixed(2) + "-" + segment.end.toFixed(2) + "]";
  23776. }
  23777. var AssetListLoader = /*#__PURE__*/function () {
  23778. function AssetListLoader(hls) {
  23779. this.hls = void 0;
  23780. this.hls = hls;
  23781. }
  23782. var _proto = AssetListLoader.prototype;
  23783. _proto.destroy = function destroy() {
  23784. // @ts-ignore
  23785. this.hls = null;
  23786. };
  23787. _proto.loadAssetList = function loadAssetList(interstitial, hlsStartOffset) {
  23788. var _this = this;
  23789. var assetListUrl = interstitial.assetListUrl;
  23790. var url;
  23791. try {
  23792. url = getInterstitialUrl(assetListUrl, this.hls.sessionId, interstitial.baseUrl);
  23793. } catch (error) {
  23794. var errorData = this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, error, assetListUrl);
  23795. this.hls.trigger(Events.ERROR, errorData);
  23796. return;
  23797. }
  23798. if (hlsStartOffset && url.protocol !== 'data:') {
  23799. url.searchParams.set('_HLS_start_offset', '' + hlsStartOffset);
  23800. }
  23801. var config = this.hls.config;
  23802. var Loader = config.loader;
  23803. var loader = new Loader(config);
  23804. var context = {
  23805. responseType: 'json',
  23806. url: url.href
  23807. };
  23808. var loadPolicy = config.interstitialAssetListLoadPolicy.default;
  23809. var loaderConfig = {
  23810. loadPolicy: loadPolicy,
  23811. timeout: loadPolicy.maxLoadTimeMs,
  23812. maxRetry: 0,
  23813. retryDelay: 0,
  23814. maxRetryDelay: 0
  23815. };
  23816. var callbacks = {
  23817. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  23818. var assetListResponse = response.data;
  23819. var assets = assetListResponse == null ? void 0 : assetListResponse.ASSETS;
  23820. if (!Array.isArray(assets)) {
  23821. var _errorData = _this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_PARSING_ERROR, new Error("Invalid interstitial asset list"), context.url, stats, networkDetails);
  23822. _this.hls.trigger(Events.ERROR, _errorData);
  23823. return;
  23824. }
  23825. interstitial.assetListResponse = assetListResponse;
  23826. _this.hls.trigger(Events.ASSET_LIST_LOADED, {
  23827. event: interstitial,
  23828. assetListResponse: assetListResponse,
  23829. networkDetails: networkDetails
  23830. });
  23831. },
  23832. onError: function onError(error, context, networkDetails, stats) {
  23833. var errorData = _this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_ERROR, new Error("Error loading X-ASSET-LIST: HTTP status " + error.code + " " + error.text + " (" + context.url + ")"), context.url, stats, networkDetails);
  23834. _this.hls.trigger(Events.ERROR, errorData);
  23835. },
  23836. onTimeout: function onTimeout(stats, context, networkDetails) {
  23837. var errorData = _this.assignAssetListError(interstitial, ErrorDetails.ASSET_LIST_LOAD_TIMEOUT, new Error("Timeout loading X-ASSET-LIST (" + context.url + ")"), context.url, stats, networkDetails);
  23838. _this.hls.trigger(Events.ERROR, errorData);
  23839. }
  23840. };
  23841. loader.load(context, loaderConfig, callbacks);
  23842. this.hls.trigger(Events.ASSET_LIST_LOADING, {
  23843. event: interstitial
  23844. });
  23845. return loader;
  23846. };
  23847. _proto.assignAssetListError = function assignAssetListError(interstitial, details, error, url, stats, networkDetails) {
  23848. interstitial.error = error;
  23849. return {
  23850. type: ErrorTypes.NETWORK_ERROR,
  23851. details: details,
  23852. fatal: false,
  23853. interstitial: interstitial,
  23854. url: url,
  23855. error: error,
  23856. networkDetails: networkDetails,
  23857. stats: stats
  23858. };
  23859. };
  23860. return AssetListLoader;
  23861. }();
  23862. function playWithCatch(media) {
  23863. media == null ? void 0 : media.play().catch(function () {
  23864. /* no-op */
  23865. });
  23866. }
  23867. var InterstitialsController = /*#__PURE__*/function (_Logger) {
  23868. function InterstitialsController(hls, HlsPlayerClass) {
  23869. var _this;
  23870. _this = _Logger.call(this, 'interstitials', hls.logger) || this;
  23871. _this.HlsPlayerClass = void 0;
  23872. _this.hls = void 0;
  23873. _this.assetListLoader = void 0;
  23874. // Last updated LevelDetails
  23875. _this.mediaSelection = null;
  23876. _this.altSelection = null;
  23877. // Media and MediaSource/SourceBuffers
  23878. _this.media = null;
  23879. _this.detachedData = null;
  23880. _this.requiredTracks = null;
  23881. // Public Interface for Interstitial playback state and control
  23882. _this.manager = null;
  23883. // Interstitial Asset Players
  23884. _this.playerQueue = [];
  23885. // Timeline position tracking
  23886. _this.bufferedPos = -1;
  23887. _this.timelinePos = -1;
  23888. // Schedule
  23889. _this.schedule = void 0;
  23890. // Schedule playback and buffering state
  23891. _this.playingItem = null;
  23892. _this.bufferingItem = null;
  23893. _this.waitingItem = null;
  23894. _this.endedItem = null;
  23895. _this.playingAsset = null;
  23896. _this.endedAsset = null;
  23897. _this.bufferingAsset = null;
  23898. _this.shouldPlay = false;
  23899. _this.onPlay = function () {
  23900. _this.shouldPlay = true;
  23901. };
  23902. _this.onPause = function () {
  23903. _this.shouldPlay = false;
  23904. };
  23905. _this.onSeeking = function () {
  23906. var currentTime = _this.currentTime;
  23907. if (currentTime === undefined || _this.playbackDisabled) {
  23908. return;
  23909. }
  23910. var diff = currentTime - _this.timelinePos;
  23911. var roundingError = Math.abs(diff) < 1 / 705600000; // one flick
  23912. if (roundingError) {
  23913. return;
  23914. }
  23915. var backwardSeek = diff <= -0.01;
  23916. _this.timelinePos = currentTime;
  23917. _this.bufferedPos = currentTime;
  23918. // Check if seeking out of an item
  23919. var playingItem = _this.playingItem;
  23920. if (!playingItem) {
  23921. _this.checkBuffer();
  23922. return;
  23923. }
  23924. if (backwardSeek) {
  23925. var resetCount = _this.schedule.resetErrorsInRange(currentTime, currentTime - diff);
  23926. if (resetCount) {
  23927. _this.updateSchedule();
  23928. }
  23929. }
  23930. _this.checkBuffer();
  23931. if (backwardSeek && currentTime < playingItem.start || currentTime >= playingItem.end) {
  23932. var _this$media;
  23933. var scheduleIndex = _this.schedule.findItemIndexAtTime(_this.timelinePos);
  23934. if (!_this.isInterstitial(playingItem) && (_this$media = _this.media) != null && _this$media.paused) {
  23935. _this.shouldPlay = false;
  23936. }
  23937. if (!backwardSeek) {
  23938. // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction
  23939. var playingIndex = _this.findItemIndex(playingItem);
  23940. if (scheduleIndex > playingIndex) {
  23941. var jumpIndex = _this.schedule.findJumpRestrictedIndex(playingIndex + 1, scheduleIndex);
  23942. if (jumpIndex > playingIndex) {
  23943. _this.setSchedulePosition(jumpIndex);
  23944. return;
  23945. }
  23946. }
  23947. }
  23948. _this.setSchedulePosition(scheduleIndex);
  23949. return;
  23950. }
  23951. // Check if seeking out of an asset (assumes same item following above check)
  23952. var playingAsset = _this.playingAsset;
  23953. if (!playingAsset) {
  23954. // restart Interstitial at end
  23955. if (_this.playingLastItem && _this.isInterstitial(playingItem)) {
  23956. var restartAsset = playingItem.event.assetList[0];
  23957. if (restartAsset) {
  23958. _this.endedItem = _this.playingItem;
  23959. _this.playingItem = null;
  23960. _this.setScheduleToAssetAtTime(currentTime, restartAsset);
  23961. }
  23962. }
  23963. return;
  23964. }
  23965. var start = playingAsset.timelineStart;
  23966. var duration = playingAsset.duration || 0;
  23967. if (backwardSeek && currentTime < start || currentTime >= start + duration) {
  23968. _this.setScheduleToAssetAtTime(currentTime, playingAsset);
  23969. }
  23970. };
  23971. _this.onTimeupdate = function () {
  23972. var currentTime = _this.currentTime;
  23973. if (currentTime === undefined || _this.playbackDisabled) {
  23974. return;
  23975. }
  23976. // Only allow timeupdate to advance primary position, seeking is used for jumping back
  23977. // this prevents primaryPos from being reset to 0 after re-attach
  23978. if (currentTime > _this.timelinePos) {
  23979. _this.timelinePos = currentTime;
  23980. if (currentTime > _this.bufferedPos) {
  23981. _this.checkBuffer();
  23982. }
  23983. } else {
  23984. return;
  23985. }
  23986. // Check if playback has entered the next item
  23987. var playingItem = _this.playingItem;
  23988. if (!playingItem || _this.playingLastItem) {
  23989. return;
  23990. }
  23991. if (currentTime >= playingItem.end) {
  23992. _this.timelinePos = playingItem.end;
  23993. var playingIndex = _this.findItemIndex(playingItem);
  23994. _this.setSchedulePosition(playingIndex + 1);
  23995. }
  23996. // Check if playback has entered the next asset
  23997. var playingAsset = _this.playingAsset;
  23998. if (!playingAsset) {
  23999. return;
  24000. }
  24001. var end = playingAsset.timelineStart + (playingAsset.duration || 0);
  24002. if (currentTime >= end) {
  24003. _this.setScheduleToAssetAtTime(currentTime, playingAsset);
  24004. }
  24005. };
  24006. // Schedule update callback
  24007. _this.onScheduleUpdate = function (removedInterstitials, previousItems) {
  24008. var schedule = _this.schedule;
  24009. var playingItem = _this.playingItem;
  24010. var interstitialEvents = schedule.events || [];
  24011. var scheduleItems = schedule.items || [];
  24012. var durations = schedule.durations;
  24013. var removedIds = removedInterstitials.map(function (interstitial) {
  24014. return interstitial.identifier;
  24015. });
  24016. var interstitialsUpdated = !!(interstitialEvents.length || removedIds.length);
  24017. if (interstitialsUpdated || previousItems) {
  24018. _this.log("INTERSTITIALS_UPDATED (" + interstitialEvents.length + "): " + interstitialEvents + "\nSchedule: " + scheduleItems.map(function (seg) {
  24019. return segmentToString(seg);
  24020. }) + " pos: " + _this.timelinePos);
  24021. }
  24022. if (removedIds.length) {
  24023. _this.log("Removed events " + removedIds);
  24024. }
  24025. _this.playerQueue.forEach(function (player) {
  24026. if (player.interstitial.appendInPlace) {
  24027. var timelineStart = player.assetItem.timelineStart;
  24028. var diff = player.timelineOffset - timelineStart;
  24029. if (diff) {
  24030. try {
  24031. player.timelineOffset = timelineStart;
  24032. } catch (e) {
  24033. if (Math.abs(diff) > ALIGNED_END_THRESHOLD_SECONDS) {
  24034. _this.warn(e + " (\"" + player.assetId + "\" " + player.timelineOffset + "->" + timelineStart + ")");
  24035. }
  24036. }
  24037. }
  24038. }
  24039. });
  24040. // Update schedule item references
  24041. // Do not replace Interstitial playingItem without a match - used for INTERSTITIAL_ASSET_ENDED and INTERSTITIAL_ENDED
  24042. var trimInPlaceForPlayout = null;
  24043. if (playingItem) {
  24044. var updatedPlayingItem = _this.updateItem(playingItem, _this.timelinePos);
  24045. if (_this.itemsMatch(playingItem, updatedPlayingItem)) {
  24046. _this.playingItem = updatedPlayingItem;
  24047. _this.waitingItem = _this.endedItem = null;
  24048. trimInPlaceForPlayout = function trimInPlaceForPlayout() {
  24049. return _this.trimInPlace(updatedPlayingItem, playingItem);
  24050. };
  24051. }
  24052. } else {
  24053. // Clear waitingItem if it has been removed from the schedule
  24054. _this.waitingItem = _this.updateItem(_this.waitingItem);
  24055. _this.endedItem = _this.updateItem(_this.endedItem);
  24056. }
  24057. // Do not replace Interstitial bufferingItem without a match - used for transfering media element or source
  24058. var bufferingItem = _this.bufferingItem;
  24059. if (bufferingItem) {
  24060. var updatedBufferingItem = _this.updateItem(bufferingItem, _this.bufferedPos);
  24061. if (_this.itemsMatch(bufferingItem, updatedBufferingItem)) {
  24062. _this.bufferingItem = updatedBufferingItem;
  24063. trimInPlaceForPlayout || (trimInPlaceForPlayout = function trimInPlaceForPlayout() {
  24064. return _this.trimInPlace(updatedBufferingItem, bufferingItem);
  24065. });
  24066. } else if (bufferingItem.event) {
  24067. // Interstitial removed from schedule (Live -> VOD or other scenario where Start Date is outside the range of VOD Playlist)
  24068. _this.bufferingItem = _this.playingItem;
  24069. _this.clearInterstitial(bufferingItem.event, null);
  24070. }
  24071. }
  24072. removedInterstitials.forEach(function (interstitial) {
  24073. interstitial.assetList.forEach(function (asset) {
  24074. _this.clearAssetPlayer(asset.identifier, null);
  24075. });
  24076. });
  24077. if (interstitialsUpdated || previousItems) {
  24078. _this.hls.trigger(Events.INTERSTITIALS_UPDATED, {
  24079. events: interstitialEvents.slice(0),
  24080. schedule: scheduleItems.slice(0),
  24081. durations: durations,
  24082. removedIds: removedIds
  24083. });
  24084. if (_this.isInterstitial(playingItem) && removedIds.includes(playingItem.event.identifier)) {
  24085. _this.warn("Interstitial \"" + playingItem.event.identifier + "\" removed while playing");
  24086. _this.primaryFallback(playingItem.event);
  24087. return;
  24088. }
  24089. if (trimInPlaceForPlayout) {
  24090. trimInPlaceForPlayout();
  24091. }
  24092. // Check is buffered to new Interstitial event boundary
  24093. // (Live update publishes Interstitial with new segment)
  24094. _this.checkBuffer();
  24095. }
  24096. };
  24097. _this.hls = hls;
  24098. _this.HlsPlayerClass = HlsPlayerClass;
  24099. _this.assetListLoader = new AssetListLoader(hls);
  24100. _this.schedule = new InterstitialsSchedule(_this.onScheduleUpdate, hls.logger);
  24101. _this.registerListeners();
  24102. return _this;
  24103. }
  24104. _inheritsLoose(InterstitialsController, _Logger);
  24105. var _proto = InterstitialsController.prototype;
  24106. _proto.registerListeners = function registerListeners() {
  24107. var hls = this.hls;
  24108. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  24109. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  24110. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  24111. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24112. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  24113. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  24114. hls.on(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  24115. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  24116. hls.on(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  24117. hls.on(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  24118. hls.on(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  24119. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  24120. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  24121. hls.on(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  24122. hls.on(Events.MEDIA_ENDED, this.onMediaEnded, this);
  24123. hls.on(Events.ERROR, this.onError, this);
  24124. hls.on(Events.DESTROYING, this.onDestroying, this);
  24125. };
  24126. _proto.unregisterListeners = function unregisterListeners() {
  24127. var hls = this.hls;
  24128. if (!hls) {
  24129. return;
  24130. }
  24131. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  24132. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  24133. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  24134. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  24135. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  24136. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  24137. hls.off(Events.AUDIO_TRACK_UPDATED, this.onAudioTrackUpdated, this);
  24138. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  24139. hls.off(Events.SUBTITLE_TRACK_UPDATED, this.onSubtitleTrackUpdated, this);
  24140. hls.off(Events.EVENT_CUE_ENTER, this.onInterstitialCueEnter, this);
  24141. hls.off(Events.ASSET_LIST_LOADED, this.onAssetListLoaded, this);
  24142. hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24143. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  24144. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  24145. hls.off(Events.BUFFERED_TO_END, this.onBufferedToEnd, this);
  24146. hls.off(Events.MEDIA_ENDED, this.onMediaEnded, this);
  24147. hls.off(Events.ERROR, this.onError, this);
  24148. hls.off(Events.DESTROYING, this.onDestroying, this);
  24149. };
  24150. _proto.startLoad = function startLoad() {
  24151. // TODO: startLoad - check for waitingItem and retry by resetting schedule
  24152. this.resumeBuffering();
  24153. };
  24154. _proto.stopLoad = function stopLoad() {
  24155. // TODO: stopLoad - stop all scheule.events[].assetListLoader?.abort() then delete the loaders
  24156. this.pauseBuffering();
  24157. };
  24158. _proto.resumeBuffering = function resumeBuffering() {
  24159. var _this$getBufferingPla;
  24160. (_this$getBufferingPla = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla.resumeBuffering();
  24161. };
  24162. _proto.pauseBuffering = function pauseBuffering() {
  24163. var _this$getBufferingPla2;
  24164. (_this$getBufferingPla2 = this.getBufferingPlayer()) == null ? void 0 : _this$getBufferingPla2.pauseBuffering();
  24165. };
  24166. _proto.destroy = function destroy() {
  24167. this.unregisterListeners();
  24168. this.stopLoad();
  24169. if (this.assetListLoader) {
  24170. this.assetListLoader.destroy();
  24171. }
  24172. this.emptyPlayerQueue();
  24173. this.clearScheduleState();
  24174. if (this.schedule) {
  24175. this.schedule.destroy();
  24176. }
  24177. this.media = this.detachedData = this.mediaSelection = this.requiredTracks = this.altSelection = this.manager = null;
  24178. // @ts-ignore
  24179. this.hls = this.HlsPlayerClass = this.schedule = this.log = null;
  24180. // @ts-ignore
  24181. this.assetListLoader = null;
  24182. // @ts-ignore
  24183. this.onPlay = this.onPause = this.onSeeking = this.onTimeupdate = null;
  24184. // @ts-ignore
  24185. this.onScheduleUpdate = null;
  24186. };
  24187. _proto.onDestroying = function onDestroying() {
  24188. var media = this.primaryMedia || this.media;
  24189. if (media) {
  24190. this.removeMediaListeners(media);
  24191. }
  24192. };
  24193. _proto.removeMediaListeners = function removeMediaListeners(media) {
  24194. removeEventListener(media, 'play', this.onPlay);
  24195. removeEventListener(media, 'pause', this.onPause);
  24196. removeEventListener(media, 'seeking', this.onSeeking);
  24197. removeEventListener(media, 'timeupdate', this.onTimeupdate);
  24198. };
  24199. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  24200. var media = this.media = data.media;
  24201. addEventListener(media, 'seeking', this.onSeeking);
  24202. addEventListener(media, 'timeupdate', this.onTimeupdate);
  24203. addEventListener(media, 'play', this.onPlay);
  24204. addEventListener(media, 'pause', this.onPause);
  24205. };
  24206. _proto.onMediaAttached = function onMediaAttached(event, data) {
  24207. var playingItem = this.effectivePlayingItem;
  24208. var detachedMedia = this.detachedData;
  24209. this.detachedData = null;
  24210. if (playingItem === null) {
  24211. this.checkStart();
  24212. } else if (!detachedMedia) {
  24213. // Resume schedule after detached externally
  24214. this.clearScheduleState();
  24215. var playingIndex = this.findItemIndex(playingItem);
  24216. this.setSchedulePosition(playingIndex);
  24217. }
  24218. };
  24219. _proto.clearScheduleState = function clearScheduleState() {
  24220. this.playingItem = this.bufferingItem = this.waitingItem = this.endedItem = this.playingAsset = this.endedAsset = this.bufferingAsset = null;
  24221. };
  24222. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  24223. var transferringMedia = !!data.transferMedia;
  24224. var media = this.media;
  24225. this.media = null;
  24226. if (transferringMedia) {
  24227. return;
  24228. }
  24229. if (media) {
  24230. this.removeMediaListeners(media);
  24231. }
  24232. // If detachMedia is called while in an Interstitial, detach the asset player as well and reset the schedule position
  24233. if (this.detachedData) {
  24234. var player = this.getBufferingPlayer();
  24235. if (player) {
  24236. this.playingAsset = this.endedAsset = this.bufferingAsset = this.bufferingItem = this.waitingItem = this.detachedData = null;
  24237. player.detachMedia();
  24238. }
  24239. this.shouldPlay = false;
  24240. }
  24241. };
  24242. _proto.isInterstitial = function isInterstitial(item) {
  24243. return !!(item != null && item.event);
  24244. };
  24245. _proto.retreiveMediaSource = function retreiveMediaSource(assetId, toSegment) {
  24246. var player = this.getAssetPlayer(assetId);
  24247. if (player) {
  24248. this.transferMediaFromPlayer(player, toSegment);
  24249. }
  24250. };
  24251. _proto.transferMediaFromPlayer = function transferMediaFromPlayer(player, toSegment) {
  24252. var appendInPlace = player.interstitial.appendInPlace;
  24253. var playerMedia = player.media;
  24254. if (appendInPlace && playerMedia === this.primaryMedia) {
  24255. this.bufferingAsset = null;
  24256. if (!toSegment || this.isInterstitial(toSegment) && !toSegment.event.appendInPlace) {
  24257. // MediaSource cannot be transfered back to an Interstitial that requires a source reset
  24258. // no-op when toSegment is undefined
  24259. if (toSegment && playerMedia) {
  24260. this.detachedData = {
  24261. media: playerMedia
  24262. };
  24263. return;
  24264. }
  24265. }
  24266. var attachMediaSourceData = player.transferMedia();
  24267. this.log("transfer MediaSource from " + player + " " + stringify(attachMediaSourceData));
  24268. this.detachedData = attachMediaSourceData;
  24269. } else if (toSegment && playerMedia) {
  24270. this.shouldPlay || (this.shouldPlay = !playerMedia.paused);
  24271. }
  24272. };
  24273. _proto.transferMediaTo = function transferMediaTo(player, media) {
  24274. var _this$detachedData,
  24275. _this2 = this,
  24276. _attachMediaSourceDat;
  24277. if (player.media === media) {
  24278. return;
  24279. }
  24280. var attachMediaSourceData = null;
  24281. var primaryPlayer = this.hls;
  24282. var isAssetPlayer = player !== primaryPlayer;
  24283. var appendInPlace = isAssetPlayer && player.interstitial.appendInPlace;
  24284. var detachedMediaSource = (_this$detachedData = this.detachedData) == null ? void 0 : _this$detachedData.mediaSource;
  24285. var logFromSource;
  24286. if (primaryPlayer.media) {
  24287. if (appendInPlace) {
  24288. attachMediaSourceData = primaryPlayer.transferMedia();
  24289. this.detachedData = attachMediaSourceData;
  24290. }
  24291. logFromSource = "Primary";
  24292. } else if (detachedMediaSource) {
  24293. var bufferingPlayer = this.getBufferingPlayer();
  24294. if (bufferingPlayer) {
  24295. attachMediaSourceData = bufferingPlayer.transferMedia();
  24296. logFromSource = "" + bufferingPlayer;
  24297. } else {
  24298. logFromSource = "detached MediaSource";
  24299. }
  24300. } else {
  24301. logFromSource = "detached media";
  24302. }
  24303. if (!attachMediaSourceData) {
  24304. if (detachedMediaSource) {
  24305. attachMediaSourceData = this.detachedData;
  24306. this.log("using detachedData: MediaSource " + stringify(attachMediaSourceData));
  24307. } else if (!this.detachedData || primaryPlayer.media === media) {
  24308. // Keep interstitial media transition consistent
  24309. var playerQueue = this.playerQueue;
  24310. if (playerQueue.length > 1) {
  24311. playerQueue.forEach(function (queuedPlayer) {
  24312. if (isAssetPlayer && queuedPlayer.interstitial.appendInPlace !== appendInPlace) {
  24313. var interstitial = queuedPlayer.interstitial;
  24314. _this2.clearInterstitial(queuedPlayer.interstitial, null);
  24315. interstitial.appendInPlace = false;
  24316. if (interstitial.appendInPlace) {
  24317. _this2.warn("Could not change append strategy for queued assets " + interstitial);
  24318. }
  24319. }
  24320. });
  24321. }
  24322. this.hls.detachMedia();
  24323. this.detachedData = {
  24324. media: media
  24325. };
  24326. }
  24327. }
  24328. var transferring = attachMediaSourceData && 'mediaSource' in attachMediaSourceData && ((_attachMediaSourceDat = attachMediaSourceData.mediaSource) == null ? void 0 : _attachMediaSourceDat.readyState) !== 'closed';
  24329. var dataToAttach = transferring && attachMediaSourceData ? attachMediaSourceData : media;
  24330. this.log((transferring ? 'transfering MediaSource' : 'attaching media') + " to " + (isAssetPlayer ? player : 'Primary') + " from " + logFromSource);
  24331. if (dataToAttach === attachMediaSourceData) {
  24332. var isAssetAtEndOfSchedule = isAssetPlayer && player.assetId === this.schedule.assetIdAtEnd;
  24333. // Prevent asset players from marking EoS on transferred MediaSource
  24334. dataToAttach.overrides = {
  24335. duration: this.schedule.duration,
  24336. endOfStream: !isAssetPlayer || isAssetAtEndOfSchedule,
  24337. cueRemoval: !isAssetPlayer
  24338. };
  24339. }
  24340. player.attachMedia(dataToAttach);
  24341. };
  24342. _proto.onInterstitialCueEnter = function onInterstitialCueEnter() {
  24343. this.onTimeupdate();
  24344. };
  24345. // Scheduling methods
  24346. _proto.checkStart = function checkStart() {
  24347. var schedule = this.schedule;
  24348. var interstitialEvents = schedule.events;
  24349. if (!interstitialEvents || this.playbackDisabled || !this.media) {
  24350. return;
  24351. }
  24352. // Check buffered to pre-roll
  24353. if (this.bufferedPos === -1) {
  24354. this.bufferedPos = 0;
  24355. }
  24356. // Start stepping through schedule when playback begins for the first time and we have a pre-roll
  24357. var timelinePos = this.timelinePos;
  24358. var effectivePlayingItem = this.effectivePlayingItem;
  24359. if (timelinePos === -1) {
  24360. var startPosition = this.hls.startPosition;
  24361. this.timelinePos = startPosition;
  24362. if (interstitialEvents.length && interstitialEvents[0].cue.pre) {
  24363. var index = schedule.findEventIndex(interstitialEvents[0].identifier);
  24364. this.setSchedulePosition(index);
  24365. } else if (startPosition >= 0 || !this.primaryLive) {
  24366. var start = this.timelinePos = startPosition > 0 ? startPosition : 0;
  24367. var _index = schedule.findItemIndexAtTime(start);
  24368. this.setSchedulePosition(_index);
  24369. }
  24370. } else if (effectivePlayingItem && !this.playingItem) {
  24371. var _index2 = schedule.findItemIndex(effectivePlayingItem);
  24372. this.setSchedulePosition(_index2);
  24373. }
  24374. };
  24375. _proto.advanceAfterAssetEnded = function advanceAfterAssetEnded(interstitial, index, assetListIndex) {
  24376. var nextAssetIndex = getNextAssetIndex(interstitial, assetListIndex);
  24377. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  24378. // Advance to next asset list item
  24379. this.setSchedulePosition(index, nextAssetIndex);
  24380. } else {
  24381. // Advance to next schedule segment
  24382. // check if we've reached the end of the program
  24383. var scheduleItems = this.schedule.items;
  24384. if (scheduleItems) {
  24385. var nextIndex = index + 1;
  24386. var scheduleLength = scheduleItems.length;
  24387. if (nextIndex >= scheduleLength) {
  24388. this.setSchedulePosition(-1);
  24389. return;
  24390. }
  24391. var resumptionTime = interstitial.resumeTime;
  24392. if (this.timelinePos < resumptionTime) {
  24393. this.timelinePos = resumptionTime;
  24394. this.checkBuffer();
  24395. }
  24396. this.setSchedulePosition(nextIndex);
  24397. }
  24398. }
  24399. };
  24400. _proto.setScheduleToAssetAtTime = function setScheduleToAssetAtTime(time, playingAsset) {
  24401. var schedule = this.schedule;
  24402. var parentIdentifier = playingAsset.parentIdentifier;
  24403. var interstitial = schedule.getEvent(parentIdentifier);
  24404. if (interstitial) {
  24405. var itemIndex = schedule.findEventIndex(parentIdentifier);
  24406. var assetListIndex = schedule.findAssetIndex(interstitial, time);
  24407. this.advanceAfterAssetEnded(interstitial, itemIndex, assetListIndex - 1);
  24408. }
  24409. };
  24410. _proto.setSchedulePosition = function setSchedulePosition(index, assetListIndex) {
  24411. var scheduleItems = this.schedule.items;
  24412. if (!scheduleItems || this.playbackDisabled) {
  24413. return;
  24414. }
  24415. this.log("setSchedulePosition " + index + ", " + assetListIndex);
  24416. var scheduledItem = index >= 0 ? scheduleItems[index] : null;
  24417. // Cleanup current item / asset
  24418. var currentItem = this.playingItem;
  24419. var playingLastItem = this.playingLastItem;
  24420. if (this.isInterstitial(currentItem)) {
  24421. var _interstitial$assetLi;
  24422. var interstitial = currentItem.event;
  24423. var playingAsset = this.playingAsset;
  24424. var assetId = playingAsset == null ? void 0 : playingAsset.identifier;
  24425. var player = assetId ? this.getAssetPlayer(assetId) : null;
  24426. if (player && assetId && (!this.eventItemsMatch(currentItem, scheduledItem) || assetListIndex !== undefined && assetId !== ((_interstitial$assetLi = interstitial.assetList) == null ? void 0 : _interstitial$assetLi[assetListIndex].identifier))) {
  24427. var _this$detachedData2;
  24428. var playingAssetListIndex = interstitial.findAssetIndex(playingAsset);
  24429. this.log("INTERSTITIAL_ASSET_ENDED " + (playingAssetListIndex + 1) + "/" + interstitial.assetList.length + " " + eventAssetToString(playingAsset));
  24430. this.endedAsset = playingAsset;
  24431. this.playingAsset = null;
  24432. this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED, {
  24433. asset: playingAsset,
  24434. assetListIndex: playingAssetListIndex,
  24435. event: interstitial,
  24436. schedule: scheduleItems.slice(0),
  24437. scheduleIndex: index,
  24438. player: player
  24439. });
  24440. if (currentItem !== this.playingItem) {
  24441. // Schedule change occured on INTERSTITIAL_ASSET_ENDED
  24442. if (this.itemsMatch(currentItem, this.playingItem) && !this.playingAsset) {
  24443. this.advanceAfterAssetEnded(interstitial, this.findItemIndex(this.playingItem), playingAssetListIndex);
  24444. }
  24445. // Navigation occured on INTERSTITIAL_ASSET_ENDED
  24446. return;
  24447. }
  24448. this.retreiveMediaSource(assetId, scheduledItem);
  24449. if (player.media && !((_this$detachedData2 = this.detachedData) != null && _this$detachedData2.mediaSource)) {
  24450. player.detachMedia();
  24451. }
  24452. }
  24453. if (!this.eventItemsMatch(currentItem, scheduledItem)) {
  24454. this.endedItem = currentItem;
  24455. this.playingItem = null;
  24456. this.log("INTERSTITIAL_ENDED " + interstitial + " " + segmentToString(currentItem));
  24457. interstitial.hasPlayed = true;
  24458. this.hls.trigger(Events.INTERSTITIAL_ENDED, {
  24459. event: interstitial,
  24460. schedule: scheduleItems.slice(0),
  24461. scheduleIndex: index
  24462. });
  24463. // Exiting an Interstitial
  24464. if (interstitial.cue.once) {
  24465. // Remove interstitial with CUE attribute value of ONCE after it has played
  24466. this.updateSchedule();
  24467. var items = this.schedule.items;
  24468. if (scheduledItem && items) {
  24469. var updatedIndex = this.findItemIndex(scheduledItem);
  24470. this.advanceSchedule(updatedIndex, items, assetListIndex, currentItem, playingLastItem);
  24471. }
  24472. return;
  24473. }
  24474. }
  24475. }
  24476. this.advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playingLastItem);
  24477. };
  24478. _proto.advanceSchedule = function advanceSchedule(index, scheduleItems, assetListIndex, currentItem, playedLastItem) {
  24479. var _this3 = this;
  24480. var scheduledItem = index >= 0 ? scheduleItems[index] : null;
  24481. var media = this.primaryMedia;
  24482. // Cleanup out of range Interstitials
  24483. var playerQueue = this.playerQueue;
  24484. if (playerQueue.length) {
  24485. playerQueue.forEach(function (player) {
  24486. var interstitial = player.interstitial;
  24487. var queuedIndex = _this3.schedule.findEventIndex(interstitial.identifier);
  24488. if (queuedIndex < index || queuedIndex > index + 1) {
  24489. _this3.clearInterstitial(interstitial, scheduledItem);
  24490. }
  24491. });
  24492. }
  24493. // Setup scheduled item
  24494. if (this.isInterstitial(scheduledItem)) {
  24495. this.timelinePos = Math.min(Math.max(this.timelinePos, scheduledItem.start), scheduledItem.end);
  24496. // Handle Interstitial
  24497. var interstitial = scheduledItem.event;
  24498. // find asset index
  24499. if (assetListIndex === undefined) {
  24500. assetListIndex = this.schedule.findAssetIndex(interstitial, this.timelinePos);
  24501. var assetIndexCandidate = getNextAssetIndex(interstitial, assetListIndex - 1);
  24502. if (interstitial.isAssetPastPlayoutLimit(assetIndexCandidate)) {
  24503. this.advanceAfterAssetEnded(interstitial, index, assetListIndex);
  24504. return;
  24505. }
  24506. assetListIndex = assetIndexCandidate;
  24507. }
  24508. // Ensure Interstitial is enqueued
  24509. var waitingItem = this.waitingItem;
  24510. if (!this.assetsBuffered(scheduledItem, media)) {
  24511. this.setBufferingItem(scheduledItem);
  24512. }
  24513. var player = this.preloadAssets(interstitial, assetListIndex);
  24514. if (!this.eventItemsMatch(scheduledItem, waitingItem || currentItem)) {
  24515. this.waitingItem = scheduledItem;
  24516. this.log("INTERSTITIAL_STARTED " + segmentToString(scheduledItem) + " " + (interstitial.appendInPlace ? 'append in place' : ''));
  24517. this.hls.trigger(Events.INTERSTITIAL_STARTED, {
  24518. event: interstitial,
  24519. schedule: scheduleItems.slice(0),
  24520. scheduleIndex: index
  24521. });
  24522. }
  24523. if (!interstitial.assetListLoaded) {
  24524. // Waiting at end of primary content segment
  24525. // Expect setSchedulePosition to be called again once ASSET-LIST is loaded
  24526. this.log("Waiting for ASSET-LIST to complete loading " + interstitial);
  24527. return;
  24528. }
  24529. if (interstitial.assetListLoader) {
  24530. interstitial.assetListLoader.destroy();
  24531. interstitial.assetListLoader = undefined;
  24532. }
  24533. if (!media) {
  24534. this.log("Waiting for attachMedia to start Interstitial " + interstitial);
  24535. return;
  24536. }
  24537. // Update schedule and asset list position now that it can start
  24538. this.waitingItem = this.endedItem = null;
  24539. this.playingItem = scheduledItem;
  24540. // If asset-list is empty or missing asset index, advance to next item
  24541. var assetItem = interstitial.assetList[assetListIndex];
  24542. if (!assetItem) {
  24543. var nextItem = scheduleItems[index + 1];
  24544. var _media = this.media;
  24545. if (nextItem && _media && !this.isInterstitial(nextItem) && _media.currentTime < nextItem.start) {
  24546. _media.currentTime = this.timelinePos = nextItem.start;
  24547. }
  24548. this.advanceAfterAssetEnded(interstitial, index, assetListIndex || 0);
  24549. return;
  24550. }
  24551. // Start Interstitial Playback
  24552. if (!player) {
  24553. player = this.getAssetPlayer(assetItem.identifier);
  24554. }
  24555. if (player === null || player.destroyed) {
  24556. var assetListLength = interstitial.assetList.length;
  24557. this.warn("asset " + (assetListIndex + 1) + "/" + assetListLength + " player destroyed " + interstitial);
  24558. player = this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  24559. }
  24560. if (!this.eventItemsMatch(scheduledItem, this.bufferingItem)) {
  24561. if (interstitial.appendInPlace && this.isAssetBuffered(assetItem)) {
  24562. return;
  24563. }
  24564. }
  24565. this.startAssetPlayer(player, assetListIndex, scheduleItems, index, media);
  24566. if (this.shouldPlay) {
  24567. playWithCatch(player.media);
  24568. }
  24569. } else if (scheduledItem !== null) {
  24570. this.resumePrimary(scheduledItem, index, currentItem);
  24571. if (this.shouldPlay) {
  24572. playWithCatch(this.hls.media);
  24573. }
  24574. } else if (playedLastItem && this.isInterstitial(currentItem)) {
  24575. // Maintain playingItem state at end of schedule (setSchedulePosition(-1) called to end program)
  24576. // this allows onSeeking handler to update schedule position
  24577. this.endedItem = null;
  24578. this.playingItem = currentItem;
  24579. if (!currentItem.event.appendInPlace) {
  24580. // Media must be re-attached to resume primary schedule if not sharing source
  24581. this.attachPrimary(this.schedule.durations.primary, null);
  24582. }
  24583. }
  24584. };
  24585. _proto.resumePrimary = function resumePrimary(scheduledItem, index, fromItem) {
  24586. var _this$detachedData3;
  24587. this.playingItem = scheduledItem;
  24588. this.playingAsset = this.endedAsset = null;
  24589. this.waitingItem = this.endedItem = null;
  24590. this.bufferedToItem(scheduledItem);
  24591. this.log("resuming " + segmentToString(scheduledItem));
  24592. if (!((_this$detachedData3 = this.detachedData) != null && _this$detachedData3.mediaSource)) {
  24593. var timelinePos = this.timelinePos;
  24594. if (timelinePos < scheduledItem.start || timelinePos >= scheduledItem.end) {
  24595. timelinePos = this.getPrimaryResumption(scheduledItem, index);
  24596. this.timelinePos = timelinePos;
  24597. }
  24598. this.attachPrimary(timelinePos, scheduledItem);
  24599. }
  24600. if (!fromItem) {
  24601. return;
  24602. }
  24603. var scheduleItems = this.schedule.items;
  24604. if (!scheduleItems) {
  24605. return;
  24606. }
  24607. this.log("INTERSTITIALS_PRIMARY_RESUMED " + segmentToString(scheduledItem));
  24608. this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED, {
  24609. schedule: scheduleItems.slice(0),
  24610. scheduleIndex: index
  24611. });
  24612. this.checkBuffer();
  24613. };
  24614. _proto.getPrimaryResumption = function getPrimaryResumption(scheduledItem, index) {
  24615. var itemStart = scheduledItem.start;
  24616. if (this.primaryLive) {
  24617. var details = this.primaryDetails;
  24618. if (index === 0) {
  24619. return this.hls.startPosition;
  24620. } else if (details && (itemStart < details.fragmentStart || itemStart > details.edge)) {
  24621. return this.hls.liveSyncPosition || -1;
  24622. }
  24623. }
  24624. return itemStart;
  24625. };
  24626. _proto.isAssetBuffered = function isAssetBuffered(asset) {
  24627. var player = this.getAssetPlayer(asset.identifier);
  24628. if (player != null && player.hls) {
  24629. return player.hls.bufferedToEnd;
  24630. }
  24631. var bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  24632. return bufferInfo.end + 1 >= asset.timelineStart + (asset.duration || 0);
  24633. };
  24634. _proto.attachPrimary = function attachPrimary(timelinePos, item, skipSeekToStartPosition) {
  24635. if (item) {
  24636. this.setBufferingItem(item);
  24637. } else {
  24638. this.bufferingItem = this.playingItem;
  24639. }
  24640. this.bufferingAsset = null;
  24641. var media = this.primaryMedia;
  24642. if (!media) {
  24643. return;
  24644. }
  24645. var hls = this.hls;
  24646. if (hls.media) {
  24647. this.checkBuffer();
  24648. } else {
  24649. this.transferMediaTo(hls, media);
  24650. if (skipSeekToStartPosition) {
  24651. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  24652. }
  24653. }
  24654. if (!skipSeekToStartPosition) {
  24655. // Set primary position to resume time
  24656. this.timelinePos = timelinePos;
  24657. this.startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition);
  24658. }
  24659. };
  24660. _proto.startLoadingPrimaryAt = function startLoadingPrimaryAt(timelinePos, skipSeekToStartPosition) {
  24661. var _hls$mainForwardBuffe;
  24662. var hls = this.hls;
  24663. if (!hls.loadingEnabled || !hls.media || Math.abs((((_hls$mainForwardBuffe = hls.mainForwardBufferInfo) == null ? void 0 : _hls$mainForwardBuffe.start) || hls.media.currentTime) - timelinePos) > 0.5) {
  24664. hls.startLoad(timelinePos, skipSeekToStartPosition);
  24665. } else if (!hls.bufferingEnabled) {
  24666. hls.resumeBuffering();
  24667. }
  24668. }
  24669. // HLS.js event callbacks
  24670. ;
  24671. _proto.onManifestLoading = function onManifestLoading() {
  24672. this.stopLoad();
  24673. this.schedule.reset();
  24674. this.emptyPlayerQueue();
  24675. this.clearScheduleState();
  24676. this.shouldPlay = false;
  24677. this.bufferedPos = this.timelinePos = -1;
  24678. this.mediaSelection = this.altSelection = this.manager = this.requiredTracks = null;
  24679. // BUFFER_CODECS listener added here for buffer-controller to handle it first where it adds tracks
  24680. this.hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24681. this.hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);
  24682. };
  24683. _proto.onLevelUpdated = function onLevelUpdated(event, data) {
  24684. if (data.level === -1) {
  24685. // level was removed
  24686. return;
  24687. }
  24688. var main = this.hls.levels[data.level];
  24689. var currentSelection = _objectSpread2(_objectSpread2({}, this.mediaSelection || this.altSelection), {}, {
  24690. main: main
  24691. });
  24692. this.mediaSelection = currentSelection;
  24693. this.schedule.parseInterstitialDateRanges(currentSelection, this.hls.config.interstitialAppendInPlace);
  24694. if (!this.effectivePlayingItem && this.schedule.items) {
  24695. this.checkStart();
  24696. }
  24697. };
  24698. _proto.onAudioTrackUpdated = function onAudioTrackUpdated(event, data) {
  24699. var audio = this.hls.audioTracks[data.id];
  24700. var previousSelection = this.mediaSelection;
  24701. if (!previousSelection) {
  24702. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  24703. audio: audio
  24704. });
  24705. return;
  24706. }
  24707. var currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  24708. audio: audio
  24709. });
  24710. this.mediaSelection = currentSelection;
  24711. };
  24712. _proto.onSubtitleTrackUpdated = function onSubtitleTrackUpdated(event, data) {
  24713. var subtitles = this.hls.subtitleTracks[data.id];
  24714. var previousSelection = this.mediaSelection;
  24715. if (!previousSelection) {
  24716. this.altSelection = _objectSpread2(_objectSpread2({}, this.altSelection), {}, {
  24717. subtitles: subtitles
  24718. });
  24719. return;
  24720. }
  24721. var currentSelection = _objectSpread2(_objectSpread2({}, previousSelection), {}, {
  24722. subtitles: subtitles
  24723. });
  24724. this.mediaSelection = currentSelection;
  24725. };
  24726. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  24727. var audioOption = getBasicSelectionOption(data);
  24728. this.playerQueue.forEach(function (player) {
  24729. return player.hls.setAudioOption(data) || player.hls.setAudioOption(audioOption);
  24730. });
  24731. };
  24732. _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
  24733. var subtitleOption = getBasicSelectionOption(data);
  24734. this.playerQueue.forEach(function (player) {
  24735. return player.hls.setSubtitleOption(data) || data.id !== -1 && player.hls.setSubtitleOption(subtitleOption);
  24736. });
  24737. };
  24738. _proto.onBufferCodecs = function onBufferCodecs(event, data) {
  24739. var requiredTracks = data.tracks;
  24740. if (requiredTracks) {
  24741. this.requiredTracks = requiredTracks;
  24742. }
  24743. };
  24744. _proto.onBufferAppended = function onBufferAppended(event, data) {
  24745. this.checkBuffer();
  24746. };
  24747. _proto.onBufferFlushed = function onBufferFlushed(event, data) {
  24748. var playingItem = this.playingItem;
  24749. if (playingItem && !this.itemsMatch(playingItem, this.bufferingItem) && !this.isInterstitial(playingItem)) {
  24750. var timelinePos = this.timelinePos;
  24751. this.bufferedPos = timelinePos;
  24752. this.checkBuffer();
  24753. }
  24754. };
  24755. _proto.onBufferedToEnd = function onBufferedToEnd(event) {
  24756. // Buffered to post-roll
  24757. var interstitialEvents = this.schedule.events;
  24758. if (this.bufferedPos < Number.MAX_VALUE && interstitialEvents) {
  24759. for (var i = 0; i < interstitialEvents.length; i++) {
  24760. var interstitial = interstitialEvents[i];
  24761. if (interstitial.cue.post) {
  24762. var _this$schedule$items;
  24763. var scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  24764. var item = (_this$schedule$items = this.schedule.items) == null ? void 0 : _this$schedule$items[scheduleIndex];
  24765. if (this.isInterstitial(item) && this.eventItemsMatch(item, this.bufferingItem)) {
  24766. this.bufferedToItem(item, 0);
  24767. }
  24768. break;
  24769. }
  24770. }
  24771. this.bufferedPos = Number.MAX_VALUE;
  24772. }
  24773. };
  24774. _proto.onMediaEnded = function onMediaEnded(event) {
  24775. var playingItem = this.playingItem;
  24776. if (!this.playingLastItem && playingItem) {
  24777. var playingIndex = this.findItemIndex(playingItem);
  24778. this.setSchedulePosition(playingIndex + 1);
  24779. } else {
  24780. this.shouldPlay = false;
  24781. }
  24782. };
  24783. _proto.updateItem = function updateItem(previousItem, time) {
  24784. // find item in this.schedule.items;
  24785. var items = this.schedule.items;
  24786. if (previousItem && items) {
  24787. var index = this.findItemIndex(previousItem, time);
  24788. return items[index] || null;
  24789. }
  24790. return null;
  24791. };
  24792. _proto.trimInPlace = function trimInPlace(updatedItem, itemBeforeUpdate) {
  24793. var _this4 = this;
  24794. if (this.isInterstitial(updatedItem) && updatedItem.event.appendInPlace && itemBeforeUpdate.end - updatedItem.end > 0.25) {
  24795. updatedItem.event.assetList.forEach(function (asset, index) {
  24796. if (updatedItem.event.isAssetPastPlayoutLimit(index)) {
  24797. _this4.clearAssetPlayer(asset.identifier, null);
  24798. }
  24799. });
  24800. var flushStart = updatedItem.end + 0.25;
  24801. var bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, flushStart, 0);
  24802. if (bufferInfo.end > flushStart || (bufferInfo.nextStart || 0) > flushStart) {
  24803. this.attachPrimary(flushStart, null);
  24804. this.flushFrontBuffer(flushStart);
  24805. }
  24806. }
  24807. };
  24808. _proto.itemsMatch = function itemsMatch(a, b) {
  24809. return !!b && (a === b || a.event && b.event && this.eventItemsMatch(a, b) || !a.event && !b.event && this.findItemIndex(a) === this.findItemIndex(b));
  24810. };
  24811. _proto.eventItemsMatch = function eventItemsMatch(a, b) {
  24812. var _b$event;
  24813. return !!b && (a === b || a.event.identifier === ((_b$event = b.event) == null ? void 0 : _b$event.identifier));
  24814. };
  24815. _proto.findItemIndex = function findItemIndex(item, time) {
  24816. return item ? this.schedule.findItemIndex(item, time) : -1;
  24817. };
  24818. _proto.updateSchedule = function updateSchedule() {
  24819. var mediaSelection = this.mediaSelection;
  24820. if (!mediaSelection) {
  24821. return;
  24822. }
  24823. this.schedule.updateSchedule(mediaSelection, []);
  24824. }
  24825. // Schedule buffer control
  24826. ;
  24827. _proto.checkBuffer = function checkBuffer(starved) {
  24828. var items = this.schedule.items;
  24829. if (!items) {
  24830. return;
  24831. }
  24832. // Find when combined forward buffer change reaches next schedule segment
  24833. var bufferInfo = BufferHelper.bufferInfo(this.primaryMedia, this.timelinePos, 0);
  24834. if (starved) {
  24835. this.bufferedPos = this.timelinePos;
  24836. }
  24837. starved || (starved = bufferInfo.len < 1);
  24838. this.updateBufferedPos(bufferInfo.end, items, starved);
  24839. };
  24840. _proto.updateBufferedPos = function updateBufferedPos(bufferEnd, items, bufferIsEmpty) {
  24841. var schedule = this.schedule;
  24842. var bufferingItem = this.bufferingItem;
  24843. if (this.bufferedPos > bufferEnd) {
  24844. return;
  24845. }
  24846. if (items.length === 1 && this.itemsMatch(items[0], bufferingItem)) {
  24847. this.bufferedPos = bufferEnd;
  24848. return;
  24849. }
  24850. var playingItem = this.playingItem;
  24851. var playingIndex = this.findItemIndex(playingItem);
  24852. var bufferEndIndex = schedule.findItemIndexAtTime(bufferEnd);
  24853. if (this.bufferedPos < bufferEnd) {
  24854. var _nextItemToBuffer$eve, _bufferingItem$event;
  24855. var bufferingIndex = this.findItemIndex(bufferingItem);
  24856. var nextToBufferIndex = Math.min(bufferingIndex + 1, items.length - 1);
  24857. var nextItemToBuffer = items[nextToBufferIndex];
  24858. if (bufferEndIndex === -1 && bufferingItem && bufferEnd >= bufferingItem.end || (_nextItemToBuffer$eve = nextItemToBuffer.event) != null && _nextItemToBuffer$eve.appendInPlace && bufferEnd + 0.01 >= nextItemToBuffer.start) {
  24859. bufferEndIndex = nextToBufferIndex;
  24860. }
  24861. if (nextToBufferIndex - playingIndex > 1 && (bufferingItem == null ? void 0 : (_bufferingItem$event = bufferingItem.event) == null ? void 0 : _bufferingItem$event.appendInPlace) === false) {
  24862. // do not advance buffering item past Interstitial that requires source reset
  24863. return;
  24864. }
  24865. this.bufferedPos = bufferEnd;
  24866. if (bufferEndIndex > bufferingIndex && bufferEndIndex > playingIndex) {
  24867. this.bufferedToItem(nextItemToBuffer);
  24868. } else {
  24869. // allow more time than distance from edge for assets to load
  24870. var details = this.primaryDetails;
  24871. if (this.primaryLive && details && bufferEnd > details.edge - details.targetduration && nextItemToBuffer.start < details.edge + this.hls.config.interstitialLiveLookAhead && this.isInterstitial(nextItemToBuffer)) {
  24872. this.preloadAssets(nextItemToBuffer.event, 0);
  24873. }
  24874. }
  24875. } else if (bufferIsEmpty && playingItem && !this.itemsMatch(playingItem, bufferingItem)) {
  24876. if (bufferEndIndex === playingIndex) {
  24877. this.bufferedToItem(playingItem);
  24878. } else if (bufferEndIndex === playingIndex + 1) {
  24879. this.bufferedToItem(items[bufferEndIndex]);
  24880. }
  24881. }
  24882. };
  24883. _proto.assetsBuffered = function assetsBuffered(item, media) {
  24884. var _this5 = this;
  24885. var assetList = item.event.assetList;
  24886. if (assetList.length === 0) {
  24887. return false;
  24888. }
  24889. return !item.event.assetList.some(function (asset) {
  24890. var player = _this5.getAssetPlayer(asset.identifier);
  24891. return !(player != null && player.bufferedInPlaceToEnd(media));
  24892. });
  24893. };
  24894. _proto.setBufferingItem = function setBufferingItem(item) {
  24895. var _this6 = this;
  24896. var bufferingLast = this.bufferingItem;
  24897. var schedule = this.schedule;
  24898. if (!this.itemsMatch(item, bufferingLast)) {
  24899. var items = schedule.items,
  24900. events = schedule.events;
  24901. if (!items || !events) {
  24902. return bufferingLast;
  24903. }
  24904. var isInterstitial = this.isInterstitial(item);
  24905. var bufferingPlayer = this.getBufferingPlayer();
  24906. this.bufferingItem = item;
  24907. this.bufferedPos = Math.max(item.start, Math.min(item.end, this.timelinePos));
  24908. var timeRemaining = bufferingPlayer ? bufferingPlayer.remaining : bufferingLast ? bufferingLast.end - this.timelinePos : 0;
  24909. this.log("INTERSTITIALS_BUFFERED_TO_BOUNDARY " + segmentToString(item) + (bufferingLast ? " (" + timeRemaining.toFixed(2) + " remaining)" : ''));
  24910. if (!this.playbackDisabled) {
  24911. if (isInterstitial) {
  24912. // primary fragment loading will exit early in base-stream-controller while `bufferingItem` is set to an Interstitial block
  24913. item.event.assetList.forEach(function (asset) {
  24914. var player = _this6.getAssetPlayer(asset.identifier);
  24915. if (player) {
  24916. player.resumeBuffering();
  24917. }
  24918. });
  24919. } else {
  24920. this.hls.resumeBuffering();
  24921. this.playerQueue.forEach(function (player) {
  24922. return player.pauseBuffering();
  24923. });
  24924. }
  24925. }
  24926. this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY, {
  24927. events: events.slice(0),
  24928. schedule: items.slice(0),
  24929. bufferingIndex: this.findItemIndex(item),
  24930. playingIndex: this.findItemIndex(this.playingItem)
  24931. });
  24932. } else if (this.bufferingItem !== item) {
  24933. this.bufferingItem = item;
  24934. }
  24935. return bufferingLast;
  24936. };
  24937. _proto.bufferedToItem = function bufferedToItem(item, assetListIndex) {
  24938. if (assetListIndex === void 0) {
  24939. assetListIndex = 0;
  24940. }
  24941. var bufferingLast = this.setBufferingItem(item);
  24942. if (this.playbackDisabled) {
  24943. return;
  24944. }
  24945. if (this.isInterstitial(item)) {
  24946. // Ensure asset list is loaded
  24947. this.bufferedToEvent(item, assetListIndex);
  24948. } else if (bufferingLast !== null) {
  24949. // If primary player is detached, it is also stopped, restart loading at primary position
  24950. this.bufferingAsset = null;
  24951. var detachedData = this.detachedData;
  24952. if (detachedData) {
  24953. if (detachedData.mediaSource) {
  24954. var skipSeekToStartPosition = true;
  24955. this.attachPrimary(item.start, item, skipSeekToStartPosition);
  24956. } else {
  24957. this.preloadPrimary(item);
  24958. }
  24959. } else {
  24960. // If not detached seek to resumption point
  24961. this.preloadPrimary(item);
  24962. }
  24963. }
  24964. };
  24965. _proto.preloadPrimary = function preloadPrimary(item) {
  24966. var index = this.findItemIndex(item);
  24967. var timelinePos = this.getPrimaryResumption(item, index);
  24968. this.startLoadingPrimaryAt(timelinePos);
  24969. };
  24970. _proto.bufferedToEvent = function bufferedToEvent(item, assetListIndex) {
  24971. var interstitial = item.event;
  24972. var neverLoaded = interstitial.assetList.length === 0 && !interstitial.assetListLoader;
  24973. var playOnce = interstitial.cue.once;
  24974. if (neverLoaded || !playOnce) {
  24975. // Buffered to Interstitial boundary
  24976. var player = this.preloadAssets(interstitial, assetListIndex);
  24977. if (player != null && player.interstitial.appendInPlace) {
  24978. // If we have a player and asset list info, start buffering
  24979. var assetItem = interstitial.assetList[assetListIndex];
  24980. var media = this.primaryMedia;
  24981. if (assetItem && media) {
  24982. this.bufferAssetPlayer(player, media);
  24983. }
  24984. }
  24985. }
  24986. };
  24987. _proto.preloadAssets = function preloadAssets(interstitial, assetListIndex) {
  24988. var uri = interstitial.assetUrl;
  24989. var assetListLength = interstitial.assetList.length;
  24990. var neverLoaded = assetListLength === 0 && !interstitial.assetListLoader;
  24991. var playOnce = interstitial.cue.once;
  24992. if (neverLoaded) {
  24993. var timelineStart = interstitial.timelineStart;
  24994. if (interstitial.appendInPlace) {
  24995. var _playingItem$nextEven;
  24996. var playingItem = this.playingItem;
  24997. if (!this.isInterstitial(playingItem) && (playingItem == null ? void 0 : (_playingItem$nextEven = playingItem.nextEvent) == null ? void 0 : _playingItem$nextEven.identifier) === interstitial.identifier) {
  24998. this.flushFrontBuffer(timelineStart + 0.25);
  24999. }
  25000. }
  25001. var hlsStartOffset;
  25002. var liveStartPosition = 0;
  25003. if (!this.playingItem && this.primaryLive) {
  25004. liveStartPosition = this.hls.startPosition;
  25005. if (liveStartPosition === -1) {
  25006. liveStartPosition = this.hls.liveSyncPosition || 0;
  25007. }
  25008. }
  25009. if (liveStartPosition && !(interstitial.cue.pre || interstitial.cue.post)) {
  25010. var startOffset = liveStartPosition - timelineStart;
  25011. if (startOffset > 0) {
  25012. hlsStartOffset = Math.round(startOffset * 1000) / 1000;
  25013. }
  25014. }
  25015. this.log("Load interstitial asset " + (assetListIndex + 1) + "/" + (uri ? 1 : assetListLength) + " " + interstitial + (hlsStartOffset ? " live-start: " + liveStartPosition + " start-offset: " + hlsStartOffset : ''));
  25016. if (uri) {
  25017. return this.createAsset(interstitial, 0, 0, timelineStart, interstitial.duration, uri);
  25018. }
  25019. var assetListLoader = this.assetListLoader.loadAssetList(interstitial, hlsStartOffset);
  25020. if (assetListLoader) {
  25021. interstitial.assetListLoader = assetListLoader;
  25022. }
  25023. } else if (!playOnce && assetListLength) {
  25024. // Re-buffered to Interstitial boundary, re-create asset player(s)
  25025. for (var i = assetListIndex; i < assetListLength; i++) {
  25026. var asset = interstitial.assetList[i];
  25027. var playerIndex = this.getAssetPlayerQueueIndex(asset.identifier);
  25028. if ((playerIndex === -1 || this.playerQueue[playerIndex].destroyed) && !asset.error) {
  25029. this.createAssetPlayer(interstitial, asset, i);
  25030. }
  25031. }
  25032. return this.getAssetPlayer(interstitial.assetList[assetListIndex].identifier);
  25033. }
  25034. return null;
  25035. };
  25036. _proto.flushFrontBuffer = function flushFrontBuffer(startOffset) {
  25037. var _this7 = this;
  25038. // Force queued flushing of all buffers
  25039. var requiredTracks = this.requiredTracks;
  25040. if (!requiredTracks) {
  25041. return;
  25042. }
  25043. this.log("Removing front buffer starting at " + startOffset);
  25044. var sourceBufferNames = Object.keys(requiredTracks);
  25045. sourceBufferNames.forEach(function (type) {
  25046. _this7.hls.trigger(Events.BUFFER_FLUSHING, {
  25047. startOffset: startOffset,
  25048. endOffset: Infinity,
  25049. type: type
  25050. });
  25051. });
  25052. }
  25053. // Interstitial Asset Player control
  25054. ;
  25055. _proto.getAssetPlayerQueueIndex = function getAssetPlayerQueueIndex(assetId) {
  25056. var playerQueue = this.playerQueue;
  25057. for (var i = 0; i < playerQueue.length; i++) {
  25058. if (assetId === playerQueue[i].assetId) {
  25059. return i;
  25060. }
  25061. }
  25062. return -1;
  25063. };
  25064. _proto.getAssetPlayer = function getAssetPlayer(assetId) {
  25065. var index = this.getAssetPlayerQueueIndex(assetId);
  25066. return this.playerQueue[index] || null;
  25067. };
  25068. _proto.getBufferingPlayer = function getBufferingPlayer() {
  25069. var playerQueue = this.playerQueue,
  25070. primaryMedia = this.primaryMedia;
  25071. if (primaryMedia) {
  25072. for (var i = 0; i < playerQueue.length; i++) {
  25073. if (playerQueue[i].media === primaryMedia) {
  25074. return playerQueue[i];
  25075. }
  25076. }
  25077. }
  25078. return null;
  25079. };
  25080. _proto.createAsset = function createAsset(interstitial, assetListIndex, startOffset, timelineStart, duration, uri) {
  25081. var assetItem = {
  25082. parentIdentifier: interstitial.identifier,
  25083. identifier: generateAssetIdentifier(interstitial, uri, assetListIndex),
  25084. duration: duration,
  25085. startOffset: startOffset,
  25086. timelineStart: timelineStart,
  25087. uri: uri
  25088. };
  25089. return this.createAssetPlayer(interstitial, assetItem, assetListIndex);
  25090. };
  25091. _proto.createAssetPlayer = function createAssetPlayer(interstitial, assetItem, assetListIndex) {
  25092. var _this8 = this;
  25093. var primary = this.hls;
  25094. var userConfig = primary.userConfig;
  25095. var videoPreference = userConfig.videoPreference;
  25096. var currentLevel = primary.loadLevelObj || primary.levels[primary.currentLevel];
  25097. if (videoPreference || currentLevel) {
  25098. videoPreference = _extends({}, videoPreference);
  25099. if (currentLevel.videoCodec) {
  25100. videoPreference.videoCodec = currentLevel.videoCodec;
  25101. }
  25102. if (currentLevel.videoRange) {
  25103. videoPreference.allowedVideoRanges = [currentLevel.videoRange];
  25104. }
  25105. }
  25106. var selectedAudio = primary.audioTracks[primary.audioTrack];
  25107. var selectedSubtitle = primary.subtitleTracks[primary.subtitleTrack];
  25108. var startPosition = 0;
  25109. if (this.primaryLive || interstitial.appendInPlace) {
  25110. var timePastStart = this.timelinePos - assetItem.timelineStart;
  25111. if (timePastStart > 1) {
  25112. var duration = assetItem.duration;
  25113. if (duration && timePastStart < duration) {
  25114. startPosition = timePastStart;
  25115. }
  25116. }
  25117. }
  25118. var assetId = assetItem.identifier;
  25119. var playerConfig = _objectSpread2(_objectSpread2({}, userConfig), {}, {
  25120. autoStartLoad: true,
  25121. startFragPrefetch: true,
  25122. primarySessionId: primary.sessionId,
  25123. assetPlayerId: assetId,
  25124. abrEwmaDefaultEstimate: primary.bandwidthEstimate,
  25125. interstitialsController: undefined,
  25126. startPosition: startPosition,
  25127. liveDurationInfinity: false,
  25128. testBandwidth: false,
  25129. videoPreference: videoPreference,
  25130. audioPreference: selectedAudio || userConfig.audioPreference,
  25131. subtitlePreference: selectedSubtitle || userConfig.subtitlePreference
  25132. });
  25133. if (interstitial.appendInPlace) {
  25134. interstitial.appendInPlaceStarted = true;
  25135. if (assetItem.timelineStart) {
  25136. playerConfig.timelineOffset = assetItem.timelineStart;
  25137. }
  25138. }
  25139. var cmcd = playerConfig.cmcd;
  25140. if (cmcd != null && cmcd.sessionId && cmcd.contentId) {
  25141. playerConfig.cmcd = _extends({}, cmcd, {
  25142. contentId: hash(assetItem.uri)
  25143. });
  25144. }
  25145. if (this.getAssetPlayer(assetId)) {
  25146. this.warn("Duplicate date range identifier " + interstitial + " and asset " + assetId);
  25147. }
  25148. var player = new HlsAssetPlayer(this.HlsPlayerClass, playerConfig, interstitial, assetItem);
  25149. this.playerQueue.push(player);
  25150. interstitial.assetList[assetListIndex] = assetItem;
  25151. // Listen for LevelDetails and PTS change to update duration
  25152. var updateAssetPlayerDetails = function updateAssetPlayerDetails(details) {
  25153. if (details.live) {
  25154. var error = new Error("Interstitials MUST be VOD assets " + interstitial);
  25155. var errorData = {
  25156. fatal: true,
  25157. type: ErrorTypes.OTHER_ERROR,
  25158. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25159. error: error
  25160. };
  25161. _this8.handleAssetItemError(errorData, interstitial, _this8.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  25162. return;
  25163. }
  25164. // Get time at end of last fragment
  25165. var duration = details.edge - details.fragmentStart;
  25166. var currentAssetDuration = assetItem.duration;
  25167. if (currentAssetDuration === null || duration > currentAssetDuration) {
  25168. _this8.log("Interstitial asset \"" + assetId + "\" duration change " + currentAssetDuration + " > " + duration);
  25169. assetItem.duration = duration;
  25170. // Update schedule with new event and asset duration
  25171. _this8.updateSchedule();
  25172. }
  25173. };
  25174. player.on(Events.LEVEL_UPDATED, function (event, _ref) {
  25175. var details = _ref.details;
  25176. return updateAssetPlayerDetails(details);
  25177. });
  25178. player.on(Events.LEVEL_PTS_UPDATED, function (event, _ref2) {
  25179. var details = _ref2.details;
  25180. return updateAssetPlayerDetails(details);
  25181. });
  25182. var _onBufferCodecs = function onBufferCodecs(event, data) {
  25183. var inQueuPlayer = _this8.getAssetPlayer(assetId);
  25184. if (inQueuPlayer && data.tracks) {
  25185. inQueuPlayer.off(Events.BUFFER_CODECS, _onBufferCodecs);
  25186. inQueuPlayer.tracks = data.tracks;
  25187. var media = _this8.primaryMedia;
  25188. if (_this8.bufferingAsset === inQueuPlayer.assetItem && media && !inQueuPlayer.media) {
  25189. _this8.bufferAssetPlayer(inQueuPlayer, media);
  25190. }
  25191. }
  25192. };
  25193. player.on(Events.BUFFER_CODECS, _onBufferCodecs);
  25194. var bufferedToEnd = function bufferedToEnd() {
  25195. var _this8$schedule$items;
  25196. var inQueuPlayer = _this8.getAssetPlayer(assetId);
  25197. _this8.log("buffered to end of asset " + inQueuPlayer);
  25198. if (!inQueuPlayer) {
  25199. return;
  25200. }
  25201. // Preload at end of asset
  25202. var scheduleIndex = _this8.schedule.findEventIndex(interstitial.identifier);
  25203. var item = (_this8$schedule$items = _this8.schedule.items) == null ? void 0 : _this8$schedule$items[scheduleIndex];
  25204. if (_this8.isInterstitial(item)) {
  25205. var _assetListIndex = interstitial.findAssetIndex(assetItem);
  25206. var nextAssetIndex = getNextAssetIndex(interstitial, _assetListIndex);
  25207. if (!interstitial.isAssetPastPlayoutLimit(nextAssetIndex)) {
  25208. _this8.bufferedToItem(item, nextAssetIndex);
  25209. } else {
  25210. var _this8$schedule$items2;
  25211. var nextItem = (_this8$schedule$items2 = _this8.schedule.items) == null ? void 0 : _this8$schedule$items2[scheduleIndex + 1];
  25212. if (nextItem) {
  25213. _this8.bufferedToItem(nextItem);
  25214. }
  25215. }
  25216. }
  25217. };
  25218. player.on(Events.BUFFERED_TO_END, bufferedToEnd);
  25219. var endedWithAssetIndex = function endedWithAssetIndex(assetIndex) {
  25220. return function () {
  25221. var inQueuPlayer = _this8.getAssetPlayer(assetId);
  25222. if (!inQueuPlayer) {
  25223. return;
  25224. }
  25225. _this8.shouldPlay = true;
  25226. var scheduleIndex = _this8.schedule.findEventIndex(interstitial.identifier);
  25227. _this8.advanceAfterAssetEnded(interstitial, scheduleIndex, assetIndex);
  25228. };
  25229. };
  25230. player.once(Events.MEDIA_ENDED, endedWithAssetIndex(assetListIndex));
  25231. player.once(Events.PLAYOUT_LIMIT_REACHED, endedWithAssetIndex(Infinity));
  25232. player.on(Events.ERROR, function (event, data) {
  25233. var inQueuPlayer = _this8.getAssetPlayer(assetId);
  25234. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  25235. if (inQueuPlayer != null && inQueuPlayer.media) {
  25236. var assetCurrentTime = inQueuPlayer.currentTime;
  25237. var distanceFromEnd = inQueuPlayer.duration - assetCurrentTime;
  25238. if (assetCurrentTime && interstitial.appendInPlace && distanceFromEnd / inQueuPlayer.media.playbackRate < 0.5) {
  25239. _this8.log("Advancing buffer past end of asset " + assetId + " " + interstitial + " at " + inQueuPlayer.media.currentTime);
  25240. bufferedToEnd();
  25241. } else {
  25242. _this8.warn("Stalled at " + assetCurrentTime + " of " + (assetCurrentTime + distanceFromEnd) + " in asset " + assetId + " " + interstitial);
  25243. _this8.onTimeupdate();
  25244. _this8.checkBuffer(true);
  25245. }
  25246. }
  25247. return;
  25248. }
  25249. _this8.handleAssetItemError(data, interstitial, _this8.schedule.findEventIndex(interstitial.identifier), assetListIndex, "Asset player error " + data.error + " " + interstitial);
  25250. });
  25251. player.on(Events.DESTROYING, function () {
  25252. var inQueuPlayer = _this8.getAssetPlayer(assetId);
  25253. if (!inQueuPlayer) {
  25254. return;
  25255. }
  25256. var error = new Error("Asset player destroyed unexpectedly " + assetId);
  25257. var errorData = {
  25258. fatal: true,
  25259. type: ErrorTypes.OTHER_ERROR,
  25260. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25261. error: error
  25262. };
  25263. _this8.handleAssetItemError(errorData, interstitial, _this8.schedule.findEventIndex(interstitial.identifier), assetListIndex, error.message);
  25264. });
  25265. this.log("INTERSTITIAL_ASSET_PLAYER_CREATED " + eventAssetToString(assetItem));
  25266. this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED, {
  25267. asset: assetItem,
  25268. assetListIndex: assetListIndex,
  25269. event: interstitial,
  25270. player: player
  25271. });
  25272. return player;
  25273. };
  25274. _proto.clearInterstitial = function clearInterstitial(interstitial, toSegment) {
  25275. var _this9 = this;
  25276. interstitial.assetList.forEach(function (asset) {
  25277. _this9.clearAssetPlayer(asset.identifier, toSegment);
  25278. });
  25279. // Remove asset list and resolved duration
  25280. interstitial.reset();
  25281. };
  25282. _proto.resetAssetPlayer = function resetAssetPlayer(assetId) {
  25283. // Reset asset player so that it's timeline can be adjusted without reloading the MVP
  25284. var playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25285. if (playerIndex !== -1) {
  25286. this.log("reset asset player \"" + assetId + "\" after error");
  25287. var player = this.playerQueue[playerIndex];
  25288. this.transferMediaFromPlayer(player, null);
  25289. player.resetDetails();
  25290. }
  25291. };
  25292. _proto.clearAssetPlayer = function clearAssetPlayer(assetId, toSegment) {
  25293. var playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25294. if (playerIndex !== -1) {
  25295. this.log("clear asset player \"" + assetId + "\" toSegment: " + (toSegment ? segmentToString(toSegment) : toSegment));
  25296. var player = this.playerQueue[playerIndex];
  25297. this.transferMediaFromPlayer(player, toSegment);
  25298. this.playerQueue.splice(playerIndex, 1);
  25299. player.destroy();
  25300. }
  25301. };
  25302. _proto.emptyPlayerQueue = function emptyPlayerQueue() {
  25303. var player;
  25304. while (player = this.playerQueue.pop()) {
  25305. player.destroy();
  25306. }
  25307. this.playerQueue = [];
  25308. };
  25309. _proto.startAssetPlayer = function startAssetPlayer(player, assetListIndex, scheduleItems, scheduleIndex, media) {
  25310. var interstitial = player.interstitial,
  25311. assetItem = player.assetItem,
  25312. assetId = player.assetId;
  25313. var assetListLength = interstitial.assetList.length;
  25314. var playingAsset = this.playingAsset;
  25315. this.endedAsset = null;
  25316. this.playingAsset = assetItem;
  25317. if (!playingAsset || playingAsset.identifier !== assetId) {
  25318. if (playingAsset) {
  25319. // Exiting another Interstitial asset
  25320. this.clearAssetPlayer(playingAsset.identifier, scheduleItems[scheduleIndex]);
  25321. delete playingAsset.error;
  25322. }
  25323. this.log("INTERSTITIAL_ASSET_STARTED " + (assetListIndex + 1) + "/" + assetListLength + " " + eventAssetToString(assetItem));
  25324. this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED, {
  25325. asset: assetItem,
  25326. assetListIndex: assetListIndex,
  25327. event: interstitial,
  25328. schedule: scheduleItems.slice(0),
  25329. scheduleIndex: scheduleIndex,
  25330. player: player
  25331. });
  25332. }
  25333. // detach media and attach to interstitial player if it does not have another element attached
  25334. this.bufferAssetPlayer(player, media);
  25335. };
  25336. _proto.bufferAssetPlayer = function bufferAssetPlayer(player, media) {
  25337. var _this$schedule$items2, _this$detachedData4;
  25338. var interstitial = player.interstitial,
  25339. assetItem = player.assetItem;
  25340. var scheduleIndex = this.schedule.findEventIndex(interstitial.identifier);
  25341. var item = (_this$schedule$items2 = this.schedule.items) == null ? void 0 : _this$schedule$items2[scheduleIndex];
  25342. if (!item) {
  25343. return;
  25344. }
  25345. this.setBufferingItem(item);
  25346. this.bufferingAsset = assetItem;
  25347. var bufferingPlayer = this.getBufferingPlayer();
  25348. if (bufferingPlayer === player) {
  25349. return;
  25350. }
  25351. var appendInPlaceNext = interstitial.appendInPlace;
  25352. if (appendInPlaceNext && (bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial.appendInPlace) === false) {
  25353. // Media is detached and not available to append in place
  25354. return;
  25355. }
  25356. var activeTracks = (bufferingPlayer == null ? void 0 : bufferingPlayer.tracks) || ((_this$detachedData4 = this.detachedData) == null ? void 0 : _this$detachedData4.tracks) || this.requiredTracks;
  25357. if (appendInPlaceNext && assetItem !== this.playingAsset) {
  25358. // Do not buffer another item if tracks are unknown or incompatible
  25359. if (!player.tracks) {
  25360. return;
  25361. }
  25362. if (activeTracks && !isCompatibleTrackChange(activeTracks, player.tracks)) {
  25363. var error = new Error("Asset " + eventAssetToString(assetItem) + " SourceBuffer tracks ('" + Object.keys(player.tracks) + "') are not compatible with primary content tracks ('" + Object.keys(activeTracks) + "')");
  25364. var errorData = {
  25365. fatal: true,
  25366. type: ErrorTypes.OTHER_ERROR,
  25367. details: ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,
  25368. error: error
  25369. };
  25370. var assetListIndex = interstitial.findAssetIndex(assetItem);
  25371. this.handleAssetItemError(errorData, interstitial, scheduleIndex, assetListIndex, error.message);
  25372. return;
  25373. }
  25374. }
  25375. this.transferMediaTo(player, media);
  25376. };
  25377. _proto.handleAssetItemError = function handleAssetItemError(data, interstitial, scheduleIndex, assetListIndex, errorMessage) {
  25378. if (data.details === ErrorDetails.BUFFER_STALLED_ERROR) {
  25379. return;
  25380. }
  25381. var assetItem = interstitial.assetList[assetListIndex];
  25382. this.warn("INTERSTITIAL_ASSET_ERROR " + (assetItem ? eventAssetToString(assetItem) : assetItem) + " " + data.error);
  25383. var assetId = assetItem == null ? void 0 : assetItem.identifier;
  25384. var playerIndex = this.getAssetPlayerQueueIndex(assetId);
  25385. var player = this.playerQueue[playerIndex] || null;
  25386. var items = this.schedule.items;
  25387. var interstitialAssetError = _extends({}, data, {
  25388. fatal: false,
  25389. errorAction: createDoNothingErrorAction(true),
  25390. asset: assetItem,
  25391. assetListIndex: assetListIndex,
  25392. event: interstitial,
  25393. schedule: items,
  25394. scheduleIndex: scheduleIndex,
  25395. player: player
  25396. });
  25397. this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR, interstitialAssetError);
  25398. if (!data.fatal) {
  25399. return;
  25400. }
  25401. var playingAsset = this.playingAsset;
  25402. var error = new Error(errorMessage);
  25403. if (assetItem) {
  25404. this.clearAssetPlayer(assetId, null);
  25405. assetItem.error = error;
  25406. }
  25407. // If all assets in interstitial fail, mark the interstitial with an error
  25408. if (!interstitial.assetList.some(function (asset) {
  25409. return !asset.error;
  25410. })) {
  25411. interstitial.error = error;
  25412. } else {
  25413. // Reset level details and reload/parse media playlists to align with updated schedule
  25414. for (var i = assetListIndex; i < interstitial.assetList.length; i++) {
  25415. this.resetAssetPlayer(interstitial.assetList[i].identifier);
  25416. }
  25417. this.updateSchedule();
  25418. }
  25419. if (interstitial.error) {
  25420. this.primaryFallback(interstitial);
  25421. } else if (playingAsset && playingAsset.identifier === assetId) {
  25422. this.advanceAfterAssetEnded(interstitial, scheduleIndex, assetListIndex);
  25423. }
  25424. };
  25425. _proto.primaryFallback = function primaryFallback(interstitial) {
  25426. // Fallback to Primary by on current or future events by updating schedule to skip errored interstitials/assets
  25427. var flushStart = interstitial.timelineStart;
  25428. var playingItem = this.effectivePlayingItem;
  25429. // Update schedule now that interstitial/assets are flagged with `error` for fallback
  25430. this.updateSchedule();
  25431. if (playingItem) {
  25432. this.log("Fallback to primary from event \"" + interstitial.identifier + "\" start: " + flushStart + " pos: " + this.timelinePos + " playing: " + (playingItem ? segmentToString(playingItem) : '<none>') + " error: " + interstitial.error);
  25433. var timelinePos = this.timelinePos;
  25434. if (timelinePos === -1) {
  25435. timelinePos = this.hls.startPosition;
  25436. }
  25437. var newPlayingItem = this.updateItem(playingItem, timelinePos);
  25438. if (this.itemsMatch(playingItem, newPlayingItem)) {
  25439. this.clearInterstitial(interstitial, null);
  25440. }
  25441. if (interstitial.appendInPlace) {
  25442. this.attachPrimary(flushStart, null);
  25443. this.flushFrontBuffer(flushStart);
  25444. }
  25445. var scheduleIndex = this.schedule.findItemIndexAtTime(timelinePos);
  25446. this.setSchedulePosition(scheduleIndex);
  25447. } else {
  25448. this.checkStart();
  25449. }
  25450. }
  25451. // Asset List loading
  25452. ;
  25453. _proto.onAssetListLoaded = function onAssetListLoaded(event, data) {
  25454. var _this0 = this,
  25455. _this$bufferingItem;
  25456. var interstitial = data.event;
  25457. var interstitialId = interstitial.identifier;
  25458. var assets = data.assetListResponse.ASSETS;
  25459. if (!this.schedule.hasEvent(interstitialId)) {
  25460. // Interstitial with id was removed
  25461. return;
  25462. }
  25463. var eventStart = interstitial.timelineStart;
  25464. var previousDuration = interstitial.duration;
  25465. var sumDuration = 0;
  25466. assets.forEach(function (asset, assetListIndex) {
  25467. var duration = parseFloat(asset.DURATION);
  25468. _this0.createAsset(interstitial, assetListIndex, sumDuration, eventStart + sumDuration, duration, asset.URI);
  25469. sumDuration += duration;
  25470. });
  25471. interstitial.duration = sumDuration;
  25472. this.log("Loaded asset-list with duration: " + sumDuration + " (was: " + previousDuration + ") " + interstitial);
  25473. var waitingItem = this.waitingItem;
  25474. var waitingForItem = (waitingItem == null ? void 0 : waitingItem.event.identifier) === interstitialId;
  25475. // Update schedule now that asset.DURATION(s) are parsed
  25476. this.updateSchedule();
  25477. var bufferingEvent = (_this$bufferingItem = this.bufferingItem) == null ? void 0 : _this$bufferingItem.event;
  25478. // If buffer reached Interstitial, start buffering first asset
  25479. if (waitingForItem) {
  25480. var _this$schedule$items3;
  25481. // Advance schedule when waiting for asset list data to play
  25482. var scheduleIndex = this.schedule.findEventIndex(interstitialId);
  25483. var item = (_this$schedule$items3 = this.schedule.items) == null ? void 0 : _this$schedule$items3[scheduleIndex];
  25484. if (item) {
  25485. if (!this.playingItem && this.timelinePos > item.end) {
  25486. // Abandon if new duration is reduced enough to land playback in primary start
  25487. var index = this.schedule.findItemIndexAtTime(this.timelinePos);
  25488. if (index !== scheduleIndex) {
  25489. interstitial.error = new Error("Interstitial no longer within playback range " + this.timelinePos + " " + interstitial);
  25490. this.primaryFallback(interstitial);
  25491. return;
  25492. }
  25493. }
  25494. this.setBufferingItem(item);
  25495. }
  25496. this.setSchedulePosition(scheduleIndex);
  25497. } else if ((bufferingEvent == null ? void 0 : bufferingEvent.identifier) === interstitialId && bufferingEvent.appendInPlace) {
  25498. // If buffering (but not playback) has reached this item transfer media-source
  25499. var assetItem = interstitial.assetList[0];
  25500. var player = this.getAssetPlayer(assetItem.identifier);
  25501. var media = this.primaryMedia;
  25502. if (assetItem && player && media) {
  25503. this.bufferAssetPlayer(player, media);
  25504. }
  25505. }
  25506. };
  25507. _proto.onError = function onError(event, data) {
  25508. switch (data.details) {
  25509. case ErrorDetails.ASSET_LIST_PARSING_ERROR:
  25510. case ErrorDetails.ASSET_LIST_LOAD_ERROR:
  25511. case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:
  25512. {
  25513. var interstitial = data.interstitial;
  25514. if (interstitial) {
  25515. this.primaryFallback(interstitial);
  25516. }
  25517. break;
  25518. }
  25519. case ErrorDetails.BUFFER_STALLED_ERROR:
  25520. {
  25521. this.onTimeupdate();
  25522. this.checkBuffer(true);
  25523. break;
  25524. }
  25525. }
  25526. };
  25527. return _createClass(InterstitialsController, [{
  25528. key: "interstitialsManager",
  25529. get: function get() {
  25530. if (!this.manager) {
  25531. if (!this.hls) {
  25532. return null;
  25533. }
  25534. var c = this;
  25535. var effectiveBufferingItem = function effectiveBufferingItem() {
  25536. return c.bufferingItem || c.waitingItem;
  25537. };
  25538. var getAssetPlayer = function getAssetPlayer(asset) {
  25539. return asset ? c.getAssetPlayer(asset.identifier) : asset;
  25540. };
  25541. var getMappedTime = function getMappedTime(item, timelineType, asset, controllerField, assetPlayerField) {
  25542. if (item) {
  25543. var time = item[timelineType].start;
  25544. var interstitial = item.event;
  25545. if (interstitial) {
  25546. if (timelineType === 'playout' || interstitial.timelineOccupancy !== TimelineOccupancy.Point) {
  25547. var assetPlayer = getAssetPlayer(asset);
  25548. if ((assetPlayer == null ? void 0 : assetPlayer.interstitial) === interstitial) {
  25549. time += assetPlayer.assetItem.startOffset + assetPlayer[assetPlayerField];
  25550. }
  25551. }
  25552. } else {
  25553. var value = controllerField === 'bufferedPos' ? getBufferedEnd() : c[controllerField];
  25554. time += value - item.start;
  25555. }
  25556. return time;
  25557. }
  25558. return 0;
  25559. };
  25560. var findMappedTime = function findMappedTime(primaryTime, timelineType) {
  25561. if (primaryTime !== 0 && timelineType !== 'primary' && c.schedule.length) {
  25562. var _c$schedule$items;
  25563. var index = c.schedule.findItemIndexAtTime(primaryTime);
  25564. var item = (_c$schedule$items = c.schedule.items) == null ? void 0 : _c$schedule$items[index];
  25565. if (item) {
  25566. var diff = item[timelineType].start - item.start;
  25567. return primaryTime + diff;
  25568. }
  25569. }
  25570. return primaryTime;
  25571. };
  25572. var getBufferedEnd = function getBufferedEnd() {
  25573. var value = c.bufferedPos;
  25574. if (value === Number.MAX_VALUE) {
  25575. return getMappedDuration('primary');
  25576. }
  25577. return Math.max(value, 0);
  25578. };
  25579. var getMappedDuration = function getMappedDuration(timelineType) {
  25580. var _c$primaryDetails;
  25581. if ((_c$primaryDetails = c.primaryDetails) != null && _c$primaryDetails.live) {
  25582. // return end of last event item or playlist
  25583. return c.primaryDetails.edge;
  25584. }
  25585. return c.schedule.durations[timelineType];
  25586. };
  25587. var seekTo = function seekTo(time, timelineType) {
  25588. var _item$event, _c$schedule$items2;
  25589. var item = c.effectivePlayingItem;
  25590. if (item != null && (_item$event = item.event) != null && _item$event.restrictions.skip) {
  25591. return;
  25592. }
  25593. c.log("seek to " + time + " \"" + timelineType + "\"");
  25594. var playingItem = c.effectivePlayingItem;
  25595. var targetIndex = c.schedule.findItemIndexAtTime(time, timelineType);
  25596. var targetItem = (_c$schedule$items2 = c.schedule.items) == null ? void 0 : _c$schedule$items2[targetIndex];
  25597. var bufferingPlayer = c.getBufferingPlayer();
  25598. var bufferingInterstitial = bufferingPlayer == null ? void 0 : bufferingPlayer.interstitial;
  25599. var appendInPlace = bufferingInterstitial == null ? void 0 : bufferingInterstitial.appendInPlace;
  25600. var seekInItem = playingItem && c.itemsMatch(playingItem, targetItem);
  25601. if (playingItem && (appendInPlace || seekInItem)) {
  25602. // seek in asset player or primary media (appendInPlace)
  25603. var assetPlayer = getAssetPlayer(c.playingAsset);
  25604. var media = (assetPlayer == null ? void 0 : assetPlayer.media) || c.primaryMedia;
  25605. if (media) {
  25606. var currentTime = timelineType === 'primary' ? media.currentTime : getMappedTime(playingItem, timelineType, c.playingAsset, 'timelinePos', 'currentTime');
  25607. var diff = time - currentTime;
  25608. var seekToTime = (appendInPlace ? currentTime : media.currentTime) + diff;
  25609. if (seekToTime >= 0 && (!assetPlayer || appendInPlace || seekToTime <= assetPlayer.duration)) {
  25610. media.currentTime = seekToTime;
  25611. return;
  25612. }
  25613. }
  25614. }
  25615. // seek out of item or asset
  25616. if (targetItem) {
  25617. var _seekToTime = time;
  25618. if (timelineType !== 'primary') {
  25619. var primarySegmentStart = targetItem[timelineType].start;
  25620. var _diff = time - primarySegmentStart;
  25621. _seekToTime = targetItem.start + _diff;
  25622. }
  25623. var targetIsPrimary = !c.isInterstitial(targetItem);
  25624. if ((!c.isInterstitial(playingItem) || playingItem.event.appendInPlace) && (targetIsPrimary || targetItem.event.appendInPlace)) {
  25625. var _media2 = c.media || (appendInPlace ? bufferingPlayer == null ? void 0 : bufferingPlayer.media : null);
  25626. if (_media2) {
  25627. _media2.currentTime = _seekToTime;
  25628. }
  25629. } else if (playingItem) {
  25630. // check if an Interstitial between the current item and target item has an X-RESTRICT JUMP restriction
  25631. var playingIndex = c.findItemIndex(playingItem);
  25632. if (targetIndex > playingIndex) {
  25633. var jumpIndex = c.schedule.findJumpRestrictedIndex(playingIndex + 1, targetIndex);
  25634. if (jumpIndex > playingIndex) {
  25635. c.setSchedulePosition(jumpIndex);
  25636. return;
  25637. }
  25638. }
  25639. var assetIndex = 0;
  25640. if (targetIsPrimary) {
  25641. c.timelinePos = _seekToTime;
  25642. c.checkBuffer();
  25643. } else {
  25644. var _targetItem$event;
  25645. var assetList = targetItem == null ? void 0 : (_targetItem$event = targetItem.event) == null ? void 0 : _targetItem$event.assetList;
  25646. if (assetList) {
  25647. var eventTime = time - (targetItem[timelineType] || targetItem).start;
  25648. for (var i = assetList.length; i--;) {
  25649. var asset = assetList[i];
  25650. if (asset.duration && eventTime >= asset.startOffset && eventTime < asset.startOffset + asset.duration) {
  25651. assetIndex = i;
  25652. break;
  25653. }
  25654. }
  25655. }
  25656. }
  25657. c.setSchedulePosition(targetIndex, assetIndex);
  25658. }
  25659. }
  25660. };
  25661. var getActiveInterstitial = function getActiveInterstitial() {
  25662. var playingItem = c.effectivePlayingItem;
  25663. if (c.isInterstitial(playingItem)) {
  25664. return playingItem;
  25665. }
  25666. var bufferingItem = effectiveBufferingItem();
  25667. if (c.isInterstitial(bufferingItem)) {
  25668. return bufferingItem;
  25669. }
  25670. return null;
  25671. };
  25672. var interstitialPlayer = {
  25673. get currentTime() {
  25674. var interstitialItem = getActiveInterstitial();
  25675. var playingItem = c.effectivePlayingItem;
  25676. if (playingItem && playingItem === interstitialItem) {
  25677. return getMappedTime(playingItem, 'playout', c.effectivePlayingAsset, 'timelinePos', 'currentTime') - playingItem.playout.start;
  25678. }
  25679. return 0;
  25680. },
  25681. set currentTime(time) {
  25682. var interstitialItem = getActiveInterstitial();
  25683. var playingItem = c.effectivePlayingItem;
  25684. if (playingItem && playingItem === interstitialItem) {
  25685. seekTo(time + playingItem.playout.start, 'playout');
  25686. }
  25687. },
  25688. get duration() {
  25689. var interstitialItem = getActiveInterstitial();
  25690. if (interstitialItem) {
  25691. return interstitialItem.playout.end - interstitialItem.playout.start;
  25692. }
  25693. return 0;
  25694. },
  25695. get assetPlayers() {
  25696. var _getActiveInterstitia;
  25697. var assetList = (_getActiveInterstitia = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia.event.assetList;
  25698. if (assetList) {
  25699. return assetList.map(function (asset) {
  25700. return c.getAssetPlayer(asset.identifier);
  25701. });
  25702. }
  25703. return [];
  25704. },
  25705. get playingIndex() {
  25706. var _getActiveInterstitia2;
  25707. var interstitial = (_getActiveInterstitia2 = getActiveInterstitial()) == null ? void 0 : _getActiveInterstitia2.event;
  25708. if (interstitial && c.effectivePlayingAsset) {
  25709. return interstitial.findAssetIndex(c.effectivePlayingAsset);
  25710. }
  25711. return -1;
  25712. },
  25713. get scheduleItem() {
  25714. return getActiveInterstitial();
  25715. }
  25716. };
  25717. this.manager = {
  25718. get events() {
  25719. var _c$schedule, _c$schedule$events;
  25720. return ((_c$schedule = c.schedule) == null ? void 0 : (_c$schedule$events = _c$schedule.events) == null ? void 0 : _c$schedule$events.slice(0)) || [];
  25721. },
  25722. get schedule() {
  25723. var _c$schedule2, _c$schedule2$items;
  25724. return ((_c$schedule2 = c.schedule) == null ? void 0 : (_c$schedule2$items = _c$schedule2.items) == null ? void 0 : _c$schedule2$items.slice(0)) || [];
  25725. },
  25726. get interstitialPlayer() {
  25727. if (getActiveInterstitial()) {
  25728. return interstitialPlayer;
  25729. }
  25730. return null;
  25731. },
  25732. get playerQueue() {
  25733. return c.playerQueue.slice(0);
  25734. },
  25735. get bufferingAsset() {
  25736. return c.bufferingAsset;
  25737. },
  25738. get bufferingItem() {
  25739. return effectiveBufferingItem();
  25740. },
  25741. get bufferingIndex() {
  25742. var item = effectiveBufferingItem();
  25743. return c.findItemIndex(item);
  25744. },
  25745. get playingAsset() {
  25746. return c.effectivePlayingAsset;
  25747. },
  25748. get playingItem() {
  25749. return c.effectivePlayingItem;
  25750. },
  25751. get playingIndex() {
  25752. var item = c.effectivePlayingItem;
  25753. return c.findItemIndex(item);
  25754. },
  25755. primary: {
  25756. get bufferedEnd() {
  25757. return getBufferedEnd();
  25758. },
  25759. get currentTime() {
  25760. var timelinePos = c.timelinePos;
  25761. return timelinePos > 0 ? timelinePos : 0;
  25762. },
  25763. set currentTime(time) {
  25764. seekTo(time, 'primary');
  25765. },
  25766. get duration() {
  25767. return getMappedDuration('primary');
  25768. },
  25769. get seekableStart() {
  25770. var _c$primaryDetails2;
  25771. return ((_c$primaryDetails2 = c.primaryDetails) == null ? void 0 : _c$primaryDetails2.fragmentStart) || 0;
  25772. }
  25773. },
  25774. integrated: {
  25775. get bufferedEnd() {
  25776. return getMappedTime(effectiveBufferingItem(), 'integrated', c.bufferingAsset, 'bufferedPos', 'bufferedEnd');
  25777. },
  25778. get currentTime() {
  25779. return getMappedTime(c.effectivePlayingItem, 'integrated', c.effectivePlayingAsset, 'timelinePos', 'currentTime');
  25780. },
  25781. set currentTime(time) {
  25782. seekTo(time, 'integrated');
  25783. },
  25784. get duration() {
  25785. return getMappedDuration('integrated');
  25786. },
  25787. get seekableStart() {
  25788. var _c$primaryDetails3;
  25789. return findMappedTime(((_c$primaryDetails3 = c.primaryDetails) == null ? void 0 : _c$primaryDetails3.fragmentStart) || 0, 'integrated');
  25790. }
  25791. },
  25792. skip: function skip() {
  25793. var item = c.effectivePlayingItem;
  25794. var event = item == null ? void 0 : item.event;
  25795. if (event && !event.restrictions.skip) {
  25796. var index = c.findItemIndex(item);
  25797. if (event.appendInPlace) {
  25798. var time = item.playout.start + item.event.duration;
  25799. seekTo(time + 0.001, 'playout');
  25800. } else {
  25801. c.advanceAfterAssetEnded(event, index, Infinity);
  25802. }
  25803. }
  25804. }
  25805. };
  25806. }
  25807. return this.manager;
  25808. }
  25809. // Schedule getters
  25810. }, {
  25811. key: "effectivePlayingItem",
  25812. get: function get() {
  25813. return this.waitingItem || this.playingItem || this.endedItem;
  25814. }
  25815. }, {
  25816. key: "effectivePlayingAsset",
  25817. get: function get() {
  25818. return this.playingAsset || this.endedAsset;
  25819. }
  25820. }, {
  25821. key: "playingLastItem",
  25822. get: function get() {
  25823. var _this$schedule;
  25824. var playingItem = this.playingItem;
  25825. var items = (_this$schedule = this.schedule) == null ? void 0 : _this$schedule.items;
  25826. if (!this.playbackStarted || !playingItem || !items) {
  25827. return false;
  25828. }
  25829. return this.findItemIndex(playingItem) === items.length - 1;
  25830. }
  25831. }, {
  25832. key: "playbackStarted",
  25833. get: function get() {
  25834. return this.effectivePlayingItem !== null;
  25835. }
  25836. // Media getters and event callbacks
  25837. }, {
  25838. key: "currentTime",
  25839. get: function get() {
  25840. var _this$bufferingItem2, _this$bufferingItem2$, _media3;
  25841. if (this.mediaSelection === null) {
  25842. // Do not advance before schedule is known
  25843. return undefined;
  25844. }
  25845. // Ignore currentTime when detached for Interstitial playback with source reset
  25846. var queuedForPlayback = this.waitingItem || this.playingItem;
  25847. if (this.isInterstitial(queuedForPlayback) && !queuedForPlayback.event.appendInPlace) {
  25848. return undefined;
  25849. }
  25850. var media = this.media;
  25851. if (!media && (_this$bufferingItem2 = this.bufferingItem) != null && (_this$bufferingItem2$ = _this$bufferingItem2.event) != null && _this$bufferingItem2$.appendInPlace) {
  25852. // Observe detached media currentTime when appending in place
  25853. media = this.primaryMedia;
  25854. }
  25855. var currentTime = (_media3 = media) == null ? void 0 : _media3.currentTime;
  25856. if (currentTime === undefined || !isFiniteNumber(currentTime)) {
  25857. return undefined;
  25858. }
  25859. return currentTime;
  25860. }
  25861. }, {
  25862. key: "primaryMedia",
  25863. get: function get() {
  25864. var _this$detachedData5;
  25865. return this.media || ((_this$detachedData5 = this.detachedData) == null ? void 0 : _this$detachedData5.media) || null;
  25866. }
  25867. }, {
  25868. key: "playbackDisabled",
  25869. get: function get() {
  25870. return this.hls.config.enableInterstitialPlayback === false;
  25871. }
  25872. }, {
  25873. key: "primaryDetails",
  25874. get: function get() {
  25875. var _this$mediaSelection, _this$mediaSelection$;
  25876. return (_this$mediaSelection = this.mediaSelection) == null ? void 0 : (_this$mediaSelection$ = _this$mediaSelection.main) == null ? void 0 : _this$mediaSelection$.details;
  25877. }
  25878. }, {
  25879. key: "primaryLive",
  25880. get: function get() {
  25881. var _this$primaryDetails;
  25882. return !!((_this$primaryDetails = this.primaryDetails) != null && _this$primaryDetails.live);
  25883. }
  25884. }]);
  25885. }(Logger);
  25886. var TICK_INTERVAL$2 = 500; // how often to tick in ms
  25887. var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
  25888. function SubtitleStreamController(hls, fragmentTracker, keyLoader) {
  25889. var _this;
  25890. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, 'subtitle-stream-controller', PlaylistLevelType.SUBTITLE) || this;
  25891. _this.currentTrackId = -1;
  25892. _this.tracksBuffered = [];
  25893. _this.mainDetails = null;
  25894. _this.registerListeners();
  25895. return _this;
  25896. }
  25897. _inheritsLoose(SubtitleStreamController, _BaseStreamController);
  25898. var _proto = SubtitleStreamController.prototype;
  25899. _proto.onHandlerDestroying = function onHandlerDestroying() {
  25900. this.unregisterListeners();
  25901. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  25902. this.mainDetails = null;
  25903. };
  25904. _proto.registerListeners = function registerListeners() {
  25905. _BaseStreamController.prototype.registerListeners.call(this);
  25906. var hls = this.hls;
  25907. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25908. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25909. hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  25910. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25911. hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  25912. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25913. };
  25914. _proto.unregisterListeners = function unregisterListeners() {
  25915. _BaseStreamController.prototype.unregisterListeners.call(this);
  25916. var hls = this.hls;
  25917. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  25918. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  25919. hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
  25920. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  25921. hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
  25922. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  25923. };
  25924. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  25925. this.stopLoad();
  25926. this.state = State.IDLE;
  25927. this.setInterval(TICK_INTERVAL$2);
  25928. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  25929. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  25930. this.tick();
  25931. };
  25932. _proto.onManifestLoading = function onManifestLoading() {
  25933. _BaseStreamController.prototype.onManifestLoading.call(this);
  25934. this.mainDetails = null;
  25935. };
  25936. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  25937. this.tracksBuffered = [];
  25938. _BaseStreamController.prototype.onMediaDetaching.call(this, event, data);
  25939. };
  25940. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  25941. this.mainDetails = data.details;
  25942. };
  25943. _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {
  25944. var frag = data.frag,
  25945. success = data.success;
  25946. if (!this.fragContextChanged(frag)) {
  25947. if (isMediaFragment(frag)) {
  25948. this.fragPrevious = frag;
  25949. }
  25950. this.state = State.IDLE;
  25951. }
  25952. if (!success) {
  25953. return;
  25954. }
  25955. var buffered = this.tracksBuffered[this.currentTrackId];
  25956. if (!buffered) {
  25957. return;
  25958. }
  25959. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  25960. // so we can re-use the logic used to detect how much has been buffered
  25961. var timeRange;
  25962. var fragStart = frag.start;
  25963. for (var i = 0; i < buffered.length; i++) {
  25964. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  25965. timeRange = buffered[i];
  25966. break;
  25967. }
  25968. }
  25969. var fragEnd = frag.start + frag.duration;
  25970. if (timeRange) {
  25971. timeRange.end = fragEnd;
  25972. } else {
  25973. timeRange = {
  25974. start: fragStart,
  25975. end: fragEnd
  25976. };
  25977. buffered.push(timeRange);
  25978. }
  25979. this.fragmentTracker.fragBuffered(frag);
  25980. this.fragBufferedComplete(frag, null);
  25981. if (this.media) {
  25982. this.tick();
  25983. }
  25984. };
  25985. _proto.onBufferFlushing = function onBufferFlushing(event, data) {
  25986. var startOffset = data.startOffset,
  25987. endOffset = data.endOffset;
  25988. if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
  25989. var endOffsetSubtitles = endOffset - 1;
  25990. if (endOffsetSubtitles <= 0) {
  25991. return;
  25992. }
  25993. data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
  25994. this.tracksBuffered.forEach(function (buffered) {
  25995. for (var i = 0; i < buffered.length;) {
  25996. if (buffered[i].end <= endOffsetSubtitles) {
  25997. buffered.shift();
  25998. continue;
  25999. } else if (buffered[i].start < endOffsetSubtitles) {
  26000. buffered[i].start = endOffsetSubtitles;
  26001. } else {
  26002. break;
  26003. }
  26004. i++;
  26005. }
  26006. });
  26007. this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, PlaylistLevelType.SUBTITLE);
  26008. }
  26009. }
  26010. // If something goes wrong, proceed to next frag, if we were processing one.
  26011. ;
  26012. _proto.onError = function onError(event, data) {
  26013. var frag = data.frag;
  26014. if ((frag == null ? void 0 : frag.type) === PlaylistLevelType.SUBTITLE) {
  26015. if (data.details === ErrorDetails.FRAG_GAP) {
  26016. this.fragmentTracker.fragBuffered(frag, true);
  26017. }
  26018. if (this.fragCurrent) {
  26019. this.fragCurrent.abortRequests();
  26020. }
  26021. if (this.state !== State.STOPPED) {
  26022. this.state = State.IDLE;
  26023. }
  26024. }
  26025. }
  26026. // Got all new subtitle levels.
  26027. ;
  26028. _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref) {
  26029. var _this2 = this;
  26030. var subtitleTracks = _ref.subtitleTracks;
  26031. if (this.levels && subtitleOptionsIdentical(this.levels, subtitleTracks)) {
  26032. this.levels = subtitleTracks.map(function (mediaPlaylist) {
  26033. return new Level(mediaPlaylist);
  26034. });
  26035. return;
  26036. }
  26037. this.tracksBuffered = [];
  26038. this.levels = subtitleTracks.map(function (mediaPlaylist) {
  26039. var level = new Level(mediaPlaylist);
  26040. _this2.tracksBuffered[level.id] = [];
  26041. return level;
  26042. });
  26043. this.fragmentTracker.removeFragmentsInRange(0, Number.POSITIVE_INFINITY, PlaylistLevelType.SUBTITLE);
  26044. this.fragPrevious = null;
  26045. this.mediaBuffer = null;
  26046. };
  26047. _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
  26048. var _this$levels;
  26049. this.currentTrackId = data.id;
  26050. if (!((_this$levels = this.levels) != null && _this$levels.length) || this.currentTrackId === -1) {
  26051. this.clearInterval();
  26052. return;
  26053. }
  26054. // Check if track has the necessary details to load fragments
  26055. var currentTrack = this.levels[this.currentTrackId];
  26056. if (currentTrack != null && currentTrack.details) {
  26057. this.mediaBuffer = this.mediaBufferTimeRanges;
  26058. } else {
  26059. this.mediaBuffer = null;
  26060. }
  26061. if (currentTrack && this.state !== State.STOPPED) {
  26062. this.setInterval(TICK_INTERVAL$2);
  26063. }
  26064. }
  26065. // Got a new set of subtitle fragments.
  26066. ;
  26067. _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
  26068. var _track$details;
  26069. var currentTrackId = this.currentTrackId,
  26070. levels = this.levels;
  26071. var newDetails = data.details,
  26072. trackId = data.id;
  26073. if (!levels) {
  26074. this.warn("Subtitle tracks were reset while loading level " + trackId);
  26075. return;
  26076. }
  26077. var track = levels[trackId];
  26078. if (trackId >= levels.length || !track) {
  26079. return;
  26080. }
  26081. this.log("Subtitle track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ",duration:" + newDetails.totalduration);
  26082. this.mediaBuffer = this.mediaBufferTimeRanges;
  26083. var sliding = 0;
  26084. if (newDetails.live || (_track$details = track.details) != null && _track$details.live) {
  26085. if (newDetails.deltaUpdateFailed) {
  26086. return;
  26087. }
  26088. var mainDetails = this.mainDetails;
  26089. if (!mainDetails) {
  26090. this.startFragRequested = false;
  26091. return;
  26092. }
  26093. var mainSlidingStartFragment = mainDetails.fragments[0];
  26094. if (!track.details) {
  26095. if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
  26096. alignMediaPlaylistByPDT(newDetails, mainDetails);
  26097. sliding = newDetails.fragmentStart;
  26098. } else if (mainSlidingStartFragment) {
  26099. // line up live playlist with main so that fragments in range are loaded
  26100. sliding = mainSlidingStartFragment.start;
  26101. addSliding(newDetails, sliding);
  26102. }
  26103. } else {
  26104. var _this$levelLastLoaded;
  26105. sliding = this.alignPlaylists(newDetails, track.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  26106. if (sliding === 0 && mainSlidingStartFragment) {
  26107. // realign with main when there is no overlap with last refresh
  26108. sliding = mainSlidingStartFragment.start;
  26109. addSliding(newDetails, sliding);
  26110. }
  26111. }
  26112. // compute start position if we are aligned with the main playlist
  26113. if (mainDetails && !this.startFragRequested) {
  26114. this.setStartPosition(mainDetails, sliding);
  26115. }
  26116. }
  26117. track.details = newDetails;
  26118. this.levelLastLoaded = track;
  26119. if (trackId !== currentTrackId) {
  26120. return;
  26121. }
  26122. this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED, {
  26123. details: newDetails,
  26124. id: trackId,
  26125. groupId: data.groupId
  26126. });
  26127. // trigger handler right now
  26128. this.tick();
  26129. // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
  26130. if (newDetails.live && !this.fragCurrent && this.media && this.state === State.IDLE) {
  26131. var foundFrag = findFragmentByPTS(null, newDetails.fragments, this.media.currentTime, 0);
  26132. if (!foundFrag) {
  26133. this.warn('Subtitle playlist not aligned with playback');
  26134. track.details = undefined;
  26135. }
  26136. }
  26137. };
  26138. _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
  26139. var _this3 = this;
  26140. var frag = fragLoadedData.frag,
  26141. payload = fragLoadedData.payload;
  26142. var decryptData = frag.decryptdata;
  26143. var hls = this.hls;
  26144. if (this.fragContextChanged(frag)) {
  26145. return;
  26146. }
  26147. // check to see if the payload needs to be decrypted
  26148. if (payload && payload.byteLength > 0 && decryptData != null && decryptData.key && decryptData.iv && isFullSegmentEncryption(decryptData.method)) {
  26149. var startTime = performance.now();
  26150. // decrypt the subtitles
  26151. this.decrypter.decrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer, getAesModeFromFullSegmentMethod(decryptData.method)).catch(function (err) {
  26152. hls.trigger(Events.ERROR, {
  26153. type: ErrorTypes.MEDIA_ERROR,
  26154. details: ErrorDetails.FRAG_DECRYPT_ERROR,
  26155. fatal: false,
  26156. error: err,
  26157. reason: err.message,
  26158. frag: frag
  26159. });
  26160. throw err;
  26161. }).then(function (decryptedData) {
  26162. var endTime = performance.now();
  26163. hls.trigger(Events.FRAG_DECRYPTED, {
  26164. frag: frag,
  26165. payload: decryptedData,
  26166. stats: {
  26167. tstart: startTime,
  26168. tdecrypt: endTime
  26169. }
  26170. });
  26171. }).catch(function (err) {
  26172. _this3.warn(err.name + ": " + err.message);
  26173. _this3.state = State.IDLE;
  26174. });
  26175. }
  26176. };
  26177. _proto.doTick = function doTick() {
  26178. if (!this.media) {
  26179. this.state = State.IDLE;
  26180. return;
  26181. }
  26182. if (this.state === State.IDLE) {
  26183. var currentTrackId = this.currentTrackId,
  26184. levels = this.levels;
  26185. var track = levels == null ? void 0 : levels[currentTrackId];
  26186. if (!track || !levels.length || !track.details) {
  26187. return;
  26188. }
  26189. if (this.waitForLive(track)) {
  26190. return;
  26191. }
  26192. var config = this.config;
  26193. var currentTime = this.getLoadPosition();
  26194. var bufferedInfo = BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId] || [], currentTime, config.maxBufferHole);
  26195. var targetBufferTime = bufferedInfo.end,
  26196. bufferLen = bufferedInfo.len;
  26197. var trackDetails = track.details;
  26198. var maxBufLen = this.hls.maxBufferLength + trackDetails.levelTargetDuration;
  26199. if (bufferLen > maxBufLen) {
  26200. return;
  26201. }
  26202. var fragments = trackDetails.fragments;
  26203. var fragLen = fragments.length;
  26204. var end = trackDetails.edge;
  26205. var foundFrag = null;
  26206. var fragPrevious = this.fragPrevious;
  26207. if (targetBufferTime < end) {
  26208. var tolerance = config.maxFragLookUpTolerance;
  26209. var lookupTolerance = targetBufferTime > end - tolerance ? 0 : tolerance;
  26210. foundFrag = findFragmentByPTS(fragPrevious, fragments, Math.max(fragments[0].start, targetBufferTime), lookupTolerance);
  26211. if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
  26212. foundFrag = fragments[0];
  26213. }
  26214. } else {
  26215. foundFrag = fragments[fragLen - 1];
  26216. }
  26217. foundFrag = this.filterReplacedPrimary(foundFrag, track.details);
  26218. if (!foundFrag) {
  26219. return;
  26220. }
  26221. // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment
  26222. var curSNIdx = foundFrag.sn - trackDetails.startSN;
  26223. var prevFrag = fragments[curSNIdx - 1];
  26224. if (prevFrag && prevFrag.cc === foundFrag.cc && this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED) {
  26225. foundFrag = prevFrag;
  26226. }
  26227. if (this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {
  26228. // only load if fragment is not loaded
  26229. var fragToLoad = this.mapToInitFragWhenRequired(foundFrag);
  26230. if (fragToLoad) {
  26231. this.loadFragment(fragToLoad, track, targetBufferTime);
  26232. }
  26233. }
  26234. }
  26235. };
  26236. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  26237. if (!isMediaFragment(frag)) {
  26238. this._loadInitSegment(frag, level);
  26239. } else {
  26240. _BaseStreamController.prototype.loadFragment.call(this, frag, level, targetBufferTime);
  26241. }
  26242. };
  26243. return _createClass(SubtitleStreamController, [{
  26244. key: "mediaBufferTimeRanges",
  26245. get: function get() {
  26246. return new BufferableInstance(this.tracksBuffered[this.currentTrackId] || []);
  26247. }
  26248. }]);
  26249. }(BaseStreamController);
  26250. var BufferableInstance = function BufferableInstance(timeranges) {
  26251. this.buffered = void 0;
  26252. var getRange = function getRange(name, index, length) {
  26253. index = index >>> 0;
  26254. if (index > length - 1) {
  26255. throw new DOMException("Failed to execute '" + name + "' on 'TimeRanges': The index provided (" + index + ") is greater than the maximum bound (" + length + ")");
  26256. }
  26257. return timeranges[index][name];
  26258. };
  26259. this.buffered = {
  26260. get length() {
  26261. return timeranges.length;
  26262. },
  26263. end: function end(index) {
  26264. return getRange('end', index, timeranges.length);
  26265. },
  26266. start: function start(index) {
  26267. return getRange('start', index, timeranges.length);
  26268. }
  26269. };
  26270. };
  26271. function sendAddTrackEvent(track, videoEl) {
  26272. var event;
  26273. try {
  26274. event = new Event('addtrack');
  26275. } catch (err) {
  26276. // for IE11
  26277. event = document.createEvent('Event');
  26278. event.initEvent('addtrack', false, false);
  26279. }
  26280. event.track = track;
  26281. videoEl.dispatchEvent(event);
  26282. }
  26283. function addCueToTrack(track, cue) {
  26284. // Sometimes there are cue overlaps on segmented vtts so the same
  26285. // cue can appear more than once in different vtt files.
  26286. // This avoid showing duplicated cues with same timecode and text.
  26287. var mode = track.mode;
  26288. if (mode === 'disabled') {
  26289. track.mode = 'hidden';
  26290. }
  26291. if (track.cues && !track.cues.getCueById(cue.id)) {
  26292. try {
  26293. track.addCue(cue);
  26294. if (!track.cues.getCueById(cue.id)) {
  26295. throw new Error("addCue is failed for: " + cue);
  26296. }
  26297. } catch (err) {
  26298. logger.debug("[texttrack-utils]: " + err);
  26299. try {
  26300. var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  26301. textTrackCue.id = cue.id;
  26302. track.addCue(textTrackCue);
  26303. } catch (err2) {
  26304. logger.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: " + err2);
  26305. }
  26306. }
  26307. }
  26308. if (mode === 'disabled') {
  26309. track.mode = mode;
  26310. }
  26311. }
  26312. function clearCurrentCues(track, enterHandler) {
  26313. // When track.mode is disabled, track.cues will be null.
  26314. // To guarantee the removal of cues, we need to temporarily
  26315. // change the mode to hidden
  26316. var mode = track.mode;
  26317. if (mode === 'disabled') {
  26318. track.mode = 'hidden';
  26319. }
  26320. if (track.cues) {
  26321. for (var i = track.cues.length; i--;) {
  26322. if (enterHandler) {
  26323. track.cues[i].removeEventListener('enter', enterHandler);
  26324. }
  26325. track.removeCue(track.cues[i]);
  26326. }
  26327. }
  26328. if (mode === 'disabled') {
  26329. track.mode = mode;
  26330. }
  26331. }
  26332. function removeCuesInRange(track, start, end, predicate) {
  26333. var mode = track.mode;
  26334. if (mode === 'disabled') {
  26335. track.mode = 'hidden';
  26336. }
  26337. if (track.cues && track.cues.length > 0) {
  26338. var cues = getCuesInRange(track.cues, start, end);
  26339. for (var i = 0; i < cues.length; i++) {
  26340. if (!predicate || predicate(cues[i])) {
  26341. track.removeCue(cues[i]);
  26342. }
  26343. }
  26344. }
  26345. if (mode === 'disabled') {
  26346. track.mode = mode;
  26347. }
  26348. }
  26349. // Find first cue starting at or after given time.
  26350. // Modified version of binary search O(log(n)).
  26351. function getFirstCueIndexFromTime(cues, time) {
  26352. // If first cue starts at or after time, start there
  26353. if (time <= cues[0].startTime) {
  26354. return 0;
  26355. }
  26356. // If the last cue ends before time there is no overlap
  26357. var len = cues.length - 1;
  26358. if (time > cues[len].endTime) {
  26359. return -1;
  26360. }
  26361. var left = 0;
  26362. var right = len;
  26363. var mid;
  26364. while (left <= right) {
  26365. mid = Math.floor((right + left) / 2);
  26366. if (time < cues[mid].startTime) {
  26367. right = mid - 1;
  26368. } else if (time > cues[mid].startTime && left < len) {
  26369. left = mid + 1;
  26370. } else {
  26371. // If it's not lower or higher, it must be equal.
  26372. return mid;
  26373. }
  26374. }
  26375. // At this point, left and right have swapped.
  26376. // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
  26377. return cues[left].startTime - time < time - cues[right].startTime ? left : right;
  26378. }
  26379. function getCuesInRange(cues, start, end) {
  26380. var cuesFound = [];
  26381. var firstCueInRange = getFirstCueIndexFromTime(cues, start);
  26382. if (firstCueInRange > -1) {
  26383. for (var i = firstCueInRange, len = cues.length; i < len; i++) {
  26384. var cue = cues[i];
  26385. if (cue.startTime >= start && cue.endTime <= end) {
  26386. cuesFound.push(cue);
  26387. } else if (cue.startTime > end) {
  26388. return cuesFound;
  26389. }
  26390. }
  26391. }
  26392. return cuesFound;
  26393. }
  26394. function filterSubtitleTracks(textTrackList) {
  26395. var tracks = [];
  26396. for (var i = 0; i < textTrackList.length; i++) {
  26397. var track = textTrackList[i];
  26398. // Edge adds a track without a label; we don't want to use it
  26399. if ((track.kind === 'subtitles' || track.kind === 'captions') && track.label) {
  26400. tracks.push(textTrackList[i]);
  26401. }
  26402. }
  26403. return tracks;
  26404. }
  26405. var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
  26406. function SubtitleTrackController(hls) {
  26407. var _this;
  26408. _this = _BasePlaylistControll.call(this, hls, 'subtitle-track-controller') || this;
  26409. _this.media = null;
  26410. _this.tracks = [];
  26411. _this.groupIds = null;
  26412. _this.tracksInGroup = [];
  26413. _this.trackId = -1;
  26414. _this.currentTrack = null;
  26415. _this.selectDefaultTrack = true;
  26416. _this.queuedDefaultTrack = -1;
  26417. _this.useTextTrackPolling = false;
  26418. _this.subtitlePollingInterval = -1;
  26419. _this._subtitleDisplay = true;
  26420. _this.asyncPollTrackChange = function () {
  26421. return _this.pollTrackChange(0);
  26422. };
  26423. _this.onTextTracksChanged = function () {
  26424. if (!_this.useTextTrackPolling) {
  26425. self.clearInterval(_this.subtitlePollingInterval);
  26426. }
  26427. // Media is undefined when switching streams via loadSource()
  26428. if (!_this.media || !_this.hls.config.renderTextTracksNatively) {
  26429. return;
  26430. }
  26431. var textTrack = null;
  26432. var tracks = filterSubtitleTracks(_this.media.textTracks);
  26433. for (var i = 0; i < tracks.length; i++) {
  26434. if (tracks[i].mode === 'hidden') {
  26435. // Do not break in case there is a following track with showing.
  26436. textTrack = tracks[i];
  26437. } else if (tracks[i].mode === 'showing') {
  26438. textTrack = tracks[i];
  26439. break;
  26440. }
  26441. }
  26442. // Find internal track index for TextTrack
  26443. var trackId = _this.findTrackForTextTrack(textTrack);
  26444. if (_this.subtitleTrack !== trackId) {
  26445. _this.setSubtitleTrack(trackId);
  26446. }
  26447. };
  26448. _this.registerListeners();
  26449. return _this;
  26450. }
  26451. _inheritsLoose(SubtitleTrackController, _BasePlaylistControll);
  26452. var _proto = SubtitleTrackController.prototype;
  26453. _proto.destroy = function destroy() {
  26454. this.unregisterListeners();
  26455. this.tracks.length = 0;
  26456. this.tracksInGroup.length = 0;
  26457. this.currentTrack = null;
  26458. // @ts-ignore
  26459. this.onTextTracksChanged = this.asyncPollTrackChange = null;
  26460. _BasePlaylistControll.prototype.destroy.call(this);
  26461. };
  26462. _proto.registerListeners = function registerListeners() {
  26463. var hls = this.hls;
  26464. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26465. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26466. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26467. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26468. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  26469. hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  26470. hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  26471. hls.on(Events.ERROR, this.onError, this);
  26472. };
  26473. _proto.unregisterListeners = function unregisterListeners() {
  26474. var hls = this.hls;
  26475. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  26476. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  26477. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  26478. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  26479. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  26480. hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);
  26481. hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
  26482. hls.off(Events.ERROR, this.onError, this);
  26483. }
  26484. // Listen for subtitle track change, then extract the current track ID.
  26485. ;
  26486. _proto.onMediaAttached = function onMediaAttached(event, data) {
  26487. this.media = data.media;
  26488. if (!this.media) {
  26489. return;
  26490. }
  26491. if (this.queuedDefaultTrack > -1) {
  26492. this.subtitleTrack = this.queuedDefaultTrack;
  26493. this.queuedDefaultTrack = -1;
  26494. }
  26495. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  26496. if (this.useTextTrackPolling) {
  26497. this.pollTrackChange(500);
  26498. } else {
  26499. this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
  26500. }
  26501. };
  26502. _proto.pollTrackChange = function pollTrackChange(timeout) {
  26503. self.clearInterval(this.subtitlePollingInterval);
  26504. this.subtitlePollingInterval = self.setInterval(this.onTextTracksChanged, timeout);
  26505. };
  26506. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  26507. var media = this.media;
  26508. if (!media) {
  26509. return;
  26510. }
  26511. var transferringMedia = !!data.transferMedia;
  26512. self.clearInterval(this.subtitlePollingInterval);
  26513. if (!this.useTextTrackPolling) {
  26514. media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
  26515. }
  26516. if (this.trackId > -1) {
  26517. this.queuedDefaultTrack = this.trackId;
  26518. }
  26519. // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
  26520. this.subtitleTrack = -1;
  26521. this.media = null;
  26522. if (transferringMedia) {
  26523. return;
  26524. }
  26525. var textTracks = filterSubtitleTracks(media.textTracks);
  26526. // Clear loaded cues on media detachment from tracks
  26527. textTracks.forEach(function (track) {
  26528. clearCurrentCues(track);
  26529. });
  26530. };
  26531. _proto.onManifestLoading = function onManifestLoading() {
  26532. this.tracks = [];
  26533. this.groupIds = null;
  26534. this.tracksInGroup = [];
  26535. this.trackId = -1;
  26536. this.currentTrack = null;
  26537. this.selectDefaultTrack = true;
  26538. }
  26539. // Fired whenever a new manifest is loaded.
  26540. ;
  26541. _proto.onManifestParsed = function onManifestParsed(event, data) {
  26542. this.tracks = data.subtitleTracks;
  26543. };
  26544. _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
  26545. var id = data.id,
  26546. groupId = data.groupId,
  26547. details = data.details;
  26548. var trackInActiveGroup = this.tracksInGroup[id];
  26549. if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {
  26550. this.warn("Subtitle track with id:" + id + " and group:" + groupId + " not found in active group " + (trackInActiveGroup == null ? void 0 : trackInActiveGroup.groupId));
  26551. return;
  26552. }
  26553. var curDetails = trackInActiveGroup.details;
  26554. trackInActiveGroup.details = data.details;
  26555. this.log("Subtitle track " + id + " \"" + trackInActiveGroup.name + "\" lang:" + trackInActiveGroup.lang + " group:" + groupId + " loaded [" + details.startSN + "-" + details.endSN + "]");
  26556. if (id === this.trackId) {
  26557. this.playlistLoaded(id, data, curDetails);
  26558. }
  26559. };
  26560. _proto.onLevelLoading = function onLevelLoading(event, data) {
  26561. this.switchLevel(data.level);
  26562. };
  26563. _proto.onLevelSwitching = function onLevelSwitching(event, data) {
  26564. this.switchLevel(data.level);
  26565. };
  26566. _proto.switchLevel = function switchLevel(levelIndex) {
  26567. var levelInfo = this.hls.levels[levelIndex];
  26568. if (!levelInfo) {
  26569. return;
  26570. }
  26571. var subtitleGroups = levelInfo.subtitleGroups || null;
  26572. var currentGroups = this.groupIds;
  26573. var currentTrack = this.currentTrack;
  26574. if (!subtitleGroups || (currentGroups == null ? void 0 : currentGroups.length) !== (subtitleGroups == null ? void 0 : subtitleGroups.length) || subtitleGroups != null && subtitleGroups.some(function (groupId) {
  26575. return (currentGroups == null ? void 0 : currentGroups.indexOf(groupId)) === -1;
  26576. })) {
  26577. this.groupIds = subtitleGroups;
  26578. this.trackId = -1;
  26579. this.currentTrack = null;
  26580. var subtitleTracks = this.tracks.filter(function (track) {
  26581. return !subtitleGroups || subtitleGroups.indexOf(track.groupId) !== -1;
  26582. });
  26583. if (subtitleTracks.length) {
  26584. // Disable selectDefaultTrack if there are no default tracks
  26585. if (this.selectDefaultTrack && !subtitleTracks.some(function (track) {
  26586. return track.default;
  26587. })) {
  26588. this.selectDefaultTrack = false;
  26589. }
  26590. // track.id should match hls.audioTracks index
  26591. subtitleTracks.forEach(function (track, i) {
  26592. track.id = i;
  26593. });
  26594. } else if (!currentTrack && !this.tracksInGroup.length) {
  26595. // Do not dispatch SUBTITLE_TRACKS_UPDATED when there were and are no tracks
  26596. return;
  26597. }
  26598. this.tracksInGroup = subtitleTracks;
  26599. // Find preferred track
  26600. var subtitlePreference = this.hls.config.subtitlePreference;
  26601. if (!currentTrack && subtitlePreference) {
  26602. this.selectDefaultTrack = false;
  26603. var groupIndex = findMatchingOption(subtitlePreference, subtitleTracks);
  26604. if (groupIndex > -1) {
  26605. currentTrack = subtitleTracks[groupIndex];
  26606. } else {
  26607. var allIndex = findMatchingOption(subtitlePreference, this.tracks);
  26608. currentTrack = this.tracks[allIndex];
  26609. }
  26610. }
  26611. // Select initial track
  26612. var trackId = this.findTrackId(currentTrack);
  26613. if (trackId === -1 && currentTrack) {
  26614. trackId = this.findTrackId(null);
  26615. }
  26616. // Dispatch events and load track if needed
  26617. var subtitleTracksUpdated = {
  26618. subtitleTracks: subtitleTracks
  26619. };
  26620. this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + (subtitleGroups == null ? void 0 : subtitleGroups.join(',')) + "\" group-id");
  26621. this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
  26622. if (trackId !== -1 && this.trackId === -1) {
  26623. this.setSubtitleTrack(trackId);
  26624. }
  26625. }
  26626. };
  26627. _proto.findTrackId = function findTrackId(currentTrack) {
  26628. var tracks = this.tracksInGroup;
  26629. var selectDefault = this.selectDefaultTrack;
  26630. for (var i = 0; i < tracks.length; i++) {
  26631. var track = tracks[i];
  26632. if (selectDefault && !track.default || !selectDefault && !currentTrack) {
  26633. continue;
  26634. }
  26635. if (!currentTrack || matchesOption(track, currentTrack)) {
  26636. return i;
  26637. }
  26638. }
  26639. if (currentTrack) {
  26640. for (var _i = 0; _i < tracks.length; _i++) {
  26641. var _track = tracks[_i];
  26642. if (mediaAttributesIdentical(currentTrack.attrs, _track.attrs, ['LANGUAGE', 'ASSOC-LANGUAGE', 'CHARACTERISTICS'])) {
  26643. return _i;
  26644. }
  26645. }
  26646. for (var _i2 = 0; _i2 < tracks.length; _i2++) {
  26647. var _track2 = tracks[_i2];
  26648. if (mediaAttributesIdentical(currentTrack.attrs, _track2.attrs, ['LANGUAGE'])) {
  26649. return _i2;
  26650. }
  26651. }
  26652. }
  26653. return -1;
  26654. };
  26655. _proto.findTrackForTextTrack = function findTrackForTextTrack(textTrack) {
  26656. if (textTrack) {
  26657. var tracks = this.tracksInGroup;
  26658. for (var i = 0; i < tracks.length; i++) {
  26659. var track = tracks[i];
  26660. if (subtitleTrackMatchesTextTrack(track, textTrack)) {
  26661. return i;
  26662. }
  26663. }
  26664. }
  26665. return -1;
  26666. };
  26667. _proto.onError = function onError(event, data) {
  26668. if (data.fatal || !data.context) {
  26669. return;
  26670. }
  26671. if (data.context.type === PlaylistContextType.SUBTITLE_TRACK && data.context.id === this.trackId && (!this.groupIds || this.groupIds.indexOf(data.context.groupId) !== -1)) {
  26672. this.checkRetry(data);
  26673. }
  26674. };
  26675. _proto.setSubtitleOption = function setSubtitleOption(subtitleOption) {
  26676. this.hls.config.subtitlePreference = subtitleOption;
  26677. if (subtitleOption) {
  26678. if (subtitleOption.id === -1) {
  26679. this.setSubtitleTrack(-1);
  26680. return null;
  26681. }
  26682. var allSubtitleTracks = this.allSubtitleTracks;
  26683. this.selectDefaultTrack = false;
  26684. if (allSubtitleTracks.length) {
  26685. // First see if current option matches (no switch op)
  26686. var currentTrack = this.currentTrack;
  26687. if (currentTrack && matchesOption(subtitleOption, currentTrack)) {
  26688. return currentTrack;
  26689. }
  26690. // Find option in current group
  26691. var groupIndex = findMatchingOption(subtitleOption, this.tracksInGroup);
  26692. if (groupIndex > -1) {
  26693. var track = this.tracksInGroup[groupIndex];
  26694. this.setSubtitleTrack(groupIndex);
  26695. return track;
  26696. } else if (currentTrack) {
  26697. // If this is not the initial selection return null
  26698. // option should have matched one in active group
  26699. return null;
  26700. } else {
  26701. // Find the option in all tracks for initial selection
  26702. var allIndex = findMatchingOption(subtitleOption, allSubtitleTracks);
  26703. if (allIndex > -1) {
  26704. return allSubtitleTracks[allIndex];
  26705. }
  26706. }
  26707. }
  26708. }
  26709. return null;
  26710. };
  26711. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  26712. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  26713. if (this.shouldLoadPlaylist(this.currentTrack)) {
  26714. this.scheduleLoading(this.currentTrack, hlsUrlParameters);
  26715. }
  26716. };
  26717. _proto.loadingPlaylist = function loadingPlaylist(currentTrack, hlsUrlParameters) {
  26718. _BasePlaylistControll.prototype.loadingPlaylist.call(this, currentTrack, hlsUrlParameters);
  26719. var id = currentTrack.id;
  26720. var groupId = currentTrack.groupId;
  26721. var url = this.getUrlWithDirectives(currentTrack.url, hlsUrlParameters);
  26722. var details = currentTrack.details;
  26723. var age = details == null ? void 0 : details.age;
  26724. this.log("Loading subtitle " + id + " \"" + currentTrack.name + "\" lang:" + currentTrack.lang + " group:" + groupId + ((hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + (age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : '') + " " + url);
  26725. this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {
  26726. url: url,
  26727. id: id,
  26728. groupId: groupId,
  26729. deliveryDirectives: hlsUrlParameters || null,
  26730. track: currentTrack
  26731. });
  26732. }
  26733. /**
  26734. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  26735. * This operates on the DOM textTracks.
  26736. * A value of -1 will disable all subtitle tracks.
  26737. */;
  26738. _proto.toggleTrackModes = function toggleTrackModes() {
  26739. var media = this.media;
  26740. if (!media) {
  26741. return;
  26742. }
  26743. var textTracks = filterSubtitleTracks(media.textTracks);
  26744. var currentTrack = this.currentTrack;
  26745. var nextTrack;
  26746. if (currentTrack) {
  26747. nextTrack = textTracks.filter(function (textTrack) {
  26748. return subtitleTrackMatchesTextTrack(currentTrack, textTrack);
  26749. })[0];
  26750. if (!nextTrack) {
  26751. this.warn("Unable to find subtitle TextTrack with name \"" + currentTrack.name + "\" and language \"" + currentTrack.lang + "\"");
  26752. }
  26753. }
  26754. [].slice.call(textTracks).forEach(function (track) {
  26755. if (track.mode !== 'disabled' && track !== nextTrack) {
  26756. track.mode = 'disabled';
  26757. }
  26758. });
  26759. if (nextTrack) {
  26760. var mode = this.subtitleDisplay ? 'showing' : 'hidden';
  26761. if (nextTrack.mode !== mode) {
  26762. nextTrack.mode = mode;
  26763. }
  26764. }
  26765. }
  26766. /**
  26767. * This method is responsible for validating the subtitle index and periodically reloading if live.
  26768. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  26769. */;
  26770. _proto.setSubtitleTrack = function setSubtitleTrack(newId) {
  26771. var tracks = this.tracksInGroup;
  26772. // setting this.subtitleTrack will trigger internal logic
  26773. // if media has not been attached yet, it will fail
  26774. // we keep a reference to the default track id
  26775. // and we'll set subtitleTrack when onMediaAttached is triggered
  26776. if (!this.media) {
  26777. this.queuedDefaultTrack = newId;
  26778. return;
  26779. }
  26780. // exit if track id as already set or invalid
  26781. if (newId < -1 || newId >= tracks.length || !isFiniteNumber(newId)) {
  26782. this.warn("Invalid subtitle track id: " + newId);
  26783. return;
  26784. }
  26785. this.selectDefaultTrack = false;
  26786. var lastTrack = this.currentTrack;
  26787. var track = tracks[newId] || null;
  26788. this.trackId = newId;
  26789. this.currentTrack = track;
  26790. this.toggleTrackModes();
  26791. if (!track) {
  26792. // switch to -1
  26793. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  26794. id: newId
  26795. });
  26796. return;
  26797. }
  26798. var trackLoaded = !!track.details && !track.details.live;
  26799. if (newId === this.trackId && track === lastTrack && trackLoaded) {
  26800. return;
  26801. }
  26802. this.log("Switching to subtitle-track " + newId + (track ? " \"" + track.name + "\" lang:" + track.lang + " group:" + track.groupId : ''));
  26803. var id = track.id,
  26804. _track$groupId = track.groupId,
  26805. groupId = _track$groupId === void 0 ? '' : _track$groupId,
  26806. name = track.name,
  26807. type = track.type,
  26808. url = track.url;
  26809. this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {
  26810. id: id,
  26811. groupId: groupId,
  26812. name: name,
  26813. type: type,
  26814. url: url
  26815. });
  26816. var hlsUrlParameters = this.switchParams(track.url, lastTrack == null ? void 0 : lastTrack.details, track.details);
  26817. this.loadPlaylist(hlsUrlParameters);
  26818. };
  26819. return _createClass(SubtitleTrackController, [{
  26820. key: "subtitleDisplay",
  26821. get: function get() {
  26822. return this._subtitleDisplay;
  26823. },
  26824. set: function set(value) {
  26825. this._subtitleDisplay = value;
  26826. if (this.trackId > -1) {
  26827. this.toggleTrackModes();
  26828. }
  26829. }
  26830. }, {
  26831. key: "allSubtitleTracks",
  26832. get: function get() {
  26833. return this.tracks;
  26834. }
  26835. /** get alternate subtitle tracks list from playlist **/
  26836. }, {
  26837. key: "subtitleTracks",
  26838. get: function get() {
  26839. return this.tracksInGroup;
  26840. }
  26841. /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
  26842. }, {
  26843. key: "subtitleTrack",
  26844. get: function get() {
  26845. return this.trackId;
  26846. },
  26847. set: function set(newId) {
  26848. this.selectDefaultTrack = false;
  26849. this.setSubtitleTrack(newId);
  26850. }
  26851. }]);
  26852. }(BasePlaylistController);
  26853. /**
  26854. *
  26855. * This code was ported from the dash.js project at:
  26856. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  26857. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  26858. *
  26859. * The original copyright appears below:
  26860. *
  26861. * The copyright in this software is being made available under the BSD License,
  26862. * included below. This software may be subject to other third party and contributor
  26863. * rights, including patent rights, and no such rights are granted under this license.
  26864. *
  26865. * Copyright (c) 2015-2016, DASH Industry Forum.
  26866. * All rights reserved.
  26867. *
  26868. * Redistribution and use in source and binary forms, with or without modification,
  26869. * are permitted provided that the following conditions are met:
  26870. * 1. Redistributions of source code must retain the above copyright notice, this
  26871. * list of conditions and the following disclaimer.
  26872. * * Redistributions in binary form must reproduce the above copyright notice,
  26873. * this list of conditions and the following disclaimer in the documentation and/or
  26874. * other materials provided with the distribution.
  26875. * 2. Neither the name of Dash Industry Forum nor the names of its
  26876. * contributors may be used to endorse or promote products derived from this software
  26877. * without specific prior written permission.
  26878. *
  26879. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  26880. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  26881. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  26882. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  26883. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  26884. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26885. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  26886. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26887. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26888. * POSSIBILITY OF SUCH DAMAGE.
  26889. */
  26890. /**
  26891. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  26892. */
  26893. var specialCea608CharsCodes = {
  26894. 0x2a: 0xe1,
  26895. // lowercase a, acute accent
  26896. 0x5c: 0xe9,
  26897. // lowercase e, acute accent
  26898. 0x5e: 0xed,
  26899. // lowercase i, acute accent
  26900. 0x5f: 0xf3,
  26901. // lowercase o, acute accent
  26902. 0x60: 0xfa,
  26903. // lowercase u, acute accent
  26904. 0x7b: 0xe7,
  26905. // lowercase c with cedilla
  26906. 0x7c: 0xf7,
  26907. // division symbol
  26908. 0x7d: 0xd1,
  26909. // uppercase N tilde
  26910. 0x7e: 0xf1,
  26911. // lowercase n tilde
  26912. 0x7f: 0x2588,
  26913. // Full block
  26914. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  26915. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  26916. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  26917. 0x80: 0xae,
  26918. // Registered symbol (R)
  26919. 0x81: 0xb0,
  26920. // degree sign
  26921. 0x82: 0xbd,
  26922. // 1/2 symbol
  26923. 0x83: 0xbf,
  26924. // Inverted (open) question mark
  26925. 0x84: 0x2122,
  26926. // Trademark symbol (TM)
  26927. 0x85: 0xa2,
  26928. // Cents symbol
  26929. 0x86: 0xa3,
  26930. // Pounds sterling
  26931. 0x87: 0x266a,
  26932. // Music 8'th note
  26933. 0x88: 0xe0,
  26934. // lowercase a, grave accent
  26935. 0x89: 0x20,
  26936. // transparent space (regular)
  26937. 0x8a: 0xe8,
  26938. // lowercase e, grave accent
  26939. 0x8b: 0xe2,
  26940. // lowercase a, circumflex accent
  26941. 0x8c: 0xea,
  26942. // lowercase e, circumflex accent
  26943. 0x8d: 0xee,
  26944. // lowercase i, circumflex accent
  26945. 0x8e: 0xf4,
  26946. // lowercase o, circumflex accent
  26947. 0x8f: 0xfb,
  26948. // lowercase u, circumflex accent
  26949. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  26950. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  26951. 0x90: 0xc1,
  26952. // capital letter A with acute
  26953. 0x91: 0xc9,
  26954. // capital letter E with acute
  26955. 0x92: 0xd3,
  26956. // capital letter O with acute
  26957. 0x93: 0xda,
  26958. // capital letter U with acute
  26959. 0x94: 0xdc,
  26960. // capital letter U with diaresis
  26961. 0x95: 0xfc,
  26962. // lowercase letter U with diaeresis
  26963. 0x96: 0x2018,
  26964. // opening single quote
  26965. 0x97: 0xa1,
  26966. // inverted exclamation mark
  26967. 0x98: 0x2a,
  26968. // asterisk
  26969. 0x99: 0x2019,
  26970. // closing single quote
  26971. 0x9a: 0x2501,
  26972. // box drawings heavy horizontal
  26973. 0x9b: 0xa9,
  26974. // copyright sign
  26975. 0x9c: 0x2120,
  26976. // Service mark
  26977. 0x9d: 0x2022,
  26978. // (round) bullet
  26979. 0x9e: 0x201c,
  26980. // Left double quotation mark
  26981. 0x9f: 0x201d,
  26982. // Right double quotation mark
  26983. 0xa0: 0xc0,
  26984. // uppercase A, grave accent
  26985. 0xa1: 0xc2,
  26986. // uppercase A, circumflex
  26987. 0xa2: 0xc7,
  26988. // uppercase C with cedilla
  26989. 0xa3: 0xc8,
  26990. // uppercase E, grave accent
  26991. 0xa4: 0xca,
  26992. // uppercase E, circumflex
  26993. 0xa5: 0xcb,
  26994. // capital letter E with diaresis
  26995. 0xa6: 0xeb,
  26996. // lowercase letter e with diaresis
  26997. 0xa7: 0xce,
  26998. // uppercase I, circumflex
  26999. 0xa8: 0xcf,
  27000. // uppercase I, with diaresis
  27001. 0xa9: 0xef,
  27002. // lowercase i, with diaresis
  27003. 0xaa: 0xd4,
  27004. // uppercase O, circumflex
  27005. 0xab: 0xd9,
  27006. // uppercase U, grave accent
  27007. 0xac: 0xf9,
  27008. // lowercase u, grave accent
  27009. 0xad: 0xdb,
  27010. // uppercase U, circumflex
  27011. 0xae: 0xab,
  27012. // left-pointing double angle quotation mark
  27013. 0xaf: 0xbb,
  27014. // right-pointing double angle quotation mark
  27015. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  27016. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  27017. 0xb0: 0xc3,
  27018. // Uppercase A, tilde
  27019. 0xb1: 0xe3,
  27020. // Lowercase a, tilde
  27021. 0xb2: 0xcd,
  27022. // Uppercase I, acute accent
  27023. 0xb3: 0xcc,
  27024. // Uppercase I, grave accent
  27025. 0xb4: 0xec,
  27026. // Lowercase i, grave accent
  27027. 0xb5: 0xd2,
  27028. // Uppercase O, grave accent
  27029. 0xb6: 0xf2,
  27030. // Lowercase o, grave accent
  27031. 0xb7: 0xd5,
  27032. // Uppercase O, tilde
  27033. 0xb8: 0xf5,
  27034. // Lowercase o, tilde
  27035. 0xb9: 0x7b,
  27036. // Open curly brace
  27037. 0xba: 0x7d,
  27038. // Closing curly brace
  27039. 0xbb: 0x5c,
  27040. // Backslash
  27041. 0xbc: 0x5e,
  27042. // Caret
  27043. 0xbd: 0x5f,
  27044. // Underscore
  27045. 0xbe: 0x7c,
  27046. // Pipe (vertical line)
  27047. 0xbf: 0x223c,
  27048. // Tilde operator
  27049. 0xc0: 0xc4,
  27050. // Uppercase A, umlaut
  27051. 0xc1: 0xe4,
  27052. // Lowercase A, umlaut
  27053. 0xc2: 0xd6,
  27054. // Uppercase O, umlaut
  27055. 0xc3: 0xf6,
  27056. // Lowercase o, umlaut
  27057. 0xc4: 0xdf,
  27058. // Esszett (sharp S)
  27059. 0xc5: 0xa5,
  27060. // Yen symbol
  27061. 0xc6: 0xa4,
  27062. // Generic currency sign
  27063. 0xc7: 0x2503,
  27064. // Box drawings heavy vertical
  27065. 0xc8: 0xc5,
  27066. // Uppercase A, ring
  27067. 0xc9: 0xe5,
  27068. // Lowercase A, ring
  27069. 0xca: 0xd8,
  27070. // Uppercase O, stroke
  27071. 0xcb: 0xf8,
  27072. // Lowercase o, strok
  27073. 0xcc: 0x250f,
  27074. // Box drawings heavy down and right
  27075. 0xcd: 0x2513,
  27076. // Box drawings heavy down and left
  27077. 0xce: 0x2517,
  27078. // Box drawings heavy up and right
  27079. 0xcf: 0x251b // Box drawings heavy up and left
  27080. };
  27081. /**
  27082. * Utils
  27083. */
  27084. var getCharForByte = function getCharForByte(_byte) {
  27085. return String.fromCharCode(specialCea608CharsCodes[_byte] || _byte);
  27086. };
  27087. var NR_ROWS = 15;
  27088. var NR_COLS = 100;
  27089. // Tables to look up row from PAC data
  27090. var rowsLowCh1 = {
  27091. 0x11: 1,
  27092. 0x12: 3,
  27093. 0x15: 5,
  27094. 0x16: 7,
  27095. 0x17: 9,
  27096. 0x10: 11,
  27097. 0x13: 12,
  27098. 0x14: 14
  27099. };
  27100. var rowsHighCh1 = {
  27101. 0x11: 2,
  27102. 0x12: 4,
  27103. 0x15: 6,
  27104. 0x16: 8,
  27105. 0x17: 10,
  27106. 0x13: 13,
  27107. 0x14: 15
  27108. };
  27109. var rowsLowCh2 = {
  27110. 0x19: 1,
  27111. 0x1a: 3,
  27112. 0x1d: 5,
  27113. 0x1e: 7,
  27114. 0x1f: 9,
  27115. 0x18: 11,
  27116. 0x1b: 12,
  27117. 0x1c: 14
  27118. };
  27119. var rowsHighCh2 = {
  27120. 0x19: 2,
  27121. 0x1a: 4,
  27122. 0x1d: 6,
  27123. 0x1e: 8,
  27124. 0x1f: 10,
  27125. 0x1b: 13,
  27126. 0x1c: 15
  27127. };
  27128. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  27129. var CaptionsLogger = /*#__PURE__*/function () {
  27130. function CaptionsLogger() {
  27131. this.time = null;
  27132. this.verboseLevel = 0;
  27133. }
  27134. var _proto = CaptionsLogger.prototype;
  27135. _proto.log = function log(severity, msg) {
  27136. if (this.verboseLevel >= severity) {
  27137. var m = typeof msg === 'function' ? msg() : msg;
  27138. logger.log(this.time + " [" + severity + "] " + m);
  27139. }
  27140. };
  27141. return CaptionsLogger;
  27142. }();
  27143. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  27144. var hexArray = [];
  27145. for (var j = 0; j < numArray.length; j++) {
  27146. hexArray.push(numArray[j].toString(16));
  27147. }
  27148. return hexArray;
  27149. };
  27150. var PenState = /*#__PURE__*/function () {
  27151. function PenState() {
  27152. this.foreground = 'white';
  27153. this.underline = false;
  27154. this.italics = false;
  27155. this.background = 'black';
  27156. this.flash = false;
  27157. }
  27158. var _proto2 = PenState.prototype;
  27159. _proto2.reset = function reset() {
  27160. this.foreground = 'white';
  27161. this.underline = false;
  27162. this.italics = false;
  27163. this.background = 'black';
  27164. this.flash = false;
  27165. };
  27166. _proto2.setStyles = function setStyles(styles) {
  27167. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  27168. for (var i = 0; i < attribs.length; i++) {
  27169. var style = attribs[i];
  27170. if (styles.hasOwnProperty(style)) {
  27171. this[style] = styles[style];
  27172. }
  27173. }
  27174. };
  27175. _proto2.isDefault = function isDefault() {
  27176. return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  27177. };
  27178. _proto2.equals = function equals(other) {
  27179. return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  27180. };
  27181. _proto2.copy = function copy(newPenState) {
  27182. this.foreground = newPenState.foreground;
  27183. this.underline = newPenState.underline;
  27184. this.italics = newPenState.italics;
  27185. this.background = newPenState.background;
  27186. this.flash = newPenState.flash;
  27187. };
  27188. _proto2.toString = function toString() {
  27189. return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  27190. };
  27191. return PenState;
  27192. }();
  27193. /**
  27194. * Unicode character with styling and background.
  27195. * @constructor
  27196. */
  27197. var StyledUnicodeChar = /*#__PURE__*/function () {
  27198. function StyledUnicodeChar() {
  27199. this.uchar = ' ';
  27200. this.penState = new PenState();
  27201. }
  27202. var _proto3 = StyledUnicodeChar.prototype;
  27203. _proto3.reset = function reset() {
  27204. this.uchar = ' ';
  27205. this.penState.reset();
  27206. };
  27207. _proto3.setChar = function setChar(uchar, newPenState) {
  27208. this.uchar = uchar;
  27209. this.penState.copy(newPenState);
  27210. };
  27211. _proto3.setPenState = function setPenState(newPenState) {
  27212. this.penState.copy(newPenState);
  27213. };
  27214. _proto3.equals = function equals(other) {
  27215. return this.uchar === other.uchar && this.penState.equals(other.penState);
  27216. };
  27217. _proto3.copy = function copy(newChar) {
  27218. this.uchar = newChar.uchar;
  27219. this.penState.copy(newChar.penState);
  27220. };
  27221. _proto3.isEmpty = function isEmpty() {
  27222. return this.uchar === ' ' && this.penState.isDefault();
  27223. };
  27224. return StyledUnicodeChar;
  27225. }();
  27226. /**
  27227. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  27228. * @constructor
  27229. */
  27230. var Row = /*#__PURE__*/function () {
  27231. function Row(logger) {
  27232. this.chars = [];
  27233. this.pos = 0;
  27234. this.currPenState = new PenState();
  27235. this.cueStartTime = null;
  27236. this.logger = void 0;
  27237. for (var i = 0; i < NR_COLS; i++) {
  27238. this.chars.push(new StyledUnicodeChar());
  27239. }
  27240. this.logger = logger;
  27241. }
  27242. var _proto4 = Row.prototype;
  27243. _proto4.equals = function equals(other) {
  27244. for (var i = 0; i < NR_COLS; i++) {
  27245. if (!this.chars[i].equals(other.chars[i])) {
  27246. return false;
  27247. }
  27248. }
  27249. return true;
  27250. };
  27251. _proto4.copy = function copy(other) {
  27252. for (var i = 0; i < NR_COLS; i++) {
  27253. this.chars[i].copy(other.chars[i]);
  27254. }
  27255. };
  27256. _proto4.isEmpty = function isEmpty() {
  27257. var empty = true;
  27258. for (var i = 0; i < NR_COLS; i++) {
  27259. if (!this.chars[i].isEmpty()) {
  27260. empty = false;
  27261. break;
  27262. }
  27263. }
  27264. return empty;
  27265. }
  27266. /**
  27267. * Set the cursor to a valid column.
  27268. */;
  27269. _proto4.setCursor = function setCursor(absPos) {
  27270. if (this.pos !== absPos) {
  27271. this.pos = absPos;
  27272. }
  27273. if (this.pos < 0) {
  27274. this.logger.log(3, 'Negative cursor position ' + this.pos);
  27275. this.pos = 0;
  27276. } else if (this.pos > NR_COLS) {
  27277. this.logger.log(3, 'Too large cursor position ' + this.pos);
  27278. this.pos = NR_COLS;
  27279. }
  27280. }
  27281. /**
  27282. * Move the cursor relative to current position.
  27283. */;
  27284. _proto4.moveCursor = function moveCursor(relPos) {
  27285. var newPos = this.pos + relPos;
  27286. if (relPos > 1) {
  27287. for (var i = this.pos + 1; i < newPos + 1; i++) {
  27288. this.chars[i].setPenState(this.currPenState);
  27289. }
  27290. }
  27291. this.setCursor(newPos);
  27292. }
  27293. /**
  27294. * Backspace, move one step back and clear character.
  27295. */;
  27296. _proto4.backSpace = function backSpace() {
  27297. this.moveCursor(-1);
  27298. this.chars[this.pos].setChar(' ', this.currPenState);
  27299. };
  27300. _proto4.insertChar = function insertChar(_byte2) {
  27301. var _this = this;
  27302. if (_byte2 >= 0x90) {
  27303. // Extended char
  27304. this.backSpace();
  27305. }
  27306. var _char = getCharForByte(_byte2);
  27307. if (this.pos >= NR_COLS) {
  27308. this.logger.log(0, function () {
  27309. return 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + _this.pos + '. Skipping it!';
  27310. });
  27311. return;
  27312. }
  27313. this.chars[this.pos].setChar(_char, this.currPenState);
  27314. this.moveCursor(1);
  27315. };
  27316. _proto4.clearFromPos = function clearFromPos(startPos) {
  27317. var i;
  27318. for (i = startPos; i < NR_COLS; i++) {
  27319. this.chars[i].reset();
  27320. }
  27321. };
  27322. _proto4.clear = function clear() {
  27323. this.clearFromPos(0);
  27324. this.pos = 0;
  27325. this.currPenState.reset();
  27326. };
  27327. _proto4.clearToEndOfRow = function clearToEndOfRow() {
  27328. this.clearFromPos(this.pos);
  27329. };
  27330. _proto4.getTextString = function getTextString() {
  27331. var chars = [];
  27332. var empty = true;
  27333. for (var i = 0; i < NR_COLS; i++) {
  27334. var _char2 = this.chars[i].uchar;
  27335. if (_char2 !== ' ') {
  27336. empty = false;
  27337. }
  27338. chars.push(_char2);
  27339. }
  27340. if (empty) {
  27341. return '';
  27342. } else {
  27343. return chars.join('');
  27344. }
  27345. };
  27346. _proto4.setPenStyles = function setPenStyles(styles) {
  27347. this.currPenState.setStyles(styles);
  27348. var currChar = this.chars[this.pos];
  27349. currChar.setPenState(this.currPenState);
  27350. };
  27351. return Row;
  27352. }();
  27353. /**
  27354. * Keep a CEA-608 screen of 32x15 styled characters
  27355. * @constructor
  27356. */
  27357. var CaptionScreen = /*#__PURE__*/function () {
  27358. function CaptionScreen(logger) {
  27359. this.rows = [];
  27360. this.currRow = NR_ROWS - 1;
  27361. this.nrRollUpRows = null;
  27362. this.lastOutputScreen = null;
  27363. this.logger = void 0;
  27364. for (var i = 0; i < NR_ROWS; i++) {
  27365. this.rows.push(new Row(logger));
  27366. }
  27367. this.logger = logger;
  27368. }
  27369. var _proto5 = CaptionScreen.prototype;
  27370. _proto5.reset = function reset() {
  27371. for (var i = 0; i < NR_ROWS; i++) {
  27372. this.rows[i].clear();
  27373. }
  27374. this.currRow = NR_ROWS - 1;
  27375. };
  27376. _proto5.equals = function equals(other) {
  27377. var equal = true;
  27378. for (var i = 0; i < NR_ROWS; i++) {
  27379. if (!this.rows[i].equals(other.rows[i])) {
  27380. equal = false;
  27381. break;
  27382. }
  27383. }
  27384. return equal;
  27385. };
  27386. _proto5.copy = function copy(other) {
  27387. for (var i = 0; i < NR_ROWS; i++) {
  27388. this.rows[i].copy(other.rows[i]);
  27389. }
  27390. };
  27391. _proto5.isEmpty = function isEmpty() {
  27392. var empty = true;
  27393. for (var i = 0; i < NR_ROWS; i++) {
  27394. if (!this.rows[i].isEmpty()) {
  27395. empty = false;
  27396. break;
  27397. }
  27398. }
  27399. return empty;
  27400. };
  27401. _proto5.backSpace = function backSpace() {
  27402. var row = this.rows[this.currRow];
  27403. row.backSpace();
  27404. };
  27405. _proto5.clearToEndOfRow = function clearToEndOfRow() {
  27406. var row = this.rows[this.currRow];
  27407. row.clearToEndOfRow();
  27408. }
  27409. /**
  27410. * Insert a character (without styling) in the current row.
  27411. */;
  27412. _proto5.insertChar = function insertChar(_char3) {
  27413. var row = this.rows[this.currRow];
  27414. row.insertChar(_char3);
  27415. };
  27416. _proto5.setPen = function setPen(styles) {
  27417. var row = this.rows[this.currRow];
  27418. row.setPenStyles(styles);
  27419. };
  27420. _proto5.moveCursor = function moveCursor(relPos) {
  27421. var row = this.rows[this.currRow];
  27422. row.moveCursor(relPos);
  27423. };
  27424. _proto5.setCursor = function setCursor(absPos) {
  27425. this.logger.log(2, 'setCursor: ' + absPos);
  27426. var row = this.rows[this.currRow];
  27427. row.setCursor(absPos);
  27428. };
  27429. _proto5.setPAC = function setPAC(pacData) {
  27430. this.logger.log(2, function () {
  27431. return 'pacData = ' + stringify(pacData);
  27432. });
  27433. var newRow = pacData.row - 1;
  27434. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  27435. newRow = this.nrRollUpRows - 1;
  27436. }
  27437. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  27438. if (this.nrRollUpRows && this.currRow !== newRow) {
  27439. // clear all rows first
  27440. for (var i = 0; i < NR_ROWS; i++) {
  27441. this.rows[i].clear();
  27442. }
  27443. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  27444. // topRowIndex - the start of rows to copy (inclusive index)
  27445. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  27446. // We only copy if the last position was already shown.
  27447. // We use the cueStartTime value to check this.
  27448. var lastOutputScreen = this.lastOutputScreen;
  27449. if (lastOutputScreen) {
  27450. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  27451. var time = this.logger.time;
  27452. if (prevLineTime !== null && time !== null && prevLineTime < time) {
  27453. for (var _i = 0; _i < this.nrRollUpRows; _i++) {
  27454. this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
  27455. }
  27456. }
  27457. }
  27458. }
  27459. this.currRow = newRow;
  27460. var row = this.rows[this.currRow];
  27461. if (pacData.indent !== null) {
  27462. var indent = pacData.indent;
  27463. var prevPos = Math.max(indent - 1, 0);
  27464. row.setCursor(pacData.indent);
  27465. pacData.color = row.chars[prevPos].penState.foreground;
  27466. }
  27467. var styles = {
  27468. foreground: pacData.color,
  27469. underline: pacData.underline,
  27470. italics: pacData.italics,
  27471. background: 'black',
  27472. flash: false
  27473. };
  27474. this.setPen(styles);
  27475. }
  27476. /**
  27477. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  27478. */;
  27479. _proto5.setBkgData = function setBkgData(bkgData) {
  27480. this.logger.log(2, function () {
  27481. return 'bkgData = ' + stringify(bkgData);
  27482. });
  27483. this.backSpace();
  27484. this.setPen(bkgData);
  27485. this.insertChar(0x20); // Space
  27486. };
  27487. _proto5.setRollUpRows = function setRollUpRows(nrRows) {
  27488. this.nrRollUpRows = nrRows;
  27489. };
  27490. _proto5.rollUp = function rollUp() {
  27491. var _this2 = this;
  27492. if (this.nrRollUpRows === null) {
  27493. this.logger.log(3, 'roll_up but nrRollUpRows not set yet');
  27494. return; // Not properly setup
  27495. }
  27496. this.logger.log(1, function () {
  27497. return _this2.getDisplayText();
  27498. });
  27499. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  27500. var topRow = this.rows.splice(topRowIndex, 1)[0];
  27501. topRow.clear();
  27502. this.rows.splice(this.currRow, 0, topRow);
  27503. this.logger.log(2, 'Rolling up');
  27504. // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
  27505. }
  27506. /**
  27507. * Get all non-empty rows with as unicode text.
  27508. */;
  27509. _proto5.getDisplayText = function getDisplayText(asOneRow) {
  27510. asOneRow = asOneRow || false;
  27511. var displayText = [];
  27512. var text = '';
  27513. var rowNr = -1;
  27514. for (var i = 0; i < NR_ROWS; i++) {
  27515. var rowText = this.rows[i].getTextString();
  27516. if (rowText) {
  27517. rowNr = i + 1;
  27518. if (asOneRow) {
  27519. displayText.push('Row ' + rowNr + ": '" + rowText + "'");
  27520. } else {
  27521. displayText.push(rowText.trim());
  27522. }
  27523. }
  27524. }
  27525. if (displayText.length > 0) {
  27526. if (asOneRow) {
  27527. text = '[' + displayText.join(' | ') + ']';
  27528. } else {
  27529. text = displayText.join('\n');
  27530. }
  27531. }
  27532. return text;
  27533. };
  27534. _proto5.getTextAndFormat = function getTextAndFormat() {
  27535. return this.rows;
  27536. };
  27537. return CaptionScreen;
  27538. }();
  27539. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  27540. var Cea608Channel = /*#__PURE__*/function () {
  27541. function Cea608Channel(channelNumber, outputFilter, logger) {
  27542. this.chNr = void 0;
  27543. this.outputFilter = void 0;
  27544. this.mode = void 0;
  27545. this.verbose = void 0;
  27546. this.displayedMemory = void 0;
  27547. this.nonDisplayedMemory = void 0;
  27548. this.lastOutputScreen = void 0;
  27549. this.currRollUpRow = void 0;
  27550. this.writeScreen = void 0;
  27551. this.cueStartTime = void 0;
  27552. this.logger = void 0;
  27553. this.chNr = channelNumber;
  27554. this.outputFilter = outputFilter;
  27555. this.mode = null;
  27556. this.verbose = 0;
  27557. this.displayedMemory = new CaptionScreen(logger);
  27558. this.nonDisplayedMemory = new CaptionScreen(logger);
  27559. this.lastOutputScreen = new CaptionScreen(logger);
  27560. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  27561. this.writeScreen = this.displayedMemory;
  27562. this.mode = null;
  27563. this.cueStartTime = null; // Keeps track of where a cue started.
  27564. this.logger = logger;
  27565. }
  27566. var _proto6 = Cea608Channel.prototype;
  27567. _proto6.reset = function reset() {
  27568. this.mode = null;
  27569. this.displayedMemory.reset();
  27570. this.nonDisplayedMemory.reset();
  27571. this.lastOutputScreen.reset();
  27572. this.outputFilter.reset();
  27573. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  27574. this.writeScreen = this.displayedMemory;
  27575. this.mode = null;
  27576. this.cueStartTime = null;
  27577. };
  27578. _proto6.getHandler = function getHandler() {
  27579. return this.outputFilter;
  27580. };
  27581. _proto6.setHandler = function setHandler(newHandler) {
  27582. this.outputFilter = newHandler;
  27583. };
  27584. _proto6.setPAC = function setPAC(pacData) {
  27585. this.writeScreen.setPAC(pacData);
  27586. };
  27587. _proto6.setBkgData = function setBkgData(bkgData) {
  27588. this.writeScreen.setBkgData(bkgData);
  27589. };
  27590. _proto6.setMode = function setMode(newMode) {
  27591. if (newMode === this.mode) {
  27592. return;
  27593. }
  27594. this.mode = newMode;
  27595. this.logger.log(2, function () {
  27596. return 'MODE=' + newMode;
  27597. });
  27598. if (this.mode === 'MODE_POP-ON') {
  27599. this.writeScreen = this.nonDisplayedMemory;
  27600. } else {
  27601. this.writeScreen = this.displayedMemory;
  27602. this.writeScreen.reset();
  27603. }
  27604. if (this.mode !== 'MODE_ROLL-UP') {
  27605. this.displayedMemory.nrRollUpRows = null;
  27606. this.nonDisplayedMemory.nrRollUpRows = null;
  27607. }
  27608. this.mode = newMode;
  27609. };
  27610. _proto6.insertChars = function insertChars(chars) {
  27611. var _this3 = this;
  27612. for (var i = 0; i < chars.length; i++) {
  27613. this.writeScreen.insertChar(chars[i]);
  27614. }
  27615. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  27616. this.logger.log(2, function () {
  27617. return screen + ': ' + _this3.writeScreen.getDisplayText(true);
  27618. });
  27619. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  27620. this.logger.log(1, function () {
  27621. return 'DISPLAYED: ' + _this3.displayedMemory.getDisplayText(true);
  27622. });
  27623. this.outputDataUpdate();
  27624. }
  27625. };
  27626. _proto6.ccRCL = function ccRCL() {
  27627. // Resume Caption Loading (switch mode to Pop On)
  27628. this.logger.log(2, 'RCL - Resume Caption Loading');
  27629. this.setMode('MODE_POP-ON');
  27630. };
  27631. _proto6.ccBS = function ccBS() {
  27632. // BackSpace
  27633. this.logger.log(2, 'BS - BackSpace');
  27634. if (this.mode === 'MODE_TEXT') {
  27635. return;
  27636. }
  27637. this.writeScreen.backSpace();
  27638. if (this.writeScreen === this.displayedMemory) {
  27639. this.outputDataUpdate();
  27640. }
  27641. };
  27642. _proto6.ccAOF = function ccAOF() {
  27643. // Reserved (formerly Alarm Off)
  27644. };
  27645. _proto6.ccAON = function ccAON() {
  27646. // Reserved (formerly Alarm On)
  27647. };
  27648. _proto6.ccDER = function ccDER() {
  27649. // Delete to End of Row
  27650. this.logger.log(2, 'DER- Delete to End of Row');
  27651. this.writeScreen.clearToEndOfRow();
  27652. this.outputDataUpdate();
  27653. };
  27654. _proto6.ccRU = function ccRU(nrRows) {
  27655. // Roll-Up Captions-2,3,or 4 Rows
  27656. this.logger.log(2, 'RU(' + nrRows + ') - Roll Up');
  27657. this.writeScreen = this.displayedMemory;
  27658. this.setMode('MODE_ROLL-UP');
  27659. this.writeScreen.setRollUpRows(nrRows);
  27660. };
  27661. _proto6.ccFON = function ccFON() {
  27662. // Flash On
  27663. this.logger.log(2, 'FON - Flash On');
  27664. this.writeScreen.setPen({
  27665. flash: true
  27666. });
  27667. };
  27668. _proto6.ccRDC = function ccRDC() {
  27669. // Resume Direct Captioning (switch mode to PaintOn)
  27670. this.logger.log(2, 'RDC - Resume Direct Captioning');
  27671. this.setMode('MODE_PAINT-ON');
  27672. };
  27673. _proto6.ccTR = function ccTR() {
  27674. // Text Restart in text mode (not supported, however)
  27675. this.logger.log(2, 'TR');
  27676. this.setMode('MODE_TEXT');
  27677. };
  27678. _proto6.ccRTD = function ccRTD() {
  27679. // Resume Text Display in Text mode (not supported, however)
  27680. this.logger.log(2, 'RTD');
  27681. this.setMode('MODE_TEXT');
  27682. };
  27683. _proto6.ccEDM = function ccEDM() {
  27684. // Erase Displayed Memory
  27685. this.logger.log(2, 'EDM - Erase Displayed Memory');
  27686. this.displayedMemory.reset();
  27687. this.outputDataUpdate(true);
  27688. };
  27689. _proto6.ccCR = function ccCR() {
  27690. // Carriage Return
  27691. this.logger.log(2, 'CR - Carriage Return');
  27692. this.writeScreen.rollUp();
  27693. this.outputDataUpdate(true);
  27694. };
  27695. _proto6.ccENM = function ccENM() {
  27696. // Erase Non-Displayed Memory
  27697. this.logger.log(2, 'ENM - Erase Non-displayed Memory');
  27698. this.nonDisplayedMemory.reset();
  27699. };
  27700. _proto6.ccEOC = function ccEOC() {
  27701. var _this4 = this;
  27702. // End of Caption (Flip Memories)
  27703. this.logger.log(2, 'EOC - End Of Caption');
  27704. if (this.mode === 'MODE_POP-ON') {
  27705. var tmp = this.displayedMemory;
  27706. this.displayedMemory = this.nonDisplayedMemory;
  27707. this.nonDisplayedMemory = tmp;
  27708. this.writeScreen = this.nonDisplayedMemory;
  27709. this.logger.log(1, function () {
  27710. return 'DISP: ' + _this4.displayedMemory.getDisplayText();
  27711. });
  27712. }
  27713. this.outputDataUpdate(true);
  27714. };
  27715. _proto6.ccTO = function ccTO(nrCols) {
  27716. // Tab Offset 1,2, or 3 columns
  27717. this.logger.log(2, 'TO(' + nrCols + ') - Tab Offset');
  27718. this.writeScreen.moveCursor(nrCols);
  27719. };
  27720. _proto6.ccMIDROW = function ccMIDROW(secondByte) {
  27721. // Parse MIDROW command
  27722. var styles = {
  27723. flash: false
  27724. };
  27725. styles.underline = secondByte % 2 === 1;
  27726. styles.italics = secondByte >= 0x2e;
  27727. if (!styles.italics) {
  27728. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  27729. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  27730. styles.foreground = colors[colorIndex];
  27731. } else {
  27732. styles.foreground = 'white';
  27733. }
  27734. this.logger.log(2, 'MIDROW: ' + stringify(styles));
  27735. this.writeScreen.setPen(styles);
  27736. };
  27737. _proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
  27738. if (dispatch === void 0) {
  27739. dispatch = false;
  27740. }
  27741. var time = this.logger.time;
  27742. if (time === null) {
  27743. return;
  27744. }
  27745. if (this.outputFilter) {
  27746. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  27747. // Start of a new cue
  27748. this.cueStartTime = time;
  27749. } else {
  27750. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  27751. this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
  27752. if (dispatch && this.outputFilter.dispatchCue) {
  27753. this.outputFilter.dispatchCue();
  27754. }
  27755. this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
  27756. }
  27757. }
  27758. this.lastOutputScreen.copy(this.displayedMemory);
  27759. }
  27760. };
  27761. _proto6.cueSplitAtTime = function cueSplitAtTime(t) {
  27762. if (this.outputFilter) {
  27763. if (!this.displayedMemory.isEmpty()) {
  27764. if (this.outputFilter.newCue) {
  27765. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  27766. }
  27767. this.cueStartTime = t;
  27768. }
  27769. }
  27770. };
  27771. return Cea608Channel;
  27772. }(); // Will be 1 or 2 when parsing captions
  27773. var Cea608Parser = /*#__PURE__*/function () {
  27774. function Cea608Parser(field, out1, out2) {
  27775. this.channels = void 0;
  27776. this.currentChannel = 0;
  27777. this.cmdHistory = createCmdHistory();
  27778. this.logger = void 0;
  27779. var logger = this.logger = new CaptionsLogger();
  27780. this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
  27781. }
  27782. var _proto7 = Cea608Parser.prototype;
  27783. _proto7.getHandler = function getHandler(channel) {
  27784. return this.channels[channel].getHandler();
  27785. };
  27786. _proto7.setHandler = function setHandler(channel, newHandler) {
  27787. this.channels[channel].setHandler(newHandler);
  27788. }
  27789. /**
  27790. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  27791. */;
  27792. _proto7.addData = function addData(time, byteList) {
  27793. var _this5 = this;
  27794. this.logger.time = time;
  27795. var _loop = function _loop(i) {
  27796. var a = byteList[i] & 0x7f;
  27797. var b = byteList[i + 1] & 0x7f;
  27798. var cmdFound = false;
  27799. var charsFound = null;
  27800. if (a === 0 && b === 0) {
  27801. return 0; // continue
  27802. } else {
  27803. _this5.logger.log(3, function () {
  27804. return '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')';
  27805. });
  27806. }
  27807. var cmdHistory = _this5.cmdHistory;
  27808. var isControlCode = a >= 0x10 && a <= 0x1f;
  27809. if (isControlCode) {
  27810. // Skip redundant control codes
  27811. if (hasCmdRepeated(a, b, cmdHistory)) {
  27812. setLastCmd(null, null, cmdHistory);
  27813. _this5.logger.log(3, function () {
  27814. return 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped';
  27815. });
  27816. return 0; // continue
  27817. }
  27818. setLastCmd(a, b, _this5.cmdHistory);
  27819. cmdFound = _this5.parseCmd(a, b);
  27820. if (!cmdFound) {
  27821. cmdFound = _this5.parseMidrow(a, b);
  27822. }
  27823. if (!cmdFound) {
  27824. cmdFound = _this5.parsePAC(a, b);
  27825. }
  27826. if (!cmdFound) {
  27827. cmdFound = _this5.parseBackgroundAttributes(a, b);
  27828. }
  27829. } else {
  27830. setLastCmd(null, null, cmdHistory);
  27831. }
  27832. if (!cmdFound) {
  27833. charsFound = _this5.parseChars(a, b);
  27834. if (charsFound) {
  27835. var currChNr = _this5.currentChannel;
  27836. if (currChNr && currChNr > 0) {
  27837. var channel = _this5.channels[currChNr];
  27838. channel.insertChars(charsFound);
  27839. } else {
  27840. _this5.logger.log(2, 'No channel found yet. TEXT-MODE?');
  27841. }
  27842. }
  27843. }
  27844. if (!cmdFound && !charsFound) {
  27845. _this5.logger.log(2, function () {
  27846. return "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]);
  27847. });
  27848. }
  27849. },
  27850. _ret;
  27851. for (var i = 0; i < byteList.length; i += 2) {
  27852. _ret = _loop(i);
  27853. if (_ret === 0) continue;
  27854. }
  27855. }
  27856. /**
  27857. * Parse Command.
  27858. * @returns True if a command was found
  27859. */;
  27860. _proto7.parseCmd = function parseCmd(a, b) {
  27861. var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
  27862. var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
  27863. if (!(cond1 || cond2)) {
  27864. return false;
  27865. }
  27866. var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
  27867. var channel = this.channels[chNr];
  27868. if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
  27869. if (b === 0x20) {
  27870. channel.ccRCL();
  27871. } else if (b === 0x21) {
  27872. channel.ccBS();
  27873. } else if (b === 0x22) {
  27874. channel.ccAOF();
  27875. } else if (b === 0x23) {
  27876. channel.ccAON();
  27877. } else if (b === 0x24) {
  27878. channel.ccDER();
  27879. } else if (b === 0x25) {
  27880. channel.ccRU(2);
  27881. } else if (b === 0x26) {
  27882. channel.ccRU(3);
  27883. } else if (b === 0x27) {
  27884. channel.ccRU(4);
  27885. } else if (b === 0x28) {
  27886. channel.ccFON();
  27887. } else if (b === 0x29) {
  27888. channel.ccRDC();
  27889. } else if (b === 0x2a) {
  27890. channel.ccTR();
  27891. } else if (b === 0x2b) {
  27892. channel.ccRTD();
  27893. } else if (b === 0x2c) {
  27894. channel.ccEDM();
  27895. } else if (b === 0x2d) {
  27896. channel.ccCR();
  27897. } else if (b === 0x2e) {
  27898. channel.ccENM();
  27899. } else if (b === 0x2f) {
  27900. channel.ccEOC();
  27901. }
  27902. } else {
  27903. // a == 0x17 || a == 0x1F
  27904. channel.ccTO(b - 0x20);
  27905. }
  27906. this.currentChannel = chNr;
  27907. return true;
  27908. }
  27909. /**
  27910. * Parse midrow styling command
  27911. */;
  27912. _proto7.parseMidrow = function parseMidrow(a, b) {
  27913. var chNr = 0;
  27914. if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
  27915. if (a === 0x11) {
  27916. chNr = 1;
  27917. } else {
  27918. chNr = 2;
  27919. }
  27920. if (chNr !== this.currentChannel) {
  27921. this.logger.log(0, 'Mismatch channel in midrow parsing');
  27922. return false;
  27923. }
  27924. var channel = this.channels[chNr];
  27925. if (!channel) {
  27926. return false;
  27927. }
  27928. channel.ccMIDROW(b);
  27929. this.logger.log(3, function () {
  27930. return 'MIDROW (' + numArrayToHexArray([a, b]) + ')';
  27931. });
  27932. return true;
  27933. }
  27934. return false;
  27935. }
  27936. /**
  27937. * Parse Preable Access Codes (Table 53).
  27938. * @returns {Boolean} Tells if PAC found
  27939. */;
  27940. _proto7.parsePAC = function parsePAC(a, b) {
  27941. var row;
  27942. var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
  27943. var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
  27944. if (!(case1 || case2)) {
  27945. return false;
  27946. }
  27947. var chNr = a <= 0x17 ? 1 : 2;
  27948. if (b >= 0x40 && b <= 0x5f) {
  27949. row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  27950. } else {
  27951. // 0x60 <= b <= 0x7F
  27952. row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  27953. }
  27954. var channel = this.channels[chNr];
  27955. if (!channel) {
  27956. return false;
  27957. }
  27958. channel.setPAC(this.interpretPAC(row, b));
  27959. this.currentChannel = chNr;
  27960. return true;
  27961. }
  27962. /**
  27963. * Interpret the second byte of the pac, and return the information.
  27964. * @returns pacData with style parameters
  27965. */;
  27966. _proto7.interpretPAC = function interpretPAC(row, _byte3) {
  27967. var pacIndex;
  27968. var pacData = {
  27969. color: null,
  27970. italics: false,
  27971. indent: null,
  27972. underline: false,
  27973. row: row
  27974. };
  27975. if (_byte3 > 0x5f) {
  27976. pacIndex = _byte3 - 0x60;
  27977. } else {
  27978. pacIndex = _byte3 - 0x40;
  27979. }
  27980. pacData.underline = (pacIndex & 1) === 1;
  27981. if (pacIndex <= 0xd) {
  27982. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  27983. } else if (pacIndex <= 0xf) {
  27984. pacData.italics = true;
  27985. pacData.color = 'white';
  27986. } else {
  27987. pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  27988. }
  27989. return pacData; // Note that row has zero offset. The spec uses 1.
  27990. }
  27991. /**
  27992. * Parse characters.
  27993. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  27994. */;
  27995. _proto7.parseChars = function parseChars(a, b) {
  27996. var channelNr;
  27997. var charCodes = null;
  27998. var charCode1 = null;
  27999. if (a >= 0x19) {
  28000. channelNr = 2;
  28001. charCode1 = a - 8;
  28002. } else {
  28003. channelNr = 1;
  28004. charCode1 = a;
  28005. }
  28006. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  28007. // Special character
  28008. var oneCode;
  28009. if (charCode1 === 0x11) {
  28010. oneCode = b + 0x50;
  28011. } else if (charCode1 === 0x12) {
  28012. oneCode = b + 0x70;
  28013. } else {
  28014. oneCode = b + 0x90;
  28015. }
  28016. this.logger.log(2, function () {
  28017. return "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr;
  28018. });
  28019. charCodes = [oneCode];
  28020. } else if (a >= 0x20 && a <= 0x7f) {
  28021. charCodes = b === 0 ? [a] : [a, b];
  28022. }
  28023. if (charCodes) {
  28024. this.logger.log(3, function () {
  28025. return 'Char codes = ' + numArrayToHexArray(charCodes).join(',');
  28026. });
  28027. }
  28028. return charCodes;
  28029. }
  28030. /**
  28031. * Parse extended background attributes as well as new foreground color black.
  28032. * @returns True if background attributes are found
  28033. */;
  28034. _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
  28035. var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
  28036. var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
  28037. if (!(case1 || case2)) {
  28038. return false;
  28039. }
  28040. var index;
  28041. var bkgData = {};
  28042. if (a === 0x10 || a === 0x18) {
  28043. index = Math.floor((b - 0x20) / 2);
  28044. bkgData.background = backgroundColors[index];
  28045. if (b % 2 === 1) {
  28046. bkgData.background = bkgData.background + '_semi';
  28047. }
  28048. } else if (b === 0x2d) {
  28049. bkgData.background = 'transparent';
  28050. } else {
  28051. bkgData.foreground = 'black';
  28052. if (b === 0x2f) {
  28053. bkgData.underline = true;
  28054. }
  28055. }
  28056. var chNr = a <= 0x17 ? 1 : 2;
  28057. var channel = this.channels[chNr];
  28058. channel.setBkgData(bkgData);
  28059. return true;
  28060. }
  28061. /**
  28062. * Reset state of parser and its channels.
  28063. */;
  28064. _proto7.reset = function reset() {
  28065. for (var i = 0; i < Object.keys(this.channels).length; i++) {
  28066. var channel = this.channels[i];
  28067. if (channel) {
  28068. channel.reset();
  28069. }
  28070. }
  28071. setLastCmd(null, null, this.cmdHistory);
  28072. }
  28073. /**
  28074. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  28075. */;
  28076. _proto7.cueSplitAtTime = function cueSplitAtTime(t) {
  28077. for (var i = 0; i < this.channels.length; i++) {
  28078. var channel = this.channels[i];
  28079. if (channel) {
  28080. channel.cueSplitAtTime(t);
  28081. }
  28082. }
  28083. };
  28084. return Cea608Parser;
  28085. }();
  28086. function setLastCmd(a, b, cmdHistory) {
  28087. cmdHistory.a = a;
  28088. cmdHistory.b = b;
  28089. }
  28090. function hasCmdRepeated(a, b, cmdHistory) {
  28091. return cmdHistory.a === a && cmdHistory.b === b;
  28092. }
  28093. function createCmdHistory() {
  28094. return {
  28095. a: null,
  28096. b: null
  28097. };
  28098. }
  28099. /**
  28100. * Copyright 2013 vtt.js Contributors
  28101. *
  28102. * Licensed under the Apache License, Version 2.0 (the 'License');
  28103. * you may not use this file except in compliance with the License.
  28104. * You may obtain a copy of the License at
  28105. *
  28106. * http://www.apache.org/licenses/LICENSE-2.0
  28107. *
  28108. * Unless required by applicable law or agreed to in writing, software
  28109. * distributed under the License is distributed on an 'AS IS' BASIS,
  28110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28111. * See the License for the specific language governing permissions and
  28112. * limitations under the License.
  28113. */
  28114. var VTTCue = (function () {
  28115. if (optionalSelf != null && optionalSelf.VTTCue) {
  28116. return self.VTTCue;
  28117. }
  28118. var AllowedDirections = ['', 'lr', 'rl'];
  28119. var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
  28120. function isAllowedValue(allowed, value) {
  28121. if (typeof value !== 'string') {
  28122. return false;
  28123. }
  28124. // necessary for assuring the generic conforms to the Array interface
  28125. if (!Array.isArray(allowed)) {
  28126. return false;
  28127. }
  28128. // reset the type so that the next narrowing works well
  28129. var lcValue = value.toLowerCase();
  28130. // use the allow list to narrow the type to a specific subset of strings
  28131. if (~allowed.indexOf(lcValue)) {
  28132. return lcValue;
  28133. }
  28134. return false;
  28135. }
  28136. function findDirectionSetting(value) {
  28137. return isAllowedValue(AllowedDirections, value);
  28138. }
  28139. function findAlignSetting(value) {
  28140. return isAllowedValue(AllowedAlignments, value);
  28141. }
  28142. function extend(obj) {
  28143. for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  28144. rest[_key - 1] = arguments[_key];
  28145. }
  28146. var i = 1;
  28147. for (; i < arguments.length; i++) {
  28148. var cobj = arguments[i];
  28149. for (var p in cobj) {
  28150. obj[p] = cobj[p];
  28151. }
  28152. }
  28153. return obj;
  28154. }
  28155. function VTTCue(startTime, endTime, text) {
  28156. var cue = this;
  28157. var baseObj = {
  28158. enumerable: true
  28159. };
  28160. /**
  28161. * Shim implementation specific properties. These properties are not in
  28162. * the spec.
  28163. */
  28164. // Lets us know when the VTTCue's data has changed in such a way that we need
  28165. // to recompute its display state. This lets us compute its display state
  28166. // lazily.
  28167. cue.hasBeenReset = false;
  28168. /**
  28169. * VTTCue and TextTrackCue properties
  28170. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  28171. */
  28172. var _id = '';
  28173. var _pauseOnExit = false;
  28174. var _startTime = startTime;
  28175. var _endTime = endTime;
  28176. var _text = text;
  28177. var _region = null;
  28178. var _vertical = '';
  28179. var _snapToLines = true;
  28180. var _line = 'auto';
  28181. var _lineAlign = 'start';
  28182. var _position = 50;
  28183. var _positionAlign = 'middle';
  28184. var _size = 50;
  28185. var _align = 'middle';
  28186. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  28187. get: function get() {
  28188. return _id;
  28189. },
  28190. set: function set(value) {
  28191. _id = '' + value;
  28192. }
  28193. }));
  28194. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  28195. get: function get() {
  28196. return _pauseOnExit;
  28197. },
  28198. set: function set(value) {
  28199. _pauseOnExit = !!value;
  28200. }
  28201. }));
  28202. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  28203. get: function get() {
  28204. return _startTime;
  28205. },
  28206. set: function set(value) {
  28207. if (typeof value !== 'number') {
  28208. throw new TypeError('Start time must be set to a number.');
  28209. }
  28210. _startTime = value;
  28211. this.hasBeenReset = true;
  28212. }
  28213. }));
  28214. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  28215. get: function get() {
  28216. return _endTime;
  28217. },
  28218. set: function set(value) {
  28219. if (typeof value !== 'number') {
  28220. throw new TypeError('End time must be set to a number.');
  28221. }
  28222. _endTime = value;
  28223. this.hasBeenReset = true;
  28224. }
  28225. }));
  28226. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  28227. get: function get() {
  28228. return _text;
  28229. },
  28230. set: function set(value) {
  28231. _text = '' + value;
  28232. this.hasBeenReset = true;
  28233. }
  28234. }));
  28235. // todo: implement VTTRegion polyfill?
  28236. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  28237. get: function get() {
  28238. return _region;
  28239. },
  28240. set: function set(value) {
  28241. _region = value;
  28242. this.hasBeenReset = true;
  28243. }
  28244. }));
  28245. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  28246. get: function get() {
  28247. return _vertical;
  28248. },
  28249. set: function set(value) {
  28250. var setting = findDirectionSetting(value);
  28251. // Have to check for false because the setting an be an empty string.
  28252. if (setting === false) {
  28253. throw new SyntaxError('An invalid or illegal string was specified.');
  28254. }
  28255. _vertical = setting;
  28256. this.hasBeenReset = true;
  28257. }
  28258. }));
  28259. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  28260. get: function get() {
  28261. return _snapToLines;
  28262. },
  28263. set: function set(value) {
  28264. _snapToLines = !!value;
  28265. this.hasBeenReset = true;
  28266. }
  28267. }));
  28268. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  28269. get: function get() {
  28270. return _line;
  28271. },
  28272. set: function set(value) {
  28273. if (typeof value !== 'number' && value !== 'auto') {
  28274. throw new SyntaxError('An invalid number or illegal string was specified.');
  28275. }
  28276. _line = value;
  28277. this.hasBeenReset = true;
  28278. }
  28279. }));
  28280. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  28281. get: function get() {
  28282. return _lineAlign;
  28283. },
  28284. set: function set(value) {
  28285. var setting = findAlignSetting(value);
  28286. if (!setting) {
  28287. throw new SyntaxError('An invalid or illegal string was specified.');
  28288. }
  28289. _lineAlign = setting;
  28290. this.hasBeenReset = true;
  28291. }
  28292. }));
  28293. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  28294. get: function get() {
  28295. return _position;
  28296. },
  28297. set: function set(value) {
  28298. if (value < 0 || value > 100) {
  28299. throw new Error('Position must be between 0 and 100.');
  28300. }
  28301. _position = value;
  28302. this.hasBeenReset = true;
  28303. }
  28304. }));
  28305. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  28306. get: function get() {
  28307. return _positionAlign;
  28308. },
  28309. set: function set(value) {
  28310. var setting = findAlignSetting(value);
  28311. if (!setting) {
  28312. throw new SyntaxError('An invalid or illegal string was specified.');
  28313. }
  28314. _positionAlign = setting;
  28315. this.hasBeenReset = true;
  28316. }
  28317. }));
  28318. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  28319. get: function get() {
  28320. return _size;
  28321. },
  28322. set: function set(value) {
  28323. if (value < 0 || value > 100) {
  28324. throw new Error('Size must be between 0 and 100.');
  28325. }
  28326. _size = value;
  28327. this.hasBeenReset = true;
  28328. }
  28329. }));
  28330. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  28331. get: function get() {
  28332. return _align;
  28333. },
  28334. set: function set(value) {
  28335. var setting = findAlignSetting(value);
  28336. if (!setting) {
  28337. throw new SyntaxError('An invalid or illegal string was specified.');
  28338. }
  28339. _align = setting;
  28340. this.hasBeenReset = true;
  28341. }
  28342. }));
  28343. /**
  28344. * Other <track> spec defined properties
  28345. */
  28346. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  28347. cue.displayState = undefined;
  28348. }
  28349. /**
  28350. * VTTCue methods
  28351. */
  28352. VTTCue.prototype.getCueAsHTML = function () {
  28353. // Assume WebVTT.convertCueToDOMTree is on the global.
  28354. var WebVTT = self.WebVTT;
  28355. return WebVTT.convertCueToDOMTree(self, this.text);
  28356. };
  28357. // this is a polyfill hack
  28358. return VTTCue;
  28359. })();
  28360. /*
  28361. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
  28362. */
  28363. var StringDecoder = /*#__PURE__*/function () {
  28364. function StringDecoder() {}
  28365. var _proto = StringDecoder.prototype;
  28366. _proto.decode = function decode(data, options) {
  28367. if (!data) {
  28368. return '';
  28369. }
  28370. if (typeof data !== 'string') {
  28371. throw new Error('Error - expected string data.');
  28372. }
  28373. return decodeURIComponent(encodeURIComponent(data));
  28374. };
  28375. return StringDecoder;
  28376. }(); // Try to parse input as a time stamp.
  28377. function parseTimeStamp(input) {
  28378. function computeSeconds(h, m, s, f) {
  28379. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
  28380. }
  28381. var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
  28382. if (!m) {
  28383. return null;
  28384. }
  28385. if (parseFloat(m[2]) > 59) {
  28386. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  28387. // First position is hours as it's over 59.
  28388. return computeSeconds(m[2], m[3], 0, m[4]);
  28389. }
  28390. // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
  28391. return computeSeconds(m[1], m[2], m[3], m[4]);
  28392. }
  28393. // A settings object holds key/value pairs and will ignore anything but the first
  28394. // assignment to a specific key.
  28395. var Settings = /*#__PURE__*/function () {
  28396. function Settings() {
  28397. this.values = Object.create(null);
  28398. }
  28399. var _proto2 = Settings.prototype;
  28400. // Only accept the first assignment to any key.
  28401. _proto2.set = function set(k, v) {
  28402. if (!this.get(k) && v !== '') {
  28403. this.values[k] = v;
  28404. }
  28405. }
  28406. // Return the value for a key, or a default value.
  28407. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  28408. // a number of possible default values as properties where 'defaultKey' is
  28409. // the key of the property that will be chosen; otherwise it's assumed to be
  28410. // a single value.
  28411. ;
  28412. _proto2.get = function get(k, dflt, defaultKey) {
  28413. if (defaultKey) {
  28414. return this.has(k) ? this.values[k] : dflt[defaultKey];
  28415. }
  28416. return this.has(k) ? this.values[k] : dflt;
  28417. }
  28418. // Check whether we have a value for a key.
  28419. ;
  28420. _proto2.has = function has(k) {
  28421. return k in this.values;
  28422. }
  28423. // Accept a setting if its one of the given alternatives.
  28424. ;
  28425. _proto2.alt = function alt(k, v, a) {
  28426. for (var n = 0; n < a.length; ++n) {
  28427. if (v === a[n]) {
  28428. this.set(k, v);
  28429. break;
  28430. }
  28431. }
  28432. }
  28433. // Accept a setting if its a valid (signed) integer.
  28434. ;
  28435. _proto2.integer = function integer(k, v) {
  28436. if (/^-?\d+$/.test(v)) {
  28437. // integer
  28438. this.set(k, parseInt(v, 10));
  28439. }
  28440. }
  28441. // Accept a setting if its a valid percentage.
  28442. ;
  28443. _proto2.percent = function percent(k, v) {
  28444. if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
  28445. var _percent = parseFloat(v);
  28446. if (_percent >= 0 && _percent <= 100) {
  28447. this.set(k, _percent);
  28448. return true;
  28449. }
  28450. }
  28451. return false;
  28452. };
  28453. return Settings;
  28454. }(); // Helper function to parse input into groups separated by 'groupDelim', and
  28455. // interpret each group as a key/value pair separated by 'keyValueDelim'.
  28456. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  28457. var groups = groupDelim ? input.split(groupDelim) : [input];
  28458. for (var i in groups) {
  28459. if (typeof groups[i] !== 'string') {
  28460. continue;
  28461. }
  28462. var kv = groups[i].split(keyValueDelim);
  28463. if (kv.length !== 2) {
  28464. continue;
  28465. }
  28466. var k = kv[0];
  28467. var v = kv[1];
  28468. callback(k, v);
  28469. }
  28470. }
  28471. var defaults = new VTTCue(0, 0, '');
  28472. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  28473. // Safari doesn't yet support this change, but FF and Chrome do.
  28474. var center = defaults.align === 'middle' ? 'middle' : 'center';
  28475. function parseCue(input, cue, regionList) {
  28476. // Remember the original input if we need to throw an error.
  28477. var oInput = input;
  28478. // 4.1 WebVTT timestamp
  28479. function consumeTimeStamp() {
  28480. var ts = parseTimeStamp(input);
  28481. if (ts === null) {
  28482. throw new Error('Malformed timestamp: ' + oInput);
  28483. }
  28484. // Remove time stamp from input.
  28485. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  28486. return ts;
  28487. }
  28488. // 4.4.2 WebVTT cue settings
  28489. function consumeCueSettings(input, cue) {
  28490. var settings = new Settings();
  28491. parseOptions(input, function (k, v) {
  28492. var vals;
  28493. switch (k) {
  28494. case 'region':
  28495. // Find the last region we parsed with the same region id.
  28496. for (var i = regionList.length - 1; i >= 0; i--) {
  28497. if (regionList[i].id === v) {
  28498. settings.set(k, regionList[i].region);
  28499. break;
  28500. }
  28501. }
  28502. break;
  28503. case 'vertical':
  28504. settings.alt(k, v, ['rl', 'lr']);
  28505. break;
  28506. case 'line':
  28507. vals = v.split(',');
  28508. settings.integer(k, vals[0]);
  28509. if (settings.percent(k, vals[0])) {
  28510. settings.set('snapToLines', false);
  28511. }
  28512. settings.alt(k, vals[0], ['auto']);
  28513. if (vals.length === 2) {
  28514. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  28515. }
  28516. break;
  28517. case 'position':
  28518. vals = v.split(',');
  28519. settings.percent(k, vals[0]);
  28520. if (vals.length === 2) {
  28521. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  28522. }
  28523. break;
  28524. case 'size':
  28525. settings.percent(k, v);
  28526. break;
  28527. case 'align':
  28528. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  28529. break;
  28530. }
  28531. }, /:/, /\s/);
  28532. // Apply default values for any missing fields.
  28533. cue.region = settings.get('region', null);
  28534. cue.vertical = settings.get('vertical', '');
  28535. var line = settings.get('line', 'auto');
  28536. if (line === 'auto' && defaults.line === -1) {
  28537. // set numeric line number for Safari
  28538. line = -1;
  28539. }
  28540. cue.line = line;
  28541. cue.lineAlign = settings.get('lineAlign', 'start');
  28542. cue.snapToLines = settings.get('snapToLines', true);
  28543. cue.size = settings.get('size', 100);
  28544. cue.align = settings.get('align', center);
  28545. var position = settings.get('position', 'auto');
  28546. if (position === 'auto' && defaults.position === 50) {
  28547. // set numeric position for Safari
  28548. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  28549. }
  28550. cue.position = position;
  28551. }
  28552. function skipWhitespace() {
  28553. input = input.replace(/^\s+/, '');
  28554. }
  28555. // 4.1 WebVTT cue timings.
  28556. skipWhitespace();
  28557. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  28558. skipWhitespace();
  28559. if (input.slice(0, 3) !== '-->') {
  28560. // (3) next characters must match '-->'
  28561. throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  28562. }
  28563. input = input.slice(3);
  28564. skipWhitespace();
  28565. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  28566. // 4.1 WebVTT cue settings list.
  28567. skipWhitespace();
  28568. consumeCueSettings(input, cue);
  28569. }
  28570. function fixLineBreaks(input) {
  28571. return input.replace(/<br(?: \/)?>/gi, '\n');
  28572. }
  28573. var VTTParser = /*#__PURE__*/function () {
  28574. function VTTParser() {
  28575. this.state = 'INITIAL';
  28576. this.buffer = '';
  28577. this.decoder = new StringDecoder();
  28578. this.regionList = [];
  28579. this.cue = null;
  28580. this.oncue = void 0;
  28581. this.onparsingerror = void 0;
  28582. this.onflush = void 0;
  28583. }
  28584. var _proto3 = VTTParser.prototype;
  28585. _proto3.parse = function parse(data) {
  28586. var _this = this;
  28587. // If there is no data then we won't decode it, but will just try to parse
  28588. // whatever is in buffer already. This may occur in circumstances, for
  28589. // example when flush() is called.
  28590. if (data) {
  28591. // Try to decode the data that we received.
  28592. _this.buffer += _this.decoder.decode(data, {
  28593. stream: true
  28594. });
  28595. }
  28596. function collectNextLine() {
  28597. var buffer = _this.buffer;
  28598. var pos = 0;
  28599. buffer = fixLineBreaks(buffer);
  28600. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  28601. ++pos;
  28602. }
  28603. var line = buffer.slice(0, pos);
  28604. // Advance the buffer early in case we fail below.
  28605. if (buffer[pos] === '\r') {
  28606. ++pos;
  28607. }
  28608. if (buffer[pos] === '\n') {
  28609. ++pos;
  28610. }
  28611. _this.buffer = buffer.slice(pos);
  28612. return line;
  28613. }
  28614. // 3.2 WebVTT metadata header syntax
  28615. function parseHeader(input) {
  28616. parseOptions(input, function (k, v) {
  28617. // switch (k) {
  28618. // case 'region':
  28619. // 3.3 WebVTT region metadata header syntax
  28620. // console.log('parse region', v);
  28621. // parseRegion(v);
  28622. // break;
  28623. // }
  28624. }, /:/);
  28625. }
  28626. // 5.1 WebVTT file parsing.
  28627. try {
  28628. var line = '';
  28629. if (_this.state === 'INITIAL') {
  28630. // We can't start parsing until we have the first line.
  28631. if (!/\r\n|\n/.test(_this.buffer)) {
  28632. return this;
  28633. }
  28634. line = collectNextLine();
  28635. // strip of UTF-8 BOM if any
  28636. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  28637. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  28638. if (!(m != null && m[0])) {
  28639. throw new Error('Malformed WebVTT signature.');
  28640. }
  28641. _this.state = 'HEADER';
  28642. }
  28643. var alreadyCollectedLine = false;
  28644. while (_this.buffer) {
  28645. // We can't parse a line until we have the full line.
  28646. if (!/\r\n|\n/.test(_this.buffer)) {
  28647. return this;
  28648. }
  28649. if (!alreadyCollectedLine) {
  28650. line = collectNextLine();
  28651. } else {
  28652. alreadyCollectedLine = false;
  28653. }
  28654. switch (_this.state) {
  28655. case 'HEADER':
  28656. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  28657. if (/:/.test(line)) {
  28658. parseHeader(line);
  28659. } else if (!line) {
  28660. // An empty line terminates the header and starts the body (cues).
  28661. _this.state = 'ID';
  28662. }
  28663. continue;
  28664. case 'NOTE':
  28665. // Ignore NOTE blocks.
  28666. if (!line) {
  28667. _this.state = 'ID';
  28668. }
  28669. continue;
  28670. case 'ID':
  28671. // Check for the start of NOTE blocks.
  28672. if (/^NOTE($|[ \t])/.test(line)) {
  28673. _this.state = 'NOTE';
  28674. break;
  28675. }
  28676. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  28677. if (!line) {
  28678. continue;
  28679. }
  28680. _this.cue = new VTTCue(0, 0, '');
  28681. _this.state = 'CUE';
  28682. // 30-39 - Check if self line contains an optional identifier or timing data.
  28683. if (line.indexOf('-->') === -1) {
  28684. _this.cue.id = line;
  28685. continue;
  28686. }
  28687. // Process line as start of a cue.
  28688. /* falls through */
  28689. case 'CUE':
  28690. // 40 - Collect cue timings and settings.
  28691. if (!_this.cue) {
  28692. _this.state = 'BADCUE';
  28693. continue;
  28694. }
  28695. try {
  28696. parseCue(line, _this.cue, _this.regionList);
  28697. } catch (e) {
  28698. // In case of an error ignore rest of the cue.
  28699. _this.cue = null;
  28700. _this.state = 'BADCUE';
  28701. continue;
  28702. }
  28703. _this.state = 'CUETEXT';
  28704. continue;
  28705. case 'CUETEXT':
  28706. {
  28707. var hasSubstring = line.indexOf('-->') !== -1;
  28708. // 34 - If we have an empty line then report the cue.
  28709. // 35 - If we have the special substring '-->' then report the cue,
  28710. // but do not collect the line as we need to process the current
  28711. // one as a new cue.
  28712. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  28713. // We are done parsing self cue.
  28714. if (_this.oncue && _this.cue) {
  28715. _this.oncue(_this.cue);
  28716. }
  28717. _this.cue = null;
  28718. _this.state = 'ID';
  28719. continue;
  28720. }
  28721. if (_this.cue === null) {
  28722. continue;
  28723. }
  28724. if (_this.cue.text) {
  28725. _this.cue.text += '\n';
  28726. }
  28727. _this.cue.text += line;
  28728. }
  28729. continue;
  28730. case 'BADCUE':
  28731. // 54-62 - Collect and discard the remaining cue.
  28732. if (!line) {
  28733. _this.state = 'ID';
  28734. }
  28735. }
  28736. }
  28737. } catch (e) {
  28738. // If we are currently parsing a cue, report what we have.
  28739. if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
  28740. _this.oncue(_this.cue);
  28741. }
  28742. _this.cue = null;
  28743. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  28744. // another exception occurred so enter BADCUE state.
  28745. _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  28746. }
  28747. return this;
  28748. };
  28749. _proto3.flush = function flush() {
  28750. var _this = this;
  28751. try {
  28752. // Finish decoding the stream.
  28753. // _this.buffer += _this.decoder.decode();
  28754. // Synthesize the end of the current cue or region.
  28755. if (_this.cue || _this.state === 'HEADER') {
  28756. _this.buffer += '\n\n';
  28757. _this.parse();
  28758. }
  28759. // If we've flushed, parsed, and we're still on the INITIAL state then
  28760. // that means we don't have enough of the stream to parse the first
  28761. // line.
  28762. if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
  28763. throw new Error('Malformed WebVTT signature.');
  28764. }
  28765. } catch (e) {
  28766. if (_this.onparsingerror) {
  28767. _this.onparsingerror(e);
  28768. }
  28769. }
  28770. if (_this.onflush) {
  28771. _this.onflush();
  28772. }
  28773. return this;
  28774. };
  28775. return VTTParser;
  28776. }();
  28777. var LINEBREAKS = /\r\n|\n\r|\n|\r/g;
  28778. // String.prototype.startsWith is not supported in IE11
  28779. var startsWith = function startsWith(inputString, searchString, position) {
  28780. if (position === void 0) {
  28781. position = 0;
  28782. }
  28783. return inputString.slice(position, position + searchString.length) === searchString;
  28784. };
  28785. var cueString2millis = function cueString2millis(timeString) {
  28786. var ts = parseInt(timeString.slice(-3));
  28787. var secs = parseInt(timeString.slice(-6, -4));
  28788. var mins = parseInt(timeString.slice(-9, -7));
  28789. var hours = timeString.length > 9 ? parseInt(timeString.substring(0, timeString.indexOf(':'))) : 0;
  28790. if (!isFiniteNumber(ts) || !isFiniteNumber(secs) || !isFiniteNumber(mins) || !isFiniteNumber(hours)) {
  28791. throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
  28792. }
  28793. ts += 1000 * secs;
  28794. ts += 60 * 1000 * mins;
  28795. ts += 60 * 60 * 1000 * hours;
  28796. return ts;
  28797. };
  28798. // Create a unique hash id for a cue based on start/end times and text.
  28799. // This helps timeline-controller to avoid showing repeated captions.
  28800. function generateCueId(startTime, endTime, text) {
  28801. return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
  28802. }
  28803. var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
  28804. var currCC = vttCCs[cc];
  28805. var prevCC = vttCCs[currCC.prevCC];
  28806. // This is the first discontinuity or cues have been processed since the last discontinuity
  28807. // Offset = current discontinuity time
  28808. if (!prevCC || !prevCC.new && currCC.new) {
  28809. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  28810. currCC.new = false;
  28811. return;
  28812. }
  28813. // There have been discontinuities since cues were last parsed.
  28814. // Offset = time elapsed
  28815. while ((_prevCC = prevCC) != null && _prevCC.new) {
  28816. var _prevCC;
  28817. vttCCs.ccOffset += currCC.start - prevCC.start;
  28818. currCC.new = false;
  28819. currCC = prevCC;
  28820. prevCC = vttCCs[currCC.prevCC];
  28821. }
  28822. vttCCs.presentationOffset = presentationTime;
  28823. };
  28824. function parseWebVTT(vttByteArray, initPTS, vttCCs, cc, timeOffset, callBack, errorCallBack) {
  28825. var parser = new VTTParser();
  28826. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  28827. // Uint8Array.prototype.reduce is not implemented in IE11
  28828. var vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
  28829. var cues = [];
  28830. var init90kHz = initPTS ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale) : 0;
  28831. var cueTime = '00:00.000';
  28832. var timestampMapMPEGTS = 0;
  28833. var timestampMapLOCAL = 0;
  28834. var parsingError;
  28835. var inHeader = true;
  28836. parser.oncue = function (cue) {
  28837. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  28838. var currCC = vttCCs[cc];
  28839. var cueOffset = vttCCs.ccOffset;
  28840. // Calculate subtitle PTS offset
  28841. var webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;
  28842. // Update offsets for new discontinuities
  28843. if (currCC != null && currCC.new) {
  28844. if (timestampMapLOCAL !== undefined) {
  28845. // When local time is provided, offset = discontinuity start time - local time
  28846. cueOffset = vttCCs.ccOffset = currCC.start;
  28847. } else {
  28848. calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
  28849. }
  28850. }
  28851. if (webVttMpegTsMapOffset) {
  28852. if (!initPTS) {
  28853. parsingError = new Error('Missing initPTS for VTT MPEGTS');
  28854. return;
  28855. }
  28856. // If we have MPEGTS, offset = presentation time + discontinuity offset
  28857. cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
  28858. }
  28859. var duration = cue.endTime - cue.startTime;
  28860. var startTime = normalizePts((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
  28861. cue.startTime = Math.max(startTime, 0);
  28862. cue.endTime = Math.max(startTime + duration, 0);
  28863. //trim trailing webvtt block whitespaces
  28864. var text = cue.text.trim();
  28865. // Fix encoding of special characters
  28866. cue.text = decodeURIComponent(encodeURIComponent(text));
  28867. // If the cue was not assigned an id from the VTT file (line above the content), create one.
  28868. if (!cue.id) {
  28869. cue.id = generateCueId(cue.startTime, cue.endTime, text);
  28870. }
  28871. if (cue.endTime > 0) {
  28872. cues.push(cue);
  28873. }
  28874. };
  28875. parser.onparsingerror = function (error) {
  28876. parsingError = error;
  28877. };
  28878. parser.onflush = function () {
  28879. if (parsingError) {
  28880. errorCallBack(parsingError);
  28881. return;
  28882. }
  28883. callBack(cues);
  28884. };
  28885. // Go through contents line by line.
  28886. vttLines.forEach(function (line) {
  28887. if (inHeader) {
  28888. // Look for X-TIMESTAMP-MAP in header.
  28889. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  28890. // Once found, no more are allowed anyway, so stop searching.
  28891. inHeader = false;
  28892. // Extract LOCAL and MPEGTS.
  28893. line.slice(16).split(',').forEach(function (timestamp) {
  28894. if (startsWith(timestamp, 'LOCAL:')) {
  28895. cueTime = timestamp.slice(6);
  28896. } else if (startsWith(timestamp, 'MPEGTS:')) {
  28897. timestampMapMPEGTS = parseInt(timestamp.slice(7));
  28898. }
  28899. });
  28900. try {
  28901. // Convert cue time to seconds
  28902. timestampMapLOCAL = cueString2millis(cueTime) / 1000;
  28903. } catch (error) {
  28904. parsingError = error;
  28905. }
  28906. // Return without parsing X-TIMESTAMP-MAP line.
  28907. return;
  28908. } else if (line === '') {
  28909. inHeader = false;
  28910. }
  28911. }
  28912. // Parse line by default.
  28913. parser.parse(line + '\n');
  28914. });
  28915. parser.flush();
  28916. }
  28917. var IMSC1_CODEC = 'stpp.ttml.im1t';
  28918. // Time format: h:m:s:frames(.subframes)
  28919. var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/;
  28920. // Time format: hours, minutes, seconds, milliseconds, frames, ticks
  28921. var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
  28922. var textAlignToLineAlign = {
  28923. left: 'start',
  28924. center: 'center',
  28925. right: 'end',
  28926. start: 'start',
  28927. end: 'end'
  28928. };
  28929. function parseIMSC1(payload, initPTS, callBack, errorCallBack) {
  28930. var results = findBox(new Uint8Array(payload), ['mdat']);
  28931. if (results.length === 0) {
  28932. errorCallBack(new Error('Could not parse IMSC1 mdat'));
  28933. return;
  28934. }
  28935. var ttmlList = results.map(function (mdat) {
  28936. return utf8ArrayToStr(mdat);
  28937. });
  28938. var syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);
  28939. try {
  28940. ttmlList.forEach(function (ttml) {
  28941. return callBack(parseTTML(ttml, syncTime));
  28942. });
  28943. } catch (error) {
  28944. errorCallBack(error);
  28945. }
  28946. }
  28947. function parseTTML(ttml, syncTime) {
  28948. var parser = new DOMParser();
  28949. var xmlDoc = parser.parseFromString(ttml, 'text/xml');
  28950. var tt = xmlDoc.getElementsByTagName('tt')[0];
  28951. if (!tt) {
  28952. throw new Error('Invalid ttml');
  28953. }
  28954. var defaultRateInfo = {
  28955. frameRate: 30,
  28956. subFrameRate: 1,
  28957. frameRateMultiplier: 0,
  28958. tickRate: 0
  28959. };
  28960. var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {
  28961. result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key];
  28962. return result;
  28963. }, {});
  28964. var trim = tt.getAttribute('xml:space') !== 'preserve';
  28965. var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
  28966. var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
  28967. var cueElements = getElementCollection(tt, 'body', '[begin]');
  28968. return [].map.call(cueElements, function (cueElement) {
  28969. var cueText = getTextContent(cueElement, trim);
  28970. if (!cueText || !cueElement.hasAttribute('begin')) {
  28971. return null;
  28972. }
  28973. var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
  28974. var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
  28975. var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
  28976. if (startTime === null) {
  28977. throw timestampParsingError(cueElement);
  28978. }
  28979. if (endTime === null) {
  28980. if (duration === null) {
  28981. throw timestampParsingError(cueElement);
  28982. }
  28983. endTime = startTime + duration;
  28984. }
  28985. var cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);
  28986. cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);
  28987. var region = regionElements[cueElement.getAttribute('region')];
  28988. var style = styleElements[cueElement.getAttribute('style')];
  28989. // Apply styles to cue
  28990. var styles = getTtmlStyles(region, style, styleElements);
  28991. var textAlign = styles.textAlign;
  28992. if (textAlign) {
  28993. // cue.positionAlign not settable in FF~2016
  28994. var lineAlign = textAlignToLineAlign[textAlign];
  28995. if (lineAlign) {
  28996. cue.lineAlign = lineAlign;
  28997. }
  28998. cue.align = textAlign;
  28999. }
  29000. _extends(cue, styles);
  29001. return cue;
  29002. }).filter(function (cue) {
  29003. return cue !== null;
  29004. });
  29005. }
  29006. function getElementCollection(fromElement, parentName, childName) {
  29007. var parent = fromElement.getElementsByTagName(parentName)[0];
  29008. if (parent) {
  29009. return [].slice.call(parent.querySelectorAll(childName));
  29010. }
  29011. return [];
  29012. }
  29013. function collectionToDictionary(elementsWithId) {
  29014. return elementsWithId.reduce(function (dict, element) {
  29015. var id = element.getAttribute('xml:id');
  29016. if (id) {
  29017. dict[id] = element;
  29018. }
  29019. return dict;
  29020. }, {});
  29021. }
  29022. function getTextContent(element, trim) {
  29023. return [].slice.call(element.childNodes).reduce(function (str, node, i) {
  29024. var _node$childNodes;
  29025. if (node.nodeName === 'br' && i) {
  29026. return str + '\n';
  29027. }
  29028. if ((_node$childNodes = node.childNodes) != null && _node$childNodes.length) {
  29029. return getTextContent(node, trim);
  29030. } else if (trim) {
  29031. return str + node.textContent.trim().replace(/\s+/g, ' ');
  29032. }
  29033. return str + node.textContent;
  29034. }, '');
  29035. }
  29036. function getTtmlStyles(region, style, styleElements) {
  29037. var ttsNs = 'http://www.w3.org/ns/ttml#styling';
  29038. var regionStyle = null;
  29039. var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily'
  29040. // 'fontWeight',
  29041. // 'lineHeight',
  29042. // 'wrapOption',
  29043. // 'fontStyle',
  29044. // 'direction',
  29045. // 'writingMode'
  29046. ];
  29047. var regionStyleName = region != null && region.hasAttribute('style') ? region.getAttribute('style') : null;
  29048. if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {
  29049. regionStyle = styleElements[regionStyleName];
  29050. }
  29051. return styleAttributes.reduce(function (styles, name) {
  29052. var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name) || getAttributeNS(regionStyle, ttsNs, name);
  29053. if (value) {
  29054. styles[name] = value;
  29055. }
  29056. return styles;
  29057. }, {});
  29058. }
  29059. function getAttributeNS(element, ns, name) {
  29060. if (!element) {
  29061. return null;
  29062. }
  29063. return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
  29064. }
  29065. function timestampParsingError(node) {
  29066. return new Error("Could not parse ttml timestamp " + node);
  29067. }
  29068. function parseTtmlTime(timeAttributeValue, rateInfo) {
  29069. if (!timeAttributeValue) {
  29070. return null;
  29071. }
  29072. var seconds = parseTimeStamp(timeAttributeValue);
  29073. if (seconds === null) {
  29074. if (HMSF_REGEX.test(timeAttributeValue)) {
  29075. seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
  29076. } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
  29077. seconds = parseTimeUnits(timeAttributeValue, rateInfo);
  29078. }
  29079. }
  29080. return seconds;
  29081. }
  29082. function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
  29083. var m = HMSF_REGEX.exec(timeAttributeValue);
  29084. var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
  29085. return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
  29086. }
  29087. function parseTimeUnits(timeAttributeValue, rateInfo) {
  29088. var m = TIME_UNIT_REGEX.exec(timeAttributeValue);
  29089. var value = Number(m[1]);
  29090. var unit = m[2];
  29091. switch (unit) {
  29092. case 'h':
  29093. return value * 3600;
  29094. case 'm':
  29095. return value * 60;
  29096. case 'ms':
  29097. return value * 1000;
  29098. case 'f':
  29099. return value / rateInfo.frameRate;
  29100. case 't':
  29101. return value / rateInfo.tickRate;
  29102. }
  29103. return value;
  29104. }
  29105. var OutputFilter = /*#__PURE__*/function () {
  29106. function OutputFilter(timelineController, trackName) {
  29107. this.timelineController = void 0;
  29108. this.cueRanges = [];
  29109. this.trackName = void 0;
  29110. this.startTime = null;
  29111. this.endTime = null;
  29112. this.screen = null;
  29113. this.timelineController = timelineController;
  29114. this.trackName = trackName;
  29115. }
  29116. var _proto = OutputFilter.prototype;
  29117. _proto.dispatchCue = function dispatchCue() {
  29118. if (this.startTime === null) {
  29119. return;
  29120. }
  29121. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
  29122. this.startTime = null;
  29123. };
  29124. _proto.newCue = function newCue(startTime, endTime, screen) {
  29125. if (this.startTime === null || this.startTime > startTime) {
  29126. this.startTime = startTime;
  29127. }
  29128. this.endTime = endTime;
  29129. this.screen = screen;
  29130. this.timelineController.createCaptionsTrack(this.trackName);
  29131. };
  29132. _proto.reset = function reset() {
  29133. this.cueRanges = [];
  29134. this.startTime = null;
  29135. };
  29136. return OutputFilter;
  29137. }();
  29138. var TimelineController = /*#__PURE__*/function () {
  29139. function TimelineController(hls) {
  29140. this.hls = void 0;
  29141. this.media = null;
  29142. this.config = void 0;
  29143. this.enabled = true;
  29144. this.Cues = void 0;
  29145. this.textTracks = [];
  29146. this.tracks = [];
  29147. this.initPTS = [];
  29148. this.unparsedVttFrags = [];
  29149. this.captionsTracks = {};
  29150. this.nonNativeCaptionsTracks = {};
  29151. this.cea608Parser1 = void 0;
  29152. this.cea608Parser2 = void 0;
  29153. this.lastCc = -1;
  29154. // Last video (CEA-608) fragment CC
  29155. this.lastSn = -1;
  29156. // Last video (CEA-608) fragment MSN
  29157. this.lastPartIndex = -1;
  29158. // Last video (CEA-608) fragment Part Index
  29159. this.prevCC = -1;
  29160. // Last subtitle fragment CC
  29161. this.vttCCs = newVTTCCs();
  29162. this.captionsProperties = void 0;
  29163. this.hls = hls;
  29164. this.config = hls.config;
  29165. this.Cues = hls.config.cueHandler;
  29166. this.captionsProperties = {
  29167. textTrack1: {
  29168. label: this.config.captionsTextTrack1Label,
  29169. languageCode: this.config.captionsTextTrack1LanguageCode
  29170. },
  29171. textTrack2: {
  29172. label: this.config.captionsTextTrack2Label,
  29173. languageCode: this.config.captionsTextTrack2LanguageCode
  29174. },
  29175. textTrack3: {
  29176. label: this.config.captionsTextTrack3Label,
  29177. languageCode: this.config.captionsTextTrack3LanguageCode
  29178. },
  29179. textTrack4: {
  29180. label: this.config.captionsTextTrack4Label,
  29181. languageCode: this.config.captionsTextTrack4LanguageCode
  29182. }
  29183. };
  29184. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  29185. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29186. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29187. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  29188. hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  29189. hls.on(Events.FRAG_LOADING, this.onFragLoading, this);
  29190. hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);
  29191. hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  29192. hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  29193. hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  29194. hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  29195. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  29196. }
  29197. var _proto = TimelineController.prototype;
  29198. _proto.destroy = function destroy() {
  29199. var hls = this.hls;
  29200. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  29201. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  29202. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  29203. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  29204. hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
  29205. hls.off(Events.FRAG_LOADING, this.onFragLoading, this);
  29206. hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);
  29207. hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
  29208. hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);
  29209. hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);
  29210. hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
  29211. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  29212. // @ts-ignore
  29213. this.hls = this.config = this.media = null;
  29214. this.cea608Parser1 = this.cea608Parser2 = undefined;
  29215. };
  29216. _proto.initCea608Parsers = function initCea608Parsers() {
  29217. var channel1 = new OutputFilter(this, 'textTrack1');
  29218. var channel2 = new OutputFilter(this, 'textTrack2');
  29219. var channel3 = new OutputFilter(this, 'textTrack3');
  29220. var channel4 = new OutputFilter(this, 'textTrack4');
  29221. this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);
  29222. this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);
  29223. };
  29224. _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
  29225. // skip cues which overlap more than 50% with previously parsed time ranges
  29226. var merged = false;
  29227. for (var i = cueRanges.length; i--;) {
  29228. var cueRange = cueRanges[i];
  29229. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  29230. if (overlap >= 0) {
  29231. cueRange[0] = Math.min(cueRange[0], startTime);
  29232. cueRange[1] = Math.max(cueRange[1], endTime);
  29233. merged = true;
  29234. if (overlap / (endTime - startTime) > 0.5) {
  29235. return;
  29236. }
  29237. }
  29238. }
  29239. if (!merged) {
  29240. cueRanges.push([startTime, endTime]);
  29241. }
  29242. if (this.config.renderTextTracksNatively) {
  29243. var track = this.captionsTracks[trackName];
  29244. this.Cues.newCue(track, startTime, endTime, screen);
  29245. } else {
  29246. var cues = this.Cues.newCue(null, startTime, endTime, screen);
  29247. this.hls.trigger(Events.CUES_PARSED, {
  29248. type: 'captions',
  29249. cues: cues,
  29250. track: trackName
  29251. });
  29252. }
  29253. }
  29254. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  29255. ;
  29256. _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
  29257. var _this = this;
  29258. var frag = _ref.frag,
  29259. id = _ref.id,
  29260. initPTS = _ref.initPTS,
  29261. timescale = _ref.timescale;
  29262. var unparsedVttFrags = this.unparsedVttFrags;
  29263. if (id === PlaylistLevelType.MAIN) {
  29264. this.initPTS[frag.cc] = {
  29265. baseTime: initPTS,
  29266. timescale: timescale
  29267. };
  29268. }
  29269. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  29270. // Parse any unparsed fragments upon receiving the initial PTS.
  29271. if (unparsedVttFrags.length) {
  29272. this.unparsedVttFrags = [];
  29273. unparsedVttFrags.forEach(function (data) {
  29274. if (_this.initPTS[data.frag.cc]) {
  29275. _this.onFragLoaded(Events.FRAG_LOADED, data);
  29276. } else {
  29277. _this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29278. success: false,
  29279. frag: data.frag,
  29280. error: new Error('Subtitle discontinuity domain does not match main')
  29281. });
  29282. }
  29283. });
  29284. }
  29285. };
  29286. _proto.getExistingTrack = function getExistingTrack(label, language) {
  29287. var media = this.media;
  29288. if (media) {
  29289. for (var i = 0; i < media.textTracks.length; i++) {
  29290. var textTrack = media.textTracks[i];
  29291. if (canReuseVttTextTrack(textTrack, {
  29292. name: label,
  29293. lang: language,
  29294. characteristics: 'transcribes-spoken-dialog,describes-music-and-sound'})) {
  29295. return textTrack;
  29296. }
  29297. }
  29298. }
  29299. return null;
  29300. };
  29301. _proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
  29302. if (this.config.renderTextTracksNatively) {
  29303. this.createNativeTrack(trackName);
  29304. } else {
  29305. this.createNonNativeTrack(trackName);
  29306. }
  29307. };
  29308. _proto.createNativeTrack = function createNativeTrack(trackName) {
  29309. if (this.captionsTracks[trackName]) {
  29310. return;
  29311. }
  29312. var captionsProperties = this.captionsProperties,
  29313. captionsTracks = this.captionsTracks,
  29314. media = this.media;
  29315. var _captionsProperties$t = captionsProperties[trackName],
  29316. label = _captionsProperties$t.label,
  29317. languageCode = _captionsProperties$t.languageCode;
  29318. // Enable reuse of existing text track.
  29319. var existingTrack = this.getExistingTrack(label, languageCode);
  29320. if (!existingTrack) {
  29321. var textTrack = this.createTextTrack('captions', label, languageCode);
  29322. if (textTrack) {
  29323. // Set a special property on the track so we know it's managed by Hls.js
  29324. textTrack[trackName] = true;
  29325. captionsTracks[trackName] = textTrack;
  29326. }
  29327. } else {
  29328. captionsTracks[trackName] = existingTrack;
  29329. clearCurrentCues(captionsTracks[trackName]);
  29330. sendAddTrackEvent(captionsTracks[trackName], media);
  29331. }
  29332. };
  29333. _proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
  29334. if (this.nonNativeCaptionsTracks[trackName]) {
  29335. return;
  29336. }
  29337. // Create a list of a single track for the provider to consume
  29338. var trackProperties = this.captionsProperties[trackName];
  29339. if (!trackProperties) {
  29340. return;
  29341. }
  29342. var label = trackProperties.label;
  29343. var track = {
  29344. _id: trackName,
  29345. label: label,
  29346. kind: 'captions',
  29347. default: trackProperties.media ? !!trackProperties.media.default : false,
  29348. closedCaptions: trackProperties.media
  29349. };
  29350. this.nonNativeCaptionsTracks[trackName] = track;
  29351. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  29352. tracks: [track]
  29353. });
  29354. };
  29355. _proto.createTextTrack = function createTextTrack(kind, label, lang) {
  29356. var media = this.media;
  29357. if (!media) {
  29358. return;
  29359. }
  29360. return media.addTextTrack(kind, label, lang);
  29361. };
  29362. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  29363. this.media = data.media;
  29364. if (!data.mediaSource) {
  29365. this._cleanTracks();
  29366. }
  29367. };
  29368. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  29369. var transferringMedia = !!data.transferMedia;
  29370. this.media = null;
  29371. if (transferringMedia) {
  29372. return;
  29373. }
  29374. var captionsTracks = this.captionsTracks;
  29375. Object.keys(captionsTracks).forEach(function (trackName) {
  29376. clearCurrentCues(captionsTracks[trackName]);
  29377. delete captionsTracks[trackName];
  29378. });
  29379. this.nonNativeCaptionsTracks = {};
  29380. };
  29381. _proto.onManifestLoading = function onManifestLoading() {
  29382. // Detect discontinuity in video fragment (CEA-608) parsing
  29383. this.lastCc = -1;
  29384. this.lastSn = -1;
  29385. this.lastPartIndex = -1;
  29386. // Detect discontinuity in subtitle manifests
  29387. this.prevCC = -1;
  29388. this.vttCCs = newVTTCCs();
  29389. // Reset tracks
  29390. this._cleanTracks();
  29391. this.tracks = [];
  29392. this.captionsTracks = {};
  29393. this.nonNativeCaptionsTracks = {};
  29394. this.textTracks = [];
  29395. this.unparsedVttFrags = [];
  29396. this.initPTS = [];
  29397. if (this.cea608Parser1 && this.cea608Parser2) {
  29398. this.cea608Parser1.reset();
  29399. this.cea608Parser2.reset();
  29400. }
  29401. };
  29402. _proto._cleanTracks = function _cleanTracks() {
  29403. // clear outdated subtitles
  29404. var media = this.media;
  29405. if (!media) {
  29406. return;
  29407. }
  29408. var textTracks = media.textTracks;
  29409. if (textTracks) {
  29410. for (var i = 0; i < textTracks.length; i++) {
  29411. clearCurrentCues(textTracks[i]);
  29412. }
  29413. }
  29414. };
  29415. _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {
  29416. var _this2 = this;
  29417. var tracks = data.subtitleTracks || [];
  29418. var hasIMSC1 = tracks.some(function (track) {
  29419. return track.textCodec === IMSC1_CODEC;
  29420. });
  29421. if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
  29422. var listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);
  29423. if (listIsIdentical) {
  29424. this.tracks = tracks;
  29425. return;
  29426. }
  29427. this.textTracks = [];
  29428. this.tracks = tracks;
  29429. if (this.config.renderTextTracksNatively) {
  29430. var media = this.media;
  29431. var inUseTracks = media ? filterSubtitleTracks(media.textTracks) : null;
  29432. this.tracks.forEach(function (track, index) {
  29433. // Reuse tracks with the same label and lang, but do not reuse 608/708 tracks
  29434. var textTrack;
  29435. if (inUseTracks) {
  29436. var inUseTrack = null;
  29437. for (var i = 0; i < inUseTracks.length; i++) {
  29438. if (inUseTracks[i] && canReuseVttTextTrack(inUseTracks[i], track)) {
  29439. inUseTrack = inUseTracks[i];
  29440. inUseTracks[i] = null;
  29441. break;
  29442. }
  29443. }
  29444. if (inUseTrack) {
  29445. textTrack = inUseTrack;
  29446. }
  29447. }
  29448. if (textTrack) {
  29449. clearCurrentCues(textTrack);
  29450. } else {
  29451. var textTrackKind = captionsOrSubtitlesFromCharacteristics(track);
  29452. textTrack = _this2.createTextTrack(textTrackKind, track.name, track.lang);
  29453. if (textTrack) {
  29454. textTrack.mode = 'disabled';
  29455. }
  29456. }
  29457. if (textTrack) {
  29458. _this2.textTracks.push(textTrack);
  29459. }
  29460. });
  29461. // Warn when video element has captions or subtitle TextTracks carried over from another source
  29462. if (inUseTracks != null && inUseTracks.length) {
  29463. var unusedTextTracks = inUseTracks.filter(function (t) {
  29464. return t !== null;
  29465. }).map(function (t) {
  29466. return t.label;
  29467. });
  29468. if (unusedTextTracks.length) {
  29469. this.hls.logger.warn("Media element contains unused subtitle tracks: " + unusedTextTracks.join(', ') + ". Replace media element for each source to clear TextTracks and captions menu.");
  29470. }
  29471. }
  29472. } else if (this.tracks.length) {
  29473. // Create a list of tracks for the provider to consume
  29474. var tracksList = this.tracks.map(function (track) {
  29475. return {
  29476. label: track.name,
  29477. kind: track.type.toLowerCase(),
  29478. default: track.default,
  29479. subtitleTrack: track
  29480. };
  29481. });
  29482. this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {
  29483. tracks: tracksList
  29484. });
  29485. }
  29486. }
  29487. };
  29488. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  29489. var _this3 = this;
  29490. if (this.config.enableCEA708Captions && data.captions) {
  29491. data.captions.forEach(function (captionsTrack) {
  29492. var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
  29493. if (!instreamIdMatch) {
  29494. return;
  29495. }
  29496. var trackName = "textTrack" + instreamIdMatch[1];
  29497. var trackProperties = _this3.captionsProperties[trackName];
  29498. if (!trackProperties) {
  29499. return;
  29500. }
  29501. trackProperties.label = captionsTrack.name;
  29502. if (captionsTrack.lang) {
  29503. // optional attribute
  29504. trackProperties.languageCode = captionsTrack.lang;
  29505. }
  29506. trackProperties.media = captionsTrack;
  29507. });
  29508. }
  29509. };
  29510. _proto.closedCaptionsForLevel = function closedCaptionsForLevel(frag) {
  29511. var level = this.hls.levels[frag.level];
  29512. return level == null ? void 0 : level.attrs['CLOSED-CAPTIONS'];
  29513. };
  29514. _proto.onFragLoading = function onFragLoading(event, data) {
  29515. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  29516. if (this.enabled && data.frag.type === PlaylistLevelType.MAIN) {
  29517. var _data$part$index, _data$part;
  29518. var cea608Parser1 = this.cea608Parser1,
  29519. cea608Parser2 = this.cea608Parser2,
  29520. lastSn = this.lastSn;
  29521. var _data$frag = data.frag,
  29522. cc = _data$frag.cc,
  29523. sn = _data$frag.sn;
  29524. var partIndex = (_data$part$index = (_data$part = data.part) == null ? void 0 : _data$part.index) != null ? _data$part$index : -1;
  29525. if (cea608Parser1 && cea608Parser2) {
  29526. if (sn !== lastSn + 1 || sn === lastSn && partIndex !== this.lastPartIndex + 1 || cc !== this.lastCc) {
  29527. cea608Parser1.reset();
  29528. cea608Parser2.reset();
  29529. }
  29530. }
  29531. this.lastCc = cc;
  29532. this.lastSn = sn;
  29533. this.lastPartIndex = partIndex;
  29534. }
  29535. };
  29536. _proto.onFragLoaded = function onFragLoaded(event, data) {
  29537. var frag = data.frag,
  29538. payload = data.payload;
  29539. if (frag.type === PlaylistLevelType.SUBTITLE) {
  29540. // If fragment is subtitle type, parse as WebVTT.
  29541. if (payload.byteLength) {
  29542. var decryptData = frag.decryptdata;
  29543. // fragment after decryption has a stats object
  29544. var decrypted = 'stats' in data;
  29545. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  29546. if (decryptData == null || !decryptData.encrypted || decrypted) {
  29547. var trackPlaylistMedia = this.tracks[frag.level];
  29548. var vttCCs = this.vttCCs;
  29549. if (!vttCCs[frag.cc]) {
  29550. vttCCs[frag.cc] = {
  29551. start: frag.start,
  29552. prevCC: this.prevCC,
  29553. new: true
  29554. };
  29555. this.prevCC = frag.cc;
  29556. }
  29557. if (trackPlaylistMedia && trackPlaylistMedia.textCodec === IMSC1_CODEC) {
  29558. this._parseIMSC1(frag, payload);
  29559. } else {
  29560. this._parseVTTs(data);
  29561. }
  29562. }
  29563. } else {
  29564. // In case there is no payload, finish unsuccessfully.
  29565. this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29566. success: false,
  29567. frag: frag,
  29568. error: new Error('Empty subtitle payload')
  29569. });
  29570. }
  29571. }
  29572. };
  29573. _proto._parseIMSC1 = function _parseIMSC1(frag, payload) {
  29574. var _this4 = this;
  29575. var hls = this.hls;
  29576. parseIMSC1(payload, this.initPTS[frag.cc], function (cues) {
  29577. _this4._appendCues(cues, frag.level);
  29578. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29579. success: true,
  29580. frag: frag
  29581. });
  29582. }, function (error) {
  29583. hls.logger.log("Failed to parse IMSC1: " + error);
  29584. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29585. success: false,
  29586. frag: frag,
  29587. error: error
  29588. });
  29589. });
  29590. };
  29591. _proto._parseVTTs = function _parseVTTs(data) {
  29592. var _frag$initSegment,
  29593. _this5 = this;
  29594. var frag = data.frag,
  29595. payload = data.payload;
  29596. // We need an initial synchronisation PTS. Store fragments as long as none has arrived
  29597. var initPTS = this.initPTS,
  29598. unparsedVttFrags = this.unparsedVttFrags;
  29599. var maxAvCC = initPTS.length - 1;
  29600. if (!initPTS[frag.cc] && maxAvCC === -1) {
  29601. unparsedVttFrags.push(data);
  29602. return;
  29603. }
  29604. var hls = this.hls;
  29605. // Parse the WebVTT file contents.
  29606. var payloadWebVTT = (_frag$initSegment = frag.initSegment) != null && _frag$initSegment.data ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload)).buffer : payload;
  29607. parseWebVTT(payloadWebVTT, this.initPTS[frag.cc], this.vttCCs, frag.cc, frag.start, function (cues) {
  29608. _this5._appendCues(cues, frag.level);
  29609. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29610. success: true,
  29611. frag: frag
  29612. });
  29613. }, function (error) {
  29614. var missingInitPTS = error.message === 'Missing initPTS for VTT MPEGTS';
  29615. if (missingInitPTS) {
  29616. unparsedVttFrags.push(data);
  29617. } else {
  29618. _this5._fallbackToIMSC1(frag, payload);
  29619. }
  29620. // Something went wrong while parsing. Trigger event with success false.
  29621. hls.logger.log("Failed to parse VTT cue: " + error);
  29622. if (missingInitPTS && maxAvCC > frag.cc) {
  29623. return;
  29624. }
  29625. hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {
  29626. success: false,
  29627. frag: frag,
  29628. error: error
  29629. });
  29630. });
  29631. };
  29632. _proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {
  29633. var _this6 = this;
  29634. // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
  29635. var trackPlaylistMedia = this.tracks[frag.level];
  29636. if (!trackPlaylistMedia.textCodec) {
  29637. parseIMSC1(payload, this.initPTS[frag.cc], function () {
  29638. trackPlaylistMedia.textCodec = IMSC1_CODEC;
  29639. _this6._parseIMSC1(frag, payload);
  29640. }, function () {
  29641. trackPlaylistMedia.textCodec = 'wvtt';
  29642. });
  29643. }
  29644. };
  29645. _proto._appendCues = function _appendCues(cues, fragLevel) {
  29646. var hls = this.hls;
  29647. if (this.config.renderTextTracksNatively) {
  29648. var textTrack = this.textTracks[fragLevel];
  29649. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  29650. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  29651. // and trying to access getCueById method of cues will throw an exception
  29652. // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
  29653. if (!textTrack || textTrack.mode === 'disabled') {
  29654. return;
  29655. }
  29656. cues.forEach(function (cue) {
  29657. return addCueToTrack(textTrack, cue);
  29658. });
  29659. } else {
  29660. var currentTrack = this.tracks[fragLevel];
  29661. if (!currentTrack) {
  29662. return;
  29663. }
  29664. var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
  29665. hls.trigger(Events.CUES_PARSED, {
  29666. type: 'subtitles',
  29667. cues: cues,
  29668. track: track
  29669. });
  29670. }
  29671. };
  29672. _proto.onFragDecrypted = function onFragDecrypted(event, data) {
  29673. var frag = data.frag;
  29674. if (frag.type === PlaylistLevelType.SUBTITLE) {
  29675. this.onFragLoaded(Events.FRAG_LOADED, data);
  29676. }
  29677. };
  29678. _proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {
  29679. this.tracks = [];
  29680. this.captionsTracks = {};
  29681. };
  29682. _proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {
  29683. if (!this.enabled || !this.config.enableCEA708Captions) {
  29684. return;
  29685. }
  29686. var frag = data.frag,
  29687. samples = data.samples;
  29688. if (frag.type === PlaylistLevelType.MAIN && this.closedCaptionsForLevel(frag) === 'NONE') {
  29689. return;
  29690. }
  29691. // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
  29692. // It will create the proper timestamps based on the PTS value
  29693. for (var i = 0; i < samples.length; i++) {
  29694. var ccBytes = samples[i].bytes;
  29695. if (ccBytes) {
  29696. if (!this.cea608Parser1) {
  29697. this.initCea608Parsers();
  29698. }
  29699. var ccdatas = this.extractCea608Data(ccBytes);
  29700. this.cea608Parser1.addData(samples[i].pts, ccdatas[0]);
  29701. this.cea608Parser2.addData(samples[i].pts, ccdatas[1]);
  29702. }
  29703. }
  29704. };
  29705. _proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {
  29706. var startOffset = _ref2.startOffset,
  29707. endOffset = _ref2.endOffset,
  29708. endOffsetSubtitles = _ref2.endOffsetSubtitles,
  29709. type = _ref2.type;
  29710. var media = this.media;
  29711. if (!media || media.currentTime < endOffset) {
  29712. return;
  29713. }
  29714. // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
  29715. // Forward cues are never removed because we can loose streamed 608 content from recent fragments
  29716. if (!type || type === 'video') {
  29717. var captionsTracks = this.captionsTracks;
  29718. Object.keys(captionsTracks).forEach(function (trackName) {
  29719. return removeCuesInRange(captionsTracks[trackName], startOffset, endOffset);
  29720. });
  29721. }
  29722. if (this.config.renderTextTracksNatively) {
  29723. // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
  29724. if (startOffset === 0 && endOffsetSubtitles !== undefined) {
  29725. var textTracks = this.textTracks;
  29726. Object.keys(textTracks).forEach(function (trackName) {
  29727. return removeCuesInRange(textTracks[trackName], startOffset, endOffsetSubtitles);
  29728. });
  29729. }
  29730. }
  29731. };
  29732. _proto.extractCea608Data = function extractCea608Data(byteArray) {
  29733. var actualCCBytes = [[], []];
  29734. var count = byteArray[0] & 0x1f;
  29735. var position = 2;
  29736. for (var j = 0; j < count; j++) {
  29737. var tmpByte = byteArray[position++];
  29738. var ccbyte1 = 0x7f & byteArray[position++];
  29739. var ccbyte2 = 0x7f & byteArray[position++];
  29740. if (ccbyte1 === 0 && ccbyte2 === 0) {
  29741. continue;
  29742. }
  29743. var ccValid = (0x04 & tmpByte) !== 0; // Support all four channels
  29744. if (ccValid) {
  29745. var ccType = 0x03 & tmpByte;
  29746. if (0x00 /* CEA608 field1*/ === ccType || 0x01 /* CEA608 field2*/ === ccType) {
  29747. // Exclude CEA708 CC data.
  29748. actualCCBytes[ccType].push(ccbyte1);
  29749. actualCCBytes[ccType].push(ccbyte2);
  29750. }
  29751. }
  29752. }
  29753. return actualCCBytes;
  29754. };
  29755. return TimelineController;
  29756. }();
  29757. function captionsOrSubtitlesFromCharacteristics(track) {
  29758. if (track.characteristics) {
  29759. if (/transcribes-spoken-dialog/gi.test(track.characteristics) && /describes-music-and-sound/gi.test(track.characteristics)) {
  29760. return 'captions';
  29761. }
  29762. }
  29763. return 'subtitles';
  29764. }
  29765. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  29766. return !!inUseTrack && inUseTrack.kind === captionsOrSubtitlesFromCharacteristics(manifestTrack) && subtitleTrackMatchesTextTrack(manifestTrack, inUseTrack);
  29767. }
  29768. function intersection(x1, x2, y1, y2) {
  29769. return Math.min(x2, y2) - Math.max(x1, y1);
  29770. }
  29771. function newVTTCCs() {
  29772. return {
  29773. ccOffset: 0,
  29774. presentationOffset: 0,
  29775. 0: {
  29776. start: 0,
  29777. prevCC: -1,
  29778. new: true
  29779. }
  29780. };
  29781. }
  29782. var WHITESPACE_CHAR = /\s/;
  29783. var Cues = {
  29784. newCue: function newCue(track, startTime, endTime, captionScreen) {
  29785. var result = [];
  29786. var row;
  29787. // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
  29788. var cue;
  29789. var indenting;
  29790. var indent;
  29791. var text;
  29792. var Cue = self.VTTCue || self.TextTrackCue;
  29793. for (var r = 0; r < captionScreen.rows.length; r++) {
  29794. row = captionScreen.rows[r];
  29795. indenting = true;
  29796. indent = 0;
  29797. text = '';
  29798. if (!row.isEmpty()) {
  29799. var _track$cues;
  29800. for (var c = 0; c < row.chars.length; c++) {
  29801. if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
  29802. indent++;
  29803. } else {
  29804. text += row.chars[c].uchar;
  29805. indenting = false;
  29806. }
  29807. }
  29808. // To be used for cleaning-up orphaned roll-up captions
  29809. row.cueStartTime = startTime;
  29810. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  29811. if (startTime === endTime) {
  29812. endTime += 0.0001;
  29813. }
  29814. if (indent >= 16) {
  29815. indent--;
  29816. } else {
  29817. indent++;
  29818. }
  29819. var cueText = fixLineBreaks(text.trim());
  29820. var id = generateCueId(startTime, endTime, cueText);
  29821. // If this cue already exists in the track do not push it
  29822. if (!(track != null && (_track$cues = track.cues) != null && _track$cues.getCueById(id))) {
  29823. cue = new Cue(startTime, endTime, cueText);
  29824. cue.id = id;
  29825. cue.line = r + 1;
  29826. cue.align = 'left';
  29827. // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
  29828. // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
  29829. // Firefox throws an exception and captions break with out of bounds 0-100 values
  29830. cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
  29831. result.push(cue);
  29832. }
  29833. }
  29834. }
  29835. if (track && result.length) {
  29836. // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
  29837. result.sort(function (cueA, cueB) {
  29838. if (cueA.line === 'auto' || cueB.line === 'auto') {
  29839. return 0;
  29840. }
  29841. if (cueA.line > 8 && cueB.line > 8) {
  29842. return cueB.line - cueA.line;
  29843. }
  29844. return cueA.line - cueB.line;
  29845. });
  29846. result.forEach(function (cue) {
  29847. return addCueToTrack(track, cue);
  29848. });
  29849. }
  29850. return result;
  29851. }
  29852. };
  29853. function fetchSupported() {
  29854. if (
  29855. // @ts-ignore
  29856. self.fetch && self.AbortController && self.ReadableStream && self.Request) {
  29857. try {
  29858. new self.ReadableStream({}); // eslint-disable-line no-new
  29859. return true;
  29860. } catch (e) {
  29861. /* noop */
  29862. }
  29863. }
  29864. return false;
  29865. }
  29866. var BYTERANGE = /(\d+)-(\d+)\/(\d+)/;
  29867. var FetchLoader = /*#__PURE__*/function () {
  29868. function FetchLoader(config) {
  29869. this.fetchSetup = void 0;
  29870. this.requestTimeout = void 0;
  29871. this.request = null;
  29872. this.response = null;
  29873. this.controller = void 0;
  29874. this.context = null;
  29875. this.config = null;
  29876. this.callbacks = null;
  29877. this.stats = void 0;
  29878. this.loader = null;
  29879. this.fetchSetup = config.fetchSetup || getRequest;
  29880. this.controller = new self.AbortController();
  29881. this.stats = new LoadStats();
  29882. }
  29883. var _proto = FetchLoader.prototype;
  29884. _proto.destroy = function destroy() {
  29885. this.loader = this.callbacks = this.context = this.config = this.request = null;
  29886. this.abortInternal();
  29887. this.response = null;
  29888. // @ts-ignore
  29889. this.fetchSetup = this.controller = this.stats = null;
  29890. };
  29891. _proto.abortInternal = function abortInternal() {
  29892. if (this.controller && !this.stats.loading.end) {
  29893. this.stats.aborted = true;
  29894. this.controller.abort();
  29895. }
  29896. };
  29897. _proto.abort = function abort() {
  29898. var _this$callbacks;
  29899. this.abortInternal();
  29900. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  29901. this.callbacks.onAbort(this.stats, this.context, this.response);
  29902. }
  29903. };
  29904. _proto.load = function load(context, config, callbacks) {
  29905. var _this = this;
  29906. var stats = this.stats;
  29907. if (stats.loading.start) {
  29908. throw new Error('Loader can only be used once.');
  29909. }
  29910. stats.loading.start = self.performance.now();
  29911. var initParams = getRequestParameters(context, this.controller.signal);
  29912. var isArrayBuffer = context.responseType === 'arraybuffer';
  29913. var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
  29914. var _config$loadPolicy = config.loadPolicy,
  29915. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  29916. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  29917. this.context = context;
  29918. this.config = config;
  29919. this.callbacks = callbacks;
  29920. this.request = this.fetchSetup(context, initParams);
  29921. self.clearTimeout(this.requestTimeout);
  29922. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  29923. this.requestTimeout = self.setTimeout(function () {
  29924. if (_this.callbacks) {
  29925. _this.abortInternal();
  29926. _this.callbacks.onTimeout(stats, context, _this.response);
  29927. }
  29928. }, config.timeout);
  29929. var fetchPromise = isPromise(this.request) ? this.request.then(self.fetch) : self.fetch(this.request);
  29930. fetchPromise.then(function (response) {
  29931. var _this$callbacks2;
  29932. _this.response = _this.loader = response;
  29933. var first = Math.max(self.performance.now(), stats.loading.start);
  29934. self.clearTimeout(_this.requestTimeout);
  29935. config.timeout = maxLoadTimeMs;
  29936. _this.requestTimeout = self.setTimeout(function () {
  29937. if (_this.callbacks) {
  29938. _this.abortInternal();
  29939. _this.callbacks.onTimeout(stats, context, _this.response);
  29940. }
  29941. }, maxLoadTimeMs - (first - stats.loading.start));
  29942. if (!response.ok) {
  29943. var status = response.status,
  29944. statusText = response.statusText;
  29945. throw new FetchError(statusText || 'fetch, bad network response', status, response);
  29946. }
  29947. stats.loading.first = first;
  29948. stats.total = getContentLength(response.headers) || stats.total;
  29949. var onProgress = (_this$callbacks2 = _this.callbacks) == null ? void 0 : _this$callbacks2.onProgress;
  29950. if (onProgress && isFiniteNumber(config.highWaterMark)) {
  29951. return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
  29952. }
  29953. if (isArrayBuffer) {
  29954. return response.arrayBuffer();
  29955. }
  29956. if (context.responseType === 'json') {
  29957. return response.json();
  29958. }
  29959. return response.text();
  29960. }).then(function (responseData) {
  29961. var _this$callbacks3, _this$callbacks4;
  29962. var response = _this.response;
  29963. if (!response) {
  29964. throw new Error('loader destroyed');
  29965. }
  29966. self.clearTimeout(_this.requestTimeout);
  29967. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  29968. var total = responseData[LENGTH];
  29969. if (total) {
  29970. stats.loaded = stats.total = total;
  29971. }
  29972. var loaderResponse = {
  29973. url: response.url,
  29974. data: responseData,
  29975. code: response.status
  29976. };
  29977. var onProgress = (_this$callbacks3 = _this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  29978. if (onProgress && !isFiniteNumber(config.highWaterMark)) {
  29979. onProgress(stats, context, responseData, response);
  29980. }
  29981. (_this$callbacks4 = _this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(loaderResponse, stats, context, response);
  29982. }).catch(function (error) {
  29983. var _this$callbacks5;
  29984. self.clearTimeout(_this.requestTimeout);
  29985. if (stats.aborted) {
  29986. return;
  29987. }
  29988. // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
  29989. // when destroying, 'error' itself can be undefined
  29990. var code = !error ? 0 : error.code || 0;
  29991. var text = !error ? null : error.message;
  29992. (_this$callbacks5 = _this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  29993. code: code,
  29994. text: text
  29995. }, context, error ? error.details : null, stats);
  29996. });
  29997. };
  29998. _proto.getCacheAge = function getCacheAge() {
  29999. var result = null;
  30000. if (this.response) {
  30001. var ageHeader = this.response.headers.get('age');
  30002. result = ageHeader ? parseFloat(ageHeader) : null;
  30003. }
  30004. return result;
  30005. };
  30006. _proto.getResponseHeader = function getResponseHeader(name) {
  30007. return this.response ? this.response.headers.get(name) : null;
  30008. };
  30009. _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
  30010. if (highWaterMark === void 0) {
  30011. highWaterMark = 0;
  30012. }
  30013. var chunkCache = new ChunkCache();
  30014. var reader = response.body.getReader();
  30015. var _pump = function pump() {
  30016. return reader.read().then(function (data) {
  30017. if (data.done) {
  30018. if (chunkCache.dataLength) {
  30019. onProgress(stats, context, chunkCache.flush().buffer, response);
  30020. }
  30021. return Promise.resolve(new ArrayBuffer(0));
  30022. }
  30023. var chunk = data.value;
  30024. var len = chunk.length;
  30025. stats.loaded += len;
  30026. if (len < highWaterMark || chunkCache.dataLength) {
  30027. // The current chunk is too small to to be emitted or the cache already has data
  30028. // Push it to the cache
  30029. chunkCache.push(chunk);
  30030. if (chunkCache.dataLength >= highWaterMark) {
  30031. // flush in order to join the typed arrays
  30032. onProgress(stats, context, chunkCache.flush().buffer, response);
  30033. }
  30034. } else {
  30035. // If there's nothing cached already, and the chache is large enough
  30036. // just emit the progress event
  30037. onProgress(stats, context, chunk.buffer, response);
  30038. }
  30039. return _pump();
  30040. }).catch(function () {
  30041. /* aborted */
  30042. return Promise.reject();
  30043. });
  30044. };
  30045. return _pump();
  30046. };
  30047. return FetchLoader;
  30048. }();
  30049. function getRequestParameters(context, signal) {
  30050. var initParams = {
  30051. method: 'GET',
  30052. mode: 'cors',
  30053. credentials: 'same-origin',
  30054. signal: signal,
  30055. headers: new self.Headers(_extends({}, context.headers))
  30056. };
  30057. if (context.rangeEnd) {
  30058. initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
  30059. }
  30060. return initParams;
  30061. }
  30062. function getByteRangeLength(byteRangeHeader) {
  30063. var result = BYTERANGE.exec(byteRangeHeader);
  30064. if (result) {
  30065. return parseInt(result[2]) - parseInt(result[1]) + 1;
  30066. }
  30067. }
  30068. function getContentLength(headers) {
  30069. var contentRange = headers.get('Content-Range');
  30070. if (contentRange) {
  30071. var byteRangeLength = getByteRangeLength(contentRange);
  30072. if (isFiniteNumber(byteRangeLength)) {
  30073. return byteRangeLength;
  30074. }
  30075. }
  30076. var contentLength = headers.get('Content-Length');
  30077. if (contentLength) {
  30078. return parseInt(contentLength);
  30079. }
  30080. }
  30081. function getRequest(context, initParams) {
  30082. return new self.Request(context.url, initParams);
  30083. }
  30084. var FetchError = /*#__PURE__*/function (_Error) {
  30085. function FetchError(message, code, details) {
  30086. var _this2;
  30087. _this2 = _Error.call(this, message) || this;
  30088. _this2.code = void 0;
  30089. _this2.details = void 0;
  30090. _this2.code = code;
  30091. _this2.details = details;
  30092. return _this2;
  30093. }
  30094. _inheritsLoose(FetchError, _Error);
  30095. return FetchError;
  30096. }(/*#__PURE__*/_wrapNativeSuper(Error));
  30097. var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/im;
  30098. var XhrLoader = /*#__PURE__*/function () {
  30099. function XhrLoader(config) {
  30100. this.xhrSetup = void 0;
  30101. this.requestTimeout = void 0;
  30102. this.retryTimeout = void 0;
  30103. this.retryDelay = void 0;
  30104. this.config = null;
  30105. this.callbacks = null;
  30106. this.context = null;
  30107. this.loader = null;
  30108. this.stats = void 0;
  30109. this.xhrSetup = config ? config.xhrSetup || null : null;
  30110. this.stats = new LoadStats();
  30111. this.retryDelay = 0;
  30112. }
  30113. var _proto = XhrLoader.prototype;
  30114. _proto.destroy = function destroy() {
  30115. this.callbacks = null;
  30116. this.abortInternal();
  30117. this.loader = null;
  30118. this.config = null;
  30119. this.context = null;
  30120. this.xhrSetup = null;
  30121. };
  30122. _proto.abortInternal = function abortInternal() {
  30123. var loader = this.loader;
  30124. self.clearTimeout(this.requestTimeout);
  30125. self.clearTimeout(this.retryTimeout);
  30126. if (loader) {
  30127. loader.onreadystatechange = null;
  30128. loader.onprogress = null;
  30129. if (loader.readyState !== 4) {
  30130. this.stats.aborted = true;
  30131. loader.abort();
  30132. }
  30133. }
  30134. };
  30135. _proto.abort = function abort() {
  30136. var _this$callbacks;
  30137. this.abortInternal();
  30138. if ((_this$callbacks = this.callbacks) != null && _this$callbacks.onAbort) {
  30139. this.callbacks.onAbort(this.stats, this.context, this.loader);
  30140. }
  30141. };
  30142. _proto.load = function load(context, config, callbacks) {
  30143. if (this.stats.loading.start) {
  30144. throw new Error('Loader can only be used once.');
  30145. }
  30146. this.stats.loading.start = self.performance.now();
  30147. this.context = context;
  30148. this.config = config;
  30149. this.callbacks = callbacks;
  30150. this.loadInternal();
  30151. };
  30152. _proto.loadInternal = function loadInternal() {
  30153. var _this = this;
  30154. var config = this.config,
  30155. context = this.context;
  30156. if (!config || !context) {
  30157. return;
  30158. }
  30159. var xhr = this.loader = new self.XMLHttpRequest();
  30160. var stats = this.stats;
  30161. stats.loading.first = 0;
  30162. stats.loaded = 0;
  30163. stats.aborted = false;
  30164. var xhrSetup = this.xhrSetup;
  30165. if (xhrSetup) {
  30166. Promise.resolve().then(function () {
  30167. if (_this.loader !== xhr || _this.stats.aborted) return;
  30168. return xhrSetup(xhr, context.url);
  30169. }).catch(function (error) {
  30170. if (_this.loader !== xhr || _this.stats.aborted) return;
  30171. xhr.open('GET', context.url, true);
  30172. return xhrSetup(xhr, context.url);
  30173. }).then(function () {
  30174. if (_this.loader !== xhr || _this.stats.aborted) return;
  30175. _this.openAndSendXhr(xhr, context, config);
  30176. }).catch(function (error) {
  30177. var _this$callbacks2;
  30178. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  30179. (_this$callbacks2 = _this.callbacks) == null ? void 0 : _this$callbacks2.onError({
  30180. code: xhr.status,
  30181. text: error.message
  30182. }, context, xhr, stats);
  30183. return;
  30184. });
  30185. } else {
  30186. this.openAndSendXhr(xhr, context, config);
  30187. }
  30188. };
  30189. _proto.openAndSendXhr = function openAndSendXhr(xhr, context, config) {
  30190. if (!xhr.readyState) {
  30191. xhr.open('GET', context.url, true);
  30192. }
  30193. var headers = context.headers;
  30194. var _config$loadPolicy = config.loadPolicy,
  30195. maxTimeToFirstByteMs = _config$loadPolicy.maxTimeToFirstByteMs,
  30196. maxLoadTimeMs = _config$loadPolicy.maxLoadTimeMs;
  30197. if (headers) {
  30198. for (var header in headers) {
  30199. xhr.setRequestHeader(header, headers[header]);
  30200. }
  30201. }
  30202. if (context.rangeEnd) {
  30203. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  30204. }
  30205. xhr.onreadystatechange = this.readystatechange.bind(this);
  30206. xhr.onprogress = this.loadprogress.bind(this);
  30207. xhr.responseType = context.responseType;
  30208. // setup timeout before we perform request
  30209. self.clearTimeout(this.requestTimeout);
  30210. config.timeout = maxTimeToFirstByteMs && isFiniteNumber(maxTimeToFirstByteMs) ? maxTimeToFirstByteMs : maxLoadTimeMs;
  30211. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
  30212. xhr.send();
  30213. };
  30214. _proto.readystatechange = function readystatechange() {
  30215. var context = this.context,
  30216. xhr = this.loader,
  30217. stats = this.stats;
  30218. if (!context || !xhr) {
  30219. return;
  30220. }
  30221. var readyState = xhr.readyState;
  30222. var config = this.config;
  30223. // don't proceed if xhr has been aborted
  30224. if (stats.aborted) {
  30225. return;
  30226. }
  30227. // >= HEADERS_RECEIVED
  30228. if (readyState >= 2) {
  30229. if (stats.loading.first === 0) {
  30230. stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
  30231. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  30232. if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {
  30233. self.clearTimeout(this.requestTimeout);
  30234. config.timeout = config.loadPolicy.maxLoadTimeMs;
  30235. this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.loadPolicy.maxLoadTimeMs - (stats.loading.first - stats.loading.start));
  30236. }
  30237. }
  30238. if (readyState === 4) {
  30239. self.clearTimeout(this.requestTimeout);
  30240. xhr.onreadystatechange = null;
  30241. xhr.onprogress = null;
  30242. var _status = xhr.status;
  30243. // http status between 200 to 299 are all successful
  30244. var useResponseText = xhr.responseType === 'text' ? xhr.responseText : null;
  30245. if (_status >= 200 && _status < 300) {
  30246. var data = useResponseText != null ? useResponseText : xhr.response;
  30247. if (data != null) {
  30248. var _this$callbacks3, _this$callbacks4;
  30249. stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
  30250. var len = xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;
  30251. stats.loaded = stats.total = len;
  30252. stats.bwEstimate = stats.total * 8000 / (stats.loading.end - stats.loading.first);
  30253. var onProgress = (_this$callbacks3 = this.callbacks) == null ? void 0 : _this$callbacks3.onProgress;
  30254. if (onProgress) {
  30255. onProgress(stats, context, data, xhr);
  30256. }
  30257. var _response = {
  30258. url: xhr.responseURL,
  30259. data: data,
  30260. code: _status
  30261. };
  30262. (_this$callbacks4 = this.callbacks) == null ? void 0 : _this$callbacks4.onSuccess(_response, stats, context, xhr);
  30263. return;
  30264. }
  30265. }
  30266. // Handle bad status or nullish response
  30267. var retryConfig = config.loadPolicy.errorRetry;
  30268. var retryCount = stats.retry;
  30269. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  30270. var response = {
  30271. url: context.url,
  30272. data: undefined,
  30273. code: _status
  30274. };
  30275. if (shouldRetry(retryConfig, retryCount, false, response)) {
  30276. this.retry(retryConfig);
  30277. } else {
  30278. var _this$callbacks5;
  30279. logger.error(_status + " while loading " + context.url);
  30280. (_this$callbacks5 = this.callbacks) == null ? void 0 : _this$callbacks5.onError({
  30281. code: _status,
  30282. text: xhr.statusText
  30283. }, context, xhr, stats);
  30284. }
  30285. }
  30286. }
  30287. };
  30288. _proto.loadtimeout = function loadtimeout() {
  30289. if (!this.config) return;
  30290. var retryConfig = this.config.loadPolicy.timeoutRetry;
  30291. var retryCount = this.stats.retry;
  30292. if (shouldRetry(retryConfig, retryCount, true)) {
  30293. this.retry(retryConfig);
  30294. } else {
  30295. var _this$context;
  30296. logger.warn("timeout while loading " + ((_this$context = this.context) == null ? void 0 : _this$context.url));
  30297. var callbacks = this.callbacks;
  30298. if (callbacks) {
  30299. this.abortInternal();
  30300. callbacks.onTimeout(this.stats, this.context, this.loader);
  30301. }
  30302. }
  30303. };
  30304. _proto.retry = function retry(retryConfig) {
  30305. var context = this.context,
  30306. stats = this.stats;
  30307. this.retryDelay = getRetryDelay(retryConfig, stats.retry);
  30308. stats.retry++;
  30309. logger.warn((status ? 'HTTP Status ' + status : 'Timeout') + " while loading " + (context == null ? void 0 : context.url) + ", retrying " + stats.retry + "/" + retryConfig.maxNumRetry + " in " + this.retryDelay + "ms");
  30310. // abort and reset internal state
  30311. this.abortInternal();
  30312. this.loader = null;
  30313. // schedule retry
  30314. self.clearTimeout(this.retryTimeout);
  30315. this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  30316. };
  30317. _proto.loadprogress = function loadprogress(event) {
  30318. var stats = this.stats;
  30319. stats.loaded = event.loaded;
  30320. if (event.lengthComputable) {
  30321. stats.total = event.total;
  30322. }
  30323. };
  30324. _proto.getCacheAge = function getCacheAge() {
  30325. var result = null;
  30326. if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
  30327. var ageHeader = this.loader.getResponseHeader('age');
  30328. result = ageHeader ? parseFloat(ageHeader) : null;
  30329. }
  30330. return result;
  30331. };
  30332. _proto.getResponseHeader = function getResponseHeader(name) {
  30333. if (this.loader && new RegExp("^" + name + ":\\s*[\\d.]+\\s*$", 'im').test(this.loader.getAllResponseHeaders())) {
  30334. return this.loader.getResponseHeader(name);
  30335. }
  30336. return null;
  30337. };
  30338. return XhrLoader;
  30339. }();
  30340. /**
  30341. * @deprecated use fragLoadPolicy.default
  30342. */
  30343. /**
  30344. * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default
  30345. */
  30346. var defaultLoadPolicy = {
  30347. maxTimeToFirstByteMs: 8000,
  30348. maxLoadTimeMs: 20000,
  30349. timeoutRetry: null,
  30350. errorRetry: null
  30351. };
  30352. /**
  30353. * @ignore
  30354. * If possible, keep hlsDefaultConfig shallow
  30355. * It is cloned whenever a new Hls instance is created, by keeping the config
  30356. * shallow the properties are cloned, and we don't end up manipulating the default
  30357. */
  30358. var hlsDefaultConfig = _objectSpread2(_objectSpread2({
  30359. autoStartLoad: true,
  30360. // used by stream-controller
  30361. startPosition: -1,
  30362. // used by stream-controller
  30363. defaultAudioCodec: undefined,
  30364. // used by stream-controller
  30365. debug: false,
  30366. // used by logger
  30367. capLevelOnFPSDrop: false,
  30368. // used by fps-controller
  30369. capLevelToPlayerSize: false,
  30370. // used by cap-level-controller
  30371. ignoreDevicePixelRatio: false,
  30372. // used by cap-level-controller
  30373. maxDevicePixelRatio: Number.POSITIVE_INFINITY,
  30374. // used by cap-level-controller
  30375. preferManagedMediaSource: true,
  30376. initialLiveManifestSize: 1,
  30377. // used by stream-controller
  30378. maxBufferLength: 30,
  30379. // used by stream-controller
  30380. backBufferLength: Infinity,
  30381. // used by buffer-controller
  30382. frontBufferFlushThreshold: Infinity,
  30383. startOnSegmentBoundary: false,
  30384. // used by stream-controller
  30385. maxBufferSize: 60 * 1000 * 1000,
  30386. // used by stream-controller
  30387. maxFragLookUpTolerance: 0.25,
  30388. // used by stream-controller
  30389. maxBufferHole: 0.1,
  30390. // used by stream-controller and gap-controller
  30391. detectStallWithCurrentTimeMs: 1250,
  30392. // used by gap-controller
  30393. highBufferWatchdogPeriod: 2,
  30394. // used by gap-controller
  30395. nudgeOffset: 0.1,
  30396. // used by gap-controller
  30397. nudgeMaxRetry: 3,
  30398. // used by gap-controller
  30399. nudgeOnVideoHole: true,
  30400. // used by gap-controller
  30401. liveSyncMode: 'edge',
  30402. // used by stream-controller
  30403. liveSyncDurationCount: 3,
  30404. // used by latency-controller
  30405. liveSyncOnStallIncrease: 1,
  30406. // used by latency-controller
  30407. liveMaxLatencyDurationCount: Infinity,
  30408. // used by latency-controller
  30409. liveSyncDuration: undefined,
  30410. // used by latency-controller
  30411. liveMaxLatencyDuration: undefined,
  30412. // used by latency-controller
  30413. maxLiveSyncPlaybackRate: 1,
  30414. // used by latency-controller
  30415. liveDurationInfinity: false,
  30416. // used by buffer-controller
  30417. /**
  30418. * @deprecated use backBufferLength
  30419. */
  30420. liveBackBufferLength: null,
  30421. // used by buffer-controller
  30422. maxMaxBufferLength: 600,
  30423. // used by stream-controller
  30424. enableWorker: true,
  30425. // used by transmuxer
  30426. workerPath: null,
  30427. // used by transmuxer
  30428. enableSoftwareAES: true,
  30429. // used by decrypter
  30430. startLevel: undefined,
  30431. // used by level-controller
  30432. startFragPrefetch: false,
  30433. // used by stream-controller
  30434. fpsDroppedMonitoringPeriod: 5000,
  30435. // used by fps-controller
  30436. fpsDroppedMonitoringThreshold: 0.2,
  30437. // used by fps-controller
  30438. appendErrorMaxRetry: 3,
  30439. // used by buffer-controller
  30440. ignorePlaylistParsingErrors: false,
  30441. loader: XhrLoader,
  30442. // loader: FetchLoader,
  30443. fLoader: undefined,
  30444. // used by fragment-loader
  30445. pLoader: undefined,
  30446. // used by playlist-loader
  30447. xhrSetup: undefined,
  30448. // used by xhr-loader
  30449. licenseXhrSetup: undefined,
  30450. // used by eme-controller
  30451. licenseResponseCallback: undefined,
  30452. // used by eme-controller
  30453. abrController: AbrController,
  30454. bufferController: BufferController,
  30455. capLevelController: CapLevelController,
  30456. errorController: ErrorController,
  30457. fpsController: FPSController,
  30458. stretchShortVideoTrack: false,
  30459. // used by mp4-remuxer
  30460. maxAudioFramesDrift: 1,
  30461. // used by mp4-remuxer
  30462. forceKeyFrameOnDiscontinuity: true,
  30463. // used by ts-demuxer
  30464. abrEwmaFastLive: 3,
  30465. // used by abr-controller
  30466. abrEwmaSlowLive: 9,
  30467. // used by abr-controller
  30468. abrEwmaFastVoD: 3,
  30469. // used by abr-controller
  30470. abrEwmaSlowVoD: 9,
  30471. // used by abr-controller
  30472. abrEwmaDefaultEstimate: 5e5,
  30473. // 500 kbps // used by abr-controller
  30474. abrEwmaDefaultEstimateMax: 5e6,
  30475. // 5 mbps
  30476. abrBandWidthFactor: 0.95,
  30477. // used by abr-controller
  30478. abrBandWidthUpFactor: 0.7,
  30479. // used by abr-controller
  30480. abrMaxWithRealBitrate: false,
  30481. // used by abr-controller
  30482. maxStarvationDelay: 4,
  30483. // used by abr-controller
  30484. maxLoadingDelay: 4,
  30485. // used by abr-controller
  30486. minAutoBitrate: 0,
  30487. // used by hls
  30488. emeEnabled: false,
  30489. // used by eme-controller
  30490. widevineLicenseUrl: undefined,
  30491. // used by eme-controller
  30492. drmSystems: {},
  30493. // used by eme-controller
  30494. drmSystemOptions: {},
  30495. // used by eme-controller
  30496. requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess ,
  30497. // used by eme-controller
  30498. requireKeySystemAccessOnStart: false,
  30499. // used by eme-controller
  30500. testBandwidth: true,
  30501. progressive: false,
  30502. lowLatencyMode: true,
  30503. cmcd: undefined,
  30504. enableDateRangeMetadataCues: true,
  30505. enableEmsgMetadataCues: true,
  30506. enableEmsgKLVMetadata: false,
  30507. enableID3MetadataCues: true,
  30508. enableInterstitialPlayback: true,
  30509. interstitialAppendInPlace: true,
  30510. interstitialLiveLookAhead: 10,
  30511. useMediaCapabilities: true,
  30512. preserveManualLevelOnError: false,
  30513. certLoadPolicy: {
  30514. default: defaultLoadPolicy
  30515. },
  30516. keyLoadPolicy: {
  30517. default: {
  30518. maxTimeToFirstByteMs: 8000,
  30519. maxLoadTimeMs: 20000,
  30520. timeoutRetry: {
  30521. maxNumRetry: 1,
  30522. retryDelayMs: 1000,
  30523. maxRetryDelayMs: 20000,
  30524. backoff: 'linear'
  30525. },
  30526. errorRetry: {
  30527. maxNumRetry: 8,
  30528. retryDelayMs: 1000,
  30529. maxRetryDelayMs: 20000,
  30530. backoff: 'linear'
  30531. }
  30532. }
  30533. },
  30534. manifestLoadPolicy: {
  30535. default: {
  30536. maxTimeToFirstByteMs: Infinity,
  30537. maxLoadTimeMs: 20000,
  30538. timeoutRetry: {
  30539. maxNumRetry: 2,
  30540. retryDelayMs: 0,
  30541. maxRetryDelayMs: 0
  30542. },
  30543. errorRetry: {
  30544. maxNumRetry: 1,
  30545. retryDelayMs: 1000,
  30546. maxRetryDelayMs: 8000
  30547. }
  30548. }
  30549. },
  30550. playlistLoadPolicy: {
  30551. default: {
  30552. maxTimeToFirstByteMs: 10000,
  30553. maxLoadTimeMs: 20000,
  30554. timeoutRetry: {
  30555. maxNumRetry: 2,
  30556. retryDelayMs: 0,
  30557. maxRetryDelayMs: 0
  30558. },
  30559. errorRetry: {
  30560. maxNumRetry: 2,
  30561. retryDelayMs: 1000,
  30562. maxRetryDelayMs: 8000
  30563. }
  30564. }
  30565. },
  30566. fragLoadPolicy: {
  30567. default: {
  30568. maxTimeToFirstByteMs: 10000,
  30569. maxLoadTimeMs: 120000,
  30570. timeoutRetry: {
  30571. maxNumRetry: 4,
  30572. retryDelayMs: 0,
  30573. maxRetryDelayMs: 0
  30574. },
  30575. errorRetry: {
  30576. maxNumRetry: 6,
  30577. retryDelayMs: 1000,
  30578. maxRetryDelayMs: 8000
  30579. }
  30580. }
  30581. },
  30582. steeringManifestLoadPolicy: {
  30583. default: {
  30584. maxTimeToFirstByteMs: 10000,
  30585. maxLoadTimeMs: 20000,
  30586. timeoutRetry: {
  30587. maxNumRetry: 2,
  30588. retryDelayMs: 0,
  30589. maxRetryDelayMs: 0
  30590. },
  30591. errorRetry: {
  30592. maxNumRetry: 1,
  30593. retryDelayMs: 1000,
  30594. maxRetryDelayMs: 8000
  30595. }
  30596. }
  30597. },
  30598. interstitialAssetListLoadPolicy: {
  30599. default: {
  30600. maxTimeToFirstByteMs: 10000,
  30601. maxLoadTimeMs: 30000,
  30602. timeoutRetry: {
  30603. maxNumRetry: 0,
  30604. retryDelayMs: 0,
  30605. maxRetryDelayMs: 0
  30606. },
  30607. errorRetry: {
  30608. maxNumRetry: 0,
  30609. retryDelayMs: 1000,
  30610. maxRetryDelayMs: 8000
  30611. }
  30612. }
  30613. },
  30614. // These default settings are deprecated in favor of the above policies
  30615. // and are maintained for backwards compatibility
  30616. manifestLoadingTimeOut: 10000,
  30617. manifestLoadingMaxRetry: 1,
  30618. manifestLoadingRetryDelay: 1000,
  30619. manifestLoadingMaxRetryTimeout: 64000,
  30620. levelLoadingTimeOut: 10000,
  30621. levelLoadingMaxRetry: 4,
  30622. levelLoadingRetryDelay: 1000,
  30623. levelLoadingMaxRetryTimeout: 64000,
  30624. fragLoadingTimeOut: 20000,
  30625. fragLoadingMaxRetry: 6,
  30626. fragLoadingRetryDelay: 1000,
  30627. fragLoadingMaxRetryTimeout: 64000
  30628. }, timelineConfig()), {}, {
  30629. subtitleStreamController: SubtitleStreamController ,
  30630. subtitleTrackController: SubtitleTrackController ,
  30631. timelineController: TimelineController ,
  30632. audioStreamController: AudioStreamController ,
  30633. audioTrackController: AudioTrackController ,
  30634. emeController: EMEController ,
  30635. cmcdController: CMCDController ,
  30636. contentSteeringController: ContentSteeringController ,
  30637. interstitialsController: InterstitialsController
  30638. });
  30639. function timelineConfig() {
  30640. return {
  30641. cueHandler: Cues,
  30642. // used by timeline-controller
  30643. enableWebVTT: true,
  30644. // used by timeline-controller
  30645. enableIMSC1: true,
  30646. // used by timeline-controller
  30647. enableCEA708Captions: true,
  30648. // used by timeline-controller
  30649. captionsTextTrack1Label: 'English',
  30650. // used by timeline-controller
  30651. captionsTextTrack1LanguageCode: 'en',
  30652. // used by timeline-controller
  30653. captionsTextTrack2Label: 'Spanish',
  30654. // used by timeline-controller
  30655. captionsTextTrack2LanguageCode: 'es',
  30656. // used by timeline-controller
  30657. captionsTextTrack3Label: 'Unknown CC',
  30658. // used by timeline-controller
  30659. captionsTextTrack3LanguageCode: '',
  30660. // used by timeline-controller
  30661. captionsTextTrack4Label: 'Unknown CC',
  30662. // used by timeline-controller
  30663. captionsTextTrack4LanguageCode: '',
  30664. // used by timeline-controller
  30665. renderTextTracksNatively: true
  30666. };
  30667. }
  30668. /**
  30669. * @ignore
  30670. */
  30671. function mergeConfig(defaultConfig, userConfig, logger) {
  30672. if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
  30673. throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
  30674. }
  30675. if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
  30676. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
  30677. }
  30678. if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
  30679. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
  30680. }
  30681. var defaultsCopy = deepCpy(defaultConfig);
  30682. // Backwards compatibility with deprecated config values
  30683. var deprecatedSettingTypes = ['manifest', 'level', 'frag'];
  30684. var deprecatedSettings = ['TimeOut', 'MaxRetry', 'RetryDelay', 'MaxRetryTimeout'];
  30685. deprecatedSettingTypes.forEach(function (type) {
  30686. var policyName = (type === 'level' ? 'playlist' : type) + "LoadPolicy";
  30687. var policyNotSet = userConfig[policyName] === undefined;
  30688. var report = [];
  30689. deprecatedSettings.forEach(function (setting) {
  30690. var deprecatedSetting = type + "Loading" + setting;
  30691. var value = userConfig[deprecatedSetting];
  30692. if (value !== undefined && policyNotSet) {
  30693. report.push(deprecatedSetting);
  30694. var settings = defaultsCopy[policyName].default;
  30695. userConfig[policyName] = {
  30696. default: settings
  30697. };
  30698. switch (setting) {
  30699. case 'TimeOut':
  30700. settings.maxLoadTimeMs = value;
  30701. settings.maxTimeToFirstByteMs = value;
  30702. break;
  30703. case 'MaxRetry':
  30704. settings.errorRetry.maxNumRetry = value;
  30705. settings.timeoutRetry.maxNumRetry = value;
  30706. break;
  30707. case 'RetryDelay':
  30708. settings.errorRetry.retryDelayMs = value;
  30709. settings.timeoutRetry.retryDelayMs = value;
  30710. break;
  30711. case 'MaxRetryTimeout':
  30712. settings.errorRetry.maxRetryDelayMs = value;
  30713. settings.timeoutRetry.maxRetryDelayMs = value;
  30714. break;
  30715. }
  30716. }
  30717. });
  30718. if (report.length) {
  30719. logger.warn("hls.js config: \"" + report.join('", "') + "\" setting(s) are deprecated, use \"" + policyName + "\": " + stringify(userConfig[policyName]));
  30720. }
  30721. });
  30722. return _objectSpread2(_objectSpread2({}, defaultsCopy), userConfig);
  30723. }
  30724. function deepCpy(obj) {
  30725. if (obj && typeof obj === 'object') {
  30726. if (Array.isArray(obj)) {
  30727. return obj.map(deepCpy);
  30728. }
  30729. return Object.keys(obj).reduce(function (result, key) {
  30730. result[key] = deepCpy(obj[key]);
  30731. return result;
  30732. }, {});
  30733. }
  30734. return obj;
  30735. }
  30736. /**
  30737. * @ignore
  30738. */
  30739. function enableStreamingMode(config, logger) {
  30740. var currentLoader = config.loader;
  30741. if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {
  30742. // If a developer has configured their own loader, respect that choice
  30743. logger.log('[config]: Custom loader detected, cannot enable progressive streaming');
  30744. config.progressive = false;
  30745. } else {
  30746. var canStreamProgressively = fetchSupported();
  30747. if (canStreamProgressively) {
  30748. config.loader = FetchLoader;
  30749. config.progressive = true;
  30750. config.enableSoftwareAES = true;
  30751. logger.log('[config]: Progressive streaming enabled, using FetchLoader');
  30752. }
  30753. }
  30754. }
  30755. var MAX_START_GAP_JUMP = 2.0;
  30756. var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
  30757. var SKIP_BUFFER_RANGE_START = 0.05;
  30758. var TICK_INTERVAL$1 = 100;
  30759. var GapController = /*#__PURE__*/function (_TaskLoop) {
  30760. function GapController(hls, fragmentTracker) {
  30761. var _this;
  30762. _this = _TaskLoop.call(this, 'gap-controller', hls.logger) || this;
  30763. _this.hls = null;
  30764. _this.fragmentTracker = null;
  30765. _this.media = null;
  30766. _this.mediaSource = void 0;
  30767. _this.nudgeRetry = 0;
  30768. _this.stallReported = false;
  30769. _this.stalled = null;
  30770. _this.moved = false;
  30771. _this.seeking = false;
  30772. _this.buffered = {};
  30773. _this.lastCurrentTime = 0;
  30774. _this.ended = 0;
  30775. _this.waiting = 0;
  30776. _this.onMediaPlaying = function () {
  30777. _this.ended = 0;
  30778. _this.waiting = 0;
  30779. };
  30780. _this.onMediaWaiting = function () {
  30781. var _this$media;
  30782. if ((_this$media = _this.media) != null && _this$media.seeking) {
  30783. return;
  30784. }
  30785. _this.waiting = self.performance.now();
  30786. _this.tick();
  30787. };
  30788. _this.onMediaEnded = function () {
  30789. if (_this.hls) {
  30790. var _this$media2;
  30791. // ended is set when triggering MEDIA_ENDED so that we do not trigger it again on stall or on tick with media.ended
  30792. _this.ended = ((_this$media2 = _this.media) == null ? void 0 : _this$media2.currentTime) || 1;
  30793. _this.hls.trigger(Events.MEDIA_ENDED, {
  30794. stalled: false
  30795. });
  30796. }
  30797. };
  30798. _this.hls = hls;
  30799. _this.fragmentTracker = fragmentTracker;
  30800. _this.registerListeners();
  30801. return _this;
  30802. }
  30803. _inheritsLoose(GapController, _TaskLoop);
  30804. var _proto = GapController.prototype;
  30805. _proto.registerListeners = function registerListeners() {
  30806. var hls = this.hls;
  30807. if (hls) {
  30808. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30809. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30810. hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  30811. }
  30812. };
  30813. _proto.unregisterListeners = function unregisterListeners() {
  30814. var hls = this.hls;
  30815. if (hls) {
  30816. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  30817. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  30818. hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);
  30819. }
  30820. };
  30821. _proto.destroy = function destroy() {
  30822. _TaskLoop.prototype.destroy.call(this);
  30823. this.unregisterListeners();
  30824. this.media = this.hls = this.fragmentTracker = null;
  30825. this.mediaSource = undefined;
  30826. };
  30827. _proto.onMediaAttached = function onMediaAttached(event, data) {
  30828. this.setInterval(TICK_INTERVAL$1);
  30829. this.mediaSource = data.mediaSource;
  30830. var media = this.media = data.media;
  30831. addEventListener(media, 'playing', this.onMediaPlaying);
  30832. addEventListener(media, 'waiting', this.onMediaWaiting);
  30833. addEventListener(media, 'ended', this.onMediaEnded);
  30834. };
  30835. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  30836. this.clearInterval();
  30837. var media = this.media;
  30838. if (media) {
  30839. removeEventListener(media, 'playing', this.onMediaPlaying);
  30840. removeEventListener(media, 'waiting', this.onMediaWaiting);
  30841. removeEventListener(media, 'ended', this.onMediaEnded);
  30842. this.media = null;
  30843. }
  30844. this.mediaSource = undefined;
  30845. };
  30846. _proto.onBufferAppended = function onBufferAppended(event, data) {
  30847. this.buffered = data.timeRanges;
  30848. };
  30849. _proto.tick = function tick() {
  30850. var _this$media3;
  30851. if (!((_this$media3 = this.media) != null && _this$media3.readyState) || !this.hasBuffered) {
  30852. return;
  30853. }
  30854. var currentTime = this.media.currentTime;
  30855. this.poll(currentTime, this.lastCurrentTime);
  30856. this.lastCurrentTime = currentTime;
  30857. }
  30858. /**
  30859. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  30860. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  30861. *
  30862. * @param lastCurrentTime - Previously read playhead position
  30863. */;
  30864. _proto.poll = function poll(currentTime, lastCurrentTime) {
  30865. var _this$hls, _this$hls2;
  30866. var config = (_this$hls = this.hls) == null ? void 0 : _this$hls.config;
  30867. if (!config) {
  30868. return;
  30869. }
  30870. var media = this.media;
  30871. if (!media) {
  30872. return;
  30873. }
  30874. var seeking = media.seeking;
  30875. var seeked = this.seeking && !seeking;
  30876. var beginSeek = !this.seeking && seeking;
  30877. var pausedEndedOrHalted = media.paused && !seeking || media.ended || media.playbackRate === 0;
  30878. this.seeking = seeking;
  30879. // The playhead is moving, no-op
  30880. if (currentTime !== lastCurrentTime) {
  30881. if (lastCurrentTime) {
  30882. this.ended = 0;
  30883. }
  30884. this.moved = true;
  30885. if (!seeking) {
  30886. this.nudgeRetry = 0;
  30887. // When crossing between buffered video time ranges, but not audio, flush pipeline with seek (Chrome)
  30888. if (config.nudgeOnVideoHole && !pausedEndedOrHalted && currentTime > lastCurrentTime) {
  30889. this.nudgeOnVideoHole(currentTime, lastCurrentTime);
  30890. }
  30891. }
  30892. if (this.waiting === 0) {
  30893. this.stallResolved(currentTime);
  30894. }
  30895. return;
  30896. }
  30897. // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
  30898. if (beginSeek || seeked) {
  30899. if (seeked) {
  30900. this.stallResolved(currentTime);
  30901. }
  30902. return;
  30903. }
  30904. // The playhead should not be moving
  30905. if (pausedEndedOrHalted) {
  30906. this.nudgeRetry = 0;
  30907. this.stallResolved(currentTime);
  30908. // Fire MEDIA_ENDED to workaround event not being dispatched by browser
  30909. if (!this.ended && media.ended && this.hls) {
  30910. this.ended = currentTime || 1;
  30911. this.hls.trigger(Events.MEDIA_ENDED, {
  30912. stalled: false
  30913. });
  30914. }
  30915. return;
  30916. }
  30917. if (!BufferHelper.getBuffered(media).length) {
  30918. this.nudgeRetry = 0;
  30919. return;
  30920. }
  30921. // Resolve stalls at buffer holes using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
  30922. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  30923. var nextStart = bufferInfo.nextStart || 0;
  30924. var fragmentTracker = this.fragmentTracker;
  30925. if (seeking && fragmentTracker && this.hls) {
  30926. // Is there a fragment loading/parsing/appending before currentTime?
  30927. var inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, currentTime);
  30928. // Waiting for seeking in a buffered range to complete
  30929. var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;
  30930. // Next buffered range is too far ahead to jump to while still seeking
  30931. var noBufferHole = !nextStart || inFlightDependency || nextStart - currentTime > MAX_START_GAP_JUMP && !fragmentTracker.getPartialFragment(currentTime);
  30932. if (hasEnoughBuffer || noBufferHole) {
  30933. return;
  30934. }
  30935. // Reset moved state when seeking to a point in or before a gap/hole
  30936. this.moved = false;
  30937. }
  30938. // Skip start gaps if we haven't played, but the last poll detected the start of a stall
  30939. // The addition poll gives the browser a chance to jump the gap for us
  30940. var levelDetails = (_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails;
  30941. if (!this.moved && this.stalled !== null && fragmentTracker) {
  30942. // There is no playable buffer (seeked, waiting for buffer)
  30943. var isBuffered = bufferInfo.len > 0;
  30944. if (!isBuffered && !nextStart) {
  30945. return;
  30946. }
  30947. // Jump start gaps within jump threshold
  30948. var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;
  30949. // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
  30950. // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
  30951. // that begins over 1 target duration after the video start position.
  30952. var isLive = !!(levelDetails != null && levelDetails.live);
  30953. var maxStartGapJump = isLive ? levelDetails.targetduration * 2 : MAX_START_GAP_JUMP;
  30954. var partialOrGap = fragmentTracker.getPartialFragment(currentTime);
  30955. if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {
  30956. if (!media.paused) {
  30957. this._trySkipBufferHole(partialOrGap);
  30958. }
  30959. return;
  30960. }
  30961. }
  30962. // Start tracking stall time
  30963. var detectStallWithCurrentTimeMs = config.detectStallWithCurrentTimeMs;
  30964. var tnow = self.performance.now();
  30965. var tWaiting = this.waiting;
  30966. var stalled = this.stalled;
  30967. if (stalled === null) {
  30968. // Use time of recent "waiting" event
  30969. if (tWaiting > 0 && tnow - tWaiting < detectStallWithCurrentTimeMs) {
  30970. stalled = this.stalled = tWaiting;
  30971. } else {
  30972. this.stalled = tnow;
  30973. return;
  30974. }
  30975. }
  30976. var stalledDuration = tnow - stalled;
  30977. if (!seeking && (stalledDuration >= detectStallWithCurrentTimeMs || tWaiting) && this.hls) {
  30978. var _this$mediaSource;
  30979. // Dispatch MEDIA_ENDED when media.ended/ended event is not signalled at end of stream
  30980. if (((_this$mediaSource = this.mediaSource) == null ? void 0 : _this$mediaSource.readyState) === 'ended' && !(levelDetails != null && levelDetails.live) && Math.abs(currentTime - ((levelDetails == null ? void 0 : levelDetails.edge) || 0)) < 1) {
  30981. if (this.ended) {
  30982. return;
  30983. }
  30984. this.ended = currentTime || 1;
  30985. this.hls.trigger(Events.MEDIA_ENDED, {
  30986. stalled: true
  30987. });
  30988. return;
  30989. }
  30990. // Report stalling after trying to fix
  30991. this._reportStall(bufferInfo);
  30992. if (!this.media || !this.hls) {
  30993. return;
  30994. }
  30995. }
  30996. var bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  30997. this._tryFixBufferStall(bufferedWithHoles, stalledDuration, currentTime);
  30998. };
  30999. _proto.stallResolved = function stallResolved(currentTime) {
  31000. var stalled = this.stalled;
  31001. if (stalled && this.hls) {
  31002. this.stalled = null;
  31003. // The playhead is now moving, but was previously stalled
  31004. if (this.stallReported) {
  31005. var stalledDuration = self.performance.now() - stalled;
  31006. this.log("playback not stuck anymore @" + currentTime + ", after " + Math.round(stalledDuration) + "ms");
  31007. this.stallReported = false;
  31008. this.waiting = 0;
  31009. this.hls.trigger(Events.STALL_RESOLVED, {});
  31010. }
  31011. }
  31012. };
  31013. _proto.nudgeOnVideoHole = function nudgeOnVideoHole(currentTime, lastCurrentTime) {
  31014. var _this$buffered$audio;
  31015. // Chrome will play one second past a hole in video buffered time ranges without rendering any video from the subsequent range and then stall as long as audio is buffered:
  31016. // https://github.com/video-dev/hls.js/issues/5631
  31017. // https://issues.chromium.org/issues/40280613#comment10
  31018. // Detect the potential for this situation and proactively seek to flush the video pipeline once the playhead passes the start of the video hole.
  31019. // When there are audio and video buffers and currentTime is past the end of the first video buffered range...
  31020. var videoSourceBuffered = this.buffered.video;
  31021. if (this.hls && this.media && this.fragmentTracker && (_this$buffered$audio = this.buffered.audio) != null && _this$buffered$audio.length && videoSourceBuffered && videoSourceBuffered.length > 1 && currentTime > videoSourceBuffered.end(0)) {
  31022. // and audio is buffered at the playhead
  31023. var audioBufferInfo = BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio), currentTime, 0);
  31024. if (audioBufferInfo.len > 1 && lastCurrentTime >= audioBufferInfo.start) {
  31025. var videoTimes = BufferHelper.timeRangesToArray(videoSourceBuffered);
  31026. var lastBufferedIndex = BufferHelper.bufferedInfo(videoTimes, lastCurrentTime, 0).bufferedIndex;
  31027. // nudge when crossing into another video buffered range (hole).
  31028. if (lastBufferedIndex > -1 && lastBufferedIndex < videoTimes.length - 1) {
  31029. var bufferedIndex = BufferHelper.bufferedInfo(videoTimes, currentTime, 0).bufferedIndex;
  31030. var holeStart = videoTimes[lastBufferedIndex].end;
  31031. var holeEnd = videoTimes[lastBufferedIndex + 1].start;
  31032. if ((bufferedIndex === -1 || bufferedIndex > lastBufferedIndex) && holeEnd - holeStart < 1 &&
  31033. // `maxBufferHole` may be too small and setting it to 0 should not disable this feature
  31034. currentTime - holeStart < 2) {
  31035. var error = new Error("nudging playhead to flush pipeline after video hole. currentTime: " + currentTime + " hole: " + holeStart + " -> " + holeEnd + " buffered index: " + bufferedIndex);
  31036. this.warn(error.message);
  31037. // Magic number to flush the pipeline without interuption to audio playback:
  31038. this.media.currentTime += 0.000001;
  31039. var frag = this.fragmentTracker.getPartialFragment(currentTime) || undefined;
  31040. var bufferInfo = BufferHelper.bufferInfo(this.media, currentTime, 0);
  31041. this.hls.trigger(Events.ERROR, {
  31042. type: ErrorTypes.MEDIA_ERROR,
  31043. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  31044. fatal: false,
  31045. error: error,
  31046. reason: error.message,
  31047. frag: frag,
  31048. buffer: bufferInfo.len,
  31049. bufferInfo: bufferInfo
  31050. });
  31051. }
  31052. }
  31053. }
  31054. }
  31055. }
  31056. /**
  31057. * Detects and attempts to fix known buffer stalling issues.
  31058. * @param bufferInfo - The properties of the current buffer.
  31059. * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
  31060. * @private
  31061. */;
  31062. _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs, currentTime) {
  31063. var _this$hls3, _this$hls4;
  31064. var fragmentTracker = this.fragmentTracker,
  31065. media = this.media;
  31066. var config = (_this$hls3 = this.hls) == null ? void 0 : _this$hls3.config;
  31067. if (!media || !fragmentTracker || !config) {
  31068. return;
  31069. }
  31070. var levelDetails = (_this$hls4 = this.hls) == null ? void 0 : _this$hls4.latestLevelDetails;
  31071. var partial = fragmentTracker.getPartialFragment(currentTime);
  31072. if (partial || levelDetails != null && levelDetails.live && currentTime < levelDetails.fragmentStart) {
  31073. // Try to skip over the buffer hole caused by a partial fragment
  31074. // This method isn't limited by the size of the gap between buffered ranges
  31075. var targetTime = this._trySkipBufferHole(partial);
  31076. // we return here in this case, meaning
  31077. // the branch below only executes when we haven't seeked to a new position
  31078. if (targetTime || !this.media) {
  31079. return;
  31080. }
  31081. }
  31082. // if we haven't had to skip over a buffer hole of a partial fragment
  31083. // we may just have to "nudge" the playlist as the browser decoding/rendering engine
  31084. // needs to cross some sort of threshold covering all source-buffers content
  31085. // to start playing properly.
  31086. var bufferedRanges = bufferInfo.buffered;
  31087. var adjacentTraversal = this.adjacentTraversal(bufferInfo, currentTime);
  31088. if ((bufferedRanges && bufferedRanges.length > 1 && bufferInfo.len > config.maxBufferHole || bufferInfo.nextStart && (bufferInfo.nextStart - currentTime < config.maxBufferHole || adjacentTraversal)) && (stalledDurationMs > config.highBufferWatchdogPeriod * 1000 || this.waiting)) {
  31089. this.warn('Trying to nudge playhead over buffer-hole');
  31090. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  31091. // We only try to jump the hole if it's under the configured size
  31092. this._tryNudgeBuffer(bufferInfo);
  31093. }
  31094. };
  31095. _proto.adjacentTraversal = function adjacentTraversal(bufferInfo, currentTime) {
  31096. var fragmentTracker = this.fragmentTracker;
  31097. var nextStart = bufferInfo.nextStart;
  31098. if (fragmentTracker && nextStart) {
  31099. var current = fragmentTracker.getFragAtPos(currentTime, PlaylistLevelType.MAIN);
  31100. var next = fragmentTracker.getFragAtPos(nextStart, PlaylistLevelType.MAIN);
  31101. if (current && next) {
  31102. return next.sn - current.sn < 2;
  31103. }
  31104. }
  31105. return false;
  31106. }
  31107. /**
  31108. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  31109. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  31110. * @private
  31111. */;
  31112. _proto._reportStall = function _reportStall(bufferInfo) {
  31113. var hls = this.hls,
  31114. media = this.media,
  31115. stallReported = this.stallReported,
  31116. stalled = this.stalled;
  31117. if (!stallReported && stalled !== null && media && hls) {
  31118. // Report stalled error once
  31119. this.stallReported = true;
  31120. var error = new Error("Playback stalling at @" + media.currentTime + " due to low buffer (" + stringify(bufferInfo) + ")");
  31121. this.warn(error.message);
  31122. hls.trigger(Events.ERROR, {
  31123. type: ErrorTypes.MEDIA_ERROR,
  31124. details: ErrorDetails.BUFFER_STALLED_ERROR,
  31125. fatal: false,
  31126. error: error,
  31127. buffer: bufferInfo.len,
  31128. bufferInfo: bufferInfo,
  31129. stalled: {
  31130. start: stalled
  31131. }
  31132. });
  31133. }
  31134. }
  31135. /**
  31136. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  31137. * @param partial - The partial fragment found at the current time (where playback is stalling).
  31138. * @private
  31139. */;
  31140. _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
  31141. var _this$hls5;
  31142. var fragmentTracker = this.fragmentTracker,
  31143. media = this.media;
  31144. var config = (_this$hls5 = this.hls) == null ? void 0 : _this$hls5.config;
  31145. if (!media || !fragmentTracker || !config) {
  31146. return 0;
  31147. }
  31148. // Check if currentTime is between unbuffered regions of partial fragments
  31149. var currentTime = media.currentTime;
  31150. var bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);
  31151. var startTime = currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;
  31152. if (startTime && this.hls) {
  31153. var bufferStarved = bufferInfo.len <= config.maxBufferHole;
  31154. var waiting = bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;
  31155. var gapLength = startTime - currentTime;
  31156. if (gapLength > 0 && (bufferStarved || waiting)) {
  31157. // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial
  31158. if (gapLength > config.maxBufferHole) {
  31159. var startGap = false;
  31160. if (currentTime === 0) {
  31161. var startFrag = fragmentTracker.getAppendedFrag(0, PlaylistLevelType.MAIN);
  31162. if (startFrag && startTime < startFrag.end) {
  31163. startGap = true;
  31164. }
  31165. }
  31166. if (!startGap) {
  31167. var startProvisioned = partial || fragmentTracker.getAppendedFrag(currentTime, PlaylistLevelType.MAIN);
  31168. if (startProvisioned) {
  31169. var _this$hls$loadLevelOb;
  31170. // Do not seek when selected variant playlist is unloaded
  31171. if (!((_this$hls$loadLevelOb = this.hls.loadLevelObj) != null && _this$hls$loadLevelOb.details)) {
  31172. return 0;
  31173. }
  31174. // Do not seek when required fragments are inflight or appending
  31175. var inFlightDependency = getInFlightDependency(this.hls.inFlightFragments, startTime);
  31176. if (inFlightDependency) {
  31177. return 0;
  31178. }
  31179. // Do not seek if we can't walk tracked fragments to end of gap
  31180. var moreToLoad = false;
  31181. var pos = startProvisioned.end;
  31182. while (pos < startTime) {
  31183. var provisioned = fragmentTracker.getAppendedFrag(pos, PlaylistLevelType.MAIN) || fragmentTracker.getPartialFragment(pos);
  31184. if (provisioned) {
  31185. pos += provisioned.duration;
  31186. } else {
  31187. moreToLoad = true;
  31188. break;
  31189. }
  31190. }
  31191. if (moreToLoad) {
  31192. return 0;
  31193. }
  31194. }
  31195. }
  31196. }
  31197. var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
  31198. this.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
  31199. this.moved = true;
  31200. media.currentTime = targetTime;
  31201. if (!(partial != null && partial.gap)) {
  31202. var error = new Error("fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime);
  31203. this.hls.trigger(Events.ERROR, {
  31204. type: ErrorTypes.MEDIA_ERROR,
  31205. details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  31206. fatal: false,
  31207. error: error,
  31208. reason: error.message,
  31209. frag: partial || undefined,
  31210. buffer: bufferInfo.len,
  31211. bufferInfo: bufferInfo
  31212. });
  31213. }
  31214. return targetTime;
  31215. }
  31216. }
  31217. return 0;
  31218. }
  31219. /**
  31220. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  31221. * @private
  31222. */;
  31223. _proto._tryNudgeBuffer = function _tryNudgeBuffer(bufferInfo) {
  31224. var hls = this.hls,
  31225. media = this.media,
  31226. nudgeRetry = this.nudgeRetry;
  31227. var config = hls == null ? void 0 : hls.config;
  31228. if (!media || !config) {
  31229. return 0;
  31230. }
  31231. var currentTime = media.currentTime;
  31232. this.nudgeRetry++;
  31233. if (nudgeRetry < config.nudgeMaxRetry) {
  31234. var targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;
  31235. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  31236. var error = new Error("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
  31237. this.warn(error.message);
  31238. media.currentTime = targetTime;
  31239. hls.trigger(Events.ERROR, {
  31240. type: ErrorTypes.MEDIA_ERROR,
  31241. details: ErrorDetails.BUFFER_NUDGE_ON_STALL,
  31242. error: error,
  31243. fatal: false,
  31244. buffer: bufferInfo.len,
  31245. bufferInfo: bufferInfo
  31246. });
  31247. } else {
  31248. var _error = new Error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
  31249. this.error(_error.message);
  31250. hls.trigger(Events.ERROR, {
  31251. type: ErrorTypes.MEDIA_ERROR,
  31252. details: ErrorDetails.BUFFER_STALLED_ERROR,
  31253. error: _error,
  31254. fatal: true,
  31255. buffer: bufferInfo.len,
  31256. bufferInfo: bufferInfo
  31257. });
  31258. }
  31259. };
  31260. return _createClass(GapController, [{
  31261. key: "hasBuffered",
  31262. get: function get() {
  31263. return Object.keys(this.buffered).length > 0;
  31264. }
  31265. }]);
  31266. }(TaskLoop);
  31267. function getInFlightDependency(inFlightFragments, currentTime) {
  31268. var main = inFlight(inFlightFragments.main);
  31269. if (main && main.start <= currentTime) {
  31270. return main;
  31271. }
  31272. var audio = inFlight(inFlightFragments.audio);
  31273. if (audio && audio.start <= currentTime) {
  31274. return audio;
  31275. }
  31276. return null;
  31277. }
  31278. function inFlight(inFlightData) {
  31279. if (!inFlightData) {
  31280. return null;
  31281. }
  31282. switch (inFlightData.state) {
  31283. case State.IDLE:
  31284. case State.STOPPED:
  31285. case State.ENDED:
  31286. case State.ERROR:
  31287. return null;
  31288. }
  31289. return inFlightData.frag;
  31290. }
  31291. var MIN_CUE_DURATION = 0.25;
  31292. function getCueClass() {
  31293. if (typeof self === 'undefined') return undefined;
  31294. return self.VTTCue || self.TextTrackCue;
  31295. }
  31296. function createCueWithDataFields(Cue, startTime, endTime, data, type) {
  31297. var cue = new Cue(startTime, endTime, '');
  31298. try {
  31299. cue.value = data;
  31300. if (type) {
  31301. cue.type = type;
  31302. }
  31303. } catch (e) {
  31304. cue = new Cue(startTime, endTime, stringify(type ? _objectSpread2({
  31305. type: type
  31306. }, data) : data));
  31307. }
  31308. return cue;
  31309. }
  31310. // VTTCue latest draft allows an infinite duration, fallback
  31311. // to MAX_VALUE if necessary
  31312. var MAX_CUE_ENDTIME = function () {
  31313. var Cue = getCueClass();
  31314. try {
  31315. Cue && new Cue(0, Number.POSITIVE_INFINITY, '');
  31316. } catch (e) {
  31317. return Number.MAX_VALUE;
  31318. }
  31319. return Number.POSITIVE_INFINITY;
  31320. }();
  31321. var ID3TrackController = /*#__PURE__*/function () {
  31322. function ID3TrackController(hls) {
  31323. var _this = this;
  31324. this.hls = void 0;
  31325. this.id3Track = null;
  31326. this.media = null;
  31327. this.dateRangeCuesAppended = {};
  31328. this.removeCues = true;
  31329. this.onEventCueEnter = function () {
  31330. if (!_this.hls) {
  31331. return;
  31332. }
  31333. _this.hls.trigger(Events.EVENT_CUE_ENTER, {});
  31334. };
  31335. this.hls = hls;
  31336. this._registerListeners();
  31337. }
  31338. var _proto = ID3TrackController.prototype;
  31339. _proto.destroy = function destroy() {
  31340. this._unregisterListeners();
  31341. this.id3Track = null;
  31342. this.media = null;
  31343. this.dateRangeCuesAppended = {};
  31344. // @ts-ignore
  31345. this.hls = this.onEventCueEnter = null;
  31346. };
  31347. _proto._registerListeners = function _registerListeners() {
  31348. var hls = this.hls;
  31349. hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  31350. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  31351. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  31352. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31353. hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  31354. hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  31355. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  31356. hls.on(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  31357. };
  31358. _proto._unregisterListeners = function _unregisterListeners() {
  31359. var hls = this.hls;
  31360. hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);
  31361. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  31362. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  31363. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31364. hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
  31365. hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);
  31366. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  31367. hls.off(Events.LEVEL_PTS_UPDATED, this.onLevelPtsUpdated, this);
  31368. };
  31369. // Add ID3 metatadata text track.
  31370. _proto.onMediaAttaching = function onMediaAttaching(event, data) {
  31371. var _data$overrides;
  31372. this.media = data.media;
  31373. if (((_data$overrides = data.overrides) == null ? void 0 : _data$overrides.cueRemoval) === false) {
  31374. this.removeCues = false;
  31375. }
  31376. };
  31377. _proto.onMediaAttached = function onMediaAttached() {
  31378. var details = this.hls.latestLevelDetails;
  31379. if (details) {
  31380. this.updateDateRangeCues(details);
  31381. }
  31382. };
  31383. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  31384. this.media = null;
  31385. var transferringMedia = !!data.transferMedia;
  31386. if (transferringMedia) {
  31387. return;
  31388. }
  31389. if (this.id3Track) {
  31390. if (this.removeCues) {
  31391. clearCurrentCues(this.id3Track, this.onEventCueEnter);
  31392. }
  31393. this.id3Track = null;
  31394. }
  31395. this.dateRangeCuesAppended = {};
  31396. };
  31397. _proto.onManifestLoading = function onManifestLoading() {
  31398. this.dateRangeCuesAppended = {};
  31399. };
  31400. _proto.createTrack = function createTrack(media) {
  31401. var track = this.getID3Track(media.textTracks);
  31402. track.mode = 'hidden';
  31403. return track;
  31404. };
  31405. _proto.getID3Track = function getID3Track(textTracks) {
  31406. if (!this.media) {
  31407. return;
  31408. }
  31409. for (var i = 0; i < textTracks.length; i++) {
  31410. var textTrack = textTracks[i];
  31411. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  31412. // send 'addtrack' when reusing the textTrack for metadata,
  31413. // same as what we do for captions
  31414. sendAddTrackEvent(textTrack, this.media);
  31415. return textTrack;
  31416. }
  31417. }
  31418. return this.media.addTextTrack('metadata', 'id3');
  31419. };
  31420. _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
  31421. if (!this.media) {
  31422. return;
  31423. }
  31424. var _this$hls$config = this.hls.config,
  31425. enableEmsgMetadataCues = _this$hls$config.enableEmsgMetadataCues,
  31426. enableID3MetadataCues = _this$hls$config.enableID3MetadataCues;
  31427. if (!enableEmsgMetadataCues && !enableID3MetadataCues) {
  31428. return;
  31429. }
  31430. var samples = data.samples;
  31431. // create track dynamically
  31432. if (!this.id3Track) {
  31433. this.id3Track = this.createTrack(this.media);
  31434. }
  31435. var Cue = getCueClass();
  31436. if (!Cue) {
  31437. return;
  31438. }
  31439. for (var i = 0; i < samples.length; i++) {
  31440. var type = samples[i].type;
  31441. if (type === MetadataSchema.emsg && !enableEmsgMetadataCues || !enableID3MetadataCues) {
  31442. continue;
  31443. }
  31444. var frames = getId3Frames(samples[i].data);
  31445. if (frames) {
  31446. var startTime = samples[i].pts;
  31447. var endTime = startTime + samples[i].duration;
  31448. if (endTime > MAX_CUE_ENDTIME) {
  31449. endTime = MAX_CUE_ENDTIME;
  31450. }
  31451. var timeDiff = endTime - startTime;
  31452. if (timeDiff <= 0) {
  31453. endTime = startTime + MIN_CUE_DURATION;
  31454. }
  31455. for (var j = 0; j < frames.length; j++) {
  31456. var frame = frames[j];
  31457. // Safari doesn't put the timestamp frame in the TextTrack
  31458. if (!isId3TimestampFrame(frame)) {
  31459. // add a bounds to any unbounded cues
  31460. this.updateId3CueEnds(startTime, type);
  31461. var cue = createCueWithDataFields(Cue, startTime, endTime, frame, type);
  31462. if (cue) {
  31463. this.id3Track.addCue(cue);
  31464. }
  31465. }
  31466. }
  31467. }
  31468. }
  31469. };
  31470. _proto.updateId3CueEnds = function updateId3CueEnds(startTime, type) {
  31471. var _this$id3Track;
  31472. var cues = (_this$id3Track = this.id3Track) == null ? void 0 : _this$id3Track.cues;
  31473. if (cues) {
  31474. for (var i = cues.length; i--;) {
  31475. var cue = cues[i];
  31476. if (cue.type === type && cue.startTime < startTime && cue.endTime === MAX_CUE_ENDTIME) {
  31477. cue.endTime = startTime;
  31478. }
  31479. }
  31480. }
  31481. };
  31482. _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
  31483. var startOffset = _ref.startOffset,
  31484. endOffset = _ref.endOffset,
  31485. type = _ref.type;
  31486. var id3Track = this.id3Track,
  31487. hls = this.hls;
  31488. if (!hls) {
  31489. return;
  31490. }
  31491. var _hls$config = hls.config,
  31492. enableEmsgMetadataCues = _hls$config.enableEmsgMetadataCues,
  31493. enableID3MetadataCues = _hls$config.enableID3MetadataCues;
  31494. if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {
  31495. var predicate;
  31496. if (type === 'audio') {
  31497. predicate = function predicate(cue) {
  31498. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues;
  31499. };
  31500. } else if (type === 'video') {
  31501. predicate = function predicate(cue) {
  31502. return cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  31503. };
  31504. } else {
  31505. predicate = function predicate(cue) {
  31506. return cue.type === MetadataSchema.audioId3 && enableID3MetadataCues || cue.type === MetadataSchema.emsg && enableEmsgMetadataCues;
  31507. };
  31508. }
  31509. removeCuesInRange(id3Track, startOffset, endOffset, predicate);
  31510. }
  31511. };
  31512. _proto.onLevelUpdated = function onLevelUpdated(event, _ref2) {
  31513. var details = _ref2.details;
  31514. this.updateDateRangeCues(details, true);
  31515. };
  31516. _proto.onLevelPtsUpdated = function onLevelPtsUpdated(event, data) {
  31517. if (Math.abs(data.drift) > 0.01) {
  31518. this.updateDateRangeCues(data.details);
  31519. }
  31520. };
  31521. _proto.updateDateRangeCues = function updateDateRangeCues(details, removeOldCues) {
  31522. var _this2 = this;
  31523. if (!this.media || !details.hasProgramDateTime || !this.hls.config.enableDateRangeMetadataCues) {
  31524. return;
  31525. }
  31526. var id3Track = this.id3Track;
  31527. var dateRanges = details.dateRanges;
  31528. var ids = Object.keys(dateRanges);
  31529. var dateRangeCuesAppended = this.dateRangeCuesAppended;
  31530. // Remove cues from track not found in details.dateRanges
  31531. if (id3Track && removeOldCues) {
  31532. var _id3Track$cues;
  31533. if ((_id3Track$cues = id3Track.cues) != null && _id3Track$cues.length) {
  31534. var idsToRemove = Object.keys(dateRangeCuesAppended).filter(function (id) {
  31535. return !ids.includes(id);
  31536. });
  31537. var _loop = function _loop() {
  31538. var id = idsToRemove[i];
  31539. var cues = dateRangeCuesAppended[id].cues;
  31540. delete dateRangeCuesAppended[id];
  31541. Object.keys(cues).forEach(function (key) {
  31542. try {
  31543. var cue = cues[key];
  31544. cue.removeEventListener('enter', _this2.onEventCueEnter);
  31545. id3Track.removeCue(cue);
  31546. } catch (e) {
  31547. /* no-op */
  31548. }
  31549. });
  31550. };
  31551. for (var i = idsToRemove.length; i--;) {
  31552. _loop();
  31553. }
  31554. } else {
  31555. dateRangeCuesAppended = this.dateRangeCuesAppended = {};
  31556. }
  31557. }
  31558. // Exit if the playlist does not have Date Ranges or does not have Program Date Time
  31559. var lastFragment = details.fragments[details.fragments.length - 1];
  31560. if (ids.length === 0 || !isFiniteNumber(lastFragment == null ? void 0 : lastFragment.programDateTime)) {
  31561. return;
  31562. }
  31563. if (!this.id3Track) {
  31564. this.id3Track = this.createTrack(this.media);
  31565. }
  31566. var Cue = getCueClass();
  31567. var _loop2 = function _loop2() {
  31568. var id = ids[_i];
  31569. var dateRange = dateRanges[id];
  31570. var startTime = dateRange.startTime;
  31571. // Process DateRanges to determine end-time (known DURATION, END-DATE, or END-ON-NEXT)
  31572. var appendedDateRangeCues = dateRangeCuesAppended[id];
  31573. var cues = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.cues) || {};
  31574. var durationKnown = (appendedDateRangeCues == null ? void 0 : appendedDateRangeCues.durationKnown) || false;
  31575. var endTime = MAX_CUE_ENDTIME;
  31576. var duration = dateRange.duration,
  31577. endDate = dateRange.endDate;
  31578. if (endDate && duration !== null) {
  31579. endTime = startTime + duration;
  31580. durationKnown = true;
  31581. } else if (dateRange.endOnNext && !durationKnown) {
  31582. var nextDateRangeWithSameClass = ids.reduce(function (candidateDateRange, id) {
  31583. if (id !== dateRange.id) {
  31584. var otherDateRange = dateRanges[id];
  31585. if (otherDateRange.class === dateRange.class && otherDateRange.startDate > dateRange.startDate && (!candidateDateRange || dateRange.startDate < candidateDateRange.startDate)) {
  31586. return otherDateRange;
  31587. }
  31588. }
  31589. return candidateDateRange;
  31590. }, null);
  31591. if (nextDateRangeWithSameClass) {
  31592. endTime = nextDateRangeWithSameClass.startTime;
  31593. durationKnown = true;
  31594. }
  31595. }
  31596. // Create TextTrack Cues for each MetadataGroup Item (select DateRange attribute)
  31597. // This is to emulate Safari HLS playback handling of DateRange tags
  31598. var attributes = Object.keys(dateRange.attr);
  31599. for (var j = 0; j < attributes.length; j++) {
  31600. var key = attributes[j];
  31601. if (!isDateRangeCueAttribute(key)) {
  31602. continue;
  31603. }
  31604. var cue = cues[key];
  31605. if (cue) {
  31606. if (durationKnown && !appendedDateRangeCues.durationKnown) {
  31607. cue.endTime = endTime;
  31608. } else if (Math.abs(cue.startTime - startTime) > 0.01) {
  31609. cue.startTime = startTime;
  31610. cue.endTime = endTime;
  31611. }
  31612. } else if (Cue) {
  31613. var data = dateRange.attr[key];
  31614. if (isSCTE35Attribute(key)) {
  31615. data = hexToArrayBuffer(data);
  31616. }
  31617. var payload = {
  31618. key: key,
  31619. data: data
  31620. };
  31621. var _cue = createCueWithDataFields(Cue, startTime, endTime, payload, MetadataSchema.dateRange);
  31622. if (_cue) {
  31623. _cue.id = id;
  31624. _this2.id3Track.addCue(_cue);
  31625. cues[key] = _cue;
  31626. if (_this2.hls.config.interstitialsController) {
  31627. if (key === 'X-ASSET-LIST' || key === 'X-ASSET-URL') {
  31628. _cue.addEventListener('enter', _this2.onEventCueEnter);
  31629. }
  31630. }
  31631. }
  31632. }
  31633. }
  31634. // Keep track of processed DateRanges by ID for updating cues with new DateRange tag attributes
  31635. dateRangeCuesAppended[id] = {
  31636. cues: cues,
  31637. dateRange: dateRange,
  31638. durationKnown: durationKnown
  31639. };
  31640. };
  31641. for (var _i = 0; _i < ids.length; _i++) {
  31642. _loop2();
  31643. }
  31644. };
  31645. return ID3TrackController;
  31646. }();
  31647. var LatencyController = /*#__PURE__*/function () {
  31648. function LatencyController(hls) {
  31649. var _this = this;
  31650. this.hls = void 0;
  31651. this.config = void 0;
  31652. this.media = null;
  31653. this.currentTime = 0;
  31654. this.stallCount = 0;
  31655. this._latency = null;
  31656. this._targetLatencyUpdated = false;
  31657. this.onTimeupdate = function () {
  31658. var media = _this.media;
  31659. var levelDetails = _this.levelDetails;
  31660. if (!media || !levelDetails) {
  31661. return;
  31662. }
  31663. _this.currentTime = media.currentTime;
  31664. var latency = _this.computeLatency();
  31665. if (latency === null) {
  31666. return;
  31667. }
  31668. _this._latency = latency;
  31669. // Adapt playbackRate to meet target latency in low-latency mode
  31670. var _this$config = _this.config,
  31671. lowLatencyMode = _this$config.lowLatencyMode,
  31672. maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
  31673. if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1 || !levelDetails.live) {
  31674. return;
  31675. }
  31676. var targetLatency = _this.targetLatency;
  31677. if (targetLatency === null) {
  31678. return;
  31679. }
  31680. var distanceFromTarget = latency - targetLatency;
  31681. // Only adjust playbackRate when within one target duration of targetLatency
  31682. // and more than one second from under-buffering.
  31683. // Playback further than one target duration from target can be considered DVR playback.
  31684. var liveMinLatencyDuration = Math.min(_this.maxLatency, targetLatency + levelDetails.targetduration);
  31685. var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
  31686. if (inLiveRange && distanceFromTarget > 0.05 && _this.forwardBufferLength > 1) {
  31687. var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
  31688. var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - _this.edgeStalled)) * 20) / 20;
  31689. var playbackRate = Math.min(max, Math.max(1, rate));
  31690. _this.changeMediaPlaybackRate(media, playbackRate);
  31691. } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
  31692. _this.changeMediaPlaybackRate(media, 1);
  31693. }
  31694. };
  31695. this.hls = hls;
  31696. this.config = hls.config;
  31697. this.registerListeners();
  31698. }
  31699. var _proto = LatencyController.prototype;
  31700. _proto.destroy = function destroy() {
  31701. this.unregisterListeners();
  31702. this.onMediaDetaching();
  31703. this.hls = null;
  31704. };
  31705. _proto.registerListeners = function registerListeners() {
  31706. var hls = this.hls;
  31707. if (!hls) {
  31708. return;
  31709. }
  31710. hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  31711. hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  31712. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31713. hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  31714. hls.on(Events.ERROR, this.onError, this);
  31715. };
  31716. _proto.unregisterListeners = function unregisterListeners() {
  31717. var hls = this.hls;
  31718. if (!hls) {
  31719. return;
  31720. }
  31721. hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);
  31722. hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);
  31723. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31724. hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);
  31725. hls.off(Events.ERROR, this.onError, this);
  31726. };
  31727. _proto.onMediaAttached = function onMediaAttached(event, data) {
  31728. this.media = data.media;
  31729. this.media.addEventListener('timeupdate', this.onTimeupdate);
  31730. };
  31731. _proto.onMediaDetaching = function onMediaDetaching() {
  31732. if (this.media) {
  31733. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  31734. this.media = null;
  31735. }
  31736. };
  31737. _proto.onManifestLoading = function onManifestLoading() {
  31738. this._latency = null;
  31739. this.stallCount = 0;
  31740. };
  31741. _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
  31742. var details = _ref.details;
  31743. if (details.advanced) {
  31744. this.onTimeupdate();
  31745. }
  31746. if (!details.live && this.media) {
  31747. this.media.removeEventListener('timeupdate', this.onTimeupdate);
  31748. }
  31749. };
  31750. _proto.onError = function onError(event, data) {
  31751. var _this$levelDetails;
  31752. if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {
  31753. return;
  31754. }
  31755. this.stallCount++;
  31756. if (this.hls && (_this$levelDetails = this.levelDetails) != null && _this$levelDetails.live) {
  31757. this.hls.logger.warn('[latency-controller]: Stall detected, adjusting target latency');
  31758. }
  31759. };
  31760. _proto.changeMediaPlaybackRate = function changeMediaPlaybackRate(media, playbackRate) {
  31761. var _this$hls, _this$targetLatency;
  31762. if (media.playbackRate === playbackRate) {
  31763. return;
  31764. }
  31765. (_this$hls = this.hls) == null ? void 0 : _this$hls.logger.debug("[latency-controller]: latency=" + this.latency.toFixed(3) + ", targetLatency=" + ((_this$targetLatency = this.targetLatency) == null ? void 0 : _this$targetLatency.toFixed(3)) + ", forwardBufferLength=" + this.forwardBufferLength.toFixed(3) + ": adjusting playback rate from " + media.playbackRate + " to " + playbackRate);
  31766. media.playbackRate = playbackRate;
  31767. };
  31768. _proto.estimateLiveEdge = function estimateLiveEdge() {
  31769. var levelDetails = this.levelDetails;
  31770. if (levelDetails === null) {
  31771. return null;
  31772. }
  31773. return levelDetails.edge + levelDetails.age;
  31774. };
  31775. _proto.computeLatency = function computeLatency() {
  31776. var liveEdge = this.estimateLiveEdge();
  31777. if (liveEdge === null) {
  31778. return null;
  31779. }
  31780. return liveEdge - this.currentTime;
  31781. };
  31782. return _createClass(LatencyController, [{
  31783. key: "levelDetails",
  31784. get: function get() {
  31785. var _this$hls2;
  31786. return ((_this$hls2 = this.hls) == null ? void 0 : _this$hls2.latestLevelDetails) || null;
  31787. }
  31788. }, {
  31789. key: "latency",
  31790. get: function get() {
  31791. return this._latency || 0;
  31792. }
  31793. }, {
  31794. key: "maxLatency",
  31795. get: function get() {
  31796. var config = this.config;
  31797. if (config.liveMaxLatencyDuration !== undefined) {
  31798. return config.liveMaxLatencyDuration;
  31799. }
  31800. var levelDetails = this.levelDetails;
  31801. return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
  31802. }
  31803. }, {
  31804. key: "targetLatency",
  31805. get: function get() {
  31806. var levelDetails = this.levelDetails;
  31807. if (levelDetails === null || this.hls === null) {
  31808. return null;
  31809. }
  31810. var holdBack = levelDetails.holdBack,
  31811. partHoldBack = levelDetails.partHoldBack,
  31812. targetduration = levelDetails.targetduration;
  31813. var _this$config2 = this.config,
  31814. liveSyncDuration = _this$config2.liveSyncDuration,
  31815. liveSyncDurationCount = _this$config2.liveSyncDurationCount,
  31816. lowLatencyMode = _this$config2.lowLatencyMode;
  31817. var userConfig = this.hls.userConfig;
  31818. var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
  31819. if (this._targetLatencyUpdated || userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
  31820. targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
  31821. }
  31822. var maxLiveSyncOnStallIncrease = targetduration;
  31823. return targetLatency + Math.min(this.stallCount * this.config.liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
  31824. },
  31825. set: function set(latency) {
  31826. this.stallCount = 0;
  31827. this.config.liveSyncDuration = latency;
  31828. this._targetLatencyUpdated = true;
  31829. }
  31830. }, {
  31831. key: "liveSyncPosition",
  31832. get: function get() {
  31833. var liveEdge = this.estimateLiveEdge();
  31834. var targetLatency = this.targetLatency;
  31835. if (liveEdge === null || targetLatency === null) {
  31836. return null;
  31837. }
  31838. var levelDetails = this.levelDetails;
  31839. if (levelDetails === null) {
  31840. return null;
  31841. }
  31842. var edge = levelDetails.edge;
  31843. var syncPosition = liveEdge - targetLatency - this.edgeStalled;
  31844. var min = edge - levelDetails.totalduration;
  31845. var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
  31846. return Math.min(Math.max(min, syncPosition), max);
  31847. }
  31848. }, {
  31849. key: "drift",
  31850. get: function get() {
  31851. var levelDetails = this.levelDetails;
  31852. if (levelDetails === null) {
  31853. return 1;
  31854. }
  31855. return levelDetails.drift;
  31856. }
  31857. }, {
  31858. key: "edgeStalled",
  31859. get: function get() {
  31860. var levelDetails = this.levelDetails;
  31861. if (levelDetails === null) {
  31862. return 0;
  31863. }
  31864. var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
  31865. return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
  31866. }
  31867. }, {
  31868. key: "forwardBufferLength",
  31869. get: function get() {
  31870. var media = this.media;
  31871. var levelDetails = this.levelDetails;
  31872. if (!media || !levelDetails) {
  31873. return 0;
  31874. }
  31875. var bufferedRanges = media.buffered.length;
  31876. return (bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge) - this.currentTime;
  31877. }
  31878. }]);
  31879. }();
  31880. var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
  31881. function LevelController(hls, contentSteeringController) {
  31882. var _this;
  31883. _this = _BasePlaylistControll.call(this, hls, 'level-controller') || this;
  31884. _this._levels = [];
  31885. _this._firstLevel = -1;
  31886. _this._maxAutoLevel = -1;
  31887. _this._startLevel = void 0;
  31888. _this.currentLevel = null;
  31889. _this.currentLevelIndex = -1;
  31890. _this.manualLevelIndex = -1;
  31891. _this.steering = void 0;
  31892. _this.onParsedComplete = void 0;
  31893. _this.steering = contentSteeringController;
  31894. _this._registerListeners();
  31895. return _this;
  31896. }
  31897. _inheritsLoose(LevelController, _BasePlaylistControll);
  31898. var _proto = LevelController.prototype;
  31899. _proto._registerListeners = function _registerListeners() {
  31900. var hls = this.hls;
  31901. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31902. hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  31903. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31904. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31905. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  31906. hls.on(Events.ERROR, this.onError, this);
  31907. };
  31908. _proto._unregisterListeners = function _unregisterListeners() {
  31909. var hls = this.hls;
  31910. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  31911. hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);
  31912. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  31913. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  31914. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  31915. hls.off(Events.ERROR, this.onError, this);
  31916. };
  31917. _proto.destroy = function destroy() {
  31918. this._unregisterListeners();
  31919. this.steering = null;
  31920. this.resetLevels();
  31921. _BasePlaylistControll.prototype.destroy.call(this);
  31922. };
  31923. _proto.stopLoad = function stopLoad() {
  31924. var levels = this._levels;
  31925. // clean up live level details to force reload them, and reset load errors
  31926. levels.forEach(function (level) {
  31927. level.loadError = 0;
  31928. level.fragmentError = 0;
  31929. });
  31930. _BasePlaylistControll.prototype.stopLoad.call(this);
  31931. };
  31932. _proto.resetLevels = function resetLevels() {
  31933. this._startLevel = undefined;
  31934. this.manualLevelIndex = -1;
  31935. this.currentLevelIndex = -1;
  31936. this.currentLevel = null;
  31937. this._levels = [];
  31938. this._maxAutoLevel = -1;
  31939. };
  31940. _proto.onManifestLoading = function onManifestLoading(event, data) {
  31941. this.resetLevels();
  31942. };
  31943. _proto.onManifestLoaded = function onManifestLoaded(event, data) {
  31944. var _this2 = this;
  31945. var preferManagedMediaSource = this.hls.config.preferManagedMediaSource;
  31946. var levels = [];
  31947. var redundantSet = {};
  31948. var generatePathwaySet = {};
  31949. var resolutionFound = false;
  31950. var videoCodecFound = false;
  31951. var audioCodecFound = false;
  31952. data.levels.forEach(function (levelParsed) {
  31953. var attributes = levelParsed.attrs;
  31954. var audioCodec = levelParsed.audioCodec,
  31955. videoCodec = levelParsed.videoCodec;
  31956. if (audioCodec) {
  31957. // Returns empty and set to undefined for 'mp4a.40.34' with fallback to 'audio/mpeg' SourceBuffer
  31958. levelParsed.audioCodec = audioCodec = getCodecCompatibleName(audioCodec, preferManagedMediaSource) || undefined;
  31959. }
  31960. if (videoCodec) {
  31961. videoCodec = levelParsed.videoCodec = convertAVC1ToAVCOTI(videoCodec);
  31962. }
  31963. // only keep levels with supported audio/video codecs
  31964. var width = levelParsed.width,
  31965. height = levelParsed.height,
  31966. unknownCodecs = levelParsed.unknownCodecs;
  31967. var unknownUnsupportedCodecCount = unknownCodecs ? unknownCodecs.length : 0;
  31968. if (unknownCodecs) {
  31969. // Treat unknown codec as audio or video codec based on passing `isTypeSupported` check
  31970. // (allows for playback of any supported codec even if not indexed in utils/codecs)
  31971. for (var i = unknownUnsupportedCodecCount; i--;) {
  31972. var unknownCodec = unknownCodecs[i];
  31973. if (_this2.isAudioSupported(unknownCodec)) {
  31974. levelParsed.audioCodec = audioCodec = audioCodec ? audioCodec + "," + unknownCodec : unknownCodec;
  31975. unknownUnsupportedCodecCount--;
  31976. sampleEntryCodesISO.audio[audioCodec.substring(0, 4)] = 2;
  31977. } else if (_this2.isVideoSupported(unknownCodec)) {
  31978. levelParsed.videoCodec = videoCodec = videoCodec ? videoCodec + "," + unknownCodec : unknownCodec;
  31979. unknownUnsupportedCodecCount--;
  31980. sampleEntryCodesISO.video[videoCodec.substring(0, 4)] = 2;
  31981. }
  31982. }
  31983. }
  31984. resolutionFound || (resolutionFound = !!(width && height));
  31985. videoCodecFound || (videoCodecFound = !!videoCodec);
  31986. audioCodecFound || (audioCodecFound = !!audioCodec);
  31987. if (unknownUnsupportedCodecCount || audioCodec && !_this2.isAudioSupported(audioCodec) || videoCodec && !_this2.isVideoSupported(videoCodec)) {
  31988. _this2.log("Some or all CODECS not supported \"" + attributes.CODECS + "\"");
  31989. return;
  31990. }
  31991. var CODECS = attributes.CODECS,
  31992. FRAMERATE = attributes['FRAME-RATE'],
  31993. HDCP = attributes['HDCP-LEVEL'],
  31994. PATHWAY = attributes['PATHWAY-ID'],
  31995. RESOLUTION = attributes.RESOLUTION,
  31996. VIDEO_RANGE = attributes['VIDEO-RANGE'];
  31997. var contentSteeringPrefix = (PATHWAY || '.') + "-";
  31998. var levelKey = "" + contentSteeringPrefix + levelParsed.bitrate + "-" + RESOLUTION + "-" + FRAMERATE + "-" + CODECS + "-" + VIDEO_RANGE + "-" + HDCP;
  31999. if (!redundantSet[levelKey]) {
  32000. var level = _this2.createLevel(levelParsed);
  32001. redundantSet[levelKey] = level;
  32002. generatePathwaySet[levelKey] = 1;
  32003. levels.push(level);
  32004. } else if (redundantSet[levelKey].uri !== levelParsed.url && !levelParsed.attrs['PATHWAY-ID']) {
  32005. // Assign Pathway IDs to Redundant Streams (default Pathways is ".". Redundant Streams "..", "...", and so on.)
  32006. // Content Steering controller to handles Pathway fallback on error
  32007. var pathwayCount = generatePathwaySet[levelKey] += 1;
  32008. levelParsed.attrs['PATHWAY-ID'] = new Array(pathwayCount + 1).join('.');
  32009. var _level = _this2.createLevel(levelParsed);
  32010. redundantSet[levelKey] = _level;
  32011. levels.push(_level);
  32012. } else {
  32013. redundantSet[levelKey].addGroupId('audio', attributes.AUDIO);
  32014. redundantSet[levelKey].addGroupId('text', attributes.SUBTITLES);
  32015. }
  32016. });
  32017. this.filterAndSortMediaOptions(levels, data, resolutionFound, videoCodecFound, audioCodecFound);
  32018. };
  32019. _proto.createLevel = function createLevel(levelParsed) {
  32020. var level = new Level(levelParsed);
  32021. var supplemental = levelParsed.supplemental;
  32022. if (supplemental != null && supplemental.videoCodec && !this.isVideoSupported(supplemental.videoCodec)) {
  32023. var error = new Error("SUPPLEMENTAL-CODECS not supported \"" + supplemental.videoCodec + "\"");
  32024. this.log(error.message);
  32025. level.supportedResult = getUnsupportedResult(error, []);
  32026. }
  32027. return level;
  32028. };
  32029. _proto.isAudioSupported = function isAudioSupported(codec) {
  32030. return areCodecsMediaSourceSupported(codec, 'audio', this.hls.config.preferManagedMediaSource);
  32031. };
  32032. _proto.isVideoSupported = function isVideoSupported(codec) {
  32033. return areCodecsMediaSourceSupported(codec, 'video', this.hls.config.preferManagedMediaSource);
  32034. };
  32035. _proto.filterAndSortMediaOptions = function filterAndSortMediaOptions(filteredLevels, data, resolutionFound, videoCodecFound, audioCodecFound) {
  32036. var _this3 = this;
  32037. var audioTracks = [];
  32038. var subtitleTracks = [];
  32039. var levels = filteredLevels;
  32040. // remove audio-only and invalid video-range levels if we also have levels with video codecs or RESOLUTION signalled
  32041. if ((resolutionFound || videoCodecFound) && audioCodecFound) {
  32042. levels = levels.filter(function (_ref) {
  32043. var videoCodec = _ref.videoCodec,
  32044. videoRange = _ref.videoRange,
  32045. width = _ref.width,
  32046. height = _ref.height;
  32047. return (!!videoCodec || !!(width && height)) && isVideoRange(videoRange);
  32048. });
  32049. }
  32050. if (levels.length === 0) {
  32051. // Dispatch error after MANIFEST_LOADED is done propagating
  32052. Promise.resolve().then(function () {
  32053. if (_this3.hls) {
  32054. var message = 'no level with compatible codecs found in manifest';
  32055. var reason = message;
  32056. if (data.levels.length) {
  32057. reason = "one or more CODECS in variant not supported: " + stringify(data.levels.map(function (level) {
  32058. return level.attrs.CODECS;
  32059. }).filter(function (value, index, array) {
  32060. return array.indexOf(value) === index;
  32061. }));
  32062. _this3.warn(reason);
  32063. message += " (" + reason + ")";
  32064. }
  32065. var error = new Error(message);
  32066. _this3.hls.trigger(Events.ERROR, {
  32067. type: ErrorTypes.MEDIA_ERROR,
  32068. details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  32069. fatal: true,
  32070. url: data.url,
  32071. error: error,
  32072. reason: reason
  32073. });
  32074. }
  32075. });
  32076. return;
  32077. }
  32078. if (data.audioTracks) {
  32079. audioTracks = data.audioTracks.filter(function (track) {
  32080. return !track.audioCodec || _this3.isAudioSupported(track.audioCodec);
  32081. });
  32082. // Assign ids after filtering as array indices by group-id
  32083. assignTrackIdsByGroup(audioTracks);
  32084. }
  32085. if (data.subtitles) {
  32086. subtitleTracks = data.subtitles;
  32087. assignTrackIdsByGroup(subtitleTracks);
  32088. }
  32089. // start bitrate is the first bitrate of the manifest
  32090. var unsortedLevels = levels.slice(0);
  32091. // sort levels from lowest to highest
  32092. levels.sort(function (a, b) {
  32093. if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {
  32094. return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '') ? 1 : -1;
  32095. }
  32096. // sort on height before bitrate for cap-level-controller
  32097. if (resolutionFound && a.height !== b.height) {
  32098. return a.height - b.height;
  32099. }
  32100. if (a.frameRate !== b.frameRate) {
  32101. return a.frameRate - b.frameRate;
  32102. }
  32103. if (a.videoRange !== b.videoRange) {
  32104. return VideoRangeValues.indexOf(a.videoRange) - VideoRangeValues.indexOf(b.videoRange);
  32105. }
  32106. if (a.videoCodec !== b.videoCodec) {
  32107. var valueA = videoCodecPreferenceValue(a.videoCodec);
  32108. var valueB = videoCodecPreferenceValue(b.videoCodec);
  32109. if (valueA !== valueB) {
  32110. return valueB - valueA;
  32111. }
  32112. }
  32113. if (a.uri === b.uri && a.codecSet !== b.codecSet) {
  32114. var _valueA = codecsSetSelectionPreferenceValue(a.codecSet);
  32115. var _valueB = codecsSetSelectionPreferenceValue(b.codecSet);
  32116. if (_valueA !== _valueB) {
  32117. return _valueB - _valueA;
  32118. }
  32119. }
  32120. if (a.averageBitrate !== b.averageBitrate) {
  32121. return a.averageBitrate - b.averageBitrate;
  32122. }
  32123. return 0;
  32124. });
  32125. var firstLevelInPlaylist = unsortedLevels[0];
  32126. if (this.steering) {
  32127. levels = this.steering.filterParsedLevels(levels);
  32128. if (levels.length !== unsortedLevels.length) {
  32129. for (var i = 0; i < unsortedLevels.length; i++) {
  32130. if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {
  32131. firstLevelInPlaylist = unsortedLevels[i];
  32132. break;
  32133. }
  32134. }
  32135. }
  32136. }
  32137. this._levels = levels;
  32138. // find index of first level in sorted levels
  32139. for (var _i = 0; _i < levels.length; _i++) {
  32140. if (levels[_i] === firstLevelInPlaylist) {
  32141. var _this$hls$userConfig;
  32142. this._firstLevel = _i;
  32143. var firstLevelBitrate = firstLevelInPlaylist.bitrate;
  32144. var bandwidthEstimate = this.hls.bandwidthEstimate;
  32145. this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + firstLevelBitrate);
  32146. // Update default bwe to first variant bitrate as long it has not been configured or set
  32147. if (((_this$hls$userConfig = this.hls.userConfig) == null ? void 0 : _this$hls$userConfig.abrEwmaDefaultEstimate) === undefined) {
  32148. var startingBwEstimate = Math.min(firstLevelBitrate, this.hls.config.abrEwmaDefaultEstimateMax);
  32149. if (startingBwEstimate > bandwidthEstimate && bandwidthEstimate === this.hls.abrEwmaDefaultEstimate) {
  32150. this.hls.bandwidthEstimate = startingBwEstimate;
  32151. }
  32152. }
  32153. break;
  32154. }
  32155. }
  32156. // Audio is only alternate if manifest include a URI along with the audio group tag,
  32157. // and this is not an audio-only stream where levels contain audio-only
  32158. var audioOnly = audioCodecFound && !videoCodecFound;
  32159. var config = this.hls.config;
  32160. var altAudioEnabled = !!(config.audioStreamController && config.audioTrackController);
  32161. var edata = {
  32162. levels: levels,
  32163. audioTracks: audioTracks,
  32164. subtitleTracks: subtitleTracks,
  32165. sessionData: data.sessionData,
  32166. sessionKeys: data.sessionKeys,
  32167. firstLevel: this._firstLevel,
  32168. stats: data.stats,
  32169. audio: audioCodecFound,
  32170. video: videoCodecFound,
  32171. altAudio: altAudioEnabled && !audioOnly && audioTracks.some(function (t) {
  32172. return !!t.url;
  32173. })
  32174. };
  32175. this.hls.trigger(Events.MANIFEST_PARSED, edata);
  32176. };
  32177. _proto.onError = function onError(event, data) {
  32178. if (data.fatal || !data.context) {
  32179. return;
  32180. }
  32181. if (data.context.type === PlaylistContextType.LEVEL && data.context.level === this.level) {
  32182. this.checkRetry(data);
  32183. }
  32184. }
  32185. // reset errors on the successful load of a fragment
  32186. ;
  32187. _proto.onFragBuffered = function onFragBuffered(event, _ref2) {
  32188. var frag = _ref2.frag;
  32189. if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {
  32190. var el = frag.elementaryStreams;
  32191. if (!Object.keys(el).some(function (type) {
  32192. return !!el[type];
  32193. })) {
  32194. return;
  32195. }
  32196. var level = this._levels[frag.level];
  32197. if (level != null && level.loadError) {
  32198. this.log("Resetting level error count of " + level.loadError + " on frag buffered");
  32199. level.loadError = 0;
  32200. }
  32201. }
  32202. };
  32203. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  32204. var _data$deliveryDirecti2;
  32205. var level = data.level,
  32206. details = data.details;
  32207. var curLevel = data.levelInfo;
  32208. if (!curLevel) {
  32209. var _data$deliveryDirecti;
  32210. this.warn("Invalid level index " + level);
  32211. if ((_data$deliveryDirecti = data.deliveryDirectives) != null && _data$deliveryDirecti.skip) {
  32212. details.deltaUpdateFailed = true;
  32213. }
  32214. return;
  32215. }
  32216. // only process level loaded events matching with expected level or prior to switch when media playlist is loaded directly
  32217. if (curLevel === this.currentLevel || data.withoutMultiVariant) {
  32218. // reset level load error counter on successful level loaded only if there is no issues with fragments
  32219. if (curLevel.fragmentError === 0) {
  32220. curLevel.loadError = 0;
  32221. }
  32222. // Ignore matching details populated by loading a Media Playlist directly
  32223. var previousDetails = curLevel.details;
  32224. if (previousDetails === data.details && previousDetails.advanced) {
  32225. previousDetails = undefined;
  32226. }
  32227. this.playlistLoaded(level, data, previousDetails);
  32228. } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) != null && _data$deliveryDirecti2.skip) {
  32229. // received a delta playlist update that cannot be merged
  32230. details.deltaUpdateFailed = true;
  32231. }
  32232. };
  32233. _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
  32234. _BasePlaylistControll.prototype.loadPlaylist.call(this);
  32235. if (this.shouldLoadPlaylist(this.currentLevel)) {
  32236. this.scheduleLoading(this.currentLevel, hlsUrlParameters);
  32237. }
  32238. };
  32239. _proto.loadingPlaylist = function loadingPlaylist(currentLevel, hlsUrlParameters) {
  32240. _BasePlaylistControll.prototype.loadingPlaylist.call(this, currentLevel, hlsUrlParameters);
  32241. var url = this.getUrlWithDirectives(currentLevel.uri, hlsUrlParameters);
  32242. var currentLevelIndex = this.currentLevelIndex;
  32243. var pathwayId = currentLevel.attrs['PATHWAY-ID'];
  32244. var details = currentLevel.details;
  32245. var age = details == null ? void 0 : details.age;
  32246. this.log("Loading level index " + currentLevelIndex + ((hlsUrlParameters == null ? void 0 : hlsUrlParameters.msn) !== undefined ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + (pathwayId ? ' Pathway ' + pathwayId : '') + (age && details.live ? ' age ' + age.toFixed(1) + (details.type ? ' ' + details.type || '' : '') : '') + " " + url);
  32247. this.hls.trigger(Events.LEVEL_LOADING, {
  32248. url: url,
  32249. level: currentLevelIndex,
  32250. levelInfo: currentLevel,
  32251. pathwayId: currentLevel.attrs['PATHWAY-ID'],
  32252. id: 0,
  32253. // Deprecated Level urlId
  32254. deliveryDirectives: hlsUrlParameters || null
  32255. });
  32256. };
  32257. _proto.removeLevel = function removeLevel(levelIndex) {
  32258. var _this4 = this,
  32259. _this$currentLevel;
  32260. if (this._levels.length === 1) {
  32261. return;
  32262. }
  32263. var levels = this._levels.filter(function (level, index) {
  32264. if (index !== levelIndex) {
  32265. return true;
  32266. }
  32267. if (_this4.steering) {
  32268. _this4.steering.removeLevel(level);
  32269. }
  32270. if (level === _this4.currentLevel) {
  32271. _this4.currentLevel = null;
  32272. _this4.currentLevelIndex = -1;
  32273. if (level.details) {
  32274. level.details.fragments.forEach(function (f) {
  32275. return f.level = -1;
  32276. });
  32277. }
  32278. }
  32279. return false;
  32280. });
  32281. reassignFragmentLevelIndexes(levels);
  32282. this._levels = levels;
  32283. if (this.currentLevelIndex > -1 && (_this$currentLevel = this.currentLevel) != null && _this$currentLevel.details) {
  32284. this.currentLevelIndex = this.currentLevel.details.fragments[0].level;
  32285. }
  32286. if (this.manualLevelIndex > -1) {
  32287. this.manualLevelIndex = this.currentLevelIndex;
  32288. }
  32289. var maxLevel = levels.length - 1;
  32290. this._firstLevel = Math.min(this._firstLevel, maxLevel);
  32291. if (this._startLevel) {
  32292. this._startLevel = Math.min(this._startLevel, maxLevel);
  32293. }
  32294. this.hls.trigger(Events.LEVELS_UPDATED, {
  32295. levels: levels
  32296. });
  32297. };
  32298. _proto.onLevelsUpdated = function onLevelsUpdated(event, _ref3) {
  32299. var levels = _ref3.levels;
  32300. this._levels = levels;
  32301. };
  32302. _proto.checkMaxAutoUpdated = function checkMaxAutoUpdated() {
  32303. var _this$hls = this.hls,
  32304. autoLevelCapping = _this$hls.autoLevelCapping,
  32305. maxAutoLevel = _this$hls.maxAutoLevel,
  32306. maxHdcpLevel = _this$hls.maxHdcpLevel;
  32307. if (this._maxAutoLevel !== maxAutoLevel) {
  32308. this._maxAutoLevel = maxAutoLevel;
  32309. this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED, {
  32310. autoLevelCapping: autoLevelCapping,
  32311. levels: this.levels,
  32312. maxAutoLevel: maxAutoLevel,
  32313. minAutoLevel: this.hls.minAutoLevel,
  32314. maxHdcpLevel: maxHdcpLevel
  32315. });
  32316. }
  32317. };
  32318. return _createClass(LevelController, [{
  32319. key: "levels",
  32320. get: function get() {
  32321. if (this._levels.length === 0) {
  32322. return null;
  32323. }
  32324. return this._levels;
  32325. }
  32326. }, {
  32327. key: "loadLevelObj",
  32328. get: function get() {
  32329. return this.currentLevel;
  32330. }
  32331. }, {
  32332. key: "level",
  32333. get: function get() {
  32334. return this.currentLevelIndex;
  32335. },
  32336. set: function set(newLevel) {
  32337. var levels = this._levels;
  32338. if (levels.length === 0) {
  32339. return;
  32340. }
  32341. // check if level idx is valid
  32342. if (newLevel < 0 || newLevel >= levels.length) {
  32343. // invalid level id given, trigger error
  32344. var error = new Error('invalid level idx');
  32345. var fatal = newLevel < 0;
  32346. this.hls.trigger(Events.ERROR, {
  32347. type: ErrorTypes.OTHER_ERROR,
  32348. details: ErrorDetails.LEVEL_SWITCH_ERROR,
  32349. level: newLevel,
  32350. fatal: fatal,
  32351. error: error,
  32352. reason: error.message
  32353. });
  32354. if (fatal) {
  32355. return;
  32356. }
  32357. newLevel = Math.min(newLevel, levels.length - 1);
  32358. }
  32359. var lastLevelIndex = this.currentLevelIndex;
  32360. var lastLevel = this.currentLevel;
  32361. var lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;
  32362. var level = levels[newLevel];
  32363. var pathwayId = level.attrs['PATHWAY-ID'];
  32364. this.currentLevelIndex = newLevel;
  32365. this.currentLevel = level;
  32366. if (lastLevelIndex === newLevel && lastLevel && lastPathwayId === pathwayId) {
  32367. return;
  32368. }
  32369. this.log("Switching to level " + newLevel + " (" + (level.height ? level.height + 'p ' : '') + (level.videoRange ? level.videoRange + ' ' : '') + (level.codecSet ? level.codecSet + ' ' : '') + "@" + level.bitrate + ")" + (pathwayId ? ' with Pathway ' + pathwayId : '') + " from level " + lastLevelIndex + (lastPathwayId ? ' with Pathway ' + lastPathwayId : ''));
  32370. var levelSwitchingData = {
  32371. level: newLevel,
  32372. attrs: level.attrs,
  32373. details: level.details,
  32374. bitrate: level.bitrate,
  32375. averageBitrate: level.averageBitrate,
  32376. maxBitrate: level.maxBitrate,
  32377. realBitrate: level.realBitrate,
  32378. width: level.width,
  32379. height: level.height,
  32380. codecSet: level.codecSet,
  32381. audioCodec: level.audioCodec,
  32382. videoCodec: level.videoCodec,
  32383. audioGroups: level.audioGroups,
  32384. subtitleGroups: level.subtitleGroups,
  32385. loaded: level.loaded,
  32386. loadError: level.loadError,
  32387. fragmentError: level.fragmentError,
  32388. name: level.name,
  32389. id: level.id,
  32390. uri: level.uri,
  32391. url: level.url,
  32392. urlId: 0,
  32393. audioGroupIds: level.audioGroupIds,
  32394. textGroupIds: level.textGroupIds
  32395. };
  32396. this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);
  32397. // check if we need to load playlist for this level
  32398. var levelDetails = level.details;
  32399. if (!levelDetails || levelDetails.live) {
  32400. // level not retrieved yet, or live playlist we need to (re)load it
  32401. var hlsUrlParameters = this.switchParams(level.uri, lastLevel == null ? void 0 : lastLevel.details, levelDetails);
  32402. this.loadPlaylist(hlsUrlParameters);
  32403. }
  32404. }
  32405. }, {
  32406. key: "manualLevel",
  32407. get: function get() {
  32408. return this.manualLevelIndex;
  32409. },
  32410. set: function set(newLevel) {
  32411. this.manualLevelIndex = newLevel;
  32412. if (this._startLevel === undefined) {
  32413. this._startLevel = newLevel;
  32414. }
  32415. if (newLevel !== -1) {
  32416. this.level = newLevel;
  32417. }
  32418. }
  32419. }, {
  32420. key: "firstLevel",
  32421. get: function get() {
  32422. return this._firstLevel;
  32423. },
  32424. set: function set(newLevel) {
  32425. this._firstLevel = newLevel;
  32426. }
  32427. }, {
  32428. key: "startLevel",
  32429. get: function get() {
  32430. // Setting hls.startLevel (this._startLevel) overrides config.startLevel
  32431. if (this._startLevel === undefined) {
  32432. var configStartLevel = this.hls.config.startLevel;
  32433. if (configStartLevel !== undefined) {
  32434. return configStartLevel;
  32435. }
  32436. return this.hls.firstAutoLevel;
  32437. }
  32438. return this._startLevel;
  32439. },
  32440. set: function set(newLevel) {
  32441. this._startLevel = newLevel;
  32442. }
  32443. }, {
  32444. key: "pathways",
  32445. get: function get() {
  32446. if (this.steering) {
  32447. return this.steering.pathways();
  32448. }
  32449. return [];
  32450. }
  32451. }, {
  32452. key: "pathwayPriority",
  32453. get: function get() {
  32454. if (this.steering) {
  32455. return this.steering.pathwayPriority;
  32456. }
  32457. return null;
  32458. },
  32459. set: function set(pathwayPriority) {
  32460. if (this.steering) {
  32461. var pathwaysList = this.steering.pathways();
  32462. var filteredPathwayPriority = pathwayPriority.filter(function (pathwayId) {
  32463. return pathwaysList.indexOf(pathwayId) !== -1;
  32464. });
  32465. if (pathwayPriority.length < 1) {
  32466. this.warn("pathwayPriority " + pathwayPriority + " should contain at least one pathway from list: " + pathwaysList);
  32467. return;
  32468. }
  32469. this.steering.pathwayPriority = filteredPathwayPriority;
  32470. }
  32471. }
  32472. }, {
  32473. key: "nextLoadLevel",
  32474. get: function get() {
  32475. if (this.manualLevelIndex !== -1) {
  32476. return this.manualLevelIndex;
  32477. } else {
  32478. return this.hls.nextAutoLevel;
  32479. }
  32480. },
  32481. set: function set(nextLevel) {
  32482. this.level = nextLevel;
  32483. if (this.manualLevelIndex === -1) {
  32484. this.hls.nextAutoLevel = nextLevel;
  32485. }
  32486. }
  32487. }]);
  32488. }(BasePlaylistController);
  32489. function assignTrackIdsByGroup(tracks) {
  32490. var groups = {};
  32491. tracks.forEach(function (track) {
  32492. var groupId = track.groupId || '';
  32493. track.id = groups[groupId] = groups[groupId] || 0;
  32494. groups[groupId]++;
  32495. });
  32496. }
  32497. function getSourceBuffer() {
  32498. return self.SourceBuffer || self.WebKitSourceBuffer;
  32499. }
  32500. function isMSESupported() {
  32501. var mediaSource = getMediaSource();
  32502. if (!mediaSource) {
  32503. return false;
  32504. }
  32505. // if SourceBuffer is exposed ensure its API is valid
  32506. // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  32507. var sourceBuffer = getSourceBuffer();
  32508. return !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
  32509. }
  32510. function isSupported() {
  32511. if (!isMSESupported()) {
  32512. return false;
  32513. }
  32514. var mediaSource = getMediaSource();
  32515. return typeof (mediaSource == null ? void 0 : mediaSource.isTypeSupported) === 'function' && (['avc1.42E01E,mp4a.40.2', 'av01.0.01M.08', 'vp09.00.50.08'].some(function (codecsForVideoContainer) {
  32516. return mediaSource.isTypeSupported(mimeTypeForCodec(codecsForVideoContainer, 'video'));
  32517. }) || ['mp4a.40.2', 'fLaC'].some(function (codecForAudioContainer) {
  32518. return mediaSource.isTypeSupported(mimeTypeForCodec(codecForAudioContainer, 'audio'));
  32519. }));
  32520. }
  32521. function changeTypeSupported() {
  32522. var _sourceBuffer$prototy;
  32523. var sourceBuffer = getSourceBuffer();
  32524. return typeof (sourceBuffer == null ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) == null ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
  32525. }
  32526. var TICK_INTERVAL = 100; // how often to tick in ms
  32527. var StreamController = /*#__PURE__*/function (_BaseStreamController) {
  32528. function StreamController(hls, fragmentTracker, keyLoader) {
  32529. var _this;
  32530. _this = _BaseStreamController.call(this, hls, fragmentTracker, keyLoader, 'stream-controller', PlaylistLevelType.MAIN) || this;
  32531. _this.audioCodecSwap = false;
  32532. _this.level = -1;
  32533. _this._forceStartLoad = false;
  32534. _this._hasEnoughToStart = false;
  32535. _this.altAudio = 0;
  32536. _this.audioOnly = false;
  32537. _this.fragPlaying = null;
  32538. _this.fragLastKbps = 0;
  32539. _this.couldBacktrack = false;
  32540. _this.backtrackFragment = null;
  32541. _this.audioCodecSwitch = false;
  32542. _this.videoBuffer = null;
  32543. _this.onMediaPlaying = function () {
  32544. // tick to speed up FRAG_CHANGED triggering
  32545. _this.tick();
  32546. };
  32547. _this.onMediaSeeked = function () {
  32548. var media = _this.media;
  32549. var currentTime = media ? media.currentTime : null;
  32550. if (currentTime === null || !isFiniteNumber(currentTime)) {
  32551. return;
  32552. }
  32553. _this.log("Media seeked to " + currentTime.toFixed(3));
  32554. // If seeked was issued before buffer was appended do not tick immediately
  32555. if (!_this.getBufferedFrag(currentTime)) {
  32556. return;
  32557. }
  32558. var bufferInfo = _this.getFwdBufferInfoAtPos(media, currentTime, PlaylistLevelType.MAIN, 0);
  32559. if (bufferInfo === null || bufferInfo.len === 0) {
  32560. _this.warn("Main forward buffer length at " + currentTime + " on \"seeked\" event " + (bufferInfo ? bufferInfo.len : 'empty') + ")");
  32561. return;
  32562. }
  32563. // tick to speed up FRAG_CHANGED triggering
  32564. _this.tick();
  32565. };
  32566. _this.registerListeners();
  32567. return _this;
  32568. }
  32569. _inheritsLoose(StreamController, _BaseStreamController);
  32570. var _proto = StreamController.prototype;
  32571. _proto.registerListeners = function registerListeners() {
  32572. _BaseStreamController.prototype.registerListeners.call(this);
  32573. var hls = this.hls;
  32574. hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  32575. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  32576. hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  32577. hls.on(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  32578. hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  32579. hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  32580. hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);
  32581. hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  32582. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  32583. hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  32584. };
  32585. _proto.unregisterListeners = function unregisterListeners() {
  32586. _BaseStreamController.prototype.unregisterListeners.call(this);
  32587. var hls = this.hls;
  32588. hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);
  32589. hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);
  32590. hls.off(Events.FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
  32591. hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
  32592. hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
  32593. hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);
  32594. hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);
  32595. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  32596. hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);
  32597. };
  32598. _proto.onHandlerDestroying = function onHandlerDestroying() {
  32599. // @ts-ignore
  32600. this.onMediaPlaying = this.onMediaSeeked = null;
  32601. this.unregisterListeners();
  32602. _BaseStreamController.prototype.onHandlerDestroying.call(this);
  32603. };
  32604. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  32605. if (this.levels) {
  32606. var lastCurrentTime = this.lastCurrentTime,
  32607. hls = this.hls;
  32608. this.stopLoad();
  32609. this.setInterval(TICK_INTERVAL);
  32610. this.level = -1;
  32611. if (!this.startFragRequested) {
  32612. // determine load level
  32613. var startLevel = hls.startLevel;
  32614. if (startLevel === -1) {
  32615. if (hls.config.testBandwidth && this.levels.length > 1) {
  32616. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  32617. startLevel = 0;
  32618. this.bitrateTest = true;
  32619. } else {
  32620. startLevel = hls.firstAutoLevel;
  32621. }
  32622. }
  32623. // set new level to playlist loader : this will trigger start level load
  32624. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  32625. hls.nextLoadLevel = startLevel;
  32626. this.level = hls.loadLevel;
  32627. this._hasEnoughToStart = !!skipSeekToStartPosition;
  32628. }
  32629. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  32630. if (lastCurrentTime > 0 && startPosition === -1 && !skipSeekToStartPosition) {
  32631. this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  32632. startPosition = lastCurrentTime;
  32633. }
  32634. this.state = State.IDLE;
  32635. this.nextLoadPosition = this.lastCurrentTime = startPosition + this.timelineOffset;
  32636. this.startPosition = skipSeekToStartPosition ? -1 : startPosition;
  32637. this.tick();
  32638. } else {
  32639. this._forceStartLoad = true;
  32640. this.state = State.STOPPED;
  32641. }
  32642. };
  32643. _proto.stopLoad = function stopLoad() {
  32644. this._forceStartLoad = false;
  32645. _BaseStreamController.prototype.stopLoad.call(this);
  32646. };
  32647. _proto.doTick = function doTick() {
  32648. switch (this.state) {
  32649. case State.WAITING_LEVEL:
  32650. {
  32651. var levels = this.levels,
  32652. level = this.level;
  32653. var currentLevel = levels == null ? void 0 : levels[level];
  32654. var details = currentLevel == null ? void 0 : currentLevel.details;
  32655. if (details && (!details.live || this.levelLastLoaded === currentLevel && !this.waitForLive(currentLevel))) {
  32656. if (this.waitForCdnTuneIn(details)) {
  32657. break;
  32658. }
  32659. this.state = State.IDLE;
  32660. break;
  32661. } else if (this.hls.nextLoadLevel !== this.level) {
  32662. this.state = State.IDLE;
  32663. break;
  32664. }
  32665. break;
  32666. }
  32667. case State.FRAG_LOADING_WAITING_RETRY:
  32668. {
  32669. var _this$media;
  32670. var now = self.performance.now();
  32671. var retryDate = this.retryDate;
  32672. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  32673. if (!retryDate || now >= retryDate || (_this$media = this.media) != null && _this$media.seeking) {
  32674. var _levels = this.levels,
  32675. _level = this.level;
  32676. var _currentLevel = _levels == null ? void 0 : _levels[_level];
  32677. this.resetStartWhenNotLoaded(_currentLevel || null);
  32678. this.state = State.IDLE;
  32679. }
  32680. }
  32681. break;
  32682. }
  32683. if (this.state === State.IDLE) {
  32684. this.doTickIdle();
  32685. }
  32686. this.onTickEnd();
  32687. };
  32688. _proto.onTickEnd = function onTickEnd() {
  32689. var _this$media2;
  32690. _BaseStreamController.prototype.onTickEnd.call(this);
  32691. if ((_this$media2 = this.media) != null && _this$media2.readyState && this.media.seeking === false) {
  32692. this.lastCurrentTime = this.media.currentTime;
  32693. }
  32694. this.checkFragmentChanged();
  32695. };
  32696. _proto.doTickIdle = function doTickIdle() {
  32697. var hls = this.hls,
  32698. levelLastLoaded = this.levelLastLoaded,
  32699. levels = this.levels,
  32700. media = this.media;
  32701. // if start level not parsed yet OR
  32702. // if video not attached AND start fragment already requested OR start frag prefetch not enabled
  32703. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  32704. if (levelLastLoaded === null || !media && !this.primaryPrefetch && (this.startFragRequested || !hls.config.startFragPrefetch)) {
  32705. return;
  32706. }
  32707. // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
  32708. if (this.altAudio && this.audioOnly) {
  32709. return;
  32710. }
  32711. var level = this.buffering ? hls.nextLoadLevel : hls.loadLevel;
  32712. if (!(levels != null && levels[level])) {
  32713. return;
  32714. }
  32715. var levelInfo = levels[level];
  32716. // if buffer length is less than maxBufLen try to load a new fragment
  32717. var bufferInfo = this.getMainFwdBufferInfo();
  32718. if (bufferInfo === null) {
  32719. return;
  32720. }
  32721. var lastDetails = this.getLevelDetails();
  32722. if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {
  32723. var data = {};
  32724. if (this.altAudio === 2) {
  32725. data.type = 'video';
  32726. }
  32727. this.hls.trigger(Events.BUFFER_EOS, data);
  32728. this.state = State.ENDED;
  32729. return;
  32730. }
  32731. if (!this.buffering) {
  32732. return;
  32733. }
  32734. // set next load level : this will trigger a playlist load if needed
  32735. if (hls.loadLevel !== level && hls.manualLevel === -1) {
  32736. this.log("Adapting to level " + level + " from level " + this.level);
  32737. }
  32738. this.level = hls.nextLoadLevel = level;
  32739. var levelDetails = levelInfo.details;
  32740. // if level info not retrieved yet, switch state and wait for level retrieval
  32741. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  32742. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  32743. if (!levelDetails || this.state === State.WAITING_LEVEL || this.waitForLive(levelInfo)) {
  32744. this.level = level;
  32745. this.state = State.WAITING_LEVEL;
  32746. this.startFragRequested = false;
  32747. return;
  32748. }
  32749. var bufferLen = bufferInfo.len;
  32750. // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
  32751. var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);
  32752. // Stay idle if we are still with buffer margins
  32753. if (bufferLen >= maxBufLen) {
  32754. return;
  32755. }
  32756. if (this.backtrackFragment && this.backtrackFragment.start > bufferInfo.end) {
  32757. this.backtrackFragment = null;
  32758. }
  32759. var targetBufferTime = this.backtrackFragment ? this.backtrackFragment.start : bufferInfo.end;
  32760. var frag = this.getNextFragment(targetBufferTime, levelDetails);
  32761. // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)
  32762. if (this.couldBacktrack && !this.fragPrevious && frag && isMediaFragment(frag) && this.fragmentTracker.getState(frag) !== FragmentState.OK) {
  32763. var _this$backtrackFragme;
  32764. var backtrackSn = ((_this$backtrackFragme = this.backtrackFragment) != null ? _this$backtrackFragme : frag).sn;
  32765. var fragIdx = backtrackSn - levelDetails.startSN;
  32766. var backtrackFrag = levelDetails.fragments[fragIdx - 1];
  32767. if (backtrackFrag && frag.cc === backtrackFrag.cc) {
  32768. frag = backtrackFrag;
  32769. this.fragmentTracker.removeFragment(backtrackFrag);
  32770. }
  32771. } else if (this.backtrackFragment && bufferInfo.len) {
  32772. this.backtrackFragment = null;
  32773. }
  32774. // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags
  32775. if (frag && this.isLoopLoading(frag, targetBufferTime)) {
  32776. var gapStart = frag.gap;
  32777. if (!gapStart) {
  32778. // Cleanup the fragment tracker before trying to find the next unbuffered fragment
  32779. var type = this.audioOnly && !this.altAudio ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
  32780. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  32781. if (mediaBuffer) {
  32782. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  32783. }
  32784. }
  32785. frag = this.getNextFragmentLoopLoading(frag, levelDetails, bufferInfo, PlaylistLevelType.MAIN, maxBufLen);
  32786. }
  32787. if (!frag) {
  32788. return;
  32789. }
  32790. if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
  32791. frag = frag.initSegment;
  32792. }
  32793. this.loadFragment(frag, levelInfo, targetBufferTime);
  32794. };
  32795. _proto.loadFragment = function loadFragment(frag, level, targetBufferTime) {
  32796. // Check if fragment is not loaded
  32797. var fragState = this.fragmentTracker.getState(frag);
  32798. if (fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
  32799. if (!isMediaFragment(frag)) {
  32800. this._loadInitSegment(frag, level);
  32801. } else if (this.bitrateTest) {
  32802. this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
  32803. this._loadBitrateTestFrag(frag, level);
  32804. } else {
  32805. _BaseStreamController.prototype.loadFragment.call(this, frag, level, targetBufferTime);
  32806. }
  32807. } else {
  32808. this.clearTrackerIfNeeded(frag);
  32809. }
  32810. };
  32811. _proto.getBufferedFrag = function getBufferedFrag(position) {
  32812. return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
  32813. };
  32814. _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
  32815. if (frag) {
  32816. // try to get range of next fragment (500ms after this range)
  32817. return this.getBufferedFrag(frag.end + 0.5);
  32818. }
  32819. return null;
  32820. }
  32821. /*
  32822. on immediate level switch :
  32823. - pause playback if playing
  32824. - cancel any pending load request
  32825. - and trigger a buffer flush
  32826. */;
  32827. _proto.immediateLevelSwitch = function immediateLevelSwitch() {
  32828. this.abortCurrentFrag();
  32829. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  32830. }
  32831. /**
  32832. * try to switch ASAP without breaking video playback:
  32833. * in order to ensure smooth but quick level switching,
  32834. * we need to find the next flushable buffer range
  32835. * we should take into account new segment fetch time
  32836. */;
  32837. _proto.nextLevelSwitch = function nextLevelSwitch() {
  32838. var levels = this.levels,
  32839. media = this.media;
  32840. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  32841. if (media != null && media.readyState) {
  32842. var fetchdelay;
  32843. var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
  32844. if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
  32845. // flush buffer preceding current fragment (flush until current fragment start offset)
  32846. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  32847. this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
  32848. }
  32849. var levelDetails = this.getLevelDetails();
  32850. if (levelDetails != null && levelDetails.live) {
  32851. var bufferInfo = this.getMainFwdBufferInfo();
  32852. // Do not flush in live stream with low buffer
  32853. if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {
  32854. return;
  32855. }
  32856. }
  32857. if (!media.paused && levels) {
  32858. // add a safety delay of 1s
  32859. var nextLevelId = this.hls.nextLoadLevel;
  32860. var nextLevel = levels[nextLevelId];
  32861. var fragLastKbps = this.fragLastKbps;
  32862. if (fragLastKbps && this.fragCurrent) {
  32863. fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
  32864. } else {
  32865. fetchdelay = 0;
  32866. }
  32867. } else {
  32868. fetchdelay = 0;
  32869. }
  32870. // this.log('fetchdelay:'+fetchdelay);
  32871. // find buffer range that will be reached once new fragment will be fetched
  32872. var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  32873. if (bufferedFrag) {
  32874. // we can flush buffer range following this one without stalling playback
  32875. var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
  32876. if (nextBufferedFrag) {
  32877. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  32878. this.abortCurrentFrag();
  32879. // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
  32880. var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
  32881. var fragDuration = nextBufferedFrag.duration;
  32882. var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * (this.couldBacktrack ? 0.5 : 0.125)), fragDuration * (this.couldBacktrack ? 0.75 : 0.25)));
  32883. this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
  32884. }
  32885. }
  32886. }
  32887. };
  32888. _proto.abortCurrentFrag = function abortCurrentFrag() {
  32889. var fragCurrent = this.fragCurrent;
  32890. this.fragCurrent = null;
  32891. this.backtrackFragment = null;
  32892. if (fragCurrent) {
  32893. fragCurrent.abortRequests();
  32894. this.fragmentTracker.removeFragment(fragCurrent);
  32895. }
  32896. switch (this.state) {
  32897. case State.KEY_LOADING:
  32898. case State.FRAG_LOADING:
  32899. case State.FRAG_LOADING_WAITING_RETRY:
  32900. case State.PARSING:
  32901. case State.PARSED:
  32902. this.state = State.IDLE;
  32903. break;
  32904. }
  32905. this.nextLoadPosition = this.getLoadPosition();
  32906. };
  32907. _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
  32908. _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio === 2 ? 'video' : null);
  32909. };
  32910. _proto.onMediaAttached = function onMediaAttached(event, data) {
  32911. _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
  32912. var media = data.media;
  32913. addEventListener(media, 'playing', this.onMediaPlaying);
  32914. addEventListener(media, 'seeked', this.onMediaSeeked);
  32915. };
  32916. _proto.onMediaDetaching = function onMediaDetaching(event, data) {
  32917. var media = this.media;
  32918. if (media) {
  32919. removeEventListener(media, 'playing', this.onMediaPlaying);
  32920. removeEventListener(media, 'seeked', this.onMediaSeeked);
  32921. }
  32922. this.videoBuffer = null;
  32923. this.fragPlaying = null;
  32924. _BaseStreamController.prototype.onMediaDetaching.call(this, event, data);
  32925. var transferringMedia = !!data.transferMedia;
  32926. if (transferringMedia) {
  32927. return;
  32928. }
  32929. this._hasEnoughToStart = false;
  32930. };
  32931. _proto.onManifestLoading = function onManifestLoading() {
  32932. _BaseStreamController.prototype.onManifestLoading.call(this);
  32933. // reset buffer on manifest loading
  32934. this.log('Trigger BUFFER_RESET');
  32935. this.hls.trigger(Events.BUFFER_RESET, undefined);
  32936. this.couldBacktrack = false;
  32937. this.fragLastKbps = 0;
  32938. this.fragPlaying = this.backtrackFragment = null;
  32939. this.altAudio = 0;
  32940. this.audioOnly = false;
  32941. };
  32942. _proto.onManifestParsed = function onManifestParsed(event, data) {
  32943. // detect if we have different kind of audio codecs used amongst playlists
  32944. var aac = false;
  32945. var heaac = false;
  32946. data.levels.forEach(function (level) {
  32947. var codec = level.audioCodec;
  32948. if (codec) {
  32949. aac = aac || codec.indexOf('mp4a.40.2') !== -1;
  32950. heaac = heaac || codec.indexOf('mp4a.40.5') !== -1;
  32951. }
  32952. });
  32953. this.audioCodecSwitch = aac && heaac && !changeTypeSupported();
  32954. if (this.audioCodecSwitch) {
  32955. this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  32956. }
  32957. this.levels = data.levels;
  32958. this.startFragRequested = false;
  32959. };
  32960. _proto.onLevelLoading = function onLevelLoading(event, data) {
  32961. var levels = this.levels;
  32962. if (!levels || this.state !== State.IDLE) {
  32963. return;
  32964. }
  32965. var level = data.levelInfo;
  32966. if (!level.details || level.details.live && (this.levelLastLoaded !== level || level.details.expired) || this.waitForCdnTuneIn(level.details)) {
  32967. this.state = State.WAITING_LEVEL;
  32968. }
  32969. };
  32970. _proto.onLevelLoaded = function onLevelLoaded(event, data) {
  32971. var _curLevel$details;
  32972. var levels = this.levels,
  32973. startFragRequested = this.startFragRequested;
  32974. var newLevelId = data.level;
  32975. var newDetails = data.details;
  32976. var duration = newDetails.totalduration;
  32977. if (!levels) {
  32978. this.warn("Levels were reset while loading level " + newLevelId);
  32979. return;
  32980. }
  32981. this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "]" + (newDetails.lastPartSn ? "[part-" + newDetails.lastPartSn + "-" + newDetails.lastPartIndex + "]" : '') + ", cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
  32982. var curLevel = data.levelInfo;
  32983. var fragCurrent = this.fragCurrent;
  32984. if (fragCurrent && (this.state === State.FRAG_LOADING || this.state === State.FRAG_LOADING_WAITING_RETRY)) {
  32985. if (fragCurrent.level !== data.level && fragCurrent.loader) {
  32986. this.abortCurrentFrag();
  32987. }
  32988. }
  32989. var sliding = 0;
  32990. if (newDetails.live || (_curLevel$details = curLevel.details) != null && _curLevel$details.live) {
  32991. var _this$levelLastLoaded;
  32992. this.checkLiveUpdate(newDetails);
  32993. if (newDetails.deltaUpdateFailed) {
  32994. return;
  32995. }
  32996. sliding = this.alignPlaylists(newDetails, curLevel.details, (_this$levelLastLoaded = this.levelLastLoaded) == null ? void 0 : _this$levelLastLoaded.details);
  32997. }
  32998. // override level info
  32999. curLevel.details = newDetails;
  33000. this.levelLastLoaded = curLevel;
  33001. if (!startFragRequested) {
  33002. this.setStartPosition(newDetails, sliding);
  33003. }
  33004. this.hls.trigger(Events.LEVEL_UPDATED, {
  33005. details: newDetails,
  33006. level: newLevelId
  33007. });
  33008. // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
  33009. if (this.state === State.WAITING_LEVEL) {
  33010. if (this.waitForCdnTuneIn(newDetails)) {
  33011. // Wait for Low-Latency CDN Tune-in
  33012. return;
  33013. }
  33014. this.state = State.IDLE;
  33015. }
  33016. if (startFragRequested && newDetails.live) {
  33017. this.synchronizeToLiveEdge(newDetails);
  33018. }
  33019. // trigger handler right now
  33020. this.tick();
  33021. };
  33022. _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
  33023. var config = this.config,
  33024. media = this.media;
  33025. if (!media) {
  33026. return;
  33027. }
  33028. var liveSyncPosition = this.hls.liveSyncPosition;
  33029. var currentTime = this.getLoadPosition();
  33030. var start = levelDetails.fragmentStart;
  33031. var end = levelDetails.edge;
  33032. var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end;
  33033. // Continue if we can seek forward to sync position or if current time is outside of sliding window
  33034. if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
  33035. // Continue if buffer is starving or if current time is behind max latency
  33036. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  33037. if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
  33038. if (!this._hasEnoughToStart) {
  33039. this.nextLoadPosition = liveSyncPosition;
  33040. }
  33041. // Only seek if ready and there is not a significant forward buffer available for playback
  33042. if (media.readyState) {
  33043. this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
  33044. if (this.config.liveSyncMode === 'buffered') {
  33045. var _bufferInfo$buffered;
  33046. var bufferInfo = BufferHelper.bufferInfo(media, liveSyncPosition, 0);
  33047. if (!(bufferInfo != null && (_bufferInfo$buffered = bufferInfo.buffered) != null && _bufferInfo$buffered.length)) {
  33048. media.currentTime = liveSyncPosition;
  33049. return;
  33050. }
  33051. var isLiveSyncInBuffer = bufferInfo.start <= currentTime;
  33052. if (isLiveSyncInBuffer) {
  33053. media.currentTime = liveSyncPosition;
  33054. return;
  33055. }
  33056. var _BufferHelper$buffere = BufferHelper.bufferedInfo(bufferInfo.buffered, currentTime, 0),
  33057. nextStart = _BufferHelper$buffere.nextStart;
  33058. if (nextStart) {
  33059. media.currentTime = nextStart;
  33060. }
  33061. } else {
  33062. media.currentTime = liveSyncPosition;
  33063. }
  33064. }
  33065. }
  33066. }
  33067. };
  33068. _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
  33069. var _frag$initSegment;
  33070. var frag = data.frag;
  33071. var part = data.part,
  33072. payload = data.payload;
  33073. var levels = this.levels;
  33074. if (!levels) {
  33075. this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
  33076. return;
  33077. }
  33078. var currentLevel = levels[frag.level];
  33079. if (!currentLevel) {
  33080. this.warn("Level " + frag.level + " not found on progress");
  33081. return;
  33082. }
  33083. var details = currentLevel.details;
  33084. if (!details) {
  33085. this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
  33086. this.fragmentTracker.removeFragment(frag);
  33087. return;
  33088. }
  33089. var videoCodec = currentLevel.videoCodec;
  33090. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  33091. var accurateTimeOffset = details.PTSKnown || !details.live;
  33092. var initSegmentData = (_frag$initSegment = frag.initSegment) == null ? void 0 : _frag$initSegment.data;
  33093. var audioCodec = this._getAudioCodec(currentLevel);
  33094. // transmux the MPEG-TS data to ISO-BMFF segments
  33095. // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
  33096. var transmuxer = this.transmuxer = this.transmuxer || new TransmuxerInterface(this.hls, PlaylistLevelType.MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
  33097. var partIndex = part ? part.index : -1;
  33098. var partial = partIndex !== -1;
  33099. var chunkMeta = new ChunkMetadata(frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
  33100. var initPTS = this.initPTS[frag.cc];
  33101. transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
  33102. };
  33103. _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
  33104. var _this2 = this;
  33105. var hls = this.hls;
  33106. // if any URL found on new audio track, it is an alternate audio track
  33107. var fromAltAudio = this.altAudio === 2;
  33108. var altAudio = useAlternateAudio(data.url, hls);
  33109. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  33110. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  33111. // we will just have to change buffer scheduling on audioTrackSwitched
  33112. if (!altAudio) {
  33113. if (this.mediaBuffer !== this.media) {
  33114. this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
  33115. this.mediaBuffer = this.media;
  33116. var fragCurrent = this.fragCurrent;
  33117. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  33118. if (fragCurrent) {
  33119. this.log('Switching to main audio track, cancel main fragment load');
  33120. fragCurrent.abortRequests();
  33121. this.fragmentTracker.removeFragment(fragCurrent);
  33122. }
  33123. // destroy transmuxer to force init segment generation (following audio switch)
  33124. this.resetTransmuxer();
  33125. // switch to IDLE state to load new fragment
  33126. this.resetLoadingState();
  33127. } else if (this.audioOnly) {
  33128. // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
  33129. this.resetTransmuxer();
  33130. }
  33131. // If switching from alt to main audio, flush all audio and trigger track switched
  33132. if (fromAltAudio) {
  33133. this.fragmentTracker.removeAllFragments();
  33134. hls.once(Events.BUFFER_FLUSHED, function () {
  33135. var _this2$hls;
  33136. (_this2$hls = _this2.hls) == null ? void 0 : _this2$hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  33137. });
  33138. hls.trigger(Events.BUFFER_FLUSHING, {
  33139. startOffset: 0,
  33140. endOffset: Number.POSITIVE_INFINITY,
  33141. type: null
  33142. });
  33143. return;
  33144. }
  33145. hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);
  33146. } else {
  33147. this.altAudio = 1;
  33148. }
  33149. };
  33150. _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
  33151. var altAudio = useAlternateAudio(data.url, this.hls);
  33152. if (altAudio) {
  33153. var videoBuffer = this.videoBuffer;
  33154. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  33155. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  33156. this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
  33157. this.mediaBuffer = videoBuffer;
  33158. }
  33159. }
  33160. this.altAudio = altAudio ? 2 : 0;
  33161. this.tick();
  33162. };
  33163. _proto.onBufferCreated = function onBufferCreated(event, data) {
  33164. var tracks = data.tracks;
  33165. var mediaTrack;
  33166. var name;
  33167. var alternate = false;
  33168. for (var type in tracks) {
  33169. var track = tracks[type];
  33170. if (track.id === 'main') {
  33171. name = type;
  33172. mediaTrack = track;
  33173. // keep video source buffer reference
  33174. if (type === 'video') {
  33175. var videoTrack = tracks[type];
  33176. if (videoTrack) {
  33177. this.videoBuffer = videoTrack.buffer;
  33178. }
  33179. }
  33180. } else {
  33181. alternate = true;
  33182. }
  33183. }
  33184. if (alternate && mediaTrack) {
  33185. this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
  33186. this.mediaBuffer = mediaTrack.buffer;
  33187. } else {
  33188. this.mediaBuffer = this.media;
  33189. }
  33190. };
  33191. _proto.onFragBuffered = function onFragBuffered(event, data) {
  33192. var frag = data.frag,
  33193. part = data.part;
  33194. var bufferedMainFragment = frag.type === PlaylistLevelType.MAIN;
  33195. if (bufferedMainFragment) {
  33196. if (this.fragContextChanged(frag)) {
  33197. // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
  33198. // Avoid setting state back to IDLE, since that will interfere with a level switch
  33199. this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
  33200. if (this.state === State.PARSED) {
  33201. this.state = State.IDLE;
  33202. }
  33203. return;
  33204. }
  33205. var stats = part ? part.stats : frag.stats;
  33206. this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
  33207. if (isMediaFragment(frag)) {
  33208. this.fragPrevious = frag;
  33209. }
  33210. this.fragBufferedComplete(frag, part);
  33211. }
  33212. var media = this.media;
  33213. if (!media) {
  33214. return;
  33215. }
  33216. if (!this._hasEnoughToStart && BufferHelper.getBuffered(media).length) {
  33217. this._hasEnoughToStart = true;
  33218. this.seekToStartPos();
  33219. }
  33220. if (bufferedMainFragment) {
  33221. this.tick();
  33222. }
  33223. };
  33224. _proto.onError = function onError(event, data) {
  33225. var _data$context;
  33226. if (data.fatal) {
  33227. this.state = State.ERROR;
  33228. return;
  33229. }
  33230. switch (data.details) {
  33231. case ErrorDetails.FRAG_GAP:
  33232. case ErrorDetails.FRAG_PARSING_ERROR:
  33233. case ErrorDetails.FRAG_DECRYPT_ERROR:
  33234. case ErrorDetails.FRAG_LOAD_ERROR:
  33235. case ErrorDetails.FRAG_LOAD_TIMEOUT:
  33236. case ErrorDetails.KEY_LOAD_ERROR:
  33237. case ErrorDetails.KEY_LOAD_TIMEOUT:
  33238. this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);
  33239. break;
  33240. case ErrorDetails.LEVEL_LOAD_ERROR:
  33241. case ErrorDetails.LEVEL_LOAD_TIMEOUT:
  33242. case ErrorDetails.LEVEL_PARSING_ERROR:
  33243. // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE
  33244. if (!data.levelRetry && this.state === State.WAITING_LEVEL && ((_data$context = data.context) == null ? void 0 : _data$context.type) === PlaylistContextType.LEVEL) {
  33245. this.state = State.IDLE;
  33246. }
  33247. break;
  33248. case ErrorDetails.BUFFER_ADD_CODEC_ERROR:
  33249. case ErrorDetails.BUFFER_APPEND_ERROR:
  33250. if (data.parent !== 'main') {
  33251. return;
  33252. }
  33253. if (this.reduceLengthAndFlushBuffer(data)) {
  33254. this.resetLoadingState();
  33255. }
  33256. break;
  33257. case ErrorDetails.BUFFER_FULL_ERROR:
  33258. if (data.parent !== 'main') {
  33259. return;
  33260. }
  33261. if (this.reduceLengthAndFlushBuffer(data)) {
  33262. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  33263. }
  33264. break;
  33265. case ErrorDetails.INTERNAL_EXCEPTION:
  33266. this.recoverWorkerError(data);
  33267. break;
  33268. }
  33269. };
  33270. _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
  33271. this.state = State.IDLE;
  33272. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  33273. // in that case, reset startFragRequested flag
  33274. if (!this._hasEnoughToStart) {
  33275. this.startFragRequested = false;
  33276. this.nextLoadPosition = this.lastCurrentTime;
  33277. }
  33278. this.tickImmediate();
  33279. };
  33280. _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
  33281. var type = _ref.type;
  33282. if (type !== ElementaryStreamTypes.AUDIO || !this.altAudio) {
  33283. var mediaBuffer = (type === ElementaryStreamTypes.VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
  33284. if (mediaBuffer) {
  33285. this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);
  33286. this.tick();
  33287. }
  33288. }
  33289. };
  33290. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  33291. if (this.level > -1 && this.fragCurrent) {
  33292. this.level = this.fragCurrent.level;
  33293. if (this.level === -1) {
  33294. this.resetWhenMissingContext(this.fragCurrent);
  33295. }
  33296. }
  33297. this.levels = data.levels;
  33298. };
  33299. _proto.swapAudioCodec = function swapAudioCodec() {
  33300. this.audioCodecSwap = !this.audioCodecSwap;
  33301. }
  33302. /**
  33303. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  33304. */;
  33305. _proto.seekToStartPos = function seekToStartPos() {
  33306. var media = this.media;
  33307. if (!media) {
  33308. return;
  33309. }
  33310. var currentTime = media.currentTime;
  33311. var startPosition = this.startPosition;
  33312. // only adjust currentTime if different from startPosition or if startPosition not buffered
  33313. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  33314. if (startPosition >= 0 && currentTime < startPosition) {
  33315. if (media.seeking) {
  33316. this.log("could not seek to " + startPosition + ", already seeking at " + currentTime);
  33317. return;
  33318. }
  33319. // Offset start position by timeline offset
  33320. var timelineOffset = this.timelineOffset;
  33321. if (timelineOffset && startPosition) {
  33322. startPosition += timelineOffset;
  33323. }
  33324. var details = this.getLevelDetails();
  33325. var buffered = BufferHelper.getBuffered(media);
  33326. var bufferStart = buffered.length ? buffered.start(0) : 0;
  33327. var delta = bufferStart - startPosition;
  33328. var skipTolerance = Math.max(this.config.maxBufferHole, this.config.maxFragLookUpTolerance);
  33329. if (this.config.startOnSegmentBoundary || delta > 0 && (delta < skipTolerance || this.loadingParts && delta < 2 * ((details == null ? void 0 : details.partTarget) || 0))) {
  33330. this.log("adjusting start position by " + delta + " to match buffer start");
  33331. startPosition += delta;
  33332. this.startPosition = startPosition;
  33333. }
  33334. if (currentTime < startPosition) {
  33335. this.log("seek to target start position " + startPosition + " from current time " + currentTime + " buffer start " + bufferStart);
  33336. media.currentTime = startPosition;
  33337. }
  33338. }
  33339. };
  33340. _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
  33341. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  33342. if (this.audioCodecSwap && audioCodec) {
  33343. this.log('Swapping audio codec');
  33344. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  33345. audioCodec = 'mp4a.40.2';
  33346. } else {
  33347. audioCodec = 'mp4a.40.5';
  33348. }
  33349. }
  33350. return audioCodec;
  33351. };
  33352. _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(fragment, level) {
  33353. var _this3 = this;
  33354. fragment.bitrateTest = true;
  33355. this._doFragLoad(fragment, level).then(function (data) {
  33356. var hls = _this3.hls;
  33357. var frag = data == null ? void 0 : data.frag;
  33358. if (!frag || _this3.fragContextChanged(frag)) {
  33359. return;
  33360. }
  33361. level.fragmentError = 0;
  33362. _this3.state = State.IDLE;
  33363. _this3.startFragRequested = false;
  33364. _this3.bitrateTest = false;
  33365. var stats = frag.stats;
  33366. // Bitrate tests fragments are neither parsed nor buffered
  33367. stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
  33368. hls.trigger(Events.FRAG_LOADED, data);
  33369. frag.bitrateTest = false;
  33370. });
  33371. };
  33372. _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
  33373. var _id3$samples;
  33374. var id = this.playlistType;
  33375. var hls = this.hls;
  33376. var remuxResult = transmuxResult.remuxResult,
  33377. chunkMeta = transmuxResult.chunkMeta;
  33378. var context = this.getCurrentContext(chunkMeta);
  33379. if (!context) {
  33380. this.resetWhenMissingContext(chunkMeta);
  33381. return;
  33382. }
  33383. var frag = context.frag,
  33384. part = context.part,
  33385. level = context.level;
  33386. var video = remuxResult.video,
  33387. text = remuxResult.text,
  33388. id3 = remuxResult.id3,
  33389. initSegment = remuxResult.initSegment;
  33390. var details = level.details;
  33391. // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
  33392. var audio = this.altAudio ? undefined : remuxResult.audio;
  33393. // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
  33394. // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
  33395. if (this.fragContextChanged(frag)) {
  33396. this.fragmentTracker.removeFragment(frag);
  33397. return;
  33398. }
  33399. this.state = State.PARSING;
  33400. if (initSegment) {
  33401. if (initSegment != null && initSegment.tracks) {
  33402. var mapFragment = frag.initSegment || frag;
  33403. this._bufferInitSegment(level, initSegment.tracks, mapFragment, chunkMeta);
  33404. hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {
  33405. frag: mapFragment,
  33406. id: id,
  33407. tracks: initSegment.tracks
  33408. });
  33409. }
  33410. // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
  33411. var baseTime = initSegment.initPTS;
  33412. var timescale = initSegment.timescale;
  33413. var initPTS = this.initPTS[frag.cc];
  33414. if (isFiniteNumber(baseTime) && (!initPTS || initPTS.baseTime !== baseTime || initPTS.timescale !== timescale)) {
  33415. this.initPTS[frag.cc] = {
  33416. baseTime: baseTime,
  33417. timescale: timescale
  33418. };
  33419. hls.trigger(Events.INIT_PTS_FOUND, {
  33420. frag: frag,
  33421. id: id,
  33422. initPTS: baseTime,
  33423. timescale: timescale
  33424. });
  33425. }
  33426. }
  33427. // Avoid buffering if backtracking this fragment
  33428. if (video && details) {
  33429. if (audio && video.type === 'audiovideo') {
  33430. this.logMuxedErr(frag);
  33431. }
  33432. var prevFrag = details.fragments[frag.sn - 1 - details.startSN];
  33433. var isFirstFragment = frag.sn === details.startSN;
  33434. var isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;
  33435. if (remuxResult.independent !== false) {
  33436. var startPTS = video.startPTS,
  33437. endPTS = video.endPTS,
  33438. startDTS = video.startDTS,
  33439. endDTS = video.endDTS;
  33440. if (part) {
  33441. part.elementaryStreams[video.type] = {
  33442. startPTS: startPTS,
  33443. endPTS: endPTS,
  33444. startDTS: startDTS,
  33445. endDTS: endDTS
  33446. };
  33447. } else {
  33448. if (video.firstKeyFrame && video.independent && chunkMeta.id === 1 && !isFirstInDiscontinuity) {
  33449. this.couldBacktrack = true;
  33450. }
  33451. if (video.dropped && video.independent) {
  33452. // Backtrack if dropped frames create a gap after currentTime
  33453. var bufferInfo = this.getMainFwdBufferInfo();
  33454. var targetBufferTime = (bufferInfo ? bufferInfo.end : this.getLoadPosition()) + this.config.maxBufferHole;
  33455. var startTime = video.firstKeyFramePTS ? video.firstKeyFramePTS : startPTS;
  33456. if (!isFirstFragment && targetBufferTime < startTime - this.config.maxBufferHole && !isFirstInDiscontinuity) {
  33457. this.backtrack(frag);
  33458. return;
  33459. } else if (isFirstInDiscontinuity) {
  33460. // Mark segment with a gap to avoid loop loading
  33461. frag.gap = true;
  33462. }
  33463. // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
  33464. frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
  33465. } else if (isFirstFragment && startPTS - (details.appliedTimelineOffset || 0) > MAX_START_GAP_JUMP) {
  33466. // Mark segment with a gap to skip large start gap
  33467. frag.gap = true;
  33468. }
  33469. }
  33470. frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
  33471. if (this.backtrackFragment) {
  33472. this.backtrackFragment = frag;
  33473. }
  33474. this.bufferFragmentData(video, frag, part, chunkMeta, isFirstFragment || isFirstInDiscontinuity);
  33475. } else if (isFirstFragment || isFirstInDiscontinuity) {
  33476. // Mark segment with a gap to avoid loop loading
  33477. frag.gap = true;
  33478. } else {
  33479. this.backtrack(frag);
  33480. return;
  33481. }
  33482. }
  33483. if (audio) {
  33484. var _startPTS = audio.startPTS,
  33485. _endPTS = audio.endPTS,
  33486. _startDTS = audio.startDTS,
  33487. _endDTS = audio.endDTS;
  33488. if (part) {
  33489. part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {
  33490. startPTS: _startPTS,
  33491. endPTS: _endPTS,
  33492. startDTS: _startDTS,
  33493. endDTS: _endDTS
  33494. };
  33495. }
  33496. frag.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
  33497. this.bufferFragmentData(audio, frag, part, chunkMeta);
  33498. }
  33499. if (details && id3 != null && (_id3$samples = id3.samples) != null && _id3$samples.length) {
  33500. var emittedID3 = {
  33501. id: id,
  33502. frag: frag,
  33503. details: details,
  33504. samples: id3.samples
  33505. };
  33506. hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);
  33507. }
  33508. if (details && text) {
  33509. var emittedText = {
  33510. id: id,
  33511. frag: frag,
  33512. details: details,
  33513. samples: text.samples
  33514. };
  33515. hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);
  33516. }
  33517. };
  33518. _proto.logMuxedErr = function logMuxedErr(frag) {
  33519. this.warn((isMediaFragment(frag) ? 'Media' : 'Init') + " segment with muxed audiovideo where only video expected: " + frag.url);
  33520. };
  33521. _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
  33522. var _this4 = this;
  33523. if (this.state !== State.PARSING) {
  33524. return;
  33525. }
  33526. this.audioOnly = !!tracks.audio && !tracks.video;
  33527. // if audio track is expected to come from audio stream controller, discard any coming from main
  33528. if (this.altAudio && !this.audioOnly) {
  33529. delete tracks.audio;
  33530. if (tracks.audiovideo) {
  33531. this.logMuxedErr(frag);
  33532. }
  33533. }
  33534. // include levelCodec in audio and video tracks
  33535. var audio = tracks.audio,
  33536. video = tracks.video,
  33537. audiovideo = tracks.audiovideo;
  33538. if (audio) {
  33539. var levelCodec = currentLevel.audioCodec;
  33540. var audioCodec = pickMostCompleteCodecName(audio.codec, levelCodec);
  33541. // Add level and profile to make up for remuxer not being able to parse full codec
  33542. // (logger warning "Unhandled audio codec...")
  33543. if (audioCodec === 'mp4a') {
  33544. audioCodec = 'mp4a.40.5';
  33545. }
  33546. // Handle `audioCodecSwitch`
  33547. var ua = navigator.userAgent.toLowerCase();
  33548. if (this.audioCodecSwitch) {
  33549. if (audioCodec) {
  33550. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  33551. audioCodec = 'mp4a.40.2';
  33552. } else {
  33553. audioCodec = 'mp4a.40.5';
  33554. }
  33555. }
  33556. // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
  33557. // force HE-AAC, as it seems that most browsers prefers it.
  33558. // don't force HE-AAC if mono stream, or in Firefox
  33559. var audioMetadata = audio.metadata;
  33560. if (audioMetadata && 'channelCount' in audioMetadata && (audioMetadata.channelCount || 1) !== 1 && ua.indexOf('firefox') === -1) {
  33561. audioCodec = 'mp4a.40.5';
  33562. }
  33563. }
  33564. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  33565. if (audioCodec && audioCodec.indexOf('mp4a.40.5') !== -1 && ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
  33566. // Exclude mpeg audio
  33567. audioCodec = 'mp4a.40.2';
  33568. this.log("Android: force audio codec to " + audioCodec);
  33569. }
  33570. if (levelCodec && levelCodec !== audioCodec) {
  33571. this.log("Swapping manifest audio codec \"" + levelCodec + "\" for \"" + audioCodec + "\"");
  33572. }
  33573. audio.levelCodec = audioCodec;
  33574. audio.id = PlaylistLevelType.MAIN;
  33575. this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (levelCodec || '') + "/" + audio.codec + "]");
  33576. delete tracks.audiovideo;
  33577. }
  33578. if (video) {
  33579. video.levelCodec = currentLevel.videoCodec;
  33580. video.id = PlaylistLevelType.MAIN;
  33581. var parsedVideoCodec = video.codec;
  33582. if ((parsedVideoCodec == null ? void 0 : parsedVideoCodec.length) === 4) {
  33583. // Make up for passthrough-remuxer not being able to parse full codec
  33584. // (logger warning "Unhandled video codec...")
  33585. switch (parsedVideoCodec) {
  33586. case 'hvc1':
  33587. case 'hev1':
  33588. video.codec = 'hvc1.1.6.L120.90';
  33589. break;
  33590. case 'av01':
  33591. video.codec = 'av01.0.04M.08';
  33592. break;
  33593. case 'avc1':
  33594. video.codec = 'avc1.42e01e';
  33595. break;
  33596. }
  33597. }
  33598. this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + parsedVideoCodec + "]" + (video.codec !== parsedVideoCodec ? ' parsed-corrected=' + video.codec : '') + (video.supplemental ? ' supplemental=' + video.supplemental : ''));
  33599. delete tracks.audiovideo;
  33600. }
  33601. if (audiovideo) {
  33602. this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + currentLevel.codecs + "/" + audiovideo.codec + "]");
  33603. delete tracks.video;
  33604. delete tracks.audio;
  33605. }
  33606. var trackTypes = Object.keys(tracks);
  33607. if (trackTypes.length) {
  33608. this.hls.trigger(Events.BUFFER_CODECS, tracks);
  33609. if (!this.hls) {
  33610. // Exit after fatal tracks error
  33611. return;
  33612. }
  33613. // loop through tracks that are going to be provided to bufferController
  33614. trackTypes.forEach(function (trackName) {
  33615. var track = tracks[trackName];
  33616. var initSegment = track.initSegment;
  33617. if (initSegment != null && initSegment.byteLength) {
  33618. _this4.hls.trigger(Events.BUFFER_APPENDING, {
  33619. type: trackName,
  33620. data: initSegment,
  33621. frag: frag,
  33622. part: null,
  33623. chunkMeta: chunkMeta,
  33624. parent: frag.type
  33625. });
  33626. }
  33627. });
  33628. }
  33629. // trigger handler right now
  33630. this.tickImmediate();
  33631. };
  33632. _proto.getMainFwdBufferInfo = function getMainFwdBufferInfo() {
  33633. // Observe video SourceBuffer (this.mediaBuffer) only when alt-audio is used, otherwise observe combined media buffer
  33634. var bufferOutput = this.mediaBuffer && this.altAudio === 2 ? this.mediaBuffer : this.media;
  33635. return this.getFwdBufferInfo(bufferOutput, PlaylistLevelType.MAIN);
  33636. };
  33637. _proto.backtrack = function backtrack(frag) {
  33638. this.couldBacktrack = true;
  33639. // Causes findFragments to backtrack through fragments to find the keyframe
  33640. this.backtrackFragment = frag;
  33641. this.resetTransmuxer();
  33642. this.flushBufferGap(frag);
  33643. this.fragmentTracker.removeFragment(frag);
  33644. this.fragPrevious = null;
  33645. this.nextLoadPosition = frag.start;
  33646. this.state = State.IDLE;
  33647. };
  33648. _proto.checkFragmentChanged = function checkFragmentChanged() {
  33649. var video = this.media;
  33650. var fragPlayingCurrent = null;
  33651. if (video && video.readyState > 1 && video.seeking === false) {
  33652. var currentTime = video.currentTime;
  33653. /* if video element is in seeked state, currentTime can only increase.
  33654. (assuming that playback rate is positive ...)
  33655. As sometimes currentTime jumps back to zero after a
  33656. media decode error, check this, to avoid seeking back to
  33657. wrong position after a media decode error
  33658. */
  33659. if (BufferHelper.isBuffered(video, currentTime)) {
  33660. fragPlayingCurrent = this.getAppendedFrag(currentTime);
  33661. } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {
  33662. /* ensure that FRAG_CHANGED event is triggered at startup,
  33663. when first video frame is displayed and playback is paused.
  33664. add a tolerance of 100ms, in case current position is not buffered,
  33665. check if current pos+100ms is buffered and use that buffer range
  33666. for FRAG_CHANGED event reporting */
  33667. fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
  33668. }
  33669. if (fragPlayingCurrent) {
  33670. this.backtrackFragment = null;
  33671. var fragPlaying = this.fragPlaying;
  33672. var fragCurrentLevel = fragPlayingCurrent.level;
  33673. if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel) {
  33674. this.fragPlaying = fragPlayingCurrent;
  33675. this.hls.trigger(Events.FRAG_CHANGED, {
  33676. frag: fragPlayingCurrent
  33677. });
  33678. if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
  33679. this.hls.trigger(Events.LEVEL_SWITCHED, {
  33680. level: fragCurrentLevel
  33681. });
  33682. }
  33683. }
  33684. }
  33685. }
  33686. };
  33687. return _createClass(StreamController, [{
  33688. key: "hasEnoughToStart",
  33689. get: function get() {
  33690. return this._hasEnoughToStart;
  33691. }
  33692. }, {
  33693. key: "maxBufferLength",
  33694. get: function get() {
  33695. var levels = this.levels,
  33696. level = this.level;
  33697. var levelInfo = levels == null ? void 0 : levels[level];
  33698. if (!levelInfo) {
  33699. return this.config.maxBufferLength;
  33700. }
  33701. return this.getMaxBufferLength(levelInfo.maxBitrate);
  33702. }
  33703. }, {
  33704. key: "nextLevel",
  33705. get: function get() {
  33706. var frag = this.nextBufferedFrag;
  33707. if (frag) {
  33708. return frag.level;
  33709. }
  33710. return -1;
  33711. }
  33712. }, {
  33713. key: "currentFrag",
  33714. get: function get() {
  33715. var _this$media3;
  33716. if (this.fragPlaying) {
  33717. return this.fragPlaying;
  33718. }
  33719. var currentTime = ((_this$media3 = this.media) == null ? void 0 : _this$media3.currentTime) || this.lastCurrentTime;
  33720. if (isFiniteNumber(currentTime)) {
  33721. return this.getAppendedFrag(currentTime);
  33722. }
  33723. return null;
  33724. }
  33725. }, {
  33726. key: "currentProgramDateTime",
  33727. get: function get() {
  33728. var _this$media4;
  33729. var currentTime = ((_this$media4 = this.media) == null ? void 0 : _this$media4.currentTime) || this.lastCurrentTime;
  33730. if (isFiniteNumber(currentTime)) {
  33731. var details = this.getLevelDetails();
  33732. var frag = this.currentFrag || (details ? findFragmentByPTS(null, details.fragments, currentTime) : null);
  33733. if (frag) {
  33734. var programDateTime = frag.programDateTime;
  33735. if (programDateTime !== null) {
  33736. var epocMs = programDateTime + (currentTime - frag.start) * 1000;
  33737. return new Date(epocMs);
  33738. }
  33739. }
  33740. }
  33741. return null;
  33742. }
  33743. }, {
  33744. key: "currentLevel",
  33745. get: function get() {
  33746. var frag = this.currentFrag;
  33747. if (frag) {
  33748. return frag.level;
  33749. }
  33750. return -1;
  33751. }
  33752. }, {
  33753. key: "nextBufferedFrag",
  33754. get: function get() {
  33755. var frag = this.currentFrag;
  33756. if (frag) {
  33757. return this.followingBufferedFrag(frag);
  33758. }
  33759. return null;
  33760. }
  33761. }, {
  33762. key: "forceStartLoad",
  33763. get: function get() {
  33764. return this._forceStartLoad;
  33765. }
  33766. }]);
  33767. }(BaseStreamController);
  33768. var KeyLoader = /*#__PURE__*/function () {
  33769. function KeyLoader(config) {
  33770. this.config = void 0;
  33771. this.keyUriToKeyInfo = {};
  33772. this.emeController = null;
  33773. this.config = config;
  33774. }
  33775. var _proto = KeyLoader.prototype;
  33776. _proto.abort = function abort(type) {
  33777. for (var uri in this.keyUriToKeyInfo) {
  33778. var loader = this.keyUriToKeyInfo[uri].loader;
  33779. if (loader) {
  33780. var _loader$context;
  33781. if (type && type !== ((_loader$context = loader.context) == null ? void 0 : _loader$context.frag.type)) {
  33782. return;
  33783. }
  33784. loader.abort();
  33785. }
  33786. }
  33787. };
  33788. _proto.detach = function detach() {
  33789. for (var uri in this.keyUriToKeyInfo) {
  33790. var keyInfo = this.keyUriToKeyInfo[uri];
  33791. // Remove cached EME keys on detach
  33792. if (keyInfo.mediaKeySessionContext || keyInfo.decryptdata.isCommonEncryption) {
  33793. delete this.keyUriToKeyInfo[uri];
  33794. }
  33795. }
  33796. };
  33797. _proto.destroy = function destroy() {
  33798. this.detach();
  33799. for (var uri in this.keyUriToKeyInfo) {
  33800. var loader = this.keyUriToKeyInfo[uri].loader;
  33801. if (loader) {
  33802. loader.destroy();
  33803. }
  33804. }
  33805. this.keyUriToKeyInfo = {};
  33806. };
  33807. _proto.createKeyLoadError = function createKeyLoadError(frag, details, error, networkDetails, response) {
  33808. if (details === void 0) {
  33809. details = ErrorDetails.KEY_LOAD_ERROR;
  33810. }
  33811. return new LoadError({
  33812. type: ErrorTypes.NETWORK_ERROR,
  33813. details: details,
  33814. fatal: false,
  33815. frag: frag,
  33816. response: response,
  33817. error: error,
  33818. networkDetails: networkDetails
  33819. });
  33820. };
  33821. _proto.loadClear = function loadClear(loadingFrag, encryptedFragments, startFragRequested) {
  33822. var _this = this;
  33823. if (this.emeController && this.config.emeEnabled && !this.emeController.getSelectedKeySystemFormats().length) {
  33824. // Access key-system with nearest key on start (loading frag is unencrypted)
  33825. if (encryptedFragments.length) {
  33826. var _loop = function _loop() {
  33827. var frag = encryptedFragments[i];
  33828. // Loading at or before segment with EXT-X-KEY, or first frag loading and last EXT-X-KEY
  33829. if (loadingFrag.cc <= frag.cc && (!isMediaFragment(loadingFrag) || !isMediaFragment(frag) || loadingFrag.sn < frag.sn) || !startFragRequested && i == l - 1) {
  33830. return {
  33831. v: _this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  33832. if (!_this.emeController) {
  33833. return;
  33834. }
  33835. frag.setKeyFormat(keySystemFormat);
  33836. var keySystem = keySystemFormatToKeySystemDomain(keySystemFormat);
  33837. if (keySystem) {
  33838. return _this.emeController.getKeySystemAccess([keySystem]);
  33839. }
  33840. })
  33841. };
  33842. }
  33843. },
  33844. _ret;
  33845. for (var i = 0, l = encryptedFragments.length; i < l; i++) {
  33846. _ret = _loop();
  33847. if (_ret) return _ret.v;
  33848. }
  33849. }
  33850. if (this.config.requireKeySystemAccessOnStart) {
  33851. var keySystemsInConfig = getKeySystemsForConfig(this.config);
  33852. if (keySystemsInConfig.length) {
  33853. return this.emeController.getKeySystemAccess(keySystemsInConfig);
  33854. }
  33855. }
  33856. }
  33857. return null;
  33858. };
  33859. _proto.load = function load(frag) {
  33860. var _this2 = this;
  33861. if (!frag.decryptdata && frag.encrypted && this.emeController && this.config.emeEnabled) {
  33862. // Multiple keys, but none selected, resolve in eme-controller
  33863. return this.emeController.selectKeySystemFormat(frag).then(function (keySystemFormat) {
  33864. return _this2.loadInternal(frag, keySystemFormat);
  33865. });
  33866. }
  33867. return this.loadInternal(frag);
  33868. };
  33869. _proto.loadInternal = function loadInternal(frag, keySystemFormat) {
  33870. var _keyInfo, _keyInfo2;
  33871. if (keySystemFormat) {
  33872. frag.setKeyFormat(keySystemFormat);
  33873. }
  33874. var decryptdata = frag.decryptdata;
  33875. if (!decryptdata) {
  33876. var error = new Error(keySystemFormat ? "Expected frag.decryptdata to be defined after setting format " + keySystemFormat : 'Missing decryption data on fragment in onKeyLoading');
  33877. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error));
  33878. }
  33879. var uri = decryptdata.uri;
  33880. if (!uri) {
  33881. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Invalid key URI: \"" + uri + "\"")));
  33882. }
  33883. var keyInfo = this.keyUriToKeyInfo[uri];
  33884. if ((_keyInfo = keyInfo) != null && _keyInfo.decryptdata.key) {
  33885. decryptdata.key = keyInfo.decryptdata.key;
  33886. return Promise.resolve({
  33887. frag: frag,
  33888. keyInfo: keyInfo
  33889. });
  33890. }
  33891. // Return key load promise as long as it does not have a mediakey session with an unusable key status
  33892. if ((_keyInfo2 = keyInfo) != null && _keyInfo2.keyLoadPromise) {
  33893. var _keyInfo$mediaKeySess;
  33894. switch ((_keyInfo$mediaKeySess = keyInfo.mediaKeySessionContext) == null ? void 0 : _keyInfo$mediaKeySess.keyStatus) {
  33895. case undefined:
  33896. case 'status-pending':
  33897. case 'usable':
  33898. case 'usable-in-future':
  33899. return keyInfo.keyLoadPromise.then(function (keyLoadedData) {
  33900. // Return the correct fragment with updated decryptdata key and loaded keyInfo
  33901. decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;
  33902. return {
  33903. frag: frag,
  33904. keyInfo: keyInfo
  33905. };
  33906. });
  33907. }
  33908. // If we have a key session and status and it is not pending or usable, continue
  33909. // This will go back to the eme-controller for expired keys to get a new keyLoadPromise
  33910. }
  33911. // Load the key or return the loading promise
  33912. keyInfo = this.keyUriToKeyInfo[uri] = {
  33913. decryptdata: decryptdata,
  33914. keyLoadPromise: null,
  33915. loader: null,
  33916. mediaKeySessionContext: null
  33917. };
  33918. switch (decryptdata.method) {
  33919. case 'ISO-23001-7':
  33920. case 'SAMPLE-AES':
  33921. case 'SAMPLE-AES-CENC':
  33922. case 'SAMPLE-AES-CTR':
  33923. if (decryptdata.keyFormat === 'identity') {
  33924. // loadKeyHTTP handles http(s) and data URLs
  33925. return this.loadKeyHTTP(keyInfo, frag);
  33926. }
  33927. return this.loadKeyEME(keyInfo, frag);
  33928. case 'AES-128':
  33929. case 'AES-256':
  33930. case 'AES-256-CTR':
  33931. return this.loadKeyHTTP(keyInfo, frag);
  33932. default:
  33933. return Promise.reject(this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("Key supplied with unsupported METHOD: \"" + decryptdata.method + "\"")));
  33934. }
  33935. };
  33936. _proto.loadKeyEME = function loadKeyEME(keyInfo, frag) {
  33937. var keyLoadedData = {
  33938. frag: frag,
  33939. keyInfo: keyInfo
  33940. };
  33941. if (this.emeController && this.config.emeEnabled) {
  33942. var keySessionContextPromise = this.emeController.loadKey(keyLoadedData);
  33943. if (keySessionContextPromise) {
  33944. return (keyInfo.keyLoadPromise = keySessionContextPromise.then(function (keySessionContext) {
  33945. keyInfo.mediaKeySessionContext = keySessionContext;
  33946. return keyLoadedData;
  33947. })).catch(function (error) {
  33948. // Remove promise for license renewal or retry
  33949. keyInfo.keyLoadPromise = null;
  33950. throw error;
  33951. });
  33952. }
  33953. }
  33954. return Promise.resolve(keyLoadedData);
  33955. };
  33956. _proto.loadKeyHTTP = function loadKeyHTTP(keyInfo, frag) {
  33957. var _this3 = this;
  33958. var config = this.config;
  33959. var Loader = config.loader;
  33960. var keyLoader = new Loader(config);
  33961. frag.keyLoader = keyInfo.loader = keyLoader;
  33962. return keyInfo.keyLoadPromise = new Promise(function (resolve, reject) {
  33963. var loaderContext = {
  33964. keyInfo: keyInfo,
  33965. frag: frag,
  33966. responseType: 'arraybuffer',
  33967. url: keyInfo.decryptdata.uri
  33968. };
  33969. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  33970. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  33971. // this will also align retry logic with fragment-loader
  33972. var loadPolicy = config.keyLoadPolicy.default;
  33973. var loaderConfig = {
  33974. loadPolicy: loadPolicy,
  33975. timeout: loadPolicy.maxLoadTimeMs,
  33976. maxRetry: 0,
  33977. retryDelay: 0,
  33978. maxRetryDelay: 0
  33979. };
  33980. var loaderCallbacks = {
  33981. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  33982. var frag = context.frag,
  33983. keyInfo = context.keyInfo,
  33984. uri = context.url;
  33985. if (!frag.decryptdata || keyInfo !== _this3.keyUriToKeyInfo[uri]) {
  33986. return reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error('after key load, decryptdata unset or changed'), networkDetails));
  33987. }
  33988. keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(response.data);
  33989. // detach fragment key loader on load success
  33990. frag.keyLoader = null;
  33991. keyInfo.loader = null;
  33992. resolve({
  33993. frag: frag,
  33994. keyInfo: keyInfo
  33995. });
  33996. },
  33997. onError: function onError(response, context, networkDetails, stats) {
  33998. _this3.resetLoader(context);
  33999. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, new Error("HTTP Error " + response.code + " loading key " + response.text), networkDetails, _objectSpread2({
  34000. url: loaderContext.url,
  34001. data: undefined
  34002. }, response)));
  34003. },
  34004. onTimeout: function onTimeout(stats, context, networkDetails) {
  34005. _this3.resetLoader(context);
  34006. reject(_this3.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_TIMEOUT, new Error('key loading timed out'), networkDetails));
  34007. },
  34008. onAbort: function onAbort(stats, context, networkDetails) {
  34009. _this3.resetLoader(context);
  34010. reject(_this3.createKeyLoadError(frag, ErrorDetails.INTERNAL_ABORTED, new Error('key loading aborted'), networkDetails));
  34011. }
  34012. };
  34013. keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);
  34014. });
  34015. };
  34016. _proto.resetLoader = function resetLoader(context) {
  34017. var frag = context.frag,
  34018. keyInfo = context.keyInfo,
  34019. uri = context.url;
  34020. var loader = keyInfo.loader;
  34021. if (frag.keyLoader === loader) {
  34022. frag.keyLoader = null;
  34023. keyInfo.loader = null;
  34024. }
  34025. delete this.keyUriToKeyInfo[uri];
  34026. if (loader) {
  34027. loader.destroy();
  34028. }
  34029. };
  34030. return KeyLoader;
  34031. }();
  34032. function mapContextToLevelType(context) {
  34033. var type = context.type;
  34034. switch (type) {
  34035. case PlaylistContextType.AUDIO_TRACK:
  34036. return PlaylistLevelType.AUDIO;
  34037. case PlaylistContextType.SUBTITLE_TRACK:
  34038. return PlaylistLevelType.SUBTITLE;
  34039. default:
  34040. return PlaylistLevelType.MAIN;
  34041. }
  34042. }
  34043. function getResponseUrl(response, context) {
  34044. var url = response.url;
  34045. // responseURL not supported on some browsers (it is used to detect URL redirection)
  34046. // data-uri mode also not supported (but no need to detect redirection)
  34047. if (url === undefined || url.indexOf('data:') === 0) {
  34048. // fallback to initial URL
  34049. url = context.url;
  34050. }
  34051. return url;
  34052. }
  34053. var PlaylistLoader = /*#__PURE__*/function () {
  34054. function PlaylistLoader(hls) {
  34055. this.hls = void 0;
  34056. this.loaders = Object.create(null);
  34057. this.variableList = null;
  34058. this.onManifestLoaded = this.checkAutostartLoad;
  34059. this.hls = hls;
  34060. this.registerListeners();
  34061. }
  34062. var _proto = PlaylistLoader.prototype;
  34063. _proto.startLoad = function startLoad(startPosition) {};
  34064. _proto.stopLoad = function stopLoad() {
  34065. this.destroyInternalLoaders();
  34066. };
  34067. _proto.registerListeners = function registerListeners() {
  34068. var hls = this.hls;
  34069. hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  34070. hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);
  34071. hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  34072. hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  34073. hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  34074. };
  34075. _proto.unregisterListeners = function unregisterListeners() {
  34076. var hls = this.hls;
  34077. hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);
  34078. hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);
  34079. hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
  34080. hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
  34081. hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);
  34082. }
  34083. /**
  34084. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  34085. */;
  34086. _proto.createInternalLoader = function createInternalLoader(context) {
  34087. var config = this.hls.config;
  34088. var PLoader = config.pLoader;
  34089. var Loader = config.loader;
  34090. var InternalLoader = PLoader || Loader;
  34091. var loader = new InternalLoader(config);
  34092. this.loaders[context.type] = loader;
  34093. return loader;
  34094. };
  34095. _proto.getInternalLoader = function getInternalLoader(context) {
  34096. return this.loaders[context.type];
  34097. };
  34098. _proto.resetInternalLoader = function resetInternalLoader(contextType) {
  34099. if (this.loaders[contextType]) {
  34100. delete this.loaders[contextType];
  34101. }
  34102. }
  34103. /**
  34104. * Call `destroy` on all internal loader instances mapped (one per context type)
  34105. */;
  34106. _proto.destroyInternalLoaders = function destroyInternalLoaders() {
  34107. for (var contextType in this.loaders) {
  34108. var loader = this.loaders[contextType];
  34109. if (loader) {
  34110. loader.destroy();
  34111. }
  34112. this.resetInternalLoader(contextType);
  34113. }
  34114. };
  34115. _proto.destroy = function destroy() {
  34116. this.variableList = null;
  34117. this.unregisterListeners();
  34118. this.destroyInternalLoaders();
  34119. };
  34120. _proto.onManifestLoading = function onManifestLoading(event, data) {
  34121. var url = data.url;
  34122. this.variableList = null;
  34123. this.load({
  34124. id: null,
  34125. level: 0,
  34126. responseType: 'text',
  34127. type: PlaylistContextType.MANIFEST,
  34128. url: url,
  34129. deliveryDirectives: null,
  34130. levelOrTrack: null
  34131. });
  34132. };
  34133. _proto.onLevelLoading = function onLevelLoading(event, data) {
  34134. var id = data.id,
  34135. level = data.level,
  34136. pathwayId = data.pathwayId,
  34137. url = data.url,
  34138. deliveryDirectives = data.deliveryDirectives,
  34139. levelInfo = data.levelInfo;
  34140. this.load({
  34141. id: id,
  34142. level: level,
  34143. pathwayId: pathwayId,
  34144. responseType: 'text',
  34145. type: PlaylistContextType.LEVEL,
  34146. url: url,
  34147. deliveryDirectives: deliveryDirectives,
  34148. levelOrTrack: levelInfo
  34149. });
  34150. };
  34151. _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
  34152. var id = data.id,
  34153. groupId = data.groupId,
  34154. url = data.url,
  34155. deliveryDirectives = data.deliveryDirectives,
  34156. track = data.track;
  34157. this.load({
  34158. id: id,
  34159. groupId: groupId,
  34160. level: null,
  34161. responseType: 'text',
  34162. type: PlaylistContextType.AUDIO_TRACK,
  34163. url: url,
  34164. deliveryDirectives: deliveryDirectives,
  34165. levelOrTrack: track
  34166. });
  34167. };
  34168. _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
  34169. var id = data.id,
  34170. groupId = data.groupId,
  34171. url = data.url,
  34172. deliveryDirectives = data.deliveryDirectives,
  34173. track = data.track;
  34174. this.load({
  34175. id: id,
  34176. groupId: groupId,
  34177. level: null,
  34178. responseType: 'text',
  34179. type: PlaylistContextType.SUBTITLE_TRACK,
  34180. url: url,
  34181. deliveryDirectives: deliveryDirectives,
  34182. levelOrTrack: track
  34183. });
  34184. };
  34185. _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
  34186. // abort and delete loader of removed levels
  34187. var loader = this.loaders[PlaylistContextType.LEVEL];
  34188. if (loader) {
  34189. var context = loader.context;
  34190. if (context && !data.levels.some(function (lvl) {
  34191. return lvl === context.levelOrTrack;
  34192. })) {
  34193. loader.abort();
  34194. delete this.loaders[PlaylistContextType.LEVEL];
  34195. }
  34196. }
  34197. };
  34198. _proto.load = function load(context) {
  34199. var _context$deliveryDire,
  34200. _this = this;
  34201. var config = this.hls.config;
  34202. // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
  34203. // Check if a loader for this context already exists
  34204. var loader = this.getInternalLoader(context);
  34205. if (loader) {
  34206. var logger = this.hls.logger;
  34207. var loaderContext = loader.context;
  34208. if (loaderContext && loaderContext.levelOrTrack === context.levelOrTrack && (loaderContext.url === context.url || loaderContext.deliveryDirectives && !context.deliveryDirectives)) {
  34209. // same URL can't overlap, or wait for blocking request
  34210. if (loaderContext.url === context.url) {
  34211. logger.log("[playlist-loader]: ignore " + context.url + " ongoing request");
  34212. } else {
  34213. logger.log("[playlist-loader]: ignore " + context.url + " in favor of " + loaderContext.url);
  34214. }
  34215. return;
  34216. }
  34217. logger.log("[playlist-loader]: aborting previous loader for type: " + context.type);
  34218. loader.abort();
  34219. }
  34220. // apply different configs for retries depending on
  34221. // context (manifest, level, audio/subs playlist)
  34222. var loadPolicy;
  34223. if (context.type === PlaylistContextType.MANIFEST) {
  34224. loadPolicy = config.manifestLoadPolicy.default;
  34225. } else {
  34226. loadPolicy = _extends({}, config.playlistLoadPolicy.default, {
  34227. timeoutRetry: null,
  34228. errorRetry: null
  34229. });
  34230. }
  34231. loader = this.createInternalLoader(context);
  34232. // Override level/track timeout for LL-HLS requests
  34233. // (the default of 10000ms is counter productive to blocking playlist reload requests)
  34234. if (isFiniteNumber((_context$deliveryDire = context.deliveryDirectives) == null ? void 0 : _context$deliveryDire.part)) {
  34235. var levelDetails;
  34236. if (context.type === PlaylistContextType.LEVEL && context.level !== null) {
  34237. levelDetails = this.hls.levels[context.level].details;
  34238. } else if (context.type === PlaylistContextType.AUDIO_TRACK && context.id !== null) {
  34239. levelDetails = this.hls.audioTracks[context.id].details;
  34240. } else if (context.type === PlaylistContextType.SUBTITLE_TRACK && context.id !== null) {
  34241. levelDetails = this.hls.subtitleTracks[context.id].details;
  34242. }
  34243. if (levelDetails) {
  34244. var partTarget = levelDetails.partTarget;
  34245. var targetDuration = levelDetails.targetduration;
  34246. if (partTarget && targetDuration) {
  34247. var maxLowLatencyPlaylistRefresh = Math.max(partTarget * 3, targetDuration * 0.8) * 1000;
  34248. loadPolicy = _extends({}, loadPolicy, {
  34249. maxTimeToFirstByteMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs),
  34250. maxLoadTimeMs: Math.min(maxLowLatencyPlaylistRefresh, loadPolicy.maxTimeToFirstByteMs)
  34251. });
  34252. }
  34253. }
  34254. }
  34255. var legacyRetryCompatibility = loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};
  34256. var loaderConfig = {
  34257. loadPolicy: loadPolicy,
  34258. timeout: loadPolicy.maxLoadTimeMs,
  34259. maxRetry: legacyRetryCompatibility.maxNumRetry || 0,
  34260. retryDelay: legacyRetryCompatibility.retryDelayMs || 0,
  34261. maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0
  34262. };
  34263. var loaderCallbacks = {
  34264. onSuccess: function onSuccess(response, stats, context, networkDetails) {
  34265. var loader = _this.getInternalLoader(context);
  34266. _this.resetInternalLoader(context.type);
  34267. var string = response.data;
  34268. // Validate if it is an M3U8 at all
  34269. if (string.indexOf('#EXTM3U') !== 0) {
  34270. _this.handleManifestParsingError(response, context, new Error('no EXTM3U delimiter'), networkDetails || null, stats);
  34271. return;
  34272. }
  34273. stats.parsing.start = performance.now();
  34274. if (M3U8Parser.isMediaPlaylist(string) || context.type !== PlaylistContextType.MANIFEST) {
  34275. _this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails || null, loader);
  34276. } else {
  34277. _this.handleMasterPlaylist(response, stats, context, networkDetails);
  34278. }
  34279. },
  34280. onError: function onError(response, context, networkDetails, stats) {
  34281. _this.handleNetworkError(context, networkDetails, false, response, stats);
  34282. },
  34283. onTimeout: function onTimeout(stats, context, networkDetails) {
  34284. _this.handleNetworkError(context, networkDetails, true, undefined, stats);
  34285. }
  34286. };
  34287. // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
  34288. loader.load(context, loaderConfig, loaderCallbacks);
  34289. };
  34290. _proto.checkAutostartLoad = function checkAutostartLoad() {
  34291. if (!this.hls) {
  34292. return;
  34293. }
  34294. var _this$hls = this.hls,
  34295. _this$hls$config = _this$hls.config,
  34296. autoStartLoad = _this$hls$config.autoStartLoad,
  34297. startPosition = _this$hls$config.startPosition,
  34298. forceStartLoad = _this$hls.forceStartLoad;
  34299. if (autoStartLoad || forceStartLoad) {
  34300. this.hls.logger.log((autoStartLoad ? 'auto' : 'force') + " startLoad with configured startPosition " + startPosition);
  34301. this.hls.startLoad(startPosition);
  34302. }
  34303. };
  34304. _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
  34305. var hls = this.hls;
  34306. var string = response.data;
  34307. var url = getResponseUrl(response, context);
  34308. var parsedResult = M3U8Parser.parseMasterPlaylist(string, url);
  34309. if (parsedResult.playlistParsingError) {
  34310. this.handleManifestParsingError(response, context, parsedResult.playlistParsingError, networkDetails, stats);
  34311. return;
  34312. }
  34313. var contentSteering = parsedResult.contentSteering,
  34314. levels = parsedResult.levels,
  34315. sessionData = parsedResult.sessionData,
  34316. sessionKeys = parsedResult.sessionKeys,
  34317. startTimeOffset = parsedResult.startTimeOffset,
  34318. variableList = parsedResult.variableList;
  34319. this.variableList = variableList;
  34320. var _M3U8Parser$parseMast = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult),
  34321. _M3U8Parser$parseMast2 = _M3U8Parser$parseMast.AUDIO,
  34322. audioTracks = _M3U8Parser$parseMast2 === void 0 ? [] : _M3U8Parser$parseMast2,
  34323. subtitles = _M3U8Parser$parseMast.SUBTITLES,
  34324. captions = _M3U8Parser$parseMast['CLOSED-CAPTIONS'];
  34325. if (audioTracks.length) {
  34326. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  34327. var embeddedAudioFound = audioTracks.some(function (audioTrack) {
  34328. return !audioTrack.url;
  34329. });
  34330. // if no embedded audio track defined, but audio codec signaled in quality level,
  34331. // we need to signal this main audio track this could happen with playlists with
  34332. // alt audio rendition in which quality levels (main)
  34333. // contains both audio+video. but with mixed audio track not signaled
  34334. if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  34335. this.hls.logger.log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
  34336. audioTracks.unshift({
  34337. type: 'main',
  34338. name: 'main',
  34339. groupId: 'main',
  34340. default: false,
  34341. autoselect: false,
  34342. forced: false,
  34343. id: -1,
  34344. attrs: new AttrList({}),
  34345. bitrate: 0,
  34346. url: ''
  34347. });
  34348. }
  34349. }
  34350. hls.trigger(Events.MANIFEST_LOADED, {
  34351. levels: levels,
  34352. audioTracks: audioTracks,
  34353. subtitles: subtitles,
  34354. captions: captions,
  34355. contentSteering: contentSteering,
  34356. url: url,
  34357. stats: stats,
  34358. networkDetails: networkDetails,
  34359. sessionData: sessionData,
  34360. sessionKeys: sessionKeys,
  34361. startTimeOffset: startTimeOffset,
  34362. variableList: variableList
  34363. });
  34364. };
  34365. _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails, loader) {
  34366. var hls = this.hls;
  34367. var id = context.id,
  34368. level = context.level,
  34369. type = context.type;
  34370. var url = getResponseUrl(response, context);
  34371. var levelId = isFiniteNumber(level) ? level : isFiniteNumber(id) ? id : 0;
  34372. var levelType = mapContextToLevelType(context);
  34373. var levelDetails = M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, 0, this.variableList);
  34374. // We have done our first request (Manifest-type) and receive
  34375. // not a master playlist but a chunk-list (track/level)
  34376. // We fire the manifest-loaded event anyway with the parsed level-details
  34377. // by creating a single-level structure for it.
  34378. if (type === PlaylistContextType.MANIFEST) {
  34379. var singleLevel = {
  34380. attrs: new AttrList({}),
  34381. bitrate: 0,
  34382. details: levelDetails,
  34383. name: '',
  34384. url: url
  34385. };
  34386. levelDetails.requestScheduled = stats.loading.start + computeReloadInterval(levelDetails, 0);
  34387. hls.trigger(Events.MANIFEST_LOADED, {
  34388. levels: [singleLevel],
  34389. audioTracks: [],
  34390. url: url,
  34391. stats: stats,
  34392. networkDetails: networkDetails,
  34393. sessionData: null,
  34394. sessionKeys: null,
  34395. contentSteering: null,
  34396. startTimeOffset: null,
  34397. variableList: null
  34398. });
  34399. }
  34400. // save parsing time
  34401. stats.parsing.end = performance.now();
  34402. // extend the context with the new levelDetails property
  34403. context.levelDetails = levelDetails;
  34404. this.handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader);
  34405. };
  34406. _proto.handleManifestParsingError = function handleManifestParsingError(response, context, error, networkDetails, stats) {
  34407. this.hls.trigger(Events.ERROR, {
  34408. type: ErrorTypes.NETWORK_ERROR,
  34409. details: ErrorDetails.MANIFEST_PARSING_ERROR,
  34410. fatal: context.type === PlaylistContextType.MANIFEST,
  34411. url: response.url,
  34412. err: error,
  34413. error: error,
  34414. reason: error.message,
  34415. response: response,
  34416. context: context,
  34417. networkDetails: networkDetails,
  34418. stats: stats
  34419. });
  34420. };
  34421. _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response, stats) {
  34422. if (timeout === void 0) {
  34423. timeout = false;
  34424. }
  34425. var message = "A network " + (timeout ? 'timeout' : 'error' + (response ? ' (status ' + response.code + ')' : '')) + " occurred while loading " + context.type;
  34426. if (context.type === PlaylistContextType.LEVEL) {
  34427. message += ": " + context.level + " id: " + context.id;
  34428. } else if (context.type === PlaylistContextType.AUDIO_TRACK || context.type === PlaylistContextType.SUBTITLE_TRACK) {
  34429. message += " id: " + context.id + " group-id: \"" + context.groupId + "\"";
  34430. }
  34431. var error = new Error(message);
  34432. this.hls.logger.warn("[playlist-loader]: " + message);
  34433. var details = ErrorDetails.UNKNOWN;
  34434. var fatal = false;
  34435. var loader = this.getInternalLoader(context);
  34436. switch (context.type) {
  34437. case PlaylistContextType.MANIFEST:
  34438. details = timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR;
  34439. fatal = true;
  34440. break;
  34441. case PlaylistContextType.LEVEL:
  34442. details = timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR;
  34443. fatal = false;
  34444. break;
  34445. case PlaylistContextType.AUDIO_TRACK:
  34446. details = timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;
  34447. fatal = false;
  34448. break;
  34449. case PlaylistContextType.SUBTITLE_TRACK:
  34450. details = timeout ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT : ErrorDetails.SUBTITLE_LOAD_ERROR;
  34451. fatal = false;
  34452. break;
  34453. }
  34454. if (loader) {
  34455. this.resetInternalLoader(context.type);
  34456. }
  34457. var errorData = {
  34458. type: ErrorTypes.NETWORK_ERROR,
  34459. details: details,
  34460. fatal: fatal,
  34461. url: context.url,
  34462. loader: loader,
  34463. context: context,
  34464. error: error,
  34465. networkDetails: networkDetails,
  34466. stats: stats
  34467. };
  34468. if (response) {
  34469. var url = (networkDetails == null ? void 0 : networkDetails.url) || context.url;
  34470. errorData.response = _objectSpread2({
  34471. url: url,
  34472. data: undefined
  34473. }, response);
  34474. }
  34475. this.hls.trigger(Events.ERROR, errorData);
  34476. };
  34477. _proto.handlePlaylistLoaded = function handlePlaylistLoaded(levelDetails, response, stats, context, networkDetails, loader) {
  34478. var hls = this.hls;
  34479. var type = context.type,
  34480. level = context.level,
  34481. id = context.id,
  34482. groupId = context.groupId,
  34483. deliveryDirectives = context.deliveryDirectives;
  34484. var url = getResponseUrl(response, context);
  34485. var parent = mapContextToLevelType(context);
  34486. var levelIndex = typeof context.level === 'number' && parent === PlaylistLevelType.MAIN ? level : undefined;
  34487. if (!levelDetails.fragments.length) {
  34488. var _error = levelDetails.playlistParsingError = new Error('No Segments found in Playlist');
  34489. hls.trigger(Events.ERROR, {
  34490. type: ErrorTypes.NETWORK_ERROR,
  34491. details: ErrorDetails.LEVEL_EMPTY_ERROR,
  34492. fatal: false,
  34493. url: url,
  34494. error: _error,
  34495. reason: _error.message,
  34496. response: response,
  34497. context: context,
  34498. level: levelIndex,
  34499. parent: parent,
  34500. networkDetails: networkDetails,
  34501. stats: stats
  34502. });
  34503. return;
  34504. }
  34505. if (!levelDetails.targetduration) {
  34506. levelDetails.playlistParsingError = new Error('Missing Target Duration');
  34507. }
  34508. var error = levelDetails.playlistParsingError;
  34509. if (error) {
  34510. this.hls.logger.warn(error);
  34511. if (!hls.config.ignorePlaylistParsingErrors) {
  34512. hls.trigger(Events.ERROR, {
  34513. type: ErrorTypes.NETWORK_ERROR,
  34514. details: ErrorDetails.LEVEL_PARSING_ERROR,
  34515. fatal: false,
  34516. url: url,
  34517. error: error,
  34518. reason: error.message,
  34519. response: response,
  34520. context: context,
  34521. level: levelIndex,
  34522. parent: parent,
  34523. networkDetails: networkDetails,
  34524. stats: stats
  34525. });
  34526. return;
  34527. }
  34528. levelDetails.playlistParsingError = null;
  34529. }
  34530. if (levelDetails.live && loader) {
  34531. if (loader.getCacheAge) {
  34532. levelDetails.ageHeader = loader.getCacheAge() || 0;
  34533. }
  34534. if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
  34535. levelDetails.ageHeader = 0;
  34536. }
  34537. }
  34538. switch (type) {
  34539. case PlaylistContextType.MANIFEST:
  34540. case PlaylistContextType.LEVEL:
  34541. hls.trigger(Events.LEVEL_LOADED, {
  34542. details: levelDetails,
  34543. levelInfo: context.levelOrTrack || hls.levels[0],
  34544. level: levelIndex || 0,
  34545. id: id || 0,
  34546. stats: stats,
  34547. networkDetails: networkDetails,
  34548. deliveryDirectives: deliveryDirectives,
  34549. withoutMultiVariant: type === PlaylistContextType.MANIFEST
  34550. });
  34551. break;
  34552. case PlaylistContextType.AUDIO_TRACK:
  34553. hls.trigger(Events.AUDIO_TRACK_LOADED, {
  34554. details: levelDetails,
  34555. track: context.levelOrTrack,
  34556. id: id || 0,
  34557. groupId: groupId || '',
  34558. stats: stats,
  34559. networkDetails: networkDetails,
  34560. deliveryDirectives: deliveryDirectives
  34561. });
  34562. break;
  34563. case PlaylistContextType.SUBTITLE_TRACK:
  34564. hls.trigger(Events.SUBTITLE_TRACK_LOADED, {
  34565. details: levelDetails,
  34566. track: context.levelOrTrack,
  34567. id: id || 0,
  34568. groupId: groupId || '',
  34569. stats: stats,
  34570. networkDetails: networkDetails,
  34571. deliveryDirectives: deliveryDirectives
  34572. });
  34573. break;
  34574. }
  34575. };
  34576. return PlaylistLoader;
  34577. }();
  34578. /**
  34579. * The `Hls` class is the core of the HLS.js library used to instantiate player instances.
  34580. * @public
  34581. */
  34582. var Hls = /*#__PURE__*/function () {
  34583. /**
  34584. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  34585. * @param userConfig - Configuration options applied over `Hls.DefaultConfig`
  34586. */
  34587. function Hls(userConfig) {
  34588. if (userConfig === void 0) {
  34589. userConfig = {};
  34590. }
  34591. /**
  34592. * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.
  34593. */
  34594. this.config = void 0;
  34595. /**
  34596. * The configuration object provided on player instantiation.
  34597. */
  34598. this.userConfig = void 0;
  34599. /**
  34600. * The logger functions used by this player instance, configured on player instantiation.
  34601. */
  34602. this.logger = void 0;
  34603. this.coreComponents = void 0;
  34604. this.networkControllers = void 0;
  34605. this._emitter = new EventEmitter();
  34606. this._autoLevelCapping = -1;
  34607. this._maxHdcpLevel = null;
  34608. this.abrController = void 0;
  34609. this.bufferController = void 0;
  34610. this.capLevelController = void 0;
  34611. this.latencyController = void 0;
  34612. this.levelController = void 0;
  34613. this.streamController = void 0;
  34614. this.audioStreamController = void 0;
  34615. this.subtititleStreamController = void 0;
  34616. this.audioTrackController = void 0;
  34617. this.subtitleTrackController = void 0;
  34618. this.interstitialsController = void 0;
  34619. this.gapController = void 0;
  34620. this.emeController = void 0;
  34621. this.cmcdController = void 0;
  34622. this._media = null;
  34623. this._url = null;
  34624. this._sessionId = void 0;
  34625. this.triggeringException = void 0;
  34626. this.started = false;
  34627. var logger = this.logger = enableLogs(userConfig.debug || false, 'Hls instance', userConfig.assetPlayerId);
  34628. var config = this.config = mergeConfig(Hls.DefaultConfig, userConfig, logger);
  34629. this.userConfig = userConfig;
  34630. if (config.progressive) {
  34631. enableStreamingMode(config, logger);
  34632. }
  34633. // core controllers and network loaders
  34634. var _AbrController = config.abrController,
  34635. _BufferController = config.bufferController,
  34636. _CapLevelController = config.capLevelController,
  34637. _ErrorController = config.errorController,
  34638. _FpsController = config.fpsController;
  34639. var errorController = new _ErrorController(this);
  34640. var abrController = this.abrController = new _AbrController(this);
  34641. // FragmentTracker must be defined before StreamController because the order of event handling is important
  34642. var fragmentTracker = new FragmentTracker(this);
  34643. var _InterstitialsController = config.interstitialsController;
  34644. var interstitialsController = _InterstitialsController ? this.interstitialsController = new _InterstitialsController(this, Hls) : null;
  34645. var bufferController = this.bufferController = new _BufferController(this, fragmentTracker);
  34646. var capLevelController = this.capLevelController = new _CapLevelController(this);
  34647. var fpsController = new _FpsController(this);
  34648. var playListLoader = new PlaylistLoader(this);
  34649. var _ContentSteeringController = config.contentSteeringController;
  34650. // Instantiate ConentSteeringController before LevelController to receive Multivariant Playlist events first
  34651. var contentSteering = _ContentSteeringController ? new _ContentSteeringController(this) : null;
  34652. var levelController = this.levelController = new LevelController(this, contentSteering);
  34653. var id3TrackController = new ID3TrackController(this);
  34654. var keyLoader = new KeyLoader(this.config);
  34655. var streamController = this.streamController = new StreamController(this, fragmentTracker, keyLoader);
  34656. var gapController = this.gapController = new GapController(this, fragmentTracker);
  34657. // Cap level controller uses streamController to flush the buffer
  34658. capLevelController.setStreamController(streamController);
  34659. // fpsController uses streamController to switch when frames are being dropped
  34660. fpsController.setStreamController(streamController);
  34661. var networkControllers = [playListLoader, levelController, streamController];
  34662. if (interstitialsController) {
  34663. networkControllers.splice(1, 0, interstitialsController);
  34664. }
  34665. if (contentSteering) {
  34666. networkControllers.splice(1, 0, contentSteering);
  34667. }
  34668. this.networkControllers = networkControllers;
  34669. var coreComponents = [abrController, bufferController, gapController, capLevelController, fpsController, id3TrackController, fragmentTracker];
  34670. this.audioTrackController = this.createController(config.audioTrackController, networkControllers);
  34671. var AudioStreamControllerClass = config.audioStreamController;
  34672. if (AudioStreamControllerClass) {
  34673. networkControllers.push(this.audioStreamController = new AudioStreamControllerClass(this, fragmentTracker, keyLoader));
  34674. }
  34675. // Instantiate subtitleTrackController before SubtitleStreamController to receive level events first
  34676. this.subtitleTrackController = this.createController(config.subtitleTrackController, networkControllers);
  34677. var SubtitleStreamControllerClass = config.subtitleStreamController;
  34678. if (SubtitleStreamControllerClass) {
  34679. networkControllers.push(this.subtititleStreamController = new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader));
  34680. }
  34681. this.createController(config.timelineController, coreComponents);
  34682. keyLoader.emeController = this.emeController = this.createController(config.emeController, coreComponents);
  34683. this.cmcdController = this.createController(config.cmcdController, coreComponents);
  34684. this.latencyController = this.createController(LatencyController, coreComponents);
  34685. this.coreComponents = coreComponents;
  34686. // Error controller handles errors before and after all other controllers
  34687. // This listener will be invoked after all other controllers error listeners
  34688. networkControllers.push(errorController);
  34689. var onErrorOut = errorController.onErrorOut;
  34690. if (typeof onErrorOut === 'function') {
  34691. this.on(Events.ERROR, onErrorOut, errorController);
  34692. }
  34693. // Autostart load handler
  34694. this.on(Events.MANIFEST_LOADED, playListLoader.onManifestLoaded, playListLoader);
  34695. }
  34696. /**
  34697. * Check if the required MediaSource Extensions are available.
  34698. */
  34699. Hls.isMSESupported = function isMSESupported$1() {
  34700. return isMSESupported();
  34701. }
  34702. /**
  34703. * Check if MediaSource Extensions are available and isTypeSupported checks pass for any baseline codecs.
  34704. */;
  34705. Hls.isSupported = function isSupported$1() {
  34706. return isSupported();
  34707. }
  34708. /**
  34709. * Get the MediaSource global used for MSE playback (ManagedMediaSource, MediaSource, or WebKitMediaSource).
  34710. */;
  34711. Hls.getMediaSource = function getMediaSource$1() {
  34712. return getMediaSource();
  34713. };
  34714. var _proto = Hls.prototype;
  34715. _proto.createController = function createController(ControllerClass, components) {
  34716. if (ControllerClass) {
  34717. var controllerInstance = new ControllerClass(this);
  34718. if (components) {
  34719. components.push(controllerInstance);
  34720. }
  34721. return controllerInstance;
  34722. }
  34723. return null;
  34724. }
  34725. // Delegate the EventEmitter through the public API of Hls.js
  34726. ;
  34727. _proto.on = function on(event, listener, context) {
  34728. if (context === void 0) {
  34729. context = this;
  34730. }
  34731. this._emitter.on(event, listener, context);
  34732. };
  34733. _proto.once = function once(event, listener, context) {
  34734. if (context === void 0) {
  34735. context = this;
  34736. }
  34737. this._emitter.once(event, listener, context);
  34738. };
  34739. _proto.removeAllListeners = function removeAllListeners(event) {
  34740. this._emitter.removeAllListeners(event);
  34741. };
  34742. _proto.off = function off(event, listener, context, once) {
  34743. if (context === void 0) {
  34744. context = this;
  34745. }
  34746. this._emitter.off(event, listener, context, once);
  34747. };
  34748. _proto.listeners = function listeners(event) {
  34749. return this._emitter.listeners(event);
  34750. };
  34751. _proto.emit = function emit(event, name, eventObject) {
  34752. return this._emitter.emit(event, name, eventObject);
  34753. };
  34754. _proto.trigger = function trigger(event, eventObject) {
  34755. if (this.config.debug) {
  34756. return this.emit(event, event, eventObject);
  34757. } else {
  34758. try {
  34759. return this.emit(event, event, eventObject);
  34760. } catch (error) {
  34761. this.logger.error('An internal error happened while handling event ' + event + '. Error message: "' + error.message + '". Here is a stacktrace:', error);
  34762. // Prevent recursion in error event handlers that throw #5497
  34763. if (!this.triggeringException) {
  34764. this.triggeringException = true;
  34765. var fatal = event === Events.ERROR;
  34766. this.trigger(Events.ERROR, {
  34767. type: ErrorTypes.OTHER_ERROR,
  34768. details: ErrorDetails.INTERNAL_EXCEPTION,
  34769. fatal: fatal,
  34770. event: event,
  34771. error: error
  34772. });
  34773. this.triggeringException = false;
  34774. }
  34775. }
  34776. }
  34777. return false;
  34778. };
  34779. _proto.listenerCount = function listenerCount(event) {
  34780. return this._emitter.listenerCount(event);
  34781. }
  34782. /**
  34783. * Dispose of the instance
  34784. */;
  34785. _proto.destroy = function destroy() {
  34786. this.logger.log('destroy');
  34787. this.trigger(Events.DESTROYING, undefined);
  34788. this.detachMedia();
  34789. this.removeAllListeners();
  34790. this._autoLevelCapping = -1;
  34791. this._url = null;
  34792. this.networkControllers.forEach(function (component) {
  34793. return component.destroy();
  34794. });
  34795. this.networkControllers.length = 0;
  34796. this.coreComponents.forEach(function (component) {
  34797. return component.destroy();
  34798. });
  34799. this.coreComponents.length = 0;
  34800. // Remove any references that could be held in config options or callbacks
  34801. var config = this.config;
  34802. config.xhrSetup = config.fetchSetup = undefined;
  34803. // @ts-ignore
  34804. this.userConfig = null;
  34805. }
  34806. /**
  34807. * Attaches Hls.js to a media element
  34808. */;
  34809. _proto.attachMedia = function attachMedia(data) {
  34810. if (!data || 'media' in data && !data.media) {
  34811. var error = new Error("attachMedia failed: invalid argument (" + data + ")");
  34812. this.trigger(Events.ERROR, {
  34813. type: ErrorTypes.OTHER_ERROR,
  34814. details: ErrorDetails.ATTACH_MEDIA_ERROR,
  34815. fatal: true,
  34816. error: error
  34817. });
  34818. return;
  34819. }
  34820. this.logger.log("attachMedia");
  34821. if (this._media) {
  34822. this.logger.warn("media must be detached before attaching");
  34823. this.detachMedia();
  34824. }
  34825. var attachMediaSource = 'media' in data;
  34826. var media = attachMediaSource ? data.media : data;
  34827. var attachingData = attachMediaSource ? data : {
  34828. media: media
  34829. };
  34830. this._media = media;
  34831. this.trigger(Events.MEDIA_ATTACHING, attachingData);
  34832. }
  34833. /**
  34834. * Detach Hls.js from the media
  34835. */;
  34836. _proto.detachMedia = function detachMedia() {
  34837. this.logger.log('detachMedia');
  34838. this.trigger(Events.MEDIA_DETACHING, {});
  34839. this._media = null;
  34840. }
  34841. /**
  34842. * Detach HTMLMediaElement, MediaSource, and SourceBuffers without reset, for attaching to another instance
  34843. */;
  34844. _proto.transferMedia = function transferMedia() {
  34845. this._media = null;
  34846. var transferMedia = this.bufferController.transferMedia();
  34847. this.trigger(Events.MEDIA_DETACHING, {
  34848. transferMedia: transferMedia
  34849. });
  34850. return transferMedia;
  34851. }
  34852. /**
  34853. * Set the source URL. Can be relative or absolute.
  34854. */;
  34855. _proto.loadSource = function loadSource(url) {
  34856. this.stopLoad();
  34857. var media = this.media;
  34858. var loadedSource = this._url;
  34859. var loadingSource = this._url = urlToolkitExports.buildAbsoluteURL(self.location.href, url, {
  34860. alwaysNormalize: true
  34861. });
  34862. this._autoLevelCapping = -1;
  34863. this._maxHdcpLevel = null;
  34864. this.logger.log("loadSource:" + loadingSource);
  34865. if (media && loadedSource && (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())) {
  34866. // Remove and re-create MediaSource
  34867. this.detachMedia();
  34868. this.attachMedia(media);
  34869. }
  34870. // when attaching to a source URL, trigger a playlist load
  34871. this.trigger(Events.MANIFEST_LOADING, {
  34872. url: url
  34873. });
  34874. }
  34875. /**
  34876. * Gets the currently loaded URL
  34877. */;
  34878. /**
  34879. * Start loading data from the stream source.
  34880. * Depending on default config, client starts loading automatically when a source is set.
  34881. *
  34882. * @param startPosition - Set the start position to stream from.
  34883. * Defaults to -1 (None: starts from earliest point)
  34884. */
  34885. _proto.startLoad = function startLoad(startPosition, skipSeekToStartPosition) {
  34886. if (startPosition === void 0) {
  34887. startPosition = -1;
  34888. }
  34889. this.logger.log("startLoad(" + (startPosition + (skipSeekToStartPosition ? ', <skip seek to start>' : '')) + ")");
  34890. this.started = true;
  34891. this.resumeBuffering();
  34892. for (var i = 0; i < this.networkControllers.length; i++) {
  34893. this.networkControllers[i].startLoad(startPosition, skipSeekToStartPosition);
  34894. if (!this.started || !this.networkControllers) {
  34895. break;
  34896. }
  34897. }
  34898. }
  34899. /**
  34900. * Stop loading of any stream data.
  34901. */;
  34902. _proto.stopLoad = function stopLoad() {
  34903. this.logger.log('stopLoad');
  34904. this.started = false;
  34905. for (var i = 0; i < this.networkControllers.length; i++) {
  34906. this.networkControllers[i].stopLoad();
  34907. if (this.started || !this.networkControllers) {
  34908. break;
  34909. }
  34910. }
  34911. }
  34912. /**
  34913. * Returns whether loading, toggled with `startLoad()` and `stopLoad()`, is active or not`.
  34914. */;
  34915. /**
  34916. * Resumes stream controller segment loading after `pauseBuffering` has been called.
  34917. */
  34918. _proto.resumeBuffering = function resumeBuffering() {
  34919. if (!this.bufferingEnabled) {
  34920. this.logger.log("resume buffering");
  34921. this.networkControllers.forEach(function (controller) {
  34922. if (controller.resumeBuffering) {
  34923. controller.resumeBuffering();
  34924. }
  34925. });
  34926. }
  34927. }
  34928. /**
  34929. * Prevents stream controller from loading new segments until `resumeBuffering` is called.
  34930. * This allows for media buffering to be paused without interupting playlist loading.
  34931. */;
  34932. _proto.pauseBuffering = function pauseBuffering() {
  34933. if (this.bufferingEnabled) {
  34934. this.logger.log("pause buffering");
  34935. this.networkControllers.forEach(function (controller) {
  34936. if (controller.pauseBuffering) {
  34937. controller.pauseBuffering();
  34938. }
  34939. });
  34940. }
  34941. };
  34942. /**
  34943. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  34944. */
  34945. _proto.swapAudioCodec = function swapAudioCodec() {
  34946. this.logger.log('swapAudioCodec');
  34947. this.streamController.swapAudioCodec();
  34948. }
  34949. /**
  34950. * When the media-element fails, this allows to detach and then re-attach it
  34951. * as one call (convenience method).
  34952. *
  34953. * Automatic recovery of media-errors by this process is configurable.
  34954. */;
  34955. _proto.recoverMediaError = function recoverMediaError() {
  34956. this.logger.log('recoverMediaError');
  34957. var media = this._media;
  34958. var time = media == null ? void 0 : media.currentTime;
  34959. this.detachMedia();
  34960. if (media) {
  34961. this.attachMedia(media);
  34962. if (time) {
  34963. this.startLoad(time);
  34964. }
  34965. }
  34966. };
  34967. _proto.removeLevel = function removeLevel(levelIndex) {
  34968. this.levelController.removeLevel(levelIndex);
  34969. }
  34970. /**
  34971. * @returns a UUID for this player instance
  34972. */;
  34973. /**
  34974. * Find and select the best matching audio track, making a level switch when a Group change is necessary.
  34975. * Updates `hls.config.audioPreference`. Returns the selected track, or null when no matching track is found.
  34976. */
  34977. _proto.setAudioOption = function setAudioOption(audioOption) {
  34978. var _this$audioTrackContr;
  34979. return ((_this$audioTrackContr = this.audioTrackController) == null ? void 0 : _this$audioTrackContr.setAudioOption(audioOption)) || null;
  34980. }
  34981. /**
  34982. * Find and select the best matching subtitle track, making a level switch when a Group change is necessary.
  34983. * Updates `hls.config.subtitlePreference`. Returns the selected track, or null when no matching track is found.
  34984. */;
  34985. _proto.setSubtitleOption = function setSubtitleOption(subtitleOption) {
  34986. var _this$subtitleTrackCo;
  34987. return ((_this$subtitleTrackCo = this.subtitleTrackController) == null ? void 0 : _this$subtitleTrackCo.setSubtitleOption(subtitleOption)) || null;
  34988. }
  34989. /**
  34990. * Get the complete list of audio tracks across all media groups
  34991. */;
  34992. /**
  34993. * returns mediaCapabilities.decodingInfo for a variant/rendition
  34994. */
  34995. _proto.getMediaDecodingInfo = function getMediaDecodingInfo(level, audioTracks) {
  34996. if (audioTracks === void 0) {
  34997. audioTracks = this.allAudioTracks;
  34998. }
  34999. var audioTracksByGroup = getAudioTracksByGroup(audioTracks);
  35000. return getMediaDecodingInfoPromise(level, audioTracksByGroup, navigator.mediaCapabilities);
  35001. };
  35002. return _createClass(Hls, [{
  35003. key: "url",
  35004. get: function get() {
  35005. return this._url;
  35006. }
  35007. /**
  35008. * Whether or not enough has been buffered to seek to start position or use `media.currentTime` to determine next load position
  35009. */
  35010. }, {
  35011. key: "hasEnoughToStart",
  35012. get: function get() {
  35013. return this.streamController.hasEnoughToStart;
  35014. }
  35015. /**
  35016. * Get the startPosition set on startLoad(position) or on autostart with config.startPosition
  35017. */
  35018. }, {
  35019. key: "startPosition",
  35020. get: function get() {
  35021. return this.streamController.startPositionValue;
  35022. }
  35023. }, {
  35024. key: "loadingEnabled",
  35025. get: function get() {
  35026. return this.started;
  35027. }
  35028. /**
  35029. * Returns state of fragment loading toggled by calling `pauseBuffering()` and `resumeBuffering()`.
  35030. */
  35031. }, {
  35032. key: "bufferingEnabled",
  35033. get: function get() {
  35034. return this.streamController.bufferingEnabled;
  35035. }
  35036. }, {
  35037. key: "inFlightFragments",
  35038. get: function get() {
  35039. var _inFlightData;
  35040. var inFlightData = (_inFlightData = {}, _inFlightData[PlaylistLevelType.MAIN] = this.streamController.inFlightFrag, _inFlightData);
  35041. if (this.audioStreamController) {
  35042. inFlightData[PlaylistLevelType.AUDIO] = this.audioStreamController.inFlightFrag;
  35043. }
  35044. if (this.subtititleStreamController) {
  35045. inFlightData[PlaylistLevelType.SUBTITLE] = this.subtititleStreamController.inFlightFrag;
  35046. }
  35047. return inFlightData;
  35048. }
  35049. }, {
  35050. key: "sessionId",
  35051. get: function get() {
  35052. var _sessionId = this._sessionId;
  35053. if (!_sessionId) {
  35054. _sessionId = this._sessionId = uuid();
  35055. }
  35056. return _sessionId;
  35057. }
  35058. /**
  35059. * @returns an array of levels (variants) sorted by HDCP-LEVEL, RESOLUTION (height), FRAME-RATE, CODECS, VIDEO-RANGE, and BANDWIDTH
  35060. */
  35061. }, {
  35062. key: "levels",
  35063. get: function get() {
  35064. var levels = this.levelController.levels;
  35065. return levels ? levels : [];
  35066. }
  35067. /**
  35068. * @returns LevelDetails of last loaded level (variant) or `null` prior to loading a media playlist.
  35069. */
  35070. }, {
  35071. key: "latestLevelDetails",
  35072. get: function get() {
  35073. return this.streamController.getLevelDetails() || null;
  35074. }
  35075. /**
  35076. * @returns Level object of selected level (variant) or `null` prior to selecting a level or once the level is removed.
  35077. */
  35078. }, {
  35079. key: "loadLevelObj",
  35080. get: function get() {
  35081. return this.levelController.loadLevelObj;
  35082. }
  35083. /**
  35084. * Index of quality level (variant) currently played
  35085. */
  35086. }, {
  35087. key: "currentLevel",
  35088. get: function get() {
  35089. return this.streamController.currentLevel;
  35090. }
  35091. /**
  35092. * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.
  35093. */,
  35094. set: function set(newLevel) {
  35095. this.logger.log("set currentLevel:" + newLevel);
  35096. this.levelController.manualLevel = newLevel;
  35097. this.streamController.immediateLevelSwitch();
  35098. }
  35099. /**
  35100. * Index of next quality level loaded as scheduled by stream controller.
  35101. */
  35102. }, {
  35103. key: "nextLevel",
  35104. get: function get() {
  35105. return this.streamController.nextLevel;
  35106. }
  35107. /**
  35108. * Set quality level index for next loaded data.
  35109. * This will switch the video quality asap, without interrupting playback.
  35110. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  35111. * @param newLevel - Pass -1 for automatic level selection
  35112. */,
  35113. set: function set(newLevel) {
  35114. this.logger.log("set nextLevel:" + newLevel);
  35115. this.levelController.manualLevel = newLevel;
  35116. this.streamController.nextLevelSwitch();
  35117. }
  35118. /**
  35119. * Return the quality level of the currently or last (of none is loaded currently) segment
  35120. */
  35121. }, {
  35122. key: "loadLevel",
  35123. get: function get() {
  35124. return this.levelController.level;
  35125. }
  35126. /**
  35127. * Set quality level index for next loaded data in a conservative way.
  35128. * This will switch the quality without flushing, but interrupt current loading.
  35129. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  35130. * @param newLevel - Pass -1 for automatic level selection
  35131. */,
  35132. set: function set(newLevel) {
  35133. this.logger.log("set loadLevel:" + newLevel);
  35134. this.levelController.manualLevel = newLevel;
  35135. }
  35136. /**
  35137. * get next quality level loaded
  35138. */
  35139. }, {
  35140. key: "nextLoadLevel",
  35141. get: function get() {
  35142. return this.levelController.nextLoadLevel;
  35143. }
  35144. /**
  35145. * Set quality level of next loaded segment in a fully "non-destructive" way.
  35146. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  35147. */,
  35148. set: function set(level) {
  35149. this.levelController.nextLoadLevel = level;
  35150. }
  35151. /**
  35152. * Return "first level": like a default level, if not set,
  35153. * falls back to index of first level referenced in manifest
  35154. */
  35155. }, {
  35156. key: "firstLevel",
  35157. get: function get() {
  35158. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  35159. }
  35160. /**
  35161. * Sets "first-level", see getter.
  35162. */,
  35163. set: function set(newLevel) {
  35164. this.logger.log("set firstLevel:" + newLevel);
  35165. this.levelController.firstLevel = newLevel;
  35166. }
  35167. /**
  35168. * Return the desired start level for the first fragment that will be loaded.
  35169. * The default value of -1 indicates automatic start level selection.
  35170. * Setting hls.nextAutoLevel without setting a startLevel will result in
  35171. * the nextAutoLevel value being used for one fragment load.
  35172. */
  35173. }, {
  35174. key: "startLevel",
  35175. get: function get() {
  35176. var startLevel = this.levelController.startLevel;
  35177. if (startLevel === -1 && this.abrController.forcedAutoLevel > -1) {
  35178. return this.abrController.forcedAutoLevel;
  35179. }
  35180. return startLevel;
  35181. }
  35182. /**
  35183. * set start level (level of first fragment that will be played back)
  35184. * if not overrided by user, first level appearing in manifest will be used as start level
  35185. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  35186. * (determined from download of first segment)
  35187. */,
  35188. set: function set(newLevel) {
  35189. this.logger.log("set startLevel:" + newLevel);
  35190. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  35191. if (newLevel !== -1) {
  35192. newLevel = Math.max(newLevel, this.minAutoLevel);
  35193. }
  35194. this.levelController.startLevel = newLevel;
  35195. }
  35196. /**
  35197. * Whether level capping is enabled.
  35198. * Default value is set via `config.capLevelToPlayerSize`.
  35199. */
  35200. }, {
  35201. key: "capLevelToPlayerSize",
  35202. get: function get() {
  35203. return this.config.capLevelToPlayerSize;
  35204. }
  35205. /**
  35206. * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.
  35207. */,
  35208. set: function set(shouldStartCapping) {
  35209. var newCapLevelToPlayerSize = !!shouldStartCapping;
  35210. if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
  35211. if (newCapLevelToPlayerSize) {
  35212. this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
  35213. } else {
  35214. this.capLevelController.stopCapping();
  35215. this.autoLevelCapping = -1;
  35216. this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
  35217. }
  35218. this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
  35219. }
  35220. }
  35221. /**
  35222. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  35223. */
  35224. }, {
  35225. key: "autoLevelCapping",
  35226. get: function get() {
  35227. return this._autoLevelCapping;
  35228. }
  35229. /**
  35230. * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.
  35231. */,
  35232. set:
  35233. /**
  35234. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  35235. */
  35236. function set(newLevel) {
  35237. if (this._autoLevelCapping !== newLevel) {
  35238. this.logger.log("set autoLevelCapping:" + newLevel);
  35239. this._autoLevelCapping = newLevel;
  35240. this.levelController.checkMaxAutoUpdated();
  35241. }
  35242. }
  35243. }, {
  35244. key: "bandwidthEstimate",
  35245. get: function get() {
  35246. var bwEstimator = this.abrController.bwEstimator;
  35247. if (!bwEstimator) {
  35248. return NaN;
  35249. }
  35250. return bwEstimator.getEstimate();
  35251. },
  35252. set: function set(abrEwmaDefaultEstimate) {
  35253. this.abrController.resetEstimator(abrEwmaDefaultEstimate);
  35254. }
  35255. }, {
  35256. key: "abrEwmaDefaultEstimate",
  35257. get: function get() {
  35258. var bwEstimator = this.abrController.bwEstimator;
  35259. if (!bwEstimator) {
  35260. return NaN;
  35261. }
  35262. return bwEstimator.defaultEstimate;
  35263. }
  35264. /**
  35265. * get time to first byte estimate
  35266. * @type {number}
  35267. */
  35268. }, {
  35269. key: "ttfbEstimate",
  35270. get: function get() {
  35271. var bwEstimator = this.abrController.bwEstimator;
  35272. if (!bwEstimator) {
  35273. return NaN;
  35274. }
  35275. return bwEstimator.getEstimateTTFB();
  35276. }
  35277. }, {
  35278. key: "maxHdcpLevel",
  35279. get: function get() {
  35280. return this._maxHdcpLevel;
  35281. },
  35282. set: function set(value) {
  35283. if (isHdcpLevel(value) && this._maxHdcpLevel !== value) {
  35284. this._maxHdcpLevel = value;
  35285. this.levelController.checkMaxAutoUpdated();
  35286. }
  35287. }
  35288. /**
  35289. * True when automatic level selection enabled
  35290. */
  35291. }, {
  35292. key: "autoLevelEnabled",
  35293. get: function get() {
  35294. return this.levelController.manualLevel === -1;
  35295. }
  35296. /**
  35297. * Level set manually (if any)
  35298. */
  35299. }, {
  35300. key: "manualLevel",
  35301. get: function get() {
  35302. return this.levelController.manualLevel;
  35303. }
  35304. /**
  35305. * min level selectable in auto mode according to config.minAutoBitrate
  35306. */
  35307. }, {
  35308. key: "minAutoLevel",
  35309. get: function get() {
  35310. var levels = this.levels,
  35311. minAutoBitrate = this.config.minAutoBitrate;
  35312. if (!levels) return 0;
  35313. var len = levels.length;
  35314. for (var i = 0; i < len; i++) {
  35315. if (levels[i].maxBitrate >= minAutoBitrate) {
  35316. return i;
  35317. }
  35318. }
  35319. return 0;
  35320. }
  35321. /**
  35322. * max level selectable in auto mode according to autoLevelCapping
  35323. */
  35324. }, {
  35325. key: "maxAutoLevel",
  35326. get: function get() {
  35327. var levels = this.levels,
  35328. autoLevelCapping = this.autoLevelCapping,
  35329. maxHdcpLevel = this.maxHdcpLevel;
  35330. var maxAutoLevel;
  35331. if (autoLevelCapping === -1 && levels != null && levels.length) {
  35332. maxAutoLevel = levels.length - 1;
  35333. } else {
  35334. maxAutoLevel = autoLevelCapping;
  35335. }
  35336. if (maxHdcpLevel) {
  35337. for (var i = maxAutoLevel; i--;) {
  35338. var hdcpLevel = levels[i].attrs['HDCP-LEVEL'];
  35339. if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {
  35340. return i;
  35341. }
  35342. }
  35343. }
  35344. return maxAutoLevel;
  35345. }
  35346. }, {
  35347. key: "firstAutoLevel",
  35348. get: function get() {
  35349. return this.abrController.firstAutoLevel;
  35350. }
  35351. /**
  35352. * next automatically selected quality level
  35353. */
  35354. }, {
  35355. key: "nextAutoLevel",
  35356. get: function get() {
  35357. return this.abrController.nextAutoLevel;
  35358. }
  35359. /**
  35360. * this setter is used to force next auto level.
  35361. * this is useful to force a switch down in auto mode:
  35362. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  35363. * forced value is valid for one fragment. upon successful frag loading at forced level,
  35364. * this value will be resetted to -1 by ABR controller.
  35365. */,
  35366. set: function set(nextLevel) {
  35367. this.abrController.nextAutoLevel = nextLevel;
  35368. }
  35369. /**
  35370. * get the datetime value relative to media.currentTime for the active level Program Date Time if present
  35371. */
  35372. }, {
  35373. key: "playingDate",
  35374. get: function get() {
  35375. return this.streamController.currentProgramDateTime;
  35376. }
  35377. }, {
  35378. key: "mainForwardBufferInfo",
  35379. get: function get() {
  35380. return this.streamController.getMainFwdBufferInfo();
  35381. }
  35382. }, {
  35383. key: "maxBufferLength",
  35384. get: function get() {
  35385. return this.streamController.maxBufferLength;
  35386. }
  35387. }, {
  35388. key: "allAudioTracks",
  35389. get: function get() {
  35390. var audioTrackController = this.audioTrackController;
  35391. return audioTrackController ? audioTrackController.allAudioTracks : [];
  35392. }
  35393. /**
  35394. * Get the list of selectable audio tracks
  35395. */
  35396. }, {
  35397. key: "audioTracks",
  35398. get: function get() {
  35399. var audioTrackController = this.audioTrackController;
  35400. return audioTrackController ? audioTrackController.audioTracks : [];
  35401. }
  35402. /**
  35403. * index of the selected audio track (index in audio track lists)
  35404. */
  35405. }, {
  35406. key: "audioTrack",
  35407. get: function get() {
  35408. var audioTrackController = this.audioTrackController;
  35409. return audioTrackController ? audioTrackController.audioTrack : -1;
  35410. }
  35411. /**
  35412. * selects an audio track, based on its index in audio track lists
  35413. */,
  35414. set: function set(audioTrackId) {
  35415. var audioTrackController = this.audioTrackController;
  35416. if (audioTrackController) {
  35417. audioTrackController.audioTrack = audioTrackId;
  35418. }
  35419. }
  35420. /**
  35421. * get the complete list of subtitle tracks across all media groups
  35422. */
  35423. }, {
  35424. key: "allSubtitleTracks",
  35425. get: function get() {
  35426. var subtitleTrackController = this.subtitleTrackController;
  35427. return subtitleTrackController ? subtitleTrackController.allSubtitleTracks : [];
  35428. }
  35429. /**
  35430. * get alternate subtitle tracks list from playlist
  35431. */
  35432. }, {
  35433. key: "subtitleTracks",
  35434. get: function get() {
  35435. var subtitleTrackController = this.subtitleTrackController;
  35436. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  35437. }
  35438. /**
  35439. * index of the selected subtitle track (index in subtitle track lists)
  35440. */
  35441. }, {
  35442. key: "subtitleTrack",
  35443. get: function get() {
  35444. var subtitleTrackController = this.subtitleTrackController;
  35445. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  35446. },
  35447. set:
  35448. /**
  35449. * select an subtitle track, based on its index in subtitle track lists
  35450. */
  35451. function set(subtitleTrackId) {
  35452. var subtitleTrackController = this.subtitleTrackController;
  35453. if (subtitleTrackController) {
  35454. subtitleTrackController.subtitleTrack = subtitleTrackId;
  35455. }
  35456. }
  35457. /**
  35458. * Whether subtitle display is enabled or not
  35459. */
  35460. }, {
  35461. key: "media",
  35462. get: function get() {
  35463. return this._media;
  35464. }
  35465. }, {
  35466. key: "subtitleDisplay",
  35467. get: function get() {
  35468. var subtitleTrackController = this.subtitleTrackController;
  35469. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  35470. }
  35471. /**
  35472. * Enable/disable subtitle display rendering
  35473. */,
  35474. set: function set(value) {
  35475. var subtitleTrackController = this.subtitleTrackController;
  35476. if (subtitleTrackController) {
  35477. subtitleTrackController.subtitleDisplay = value;
  35478. }
  35479. }
  35480. /**
  35481. * get mode for Low-Latency HLS loading
  35482. */
  35483. }, {
  35484. key: "lowLatencyMode",
  35485. get: function get() {
  35486. return this.config.lowLatencyMode;
  35487. }
  35488. /**
  35489. * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
  35490. */,
  35491. set: function set(mode) {
  35492. this.config.lowLatencyMode = mode;
  35493. }
  35494. /**
  35495. * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
  35496. * @returns null prior to loading live Playlist
  35497. */
  35498. }, {
  35499. key: "liveSyncPosition",
  35500. get: function get() {
  35501. return this.latencyController.liveSyncPosition;
  35502. }
  35503. /**
  35504. * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
  35505. * @returns 0 before first playlist is loaded
  35506. */
  35507. }, {
  35508. key: "latency",
  35509. get: function get() {
  35510. return this.latencyController.latency;
  35511. }
  35512. /**
  35513. * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
  35514. * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
  35515. * @returns 0 before first playlist is loaded
  35516. */
  35517. }, {
  35518. key: "maxLatency",
  35519. get: function get() {
  35520. return this.latencyController.maxLatency;
  35521. }
  35522. /**
  35523. * target distance from the edge as calculated by the latency controller
  35524. */
  35525. }, {
  35526. key: "targetLatency",
  35527. get: function get() {
  35528. return this.latencyController.targetLatency;
  35529. },
  35530. set: function set(latency) {
  35531. this.latencyController.targetLatency = latency;
  35532. }
  35533. /**
  35534. * the rate at which the edge of the current live playlist is advancing or 1 if there is none
  35535. */
  35536. }, {
  35537. key: "drift",
  35538. get: function get() {
  35539. return this.latencyController.drift;
  35540. }
  35541. /**
  35542. * set to true when startLoad is called before MANIFEST_PARSED event
  35543. */
  35544. }, {
  35545. key: "forceStartLoad",
  35546. get: function get() {
  35547. return this.streamController.forceStartLoad;
  35548. }
  35549. /**
  35550. * ContentSteering pathways getter
  35551. */
  35552. }, {
  35553. key: "pathways",
  35554. get: function get() {
  35555. return this.levelController.pathways;
  35556. }
  35557. /**
  35558. * ContentSteering pathwayPriority getter/setter
  35559. */
  35560. }, {
  35561. key: "pathwayPriority",
  35562. get: function get() {
  35563. return this.levelController.pathwayPriority;
  35564. },
  35565. set: function set(pathwayPriority) {
  35566. this.levelController.pathwayPriority = pathwayPriority;
  35567. }
  35568. /**
  35569. * returns true when all SourceBuffers are buffered to the end
  35570. */
  35571. }, {
  35572. key: "bufferedToEnd",
  35573. get: function get() {
  35574. var _this$bufferControlle;
  35575. return !!((_this$bufferControlle = this.bufferController) != null && _this$bufferControlle.bufferedToEnd);
  35576. }
  35577. /**
  35578. * returns Interstitials Program Manager
  35579. */
  35580. }, {
  35581. key: "interstitialsManager",
  35582. get: function get() {
  35583. var _this$interstitialsCo;
  35584. return ((_this$interstitialsCo = this.interstitialsController) == null ? void 0 : _this$interstitialsCo.interstitialsManager) || null;
  35585. }
  35586. }], [{
  35587. key: "version",
  35588. get:
  35589. /**
  35590. * Get the video-dev/hls.js package version.
  35591. */
  35592. function get() {
  35593. return version;
  35594. }
  35595. }, {
  35596. key: "Events",
  35597. get: function get() {
  35598. return Events;
  35599. }
  35600. }, {
  35601. key: "MetadataSchema",
  35602. get: function get() {
  35603. return MetadataSchema;
  35604. }
  35605. }, {
  35606. key: "ErrorTypes",
  35607. get: function get() {
  35608. return ErrorTypes;
  35609. }
  35610. }, {
  35611. key: "ErrorDetails",
  35612. get: function get() {
  35613. return ErrorDetails;
  35614. }
  35615. /**
  35616. * Get the default configuration applied to new instances.
  35617. */
  35618. }, {
  35619. key: "DefaultConfig",
  35620. get: function get() {
  35621. if (!Hls.defaultConfig) {
  35622. return hlsDefaultConfig;
  35623. }
  35624. return Hls.defaultConfig;
  35625. }
  35626. /**
  35627. * Replace the default configuration applied to new instances.
  35628. */,
  35629. set: function set(defaultConfig) {
  35630. Hls.defaultConfig = defaultConfig;
  35631. }
  35632. }]);
  35633. }();
  35634. Hls.defaultConfig = void 0;
  35635. return Hls;
  35636. }));
  35637. })(false);
  35638. //# sourceMappingURL=hls.js.map