mux-mp4.js 255 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017
  1. /*! @name mux.js @version 6.3.0 @license Apache-2.0 */
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/window')) :
  4. typeof define === 'function' && define.amd ? define(['global/window'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.muxjs = factory(global.window));
  6. }(this, (function (window) { 'use strict';
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var window__default = /*#__PURE__*/_interopDefaultLegacy(window);
  9. var MAX_UINT32$1 = Math.pow(2, 32);
  10. var getUint64$3 = function getUint64(uint8) {
  11. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  12. var value;
  13. if (dv.getBigUint64) {
  14. value = dv.getBigUint64(0);
  15. if (value < Number.MAX_SAFE_INTEGER) {
  16. return Number(value);
  17. }
  18. return value;
  19. }
  20. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  21. };
  22. var numbers = {
  23. getUint64: getUint64$3,
  24. MAX_UINT32: MAX_UINT32$1
  25. };
  26. var MAX_UINT32 = numbers.MAX_UINT32;
  27. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
  28. (function () {
  29. var i;
  30. types = {
  31. avc1: [],
  32. // codingname
  33. avcC: [],
  34. btrt: [],
  35. dinf: [],
  36. dref: [],
  37. esds: [],
  38. ftyp: [],
  39. hdlr: [],
  40. mdat: [],
  41. mdhd: [],
  42. mdia: [],
  43. mfhd: [],
  44. minf: [],
  45. moof: [],
  46. moov: [],
  47. mp4a: [],
  48. // codingname
  49. mvex: [],
  50. mvhd: [],
  51. pasp: [],
  52. sdtp: [],
  53. smhd: [],
  54. stbl: [],
  55. stco: [],
  56. stsc: [],
  57. stsd: [],
  58. stsz: [],
  59. stts: [],
  60. styp: [],
  61. tfdt: [],
  62. tfhd: [],
  63. traf: [],
  64. trak: [],
  65. trun: [],
  66. trex: [],
  67. tkhd: [],
  68. vmhd: []
  69. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  70. // don't throw an error
  71. if (typeof Uint8Array === 'undefined') {
  72. return;
  73. }
  74. for (i in types) {
  75. if (types.hasOwnProperty(i)) {
  76. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  77. }
  78. }
  79. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  80. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  81. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  82. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  83. 0x00, 0x00, 0x00, // flags
  84. 0x00, 0x00, 0x00, 0x00, // pre_defined
  85. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  86. 0x00, 0x00, 0x00, 0x00, // reserved
  87. 0x00, 0x00, 0x00, 0x00, // reserved
  88. 0x00, 0x00, 0x00, 0x00, // reserved
  89. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  90. ]);
  91. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  92. 0x00, 0x00, 0x00, // flags
  93. 0x00, 0x00, 0x00, 0x00, // pre_defined
  94. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  95. 0x00, 0x00, 0x00, 0x00, // reserved
  96. 0x00, 0x00, 0x00, 0x00, // reserved
  97. 0x00, 0x00, 0x00, 0x00, // reserved
  98. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  99. ]);
  100. HDLR_TYPES = {
  101. video: VIDEO_HDLR,
  102. audio: AUDIO_HDLR
  103. };
  104. DREF = new Uint8Array([0x00, // version 0
  105. 0x00, 0x00, 0x00, // flags
  106. 0x00, 0x00, 0x00, 0x01, // entry_count
  107. 0x00, 0x00, 0x00, 0x0c, // entry_size
  108. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  109. 0x00, // version 0
  110. 0x00, 0x00, 0x01 // entry_flags
  111. ]);
  112. SMHD = new Uint8Array([0x00, // version
  113. 0x00, 0x00, 0x00, // flags
  114. 0x00, 0x00, // balance, 0 means centered
  115. 0x00, 0x00 // reserved
  116. ]);
  117. STCO = new Uint8Array([0x00, // version
  118. 0x00, 0x00, 0x00, // flags
  119. 0x00, 0x00, 0x00, 0x00 // entry_count
  120. ]);
  121. STSC = STCO;
  122. STSZ = new Uint8Array([0x00, // version
  123. 0x00, 0x00, 0x00, // flags
  124. 0x00, 0x00, 0x00, 0x00, // sample_size
  125. 0x00, 0x00, 0x00, 0x00 // sample_count
  126. ]);
  127. STTS = STCO;
  128. VMHD = new Uint8Array([0x00, // version
  129. 0x00, 0x00, 0x01, // flags
  130. 0x00, 0x00, // graphicsmode
  131. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  132. ]);
  133. })();
  134. box = function box(type) {
  135. var payload = [],
  136. size = 0,
  137. i,
  138. result,
  139. view;
  140. for (i = 1; i < arguments.length; i++) {
  141. payload.push(arguments[i]);
  142. }
  143. i = payload.length; // calculate the total size we need to allocate
  144. while (i--) {
  145. size += payload[i].byteLength;
  146. }
  147. result = new Uint8Array(size + 8);
  148. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  149. view.setUint32(0, result.byteLength);
  150. result.set(type, 4); // copy the payload into the result
  151. for (i = 0, size = 8; i < payload.length; i++) {
  152. result.set(payload[i], size);
  153. size += payload[i].byteLength;
  154. }
  155. return result;
  156. };
  157. dinf = function dinf() {
  158. return box(types.dinf, box(types.dref, DREF));
  159. };
  160. esds = function esds(track) {
  161. return box(types.esds, new Uint8Array([0x00, // version
  162. 0x00, 0x00, 0x00, // flags
  163. // ES_Descriptor
  164. 0x03, // tag, ES_DescrTag
  165. 0x19, // length
  166. 0x00, 0x00, // ES_ID
  167. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  168. // DecoderConfigDescriptor
  169. 0x04, // tag, DecoderConfigDescrTag
  170. 0x11, // length
  171. 0x40, // object type
  172. 0x15, // streamType
  173. 0x00, 0x06, 0x00, // bufferSizeDB
  174. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  175. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  176. // DecoderSpecificInfo
  177. 0x05, // tag, DecoderSpecificInfoTag
  178. 0x02, // length
  179. // ISO/IEC 14496-3, AudioSpecificConfig
  180. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  181. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  182. ]));
  183. };
  184. ftyp = function ftyp() {
  185. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  186. };
  187. hdlr = function hdlr(type) {
  188. return box(types.hdlr, HDLR_TYPES[type]);
  189. };
  190. mdat = function mdat(data) {
  191. return box(types.mdat, data);
  192. };
  193. mdhd = function mdhd(track) {
  194. var result = new Uint8Array([0x00, // version 0
  195. 0x00, 0x00, 0x00, // flags
  196. 0x00, 0x00, 0x00, 0x02, // creation_time
  197. 0x00, 0x00, 0x00, 0x03, // modification_time
  198. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  199. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  200. 0x55, 0xc4, // 'und' language (undetermined)
  201. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  202. // defined. The sample rate can be parsed out of an ADTS header, for
  203. // instance.
  204. if (track.samplerate) {
  205. result[12] = track.samplerate >>> 24 & 0xFF;
  206. result[13] = track.samplerate >>> 16 & 0xFF;
  207. result[14] = track.samplerate >>> 8 & 0xFF;
  208. result[15] = track.samplerate & 0xFF;
  209. }
  210. return box(types.mdhd, result);
  211. };
  212. mdia = function mdia(track) {
  213. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  214. };
  215. mfhd = function mfhd(sequenceNumber) {
  216. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  217. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  218. ]));
  219. };
  220. minf = function minf(track) {
  221. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  222. };
  223. moof = function moof(sequenceNumber, tracks) {
  224. var trackFragments = [],
  225. i = tracks.length; // build traf boxes for each track fragment
  226. while (i--) {
  227. trackFragments[i] = traf(tracks[i]);
  228. }
  229. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  230. };
  231. /**
  232. * Returns a movie box.
  233. * @param tracks {array} the tracks associated with this movie
  234. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  235. */
  236. moov = function moov(tracks) {
  237. var i = tracks.length,
  238. boxes = [];
  239. while (i--) {
  240. boxes[i] = trak(tracks[i]);
  241. }
  242. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  243. };
  244. mvex = function mvex(tracks) {
  245. var i = tracks.length,
  246. boxes = [];
  247. while (i--) {
  248. boxes[i] = trex(tracks[i]);
  249. }
  250. return box.apply(null, [types.mvex].concat(boxes));
  251. };
  252. mvhd = function mvhd(duration) {
  253. var bytes = new Uint8Array([0x00, // version 0
  254. 0x00, 0x00, 0x00, // flags
  255. 0x00, 0x00, 0x00, 0x01, // creation_time
  256. 0x00, 0x00, 0x00, 0x02, // modification_time
  257. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  258. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  259. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  260. 0x01, 0x00, // 1.0 volume
  261. 0x00, 0x00, // reserved
  262. 0x00, 0x00, 0x00, 0x00, // reserved
  263. 0x00, 0x00, 0x00, 0x00, // reserved
  264. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  265. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  266. 0xff, 0xff, 0xff, 0xff // next_track_ID
  267. ]);
  268. return box(types.mvhd, bytes);
  269. };
  270. sdtp = function sdtp(track) {
  271. var samples = track.samples || [],
  272. bytes = new Uint8Array(4 + samples.length),
  273. flags,
  274. i; // leave the full box header (4 bytes) all zero
  275. // write the sample table
  276. for (i = 0; i < samples.length; i++) {
  277. flags = samples[i].flags;
  278. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  279. }
  280. return box(types.sdtp, bytes);
  281. };
  282. stbl = function stbl(track) {
  283. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  284. };
  285. (function () {
  286. var videoSample, audioSample;
  287. stsd = function stsd(track) {
  288. return box(types.stsd, new Uint8Array([0x00, // version 0
  289. 0x00, 0x00, 0x00, // flags
  290. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  291. };
  292. videoSample = function videoSample(track) {
  293. var sps = track.sps || [],
  294. pps = track.pps || [],
  295. sequenceParameterSets = [],
  296. pictureParameterSets = [],
  297. i,
  298. avc1Box; // assemble the SPSs
  299. for (i = 0; i < sps.length; i++) {
  300. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  301. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  302. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  303. } // assemble the PPSs
  304. for (i = 0; i < pps.length; i++) {
  305. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  306. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  307. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  308. }
  309. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  310. 0x00, 0x01, // data_reference_index
  311. 0x00, 0x00, // pre_defined
  312. 0x00, 0x00, // reserved
  313. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  314. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  315. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  316. 0x00, 0x48, 0x00, 0x00, // horizresolution
  317. 0x00, 0x48, 0x00, 0x00, // vertresolution
  318. 0x00, 0x00, 0x00, 0x00, // reserved
  319. 0x00, 0x01, // frame_count
  320. 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  321. 0x00, 0x18, // depth = 24
  322. 0x11, 0x11 // pre_defined = -1
  323. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  324. track.profileIdc, // AVCProfileIndication
  325. track.profileCompatibility, // profile_compatibility
  326. track.levelIdc, // AVCLevelIndication
  327. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  328. ].concat([sps.length], // numOfSequenceParameterSets
  329. sequenceParameterSets, // "SPS"
  330. [pps.length], // numOfPictureParameterSets
  331. pictureParameterSets // "PPS"
  332. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  333. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  334. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  335. ]))];
  336. if (track.sarRatio) {
  337. var hSpacing = track.sarRatio[0],
  338. vSpacing = track.sarRatio[1];
  339. avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
  340. }
  341. return box.apply(null, avc1Box);
  342. };
  343. audioSample = function audioSample(track) {
  344. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  345. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  346. 0x00, 0x01, // data_reference_index
  347. // AudioSampleEntry, ISO/IEC 14496-12
  348. 0x00, 0x00, 0x00, 0x00, // reserved
  349. 0x00, 0x00, 0x00, 0x00, // reserved
  350. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  351. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  352. 0x00, 0x00, // pre_defined
  353. 0x00, 0x00, // reserved
  354. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  355. // MP4AudioSampleEntry, ISO/IEC 14496-14
  356. ]), esds(track));
  357. };
  358. })();
  359. tkhd = function tkhd(track) {
  360. var result = new Uint8Array([0x00, // version 0
  361. 0x00, 0x00, 0x07, // flags
  362. 0x00, 0x00, 0x00, 0x00, // creation_time
  363. 0x00, 0x00, 0x00, 0x00, // modification_time
  364. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  365. 0x00, 0x00, 0x00, 0x00, // reserved
  366. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  367. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  368. 0x00, 0x00, // layer
  369. 0x00, 0x00, // alternate_group
  370. 0x01, 0x00, // non-audio track volume
  371. 0x00, 0x00, // reserved
  372. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  373. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  374. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  375. ]);
  376. return box(types.tkhd, result);
  377. };
  378. /**
  379. * Generate a track fragment (traf) box. A traf box collects metadata
  380. * about tracks in a movie fragment (moof) box.
  381. */
  382. traf = function traf(track) {
  383. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  384. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  385. 0x00, 0x00, 0x3a, // flags
  386. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  387. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  388. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  389. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  390. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  391. ]));
  392. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  393. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  394. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  395. 0x00, 0x00, 0x00, // flags
  396. // baseMediaDecodeTime
  397. upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
  398. // the containing moof to the first payload byte of the associated
  399. // mdat
  400. dataOffset = 32 + // tfhd
  401. 20 + // tfdt
  402. 8 + // traf header
  403. 16 + // mfhd
  404. 8 + // moof header
  405. 8; // mdat header
  406. // audio tracks require less metadata
  407. if (track.type === 'audio') {
  408. trackFragmentRun = trun$1(track, dataOffset);
  409. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  410. } // video tracks should contain an independent and disposable samples
  411. // box (sdtp)
  412. // generate one and adjust offsets to match
  413. sampleDependencyTable = sdtp(track);
  414. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  415. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  416. };
  417. /**
  418. * Generate a track box.
  419. * @param track {object} a track definition
  420. * @return {Uint8Array} the track box
  421. */
  422. trak = function trak(track) {
  423. track.duration = track.duration || 0xffffffff;
  424. return box(types.trak, tkhd(track), mdia(track));
  425. };
  426. trex = function trex(track) {
  427. var result = new Uint8Array([0x00, // version 0
  428. 0x00, 0x00, 0x00, // flags
  429. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  430. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  431. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  432. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  433. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  434. ]); // the last two bytes of default_sample_flags is the sample
  435. // degradation priority, a hint about the importance of this sample
  436. // relative to others. Lower the degradation priority for all sample
  437. // types other than video.
  438. if (track.type !== 'video') {
  439. result[result.length - 1] = 0x00;
  440. }
  441. return box(types.trex, result);
  442. };
  443. (function () {
  444. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  445. // duration is present for the first sample, it will be present for
  446. // all subsequent samples.
  447. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  448. trunHeader = function trunHeader(samples, offset) {
  449. var durationPresent = 0,
  450. sizePresent = 0,
  451. flagsPresent = 0,
  452. compositionTimeOffset = 0; // trun flag constants
  453. if (samples.length) {
  454. if (samples[0].duration !== undefined) {
  455. durationPresent = 0x1;
  456. }
  457. if (samples[0].size !== undefined) {
  458. sizePresent = 0x2;
  459. }
  460. if (samples[0].flags !== undefined) {
  461. flagsPresent = 0x4;
  462. }
  463. if (samples[0].compositionTimeOffset !== undefined) {
  464. compositionTimeOffset = 0x8;
  465. }
  466. }
  467. return [0x00, // version 0
  468. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  469. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  470. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  471. ];
  472. };
  473. videoTrun = function videoTrun(track, offset) {
  474. var bytesOffest, bytes, header, samples, sample, i;
  475. samples = track.samples || [];
  476. offset += 8 + 12 + 16 * samples.length;
  477. header = trunHeader(samples, offset);
  478. bytes = new Uint8Array(header.length + samples.length * 16);
  479. bytes.set(header);
  480. bytesOffest = header.length;
  481. for (i = 0; i < samples.length; i++) {
  482. sample = samples[i];
  483. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  484. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  485. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  486. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  487. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  488. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  489. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  490. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  491. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  492. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  493. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  494. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  495. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  496. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  497. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  498. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  499. }
  500. return box(types.trun, bytes);
  501. };
  502. audioTrun = function audioTrun(track, offset) {
  503. var bytes, bytesOffest, header, samples, sample, i;
  504. samples = track.samples || [];
  505. offset += 8 + 12 + 8 * samples.length;
  506. header = trunHeader(samples, offset);
  507. bytes = new Uint8Array(header.length + samples.length * 8);
  508. bytes.set(header);
  509. bytesOffest = header.length;
  510. for (i = 0; i < samples.length; i++) {
  511. sample = samples[i];
  512. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  513. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  514. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  515. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  516. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  517. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  518. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  519. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  520. }
  521. return box(types.trun, bytes);
  522. };
  523. trun$1 = function trun(track, offset) {
  524. if (track.type === 'audio') {
  525. return audioTrun(track, offset);
  526. }
  527. return videoTrun(track, offset);
  528. };
  529. })();
  530. var mp4Generator = {
  531. ftyp: ftyp,
  532. mdat: mdat,
  533. moof: moof,
  534. moov: moov,
  535. initSegment: function initSegment(tracks) {
  536. var fileType = ftyp(),
  537. movie = moov(tracks),
  538. result;
  539. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  540. result.set(fileType);
  541. result.set(movie, fileType.byteLength);
  542. return result;
  543. }
  544. };
  545. /**
  546. * mux.js
  547. *
  548. * Copyright (c) Brightcove
  549. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  550. */
  551. var toUnsigned$3 = function toUnsigned(value) {
  552. return value >>> 0;
  553. };
  554. var toHexString$1 = function toHexString(value) {
  555. return ('00' + value.toString(16)).slice(-2);
  556. };
  557. var bin = {
  558. toUnsigned: toUnsigned$3,
  559. toHexString: toHexString$1
  560. };
  561. var parseType$1 = function parseType(buffer) {
  562. var result = '';
  563. result += String.fromCharCode(buffer[0]);
  564. result += String.fromCharCode(buffer[1]);
  565. result += String.fromCharCode(buffer[2]);
  566. result += String.fromCharCode(buffer[3]);
  567. return result;
  568. };
  569. var parseType_1 = parseType$1;
  570. var toUnsigned$2 = bin.toUnsigned;
  571. var findBox = function findBox(data, path) {
  572. var results = [],
  573. i,
  574. size,
  575. type,
  576. end,
  577. subresults;
  578. if (!path.length) {
  579. // short-circuit the search for empty paths
  580. return null;
  581. }
  582. for (i = 0; i < data.byteLength;) {
  583. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  584. type = parseType_1(data.subarray(i + 4, i + 8));
  585. end = size > 1 ? i + size : data.byteLength;
  586. if (type === path[0]) {
  587. if (path.length === 1) {
  588. // this is the end of the path and we've found the box we were
  589. // looking for
  590. results.push(data.subarray(i + 8, end));
  591. } else {
  592. // recursively search for the next box along the path
  593. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  594. if (subresults.length) {
  595. results = results.concat(subresults);
  596. }
  597. }
  598. }
  599. i = end;
  600. } // we've finished searching all of data
  601. return results;
  602. };
  603. var findBox_1 = findBox;
  604. /**
  605. * Returns the first string in the data array ending with a null char '\0'
  606. * @param {UInt8} data
  607. * @returns the string with the null char
  608. */
  609. var uint8ToCString$1 = function uint8ToCString(data) {
  610. var index = 0;
  611. var curChar = String.fromCharCode(data[index]);
  612. var retString = '';
  613. while (curChar !== '\0') {
  614. retString += curChar;
  615. index++;
  616. curChar = String.fromCharCode(data[index]);
  617. } // Add nullChar
  618. retString += curChar;
  619. return retString;
  620. };
  621. var string = {
  622. uint8ToCString: uint8ToCString$1
  623. };
  624. var uint8ToCString = string.uint8ToCString;
  625. var getUint64$2 = numbers.getUint64;
  626. /**
  627. * Based on: ISO/IEC 23009 Section: 5.10.3.3
  628. * References:
  629. * https://dashif-documents.azurewebsites.net/Events/master/event.html#emsg-format
  630. * https://aomediacodec.github.io/id3-emsg/
  631. *
  632. * Takes emsg box data as a uint8 array and returns a emsg box object
  633. * @param {UInt8Array} boxData data from emsg box
  634. * @returns A parsed emsg box object
  635. */
  636. var parseEmsgBox = function parseEmsgBox(boxData) {
  637. // version + flags
  638. var offset = 4;
  639. var version = boxData[0];
  640. var scheme_id_uri, value, timescale, presentation_time, presentation_time_delta, event_duration, id, message_data;
  641. if (version === 0) {
  642. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  643. offset += scheme_id_uri.length;
  644. value = uint8ToCString(boxData.subarray(offset));
  645. offset += value.length;
  646. var dv = new DataView(boxData.buffer);
  647. timescale = dv.getUint32(offset);
  648. offset += 4;
  649. presentation_time_delta = dv.getUint32(offset);
  650. offset += 4;
  651. event_duration = dv.getUint32(offset);
  652. offset += 4;
  653. id = dv.getUint32(offset);
  654. offset += 4;
  655. } else if (version === 1) {
  656. var dv = new DataView(boxData.buffer);
  657. timescale = dv.getUint32(offset);
  658. offset += 4;
  659. presentation_time = getUint64$2(boxData.subarray(offset));
  660. offset += 8;
  661. event_duration = dv.getUint32(offset);
  662. offset += 4;
  663. id = dv.getUint32(offset);
  664. offset += 4;
  665. scheme_id_uri = uint8ToCString(boxData.subarray(offset));
  666. offset += scheme_id_uri.length;
  667. value = uint8ToCString(boxData.subarray(offset));
  668. offset += value.length;
  669. }
  670. message_data = new Uint8Array(boxData.subarray(offset, boxData.byteLength));
  671. var emsgBox = {
  672. scheme_id_uri: scheme_id_uri,
  673. value: value,
  674. // if timescale is undefined or 0 set to 1
  675. timescale: timescale ? timescale : 1,
  676. presentation_time: presentation_time,
  677. presentation_time_delta: presentation_time_delta,
  678. event_duration: event_duration,
  679. id: id,
  680. message_data: message_data
  681. };
  682. return isValidEmsgBox(version, emsgBox) ? emsgBox : undefined;
  683. };
  684. /**
  685. * Scales a presentation time or time delta with an offset with a provided timescale
  686. * @param {number} presentationTime
  687. * @param {number} timescale
  688. * @param {number} timeDelta
  689. * @param {number} offset
  690. * @returns the scaled time as a number
  691. */
  692. var scaleTime = function scaleTime(presentationTime, timescale, timeDelta, offset) {
  693. return presentationTime || presentationTime === 0 ? presentationTime / timescale : offset + timeDelta / timescale;
  694. };
  695. /**
  696. * Checks the emsg box data for validity based on the version
  697. * @param {number} version of the emsg box to validate
  698. * @param {Object} emsg the emsg data to validate
  699. * @returns if the box is valid as a boolean
  700. */
  701. var isValidEmsgBox = function isValidEmsgBox(version, emsg) {
  702. var hasScheme = emsg.scheme_id_uri !== '\0';
  703. var isValidV0Box = version === 0 && isDefined(emsg.presentation_time_delta) && hasScheme;
  704. var isValidV1Box = version === 1 && isDefined(emsg.presentation_time) && hasScheme; // Only valid versions of emsg are 0 and 1
  705. return !(version > 1) && isValidV0Box || isValidV1Box;
  706. }; // Utility function to check if an object is defined
  707. var isDefined = function isDefined(data) {
  708. return data !== undefined || data !== null;
  709. };
  710. var emsg = {
  711. parseEmsgBox: parseEmsgBox,
  712. scaleTime: scaleTime
  713. };
  714. var tfhd = function tfhd(data) {
  715. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  716. result = {
  717. version: data[0],
  718. flags: new Uint8Array(data.subarray(1, 4)),
  719. trackId: view.getUint32(4)
  720. },
  721. baseDataOffsetPresent = result.flags[2] & 0x01,
  722. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  723. defaultSampleDurationPresent = result.flags[2] & 0x08,
  724. defaultSampleSizePresent = result.flags[2] & 0x10,
  725. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  726. durationIsEmpty = result.flags[0] & 0x010000,
  727. defaultBaseIsMoof = result.flags[0] & 0x020000,
  728. i;
  729. i = 8;
  730. if (baseDataOffsetPresent) {
  731. i += 4; // truncate top 4 bytes
  732. // FIXME: should we read the full 64 bits?
  733. result.baseDataOffset = view.getUint32(12);
  734. i += 4;
  735. }
  736. if (sampleDescriptionIndexPresent) {
  737. result.sampleDescriptionIndex = view.getUint32(i);
  738. i += 4;
  739. }
  740. if (defaultSampleDurationPresent) {
  741. result.defaultSampleDuration = view.getUint32(i);
  742. i += 4;
  743. }
  744. if (defaultSampleSizePresent) {
  745. result.defaultSampleSize = view.getUint32(i);
  746. i += 4;
  747. }
  748. if (defaultSampleFlagsPresent) {
  749. result.defaultSampleFlags = view.getUint32(i);
  750. }
  751. if (durationIsEmpty) {
  752. result.durationIsEmpty = true;
  753. }
  754. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  755. result.baseDataOffsetIsMoof = true;
  756. }
  757. return result;
  758. };
  759. var parseTfhd = tfhd;
  760. var parseSampleFlags = function parseSampleFlags(flags) {
  761. return {
  762. isLeading: (flags[0] & 0x0c) >>> 2,
  763. dependsOn: flags[0] & 0x03,
  764. isDependedOn: (flags[1] & 0xc0) >>> 6,
  765. hasRedundancy: (flags[1] & 0x30) >>> 4,
  766. paddingValue: (flags[1] & 0x0e) >>> 1,
  767. isNonSyncSample: flags[1] & 0x01,
  768. degradationPriority: flags[2] << 8 | flags[3]
  769. };
  770. };
  771. var parseSampleFlags_1 = parseSampleFlags;
  772. var trun = function trun(data) {
  773. var result = {
  774. version: data[0],
  775. flags: new Uint8Array(data.subarray(1, 4)),
  776. samples: []
  777. },
  778. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  779. // Flag interpretation
  780. dataOffsetPresent = result.flags[2] & 0x01,
  781. // compare with 2nd byte of 0x1
  782. firstSampleFlagsPresent = result.flags[2] & 0x04,
  783. // compare with 2nd byte of 0x4
  784. sampleDurationPresent = result.flags[1] & 0x01,
  785. // compare with 2nd byte of 0x100
  786. sampleSizePresent = result.flags[1] & 0x02,
  787. // compare with 2nd byte of 0x200
  788. sampleFlagsPresent = result.flags[1] & 0x04,
  789. // compare with 2nd byte of 0x400
  790. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  791. // compare with 2nd byte of 0x800
  792. sampleCount = view.getUint32(4),
  793. offset = 8,
  794. sample;
  795. if (dataOffsetPresent) {
  796. // 32 bit signed integer
  797. result.dataOffset = view.getInt32(offset);
  798. offset += 4;
  799. } // Overrides the flags for the first sample only. The order of
  800. // optional values will be: duration, size, compositionTimeOffset
  801. if (firstSampleFlagsPresent && sampleCount) {
  802. sample = {
  803. flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
  804. };
  805. offset += 4;
  806. if (sampleDurationPresent) {
  807. sample.duration = view.getUint32(offset);
  808. offset += 4;
  809. }
  810. if (sampleSizePresent) {
  811. sample.size = view.getUint32(offset);
  812. offset += 4;
  813. }
  814. if (sampleCompositionTimeOffsetPresent) {
  815. if (result.version === 1) {
  816. sample.compositionTimeOffset = view.getInt32(offset);
  817. } else {
  818. sample.compositionTimeOffset = view.getUint32(offset);
  819. }
  820. offset += 4;
  821. }
  822. result.samples.push(sample);
  823. sampleCount--;
  824. }
  825. while (sampleCount--) {
  826. sample = {};
  827. if (sampleDurationPresent) {
  828. sample.duration = view.getUint32(offset);
  829. offset += 4;
  830. }
  831. if (sampleSizePresent) {
  832. sample.size = view.getUint32(offset);
  833. offset += 4;
  834. }
  835. if (sampleFlagsPresent) {
  836. sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
  837. offset += 4;
  838. }
  839. if (sampleCompositionTimeOffsetPresent) {
  840. if (result.version === 1) {
  841. sample.compositionTimeOffset = view.getInt32(offset);
  842. } else {
  843. sample.compositionTimeOffset = view.getUint32(offset);
  844. }
  845. offset += 4;
  846. }
  847. result.samples.push(sample);
  848. }
  849. return result;
  850. };
  851. var parseTrun = trun;
  852. var toUnsigned$1 = bin.toUnsigned;
  853. var getUint64$1 = numbers.getUint64;
  854. var tfdt = function tfdt(data) {
  855. var result = {
  856. version: data[0],
  857. flags: new Uint8Array(data.subarray(1, 4))
  858. };
  859. if (result.version === 1) {
  860. result.baseMediaDecodeTime = getUint64$1(data.subarray(4));
  861. } else {
  862. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  863. }
  864. return result;
  865. };
  866. var parseTfdt = tfdt;
  867. // IE11 doesn't support indexOf for TypedArrays.
  868. // Once IE11 support is dropped, this function should be removed.
  869. var typedArrayIndexOf$1 = function typedArrayIndexOf(typedArray, element, fromIndex) {
  870. if (!typedArray) {
  871. return -1;
  872. }
  873. var currentIndex = fromIndex;
  874. for (; currentIndex < typedArray.length; currentIndex++) {
  875. if (typedArray[currentIndex] === element) {
  876. return currentIndex;
  877. }
  878. }
  879. return -1;
  880. };
  881. var typedArray = {
  882. typedArrayIndexOf: typedArrayIndexOf$1
  883. };
  884. var typedArrayIndexOf = typedArray.typedArrayIndexOf,
  885. // Frames that allow different types of text encoding contain a text
  886. // encoding description byte [ID3v2.4.0 section 4.]
  887. textEncodingDescriptionByte = {
  888. Iso88591: 0x00,
  889. // ISO-8859-1, terminated with \0.
  890. Utf16: 0x01,
  891. // UTF-16 encoded Unicode BOM, terminated with \0\0
  892. Utf16be: 0x02,
  893. // UTF-16BE encoded Unicode, without BOM, terminated with \0\0
  894. Utf8: 0x03 // UTF-8 encoded Unicode, terminated with \0
  895. },
  896. // return a percent-encoded representation of the specified byte range
  897. // @see http://en.wikipedia.org/wiki/Percent-encoding
  898. percentEncode$1 = function percentEncode(bytes, start, end) {
  899. var i,
  900. result = '';
  901. for (i = start; i < end; i++) {
  902. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  903. }
  904. return result;
  905. },
  906. // return the string representation of the specified byte range,
  907. // interpreted as UTf-8.
  908. parseUtf8 = function parseUtf8(bytes, start, end) {
  909. return decodeURIComponent(percentEncode$1(bytes, start, end));
  910. },
  911. // return the string representation of the specified byte range,
  912. // interpreted as ISO-8859-1.
  913. parseIso88591$1 = function parseIso88591(bytes, start, end) {
  914. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  915. },
  916. parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
  917. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  918. },
  919. frameParsers = {
  920. 'APIC': function APIC(frame) {
  921. var i = 1,
  922. mimeTypeEndIndex,
  923. descriptionEndIndex,
  924. LINK_MIME_TYPE = '-->';
  925. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  926. // ignore frames with unrecognized character encodings
  927. return;
  928. } // parsing fields [ID3v2.4.0 section 4.14.]
  929. mimeTypeEndIndex = typedArrayIndexOf(frame.data, 0, i);
  930. if (mimeTypeEndIndex < 0) {
  931. // malformed frame
  932. return;
  933. } // parsing Mime type field (terminated with \0)
  934. frame.mimeType = parseIso88591$1(frame.data, i, mimeTypeEndIndex);
  935. i = mimeTypeEndIndex + 1; // parsing 1-byte Picture Type field
  936. frame.pictureType = frame.data[i];
  937. i++;
  938. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, i);
  939. if (descriptionEndIndex < 0) {
  940. // malformed frame
  941. return;
  942. } // parsing Description field (terminated with \0)
  943. frame.description = parseUtf8(frame.data, i, descriptionEndIndex);
  944. i = descriptionEndIndex + 1;
  945. if (frame.mimeType === LINK_MIME_TYPE) {
  946. // parsing Picture Data field as URL (always represented as ISO-8859-1 [ID3v2.4.0 section 4.])
  947. frame.url = parseIso88591$1(frame.data, i, frame.data.length);
  948. } else {
  949. // parsing Picture Data field as binary data
  950. frame.pictureData = frame.data.subarray(i, frame.data.length);
  951. }
  952. },
  953. 'T*': function T(frame) {
  954. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  955. // ignore frames with unrecognized character encodings
  956. return;
  957. } // parse text field, do not include null terminator in the frame value
  958. // frames that allow different types of encoding contain terminated text [ID3v2.4.0 section 4.]
  959. frame.value = parseUtf8(frame.data, 1, frame.data.length).replace(/\0*$/, ''); // text information frames supports multiple strings, stored as a terminator separated list [ID3v2.4.0 section 4.2.]
  960. frame.values = frame.value.split('\0');
  961. },
  962. 'TXXX': function TXXX(frame) {
  963. var descriptionEndIndex;
  964. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  965. // ignore frames with unrecognized character encodings
  966. return;
  967. }
  968. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  969. if (descriptionEndIndex === -1) {
  970. return;
  971. } // parse the text fields
  972. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // do not include the null terminator in the tag value
  973. // frames that allow different types of encoding contain terminated text
  974. // [ID3v2.4.0 section 4.]
  975. frame.value = parseUtf8(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0*$/, '');
  976. frame.data = frame.value;
  977. },
  978. 'W*': function W(frame) {
  979. // parse URL field; URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  980. // if the value is followed by a string termination all the following information should be ignored [ID3v2.4.0 section 4.3]
  981. frame.url = parseIso88591$1(frame.data, 0, frame.data.length).replace(/\0.*$/, '');
  982. },
  983. 'WXXX': function WXXX(frame) {
  984. var descriptionEndIndex;
  985. if (frame.data[0] !== textEncodingDescriptionByte.Utf8) {
  986. // ignore frames with unrecognized character encodings
  987. return;
  988. }
  989. descriptionEndIndex = typedArrayIndexOf(frame.data, 0, 1);
  990. if (descriptionEndIndex === -1) {
  991. return;
  992. } // parse the description and URL fields
  993. frame.description = parseUtf8(frame.data, 1, descriptionEndIndex); // URL fields are always represented as ISO-8859-1 [ID3v2.4.0 section 4.]
  994. // if the value is followed by a string termination all the following information
  995. // should be ignored [ID3v2.4.0 section 4.3]
  996. frame.url = parseIso88591$1(frame.data, descriptionEndIndex + 1, frame.data.length).replace(/\0.*$/, '');
  997. },
  998. 'PRIV': function PRIV(frame) {
  999. var i;
  1000. for (i = 0; i < frame.data.length; i++) {
  1001. if (frame.data[i] === 0) {
  1002. // parse the description and URL fields
  1003. frame.owner = parseIso88591$1(frame.data, 0, i);
  1004. break;
  1005. }
  1006. }
  1007. frame.privateData = frame.data.subarray(i + 1);
  1008. frame.data = frame.privateData;
  1009. }
  1010. };
  1011. var parseId3Frames$1 = function parseId3Frames(data) {
  1012. var frameSize,
  1013. frameHeader,
  1014. frameStart = 10,
  1015. tagSize = 0,
  1016. frames = []; // If we don't have enough data for a header, 10 bytes,
  1017. // or 'ID3' in the first 3 bytes this is not a valid ID3 tag.
  1018. if (data.length < 10 || data[0] !== 'I'.charCodeAt(0) || data[1] !== 'D'.charCodeAt(0) || data[2] !== '3'.charCodeAt(0)) {
  1019. return;
  1020. } // the frame size is transmitted as a 28-bit integer in the
  1021. // last four bytes of the ID3 header.
  1022. // The most significant bit of each byte is dropped and the
  1023. // results concatenated to recover the actual value.
  1024. tagSize = parseSyncSafeInteger$1(data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  1025. // convenient for our comparisons to include it
  1026. tagSize += 10; // check bit 6 of byte 5 for the extended header flag.
  1027. var hasExtendedHeader = data[5] & 0x40;
  1028. if (hasExtendedHeader) {
  1029. // advance the frame start past the extended header
  1030. frameStart += 4; // header size field
  1031. frameStart += parseSyncSafeInteger$1(data.subarray(10, 14));
  1032. tagSize -= parseSyncSafeInteger$1(data.subarray(16, 20)); // clip any padding off the end
  1033. } // parse one or more ID3 frames
  1034. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  1035. do {
  1036. // determine the number of bytes in this frame
  1037. frameSize = parseSyncSafeInteger$1(data.subarray(frameStart + 4, frameStart + 8));
  1038. if (frameSize < 1) {
  1039. break;
  1040. }
  1041. frameHeader = String.fromCharCode(data[frameStart], data[frameStart + 1], data[frameStart + 2], data[frameStart + 3]);
  1042. var frame = {
  1043. id: frameHeader,
  1044. data: data.subarray(frameStart + 10, frameStart + frameSize + 10)
  1045. };
  1046. frame.key = frame.id; // parse frame values
  1047. if (frameParsers[frame.id]) {
  1048. // use frame specific parser
  1049. frameParsers[frame.id](frame);
  1050. } else if (frame.id[0] === 'T') {
  1051. // use text frame generic parser
  1052. frameParsers['T*'](frame);
  1053. } else if (frame.id[0] === 'W') {
  1054. // use URL link frame generic parser
  1055. frameParsers['W*'](frame);
  1056. }
  1057. frames.push(frame);
  1058. frameStart += 10; // advance past the frame header
  1059. frameStart += frameSize; // advance past the frame body
  1060. } while (frameStart < tagSize);
  1061. return frames;
  1062. };
  1063. var parseId3 = {
  1064. parseId3Frames: parseId3Frames$1,
  1065. parseSyncSafeInteger: parseSyncSafeInteger$1,
  1066. frameParsers: frameParsers
  1067. };
  1068. var toUnsigned = bin.toUnsigned;
  1069. var toHexString = bin.toHexString;
  1070. var getUint64 = numbers.getUint64;
  1071. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader, getEmsgID3;
  1072. var parseId3Frames = parseId3.parseId3Frames;
  1073. /**
  1074. * Parses an MP4 initialization segment and extracts the timescale
  1075. * values for any declared tracks. Timescale values indicate the
  1076. * number of clock ticks per second to assume for time-based values
  1077. * elsewhere in the MP4.
  1078. *
  1079. * To determine the start time of an MP4, you need two pieces of
  1080. * information: the timescale unit and the earliest base media decode
  1081. * time. Multiple timescales can be specified within an MP4 but the
  1082. * base media decode time is always expressed in the timescale from
  1083. * the media header box for the track:
  1084. * ```
  1085. * moov > trak > mdia > mdhd.timescale
  1086. * ```
  1087. * @param init {Uint8Array} the bytes of the init segment
  1088. * @return {object} a hash of track ids to timescale values or null if
  1089. * the init segment is malformed.
  1090. */
  1091. timescale = function timescale(init) {
  1092. var result = {},
  1093. traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
  1094. return traks.reduce(function (result, trak) {
  1095. var tkhd, version, index, id, mdhd;
  1096. tkhd = findBox_1(trak, ['tkhd'])[0];
  1097. if (!tkhd) {
  1098. return null;
  1099. }
  1100. version = tkhd[0];
  1101. index = version === 0 ? 12 : 20;
  1102. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  1103. mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  1104. if (!mdhd) {
  1105. return null;
  1106. }
  1107. version = mdhd[0];
  1108. index = version === 0 ? 12 : 20;
  1109. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  1110. return result;
  1111. }, result);
  1112. };
  1113. /**
  1114. * Determine the base media decode start time, in seconds, for an MP4
  1115. * fragment. If multiple fragments are specified, the earliest time is
  1116. * returned.
  1117. *
  1118. * The base media decode time can be parsed from track fragment
  1119. * metadata:
  1120. * ```
  1121. * moof > traf > tfdt.baseMediaDecodeTime
  1122. * ```
  1123. * It requires the timescale value from the mdhd to interpret.
  1124. *
  1125. * @param timescale {object} a hash of track ids to timescale values.
  1126. * @return {number} the earliest base media decode start time for the
  1127. * fragment, in seconds
  1128. */
  1129. startTime = function startTime(timescale, fragment) {
  1130. var trafs; // we need info from two childrend of each track fragment box
  1131. trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
  1132. var lowestTime = trafs.reduce(function (acc, traf) {
  1133. var tfhd = findBox_1(traf, ['tfhd'])[0]; // get the track id from the tfhd
  1134. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  1135. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  1136. var tfdt = findBox_1(traf, ['tfdt'])[0];
  1137. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  1138. var baseTime; // version 1 is 64 bit
  1139. if (tfdt[0] === 1) {
  1140. baseTime = getUint64(tfdt.subarray(4, 12));
  1141. } else {
  1142. baseTime = dv.getUint32(4);
  1143. } // convert base time to seconds if it is a valid number.
  1144. var seconds;
  1145. if (typeof baseTime === 'bigint') {
  1146. seconds = baseTime / window__default['default'].BigInt(scale);
  1147. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  1148. seconds = baseTime / scale;
  1149. }
  1150. if (seconds < Number.MAX_SAFE_INTEGER) {
  1151. seconds = Number(seconds);
  1152. }
  1153. if (seconds < acc) {
  1154. acc = seconds;
  1155. }
  1156. return acc;
  1157. }, Infinity);
  1158. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  1159. };
  1160. /**
  1161. * Determine the composition start, in seconds, for an MP4
  1162. * fragment.
  1163. *
  1164. * The composition start time of a fragment can be calculated using the base
  1165. * media decode time, composition time offset, and timescale, as follows:
  1166. *
  1167. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  1168. *
  1169. * All of the aforementioned information is contained within a media fragment's
  1170. * `traf` box, except for timescale info, which comes from the initialization
  1171. * segment, so a track id (also contained within a `traf`) is also necessary to
  1172. * associate it with a timescale
  1173. *
  1174. *
  1175. * @param timescales {object} - a hash of track ids to timescale values.
  1176. * @param fragment {Unit8Array} - the bytes of a media segment
  1177. * @return {number} the composition start time for the fragment, in seconds
  1178. **/
  1179. compositionStartTime = function compositionStartTime(timescales, fragment) {
  1180. var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
  1181. var baseMediaDecodeTime = 0;
  1182. var compositionTimeOffset = 0;
  1183. var trackId;
  1184. if (trafBoxes && trafBoxes.length) {
  1185. // The spec states that track run samples contained within a `traf` box are contiguous, but
  1186. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  1187. // We will assume that they are, so we only need the first to calculate start time.
  1188. var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
  1189. var trun = findBox_1(trafBoxes[0], ['trun'])[0];
  1190. var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
  1191. if (tfhd) {
  1192. var parsedTfhd = parseTfhd(tfhd);
  1193. trackId = parsedTfhd.trackId;
  1194. }
  1195. if (tfdt) {
  1196. var parsedTfdt = parseTfdt(tfdt);
  1197. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  1198. }
  1199. if (trun) {
  1200. var parsedTrun = parseTrun(trun);
  1201. if (parsedTrun.samples && parsedTrun.samples.length) {
  1202. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  1203. }
  1204. }
  1205. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  1206. // specified.
  1207. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  1208. if (typeof baseMediaDecodeTime === 'bigint') {
  1209. compositionTimeOffset = window__default['default'].BigInt(compositionTimeOffset);
  1210. timescale = window__default['default'].BigInt(timescale);
  1211. }
  1212. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  1213. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  1214. result = Number(result);
  1215. }
  1216. return result;
  1217. };
  1218. /**
  1219. * Find the trackIds of the video tracks in this source.
  1220. * Found by parsing the Handler Reference and Track Header Boxes:
  1221. * moov > trak > mdia > hdlr
  1222. * moov > trak > tkhd
  1223. *
  1224. * @param {Uint8Array} init - The bytes of the init segment for this source
  1225. * @return {Number[]} A list of trackIds
  1226. *
  1227. * @see ISO-BMFF-12/2015, Section 8.4.3
  1228. **/
  1229. getVideoTrackIds = function getVideoTrackIds(init) {
  1230. var traks = findBox_1(init, ['moov', 'trak']);
  1231. var videoTrackIds = [];
  1232. traks.forEach(function (trak) {
  1233. var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
  1234. var tkhds = findBox_1(trak, ['tkhd']);
  1235. hdlrs.forEach(function (hdlr, index) {
  1236. var handlerType = parseType_1(hdlr.subarray(8, 12));
  1237. var tkhd = tkhds[index];
  1238. var view;
  1239. var version;
  1240. var trackId;
  1241. if (handlerType === 'vide') {
  1242. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  1243. version = view.getUint8(0);
  1244. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  1245. videoTrackIds.push(trackId);
  1246. }
  1247. });
  1248. });
  1249. return videoTrackIds;
  1250. };
  1251. getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
  1252. // mdhd is a FullBox, meaning it will have its own version as the first byte
  1253. var version = mdhd[0];
  1254. var index = version === 0 ? 12 : 20;
  1255. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  1256. };
  1257. /**
  1258. * Get all the video, audio, and hint tracks from a non fragmented
  1259. * mp4 segment
  1260. */
  1261. getTracks = function getTracks(init) {
  1262. var traks = findBox_1(init, ['moov', 'trak']);
  1263. var tracks = [];
  1264. traks.forEach(function (trak) {
  1265. var track = {};
  1266. var tkhd = findBox_1(trak, ['tkhd'])[0];
  1267. var view, tkhdVersion; // id
  1268. if (tkhd) {
  1269. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  1270. tkhdVersion = view.getUint8(0);
  1271. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  1272. }
  1273. var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
  1274. if (hdlr) {
  1275. var type = parseType_1(hdlr.subarray(8, 12));
  1276. if (type === 'vide') {
  1277. track.type = 'video';
  1278. } else if (type === 'soun') {
  1279. track.type = 'audio';
  1280. } else {
  1281. track.type = type;
  1282. }
  1283. } // codec
  1284. var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  1285. if (stsd) {
  1286. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  1287. track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
  1288. var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
  1289. var codecConfig, codecConfigType;
  1290. if (codecBox) {
  1291. // https://tools.ietf.org/html/rfc6381#section-3.3
  1292. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  1293. // we don't need anything but the "config" parameter of the
  1294. // avc1 codecBox
  1295. codecConfig = codecBox.subarray(78);
  1296. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  1297. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  1298. track.codec += '.'; // left padded with zeroes for single digit hex
  1299. // profile idc
  1300. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  1301. track.codec += toHexString(codecConfig[10]); // level idc
  1302. track.codec += toHexString(codecConfig[11]);
  1303. } else {
  1304. // TODO: show a warning that we couldn't parse the codec
  1305. // and are using the default
  1306. track.codec = 'avc1.4d400d';
  1307. }
  1308. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  1309. // we do not need anything but the streamDescriptor of the mp4a codecBox
  1310. codecConfig = codecBox.subarray(28);
  1311. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  1312. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  1313. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  1314. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  1315. } else {
  1316. // TODO: show a warning that we couldn't parse the codec
  1317. // and are using the default
  1318. track.codec = 'mp4a.40.2';
  1319. }
  1320. } else {
  1321. // flac, opus, etc
  1322. track.codec = track.codec.toLowerCase();
  1323. }
  1324. }
  1325. }
  1326. var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  1327. if (mdhd) {
  1328. track.timescale = getTimescaleFromMediaHeader(mdhd);
  1329. }
  1330. tracks.push(track);
  1331. });
  1332. return tracks;
  1333. };
  1334. /**
  1335. * Returns an array of emsg ID3 data from the provided segmentData.
  1336. * An offset can also be provided as the Latest Arrival Time to calculate
  1337. * the Event Start Time of v0 EMSG boxes.
  1338. * See: https://dashif-documents.azurewebsites.net/Events/master/event.html#Inband-event-timing
  1339. *
  1340. * @param {Uint8Array} segmentData the segment byte array.
  1341. * @param {number} offset the segment start time or Latest Arrival Time,
  1342. * @return {Object[]} an array of ID3 parsed from EMSG boxes
  1343. */
  1344. getEmsgID3 = function getEmsgID3(segmentData, offset) {
  1345. if (offset === void 0) {
  1346. offset = 0;
  1347. }
  1348. var emsgBoxes = findBox_1(segmentData, ['emsg']);
  1349. return emsgBoxes.map(function (data) {
  1350. var parsedBox = emsg.parseEmsgBox(new Uint8Array(data));
  1351. var parsedId3Frames = parseId3Frames(parsedBox.message_data);
  1352. return {
  1353. cueTime: emsg.scaleTime(parsedBox.presentation_time, parsedBox.timescale, parsedBox.presentation_time_delta, offset),
  1354. duration: emsg.scaleTime(parsedBox.event_duration, parsedBox.timescale),
  1355. frames: parsedId3Frames
  1356. };
  1357. });
  1358. };
  1359. var probe = {
  1360. // export mp4 inspector's findBox and parseType for backwards compatibility
  1361. findBox: findBox_1,
  1362. parseType: parseType_1,
  1363. timescale: timescale,
  1364. startTime: startTime,
  1365. compositionStartTime: compositionStartTime,
  1366. videoTrackIds: getVideoTrackIds,
  1367. tracks: getTracks,
  1368. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader,
  1369. getEmsgID3: getEmsgID3
  1370. };
  1371. /**
  1372. * mux.js
  1373. *
  1374. * Copyright (c) Brightcove
  1375. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1376. *
  1377. * A lightweight readable stream implemention that handles event dispatching.
  1378. * Objects that inherit from streams should call init in their constructors.
  1379. */
  1380. var Stream = function Stream() {
  1381. this.init = function () {
  1382. var listeners = {};
  1383. /**
  1384. * Add a listener for a specified event type.
  1385. * @param type {string} the event name
  1386. * @param listener {function} the callback to be invoked when an event of
  1387. * the specified type occurs
  1388. */
  1389. this.on = function (type, listener) {
  1390. if (!listeners[type]) {
  1391. listeners[type] = [];
  1392. }
  1393. listeners[type] = listeners[type].concat(listener);
  1394. };
  1395. /**
  1396. * Remove a listener for a specified event type.
  1397. * @param type {string} the event name
  1398. * @param listener {function} a function previously registered for this
  1399. * type of event through `on`
  1400. */
  1401. this.off = function (type, listener) {
  1402. var index;
  1403. if (!listeners[type]) {
  1404. return false;
  1405. }
  1406. index = listeners[type].indexOf(listener);
  1407. listeners[type] = listeners[type].slice();
  1408. listeners[type].splice(index, 1);
  1409. return index > -1;
  1410. };
  1411. /**
  1412. * Trigger an event of the specified type on this stream. Any additional
  1413. * arguments to this function are passed as parameters to event listeners.
  1414. * @param type {string} the event name
  1415. */
  1416. this.trigger = function (type) {
  1417. var callbacks, i, length, args;
  1418. callbacks = listeners[type];
  1419. if (!callbacks) {
  1420. return;
  1421. } // Slicing the arguments on every invocation of this method
  1422. // can add a significant amount of overhead. Avoid the
  1423. // intermediate object creation for the common case of a
  1424. // single callback argument
  1425. if (arguments.length === 2) {
  1426. length = callbacks.length;
  1427. for (i = 0; i < length; ++i) {
  1428. callbacks[i].call(this, arguments[1]);
  1429. }
  1430. } else {
  1431. args = [];
  1432. i = arguments.length;
  1433. for (i = 1; i < arguments.length; ++i) {
  1434. args.push(arguments[i]);
  1435. }
  1436. length = callbacks.length;
  1437. for (i = 0; i < length; ++i) {
  1438. callbacks[i].apply(this, args);
  1439. }
  1440. }
  1441. };
  1442. /**
  1443. * Destroys the stream and cleans up.
  1444. */
  1445. this.dispose = function () {
  1446. listeners = {};
  1447. };
  1448. };
  1449. };
  1450. /**
  1451. * Forwards all `data` events on this stream to the destination stream. The
  1452. * destination stream should provide a method `push` to receive the data
  1453. * events as they arrive.
  1454. * @param destination {stream} the stream that will receive all `data` events
  1455. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  1456. * when the current stream emits a 'done' event
  1457. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  1458. */
  1459. Stream.prototype.pipe = function (destination) {
  1460. this.on('data', function (data) {
  1461. destination.push(data);
  1462. });
  1463. this.on('done', function (flushSource) {
  1464. destination.flush(flushSource);
  1465. });
  1466. this.on('partialdone', function (flushSource) {
  1467. destination.partialFlush(flushSource);
  1468. });
  1469. this.on('endedtimeline', function (flushSource) {
  1470. destination.endTimeline(flushSource);
  1471. });
  1472. this.on('reset', function (flushSource) {
  1473. destination.reset(flushSource);
  1474. });
  1475. return destination;
  1476. }; // Default stream functions that are expected to be overridden to perform
  1477. // actual work. These are provided by the prototype as a sort of no-op
  1478. // implementation so that we don't have to check for their existence in the
  1479. // `pipe` function above.
  1480. Stream.prototype.push = function (data) {
  1481. this.trigger('data', data);
  1482. };
  1483. Stream.prototype.flush = function (flushSource) {
  1484. this.trigger('done', flushSource);
  1485. };
  1486. Stream.prototype.partialFlush = function (flushSource) {
  1487. this.trigger('partialdone', flushSource);
  1488. };
  1489. Stream.prototype.endTimeline = function (flushSource) {
  1490. this.trigger('endedtimeline', flushSource);
  1491. };
  1492. Stream.prototype.reset = function (flushSource) {
  1493. this.trigger('reset', flushSource);
  1494. };
  1495. var stream = Stream;
  1496. /**
  1497. * mux.js
  1498. *
  1499. * Copyright (c) Brightcove
  1500. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1501. */
  1502. // Convert an array of nal units into an array of frames with each frame being
  1503. // composed of the nal units that make up that frame
  1504. // Also keep track of cummulative data about the frame from the nal units such
  1505. // as the frame duration, starting pts, etc.
  1506. var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
  1507. var i,
  1508. currentNal,
  1509. currentFrame = [],
  1510. frames = []; // TODO added for LHLS, make sure this is OK
  1511. frames.byteLength = 0;
  1512. frames.nalCount = 0;
  1513. frames.duration = 0;
  1514. currentFrame.byteLength = 0;
  1515. for (i = 0; i < nalUnits.length; i++) {
  1516. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  1517. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  1518. // Since the very first nal unit is expected to be an AUD
  1519. // only push to the frames array when currentFrame is not empty
  1520. if (currentFrame.length) {
  1521. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  1522. frames.byteLength += currentFrame.byteLength;
  1523. frames.nalCount += currentFrame.length;
  1524. frames.duration += currentFrame.duration;
  1525. frames.push(currentFrame);
  1526. }
  1527. currentFrame = [currentNal];
  1528. currentFrame.byteLength = currentNal.data.byteLength;
  1529. currentFrame.pts = currentNal.pts;
  1530. currentFrame.dts = currentNal.dts;
  1531. } else {
  1532. // Specifically flag key frames for ease of use later
  1533. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  1534. currentFrame.keyFrame = true;
  1535. }
  1536. currentFrame.duration = currentNal.dts - currentFrame.dts;
  1537. currentFrame.byteLength += currentNal.data.byteLength;
  1538. currentFrame.push(currentNal);
  1539. }
  1540. } // For the last frame, use the duration of the previous frame if we
  1541. // have nothing better to go on
  1542. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  1543. currentFrame.duration = frames[frames.length - 1].duration;
  1544. } // Push the final frame
  1545. // TODO added for LHLS, make sure this is OK
  1546. frames.byteLength += currentFrame.byteLength;
  1547. frames.nalCount += currentFrame.length;
  1548. frames.duration += currentFrame.duration;
  1549. frames.push(currentFrame);
  1550. return frames;
  1551. }; // Convert an array of frames into an array of Gop with each Gop being composed
  1552. // of the frames that make up that Gop
  1553. // Also keep track of cummulative data about the Gop from the frames such as the
  1554. // Gop duration, starting pts, etc.
  1555. var groupFramesIntoGops = function groupFramesIntoGops(frames) {
  1556. var i,
  1557. currentFrame,
  1558. currentGop = [],
  1559. gops = []; // We must pre-set some of the values on the Gop since we
  1560. // keep running totals of these values
  1561. currentGop.byteLength = 0;
  1562. currentGop.nalCount = 0;
  1563. currentGop.duration = 0;
  1564. currentGop.pts = frames[0].pts;
  1565. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  1566. gops.byteLength = 0;
  1567. gops.nalCount = 0;
  1568. gops.duration = 0;
  1569. gops.pts = frames[0].pts;
  1570. gops.dts = frames[0].dts;
  1571. for (i = 0; i < frames.length; i++) {
  1572. currentFrame = frames[i];
  1573. if (currentFrame.keyFrame) {
  1574. // Since the very first frame is expected to be an keyframe
  1575. // only push to the gops array when currentGop is not empty
  1576. if (currentGop.length) {
  1577. gops.push(currentGop);
  1578. gops.byteLength += currentGop.byteLength;
  1579. gops.nalCount += currentGop.nalCount;
  1580. gops.duration += currentGop.duration;
  1581. }
  1582. currentGop = [currentFrame];
  1583. currentGop.nalCount = currentFrame.length;
  1584. currentGop.byteLength = currentFrame.byteLength;
  1585. currentGop.pts = currentFrame.pts;
  1586. currentGop.dts = currentFrame.dts;
  1587. currentGop.duration = currentFrame.duration;
  1588. } else {
  1589. currentGop.duration += currentFrame.duration;
  1590. currentGop.nalCount += currentFrame.length;
  1591. currentGop.byteLength += currentFrame.byteLength;
  1592. currentGop.push(currentFrame);
  1593. }
  1594. }
  1595. if (gops.length && currentGop.duration <= 0) {
  1596. currentGop.duration = gops[gops.length - 1].duration;
  1597. }
  1598. gops.byteLength += currentGop.byteLength;
  1599. gops.nalCount += currentGop.nalCount;
  1600. gops.duration += currentGop.duration; // push the final Gop
  1601. gops.push(currentGop);
  1602. return gops;
  1603. };
  1604. /*
  1605. * Search for the first keyframe in the GOPs and throw away all frames
  1606. * until that keyframe. Then extend the duration of the pulled keyframe
  1607. * and pull the PTS and DTS of the keyframe so that it covers the time
  1608. * range of the frames that were disposed.
  1609. *
  1610. * @param {Array} gops video GOPs
  1611. * @returns {Array} modified video GOPs
  1612. */
  1613. var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
  1614. var currentGop;
  1615. if (!gops[0][0].keyFrame && gops.length > 1) {
  1616. // Remove the first GOP
  1617. currentGop = gops.shift();
  1618. gops.byteLength -= currentGop.byteLength;
  1619. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  1620. // first gop to cover the time period of the
  1621. // frames we just removed
  1622. gops[0][0].dts = currentGop.dts;
  1623. gops[0][0].pts = currentGop.pts;
  1624. gops[0][0].duration += currentGop.duration;
  1625. }
  1626. return gops;
  1627. };
  1628. /**
  1629. * Default sample object
  1630. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  1631. */
  1632. var createDefaultSample = function createDefaultSample() {
  1633. return {
  1634. size: 0,
  1635. flags: {
  1636. isLeading: 0,
  1637. dependsOn: 1,
  1638. isDependedOn: 0,
  1639. hasRedundancy: 0,
  1640. degradationPriority: 0,
  1641. isNonSyncSample: 1
  1642. }
  1643. };
  1644. };
  1645. /*
  1646. * Collates information from a video frame into an object for eventual
  1647. * entry into an MP4 sample table.
  1648. *
  1649. * @param {Object} frame the video frame
  1650. * @param {Number} dataOffset the byte offset to position the sample
  1651. * @return {Object} object containing sample table info for a frame
  1652. */
  1653. var sampleForFrame = function sampleForFrame(frame, dataOffset) {
  1654. var sample = createDefaultSample();
  1655. sample.dataOffset = dataOffset;
  1656. sample.compositionTimeOffset = frame.pts - frame.dts;
  1657. sample.duration = frame.duration;
  1658. sample.size = 4 * frame.length; // Space for nal unit size
  1659. sample.size += frame.byteLength;
  1660. if (frame.keyFrame) {
  1661. sample.flags.dependsOn = 2;
  1662. sample.flags.isNonSyncSample = 0;
  1663. }
  1664. return sample;
  1665. }; // generate the track's sample table from an array of gops
  1666. var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
  1667. var h,
  1668. i,
  1669. sample,
  1670. currentGop,
  1671. currentFrame,
  1672. dataOffset = baseDataOffset || 0,
  1673. samples = [];
  1674. for (h = 0; h < gops.length; h++) {
  1675. currentGop = gops[h];
  1676. for (i = 0; i < currentGop.length; i++) {
  1677. currentFrame = currentGop[i];
  1678. sample = sampleForFrame(currentFrame, dataOffset);
  1679. dataOffset += sample.size;
  1680. samples.push(sample);
  1681. }
  1682. }
  1683. return samples;
  1684. }; // generate the track's raw mdat data from an array of gops
  1685. var concatenateNalData = function concatenateNalData(gops) {
  1686. var h,
  1687. i,
  1688. j,
  1689. currentGop,
  1690. currentFrame,
  1691. currentNal,
  1692. dataOffset = 0,
  1693. nalsByteLength = gops.byteLength,
  1694. numberOfNals = gops.nalCount,
  1695. totalByteLength = nalsByteLength + 4 * numberOfNals,
  1696. data = new Uint8Array(totalByteLength),
  1697. view = new DataView(data.buffer); // For each Gop..
  1698. for (h = 0; h < gops.length; h++) {
  1699. currentGop = gops[h]; // For each Frame..
  1700. for (i = 0; i < currentGop.length; i++) {
  1701. currentFrame = currentGop[i]; // For each NAL..
  1702. for (j = 0; j < currentFrame.length; j++) {
  1703. currentNal = currentFrame[j];
  1704. view.setUint32(dataOffset, currentNal.data.byteLength);
  1705. dataOffset += 4;
  1706. data.set(currentNal.data, dataOffset);
  1707. dataOffset += currentNal.data.byteLength;
  1708. }
  1709. }
  1710. }
  1711. return data;
  1712. }; // generate the track's sample table from a frame
  1713. var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
  1714. var sample,
  1715. dataOffset = baseDataOffset || 0,
  1716. samples = [];
  1717. sample = sampleForFrame(frame, dataOffset);
  1718. samples.push(sample);
  1719. return samples;
  1720. }; // generate the track's raw mdat data from a frame
  1721. var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
  1722. var i,
  1723. currentNal,
  1724. dataOffset = 0,
  1725. nalsByteLength = frame.byteLength,
  1726. numberOfNals = frame.length,
  1727. totalByteLength = nalsByteLength + 4 * numberOfNals,
  1728. data = new Uint8Array(totalByteLength),
  1729. view = new DataView(data.buffer); // For each NAL..
  1730. for (i = 0; i < frame.length; i++) {
  1731. currentNal = frame[i];
  1732. view.setUint32(dataOffset, currentNal.data.byteLength);
  1733. dataOffset += 4;
  1734. data.set(currentNal.data, dataOffset);
  1735. dataOffset += currentNal.data.byteLength;
  1736. }
  1737. return data;
  1738. };
  1739. var frameUtils = {
  1740. groupNalsIntoFrames: groupNalsIntoFrames,
  1741. groupFramesIntoGops: groupFramesIntoGops,
  1742. extendFirstKeyFrame: extendFirstKeyFrame,
  1743. generateSampleTable: generateSampleTable$1,
  1744. concatenateNalData: concatenateNalData,
  1745. generateSampleTableForFrame: generateSampleTableForFrame,
  1746. concatenateNalDataForFrame: concatenateNalDataForFrame
  1747. };
  1748. /**
  1749. * mux.js
  1750. *
  1751. * Copyright (c) Brightcove
  1752. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1753. */
  1754. var highPrefix = [33, 16, 5, 32, 164, 27];
  1755. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  1756. var zeroFill = function zeroFill(count) {
  1757. var a = [];
  1758. while (count--) {
  1759. a.push(0);
  1760. }
  1761. return a;
  1762. };
  1763. var makeTable = function makeTable(metaTable) {
  1764. return Object.keys(metaTable).reduce(function (obj, key) {
  1765. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  1766. return arr.concat(part);
  1767. }, []));
  1768. return obj;
  1769. }, {});
  1770. };
  1771. var silence;
  1772. var silence_1 = function silence_1() {
  1773. if (!silence) {
  1774. // Frames-of-silence to use for filling in missing AAC frames
  1775. var coneOfSilence = {
  1776. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  1777. 88200: [highPrefix, [231], zeroFill(170), [56]],
  1778. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  1779. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  1780. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  1781. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  1782. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  1783. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  1784. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  1785. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  1786. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  1787. };
  1788. silence = makeTable(coneOfSilence);
  1789. }
  1790. return silence;
  1791. };
  1792. /**
  1793. * mux.js
  1794. *
  1795. * Copyright (c) Brightcove
  1796. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1797. */
  1798. var ONE_SECOND_IN_TS$3 = 90000,
  1799. // 90kHz clock
  1800. secondsToVideoTs,
  1801. secondsToAudioTs,
  1802. videoTsToSeconds,
  1803. audioTsToSeconds,
  1804. audioTsToVideoTs,
  1805. videoTsToAudioTs,
  1806. metadataTsToSeconds;
  1807. secondsToVideoTs = function secondsToVideoTs(seconds) {
  1808. return seconds * ONE_SECOND_IN_TS$3;
  1809. };
  1810. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  1811. return seconds * sampleRate;
  1812. };
  1813. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  1814. return timestamp / ONE_SECOND_IN_TS$3;
  1815. };
  1816. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  1817. return timestamp / sampleRate;
  1818. };
  1819. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  1820. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  1821. };
  1822. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  1823. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  1824. };
  1825. /**
  1826. * Adjust ID3 tag or caption timing information by the timeline pts values
  1827. * (if keepOriginalTimestamps is false) and convert to seconds
  1828. */
  1829. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  1830. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  1831. };
  1832. var clock = {
  1833. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$3,
  1834. secondsToVideoTs: secondsToVideoTs,
  1835. secondsToAudioTs: secondsToAudioTs,
  1836. videoTsToSeconds: videoTsToSeconds,
  1837. audioTsToSeconds: audioTsToSeconds,
  1838. audioTsToVideoTs: audioTsToVideoTs,
  1839. videoTsToAudioTs: videoTsToAudioTs,
  1840. metadataTsToSeconds: metadataTsToSeconds
  1841. };
  1842. /**
  1843. * mux.js
  1844. *
  1845. * Copyright (c) Brightcove
  1846. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1847. */
  1848. /**
  1849. * Sum the `byteLength` properties of the data in each AAC frame
  1850. */
  1851. var sumFrameByteLengths = function sumFrameByteLengths(array) {
  1852. var i,
  1853. currentObj,
  1854. sum = 0; // sum the byteLength's all each nal unit in the frame
  1855. for (i = 0; i < array.length; i++) {
  1856. currentObj = array[i];
  1857. sum += currentObj.data.byteLength;
  1858. }
  1859. return sum;
  1860. }; // Possibly pad (prefix) the audio track with silence if appending this track
  1861. // would lead to the introduction of a gap in the audio buffer
  1862. var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  1863. var baseMediaDecodeTimeTs,
  1864. frameDuration = 0,
  1865. audioGapDuration = 0,
  1866. audioFillFrameCount = 0,
  1867. audioFillDuration = 0,
  1868. silentFrame,
  1869. i,
  1870. firstFrame;
  1871. if (!frames.length) {
  1872. return;
  1873. }
  1874. baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  1875. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  1876. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  1877. // insert the shortest possible amount (audio gap or audio to video gap)
  1878. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  1879. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  1880. audioFillDuration = audioFillFrameCount * frameDuration;
  1881. } // don't attempt to fill gaps smaller than a single frame or larger
  1882. // than a half second
  1883. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  1884. return;
  1885. }
  1886. silentFrame = silence_1()[track.samplerate];
  1887. if (!silentFrame) {
  1888. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  1889. // from the content instead
  1890. silentFrame = frames[0].data;
  1891. }
  1892. for (i = 0; i < audioFillFrameCount; i++) {
  1893. firstFrame = frames[0];
  1894. frames.splice(0, 0, {
  1895. data: silentFrame,
  1896. dts: firstFrame.dts - frameDuration,
  1897. pts: firstFrame.pts - frameDuration
  1898. });
  1899. }
  1900. track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  1901. return audioFillDuration;
  1902. }; // If the audio segment extends before the earliest allowed dts
  1903. // value, remove AAC frames until starts at or after the earliest
  1904. // allowed DTS so that we don't end up with a negative baseMedia-
  1905. // DecodeTime for the audio track
  1906. var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
  1907. if (track.minSegmentDts >= earliestAllowedDts) {
  1908. return adtsFrames;
  1909. } // We will need to recalculate the earliest segment Dts
  1910. track.minSegmentDts = Infinity;
  1911. return adtsFrames.filter(function (currentFrame) {
  1912. // If this is an allowed frame, keep it and record it's Dts
  1913. if (currentFrame.dts >= earliestAllowedDts) {
  1914. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  1915. track.minSegmentPts = track.minSegmentDts;
  1916. return true;
  1917. } // Otherwise, discard it
  1918. return false;
  1919. });
  1920. }; // generate the track's raw mdat data from an array of frames
  1921. var generateSampleTable = function generateSampleTable(frames) {
  1922. var i,
  1923. currentFrame,
  1924. samples = [];
  1925. for (i = 0; i < frames.length; i++) {
  1926. currentFrame = frames[i];
  1927. samples.push({
  1928. size: currentFrame.data.byteLength,
  1929. duration: 1024 // For AAC audio, all samples contain 1024 samples
  1930. });
  1931. }
  1932. return samples;
  1933. }; // generate the track's sample table from an array of frames
  1934. var concatenateFrameData = function concatenateFrameData(frames) {
  1935. var i,
  1936. currentFrame,
  1937. dataOffset = 0,
  1938. data = new Uint8Array(sumFrameByteLengths(frames));
  1939. for (i = 0; i < frames.length; i++) {
  1940. currentFrame = frames[i];
  1941. data.set(currentFrame.data, dataOffset);
  1942. dataOffset += currentFrame.data.byteLength;
  1943. }
  1944. return data;
  1945. };
  1946. var audioFrameUtils = {
  1947. prefixWithSilence: prefixWithSilence,
  1948. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  1949. generateSampleTable: generateSampleTable,
  1950. concatenateFrameData: concatenateFrameData
  1951. };
  1952. /**
  1953. * mux.js
  1954. *
  1955. * Copyright (c) Brightcove
  1956. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1957. */
  1958. var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
  1959. /**
  1960. * Store information about the start and end of the track and the
  1961. * duration for each frame/sample we process in order to calculate
  1962. * the baseMediaDecodeTime
  1963. */
  1964. var collectDtsInfo = function collectDtsInfo(track, data) {
  1965. if (typeof data.pts === 'number') {
  1966. if (track.timelineStartInfo.pts === undefined) {
  1967. track.timelineStartInfo.pts = data.pts;
  1968. }
  1969. if (track.minSegmentPts === undefined) {
  1970. track.minSegmentPts = data.pts;
  1971. } else {
  1972. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  1973. }
  1974. if (track.maxSegmentPts === undefined) {
  1975. track.maxSegmentPts = data.pts;
  1976. } else {
  1977. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  1978. }
  1979. }
  1980. if (typeof data.dts === 'number') {
  1981. if (track.timelineStartInfo.dts === undefined) {
  1982. track.timelineStartInfo.dts = data.dts;
  1983. }
  1984. if (track.minSegmentDts === undefined) {
  1985. track.minSegmentDts = data.dts;
  1986. } else {
  1987. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  1988. }
  1989. if (track.maxSegmentDts === undefined) {
  1990. track.maxSegmentDts = data.dts;
  1991. } else {
  1992. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  1993. }
  1994. }
  1995. };
  1996. /**
  1997. * Clear values used to calculate the baseMediaDecodeTime between
  1998. * tracks
  1999. */
  2000. var clearDtsInfo = function clearDtsInfo(track) {
  2001. delete track.minSegmentDts;
  2002. delete track.maxSegmentDts;
  2003. delete track.minSegmentPts;
  2004. delete track.maxSegmentPts;
  2005. };
  2006. /**
  2007. * Calculate the track's baseMediaDecodeTime based on the earliest
  2008. * DTS the transmuxer has ever seen and the minimum DTS for the
  2009. * current track
  2010. * @param track {object} track metadata configuration
  2011. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  2012. * in the source; false to adjust the first segment to start at 0.
  2013. */
  2014. var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
  2015. var baseMediaDecodeTime,
  2016. scale,
  2017. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  2018. if (!keepOriginalTimestamps) {
  2019. minSegmentDts -= track.timelineStartInfo.dts;
  2020. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  2021. // we want the start of the first segment to be placed
  2022. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  2023. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  2024. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  2025. if (track.type === 'audio') {
  2026. // Audio has a different clock equal to the sampling_rate so we need to
  2027. // scale the PTS values into the clock rate of the track
  2028. scale = track.samplerate / ONE_SECOND_IN_TS$2;
  2029. baseMediaDecodeTime *= scale;
  2030. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  2031. }
  2032. return baseMediaDecodeTime;
  2033. };
  2034. var trackDecodeInfo = {
  2035. clearDtsInfo: clearDtsInfo,
  2036. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  2037. collectDtsInfo: collectDtsInfo
  2038. };
  2039. /**
  2040. * mux.js
  2041. *
  2042. * Copyright (c) Brightcove
  2043. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2044. *
  2045. * Reads in-band caption information from a video elementary
  2046. * stream. Captions must follow the CEA-708 standard for injection
  2047. * into an MPEG-2 transport streams.
  2048. * @see https://en.wikipedia.org/wiki/CEA-708
  2049. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  2050. */
  2051. // payload type field to indicate how they are to be
  2052. // interpreted. CEAS-708 caption content is always transmitted with
  2053. // payload type 0x04.
  2054. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  2055. RBSP_TRAILING_BITS = 128;
  2056. /**
  2057. * Parse a supplemental enhancement information (SEI) NAL unit.
  2058. * Stops parsing once a message of type ITU T T35 has been found.
  2059. *
  2060. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  2061. * @return {object} the parsed SEI payload
  2062. * @see Rec. ITU-T H.264, 7.3.2.3.1
  2063. */
  2064. var parseSei = function parseSei(bytes) {
  2065. var i = 0,
  2066. result = {
  2067. payloadType: -1,
  2068. payloadSize: 0
  2069. },
  2070. payloadType = 0,
  2071. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  2072. while (i < bytes.byteLength) {
  2073. // stop once we have hit the end of the sei_rbsp
  2074. if (bytes[i] === RBSP_TRAILING_BITS) {
  2075. break;
  2076. } // Parse payload type
  2077. while (bytes[i] === 0xFF) {
  2078. payloadType += 255;
  2079. i++;
  2080. }
  2081. payloadType += bytes[i++]; // Parse payload size
  2082. while (bytes[i] === 0xFF) {
  2083. payloadSize += 255;
  2084. i++;
  2085. }
  2086. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  2087. // there can only ever be one caption message in a frame's sei
  2088. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  2089. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  2090. if (userIdentifier === 'GA94') {
  2091. result.payloadType = payloadType;
  2092. result.payloadSize = payloadSize;
  2093. result.payload = bytes.subarray(i, i + payloadSize);
  2094. break;
  2095. } else {
  2096. result.payload = void 0;
  2097. }
  2098. } // skip the payload and parse the next message
  2099. i += payloadSize;
  2100. payloadType = 0;
  2101. payloadSize = 0;
  2102. }
  2103. return result;
  2104. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  2105. var parseUserData = function parseUserData(sei) {
  2106. // itu_t_t35_contry_code must be 181 (United States) for
  2107. // captions
  2108. if (sei.payload[0] !== 181) {
  2109. return null;
  2110. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  2111. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  2112. return null;
  2113. } // the user_identifier should be "GA94" to indicate ATSC1 data
  2114. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  2115. return null;
  2116. } // finally, user_data_type_code should be 0x03 for caption data
  2117. if (sei.payload[7] !== 0x03) {
  2118. return null;
  2119. } // return the user_data_type_structure and strip the trailing
  2120. // marker bits
  2121. return sei.payload.subarray(8, sei.payload.length - 1);
  2122. }; // see CEA-708-D, section 4.4
  2123. var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
  2124. var results = [],
  2125. i,
  2126. count,
  2127. offset,
  2128. data; // if this is just filler, return immediately
  2129. if (!(userData[0] & 0x40)) {
  2130. return results;
  2131. } // parse out the cc_data_1 and cc_data_2 fields
  2132. count = userData[0] & 0x1f;
  2133. for (i = 0; i < count; i++) {
  2134. offset = i * 3;
  2135. data = {
  2136. type: userData[offset + 2] & 0x03,
  2137. pts: pts
  2138. }; // capture cc data when cc_valid is 1
  2139. if (userData[offset + 2] & 0x04) {
  2140. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  2141. results.push(data);
  2142. }
  2143. }
  2144. return results;
  2145. };
  2146. var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
  2147. var length = data.byteLength,
  2148. emulationPreventionBytesPositions = [],
  2149. i = 1,
  2150. newLength,
  2151. newData; // Find all `Emulation Prevention Bytes`
  2152. while (i < length - 2) {
  2153. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  2154. emulationPreventionBytesPositions.push(i + 2);
  2155. i += 2;
  2156. } else {
  2157. i++;
  2158. }
  2159. } // If no Emulation Prevention Bytes were found just return the original
  2160. // array
  2161. if (emulationPreventionBytesPositions.length === 0) {
  2162. return data;
  2163. } // Create a new array to hold the NAL unit data
  2164. newLength = length - emulationPreventionBytesPositions.length;
  2165. newData = new Uint8Array(newLength);
  2166. var sourceIndex = 0;
  2167. for (i = 0; i < newLength; sourceIndex++, i++) {
  2168. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  2169. // Skip this byte
  2170. sourceIndex++; // Remove this position index
  2171. emulationPreventionBytesPositions.shift();
  2172. }
  2173. newData[i] = data[sourceIndex];
  2174. }
  2175. return newData;
  2176. }; // exports
  2177. var captionPacketParser = {
  2178. parseSei: parseSei,
  2179. parseUserData: parseUserData,
  2180. parseCaptionPackets: parseCaptionPackets,
  2181. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  2182. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  2183. };
  2184. // Link To Transport
  2185. // -----------------
  2186. var CaptionStream$1 = function CaptionStream(options) {
  2187. options = options || {};
  2188. CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
  2189. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  2190. this.captionPackets_ = [];
  2191. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  2192. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  2193. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  2194. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  2195. ];
  2196. if (this.parse708captions_) {
  2197. this.cc708Stream_ = new Cea708Stream({
  2198. captionServices: options.captionServices
  2199. }); // eslint-disable-line no-use-before-define
  2200. }
  2201. this.reset(); // forward data and done events from CCs to this CaptionStream
  2202. this.ccStreams_.forEach(function (cc) {
  2203. cc.on('data', this.trigger.bind(this, 'data'));
  2204. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  2205. cc.on('done', this.trigger.bind(this, 'done'));
  2206. }, this);
  2207. if (this.parse708captions_) {
  2208. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  2209. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  2210. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  2211. }
  2212. };
  2213. CaptionStream$1.prototype = new stream();
  2214. CaptionStream$1.prototype.push = function (event) {
  2215. var sei, userData, newCaptionPackets; // only examine SEI NALs
  2216. if (event.nalUnitType !== 'sei_rbsp') {
  2217. return;
  2218. } // parse the sei
  2219. sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
  2220. if (!sei.payload) {
  2221. return;
  2222. } // ignore everything but user_data_registered_itu_t_t35
  2223. if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
  2224. return;
  2225. } // parse out the user data payload
  2226. userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
  2227. if (!userData) {
  2228. return;
  2229. } // Sometimes, the same segment # will be downloaded twice. To stop the
  2230. // caption data from being processed twice, we track the latest dts we've
  2231. // received and ignore everything with a dts before that. However, since
  2232. // data for a specific dts can be split across packets on either side of
  2233. // a segment boundary, we need to make sure we *don't* ignore the packets
  2234. // from the *next* segment that have dts === this.latestDts_. By constantly
  2235. // tracking the number of packets received with dts === this.latestDts_, we
  2236. // know how many should be ignored once we start receiving duplicates.
  2237. if (event.dts < this.latestDts_) {
  2238. // We've started getting older data, so set the flag.
  2239. this.ignoreNextEqualDts_ = true;
  2240. return;
  2241. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  2242. this.numSameDts_--;
  2243. if (!this.numSameDts_) {
  2244. // We've received the last duplicate packet, time to start processing again
  2245. this.ignoreNextEqualDts_ = false;
  2246. }
  2247. return;
  2248. } // parse out CC data packets and save them for later
  2249. newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
  2250. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  2251. if (this.latestDts_ !== event.dts) {
  2252. this.numSameDts_ = 0;
  2253. }
  2254. this.numSameDts_++;
  2255. this.latestDts_ = event.dts;
  2256. };
  2257. CaptionStream$1.prototype.flushCCStreams = function (flushType) {
  2258. this.ccStreams_.forEach(function (cc) {
  2259. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  2260. }, this);
  2261. };
  2262. CaptionStream$1.prototype.flushStream = function (flushType) {
  2263. // make sure we actually parsed captions before proceeding
  2264. if (!this.captionPackets_.length) {
  2265. this.flushCCStreams(flushType);
  2266. return;
  2267. } // In Chrome, the Array#sort function is not stable so add a
  2268. // presortIndex that we can use to ensure we get a stable-sort
  2269. this.captionPackets_.forEach(function (elem, idx) {
  2270. elem.presortIndex = idx;
  2271. }); // sort caption byte-pairs based on their PTS values
  2272. this.captionPackets_.sort(function (a, b) {
  2273. if (a.pts === b.pts) {
  2274. return a.presortIndex - b.presortIndex;
  2275. }
  2276. return a.pts - b.pts;
  2277. });
  2278. this.captionPackets_.forEach(function (packet) {
  2279. if (packet.type < 2) {
  2280. // Dispatch packet to the right Cea608Stream
  2281. this.dispatchCea608Packet(packet);
  2282. } else {
  2283. // Dispatch packet to the Cea708Stream
  2284. this.dispatchCea708Packet(packet);
  2285. }
  2286. }, this);
  2287. this.captionPackets_.length = 0;
  2288. this.flushCCStreams(flushType);
  2289. };
  2290. CaptionStream$1.prototype.flush = function () {
  2291. return this.flushStream('flush');
  2292. }; // Only called if handling partial data
  2293. CaptionStream$1.prototype.partialFlush = function () {
  2294. return this.flushStream('partialFlush');
  2295. };
  2296. CaptionStream$1.prototype.reset = function () {
  2297. this.latestDts_ = null;
  2298. this.ignoreNextEqualDts_ = false;
  2299. this.numSameDts_ = 0;
  2300. this.activeCea608Channel_ = [null, null];
  2301. this.ccStreams_.forEach(function (ccStream) {
  2302. ccStream.reset();
  2303. });
  2304. }; // From the CEA-608 spec:
  2305. /*
  2306. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  2307. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  2308. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  2309. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  2310. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  2311. * to switch to captioning or Text.
  2312. */
  2313. // With that in mind, we ignore any data between an XDS control code and a
  2314. // subsequent closed-captioning control code.
  2315. CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
  2316. // NOTE: packet.type is the CEA608 field
  2317. if (this.setsTextOrXDSActive(packet)) {
  2318. this.activeCea608Channel_[packet.type] = null;
  2319. } else if (this.setsChannel1Active(packet)) {
  2320. this.activeCea608Channel_[packet.type] = 0;
  2321. } else if (this.setsChannel2Active(packet)) {
  2322. this.activeCea608Channel_[packet.type] = 1;
  2323. }
  2324. if (this.activeCea608Channel_[packet.type] === null) {
  2325. // If we haven't received anything to set the active channel, or the
  2326. // packets are Text/XDS data, discard the data; we don't want jumbled
  2327. // captions
  2328. return;
  2329. }
  2330. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  2331. };
  2332. CaptionStream$1.prototype.setsChannel1Active = function (packet) {
  2333. return (packet.ccData & 0x7800) === 0x1000;
  2334. };
  2335. CaptionStream$1.prototype.setsChannel2Active = function (packet) {
  2336. return (packet.ccData & 0x7800) === 0x1800;
  2337. };
  2338. CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
  2339. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  2340. };
  2341. CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
  2342. if (this.parse708captions_) {
  2343. this.cc708Stream_.push(packet);
  2344. }
  2345. }; // ----------------------
  2346. // Session to Application
  2347. // ----------------------
  2348. // This hash maps special and extended character codes to their
  2349. // proper Unicode equivalent. The first one-byte key is just a
  2350. // non-standard character code. The two-byte keys that follow are
  2351. // the extended CEA708 character codes, along with the preceding
  2352. // 0x10 extended character byte to distinguish these codes from
  2353. // non-extended character codes. Every CEA708 character code that
  2354. // is not in this object maps directly to a standard unicode
  2355. // character code.
  2356. // The transparent space and non-breaking transparent space are
  2357. // technically not fully supported since there is no code to
  2358. // make them transparent, so they have normal non-transparent
  2359. // stand-ins.
  2360. // The special closed caption (CC) character isn't a standard
  2361. // unicode character, so a fairly similar unicode character was
  2362. // chosen in it's place.
  2363. var CHARACTER_TRANSLATION_708 = {
  2364. 0x7f: 0x266a,
  2365. // ♪
  2366. 0x1020: 0x20,
  2367. // Transparent Space
  2368. 0x1021: 0xa0,
  2369. // Nob-breaking Transparent Space
  2370. 0x1025: 0x2026,
  2371. // …
  2372. 0x102a: 0x0160,
  2373. // Š
  2374. 0x102c: 0x0152,
  2375. // Œ
  2376. 0x1030: 0x2588,
  2377. // █
  2378. 0x1031: 0x2018,
  2379. // ‘
  2380. 0x1032: 0x2019,
  2381. // ’
  2382. 0x1033: 0x201c,
  2383. // “
  2384. 0x1034: 0x201d,
  2385. // ”
  2386. 0x1035: 0x2022,
  2387. // •
  2388. 0x1039: 0x2122,
  2389. // ™
  2390. 0x103a: 0x0161,
  2391. // š
  2392. 0x103c: 0x0153,
  2393. // œ
  2394. 0x103d: 0x2120,
  2395. // ℠
  2396. 0x103f: 0x0178,
  2397. // Ÿ
  2398. 0x1076: 0x215b,
  2399. // ⅛
  2400. 0x1077: 0x215c,
  2401. // ⅜
  2402. 0x1078: 0x215d,
  2403. // ⅝
  2404. 0x1079: 0x215e,
  2405. // ⅞
  2406. 0x107a: 0x23d0,
  2407. // ⏐
  2408. 0x107b: 0x23a4,
  2409. // ⎤
  2410. 0x107c: 0x23a3,
  2411. // ⎣
  2412. 0x107d: 0x23af,
  2413. // ⎯
  2414. 0x107e: 0x23a6,
  2415. // ⎦
  2416. 0x107f: 0x23a1,
  2417. // ⎡
  2418. 0x10a0: 0x3138 // ㄸ (CC char)
  2419. };
  2420. var get708CharFromCode = function get708CharFromCode(code) {
  2421. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  2422. if (code & 0x1000 && code === newCode) {
  2423. // Invalid extended code
  2424. return '';
  2425. }
  2426. return String.fromCharCode(newCode);
  2427. };
  2428. var within708TextBlock = function within708TextBlock(b) {
  2429. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  2430. };
  2431. var Cea708Window = function Cea708Window(windowNum) {
  2432. this.windowNum = windowNum;
  2433. this.reset();
  2434. };
  2435. Cea708Window.prototype.reset = function () {
  2436. this.clearText();
  2437. this.pendingNewLine = false;
  2438. this.winAttr = {};
  2439. this.penAttr = {};
  2440. this.penLoc = {};
  2441. this.penColor = {}; // These default values are arbitrary,
  2442. // defineWindow will usually override them
  2443. this.visible = 0;
  2444. this.rowLock = 0;
  2445. this.columnLock = 0;
  2446. this.priority = 0;
  2447. this.relativePositioning = 0;
  2448. this.anchorVertical = 0;
  2449. this.anchorHorizontal = 0;
  2450. this.anchorPoint = 0;
  2451. this.rowCount = 1;
  2452. this.virtualRowCount = this.rowCount + 1;
  2453. this.columnCount = 41;
  2454. this.windowStyle = 0;
  2455. this.penStyle = 0;
  2456. };
  2457. Cea708Window.prototype.getText = function () {
  2458. return this.rows.join('\n');
  2459. };
  2460. Cea708Window.prototype.clearText = function () {
  2461. this.rows = [''];
  2462. this.rowIdx = 0;
  2463. };
  2464. Cea708Window.prototype.newLine = function (pts) {
  2465. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  2466. this.beforeRowOverflow(pts);
  2467. }
  2468. if (this.rows.length > 0) {
  2469. this.rows.push('');
  2470. this.rowIdx++;
  2471. } // Show all virtual rows since there's no visible scrolling
  2472. while (this.rows.length > this.virtualRowCount) {
  2473. this.rows.shift();
  2474. this.rowIdx--;
  2475. }
  2476. };
  2477. Cea708Window.prototype.isEmpty = function () {
  2478. if (this.rows.length === 0) {
  2479. return true;
  2480. } else if (this.rows.length === 1) {
  2481. return this.rows[0] === '';
  2482. }
  2483. return false;
  2484. };
  2485. Cea708Window.prototype.addText = function (text) {
  2486. this.rows[this.rowIdx] += text;
  2487. };
  2488. Cea708Window.prototype.backspace = function () {
  2489. if (!this.isEmpty()) {
  2490. var row = this.rows[this.rowIdx];
  2491. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  2492. }
  2493. };
  2494. var Cea708Service = function Cea708Service(serviceNum, encoding, stream) {
  2495. this.serviceNum = serviceNum;
  2496. this.text = '';
  2497. this.currentWindow = new Cea708Window(-1);
  2498. this.windows = [];
  2499. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  2500. if (typeof encoding === 'string') {
  2501. this.createTextDecoder(encoding);
  2502. }
  2503. };
  2504. /**
  2505. * Initialize service windows
  2506. * Must be run before service use
  2507. *
  2508. * @param {Integer} pts PTS value
  2509. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  2510. */
  2511. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  2512. this.startPts = pts;
  2513. for (var win = 0; win < 8; win++) {
  2514. this.windows[win] = new Cea708Window(win);
  2515. if (typeof beforeRowOverflow === 'function') {
  2516. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  2517. }
  2518. }
  2519. };
  2520. /**
  2521. * Set current window of service to be affected by commands
  2522. *
  2523. * @param {Integer} windowNum Window number
  2524. */
  2525. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  2526. this.currentWindow = this.windows[windowNum];
  2527. };
  2528. /**
  2529. * Try to create a TextDecoder if it is natively supported
  2530. */
  2531. Cea708Service.prototype.createTextDecoder = function (encoding) {
  2532. if (typeof TextDecoder === 'undefined') {
  2533. this.stream.trigger('log', {
  2534. level: 'warn',
  2535. message: 'The `encoding` option is unsupported without TextDecoder support'
  2536. });
  2537. } else {
  2538. try {
  2539. this.textDecoder_ = new TextDecoder(encoding);
  2540. } catch (error) {
  2541. this.stream.trigger('log', {
  2542. level: 'warn',
  2543. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  2544. });
  2545. }
  2546. }
  2547. };
  2548. var Cea708Stream = function Cea708Stream(options) {
  2549. options = options || {};
  2550. Cea708Stream.prototype.init.call(this);
  2551. var self = this;
  2552. var captionServices = options.captionServices || {};
  2553. var captionServiceEncodings = {};
  2554. var serviceProps; // Get service encodings from captionServices option block
  2555. Object.keys(captionServices).forEach(function (serviceName) {
  2556. serviceProps = captionServices[serviceName];
  2557. if (/^SERVICE/.test(serviceName)) {
  2558. captionServiceEncodings[serviceName] = serviceProps.encoding;
  2559. }
  2560. });
  2561. this.serviceEncodings = captionServiceEncodings;
  2562. this.current708Packet = null;
  2563. this.services = {};
  2564. this.push = function (packet) {
  2565. if (packet.type === 3) {
  2566. // 708 packet start
  2567. self.new708Packet();
  2568. self.add708Bytes(packet);
  2569. } else {
  2570. if (self.current708Packet === null) {
  2571. // This should only happen at the start of a file if there's no packet start.
  2572. self.new708Packet();
  2573. }
  2574. self.add708Bytes(packet);
  2575. }
  2576. };
  2577. };
  2578. Cea708Stream.prototype = new stream();
  2579. /**
  2580. * Push current 708 packet, create new 708 packet.
  2581. */
  2582. Cea708Stream.prototype.new708Packet = function () {
  2583. if (this.current708Packet !== null) {
  2584. this.push708Packet();
  2585. }
  2586. this.current708Packet = {
  2587. data: [],
  2588. ptsVals: []
  2589. };
  2590. };
  2591. /**
  2592. * Add pts and both bytes from packet into current 708 packet.
  2593. */
  2594. Cea708Stream.prototype.add708Bytes = function (packet) {
  2595. var data = packet.ccData;
  2596. var byte0 = data >>> 8;
  2597. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  2598. // that service blocks will always line up with byte pairs.
  2599. this.current708Packet.ptsVals.push(packet.pts);
  2600. this.current708Packet.data.push(byte0);
  2601. this.current708Packet.data.push(byte1);
  2602. };
  2603. /**
  2604. * Parse completed 708 packet into service blocks and push each service block.
  2605. */
  2606. Cea708Stream.prototype.push708Packet = function () {
  2607. var packet708 = this.current708Packet;
  2608. var packetData = packet708.data;
  2609. var serviceNum = null;
  2610. var blockSize = null;
  2611. var i = 0;
  2612. var b = packetData[i++];
  2613. packet708.seq = b >> 6;
  2614. packet708.sizeCode = b & 0x3f; // 0b00111111;
  2615. for (; i < packetData.length; i++) {
  2616. b = packetData[i++];
  2617. serviceNum = b >> 5;
  2618. blockSize = b & 0x1f; // 0b00011111
  2619. if (serviceNum === 7 && blockSize > 0) {
  2620. // Extended service num
  2621. b = packetData[i++];
  2622. serviceNum = b;
  2623. }
  2624. this.pushServiceBlock(serviceNum, i, blockSize);
  2625. if (blockSize > 0) {
  2626. i += blockSize - 1;
  2627. }
  2628. }
  2629. };
  2630. /**
  2631. * Parse service block, execute commands, read text.
  2632. *
  2633. * Note: While many of these commands serve important purposes,
  2634. * many others just parse out the parameters or attributes, but
  2635. * nothing is done with them because this is not a full and complete
  2636. * implementation of the entire 708 spec.
  2637. *
  2638. * @param {Integer} serviceNum Service number
  2639. * @param {Integer} start Start index of the 708 packet data
  2640. * @param {Integer} size Block size
  2641. */
  2642. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  2643. var b;
  2644. var i = start;
  2645. var packetData = this.current708Packet.data;
  2646. var service = this.services[serviceNum];
  2647. if (!service) {
  2648. service = this.initService(serviceNum, i);
  2649. }
  2650. for (; i < start + size && i < packetData.length; i++) {
  2651. b = packetData[i];
  2652. if (within708TextBlock(b)) {
  2653. i = this.handleText(i, service);
  2654. } else if (b === 0x18) {
  2655. i = this.multiByteCharacter(i, service);
  2656. } else if (b === 0x10) {
  2657. i = this.extendedCommands(i, service);
  2658. } else if (0x80 <= b && b <= 0x87) {
  2659. i = this.setCurrentWindow(i, service);
  2660. } else if (0x98 <= b && b <= 0x9f) {
  2661. i = this.defineWindow(i, service);
  2662. } else if (b === 0x88) {
  2663. i = this.clearWindows(i, service);
  2664. } else if (b === 0x8c) {
  2665. i = this.deleteWindows(i, service);
  2666. } else if (b === 0x89) {
  2667. i = this.displayWindows(i, service);
  2668. } else if (b === 0x8a) {
  2669. i = this.hideWindows(i, service);
  2670. } else if (b === 0x8b) {
  2671. i = this.toggleWindows(i, service);
  2672. } else if (b === 0x97) {
  2673. i = this.setWindowAttributes(i, service);
  2674. } else if (b === 0x90) {
  2675. i = this.setPenAttributes(i, service);
  2676. } else if (b === 0x91) {
  2677. i = this.setPenColor(i, service);
  2678. } else if (b === 0x92) {
  2679. i = this.setPenLocation(i, service);
  2680. } else if (b === 0x8f) {
  2681. service = this.reset(i, service);
  2682. } else if (b === 0x08) {
  2683. // BS: Backspace
  2684. service.currentWindow.backspace();
  2685. } else if (b === 0x0c) {
  2686. // FF: Form feed
  2687. service.currentWindow.clearText();
  2688. } else if (b === 0x0d) {
  2689. // CR: Carriage return
  2690. service.currentWindow.pendingNewLine = true;
  2691. } else if (b === 0x0e) {
  2692. // HCR: Horizontal carriage return
  2693. service.currentWindow.clearText();
  2694. } else if (b === 0x8d) {
  2695. // DLY: Delay, nothing to do
  2696. i++;
  2697. } else ;
  2698. }
  2699. };
  2700. /**
  2701. * Execute an extended command
  2702. *
  2703. * @param {Integer} i Current index in the 708 packet
  2704. * @param {Service} service The service object to be affected
  2705. * @return {Integer} New index after parsing
  2706. */
  2707. Cea708Stream.prototype.extendedCommands = function (i, service) {
  2708. var packetData = this.current708Packet.data;
  2709. var b = packetData[++i];
  2710. if (within708TextBlock(b)) {
  2711. i = this.handleText(i, service, {
  2712. isExtended: true
  2713. });
  2714. }
  2715. return i;
  2716. };
  2717. /**
  2718. * Get PTS value of a given byte index
  2719. *
  2720. * @param {Integer} byteIndex Index of the byte
  2721. * @return {Integer} PTS
  2722. */
  2723. Cea708Stream.prototype.getPts = function (byteIndex) {
  2724. // There's 1 pts value per 2 bytes
  2725. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  2726. };
  2727. /**
  2728. * Initializes a service
  2729. *
  2730. * @param {Integer} serviceNum Service number
  2731. * @return {Service} Initialized service object
  2732. */
  2733. Cea708Stream.prototype.initService = function (serviceNum, i) {
  2734. var serviceName = 'SERVICE' + serviceNum;
  2735. var self = this;
  2736. var serviceName;
  2737. var encoding;
  2738. if (serviceName in this.serviceEncodings) {
  2739. encoding = this.serviceEncodings[serviceName];
  2740. }
  2741. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  2742. this.services[serviceNum].init(this.getPts(i), function (pts) {
  2743. self.flushDisplayed(pts, self.services[serviceNum]);
  2744. });
  2745. return this.services[serviceNum];
  2746. };
  2747. /**
  2748. * Execute text writing to current window
  2749. *
  2750. * @param {Integer} i Current index in the 708 packet
  2751. * @param {Service} service The service object to be affected
  2752. * @return {Integer} New index after parsing
  2753. */
  2754. Cea708Stream.prototype.handleText = function (i, service, options) {
  2755. var isExtended = options && options.isExtended;
  2756. var isMultiByte = options && options.isMultiByte;
  2757. var packetData = this.current708Packet.data;
  2758. var extended = isExtended ? 0x1000 : 0x0000;
  2759. var currentByte = packetData[i];
  2760. var nextByte = packetData[i + 1];
  2761. var win = service.currentWindow;
  2762. var char;
  2763. var charCodeArray; // Use the TextDecoder if one was created for this service
  2764. if (service.textDecoder_ && !isExtended) {
  2765. if (isMultiByte) {
  2766. charCodeArray = [currentByte, nextByte];
  2767. i++;
  2768. } else {
  2769. charCodeArray = [currentByte];
  2770. }
  2771. char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  2772. } else {
  2773. char = get708CharFromCode(extended | currentByte);
  2774. }
  2775. if (win.pendingNewLine && !win.isEmpty()) {
  2776. win.newLine(this.getPts(i));
  2777. }
  2778. win.pendingNewLine = false;
  2779. win.addText(char);
  2780. return i;
  2781. };
  2782. /**
  2783. * Handle decoding of multibyte character
  2784. *
  2785. * @param {Integer} i Current index in the 708 packet
  2786. * @param {Service} service The service object to be affected
  2787. * @return {Integer} New index after parsing
  2788. */
  2789. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  2790. var packetData = this.current708Packet.data;
  2791. var firstByte = packetData[i + 1];
  2792. var secondByte = packetData[i + 2];
  2793. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  2794. i = this.handleText(++i, service, {
  2795. isMultiByte: true
  2796. });
  2797. }
  2798. return i;
  2799. };
  2800. /**
  2801. * Parse and execute the CW# command.
  2802. *
  2803. * Set the current window.
  2804. *
  2805. * @param {Integer} i Current index in the 708 packet
  2806. * @param {Service} service The service object to be affected
  2807. * @return {Integer} New index after parsing
  2808. */
  2809. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  2810. var packetData = this.current708Packet.data;
  2811. var b = packetData[i];
  2812. var windowNum = b & 0x07;
  2813. service.setCurrentWindow(windowNum);
  2814. return i;
  2815. };
  2816. /**
  2817. * Parse and execute the DF# command.
  2818. *
  2819. * Define a window and set it as the current window.
  2820. *
  2821. * @param {Integer} i Current index in the 708 packet
  2822. * @param {Service} service The service object to be affected
  2823. * @return {Integer} New index after parsing
  2824. */
  2825. Cea708Stream.prototype.defineWindow = function (i, service) {
  2826. var packetData = this.current708Packet.data;
  2827. var b = packetData[i];
  2828. var windowNum = b & 0x07;
  2829. service.setCurrentWindow(windowNum);
  2830. var win = service.currentWindow;
  2831. b = packetData[++i];
  2832. win.visible = (b & 0x20) >> 5; // v
  2833. win.rowLock = (b & 0x10) >> 4; // rl
  2834. win.columnLock = (b & 0x08) >> 3; // cl
  2835. win.priority = b & 0x07; // p
  2836. b = packetData[++i];
  2837. win.relativePositioning = (b & 0x80) >> 7; // rp
  2838. win.anchorVertical = b & 0x7f; // av
  2839. b = packetData[++i];
  2840. win.anchorHorizontal = b; // ah
  2841. b = packetData[++i];
  2842. win.anchorPoint = (b & 0xf0) >> 4; // ap
  2843. win.rowCount = b & 0x0f; // rc
  2844. b = packetData[++i];
  2845. win.columnCount = b & 0x3f; // cc
  2846. b = packetData[++i];
  2847. win.windowStyle = (b & 0x38) >> 3; // ws
  2848. win.penStyle = b & 0x07; // ps
  2849. // The spec says there are (rowCount+1) "virtual rows"
  2850. win.virtualRowCount = win.rowCount + 1;
  2851. return i;
  2852. };
  2853. /**
  2854. * Parse and execute the SWA command.
  2855. *
  2856. * Set attributes of the current window.
  2857. *
  2858. * @param {Integer} i Current index in the 708 packet
  2859. * @param {Service} service The service object to be affected
  2860. * @return {Integer} New index after parsing
  2861. */
  2862. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  2863. var packetData = this.current708Packet.data;
  2864. var b = packetData[i];
  2865. var winAttr = service.currentWindow.winAttr;
  2866. b = packetData[++i];
  2867. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  2868. winAttr.fillRed = (b & 0x30) >> 4; // fr
  2869. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  2870. winAttr.fillBlue = b & 0x03; // fb
  2871. b = packetData[++i];
  2872. winAttr.borderType = (b & 0xc0) >> 6; // bt
  2873. winAttr.borderRed = (b & 0x30) >> 4; // br
  2874. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  2875. winAttr.borderBlue = b & 0x03; // bb
  2876. b = packetData[++i];
  2877. winAttr.borderType += (b & 0x80) >> 5; // bt
  2878. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  2879. winAttr.printDirection = (b & 0x30) >> 4; // pd
  2880. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  2881. winAttr.justify = b & 0x03; // j
  2882. b = packetData[++i];
  2883. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  2884. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  2885. winAttr.displayEffect = b & 0x03; // de
  2886. return i;
  2887. };
  2888. /**
  2889. * Gather text from all displayed windows and push a caption to output.
  2890. *
  2891. * @param {Integer} i Current index in the 708 packet
  2892. * @param {Service} service The service object to be affected
  2893. */
  2894. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  2895. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  2896. // display text in the correct order, but sample files so far have not shown any issue.
  2897. for (var winId = 0; winId < 8; winId++) {
  2898. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  2899. displayedText.push(service.windows[winId].getText());
  2900. }
  2901. }
  2902. service.endPts = pts;
  2903. service.text = displayedText.join('\n\n');
  2904. this.pushCaption(service);
  2905. service.startPts = pts;
  2906. };
  2907. /**
  2908. * Push a caption to output if the caption contains text.
  2909. *
  2910. * @param {Service} service The service object to be affected
  2911. */
  2912. Cea708Stream.prototype.pushCaption = function (service) {
  2913. if (service.text !== '') {
  2914. this.trigger('data', {
  2915. startPts: service.startPts,
  2916. endPts: service.endPts,
  2917. text: service.text,
  2918. stream: 'cc708_' + service.serviceNum
  2919. });
  2920. service.text = '';
  2921. service.startPts = service.endPts;
  2922. }
  2923. };
  2924. /**
  2925. * Parse and execute the DSW command.
  2926. *
  2927. * Set visible property of windows based on the parsed bitmask.
  2928. *
  2929. * @param {Integer} i Current index in the 708 packet
  2930. * @param {Service} service The service object to be affected
  2931. * @return {Integer} New index after parsing
  2932. */
  2933. Cea708Stream.prototype.displayWindows = function (i, service) {
  2934. var packetData = this.current708Packet.data;
  2935. var b = packetData[++i];
  2936. var pts = this.getPts(i);
  2937. this.flushDisplayed(pts, service);
  2938. for (var winId = 0; winId < 8; winId++) {
  2939. if (b & 0x01 << winId) {
  2940. service.windows[winId].visible = 1;
  2941. }
  2942. }
  2943. return i;
  2944. };
  2945. /**
  2946. * Parse and execute the HDW command.
  2947. *
  2948. * Set visible property of windows based on the parsed bitmask.
  2949. *
  2950. * @param {Integer} i Current index in the 708 packet
  2951. * @param {Service} service The service object to be affected
  2952. * @return {Integer} New index after parsing
  2953. */
  2954. Cea708Stream.prototype.hideWindows = function (i, service) {
  2955. var packetData = this.current708Packet.data;
  2956. var b = packetData[++i];
  2957. var pts = this.getPts(i);
  2958. this.flushDisplayed(pts, service);
  2959. for (var winId = 0; winId < 8; winId++) {
  2960. if (b & 0x01 << winId) {
  2961. service.windows[winId].visible = 0;
  2962. }
  2963. }
  2964. return i;
  2965. };
  2966. /**
  2967. * Parse and execute the TGW command.
  2968. *
  2969. * Set visible property of windows based on the parsed bitmask.
  2970. *
  2971. * @param {Integer} i Current index in the 708 packet
  2972. * @param {Service} service The service object to be affected
  2973. * @return {Integer} New index after parsing
  2974. */
  2975. Cea708Stream.prototype.toggleWindows = function (i, service) {
  2976. var packetData = this.current708Packet.data;
  2977. var b = packetData[++i];
  2978. var pts = this.getPts(i);
  2979. this.flushDisplayed(pts, service);
  2980. for (var winId = 0; winId < 8; winId++) {
  2981. if (b & 0x01 << winId) {
  2982. service.windows[winId].visible ^= 1;
  2983. }
  2984. }
  2985. return i;
  2986. };
  2987. /**
  2988. * Parse and execute the CLW command.
  2989. *
  2990. * Clear text of windows based on the parsed bitmask.
  2991. *
  2992. * @param {Integer} i Current index in the 708 packet
  2993. * @param {Service} service The service object to be affected
  2994. * @return {Integer} New index after parsing
  2995. */
  2996. Cea708Stream.prototype.clearWindows = function (i, service) {
  2997. var packetData = this.current708Packet.data;
  2998. var b = packetData[++i];
  2999. var pts = this.getPts(i);
  3000. this.flushDisplayed(pts, service);
  3001. for (var winId = 0; winId < 8; winId++) {
  3002. if (b & 0x01 << winId) {
  3003. service.windows[winId].clearText();
  3004. }
  3005. }
  3006. return i;
  3007. };
  3008. /**
  3009. * Parse and execute the DLW command.
  3010. *
  3011. * Re-initialize windows based on the parsed bitmask.
  3012. *
  3013. * @param {Integer} i Current index in the 708 packet
  3014. * @param {Service} service The service object to be affected
  3015. * @return {Integer} New index after parsing
  3016. */
  3017. Cea708Stream.prototype.deleteWindows = function (i, service) {
  3018. var packetData = this.current708Packet.data;
  3019. var b = packetData[++i];
  3020. var pts = this.getPts(i);
  3021. this.flushDisplayed(pts, service);
  3022. for (var winId = 0; winId < 8; winId++) {
  3023. if (b & 0x01 << winId) {
  3024. service.windows[winId].reset();
  3025. }
  3026. }
  3027. return i;
  3028. };
  3029. /**
  3030. * Parse and execute the SPA command.
  3031. *
  3032. * Set pen attributes of the current window.
  3033. *
  3034. * @param {Integer} i Current index in the 708 packet
  3035. * @param {Service} service The service object to be affected
  3036. * @return {Integer} New index after parsing
  3037. */
  3038. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  3039. var packetData = this.current708Packet.data;
  3040. var b = packetData[i];
  3041. var penAttr = service.currentWindow.penAttr;
  3042. b = packetData[++i];
  3043. penAttr.textTag = (b & 0xf0) >> 4; // tt
  3044. penAttr.offset = (b & 0x0c) >> 2; // o
  3045. penAttr.penSize = b & 0x03; // s
  3046. b = packetData[++i];
  3047. penAttr.italics = (b & 0x80) >> 7; // i
  3048. penAttr.underline = (b & 0x40) >> 6; // u
  3049. penAttr.edgeType = (b & 0x38) >> 3; // et
  3050. penAttr.fontStyle = b & 0x07; // fs
  3051. return i;
  3052. };
  3053. /**
  3054. * Parse and execute the SPC command.
  3055. *
  3056. * Set pen color of the current window.
  3057. *
  3058. * @param {Integer} i Current index in the 708 packet
  3059. * @param {Service} service The service object to be affected
  3060. * @return {Integer} New index after parsing
  3061. */
  3062. Cea708Stream.prototype.setPenColor = function (i, service) {
  3063. var packetData = this.current708Packet.data;
  3064. var b = packetData[i];
  3065. var penColor = service.currentWindow.penColor;
  3066. b = packetData[++i];
  3067. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  3068. penColor.fgRed = (b & 0x30) >> 4; // fr
  3069. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  3070. penColor.fgBlue = b & 0x03; // fb
  3071. b = packetData[++i];
  3072. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  3073. penColor.bgRed = (b & 0x30) >> 4; // br
  3074. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  3075. penColor.bgBlue = b & 0x03; // bb
  3076. b = packetData[++i];
  3077. penColor.edgeRed = (b & 0x30) >> 4; // er
  3078. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  3079. penColor.edgeBlue = b & 0x03; // eb
  3080. return i;
  3081. };
  3082. /**
  3083. * Parse and execute the SPL command.
  3084. *
  3085. * Set pen location of the current window.
  3086. *
  3087. * @param {Integer} i Current index in the 708 packet
  3088. * @param {Service} service The service object to be affected
  3089. * @return {Integer} New index after parsing
  3090. */
  3091. Cea708Stream.prototype.setPenLocation = function (i, service) {
  3092. var packetData = this.current708Packet.data;
  3093. var b = packetData[i];
  3094. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  3095. service.currentWindow.pendingNewLine = true;
  3096. b = packetData[++i];
  3097. penLoc.row = b & 0x0f; // r
  3098. b = packetData[++i];
  3099. penLoc.column = b & 0x3f; // c
  3100. return i;
  3101. };
  3102. /**
  3103. * Execute the RST command.
  3104. *
  3105. * Reset service to a clean slate. Re-initialize.
  3106. *
  3107. * @param {Integer} i Current index in the 708 packet
  3108. * @param {Service} service The service object to be affected
  3109. * @return {Service} Re-initialized service
  3110. */
  3111. Cea708Stream.prototype.reset = function (i, service) {
  3112. var pts = this.getPts(i);
  3113. this.flushDisplayed(pts, service);
  3114. return this.initService(service.serviceNum, i);
  3115. }; // This hash maps non-ASCII, special, and extended character codes to their
  3116. // proper Unicode equivalent. The first keys that are only a single byte
  3117. // are the non-standard ASCII characters, which simply map the CEA608 byte
  3118. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  3119. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  3120. // can be performed regardless of the field and data channel on which the
  3121. // character code was received.
  3122. var CHARACTER_TRANSLATION = {
  3123. 0x2a: 0xe1,
  3124. // á
  3125. 0x5c: 0xe9,
  3126. // é
  3127. 0x5e: 0xed,
  3128. // í
  3129. 0x5f: 0xf3,
  3130. // ó
  3131. 0x60: 0xfa,
  3132. // ú
  3133. 0x7b: 0xe7,
  3134. // ç
  3135. 0x7c: 0xf7,
  3136. // ÷
  3137. 0x7d: 0xd1,
  3138. // Ñ
  3139. 0x7e: 0xf1,
  3140. // ñ
  3141. 0x7f: 0x2588,
  3142. // █
  3143. 0x0130: 0xae,
  3144. // ®
  3145. 0x0131: 0xb0,
  3146. // °
  3147. 0x0132: 0xbd,
  3148. // ½
  3149. 0x0133: 0xbf,
  3150. // ¿
  3151. 0x0134: 0x2122,
  3152. // ™
  3153. 0x0135: 0xa2,
  3154. // ¢
  3155. 0x0136: 0xa3,
  3156. // £
  3157. 0x0137: 0x266a,
  3158. // ♪
  3159. 0x0138: 0xe0,
  3160. // à
  3161. 0x0139: 0xa0,
  3162. //
  3163. 0x013a: 0xe8,
  3164. // è
  3165. 0x013b: 0xe2,
  3166. // â
  3167. 0x013c: 0xea,
  3168. // ê
  3169. 0x013d: 0xee,
  3170. // î
  3171. 0x013e: 0xf4,
  3172. // ô
  3173. 0x013f: 0xfb,
  3174. // û
  3175. 0x0220: 0xc1,
  3176. // Á
  3177. 0x0221: 0xc9,
  3178. // É
  3179. 0x0222: 0xd3,
  3180. // Ó
  3181. 0x0223: 0xda,
  3182. // Ú
  3183. 0x0224: 0xdc,
  3184. // Ü
  3185. 0x0225: 0xfc,
  3186. // ü
  3187. 0x0226: 0x2018,
  3188. // ‘
  3189. 0x0227: 0xa1,
  3190. // ¡
  3191. 0x0228: 0x2a,
  3192. // *
  3193. 0x0229: 0x27,
  3194. // '
  3195. 0x022a: 0x2014,
  3196. // —
  3197. 0x022b: 0xa9,
  3198. // ©
  3199. 0x022c: 0x2120,
  3200. // ℠
  3201. 0x022d: 0x2022,
  3202. // •
  3203. 0x022e: 0x201c,
  3204. // “
  3205. 0x022f: 0x201d,
  3206. // ”
  3207. 0x0230: 0xc0,
  3208. // À
  3209. 0x0231: 0xc2,
  3210. // Â
  3211. 0x0232: 0xc7,
  3212. // Ç
  3213. 0x0233: 0xc8,
  3214. // È
  3215. 0x0234: 0xca,
  3216. // Ê
  3217. 0x0235: 0xcb,
  3218. // Ë
  3219. 0x0236: 0xeb,
  3220. // ë
  3221. 0x0237: 0xce,
  3222. // Î
  3223. 0x0238: 0xcf,
  3224. // Ï
  3225. 0x0239: 0xef,
  3226. // ï
  3227. 0x023a: 0xd4,
  3228. // Ô
  3229. 0x023b: 0xd9,
  3230. // Ù
  3231. 0x023c: 0xf9,
  3232. // ù
  3233. 0x023d: 0xdb,
  3234. // Û
  3235. 0x023e: 0xab,
  3236. // «
  3237. 0x023f: 0xbb,
  3238. // »
  3239. 0x0320: 0xc3,
  3240. // Ã
  3241. 0x0321: 0xe3,
  3242. // ã
  3243. 0x0322: 0xcd,
  3244. // Í
  3245. 0x0323: 0xcc,
  3246. // Ì
  3247. 0x0324: 0xec,
  3248. // ì
  3249. 0x0325: 0xd2,
  3250. // Ò
  3251. 0x0326: 0xf2,
  3252. // ò
  3253. 0x0327: 0xd5,
  3254. // Õ
  3255. 0x0328: 0xf5,
  3256. // õ
  3257. 0x0329: 0x7b,
  3258. // {
  3259. 0x032a: 0x7d,
  3260. // }
  3261. 0x032b: 0x5c,
  3262. // \
  3263. 0x032c: 0x5e,
  3264. // ^
  3265. 0x032d: 0x5f,
  3266. // _
  3267. 0x032e: 0x7c,
  3268. // |
  3269. 0x032f: 0x7e,
  3270. // ~
  3271. 0x0330: 0xc4,
  3272. // Ä
  3273. 0x0331: 0xe4,
  3274. // ä
  3275. 0x0332: 0xd6,
  3276. // Ö
  3277. 0x0333: 0xf6,
  3278. // ö
  3279. 0x0334: 0xdf,
  3280. // ß
  3281. 0x0335: 0xa5,
  3282. // ¥
  3283. 0x0336: 0xa4,
  3284. // ¤
  3285. 0x0337: 0x2502,
  3286. // │
  3287. 0x0338: 0xc5,
  3288. // Å
  3289. 0x0339: 0xe5,
  3290. // å
  3291. 0x033a: 0xd8,
  3292. // Ø
  3293. 0x033b: 0xf8,
  3294. // ø
  3295. 0x033c: 0x250c,
  3296. // ┌
  3297. 0x033d: 0x2510,
  3298. // ┐
  3299. 0x033e: 0x2514,
  3300. // └
  3301. 0x033f: 0x2518 // ┘
  3302. };
  3303. var getCharFromCode = function getCharFromCode(code) {
  3304. if (code === null) {
  3305. return '';
  3306. }
  3307. code = CHARACTER_TRANSLATION[code] || code;
  3308. return String.fromCharCode(code);
  3309. }; // the index of the last row in a CEA-608 display buffer
  3310. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  3311. // getting it through bit logic.
  3312. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
  3313. // cells. The "bottom" row is the last element in the outer array.
  3314. var createDisplayBuffer = function createDisplayBuffer() {
  3315. var result = [],
  3316. i = BOTTOM_ROW + 1;
  3317. while (i--) {
  3318. result.push('');
  3319. }
  3320. return result;
  3321. };
  3322. var Cea608Stream = function Cea608Stream(field, dataChannel) {
  3323. Cea608Stream.prototype.init.call(this);
  3324. this.field_ = field || 0;
  3325. this.dataChannel_ = dataChannel || 0;
  3326. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  3327. this.setConstants();
  3328. this.reset();
  3329. this.push = function (packet) {
  3330. var data, swap, char0, char1, text; // remove the parity bits
  3331. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  3332. if (data === this.lastControlCode_) {
  3333. this.lastControlCode_ = null;
  3334. return;
  3335. } // Store control codes
  3336. if ((data & 0xf000) === 0x1000) {
  3337. this.lastControlCode_ = data;
  3338. } else if (data !== this.PADDING_) {
  3339. this.lastControlCode_ = null;
  3340. }
  3341. char0 = data >>> 8;
  3342. char1 = data & 0xff;
  3343. if (data === this.PADDING_) {
  3344. return;
  3345. } else if (data === this.RESUME_CAPTION_LOADING_) {
  3346. this.mode_ = 'popOn';
  3347. } else if (data === this.END_OF_CAPTION_) {
  3348. // If an EOC is received while in paint-on mode, the displayed caption
  3349. // text should be swapped to non-displayed memory as if it was a pop-on
  3350. // caption. Because of that, we should explicitly switch back to pop-on
  3351. // mode
  3352. this.mode_ = 'popOn';
  3353. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  3354. this.flushDisplayed(packet.pts); // flip memory
  3355. swap = this.displayed_;
  3356. this.displayed_ = this.nonDisplayed_;
  3357. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  3358. this.startPts_ = packet.pts;
  3359. } else if (data === this.ROLL_UP_2_ROWS_) {
  3360. this.rollUpRows_ = 2;
  3361. this.setRollUp(packet.pts);
  3362. } else if (data === this.ROLL_UP_3_ROWS_) {
  3363. this.rollUpRows_ = 3;
  3364. this.setRollUp(packet.pts);
  3365. } else if (data === this.ROLL_UP_4_ROWS_) {
  3366. this.rollUpRows_ = 4;
  3367. this.setRollUp(packet.pts);
  3368. } else if (data === this.CARRIAGE_RETURN_) {
  3369. this.clearFormatting(packet.pts);
  3370. this.flushDisplayed(packet.pts);
  3371. this.shiftRowsUp_();
  3372. this.startPts_ = packet.pts;
  3373. } else if (data === this.BACKSPACE_) {
  3374. if (this.mode_ === 'popOn') {
  3375. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  3376. } else {
  3377. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  3378. }
  3379. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  3380. this.flushDisplayed(packet.pts);
  3381. this.displayed_ = createDisplayBuffer();
  3382. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  3383. this.nonDisplayed_ = createDisplayBuffer();
  3384. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  3385. if (this.mode_ !== 'paintOn') {
  3386. // NOTE: This should be removed when proper caption positioning is
  3387. // implemented
  3388. this.flushDisplayed(packet.pts);
  3389. this.displayed_ = createDisplayBuffer();
  3390. }
  3391. this.mode_ = 'paintOn';
  3392. this.startPts_ = packet.pts; // Append special characters to caption text
  3393. } else if (this.isSpecialCharacter(char0, char1)) {
  3394. // Bitmask char0 so that we can apply character transformations
  3395. // regardless of field and data channel.
  3396. // Then byte-shift to the left and OR with char1 so we can pass the
  3397. // entire character code to `getCharFromCode`.
  3398. char0 = (char0 & 0x03) << 8;
  3399. text = getCharFromCode(char0 | char1);
  3400. this[this.mode_](packet.pts, text);
  3401. this.column_++; // Append extended characters to caption text
  3402. } else if (this.isExtCharacter(char0, char1)) {
  3403. // Extended characters always follow their "non-extended" equivalents.
  3404. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  3405. // decoders are supposed to drop the "è", while compliant decoders
  3406. // backspace the "e" and insert "è".
  3407. // Delete the previous character
  3408. if (this.mode_ === 'popOn') {
  3409. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  3410. } else {
  3411. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  3412. } // Bitmask char0 so that we can apply character transformations
  3413. // regardless of field and data channel.
  3414. // Then byte-shift to the left and OR with char1 so we can pass the
  3415. // entire character code to `getCharFromCode`.
  3416. char0 = (char0 & 0x03) << 8;
  3417. text = getCharFromCode(char0 | char1);
  3418. this[this.mode_](packet.pts, text);
  3419. this.column_++; // Process mid-row codes
  3420. } else if (this.isMidRowCode(char0, char1)) {
  3421. // Attributes are not additive, so clear all formatting
  3422. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  3423. // should be replaced with spaces, so add one now
  3424. this[this.mode_](packet.pts, ' ');
  3425. this.column_++;
  3426. if ((char1 & 0xe) === 0xe) {
  3427. this.addFormatting(packet.pts, ['i']);
  3428. }
  3429. if ((char1 & 0x1) === 0x1) {
  3430. this.addFormatting(packet.pts, ['u']);
  3431. } // Detect offset control codes and adjust cursor
  3432. } else if (this.isOffsetControlCode(char0, char1)) {
  3433. // Cursor position is set by indent PAC (see below) in 4-column
  3434. // increments, with an additional offset code of 1-3 to reach any
  3435. // of the 32 columns specified by CEA-608. So all we need to do
  3436. // here is increment the column cursor by the given offset.
  3437. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  3438. } else if (this.isPAC(char0, char1)) {
  3439. // There's no logic for PAC -> row mapping, so we have to just
  3440. // find the row code in an array and use its index :(
  3441. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  3442. if (this.mode_ === 'rollUp') {
  3443. // This implies that the base row is incorrectly set.
  3444. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  3445. // of roll-up rows set.
  3446. if (row - this.rollUpRows_ + 1 < 0) {
  3447. row = this.rollUpRows_ - 1;
  3448. }
  3449. this.setRollUp(packet.pts, row);
  3450. }
  3451. if (row !== this.row_) {
  3452. // formatting is only persistent for current row
  3453. this.clearFormatting(packet.pts);
  3454. this.row_ = row;
  3455. } // All PACs can apply underline, so detect and apply
  3456. // (All odd-numbered second bytes set underline)
  3457. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  3458. this.addFormatting(packet.pts, ['u']);
  3459. }
  3460. if ((data & 0x10) === 0x10) {
  3461. // We've got an indent level code. Each successive even number
  3462. // increments the column cursor by 4, so we can get the desired
  3463. // column position by bit-shifting to the right (to get n/2)
  3464. // and multiplying by 4.
  3465. this.column_ = ((data & 0xe) >> 1) * 4;
  3466. }
  3467. if (this.isColorPAC(char1)) {
  3468. // it's a color code, though we only support white, which
  3469. // can be either normal or italicized. white italics can be
  3470. // either 0x4e or 0x6e depending on the row, so we just
  3471. // bitwise-and with 0xe to see if italics should be turned on
  3472. if ((char1 & 0xe) === 0xe) {
  3473. this.addFormatting(packet.pts, ['i']);
  3474. }
  3475. } // We have a normal character in char0, and possibly one in char1
  3476. } else if (this.isNormalChar(char0)) {
  3477. if (char1 === 0x00) {
  3478. char1 = null;
  3479. }
  3480. text = getCharFromCode(char0);
  3481. text += getCharFromCode(char1);
  3482. this[this.mode_](packet.pts, text);
  3483. this.column_ += text.length;
  3484. } // finish data processing
  3485. };
  3486. };
  3487. Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
  3488. // display buffer
  3489. Cea608Stream.prototype.flushDisplayed = function (pts) {
  3490. var content = this.displayed_ // remove spaces from the start and end of the string
  3491. .map(function (row, index) {
  3492. try {
  3493. return row.trim();
  3494. } catch (e) {
  3495. // Ordinarily, this shouldn't happen. However, caption
  3496. // parsing errors should not throw exceptions and
  3497. // break playback.
  3498. this.trigger('log', {
  3499. level: 'warn',
  3500. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  3501. });
  3502. return '';
  3503. }
  3504. }, this) // combine all text rows to display in one cue
  3505. .join('\n') // and remove blank rows from the start and end, but not the middle
  3506. .replace(/^\n+|\n+$/g, '');
  3507. if (content.length) {
  3508. this.trigger('data', {
  3509. startPts: this.startPts_,
  3510. endPts: pts,
  3511. text: content,
  3512. stream: this.name_
  3513. });
  3514. }
  3515. };
  3516. /**
  3517. * Zero out the data, used for startup and on seek
  3518. */
  3519. Cea608Stream.prototype.reset = function () {
  3520. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  3521. // actually display captions. If a caption is shifted to a row
  3522. // with a lower index than this, it is cleared from the display
  3523. // buffer
  3524. this.topRow_ = 0;
  3525. this.startPts_ = 0;
  3526. this.displayed_ = createDisplayBuffer();
  3527. this.nonDisplayed_ = createDisplayBuffer();
  3528. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  3529. this.column_ = 0;
  3530. this.row_ = BOTTOM_ROW;
  3531. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  3532. this.formatting_ = [];
  3533. };
  3534. /**
  3535. * Sets up control code and related constants for this instance
  3536. */
  3537. Cea608Stream.prototype.setConstants = function () {
  3538. // The following attributes have these uses:
  3539. // ext_ : char0 for mid-row codes, and the base for extended
  3540. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  3541. // extended codes)
  3542. // control_: char0 for control codes, except byte-shifted to the
  3543. // left so that we can do this.control_ | CONTROL_CODE
  3544. // offset_: char0 for tab offset codes
  3545. //
  3546. // It's also worth noting that control codes, and _only_ control codes,
  3547. // differ between field 1 and field2. Field 2 control codes are always
  3548. // their field 1 value plus 1. That's why there's the "| field" on the
  3549. // control value.
  3550. if (this.dataChannel_ === 0) {
  3551. this.BASE_ = 0x10;
  3552. this.EXT_ = 0x11;
  3553. this.CONTROL_ = (0x14 | this.field_) << 8;
  3554. this.OFFSET_ = 0x17;
  3555. } else if (this.dataChannel_ === 1) {
  3556. this.BASE_ = 0x18;
  3557. this.EXT_ = 0x19;
  3558. this.CONTROL_ = (0x1c | this.field_) << 8;
  3559. this.OFFSET_ = 0x1f;
  3560. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  3561. // list is not exhaustive. For a more comprehensive listing and semantics see
  3562. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  3563. // Padding
  3564. this.PADDING_ = 0x0000; // Pop-on Mode
  3565. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  3566. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  3567. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  3568. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  3569. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  3570. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  3571. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  3572. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  3573. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  3574. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  3575. };
  3576. /**
  3577. * Detects if the 2-byte packet data is a special character
  3578. *
  3579. * Special characters have a second byte in the range 0x30 to 0x3f,
  3580. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  3581. * data channel 2).
  3582. *
  3583. * @param {Integer} char0 The first byte
  3584. * @param {Integer} char1 The second byte
  3585. * @return {Boolean} Whether the 2 bytes are an special character
  3586. */
  3587. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  3588. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  3589. };
  3590. /**
  3591. * Detects if the 2-byte packet data is an extended character
  3592. *
  3593. * Extended characters have a second byte in the range 0x20 to 0x3f,
  3594. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  3595. * 0x1a or 0x1b (for data channel 2).
  3596. *
  3597. * @param {Integer} char0 The first byte
  3598. * @param {Integer} char1 The second byte
  3599. * @return {Boolean} Whether the 2 bytes are an extended character
  3600. */
  3601. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  3602. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  3603. };
  3604. /**
  3605. * Detects if the 2-byte packet is a mid-row code
  3606. *
  3607. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  3608. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  3609. * channel 2).
  3610. *
  3611. * @param {Integer} char0 The first byte
  3612. * @param {Integer} char1 The second byte
  3613. * @return {Boolean} Whether the 2 bytes are a mid-row code
  3614. */
  3615. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  3616. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  3617. };
  3618. /**
  3619. * Detects if the 2-byte packet is an offset control code
  3620. *
  3621. * Offset control codes have a second byte in the range 0x21 to 0x23,
  3622. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  3623. * data channel 2).
  3624. *
  3625. * @param {Integer} char0 The first byte
  3626. * @param {Integer} char1 The second byte
  3627. * @return {Boolean} Whether the 2 bytes are an offset control code
  3628. */
  3629. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  3630. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  3631. };
  3632. /**
  3633. * Detects if the 2-byte packet is a Preamble Address Code
  3634. *
  3635. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  3636. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  3637. * range 0x40 to 0x7f.
  3638. *
  3639. * @param {Integer} char0 The first byte
  3640. * @param {Integer} char1 The second byte
  3641. * @return {Boolean} Whether the 2 bytes are a PAC
  3642. */
  3643. Cea608Stream.prototype.isPAC = function (char0, char1) {
  3644. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  3645. };
  3646. /**
  3647. * Detects if a packet's second byte is in the range of a PAC color code
  3648. *
  3649. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  3650. * 0x60 to 0x6f.
  3651. *
  3652. * @param {Integer} char1 The second byte
  3653. * @return {Boolean} Whether the byte is a color PAC
  3654. */
  3655. Cea608Stream.prototype.isColorPAC = function (char1) {
  3656. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  3657. };
  3658. /**
  3659. * Detects if a single byte is in the range of a normal character
  3660. *
  3661. * Normal text bytes are in the range 0x20 to 0x7f.
  3662. *
  3663. * @param {Integer} char The byte
  3664. * @return {Boolean} Whether the byte is a normal character
  3665. */
  3666. Cea608Stream.prototype.isNormalChar = function (char) {
  3667. return char >= 0x20 && char <= 0x7f;
  3668. };
  3669. /**
  3670. * Configures roll-up
  3671. *
  3672. * @param {Integer} pts Current PTS
  3673. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  3674. * a new position
  3675. */
  3676. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  3677. // Reset the base row to the bottom row when switching modes
  3678. if (this.mode_ !== 'rollUp') {
  3679. this.row_ = BOTTOM_ROW;
  3680. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  3681. this.flushDisplayed(pts);
  3682. this.nonDisplayed_ = createDisplayBuffer();
  3683. this.displayed_ = createDisplayBuffer();
  3684. }
  3685. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  3686. // move currently displayed captions (up or down) to the new base row
  3687. for (var i = 0; i < this.rollUpRows_; i++) {
  3688. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  3689. this.displayed_[this.row_ - i] = '';
  3690. }
  3691. }
  3692. if (newBaseRow === undefined) {
  3693. newBaseRow = this.row_;
  3694. }
  3695. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  3696. }; // Adds the opening HTML tag for the passed character to the caption text,
  3697. // and keeps track of it for later closing
  3698. Cea608Stream.prototype.addFormatting = function (pts, format) {
  3699. this.formatting_ = this.formatting_.concat(format);
  3700. var text = format.reduce(function (text, format) {
  3701. return text + '<' + format + '>';
  3702. }, '');
  3703. this[this.mode_](pts, text);
  3704. }; // Adds HTML closing tags for current formatting to caption text and
  3705. // clears remembered formatting
  3706. Cea608Stream.prototype.clearFormatting = function (pts) {
  3707. if (!this.formatting_.length) {
  3708. return;
  3709. }
  3710. var text = this.formatting_.reverse().reduce(function (text, format) {
  3711. return text + '</' + format + '>';
  3712. }, '');
  3713. this.formatting_ = [];
  3714. this[this.mode_](pts, text);
  3715. }; // Mode Implementations
  3716. Cea608Stream.prototype.popOn = function (pts, text) {
  3717. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  3718. baseRow += text;
  3719. this.nonDisplayed_[this.row_] = baseRow;
  3720. };
  3721. Cea608Stream.prototype.rollUp = function (pts, text) {
  3722. var baseRow = this.displayed_[this.row_];
  3723. baseRow += text;
  3724. this.displayed_[this.row_] = baseRow;
  3725. };
  3726. Cea608Stream.prototype.shiftRowsUp_ = function () {
  3727. var i; // clear out inactive rows
  3728. for (i = 0; i < this.topRow_; i++) {
  3729. this.displayed_[i] = '';
  3730. }
  3731. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  3732. this.displayed_[i] = '';
  3733. } // shift displayed rows up
  3734. for (i = this.topRow_; i < this.row_; i++) {
  3735. this.displayed_[i] = this.displayed_[i + 1];
  3736. } // clear out the bottom row
  3737. this.displayed_[this.row_] = '';
  3738. };
  3739. Cea608Stream.prototype.paintOn = function (pts, text) {
  3740. var baseRow = this.displayed_[this.row_];
  3741. baseRow += text;
  3742. this.displayed_[this.row_] = baseRow;
  3743. }; // exports
  3744. var captionStream = {
  3745. CaptionStream: CaptionStream$1,
  3746. Cea608Stream: Cea608Stream,
  3747. Cea708Stream: Cea708Stream
  3748. };
  3749. /**
  3750. * mux.js
  3751. *
  3752. * Copyright (c) Brightcove
  3753. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3754. */
  3755. var streamTypes = {
  3756. H264_STREAM_TYPE: 0x1B,
  3757. ADTS_STREAM_TYPE: 0x0F,
  3758. METADATA_STREAM_TYPE: 0x15
  3759. };
  3760. var MAX_TS = 8589934592;
  3761. var RO_THRESH = 4294967296;
  3762. var TYPE_SHARED = 'shared';
  3763. var handleRollover = function handleRollover(value, reference) {
  3764. var direction = 1;
  3765. if (value > reference) {
  3766. // If the current timestamp value is greater than our reference timestamp and we detect a
  3767. // timestamp rollover, this means the roll over is happening in the opposite direction.
  3768. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  3769. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  3770. // rollover point. In loading this segment, the timestamp values will be very large,
  3771. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  3772. // the time stamp to be `value - 2^33`.
  3773. direction = -1;
  3774. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  3775. // cause an incorrect adjustment.
  3776. while (Math.abs(reference - value) > RO_THRESH) {
  3777. value += direction * MAX_TS;
  3778. }
  3779. return value;
  3780. };
  3781. var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
  3782. var lastDTS, referenceDTS;
  3783. TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  3784. // video and audio. We could use `undefined` here, but having a string
  3785. // makes debugging a little clearer.
  3786. this.type_ = type || TYPE_SHARED;
  3787. this.push = function (data) {
  3788. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  3789. // streams will only accept data that matches their type.
  3790. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  3791. return;
  3792. }
  3793. if (referenceDTS === undefined) {
  3794. referenceDTS = data.dts;
  3795. }
  3796. data.dts = handleRollover(data.dts, referenceDTS);
  3797. data.pts = handleRollover(data.pts, referenceDTS);
  3798. lastDTS = data.dts;
  3799. this.trigger('data', data);
  3800. };
  3801. this.flush = function () {
  3802. referenceDTS = lastDTS;
  3803. this.trigger('done');
  3804. };
  3805. this.endTimeline = function () {
  3806. this.flush();
  3807. this.trigger('endedtimeline');
  3808. };
  3809. this.discontinuity = function () {
  3810. referenceDTS = void 0;
  3811. lastDTS = void 0;
  3812. };
  3813. this.reset = function () {
  3814. this.discontinuity();
  3815. this.trigger('reset');
  3816. };
  3817. };
  3818. TimestampRolloverStream$1.prototype = new stream();
  3819. var timestampRolloverStream = {
  3820. TimestampRolloverStream: TimestampRolloverStream$1,
  3821. handleRollover: handleRollover
  3822. };
  3823. var _MetadataStream;
  3824. _MetadataStream = function MetadataStream(options) {
  3825. var settings = {
  3826. // the bytes of the program-level descriptor field in MP2T
  3827. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  3828. // program element descriptors"
  3829. descriptor: options && options.descriptor
  3830. },
  3831. // the total size in bytes of the ID3 tag being parsed
  3832. tagSize = 0,
  3833. // tag data that is not complete enough to be parsed
  3834. buffer = [],
  3835. // the total number of bytes currently in the buffer
  3836. bufferSize = 0,
  3837. i;
  3838. _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  3839. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  3840. this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
  3841. if (settings.descriptor) {
  3842. for (i = 0; i < settings.descriptor.length; i++) {
  3843. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  3844. }
  3845. }
  3846. this.push = function (chunk) {
  3847. var tag, frameStart, frameSize, frame, i, frameHeader;
  3848. if (chunk.type !== 'timed-metadata') {
  3849. return;
  3850. } // if data_alignment_indicator is set in the PES header,
  3851. // we must have the start of a new ID3 tag. Assume anything
  3852. // remaining in the buffer was malformed and throw it out
  3853. if (chunk.dataAlignmentIndicator) {
  3854. bufferSize = 0;
  3855. buffer.length = 0;
  3856. } // ignore events that don't look like ID3 data
  3857. if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
  3858. this.trigger('log', {
  3859. level: 'warn',
  3860. message: 'Skipping unrecognized metadata packet'
  3861. });
  3862. return;
  3863. } // add this chunk to the data we've collected so far
  3864. buffer.push(chunk);
  3865. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  3866. if (buffer.length === 1) {
  3867. // the frame size is transmitted as a 28-bit integer in the
  3868. // last four bytes of the ID3 header.
  3869. // The most significant bit of each byte is dropped and the
  3870. // results concatenated to recover the actual value.
  3871. tagSize = parseId3.parseSyncSafeInteger(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  3872. // convenient for our comparisons to include it
  3873. tagSize += 10;
  3874. } // if the entire frame has not arrived, wait for more data
  3875. if (bufferSize < tagSize) {
  3876. return;
  3877. } // collect the entire frame so it can be parsed
  3878. tag = {
  3879. data: new Uint8Array(tagSize),
  3880. frames: [],
  3881. pts: buffer[0].pts,
  3882. dts: buffer[0].dts
  3883. };
  3884. for (i = 0; i < tagSize;) {
  3885. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  3886. i += buffer[0].data.byteLength;
  3887. bufferSize -= buffer[0].data.byteLength;
  3888. buffer.shift();
  3889. } // find the start of the first frame and the end of the tag
  3890. frameStart = 10;
  3891. if (tag.data[5] & 0x40) {
  3892. // advance the frame start past the extended header
  3893. frameStart += 4; // header size field
  3894. frameStart += parseId3.parseSyncSafeInteger(tag.data.subarray(10, 14)); // clip any padding off the end
  3895. tagSize -= parseId3.parseSyncSafeInteger(tag.data.subarray(16, 20));
  3896. } // parse one or more ID3 frames
  3897. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  3898. do {
  3899. // determine the number of bytes in this frame
  3900. frameSize = parseId3.parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  3901. if (frameSize < 1) {
  3902. this.trigger('log', {
  3903. level: 'warn',
  3904. message: 'Malformed ID3 frame encountered. Skipping remaining metadata parsing.'
  3905. }); // If the frame is malformed, don't parse any further frames but allow previous valid parsed frames
  3906. // to be sent along.
  3907. break;
  3908. }
  3909. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  3910. frame = {
  3911. id: frameHeader,
  3912. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  3913. };
  3914. frame.key = frame.id; // parse frame values
  3915. if (parseId3.frameParsers[frame.id]) {
  3916. // use frame specific parser
  3917. parseId3.frameParsers[frame.id](frame);
  3918. } else if (frame.id[0] === 'T') {
  3919. // use text frame generic parser
  3920. parseId3.frameParsers['T*'](frame);
  3921. } else if (frame.id[0] === 'W') {
  3922. // use URL link frame generic parser
  3923. parseId3.frameParsers['W*'](frame);
  3924. } // handle the special PRIV frame used to indicate the start
  3925. // time for raw AAC data
  3926. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  3927. var d = frame.data,
  3928. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  3929. size *= 4;
  3930. size += d[7] & 0x03;
  3931. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  3932. // on the value of this frame
  3933. // we couldn't have known the appropriate pts and dts before
  3934. // parsing this ID3 tag so set those values now
  3935. if (tag.pts === undefined && tag.dts === undefined) {
  3936. tag.pts = frame.timeStamp;
  3937. tag.dts = frame.timeStamp;
  3938. }
  3939. this.trigger('timestamp', frame);
  3940. }
  3941. tag.frames.push(frame);
  3942. frameStart += 10; // advance past the frame header
  3943. frameStart += frameSize; // advance past the frame body
  3944. } while (frameStart < tagSize);
  3945. this.trigger('data', tag);
  3946. };
  3947. };
  3948. _MetadataStream.prototype = new stream();
  3949. var metadataStream = _MetadataStream;
  3950. var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  3951. var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
  3952. var MP2T_PACKET_LENGTH = 188,
  3953. // bytes
  3954. SYNC_BYTE = 0x47;
  3955. /**
  3956. * Splits an incoming stream of binary data into MPEG-2 Transport
  3957. * Stream packets.
  3958. */
  3959. _TransportPacketStream = function TransportPacketStream() {
  3960. var buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  3961. bytesInBuffer = 0;
  3962. _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  3963. /**
  3964. * Split a stream of data into M2TS packets
  3965. **/
  3966. this.push = function (bytes) {
  3967. var startIndex = 0,
  3968. endIndex = MP2T_PACKET_LENGTH,
  3969. everything; // If there are bytes remaining from the last segment, prepend them to the
  3970. // bytes that were pushed in
  3971. if (bytesInBuffer) {
  3972. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  3973. everything.set(buffer.subarray(0, bytesInBuffer));
  3974. everything.set(bytes, bytesInBuffer);
  3975. bytesInBuffer = 0;
  3976. } else {
  3977. everything = bytes;
  3978. } // While we have enough data for a packet
  3979. while (endIndex < everything.byteLength) {
  3980. // Look for a pair of start and end sync bytes in the data..
  3981. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  3982. // We found a packet so emit it and jump one whole packet forward in
  3983. // the stream
  3984. this.trigger('data', everything.subarray(startIndex, endIndex));
  3985. startIndex += MP2T_PACKET_LENGTH;
  3986. endIndex += MP2T_PACKET_LENGTH;
  3987. continue;
  3988. } // If we get here, we have somehow become de-synchronized and we need to step
  3989. // forward one byte at a time until we find a pair of sync bytes that denote
  3990. // a packet
  3991. startIndex++;
  3992. endIndex++;
  3993. } // If there was some data left over at the end of the segment that couldn't
  3994. // possibly be a whole packet, keep it because it might be the start of a packet
  3995. // that continues in the next segment
  3996. if (startIndex < everything.byteLength) {
  3997. buffer.set(everything.subarray(startIndex), 0);
  3998. bytesInBuffer = everything.byteLength - startIndex;
  3999. }
  4000. };
  4001. /**
  4002. * Passes identified M2TS packets to the TransportParseStream to be parsed
  4003. **/
  4004. this.flush = function () {
  4005. // If the buffer contains a whole packet when we are being flushed, emit it
  4006. // and empty the buffer. Otherwise hold onto the data because it may be
  4007. // important for decoding the next segment
  4008. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  4009. this.trigger('data', buffer);
  4010. bytesInBuffer = 0;
  4011. }
  4012. this.trigger('done');
  4013. };
  4014. this.endTimeline = function () {
  4015. this.flush();
  4016. this.trigger('endedtimeline');
  4017. };
  4018. this.reset = function () {
  4019. bytesInBuffer = 0;
  4020. this.trigger('reset');
  4021. };
  4022. };
  4023. _TransportPacketStream.prototype = new stream();
  4024. /**
  4025. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  4026. * forms of the individual transport stream packets.
  4027. */
  4028. _TransportParseStream = function TransportParseStream() {
  4029. var parsePsi, parsePat, parsePmt, self;
  4030. _TransportParseStream.prototype.init.call(this);
  4031. self = this;
  4032. this.packetsWaitingForPmt = [];
  4033. this.programMapTable = undefined;
  4034. parsePsi = function parsePsi(payload, psi) {
  4035. var offset = 0; // PSI packets may be split into multiple sections and those
  4036. // sections may be split into multiple packets. If a PSI
  4037. // section starts in this packet, the payload_unit_start_indicator
  4038. // will be true and the first byte of the payload will indicate
  4039. // the offset from the current position to the start of the
  4040. // section.
  4041. if (psi.payloadUnitStartIndicator) {
  4042. offset += payload[offset] + 1;
  4043. }
  4044. if (psi.type === 'pat') {
  4045. parsePat(payload.subarray(offset), psi);
  4046. } else {
  4047. parsePmt(payload.subarray(offset), psi);
  4048. }
  4049. };
  4050. parsePat = function parsePat(payload, pat) {
  4051. pat.section_number = payload[7]; // eslint-disable-line camelcase
  4052. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  4053. // skip the PSI header and parse the first PMT entry
  4054. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  4055. pat.pmtPid = self.pmtPid;
  4056. };
  4057. /**
  4058. * Parse out the relevant fields of a Program Map Table (PMT).
  4059. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  4060. * packet. The first byte in this array should be the table_id
  4061. * field.
  4062. * @param pmt {object} the object that should be decorated with
  4063. * fields parsed from the PMT.
  4064. */
  4065. parsePmt = function parsePmt(payload, pmt) {
  4066. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  4067. // take effect. We don't believe this should ever be the case
  4068. // for HLS but we'll ignore "forward" PMT declarations if we see
  4069. // them. Future PMT declarations have the current_next_indicator
  4070. // set to zero.
  4071. if (!(payload[5] & 0x01)) {
  4072. return;
  4073. } // overwrite any existing program map table
  4074. self.programMapTable = {
  4075. video: null,
  4076. audio: null,
  4077. 'timed-metadata': {}
  4078. }; // the mapping table ends at the end of the current section
  4079. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  4080. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  4081. // long the program info descriptors are
  4082. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  4083. offset = 12 + programInfoLength;
  4084. while (offset < tableEnd) {
  4085. var streamType = payload[offset];
  4086. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  4087. // TODO: should this be done for metadata too? for now maintain behavior of
  4088. // multiple metadata streams
  4089. if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
  4090. self.programMapTable.video = pid;
  4091. } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  4092. self.programMapTable.audio = pid;
  4093. } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
  4094. // map pid to stream type for metadata streams
  4095. self.programMapTable['timed-metadata'][pid] = streamType;
  4096. } // move to the next table entry
  4097. // skip past the elementary stream descriptors, if present
  4098. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  4099. } // record the map on the packet as well
  4100. pmt.programMapTable = self.programMapTable;
  4101. };
  4102. /**
  4103. * Deliver a new MP2T packet to the next stream in the pipeline.
  4104. */
  4105. this.push = function (packet) {
  4106. var result = {},
  4107. offset = 4;
  4108. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  4109. result.pid = packet[1] & 0x1f;
  4110. result.pid <<= 8;
  4111. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  4112. // fifth byte of the TS packet header. The adaptation field is
  4113. // used to add stuffing to PES packets that don't fill a complete
  4114. // TS packet, and to specify some forms of timing and control data
  4115. // that we do not currently use.
  4116. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  4117. offset += packet[offset] + 1;
  4118. } // parse the rest of the packet based on the type
  4119. if (result.pid === 0) {
  4120. result.type = 'pat';
  4121. parsePsi(packet.subarray(offset), result);
  4122. this.trigger('data', result);
  4123. } else if (result.pid === this.pmtPid) {
  4124. result.type = 'pmt';
  4125. parsePsi(packet.subarray(offset), result);
  4126. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  4127. while (this.packetsWaitingForPmt.length) {
  4128. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  4129. }
  4130. } else if (this.programMapTable === undefined) {
  4131. // When we have not seen a PMT yet, defer further processing of
  4132. // PES packets until one has been parsed
  4133. this.packetsWaitingForPmt.push([packet, offset, result]);
  4134. } else {
  4135. this.processPes_(packet, offset, result);
  4136. }
  4137. };
  4138. this.processPes_ = function (packet, offset, result) {
  4139. // set the appropriate stream type
  4140. if (result.pid === this.programMapTable.video) {
  4141. result.streamType = streamTypes.H264_STREAM_TYPE;
  4142. } else if (result.pid === this.programMapTable.audio) {
  4143. result.streamType = streamTypes.ADTS_STREAM_TYPE;
  4144. } else {
  4145. // if not video or audio, it is timed-metadata or unknown
  4146. // if unknown, streamType will be undefined
  4147. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  4148. }
  4149. result.type = 'pes';
  4150. result.data = packet.subarray(offset);
  4151. this.trigger('data', result);
  4152. };
  4153. };
  4154. _TransportParseStream.prototype = new stream();
  4155. _TransportParseStream.STREAM_TYPES = {
  4156. h264: 0x1b,
  4157. adts: 0x0f
  4158. };
  4159. /**
  4160. * Reconsistutes program elementary stream (PES) packets from parsed
  4161. * transport stream packets. That is, if you pipe an
  4162. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  4163. * events will be events which capture the bytes for individual PES
  4164. * packets plus relevant metadata that has been extracted from the
  4165. * container.
  4166. */
  4167. _ElementaryStream = function ElementaryStream() {
  4168. var self = this,
  4169. segmentHadPmt = false,
  4170. // PES packet fragments
  4171. video = {
  4172. data: [],
  4173. size: 0
  4174. },
  4175. audio = {
  4176. data: [],
  4177. size: 0
  4178. },
  4179. timedMetadata = {
  4180. data: [],
  4181. size: 0
  4182. },
  4183. programMapTable,
  4184. parsePes = function parsePes(payload, pes) {
  4185. var ptsDtsFlags;
  4186. var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  4187. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  4188. // that are frame data that is continuing from the previous fragment. This
  4189. // is to check that the pes data is the start of a new pes payload
  4190. if (startPrefix !== 1) {
  4191. return;
  4192. } // get the packet length, this will be 0 for video
  4193. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  4194. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  4195. // and a DTS value. Determine what combination of values is
  4196. // available to work with.
  4197. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  4198. // performs all bitwise operations on 32-bit integers but javascript
  4199. // supports a much greater range (52-bits) of integer using standard
  4200. // mathematical operations.
  4201. // We construct a 31-bit value using bitwise operators over the 31
  4202. // most significant bits and then multiply by 4 (equal to a left-shift
  4203. // of 2) before we add the final 2 least significant bits of the
  4204. // timestamp (equal to an OR.)
  4205. if (ptsDtsFlags & 0xC0) {
  4206. // the PTS and DTS are not written out directly. For information
  4207. // on how they are encoded, see
  4208. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  4209. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  4210. pes.pts *= 4; // Left shift by 2
  4211. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  4212. pes.dts = pes.pts;
  4213. if (ptsDtsFlags & 0x40) {
  4214. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  4215. pes.dts *= 4; // Left shift by 2
  4216. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  4217. }
  4218. } // the data section starts immediately after the PES header.
  4219. // pes_header_data_length specifies the number of header bytes
  4220. // that follow the last byte of the field.
  4221. pes.data = payload.subarray(9 + payload[8]);
  4222. },
  4223. /**
  4224. * Pass completely parsed PES packets to the next stream in the pipeline
  4225. **/
  4226. flushStream = function flushStream(stream, type, forceFlush) {
  4227. var packetData = new Uint8Array(stream.size),
  4228. event = {
  4229. type: type
  4230. },
  4231. i = 0,
  4232. offset = 0,
  4233. packetFlushable = false,
  4234. fragment; // do nothing if there is not enough buffered data for a complete
  4235. // PES header
  4236. if (!stream.data.length || stream.size < 9) {
  4237. return;
  4238. }
  4239. event.trackId = stream.data[0].pid; // reassemble the packet
  4240. for (i = 0; i < stream.data.length; i++) {
  4241. fragment = stream.data[i];
  4242. packetData.set(fragment.data, offset);
  4243. offset += fragment.data.byteLength;
  4244. } // parse assembled packet's PES header
  4245. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  4246. // check that there is enough stream data to fill the packet
  4247. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  4248. if (forceFlush || packetFlushable) {
  4249. stream.size = 0;
  4250. stream.data.length = 0;
  4251. } // only emit packets that are complete. this is to avoid assembling
  4252. // incomplete PES packets due to poor segmentation
  4253. if (packetFlushable) {
  4254. self.trigger('data', event);
  4255. }
  4256. };
  4257. _ElementaryStream.prototype.init.call(this);
  4258. /**
  4259. * Identifies M2TS packet types and parses PES packets using metadata
  4260. * parsed from the PMT
  4261. **/
  4262. this.push = function (data) {
  4263. ({
  4264. pat: function pat() {// we have to wait for the PMT to arrive as well before we
  4265. // have any meaningful metadata
  4266. },
  4267. pes: function pes() {
  4268. var stream, streamType;
  4269. switch (data.streamType) {
  4270. case streamTypes.H264_STREAM_TYPE:
  4271. stream = video;
  4272. streamType = 'video';
  4273. break;
  4274. case streamTypes.ADTS_STREAM_TYPE:
  4275. stream = audio;
  4276. streamType = 'audio';
  4277. break;
  4278. case streamTypes.METADATA_STREAM_TYPE:
  4279. stream = timedMetadata;
  4280. streamType = 'timed-metadata';
  4281. break;
  4282. default:
  4283. // ignore unknown stream types
  4284. return;
  4285. } // if a new packet is starting, we can flush the completed
  4286. // packet
  4287. if (data.payloadUnitStartIndicator) {
  4288. flushStream(stream, streamType, true);
  4289. } // buffer this fragment until we are sure we've received the
  4290. // complete payload
  4291. stream.data.push(data);
  4292. stream.size += data.data.byteLength;
  4293. },
  4294. pmt: function pmt() {
  4295. var event = {
  4296. type: 'metadata',
  4297. tracks: []
  4298. };
  4299. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  4300. if (programMapTable.video !== null) {
  4301. event.tracks.push({
  4302. timelineStartInfo: {
  4303. baseMediaDecodeTime: 0
  4304. },
  4305. id: +programMapTable.video,
  4306. codec: 'avc',
  4307. type: 'video'
  4308. });
  4309. }
  4310. if (programMapTable.audio !== null) {
  4311. event.tracks.push({
  4312. timelineStartInfo: {
  4313. baseMediaDecodeTime: 0
  4314. },
  4315. id: +programMapTable.audio,
  4316. codec: 'adts',
  4317. type: 'audio'
  4318. });
  4319. }
  4320. segmentHadPmt = true;
  4321. self.trigger('data', event);
  4322. }
  4323. })[data.type]();
  4324. };
  4325. this.reset = function () {
  4326. video.size = 0;
  4327. video.data.length = 0;
  4328. audio.size = 0;
  4329. audio.data.length = 0;
  4330. this.trigger('reset');
  4331. };
  4332. /**
  4333. * Flush any remaining input. Video PES packets may be of variable
  4334. * length. Normally, the start of a new video packet can trigger the
  4335. * finalization of the previous packet. That is not possible if no
  4336. * more video is forthcoming, however. In that case, some other
  4337. * mechanism (like the end of the file) has to be employed. When it is
  4338. * clear that no additional data is forthcoming, calling this method
  4339. * will flush the buffered packets.
  4340. */
  4341. this.flushStreams_ = function () {
  4342. // !!THIS ORDER IS IMPORTANT!!
  4343. // video first then audio
  4344. flushStream(video, 'video');
  4345. flushStream(audio, 'audio');
  4346. flushStream(timedMetadata, 'timed-metadata');
  4347. };
  4348. this.flush = function () {
  4349. // if on flush we haven't had a pmt emitted
  4350. // and we have a pmt to emit. emit the pmt
  4351. // so that we trigger a trackinfo downstream.
  4352. if (!segmentHadPmt && programMapTable) {
  4353. var pmt = {
  4354. type: 'metadata',
  4355. tracks: []
  4356. }; // translate audio and video streams to tracks
  4357. if (programMapTable.video !== null) {
  4358. pmt.tracks.push({
  4359. timelineStartInfo: {
  4360. baseMediaDecodeTime: 0
  4361. },
  4362. id: +programMapTable.video,
  4363. codec: 'avc',
  4364. type: 'video'
  4365. });
  4366. }
  4367. if (programMapTable.audio !== null) {
  4368. pmt.tracks.push({
  4369. timelineStartInfo: {
  4370. baseMediaDecodeTime: 0
  4371. },
  4372. id: +programMapTable.audio,
  4373. codec: 'adts',
  4374. type: 'audio'
  4375. });
  4376. }
  4377. self.trigger('data', pmt);
  4378. }
  4379. segmentHadPmt = false;
  4380. this.flushStreams_();
  4381. this.trigger('done');
  4382. };
  4383. };
  4384. _ElementaryStream.prototype = new stream();
  4385. var m2ts = {
  4386. PAT_PID: 0x0000,
  4387. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  4388. TransportPacketStream: _TransportPacketStream,
  4389. TransportParseStream: _TransportParseStream,
  4390. ElementaryStream: _ElementaryStream,
  4391. TimestampRolloverStream: TimestampRolloverStream,
  4392. CaptionStream: captionStream.CaptionStream,
  4393. Cea608Stream: captionStream.Cea608Stream,
  4394. Cea708Stream: captionStream.Cea708Stream,
  4395. MetadataStream: metadataStream
  4396. };
  4397. for (var type in streamTypes) {
  4398. if (streamTypes.hasOwnProperty(type)) {
  4399. m2ts[type] = streamTypes[type];
  4400. }
  4401. }
  4402. var m2ts_1 = m2ts;
  4403. var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS;
  4404. var _AdtsStream;
  4405. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  4406. /*
  4407. * Accepts a ElementaryStream and emits data events with parsed
  4408. * AAC Audio Frames of the individual packets. Input audio in ADTS
  4409. * format is unpacked and re-emitted as AAC frames.
  4410. *
  4411. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  4412. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  4413. */
  4414. _AdtsStream = function AdtsStream(handlePartialSegments) {
  4415. var buffer,
  4416. frameNum = 0;
  4417. _AdtsStream.prototype.init.call(this);
  4418. this.skipWarn_ = function (start, end) {
  4419. this.trigger('log', {
  4420. level: 'warn',
  4421. message: "adts skiping bytes " + start + " to " + end + " in frame " + frameNum + " outside syncword"
  4422. });
  4423. };
  4424. this.push = function (packet) {
  4425. var i = 0,
  4426. frameLength,
  4427. protectionSkipBytes,
  4428. oldBuffer,
  4429. sampleCount,
  4430. adtsFrameDuration;
  4431. if (!handlePartialSegments) {
  4432. frameNum = 0;
  4433. }
  4434. if (packet.type !== 'audio') {
  4435. // ignore non-audio data
  4436. return;
  4437. } // Prepend any data in the buffer to the input data so that we can parse
  4438. // aac frames the cross a PES packet boundary
  4439. if (buffer && buffer.length) {
  4440. oldBuffer = buffer;
  4441. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  4442. buffer.set(oldBuffer);
  4443. buffer.set(packet.data, oldBuffer.byteLength);
  4444. } else {
  4445. buffer = packet.data;
  4446. } // unpack any ADTS frames which have been fully received
  4447. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  4448. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  4449. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  4450. while (i + 7 < buffer.length) {
  4451. // Look for the start of an ADTS header..
  4452. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  4453. if (typeof skip !== 'number') {
  4454. skip = i;
  4455. } // If a valid header was not found, jump one forward and attempt to
  4456. // find a valid ADTS header starting at the next byte
  4457. i++;
  4458. continue;
  4459. }
  4460. if (typeof skip === 'number') {
  4461. this.skipWarn_(skip, i);
  4462. skip = null;
  4463. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  4464. // end of the ADTS header
  4465. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  4466. // end of the sync sequence
  4467. // NOTE: frame length includes the size of the header
  4468. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  4469. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  4470. adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$1 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2]; // If we don't have enough data to actually finish this ADTS frame,
  4471. // then we have to wait for more data
  4472. if (buffer.byteLength - i < frameLength) {
  4473. break;
  4474. } // Otherwise, deliver the complete AAC frame
  4475. this.trigger('data', {
  4476. pts: packet.pts + frameNum * adtsFrameDuration,
  4477. dts: packet.dts + frameNum * adtsFrameDuration,
  4478. sampleCount: sampleCount,
  4479. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  4480. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  4481. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  4482. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  4483. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  4484. samplesize: 16,
  4485. // data is the frame without it's header
  4486. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  4487. });
  4488. frameNum++;
  4489. i += frameLength;
  4490. }
  4491. if (typeof skip === 'number') {
  4492. this.skipWarn_(skip, i);
  4493. skip = null;
  4494. } // remove processed bytes from the buffer.
  4495. buffer = buffer.subarray(i);
  4496. };
  4497. this.flush = function () {
  4498. frameNum = 0;
  4499. this.trigger('done');
  4500. };
  4501. this.reset = function () {
  4502. buffer = void 0;
  4503. this.trigger('reset');
  4504. };
  4505. this.endTimeline = function () {
  4506. buffer = void 0;
  4507. this.trigger('endedtimeline');
  4508. };
  4509. };
  4510. _AdtsStream.prototype = new stream();
  4511. var adts = _AdtsStream;
  4512. /**
  4513. * mux.js
  4514. *
  4515. * Copyright (c) Brightcove
  4516. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4517. */
  4518. var ExpGolomb;
  4519. /**
  4520. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  4521. * scheme used by h264.
  4522. */
  4523. ExpGolomb = function ExpGolomb(workingData) {
  4524. var // the number of bytes left to examine in workingData
  4525. workingBytesAvailable = workingData.byteLength,
  4526. // the current word being examined
  4527. workingWord = 0,
  4528. // :uint
  4529. // the number of bits left to examine in the current word
  4530. workingBitsAvailable = 0; // :uint;
  4531. // ():uint
  4532. this.length = function () {
  4533. return 8 * workingBytesAvailable;
  4534. }; // ():uint
  4535. this.bitsAvailable = function () {
  4536. return 8 * workingBytesAvailable + workingBitsAvailable;
  4537. }; // ():void
  4538. this.loadWord = function () {
  4539. var position = workingData.byteLength - workingBytesAvailable,
  4540. workingBytes = new Uint8Array(4),
  4541. availableBytes = Math.min(4, workingBytesAvailable);
  4542. if (availableBytes === 0) {
  4543. throw new Error('no bytes available');
  4544. }
  4545. workingBytes.set(workingData.subarray(position, position + availableBytes));
  4546. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  4547. workingBitsAvailable = availableBytes * 8;
  4548. workingBytesAvailable -= availableBytes;
  4549. }; // (count:int):void
  4550. this.skipBits = function (count) {
  4551. var skipBytes; // :int
  4552. if (workingBitsAvailable > count) {
  4553. workingWord <<= count;
  4554. workingBitsAvailable -= count;
  4555. } else {
  4556. count -= workingBitsAvailable;
  4557. skipBytes = Math.floor(count / 8);
  4558. count -= skipBytes * 8;
  4559. workingBytesAvailable -= skipBytes;
  4560. this.loadWord();
  4561. workingWord <<= count;
  4562. workingBitsAvailable -= count;
  4563. }
  4564. }; // (size:int):uint
  4565. this.readBits = function (size) {
  4566. var bits = Math.min(workingBitsAvailable, size),
  4567. // :uint
  4568. valu = workingWord >>> 32 - bits; // :uint
  4569. // if size > 31, handle error
  4570. workingBitsAvailable -= bits;
  4571. if (workingBitsAvailable > 0) {
  4572. workingWord <<= bits;
  4573. } else if (workingBytesAvailable > 0) {
  4574. this.loadWord();
  4575. }
  4576. bits = size - bits;
  4577. if (bits > 0) {
  4578. return valu << bits | this.readBits(bits);
  4579. }
  4580. return valu;
  4581. }; // ():uint
  4582. this.skipLeadingZeros = function () {
  4583. var leadingZeroCount; // :uint
  4584. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  4585. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  4586. // the first bit of working word is 1
  4587. workingWord <<= leadingZeroCount;
  4588. workingBitsAvailable -= leadingZeroCount;
  4589. return leadingZeroCount;
  4590. }
  4591. } // we exhausted workingWord and still have not found a 1
  4592. this.loadWord();
  4593. return leadingZeroCount + this.skipLeadingZeros();
  4594. }; // ():void
  4595. this.skipUnsignedExpGolomb = function () {
  4596. this.skipBits(1 + this.skipLeadingZeros());
  4597. }; // ():void
  4598. this.skipExpGolomb = function () {
  4599. this.skipBits(1 + this.skipLeadingZeros());
  4600. }; // ():uint
  4601. this.readUnsignedExpGolomb = function () {
  4602. var clz = this.skipLeadingZeros(); // :uint
  4603. return this.readBits(clz + 1) - 1;
  4604. }; // ():int
  4605. this.readExpGolomb = function () {
  4606. var valu = this.readUnsignedExpGolomb(); // :int
  4607. if (0x01 & valu) {
  4608. // the number is odd if the low order bit is set
  4609. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  4610. }
  4611. return -1 * (valu >>> 1); // divide by two then make it negative
  4612. }; // Some convenience functions
  4613. // :Boolean
  4614. this.readBoolean = function () {
  4615. return this.readBits(1) === 1;
  4616. }; // ():int
  4617. this.readUnsignedByte = function () {
  4618. return this.readBits(8);
  4619. };
  4620. this.loadWord();
  4621. };
  4622. var expGolomb = ExpGolomb;
  4623. var _H264Stream, _NalByteStream;
  4624. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  4625. /**
  4626. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  4627. */
  4628. _NalByteStream = function NalByteStream() {
  4629. var syncPoint = 0,
  4630. i,
  4631. buffer;
  4632. _NalByteStream.prototype.init.call(this);
  4633. /*
  4634. * Scans a byte stream and triggers a data event with the NAL units found.
  4635. * @param {Object} data Event received from H264Stream
  4636. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  4637. *
  4638. * @see H264Stream.push
  4639. */
  4640. this.push = function (data) {
  4641. var swapBuffer;
  4642. if (!buffer) {
  4643. buffer = data.data;
  4644. } else {
  4645. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  4646. swapBuffer.set(buffer);
  4647. swapBuffer.set(data.data, buffer.byteLength);
  4648. buffer = swapBuffer;
  4649. }
  4650. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  4651. // scan for NAL unit boundaries
  4652. // a match looks like this:
  4653. // 0 0 1 .. NAL .. 0 0 1
  4654. // ^ sync point ^ i
  4655. // or this:
  4656. // 0 0 1 .. NAL .. 0 0 0
  4657. // ^ sync point ^ i
  4658. // advance the sync point to a NAL start, if necessary
  4659. for (; syncPoint < len - 3; syncPoint++) {
  4660. if (buffer[syncPoint + 2] === 1) {
  4661. // the sync point is properly aligned
  4662. i = syncPoint + 5;
  4663. break;
  4664. }
  4665. }
  4666. while (i < len) {
  4667. // look at the current byte to determine if we've hit the end of
  4668. // a NAL unit boundary
  4669. switch (buffer[i]) {
  4670. case 0:
  4671. // skip past non-sync sequences
  4672. if (buffer[i - 1] !== 0) {
  4673. i += 2;
  4674. break;
  4675. } else if (buffer[i - 2] !== 0) {
  4676. i++;
  4677. break;
  4678. } // deliver the NAL unit if it isn't empty
  4679. if (syncPoint + 3 !== i - 2) {
  4680. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  4681. } // drop trailing zeroes
  4682. do {
  4683. i++;
  4684. } while (buffer[i] !== 1 && i < len);
  4685. syncPoint = i - 2;
  4686. i += 3;
  4687. break;
  4688. case 1:
  4689. // skip past non-sync sequences
  4690. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  4691. i += 3;
  4692. break;
  4693. } // deliver the NAL unit
  4694. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  4695. syncPoint = i - 2;
  4696. i += 3;
  4697. break;
  4698. default:
  4699. // the current byte isn't a one or zero, so it cannot be part
  4700. // of a sync sequence
  4701. i += 3;
  4702. break;
  4703. }
  4704. } // filter out the NAL units that were delivered
  4705. buffer = buffer.subarray(syncPoint);
  4706. i -= syncPoint;
  4707. syncPoint = 0;
  4708. };
  4709. this.reset = function () {
  4710. buffer = null;
  4711. syncPoint = 0;
  4712. this.trigger('reset');
  4713. };
  4714. this.flush = function () {
  4715. // deliver the last buffered NAL unit
  4716. if (buffer && buffer.byteLength > 3) {
  4717. this.trigger('data', buffer.subarray(syncPoint + 3));
  4718. } // reset the stream state
  4719. buffer = null;
  4720. syncPoint = 0;
  4721. this.trigger('done');
  4722. };
  4723. this.endTimeline = function () {
  4724. this.flush();
  4725. this.trigger('endedtimeline');
  4726. };
  4727. };
  4728. _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
  4729. // see Recommendation ITU-T H.264 (4/2013),
  4730. // 7.3.2.1.1 Sequence parameter set data syntax
  4731. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  4732. 100: true,
  4733. 110: true,
  4734. 122: true,
  4735. 244: true,
  4736. 44: true,
  4737. 83: true,
  4738. 86: true,
  4739. 118: true,
  4740. 128: true,
  4741. // TODO: the three profiles below don't
  4742. // appear to have sps data in the specificiation anymore?
  4743. 138: true,
  4744. 139: true,
  4745. 134: true
  4746. };
  4747. /**
  4748. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  4749. * events.
  4750. */
  4751. _H264Stream = function H264Stream() {
  4752. var nalByteStream = new _NalByteStream(),
  4753. self,
  4754. trackId,
  4755. currentPts,
  4756. currentDts,
  4757. discardEmulationPreventionBytes,
  4758. readSequenceParameterSet,
  4759. skipScalingList;
  4760. _H264Stream.prototype.init.call(this);
  4761. self = this;
  4762. /*
  4763. * Pushes a packet from a stream onto the NalByteStream
  4764. *
  4765. * @param {Object} packet - A packet received from a stream
  4766. * @param {Uint8Array} packet.data - The raw bytes of the packet
  4767. * @param {Number} packet.dts - Decode timestamp of the packet
  4768. * @param {Number} packet.pts - Presentation timestamp of the packet
  4769. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  4770. * @param {('video'|'audio')} packet.type - The type of packet
  4771. *
  4772. */
  4773. this.push = function (packet) {
  4774. if (packet.type !== 'video') {
  4775. return;
  4776. }
  4777. trackId = packet.trackId;
  4778. currentPts = packet.pts;
  4779. currentDts = packet.dts;
  4780. nalByteStream.push(packet);
  4781. };
  4782. /*
  4783. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  4784. * for the NALUs to the next stream component.
  4785. * Also, preprocess caption and sequence parameter NALUs.
  4786. *
  4787. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  4788. * @see NalByteStream.push
  4789. */
  4790. nalByteStream.on('data', function (data) {
  4791. var event = {
  4792. trackId: trackId,
  4793. pts: currentPts,
  4794. dts: currentDts,
  4795. data: data,
  4796. nalUnitTypeCode: data[0] & 0x1f
  4797. };
  4798. switch (event.nalUnitTypeCode) {
  4799. case 0x05:
  4800. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  4801. break;
  4802. case 0x06:
  4803. event.nalUnitType = 'sei_rbsp';
  4804. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  4805. break;
  4806. case 0x07:
  4807. event.nalUnitType = 'seq_parameter_set_rbsp';
  4808. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  4809. event.config = readSequenceParameterSet(event.escapedRBSP);
  4810. break;
  4811. case 0x08:
  4812. event.nalUnitType = 'pic_parameter_set_rbsp';
  4813. break;
  4814. case 0x09:
  4815. event.nalUnitType = 'access_unit_delimiter_rbsp';
  4816. break;
  4817. } // This triggers data on the H264Stream
  4818. self.trigger('data', event);
  4819. });
  4820. nalByteStream.on('done', function () {
  4821. self.trigger('done');
  4822. });
  4823. nalByteStream.on('partialdone', function () {
  4824. self.trigger('partialdone');
  4825. });
  4826. nalByteStream.on('reset', function () {
  4827. self.trigger('reset');
  4828. });
  4829. nalByteStream.on('endedtimeline', function () {
  4830. self.trigger('endedtimeline');
  4831. });
  4832. this.flush = function () {
  4833. nalByteStream.flush();
  4834. };
  4835. this.partialFlush = function () {
  4836. nalByteStream.partialFlush();
  4837. };
  4838. this.reset = function () {
  4839. nalByteStream.reset();
  4840. };
  4841. this.endTimeline = function () {
  4842. nalByteStream.endTimeline();
  4843. };
  4844. /**
  4845. * Advance the ExpGolomb decoder past a scaling list. The scaling
  4846. * list is optionally transmitted as part of a sequence parameter
  4847. * set and is not relevant to transmuxing.
  4848. * @param count {number} the number of entries in this scaling list
  4849. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  4850. * start of a scaling list
  4851. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  4852. */
  4853. skipScalingList = function skipScalingList(count, expGolombDecoder) {
  4854. var lastScale = 8,
  4855. nextScale = 8,
  4856. j,
  4857. deltaScale;
  4858. for (j = 0; j < count; j++) {
  4859. if (nextScale !== 0) {
  4860. deltaScale = expGolombDecoder.readExpGolomb();
  4861. nextScale = (lastScale + deltaScale + 256) % 256;
  4862. }
  4863. lastScale = nextScale === 0 ? lastScale : nextScale;
  4864. }
  4865. };
  4866. /**
  4867. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  4868. * Sequence Payload"
  4869. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  4870. * unit
  4871. * @return {Uint8Array} the RBSP without any Emulation
  4872. * Prevention Bytes
  4873. */
  4874. discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
  4875. var length = data.byteLength,
  4876. emulationPreventionBytesPositions = [],
  4877. i = 1,
  4878. newLength,
  4879. newData; // Find all `Emulation Prevention Bytes`
  4880. while (i < length - 2) {
  4881. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  4882. emulationPreventionBytesPositions.push(i + 2);
  4883. i += 2;
  4884. } else {
  4885. i++;
  4886. }
  4887. } // If no Emulation Prevention Bytes were found just return the original
  4888. // array
  4889. if (emulationPreventionBytesPositions.length === 0) {
  4890. return data;
  4891. } // Create a new array to hold the NAL unit data
  4892. newLength = length - emulationPreventionBytesPositions.length;
  4893. newData = new Uint8Array(newLength);
  4894. var sourceIndex = 0;
  4895. for (i = 0; i < newLength; sourceIndex++, i++) {
  4896. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  4897. // Skip this byte
  4898. sourceIndex++; // Remove this position index
  4899. emulationPreventionBytesPositions.shift();
  4900. }
  4901. newData[i] = data[sourceIndex];
  4902. }
  4903. return newData;
  4904. };
  4905. /**
  4906. * Read a sequence parameter set and return some interesting video
  4907. * properties. A sequence parameter set is the H264 metadata that
  4908. * describes the properties of upcoming video frames.
  4909. * @param data {Uint8Array} the bytes of a sequence parameter set
  4910. * @return {object} an object with configuration parsed from the
  4911. * sequence parameter set, including the dimensions of the
  4912. * associated video frames.
  4913. */
  4914. readSequenceParameterSet = function readSequenceParameterSet(data) {
  4915. var frameCropLeftOffset = 0,
  4916. frameCropRightOffset = 0,
  4917. frameCropTopOffset = 0,
  4918. frameCropBottomOffset = 0,
  4919. expGolombDecoder,
  4920. profileIdc,
  4921. levelIdc,
  4922. profileCompatibility,
  4923. chromaFormatIdc,
  4924. picOrderCntType,
  4925. numRefFramesInPicOrderCntCycle,
  4926. picWidthInMbsMinus1,
  4927. picHeightInMapUnitsMinus1,
  4928. frameMbsOnlyFlag,
  4929. scalingListCount,
  4930. sarRatio = [1, 1],
  4931. aspectRatioIdc,
  4932. i;
  4933. expGolombDecoder = new expGolomb(data);
  4934. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  4935. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  4936. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  4937. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  4938. // some profiles have more optional data we don't need
  4939. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  4940. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  4941. if (chromaFormatIdc === 3) {
  4942. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  4943. }
  4944. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  4945. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  4946. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  4947. if (expGolombDecoder.readBoolean()) {
  4948. // seq_scaling_matrix_present_flag
  4949. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  4950. for (i = 0; i < scalingListCount; i++) {
  4951. if (expGolombDecoder.readBoolean()) {
  4952. // seq_scaling_list_present_flag[ i ]
  4953. if (i < 6) {
  4954. skipScalingList(16, expGolombDecoder);
  4955. } else {
  4956. skipScalingList(64, expGolombDecoder);
  4957. }
  4958. }
  4959. }
  4960. }
  4961. }
  4962. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  4963. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  4964. if (picOrderCntType === 0) {
  4965. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  4966. } else if (picOrderCntType === 1) {
  4967. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  4968. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  4969. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  4970. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  4971. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  4972. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  4973. }
  4974. }
  4975. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  4976. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  4977. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  4978. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  4979. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  4980. if (frameMbsOnlyFlag === 0) {
  4981. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  4982. }
  4983. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  4984. if (expGolombDecoder.readBoolean()) {
  4985. // frame_cropping_flag
  4986. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  4987. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  4988. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  4989. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  4990. }
  4991. if (expGolombDecoder.readBoolean()) {
  4992. // vui_parameters_present_flag
  4993. if (expGolombDecoder.readBoolean()) {
  4994. // aspect_ratio_info_present_flag
  4995. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  4996. switch (aspectRatioIdc) {
  4997. case 1:
  4998. sarRatio = [1, 1];
  4999. break;
  5000. case 2:
  5001. sarRatio = [12, 11];
  5002. break;
  5003. case 3:
  5004. sarRatio = [10, 11];
  5005. break;
  5006. case 4:
  5007. sarRatio = [16, 11];
  5008. break;
  5009. case 5:
  5010. sarRatio = [40, 33];
  5011. break;
  5012. case 6:
  5013. sarRatio = [24, 11];
  5014. break;
  5015. case 7:
  5016. sarRatio = [20, 11];
  5017. break;
  5018. case 8:
  5019. sarRatio = [32, 11];
  5020. break;
  5021. case 9:
  5022. sarRatio = [80, 33];
  5023. break;
  5024. case 10:
  5025. sarRatio = [18, 11];
  5026. break;
  5027. case 11:
  5028. sarRatio = [15, 11];
  5029. break;
  5030. case 12:
  5031. sarRatio = [64, 33];
  5032. break;
  5033. case 13:
  5034. sarRatio = [160, 99];
  5035. break;
  5036. case 14:
  5037. sarRatio = [4, 3];
  5038. break;
  5039. case 15:
  5040. sarRatio = [3, 2];
  5041. break;
  5042. case 16:
  5043. sarRatio = [2, 1];
  5044. break;
  5045. case 255:
  5046. {
  5047. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  5048. break;
  5049. }
  5050. }
  5051. if (sarRatio) {
  5052. sarRatio[0] / sarRatio[1];
  5053. }
  5054. }
  5055. }
  5056. return {
  5057. profileIdc: profileIdc,
  5058. levelIdc: levelIdc,
  5059. profileCompatibility: profileCompatibility,
  5060. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  5061. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  5062. // sar is sample aspect ratio
  5063. sarRatio: sarRatio
  5064. };
  5065. };
  5066. };
  5067. _H264Stream.prototype = new stream();
  5068. var h264 = {
  5069. H264Stream: _H264Stream,
  5070. NalByteStream: _NalByteStream
  5071. };
  5072. /**
  5073. * mux.js
  5074. *
  5075. * Copyright (c) Brightcove
  5076. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5077. *
  5078. * Utilities to detect basic properties and metadata about Aac data.
  5079. */
  5080. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  5081. var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
  5082. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  5083. flags = header[byteIndex + 5],
  5084. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  5085. returnSize = returnSize >= 0 ? returnSize : 0;
  5086. if (footerPresent) {
  5087. return returnSize + 20;
  5088. }
  5089. return returnSize + 10;
  5090. };
  5091. var getId3Offset = function getId3Offset(data, offset) {
  5092. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  5093. return offset;
  5094. }
  5095. offset += parseId3TagSize(data, offset);
  5096. return getId3Offset(data, offset);
  5097. }; // TODO: use vhs-utils
  5098. var isLikelyAacData$1 = function isLikelyAacData(data) {
  5099. var offset = getId3Offset(data, 0);
  5100. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  5101. // is not mp3 data but aac data.
  5102. (data[offset + 1] & 0x16) === 0x10;
  5103. };
  5104. var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
  5105. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  5106. }; // return a percent-encoded representation of the specified byte range
  5107. // @see http://en.wikipedia.org/wiki/Percent-encoding
  5108. var percentEncode = function percentEncode(bytes, start, end) {
  5109. var i,
  5110. result = '';
  5111. for (i = start; i < end; i++) {
  5112. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  5113. }
  5114. return result;
  5115. }; // return the string representation of the specified byte range,
  5116. // interpreted as ISO-8859-1.
  5117. var parseIso88591 = function parseIso88591(bytes, start, end) {
  5118. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  5119. };
  5120. var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
  5121. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  5122. middle = header[byteIndex + 4] << 3,
  5123. highTwo = header[byteIndex + 3] & 0x3 << 11;
  5124. return highTwo | middle | lowThree;
  5125. };
  5126. var parseType = function parseType(header, byteIndex) {
  5127. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  5128. return 'timed-metadata';
  5129. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  5130. return 'audio';
  5131. }
  5132. return null;
  5133. };
  5134. var parseSampleRate = function parseSampleRate(packet) {
  5135. var i = 0;
  5136. while (i + 5 < packet.length) {
  5137. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  5138. // If a valid header was not found, jump one forward and attempt to
  5139. // find a valid ADTS header starting at the next byte
  5140. i++;
  5141. continue;
  5142. }
  5143. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  5144. }
  5145. return null;
  5146. };
  5147. var parseAacTimestamp = function parseAacTimestamp(packet) {
  5148. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  5149. frameStart = 10;
  5150. if (packet[5] & 0x40) {
  5151. // advance the frame start past the extended header
  5152. frameStart += 4; // header size field
  5153. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  5154. } // parse one or more ID3 frames
  5155. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  5156. do {
  5157. // determine the number of bytes in this frame
  5158. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  5159. if (frameSize < 1) {
  5160. return null;
  5161. }
  5162. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  5163. if (frameHeader === 'PRIV') {
  5164. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  5165. for (var i = 0; i < frame.byteLength; i++) {
  5166. if (frame[i] === 0) {
  5167. var owner = parseIso88591(frame, 0, i);
  5168. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  5169. var d = frame.subarray(i + 1);
  5170. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  5171. size *= 4;
  5172. size += d[7] & 0x03;
  5173. return size;
  5174. }
  5175. break;
  5176. }
  5177. }
  5178. }
  5179. frameStart += 10; // advance past the frame header
  5180. frameStart += frameSize; // advance past the frame body
  5181. } while (frameStart < packet.byteLength);
  5182. return null;
  5183. };
  5184. var utils = {
  5185. isLikelyAacData: isLikelyAacData$1,
  5186. parseId3TagSize: parseId3TagSize,
  5187. parseAdtsSize: parseAdtsSize,
  5188. parseType: parseType,
  5189. parseSampleRate: parseSampleRate,
  5190. parseAacTimestamp: parseAacTimestamp
  5191. };
  5192. var _AacStream;
  5193. /**
  5194. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  5195. */
  5196. _AacStream = function AacStream() {
  5197. var everything = new Uint8Array(),
  5198. timeStamp = 0;
  5199. _AacStream.prototype.init.call(this);
  5200. this.setTimestamp = function (timestamp) {
  5201. timeStamp = timestamp;
  5202. };
  5203. this.push = function (bytes) {
  5204. var frameSize = 0,
  5205. byteIndex = 0,
  5206. bytesLeft,
  5207. chunk,
  5208. packet,
  5209. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  5210. // bytes that were pushed in
  5211. if (everything.length) {
  5212. tempLength = everything.length;
  5213. everything = new Uint8Array(bytes.byteLength + tempLength);
  5214. everything.set(everything.subarray(0, tempLength));
  5215. everything.set(bytes, tempLength);
  5216. } else {
  5217. everything = bytes;
  5218. }
  5219. while (everything.length - byteIndex >= 3) {
  5220. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  5221. // Exit early because we don't have enough to parse
  5222. // the ID3 tag header
  5223. if (everything.length - byteIndex < 10) {
  5224. break;
  5225. } // check framesize
  5226. frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  5227. // to emit a full packet
  5228. // Add to byteIndex to support multiple ID3 tags in sequence
  5229. if (byteIndex + frameSize > everything.length) {
  5230. break;
  5231. }
  5232. chunk = {
  5233. type: 'timed-metadata',
  5234. data: everything.subarray(byteIndex, byteIndex + frameSize)
  5235. };
  5236. this.trigger('data', chunk);
  5237. byteIndex += frameSize;
  5238. continue;
  5239. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  5240. // Exit early because we don't have enough to parse
  5241. // the ADTS frame header
  5242. if (everything.length - byteIndex < 7) {
  5243. break;
  5244. }
  5245. frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  5246. // to emit a full packet
  5247. if (byteIndex + frameSize > everything.length) {
  5248. break;
  5249. }
  5250. packet = {
  5251. type: 'audio',
  5252. data: everything.subarray(byteIndex, byteIndex + frameSize),
  5253. pts: timeStamp,
  5254. dts: timeStamp
  5255. };
  5256. this.trigger('data', packet);
  5257. byteIndex += frameSize;
  5258. continue;
  5259. }
  5260. byteIndex++;
  5261. }
  5262. bytesLeft = everything.length - byteIndex;
  5263. if (bytesLeft > 0) {
  5264. everything = everything.subarray(byteIndex);
  5265. } else {
  5266. everything = new Uint8Array();
  5267. }
  5268. };
  5269. this.reset = function () {
  5270. everything = new Uint8Array();
  5271. this.trigger('reset');
  5272. };
  5273. this.endTimeline = function () {
  5274. everything = new Uint8Array();
  5275. this.trigger('endedtimeline');
  5276. };
  5277. };
  5278. _AacStream.prototype = new stream();
  5279. var aac = _AacStream;
  5280. // constants
  5281. var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  5282. var audioProperties = AUDIO_PROPERTIES;
  5283. var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  5284. var videoProperties = VIDEO_PROPERTIES;
  5285. var H264Stream = h264.H264Stream;
  5286. var isLikelyAacData = utils.isLikelyAacData;
  5287. var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS; // object types
  5288. var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
  5289. var retriggerForStream = function retriggerForStream(key, event) {
  5290. event.stream = key;
  5291. this.trigger('log', event);
  5292. };
  5293. var addPipelineLogRetriggers = function addPipelineLogRetriggers(transmuxer, pipeline) {
  5294. var keys = Object.keys(pipeline);
  5295. for (var i = 0; i < keys.length; i++) {
  5296. var key = keys[i]; // skip non-stream keys and headOfPipeline
  5297. // which is just a duplicate
  5298. if (key === 'headOfPipeline' || !pipeline[key].on) {
  5299. continue;
  5300. }
  5301. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  5302. }
  5303. };
  5304. /**
  5305. * Compare two arrays (even typed) for same-ness
  5306. */
  5307. var arrayEquals = function arrayEquals(a, b) {
  5308. var i;
  5309. if (a.length !== b.length) {
  5310. return false;
  5311. } // compare the value of each element in the array
  5312. for (i = 0; i < a.length; i++) {
  5313. if (a[i] !== b[i]) {
  5314. return false;
  5315. }
  5316. }
  5317. return true;
  5318. };
  5319. var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  5320. var ptsOffsetFromDts = startPts - startDts,
  5321. decodeDuration = endDts - startDts,
  5322. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  5323. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  5324. // In order to provide relevant values for the player times, base timing info on the
  5325. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  5326. return {
  5327. start: {
  5328. dts: baseMediaDecodeTime,
  5329. pts: baseMediaDecodeTime + ptsOffsetFromDts
  5330. },
  5331. end: {
  5332. dts: baseMediaDecodeTime + decodeDuration,
  5333. pts: baseMediaDecodeTime + presentationDuration
  5334. },
  5335. prependedContentDuration: prependedContentDuration,
  5336. baseMediaDecodeTime: baseMediaDecodeTime
  5337. };
  5338. };
  5339. /**
  5340. * Constructs a single-track, ISO BMFF media segment from AAC data
  5341. * events. The output of this stream can be fed to a SourceBuffer
  5342. * configured with a suitable initialization segment.
  5343. * @param track {object} track metadata configuration
  5344. * @param options {object} transmuxer options object
  5345. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5346. * in the source; false to adjust the first segment to start at 0.
  5347. */
  5348. _AudioSegmentStream = function AudioSegmentStream(track, options) {
  5349. var adtsFrames = [],
  5350. sequenceNumber,
  5351. earliestAllowedDts = 0,
  5352. audioAppendStartTs = 0,
  5353. videoBaseMediaDecodeTime = Infinity;
  5354. options = options || {};
  5355. sequenceNumber = options.firstSequenceNumber || 0;
  5356. _AudioSegmentStream.prototype.init.call(this);
  5357. this.push = function (data) {
  5358. trackDecodeInfo.collectDtsInfo(track, data);
  5359. if (track) {
  5360. audioProperties.forEach(function (prop) {
  5361. track[prop] = data[prop];
  5362. });
  5363. } // buffer audio data until end() is called
  5364. adtsFrames.push(data);
  5365. };
  5366. this.setEarliestDts = function (earliestDts) {
  5367. earliestAllowedDts = earliestDts;
  5368. };
  5369. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  5370. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  5371. };
  5372. this.setAudioAppendStart = function (timestamp) {
  5373. audioAppendStartTs = timestamp;
  5374. };
  5375. this.flush = function () {
  5376. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  5377. if (adtsFrames.length === 0) {
  5378. this.trigger('done', 'AudioSegmentStream');
  5379. return;
  5380. }
  5381. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  5382. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  5383. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  5384. // samples (that is, adts frames) in the audio data
  5385. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  5386. mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
  5387. adtsFrames = [];
  5388. moof = mp4Generator.moof(sequenceNumber, [track]);
  5389. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  5390. sequenceNumber++;
  5391. boxes.set(moof);
  5392. boxes.set(mdat, moof.byteLength);
  5393. trackDecodeInfo.clearDtsInfo(track);
  5394. frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  5395. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  5396. // valid use-case where an init segment/data should be triggered without associated
  5397. // frames. Leaving for now, but should be looked into.
  5398. if (frames.length) {
  5399. segmentDuration = frames.length * frameDuration;
  5400. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  5401. // frame info is in video clock cycles. Convert to match expectation of
  5402. // listeners (that all timestamps will be based on video clock cycles).
  5403. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  5404. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  5405. this.trigger('timingInfo', {
  5406. start: frames[0].pts,
  5407. end: frames[0].pts + segmentDuration
  5408. });
  5409. }
  5410. this.trigger('data', {
  5411. track: track,
  5412. boxes: boxes
  5413. });
  5414. this.trigger('done', 'AudioSegmentStream');
  5415. };
  5416. this.reset = function () {
  5417. trackDecodeInfo.clearDtsInfo(track);
  5418. adtsFrames = [];
  5419. this.trigger('reset');
  5420. };
  5421. };
  5422. _AudioSegmentStream.prototype = new stream();
  5423. /**
  5424. * Constructs a single-track, ISO BMFF media segment from H264 data
  5425. * events. The output of this stream can be fed to a SourceBuffer
  5426. * configured with a suitable initialization segment.
  5427. * @param track {object} track metadata configuration
  5428. * @param options {object} transmuxer options object
  5429. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  5430. * gopsToAlignWith list when attempting to align gop pts
  5431. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5432. * in the source; false to adjust the first segment to start at 0.
  5433. */
  5434. _VideoSegmentStream = function VideoSegmentStream(track, options) {
  5435. var sequenceNumber,
  5436. nalUnits = [],
  5437. gopsToAlignWith = [],
  5438. config,
  5439. pps;
  5440. options = options || {};
  5441. sequenceNumber = options.firstSequenceNumber || 0;
  5442. _VideoSegmentStream.prototype.init.call(this);
  5443. delete track.minPTS;
  5444. this.gopCache_ = [];
  5445. /**
  5446. * Constructs a ISO BMFF segment given H264 nalUnits
  5447. * @param {Object} nalUnit A data event representing a nalUnit
  5448. * @param {String} nalUnit.nalUnitType
  5449. * @param {Object} nalUnit.config Properties for a mp4 track
  5450. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  5451. * @see lib/codecs/h264.js
  5452. **/
  5453. this.push = function (nalUnit) {
  5454. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  5455. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  5456. config = nalUnit.config;
  5457. track.sps = [nalUnit.data];
  5458. videoProperties.forEach(function (prop) {
  5459. track[prop] = config[prop];
  5460. }, this);
  5461. }
  5462. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  5463. pps = nalUnit.data;
  5464. track.pps = [nalUnit.data];
  5465. } // buffer video until flush() is called
  5466. nalUnits.push(nalUnit);
  5467. };
  5468. /**
  5469. * Pass constructed ISO BMFF track and boxes on to the
  5470. * next stream in the pipeline
  5471. **/
  5472. this.flush = function () {
  5473. var frames,
  5474. gopForFusion,
  5475. gops,
  5476. moof,
  5477. mdat,
  5478. boxes,
  5479. prependedContentDuration = 0,
  5480. firstGop,
  5481. lastGop; // Throw away nalUnits at the start of the byte stream until
  5482. // we find the first AUD
  5483. while (nalUnits.length) {
  5484. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  5485. break;
  5486. }
  5487. nalUnits.shift();
  5488. } // Return early if no video data has been observed
  5489. if (nalUnits.length === 0) {
  5490. this.resetStream_();
  5491. this.trigger('done', 'VideoSegmentStream');
  5492. return;
  5493. } // Organize the raw nal-units into arrays that represent
  5494. // higher-level constructs such as frames and gops
  5495. // (group-of-pictures)
  5496. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  5497. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  5498. // a problem since MSE (on Chrome) requires a leading keyframe.
  5499. //
  5500. // We have two approaches to repairing this situation:
  5501. // 1) GOP-FUSION:
  5502. // This is where we keep track of the GOPS (group-of-pictures)
  5503. // from previous fragments and attempt to find one that we can
  5504. // prepend to the current fragment in order to create a valid
  5505. // fragment.
  5506. // 2) KEYFRAME-PULLING:
  5507. // Here we search for the first keyframe in the fragment and
  5508. // throw away all the frames between the start of the fragment
  5509. // and that keyframe. We then extend the duration and pull the
  5510. // PTS of the keyframe forward so that it covers the time range
  5511. // of the frames that were disposed of.
  5512. //
  5513. // #1 is far prefereable over #2 which can cause "stuttering" but
  5514. // requires more things to be just right.
  5515. if (!gops[0][0].keyFrame) {
  5516. // Search for a gop for fusion from our gopCache
  5517. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  5518. if (gopForFusion) {
  5519. // in order to provide more accurate timing information about the segment, save
  5520. // the number of seconds prepended to the original segment due to GOP fusion
  5521. prependedContentDuration = gopForFusion.duration;
  5522. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  5523. // new gop at the beginning
  5524. gops.byteLength += gopForFusion.byteLength;
  5525. gops.nalCount += gopForFusion.nalCount;
  5526. gops.pts = gopForFusion.pts;
  5527. gops.dts = gopForFusion.dts;
  5528. gops.duration += gopForFusion.duration;
  5529. } else {
  5530. // If we didn't find a candidate gop fall back to keyframe-pulling
  5531. gops = frameUtils.extendFirstKeyFrame(gops);
  5532. }
  5533. } // Trim gops to align with gopsToAlignWith
  5534. if (gopsToAlignWith.length) {
  5535. var alignedGops;
  5536. if (options.alignGopsAtEnd) {
  5537. alignedGops = this.alignGopsAtEnd_(gops);
  5538. } else {
  5539. alignedGops = this.alignGopsAtStart_(gops);
  5540. }
  5541. if (!alignedGops) {
  5542. // save all the nals in the last GOP into the gop cache
  5543. this.gopCache_.unshift({
  5544. gop: gops.pop(),
  5545. pps: track.pps,
  5546. sps: track.sps
  5547. }); // Keep a maximum of 6 GOPs in the cache
  5548. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  5549. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  5550. this.resetStream_();
  5551. this.trigger('done', 'VideoSegmentStream');
  5552. return;
  5553. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  5554. // when recalculated before sending off to CoalesceStream
  5555. trackDecodeInfo.clearDtsInfo(track);
  5556. gops = alignedGops;
  5557. }
  5558. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  5559. // samples (that is, frames) in the video data
  5560. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  5561. mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
  5562. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  5563. this.trigger('processedGopsInfo', gops.map(function (gop) {
  5564. return {
  5565. pts: gop.pts,
  5566. dts: gop.dts,
  5567. byteLength: gop.byteLength
  5568. };
  5569. }));
  5570. firstGop = gops[0];
  5571. lastGop = gops[gops.length - 1];
  5572. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  5573. this.trigger('timingInfo', {
  5574. start: gops[0].pts,
  5575. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  5576. }); // save all the nals in the last GOP into the gop cache
  5577. this.gopCache_.unshift({
  5578. gop: gops.pop(),
  5579. pps: track.pps,
  5580. sps: track.sps
  5581. }); // Keep a maximum of 6 GOPs in the cache
  5582. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  5583. nalUnits = [];
  5584. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  5585. this.trigger('timelineStartInfo', track.timelineStartInfo);
  5586. moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  5587. // throwing away hundreds of media segment fragments
  5588. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  5589. sequenceNumber++;
  5590. boxes.set(moof);
  5591. boxes.set(mdat, moof.byteLength);
  5592. this.trigger('data', {
  5593. track: track,
  5594. boxes: boxes
  5595. });
  5596. this.resetStream_(); // Continue with the flush process now
  5597. this.trigger('done', 'VideoSegmentStream');
  5598. };
  5599. this.reset = function () {
  5600. this.resetStream_();
  5601. nalUnits = [];
  5602. this.gopCache_.length = 0;
  5603. gopsToAlignWith.length = 0;
  5604. this.trigger('reset');
  5605. };
  5606. this.resetStream_ = function () {
  5607. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  5608. // for instance, when we are rendition switching
  5609. config = undefined;
  5610. pps = undefined;
  5611. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  5612. // return it or return null if no good candidate was found
  5613. this.getGopForFusion_ = function (nalUnit) {
  5614. var halfSecond = 45000,
  5615. // Half-a-second in a 90khz clock
  5616. allowableOverlap = 10000,
  5617. // About 3 frames @ 30fps
  5618. nearestDistance = Infinity,
  5619. dtsDistance,
  5620. nearestGopObj,
  5621. currentGop,
  5622. currentGopObj,
  5623. i; // Search for the GOP nearest to the beginning of this nal unit
  5624. for (i = 0; i < this.gopCache_.length; i++) {
  5625. currentGopObj = this.gopCache_[i];
  5626. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  5627. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  5628. continue;
  5629. } // Reject Gops that would require a negative baseMediaDecodeTime
  5630. if (currentGop.dts < track.timelineStartInfo.dts) {
  5631. continue;
  5632. } // The distance between the end of the gop and the start of the nalUnit
  5633. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  5634. // a half-second of the nal unit
  5635. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  5636. // Always use the closest GOP we found if there is more than
  5637. // one candidate
  5638. if (!nearestGopObj || nearestDistance > dtsDistance) {
  5639. nearestGopObj = currentGopObj;
  5640. nearestDistance = dtsDistance;
  5641. }
  5642. }
  5643. }
  5644. if (nearestGopObj) {
  5645. return nearestGopObj.gop;
  5646. }
  5647. return null;
  5648. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  5649. // of gopsToAlignWith starting from the START of the list
  5650. this.alignGopsAtStart_ = function (gops) {
  5651. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  5652. byteLength = gops.byteLength;
  5653. nalCount = gops.nalCount;
  5654. duration = gops.duration;
  5655. alignIndex = gopIndex = 0;
  5656. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  5657. align = gopsToAlignWith[alignIndex];
  5658. gop = gops[gopIndex];
  5659. if (align.pts === gop.pts) {
  5660. break;
  5661. }
  5662. if (gop.pts > align.pts) {
  5663. // this current gop starts after the current gop we want to align on, so increment
  5664. // align index
  5665. alignIndex++;
  5666. continue;
  5667. } // current gop starts before the current gop we want to align on. so increment gop
  5668. // index
  5669. gopIndex++;
  5670. byteLength -= gop.byteLength;
  5671. nalCount -= gop.nalCount;
  5672. duration -= gop.duration;
  5673. }
  5674. if (gopIndex === 0) {
  5675. // no gops to trim
  5676. return gops;
  5677. }
  5678. if (gopIndex === gops.length) {
  5679. // all gops trimmed, skip appending all gops
  5680. return null;
  5681. }
  5682. alignedGops = gops.slice(gopIndex);
  5683. alignedGops.byteLength = byteLength;
  5684. alignedGops.duration = duration;
  5685. alignedGops.nalCount = nalCount;
  5686. alignedGops.pts = alignedGops[0].pts;
  5687. alignedGops.dts = alignedGops[0].dts;
  5688. return alignedGops;
  5689. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  5690. // of gopsToAlignWith starting from the END of the list
  5691. this.alignGopsAtEnd_ = function (gops) {
  5692. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  5693. alignIndex = gopsToAlignWith.length - 1;
  5694. gopIndex = gops.length - 1;
  5695. alignEndIndex = null;
  5696. matchFound = false;
  5697. while (alignIndex >= 0 && gopIndex >= 0) {
  5698. align = gopsToAlignWith[alignIndex];
  5699. gop = gops[gopIndex];
  5700. if (align.pts === gop.pts) {
  5701. matchFound = true;
  5702. break;
  5703. }
  5704. if (align.pts > gop.pts) {
  5705. alignIndex--;
  5706. continue;
  5707. }
  5708. if (alignIndex === gopsToAlignWith.length - 1) {
  5709. // gop.pts is greater than the last alignment candidate. If no match is found
  5710. // by the end of this loop, we still want to append gops that come after this
  5711. // point
  5712. alignEndIndex = gopIndex;
  5713. }
  5714. gopIndex--;
  5715. }
  5716. if (!matchFound && alignEndIndex === null) {
  5717. return null;
  5718. }
  5719. var trimIndex;
  5720. if (matchFound) {
  5721. trimIndex = gopIndex;
  5722. } else {
  5723. trimIndex = alignEndIndex;
  5724. }
  5725. if (trimIndex === 0) {
  5726. return gops;
  5727. }
  5728. var alignedGops = gops.slice(trimIndex);
  5729. var metadata = alignedGops.reduce(function (total, gop) {
  5730. total.byteLength += gop.byteLength;
  5731. total.duration += gop.duration;
  5732. total.nalCount += gop.nalCount;
  5733. return total;
  5734. }, {
  5735. byteLength: 0,
  5736. duration: 0,
  5737. nalCount: 0
  5738. });
  5739. alignedGops.byteLength = metadata.byteLength;
  5740. alignedGops.duration = metadata.duration;
  5741. alignedGops.nalCount = metadata.nalCount;
  5742. alignedGops.pts = alignedGops[0].pts;
  5743. alignedGops.dts = alignedGops[0].dts;
  5744. return alignedGops;
  5745. };
  5746. this.alignGopsWith = function (newGopsToAlignWith) {
  5747. gopsToAlignWith = newGopsToAlignWith;
  5748. };
  5749. };
  5750. _VideoSegmentStream.prototype = new stream();
  5751. /**
  5752. * A Stream that can combine multiple streams (ie. audio & video)
  5753. * into a single output segment for MSE. Also supports audio-only
  5754. * and video-only streams.
  5755. * @param options {object} transmuxer options object
  5756. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5757. * in the source; false to adjust the first segment to start at media timeline start.
  5758. */
  5759. _CoalesceStream = function CoalesceStream(options, metadataStream) {
  5760. // Number of Tracks per output segment
  5761. // If greater than 1, we combine multiple
  5762. // tracks into a single segment
  5763. this.numberOfTracks = 0;
  5764. this.metadataStream = metadataStream;
  5765. options = options || {};
  5766. if (typeof options.remux !== 'undefined') {
  5767. this.remuxTracks = !!options.remux;
  5768. } else {
  5769. this.remuxTracks = true;
  5770. }
  5771. if (typeof options.keepOriginalTimestamps === 'boolean') {
  5772. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  5773. } else {
  5774. this.keepOriginalTimestamps = false;
  5775. }
  5776. this.pendingTracks = [];
  5777. this.videoTrack = null;
  5778. this.pendingBoxes = [];
  5779. this.pendingCaptions = [];
  5780. this.pendingMetadata = [];
  5781. this.pendingBytes = 0;
  5782. this.emittedTracks = 0;
  5783. _CoalesceStream.prototype.init.call(this); // Take output from multiple
  5784. this.push = function (output) {
  5785. // buffer incoming captions until the associated video segment
  5786. // finishes
  5787. if (output.text) {
  5788. return this.pendingCaptions.push(output);
  5789. } // buffer incoming id3 tags until the final flush
  5790. if (output.frames) {
  5791. return this.pendingMetadata.push(output);
  5792. } // Add this track to the list of pending tracks and store
  5793. // important information required for the construction of
  5794. // the final segment
  5795. this.pendingTracks.push(output.track);
  5796. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  5797. // We unshift audio and push video because
  5798. // as of Chrome 75 when switching from
  5799. // one init segment to another if the video
  5800. // mdat does not appear after the audio mdat
  5801. // only audio will play for the duration of our transmux.
  5802. if (output.track.type === 'video') {
  5803. this.videoTrack = output.track;
  5804. this.pendingBoxes.push(output.boxes);
  5805. }
  5806. if (output.track.type === 'audio') {
  5807. this.audioTrack = output.track;
  5808. this.pendingBoxes.unshift(output.boxes);
  5809. }
  5810. };
  5811. };
  5812. _CoalesceStream.prototype = new stream();
  5813. _CoalesceStream.prototype.flush = function (flushSource) {
  5814. var offset = 0,
  5815. event = {
  5816. captions: [],
  5817. captionStreams: {},
  5818. metadata: [],
  5819. info: {}
  5820. },
  5821. caption,
  5822. id3,
  5823. initSegment,
  5824. timelineStartPts = 0,
  5825. i;
  5826. if (this.pendingTracks.length < this.numberOfTracks) {
  5827. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  5828. // Return because we haven't received a flush from a data-generating
  5829. // portion of the segment (meaning that we have only recieved meta-data
  5830. // or captions.)
  5831. return;
  5832. } else if (this.remuxTracks) {
  5833. // Return until we have enough tracks from the pipeline to remux (if we
  5834. // are remuxing audio and video into a single MP4)
  5835. return;
  5836. } else if (this.pendingTracks.length === 0) {
  5837. // In the case where we receive a flush without any data having been
  5838. // received we consider it an emitted track for the purposes of coalescing
  5839. // `done` events.
  5840. // We do this for the case where there is an audio and video track in the
  5841. // segment but no audio data. (seen in several playlists with alternate
  5842. // audio tracks and no audio present in the main TS segments.)
  5843. this.emittedTracks++;
  5844. if (this.emittedTracks >= this.numberOfTracks) {
  5845. this.trigger('done');
  5846. this.emittedTracks = 0;
  5847. }
  5848. return;
  5849. }
  5850. }
  5851. if (this.videoTrack) {
  5852. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  5853. videoProperties.forEach(function (prop) {
  5854. event.info[prop] = this.videoTrack[prop];
  5855. }, this);
  5856. } else if (this.audioTrack) {
  5857. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  5858. audioProperties.forEach(function (prop) {
  5859. event.info[prop] = this.audioTrack[prop];
  5860. }, this);
  5861. }
  5862. if (this.videoTrack || this.audioTrack) {
  5863. if (this.pendingTracks.length === 1) {
  5864. event.type = this.pendingTracks[0].type;
  5865. } else {
  5866. event.type = 'combined';
  5867. }
  5868. this.emittedTracks += this.pendingTracks.length;
  5869. initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  5870. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  5871. // and track definitions
  5872. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  5873. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  5874. for (i = 0; i < this.pendingBoxes.length; i++) {
  5875. event.data.set(this.pendingBoxes[i], offset);
  5876. offset += this.pendingBoxes[i].byteLength;
  5877. } // Translate caption PTS times into second offsets to match the
  5878. // video timeline for the segment, and add track info
  5879. for (i = 0; i < this.pendingCaptions.length; i++) {
  5880. caption = this.pendingCaptions[i];
  5881. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  5882. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  5883. event.captionStreams[caption.stream] = true;
  5884. event.captions.push(caption);
  5885. } // Translate ID3 frame PTS times into second offsets to match the
  5886. // video timeline for the segment
  5887. for (i = 0; i < this.pendingMetadata.length; i++) {
  5888. id3 = this.pendingMetadata[i];
  5889. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  5890. event.metadata.push(id3);
  5891. } // We add this to every single emitted segment even though we only need
  5892. // it for the first
  5893. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  5894. this.pendingTracks.length = 0;
  5895. this.videoTrack = null;
  5896. this.pendingBoxes.length = 0;
  5897. this.pendingCaptions.length = 0;
  5898. this.pendingBytes = 0;
  5899. this.pendingMetadata.length = 0; // Emit the built segment
  5900. // We include captions and ID3 tags for backwards compatibility,
  5901. // ideally we should send only video and audio in the data event
  5902. this.trigger('data', event); // Emit each caption to the outside world
  5903. // Ideally, this would happen immediately on parsing captions,
  5904. // but we need to ensure that video data is sent back first
  5905. // so that caption timing can be adjusted to match video timing
  5906. for (i = 0; i < event.captions.length; i++) {
  5907. caption = event.captions[i];
  5908. this.trigger('caption', caption);
  5909. } // Emit each id3 tag to the outside world
  5910. // Ideally, this would happen immediately on parsing the tag,
  5911. // but we need to ensure that video data is sent back first
  5912. // so that ID3 frame timing can be adjusted to match video timing
  5913. for (i = 0; i < event.metadata.length; i++) {
  5914. id3 = event.metadata[i];
  5915. this.trigger('id3Frame', id3);
  5916. }
  5917. } // Only emit `done` if all tracks have been flushed and emitted
  5918. if (this.emittedTracks >= this.numberOfTracks) {
  5919. this.trigger('done');
  5920. this.emittedTracks = 0;
  5921. }
  5922. };
  5923. _CoalesceStream.prototype.setRemux = function (val) {
  5924. this.remuxTracks = val;
  5925. };
  5926. /**
  5927. * A Stream that expects MP2T binary data as input and produces
  5928. * corresponding media segments, suitable for use with Media Source
  5929. * Extension (MSE) implementations that support the ISO BMFF byte
  5930. * stream format, like Chrome.
  5931. */
  5932. _Transmuxer = function Transmuxer(options) {
  5933. var self = this,
  5934. hasFlushed = true,
  5935. videoTrack,
  5936. audioTrack;
  5937. _Transmuxer.prototype.init.call(this);
  5938. options = options || {};
  5939. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  5940. this.transmuxPipeline_ = {};
  5941. this.setupAacPipeline = function () {
  5942. var pipeline = {};
  5943. this.transmuxPipeline_ = pipeline;
  5944. pipeline.type = 'aac';
  5945. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  5946. pipeline.aacStream = new aac();
  5947. pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
  5948. pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
  5949. pipeline.adtsStream = new adts();
  5950. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  5951. pipeline.headOfPipeline = pipeline.aacStream;
  5952. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  5953. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  5954. pipeline.metadataStream.on('timestamp', function (frame) {
  5955. pipeline.aacStream.setTimestamp(frame.timeStamp);
  5956. });
  5957. pipeline.aacStream.on('data', function (data) {
  5958. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  5959. return;
  5960. }
  5961. audioTrack = audioTrack || {
  5962. timelineStartInfo: {
  5963. baseMediaDecodeTime: self.baseMediaDecodeTime
  5964. },
  5965. codec: 'adts',
  5966. type: 'audio'
  5967. }; // hook up the audio segment stream to the first track with aac data
  5968. pipeline.coalesceStream.numberOfTracks++;
  5969. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  5970. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  5971. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  5972. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  5973. self.trigger('trackinfo', {
  5974. hasAudio: !!audioTrack,
  5975. hasVideo: !!videoTrack
  5976. });
  5977. }); // Re-emit any data coming from the coalesce stream to the outside world
  5978. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  5979. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  5980. addPipelineLogRetriggers(this, pipeline);
  5981. };
  5982. this.setupTsPipeline = function () {
  5983. var pipeline = {};
  5984. this.transmuxPipeline_ = pipeline;
  5985. pipeline.type = 'ts';
  5986. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  5987. pipeline.packetStream = new m2ts_1.TransportPacketStream();
  5988. pipeline.parseStream = new m2ts_1.TransportParseStream();
  5989. pipeline.elementaryStream = new m2ts_1.ElementaryStream();
  5990. pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
  5991. pipeline.adtsStream = new adts();
  5992. pipeline.h264Stream = new H264Stream();
  5993. pipeline.captionStream = new m2ts_1.CaptionStream(options);
  5994. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  5995. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  5996. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  5997. // demux the streams
  5998. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  5999. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  6000. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  6001. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  6002. pipeline.elementaryStream.on('data', function (data) {
  6003. var i;
  6004. if (data.type === 'metadata') {
  6005. i = data.tracks.length; // scan the tracks listed in the metadata
  6006. while (i--) {
  6007. if (!videoTrack && data.tracks[i].type === 'video') {
  6008. videoTrack = data.tracks[i];
  6009. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  6010. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  6011. audioTrack = data.tracks[i];
  6012. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  6013. }
  6014. } // hook up the video segment stream to the first track with h264 data
  6015. if (videoTrack && !pipeline.videoSegmentStream) {
  6016. pipeline.coalesceStream.numberOfTracks++;
  6017. pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
  6018. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  6019. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  6020. // When video emits timelineStartInfo data after a flush, we forward that
  6021. // info to the AudioSegmentStream, if it exists, because video timeline
  6022. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  6023. // because this is a particularly subtle form of timestamp alteration.
  6024. if (audioTrack && !options.keepOriginalTimestamps) {
  6025. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  6026. // very earliest DTS we have seen in video because Chrome will
  6027. // interpret any video track with a baseMediaDecodeTime that is
  6028. // non-zero as a gap.
  6029. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  6030. }
  6031. });
  6032. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  6033. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  6034. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  6035. if (audioTrack) {
  6036. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  6037. }
  6038. });
  6039. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  6040. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  6041. }
  6042. if (audioTrack && !pipeline.audioSegmentStream) {
  6043. // hook up the audio segment stream to the first track with aac data
  6044. pipeline.coalesceStream.numberOfTracks++;
  6045. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  6046. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  6047. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  6048. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  6049. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  6050. } // emit pmt info
  6051. self.trigger('trackinfo', {
  6052. hasAudio: !!audioTrack,
  6053. hasVideo: !!videoTrack
  6054. });
  6055. }
  6056. }); // Re-emit any data coming from the coalesce stream to the outside world
  6057. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  6058. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  6059. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  6060. self.trigger('id3Frame', id3Frame);
  6061. });
  6062. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  6063. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  6064. addPipelineLogRetriggers(this, pipeline);
  6065. }; // hook up the segment streams once track metadata is delivered
  6066. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  6067. var pipeline = this.transmuxPipeline_;
  6068. if (!options.keepOriginalTimestamps) {
  6069. this.baseMediaDecodeTime = baseMediaDecodeTime;
  6070. }
  6071. if (audioTrack) {
  6072. audioTrack.timelineStartInfo.dts = undefined;
  6073. audioTrack.timelineStartInfo.pts = undefined;
  6074. trackDecodeInfo.clearDtsInfo(audioTrack);
  6075. if (pipeline.audioTimestampRolloverStream) {
  6076. pipeline.audioTimestampRolloverStream.discontinuity();
  6077. }
  6078. }
  6079. if (videoTrack) {
  6080. if (pipeline.videoSegmentStream) {
  6081. pipeline.videoSegmentStream.gopCache_ = [];
  6082. }
  6083. videoTrack.timelineStartInfo.dts = undefined;
  6084. videoTrack.timelineStartInfo.pts = undefined;
  6085. trackDecodeInfo.clearDtsInfo(videoTrack);
  6086. pipeline.captionStream.reset();
  6087. }
  6088. if (pipeline.timestampRolloverStream) {
  6089. pipeline.timestampRolloverStream.discontinuity();
  6090. }
  6091. };
  6092. this.setAudioAppendStart = function (timestamp) {
  6093. if (audioTrack) {
  6094. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  6095. }
  6096. };
  6097. this.setRemux = function (val) {
  6098. var pipeline = this.transmuxPipeline_;
  6099. options.remux = val;
  6100. if (pipeline && pipeline.coalesceStream) {
  6101. pipeline.coalesceStream.setRemux(val);
  6102. }
  6103. };
  6104. this.alignGopsWith = function (gopsToAlignWith) {
  6105. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  6106. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  6107. }
  6108. };
  6109. this.getLogTrigger_ = function (key) {
  6110. var self = this;
  6111. return function (event) {
  6112. event.stream = key;
  6113. self.trigger('log', event);
  6114. };
  6115. }; // feed incoming data to the front of the parsing pipeline
  6116. this.push = function (data) {
  6117. if (hasFlushed) {
  6118. var isAac = isLikelyAacData(data);
  6119. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  6120. this.setupAacPipeline();
  6121. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  6122. this.setupTsPipeline();
  6123. }
  6124. hasFlushed = false;
  6125. }
  6126. this.transmuxPipeline_.headOfPipeline.push(data);
  6127. }; // flush any buffered data
  6128. this.flush = function () {
  6129. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  6130. this.transmuxPipeline_.headOfPipeline.flush();
  6131. };
  6132. this.endTimeline = function () {
  6133. this.transmuxPipeline_.headOfPipeline.endTimeline();
  6134. };
  6135. this.reset = function () {
  6136. if (this.transmuxPipeline_.headOfPipeline) {
  6137. this.transmuxPipeline_.headOfPipeline.reset();
  6138. }
  6139. }; // Caption data has to be reset when seeking outside buffered range
  6140. this.resetCaptions = function () {
  6141. if (this.transmuxPipeline_.captionStream) {
  6142. this.transmuxPipeline_.captionStream.reset();
  6143. }
  6144. };
  6145. };
  6146. _Transmuxer.prototype = new stream();
  6147. var transmuxer = {
  6148. Transmuxer: _Transmuxer,
  6149. VideoSegmentStream: _VideoSegmentStream,
  6150. AudioSegmentStream: _AudioSegmentStream,
  6151. AUDIO_PROPERTIES: audioProperties,
  6152. VIDEO_PROPERTIES: videoProperties,
  6153. // exported for testing
  6154. generateSegmentTimingInfo: generateSegmentTimingInfo
  6155. };
  6156. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  6157. var CaptionStream = captionStream.CaptionStream;
  6158. /**
  6159. * Maps an offset in the mdat to a sample based on the the size of the samples.
  6160. * Assumes that `parseSamples` has been called first.
  6161. *
  6162. * @param {Number} offset - The offset into the mdat
  6163. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  6164. * @return {?Object} The matching sample, or null if no match was found.
  6165. *
  6166. * @see ISO-BMFF-12/2015, Section 8.8.8
  6167. **/
  6168. var mapToSample = function mapToSample(offset, samples) {
  6169. var approximateOffset = offset;
  6170. for (var i = 0; i < samples.length; i++) {
  6171. var sample = samples[i];
  6172. if (approximateOffset < sample.size) {
  6173. return sample;
  6174. }
  6175. approximateOffset -= sample.size;
  6176. }
  6177. return null;
  6178. };
  6179. /**
  6180. * Finds SEI nal units contained in a Media Data Box.
  6181. * Assumes that `parseSamples` has been called first.
  6182. *
  6183. * @param {Uint8Array} avcStream - The bytes of the mdat
  6184. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  6185. * @param {Number} trackId - The trackId of this video track
  6186. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  6187. * The contents of the seiNal should match what is expected by
  6188. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  6189. *
  6190. * @see ISO-BMFF-12/2015, Section 8.1.1
  6191. * @see Rec. ITU-T H.264, 7.3.2.3.1
  6192. **/
  6193. var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
  6194. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  6195. result = {
  6196. logs: [],
  6197. seiNals: []
  6198. },
  6199. seiNal,
  6200. i,
  6201. length,
  6202. lastMatchedSample;
  6203. for (i = 0; i + 4 < avcStream.length; i += length) {
  6204. length = avcView.getUint32(i);
  6205. i += 4; // Bail if this doesn't appear to be an H264 stream
  6206. if (length <= 0) {
  6207. continue;
  6208. }
  6209. switch (avcStream[i] & 0x1F) {
  6210. case 0x06:
  6211. var data = avcStream.subarray(i + 1, i + 1 + length);
  6212. var matchingSample = mapToSample(i, samples);
  6213. seiNal = {
  6214. nalUnitType: 'sei_rbsp',
  6215. size: length,
  6216. data: data,
  6217. escapedRBSP: discardEmulationPreventionBytes(data),
  6218. trackId: trackId
  6219. };
  6220. if (matchingSample) {
  6221. seiNal.pts = matchingSample.pts;
  6222. seiNal.dts = matchingSample.dts;
  6223. lastMatchedSample = matchingSample;
  6224. } else if (lastMatchedSample) {
  6225. // If a matching sample cannot be found, use the last
  6226. // sample's values as they should be as close as possible
  6227. seiNal.pts = lastMatchedSample.pts;
  6228. seiNal.dts = lastMatchedSample.dts;
  6229. } else {
  6230. result.logs.push({
  6231. level: 'warn',
  6232. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  6233. });
  6234. break;
  6235. }
  6236. result.seiNals.push(seiNal);
  6237. break;
  6238. }
  6239. }
  6240. return result;
  6241. };
  6242. /**
  6243. * Parses sample information out of Track Run Boxes and calculates
  6244. * the absolute presentation and decode timestamps of each sample.
  6245. *
  6246. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  6247. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  6248. @see ISO-BMFF-12/2015, Section 8.8.12
  6249. * @param {Object} tfhd - The parsed Track Fragment Header
  6250. * @see inspect.parseTfhd
  6251. * @return {Object[]} the parsed samples
  6252. *
  6253. * @see ISO-BMFF-12/2015, Section 8.8.8
  6254. **/
  6255. var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
  6256. var currentDts = baseMediaDecodeTime;
  6257. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  6258. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  6259. var trackId = tfhd.trackId;
  6260. var allSamples = [];
  6261. truns.forEach(function (trun) {
  6262. // Note: We currently do not parse the sample table as well
  6263. // as the trun. It's possible some sources will require this.
  6264. // moov > trak > mdia > minf > stbl
  6265. var trackRun = parseTrun(trun);
  6266. var samples = trackRun.samples;
  6267. samples.forEach(function (sample) {
  6268. if (sample.duration === undefined) {
  6269. sample.duration = defaultSampleDuration;
  6270. }
  6271. if (sample.size === undefined) {
  6272. sample.size = defaultSampleSize;
  6273. }
  6274. sample.trackId = trackId;
  6275. sample.dts = currentDts;
  6276. if (sample.compositionTimeOffset === undefined) {
  6277. sample.compositionTimeOffset = 0;
  6278. }
  6279. if (typeof currentDts === 'bigint') {
  6280. sample.pts = currentDts + window__default['default'].BigInt(sample.compositionTimeOffset);
  6281. currentDts += window__default['default'].BigInt(sample.duration);
  6282. } else {
  6283. sample.pts = currentDts + sample.compositionTimeOffset;
  6284. currentDts += sample.duration;
  6285. }
  6286. });
  6287. allSamples = allSamples.concat(samples);
  6288. });
  6289. return allSamples;
  6290. };
  6291. /**
  6292. * Parses out caption nals from an FMP4 segment's video tracks.
  6293. *
  6294. * @param {Uint8Array} segment - The bytes of a single segment
  6295. * @param {Number} videoTrackId - The trackId of a video track in the segment
  6296. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  6297. * a list of seiNals found in that track
  6298. **/
  6299. var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
  6300. // To get the samples
  6301. var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
  6302. var mdats = findBox_1(segment, ['mdat']);
  6303. var captionNals = {};
  6304. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  6305. mdats.forEach(function (mdat, index) {
  6306. var matchingTraf = trafs[index];
  6307. mdatTrafPairs.push({
  6308. mdat: mdat,
  6309. traf: matchingTraf
  6310. });
  6311. });
  6312. mdatTrafPairs.forEach(function (pair) {
  6313. var mdat = pair.mdat;
  6314. var traf = pair.traf;
  6315. var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  6316. var headerInfo = parseTfhd(tfhd[0]);
  6317. var trackId = headerInfo.trackId;
  6318. var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  6319. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  6320. var truns = findBox_1(traf, ['trun']);
  6321. var samples;
  6322. var result; // Only parse video data for the chosen video track
  6323. if (videoTrackId === trackId && truns.length > 0) {
  6324. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  6325. result = findSeiNals(mdat, samples, trackId);
  6326. if (!captionNals[trackId]) {
  6327. captionNals[trackId] = {
  6328. seiNals: [],
  6329. logs: []
  6330. };
  6331. }
  6332. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  6333. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  6334. }
  6335. });
  6336. return captionNals;
  6337. };
  6338. /**
  6339. * Parses out inband captions from an MP4 container and returns
  6340. * caption objects that can be used by WebVTT and the TextTrack API.
  6341. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  6342. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  6343. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  6344. *
  6345. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  6346. * @param {Number} trackId - The id of the video track to parse
  6347. * @param {Number} timescale - The timescale for the video track from the init segment
  6348. *
  6349. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  6350. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  6351. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  6352. * @return {String} parsedCaptions[].text - The visible content of the caption
  6353. **/
  6354. var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
  6355. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  6356. if (trackId === null) {
  6357. return null;
  6358. }
  6359. captionNals = parseCaptionNals(segment, trackId);
  6360. var trackNals = captionNals[trackId] || {};
  6361. return {
  6362. seiNals: trackNals.seiNals,
  6363. logs: trackNals.logs,
  6364. timescale: timescale
  6365. };
  6366. };
  6367. /**
  6368. * Converts SEI NALUs into captions that can be used by video.js
  6369. **/
  6370. var CaptionParser = function CaptionParser() {
  6371. var isInitialized = false;
  6372. var captionStream; // Stores segments seen before trackId and timescale are set
  6373. var segmentCache; // Stores video track ID of the track being parsed
  6374. var trackId; // Stores the timescale of the track being parsed
  6375. var timescale; // Stores captions parsed so far
  6376. var parsedCaptions; // Stores whether we are receiving partial data or not
  6377. var parsingPartial;
  6378. /**
  6379. * A method to indicate whether a CaptionParser has been initalized
  6380. * @returns {Boolean}
  6381. **/
  6382. this.isInitialized = function () {
  6383. return isInitialized;
  6384. };
  6385. /**
  6386. * Initializes the underlying CaptionStream, SEI NAL parsing
  6387. * and management, and caption collection
  6388. **/
  6389. this.init = function (options) {
  6390. captionStream = new CaptionStream();
  6391. isInitialized = true;
  6392. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  6393. captionStream.on('data', function (event) {
  6394. // Convert to seconds in the source's timescale
  6395. event.startTime = event.startPts / timescale;
  6396. event.endTime = event.endPts / timescale;
  6397. parsedCaptions.captions.push(event);
  6398. parsedCaptions.captionStreams[event.stream] = true;
  6399. });
  6400. captionStream.on('log', function (log) {
  6401. parsedCaptions.logs.push(log);
  6402. });
  6403. };
  6404. /**
  6405. * Determines if a new video track will be selected
  6406. * or if the timescale changed
  6407. * @return {Boolean}
  6408. **/
  6409. this.isNewInit = function (videoTrackIds, timescales) {
  6410. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  6411. return false;
  6412. }
  6413. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  6414. };
  6415. /**
  6416. * Parses out SEI captions and interacts with underlying
  6417. * CaptionStream to return dispatched captions
  6418. *
  6419. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  6420. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  6421. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  6422. * @see parseEmbeddedCaptions
  6423. * @see m2ts/caption-stream.js
  6424. **/
  6425. this.parse = function (segment, videoTrackIds, timescales) {
  6426. var parsedData;
  6427. if (!this.isInitialized()) {
  6428. return null; // This is not likely to be a video segment
  6429. } else if (!videoTrackIds || !timescales) {
  6430. return null;
  6431. } else if (this.isNewInit(videoTrackIds, timescales)) {
  6432. // Use the first video track only as there is no
  6433. // mechanism to switch to other video tracks
  6434. trackId = videoTrackIds[0];
  6435. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  6436. // data until we have one.
  6437. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  6438. } else if (trackId === null || !timescale) {
  6439. segmentCache.push(segment);
  6440. return null;
  6441. } // Now that a timescale and trackId is set, parse cached segments
  6442. while (segmentCache.length > 0) {
  6443. var cachedSegment = segmentCache.shift();
  6444. this.parse(cachedSegment, videoTrackIds, timescales);
  6445. }
  6446. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  6447. if (parsedData && parsedData.logs) {
  6448. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  6449. }
  6450. if (parsedData === null || !parsedData.seiNals) {
  6451. if (parsedCaptions.logs.length) {
  6452. return {
  6453. logs: parsedCaptions.logs,
  6454. captions: [],
  6455. captionStreams: []
  6456. };
  6457. }
  6458. return null;
  6459. }
  6460. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  6461. this.flushStream();
  6462. return parsedCaptions;
  6463. };
  6464. /**
  6465. * Pushes SEI NALUs onto CaptionStream
  6466. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  6467. * Assumes that `parseCaptionNals` has been called first
  6468. * @see m2ts/caption-stream.js
  6469. **/
  6470. this.pushNals = function (nals) {
  6471. if (!this.isInitialized() || !nals || nals.length === 0) {
  6472. return null;
  6473. }
  6474. nals.forEach(function (nal) {
  6475. captionStream.push(nal);
  6476. });
  6477. };
  6478. /**
  6479. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  6480. * @see m2ts/caption-stream.js
  6481. **/
  6482. this.flushStream = function () {
  6483. if (!this.isInitialized()) {
  6484. return null;
  6485. }
  6486. if (!parsingPartial) {
  6487. captionStream.flush();
  6488. } else {
  6489. captionStream.partialFlush();
  6490. }
  6491. };
  6492. /**
  6493. * Reset caption buckets for new data
  6494. **/
  6495. this.clearParsedCaptions = function () {
  6496. parsedCaptions.captions = [];
  6497. parsedCaptions.captionStreams = {};
  6498. parsedCaptions.logs = [];
  6499. };
  6500. /**
  6501. * Resets underlying CaptionStream
  6502. * @see m2ts/caption-stream.js
  6503. **/
  6504. this.resetCaptionStream = function () {
  6505. if (!this.isInitialized()) {
  6506. return null;
  6507. }
  6508. captionStream.reset();
  6509. };
  6510. /**
  6511. * Convenience method to clear all captions flushed from the
  6512. * CaptionStream and still being parsed
  6513. * @see m2ts/caption-stream.js
  6514. **/
  6515. this.clearAllCaptions = function () {
  6516. this.clearParsedCaptions();
  6517. this.resetCaptionStream();
  6518. };
  6519. /**
  6520. * Reset caption parser
  6521. **/
  6522. this.reset = function () {
  6523. segmentCache = [];
  6524. trackId = null;
  6525. timescale = null;
  6526. if (!parsedCaptions) {
  6527. parsedCaptions = {
  6528. captions: [],
  6529. // CC1, CC2, CC3, CC4
  6530. captionStreams: {},
  6531. logs: []
  6532. };
  6533. } else {
  6534. this.clearParsedCaptions();
  6535. }
  6536. this.resetCaptionStream();
  6537. };
  6538. this.reset();
  6539. };
  6540. var captionParser = CaptionParser;
  6541. /**
  6542. * mux.js
  6543. *
  6544. * Copyright (c) Brightcove
  6545. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6546. */
  6547. var mp4 = {
  6548. generator: mp4Generator,
  6549. probe: probe,
  6550. Transmuxer: transmuxer.Transmuxer,
  6551. AudioSegmentStream: transmuxer.AudioSegmentStream,
  6552. VideoSegmentStream: transmuxer.VideoSegmentStream,
  6553. CaptionParser: captionParser
  6554. };
  6555. return mp4;
  6556. })));