mkvparser.cc 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049
  1. // Copyright (c) 2012 The WebM project authors. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. #include "mkvparser/mkvparser.h"
  9. #if defined(_MSC_VER) && _MSC_VER < 1800
  10. #include <float.h> // _isnan() / _finite()
  11. #define MSC_COMPAT
  12. #endif
  13. #include <cassert>
  14. #include <cfloat>
  15. #include <climits>
  16. #include <cmath>
  17. #include <cstring>
  18. #include <memory>
  19. #include <new>
  20. #include "common/webmids.h"
  21. namespace mkvparser {
  22. const long long kStringElementSizeLimit = 20 * 1000 * 1000;
  23. const float MasteringMetadata::kValueNotPresent = FLT_MAX;
  24. const long long Colour::kValueNotPresent = LLONG_MAX;
  25. const float Projection::kValueNotPresent = FLT_MAX;
  26. #ifdef MSC_COMPAT
  27. inline bool isnan(double val) { return !!_isnan(val); }
  28. inline bool isinf(double val) { return !_finite(val); }
  29. #else
  30. inline bool isnan(double val) { return std::isnan(val); }
  31. inline bool isinf(double val) { return std::isinf(val); }
  32. #endif // MSC_COMPAT
  33. IMkvReader::~IMkvReader() {}
  34. template <typename Type>
  35. Type* SafeArrayAlloc(unsigned long long num_elements,
  36. unsigned long long element_size) {
  37. if (num_elements == 0 || element_size == 0)
  38. return NULL;
  39. const size_t kMaxAllocSize = 0x80000000; // 2GiB
  40. const unsigned long long num_bytes = num_elements * element_size;
  41. if (element_size > (kMaxAllocSize / num_elements))
  42. return NULL;
  43. if (num_bytes != static_cast<size_t>(num_bytes))
  44. return NULL;
  45. return new (std::nothrow) Type[static_cast<size_t>(num_bytes)];
  46. }
  47. void GetVersion(int& major, int& minor, int& build, int& revision) {
  48. major = 1;
  49. minor = 0;
  50. build = 0;
  51. revision = 30;
  52. }
  53. long long ReadUInt(IMkvReader* pReader, long long pos, long& len) {
  54. if (!pReader || pos < 0)
  55. return E_FILE_FORMAT_INVALID;
  56. len = 1;
  57. unsigned char b;
  58. int status = pReader->Read(pos, 1, &b);
  59. if (status < 0) // error or underflow
  60. return status;
  61. if (status > 0) // interpreted as "underflow"
  62. return E_BUFFER_NOT_FULL;
  63. if (b == 0) // we can't handle u-int values larger than 8 bytes
  64. return E_FILE_FORMAT_INVALID;
  65. unsigned char m = 0x80;
  66. while (!(b & m)) {
  67. m >>= 1;
  68. ++len;
  69. }
  70. long long result = b & (~m);
  71. ++pos;
  72. for (int i = 1; i < len; ++i) {
  73. status = pReader->Read(pos, 1, &b);
  74. if (status < 0) {
  75. len = 1;
  76. return status;
  77. }
  78. if (status > 0) {
  79. len = 1;
  80. return E_BUFFER_NOT_FULL;
  81. }
  82. result <<= 8;
  83. result |= b;
  84. ++pos;
  85. }
  86. return result;
  87. }
  88. // Reads an EBML ID and returns it.
  89. // An ID must at least 1 byte long, cannot exceed 4, and its value must be
  90. // greater than 0.
  91. // See known EBML values and EBMLMaxIDLength:
  92. // http://www.matroska.org/technical/specs/index.html
  93. // Returns the ID, or a value less than 0 to report an error while reading the
  94. // ID.
  95. long long ReadID(IMkvReader* pReader, long long pos, long& len) {
  96. if (pReader == NULL || pos < 0)
  97. return E_FILE_FORMAT_INVALID;
  98. // Read the first byte. The length in bytes of the ID is determined by
  99. // finding the first set bit in the first byte of the ID.
  100. unsigned char temp_byte = 0;
  101. int read_status = pReader->Read(pos, 1, &temp_byte);
  102. if (read_status < 0)
  103. return E_FILE_FORMAT_INVALID;
  104. else if (read_status > 0) // No data to read.
  105. return E_BUFFER_NOT_FULL;
  106. if (temp_byte == 0) // ID length > 8 bytes; invalid file.
  107. return E_FILE_FORMAT_INVALID;
  108. int bit_pos = 0;
  109. const int kMaxIdLengthInBytes = 4;
  110. const int kCheckByte = 0x80;
  111. // Find the first bit that's set.
  112. bool found_bit = false;
  113. for (; bit_pos < kMaxIdLengthInBytes; ++bit_pos) {
  114. if ((kCheckByte >> bit_pos) & temp_byte) {
  115. found_bit = true;
  116. break;
  117. }
  118. }
  119. if (!found_bit) {
  120. // The value is too large to be a valid ID.
  121. return E_FILE_FORMAT_INVALID;
  122. }
  123. // Read the remaining bytes of the ID (if any).
  124. const int id_length = bit_pos + 1;
  125. long long ebml_id = temp_byte;
  126. for (int i = 1; i < id_length; ++i) {
  127. ebml_id <<= 8;
  128. read_status = pReader->Read(pos + i, 1, &temp_byte);
  129. if (read_status < 0)
  130. return E_FILE_FORMAT_INVALID;
  131. else if (read_status > 0)
  132. return E_BUFFER_NOT_FULL;
  133. ebml_id |= temp_byte;
  134. }
  135. len = id_length;
  136. return ebml_id;
  137. }
  138. long long GetUIntLength(IMkvReader* pReader, long long pos, long& len) {
  139. if (!pReader || pos < 0)
  140. return E_FILE_FORMAT_INVALID;
  141. long long total, available;
  142. int status = pReader->Length(&total, &available);
  143. if (status < 0 || (total >= 0 && available > total))
  144. return E_FILE_FORMAT_INVALID;
  145. len = 1;
  146. if (pos >= available)
  147. return pos; // too few bytes available
  148. unsigned char b;
  149. status = pReader->Read(pos, 1, &b);
  150. if (status != 0)
  151. return status;
  152. if (b == 0) // we can't handle u-int values larger than 8 bytes
  153. return E_FILE_FORMAT_INVALID;
  154. unsigned char m = 0x80;
  155. while (!(b & m)) {
  156. m >>= 1;
  157. ++len;
  158. }
  159. return 0; // success
  160. }
  161. // TODO(vigneshv): This function assumes that unsigned values never have their
  162. // high bit set.
  163. long long UnserializeUInt(IMkvReader* pReader, long long pos, long long size) {
  164. if (!pReader || pos < 0 || (size <= 0) || (size > 8))
  165. return E_FILE_FORMAT_INVALID;
  166. long long result = 0;
  167. for (long long i = 0; i < size; ++i) {
  168. unsigned char b;
  169. const long status = pReader->Read(pos, 1, &b);
  170. if (status < 0)
  171. return status;
  172. result <<= 8;
  173. result |= b;
  174. ++pos;
  175. }
  176. return result;
  177. }
  178. long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_,
  179. double& result) {
  180. if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8)))
  181. return E_FILE_FORMAT_INVALID;
  182. const long size = static_cast<long>(size_);
  183. unsigned char buf[8];
  184. const int status = pReader->Read(pos, size, buf);
  185. if (status < 0) // error
  186. return status;
  187. if (size == 4) {
  188. union {
  189. float f;
  190. unsigned long ff;
  191. };
  192. ff = 0;
  193. for (int i = 0;;) {
  194. ff |= buf[i];
  195. if (++i >= 4)
  196. break;
  197. ff <<= 8;
  198. }
  199. result = f;
  200. } else {
  201. union {
  202. double d;
  203. unsigned long long dd;
  204. };
  205. dd = 0;
  206. for (int i = 0;;) {
  207. dd |= buf[i];
  208. if (++i >= 8)
  209. break;
  210. dd <<= 8;
  211. }
  212. result = d;
  213. }
  214. if (mkvparser::isinf(result) || mkvparser::isnan(result))
  215. return E_FILE_FORMAT_INVALID;
  216. return 0;
  217. }
  218. long UnserializeInt(IMkvReader* pReader, long long pos, long long size,
  219. long long& result_ref) {
  220. if (!pReader || pos < 0 || size < 1 || size > 8)
  221. return E_FILE_FORMAT_INVALID;
  222. signed char first_byte = 0;
  223. const long status = pReader->Read(pos, 1, (unsigned char*)&first_byte);
  224. if (status < 0)
  225. return status;
  226. unsigned long long result = first_byte;
  227. ++pos;
  228. for (long i = 1; i < size; ++i) {
  229. unsigned char b;
  230. const long status = pReader->Read(pos, 1, &b);
  231. if (status < 0)
  232. return status;
  233. result <<= 8;
  234. result |= b;
  235. ++pos;
  236. }
  237. result_ref = static_cast<long long>(result);
  238. return 0;
  239. }
  240. long UnserializeString(IMkvReader* pReader, long long pos, long long size,
  241. char*& str) {
  242. delete[] str;
  243. str = NULL;
  244. if (size >= LONG_MAX || size < 0 || size > kStringElementSizeLimit)
  245. return E_FILE_FORMAT_INVALID;
  246. // +1 for '\0' terminator
  247. const long required_size = static_cast<long>(size) + 1;
  248. str = SafeArrayAlloc<char>(1, required_size);
  249. if (str == NULL)
  250. return E_FILE_FORMAT_INVALID;
  251. unsigned char* const buf = reinterpret_cast<unsigned char*>(str);
  252. const long status = pReader->Read(pos, static_cast<long>(size), buf);
  253. if (status) {
  254. delete[] str;
  255. str = NULL;
  256. return status;
  257. }
  258. str[required_size - 1] = '\0';
  259. return 0;
  260. }
  261. long ParseElementHeader(IMkvReader* pReader, long long& pos, long long stop,
  262. long long& id, long long& size) {
  263. if (stop >= 0 && pos >= stop)
  264. return E_FILE_FORMAT_INVALID;
  265. long len;
  266. id = ReadID(pReader, pos, len);
  267. if (id < 0)
  268. return E_FILE_FORMAT_INVALID;
  269. pos += len; // consume id
  270. if (stop >= 0 && pos >= stop)
  271. return E_FILE_FORMAT_INVALID;
  272. size = ReadUInt(pReader, pos, len);
  273. if (size < 0 || len < 1 || len > 8) {
  274. // Invalid: Negative payload size, negative or 0 length integer, or integer
  275. // larger than 64 bits (libwebm cannot handle them).
  276. return E_FILE_FORMAT_INVALID;
  277. }
  278. // Avoid rolling over pos when very close to LLONG_MAX.
  279. const unsigned long long rollover_check =
  280. static_cast<unsigned long long>(pos) + len;
  281. if (rollover_check > LLONG_MAX)
  282. return E_FILE_FORMAT_INVALID;
  283. pos += len; // consume length of size
  284. // pos now designates payload
  285. if (stop >= 0 && pos > stop)
  286. return E_FILE_FORMAT_INVALID;
  287. return 0; // success
  288. }
  289. bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id,
  290. long long& val) {
  291. if (!pReader || pos < 0)
  292. return false;
  293. long long total = 0;
  294. long long available = 0;
  295. const long status = pReader->Length(&total, &available);
  296. if (status < 0 || (total >= 0 && available > total))
  297. return false;
  298. long len = 0;
  299. const long long id = ReadID(pReader, pos, len);
  300. if (id < 0 || (available - pos) > len)
  301. return false;
  302. if (static_cast<unsigned long>(id) != expected_id)
  303. return false;
  304. pos += len; // consume id
  305. const long long size = ReadUInt(pReader, pos, len);
  306. if (size < 0 || size > 8 || len < 1 || len > 8 || (available - pos) > len)
  307. return false;
  308. pos += len; // consume length of size of payload
  309. val = UnserializeUInt(pReader, pos, size);
  310. if (val < 0)
  311. return false;
  312. pos += size; // consume size of payload
  313. return true;
  314. }
  315. bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id,
  316. unsigned char*& buf, size_t& buflen) {
  317. if (!pReader || pos < 0)
  318. return false;
  319. long long total = 0;
  320. long long available = 0;
  321. long status = pReader->Length(&total, &available);
  322. if (status < 0 || (total >= 0 && available > total))
  323. return false;
  324. long len = 0;
  325. const long long id = ReadID(pReader, pos, len);
  326. if (id < 0 || (available - pos) > len)
  327. return false;
  328. if (static_cast<unsigned long>(id) != expected_id)
  329. return false;
  330. pos += len; // consume id
  331. const long long size = ReadUInt(pReader, pos, len);
  332. if (size < 0 || len <= 0 || len > 8 || (available - pos) > len)
  333. return false;
  334. unsigned long long rollover_check =
  335. static_cast<unsigned long long>(pos) + len;
  336. if (rollover_check > LLONG_MAX)
  337. return false;
  338. pos += len; // consume length of size of payload
  339. rollover_check = static_cast<unsigned long long>(pos) + size;
  340. if (rollover_check > LLONG_MAX)
  341. return false;
  342. if ((pos + size) > available)
  343. return false;
  344. if (size >= LONG_MAX)
  345. return false;
  346. const long buflen_ = static_cast<long>(size);
  347. buf = SafeArrayAlloc<unsigned char>(1, buflen_);
  348. if (!buf)
  349. return false;
  350. status = pReader->Read(pos, buflen_, buf);
  351. if (status != 0)
  352. return false;
  353. buflen = buflen_;
  354. pos += size; // consume size of payload
  355. return true;
  356. }
  357. EBMLHeader::EBMLHeader() : m_docType(NULL) { Init(); }
  358. EBMLHeader::~EBMLHeader() { delete[] m_docType; }
  359. void EBMLHeader::Init() {
  360. m_version = 1;
  361. m_readVersion = 1;
  362. m_maxIdLength = 4;
  363. m_maxSizeLength = 8;
  364. if (m_docType) {
  365. delete[] m_docType;
  366. m_docType = NULL;
  367. }
  368. m_docTypeVersion = 1;
  369. m_docTypeReadVersion = 1;
  370. }
  371. long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) {
  372. if (!pReader)
  373. return E_FILE_FORMAT_INVALID;
  374. long long total, available;
  375. long status = pReader->Length(&total, &available);
  376. if (status < 0) // error
  377. return status;
  378. pos = 0;
  379. // Scan until we find what looks like the first byte of the EBML header.
  380. const long long kMaxScanBytes = (available >= 1024) ? 1024 : available;
  381. const unsigned char kEbmlByte0 = 0x1A;
  382. unsigned char scan_byte = 0;
  383. while (pos < kMaxScanBytes) {
  384. status = pReader->Read(pos, 1, &scan_byte);
  385. if (status < 0) // error
  386. return status;
  387. else if (status > 0)
  388. return E_BUFFER_NOT_FULL;
  389. if (scan_byte == kEbmlByte0)
  390. break;
  391. ++pos;
  392. }
  393. long len = 0;
  394. const long long ebml_id = ReadID(pReader, pos, len);
  395. if (ebml_id == E_BUFFER_NOT_FULL)
  396. return E_BUFFER_NOT_FULL;
  397. if (len != 4 || ebml_id != libwebm::kMkvEBML)
  398. return E_FILE_FORMAT_INVALID;
  399. // Move read pos forward to the EBML header size field.
  400. pos += 4;
  401. // Read length of size field.
  402. long long result = GetUIntLength(pReader, pos, len);
  403. if (result < 0) // error
  404. return E_FILE_FORMAT_INVALID;
  405. else if (result > 0) // need more data
  406. return E_BUFFER_NOT_FULL;
  407. if (len < 1 || len > 8)
  408. return E_FILE_FORMAT_INVALID;
  409. if ((total >= 0) && ((total - pos) < len))
  410. return E_FILE_FORMAT_INVALID;
  411. if ((available - pos) < len)
  412. return pos + len; // try again later
  413. // Read the EBML header size.
  414. result = ReadUInt(pReader, pos, len);
  415. if (result < 0) // error
  416. return result;
  417. pos += len; // consume size field
  418. // pos now designates start of payload
  419. if ((total >= 0) && ((total - pos) < result))
  420. return E_FILE_FORMAT_INVALID;
  421. if ((available - pos) < result)
  422. return pos + result;
  423. const long long end = pos + result;
  424. Init();
  425. while (pos < end) {
  426. long long id, size;
  427. status = ParseElementHeader(pReader, pos, end, id, size);
  428. if (status < 0) // error
  429. return status;
  430. if (size == 0)
  431. return E_FILE_FORMAT_INVALID;
  432. if (id == libwebm::kMkvEBMLVersion) {
  433. m_version = UnserializeUInt(pReader, pos, size);
  434. if (m_version <= 0)
  435. return E_FILE_FORMAT_INVALID;
  436. } else if (id == libwebm::kMkvEBMLReadVersion) {
  437. m_readVersion = UnserializeUInt(pReader, pos, size);
  438. if (m_readVersion <= 0)
  439. return E_FILE_FORMAT_INVALID;
  440. } else if (id == libwebm::kMkvEBMLMaxIDLength) {
  441. m_maxIdLength = UnserializeUInt(pReader, pos, size);
  442. if (m_maxIdLength <= 0)
  443. return E_FILE_FORMAT_INVALID;
  444. } else if (id == libwebm::kMkvEBMLMaxSizeLength) {
  445. m_maxSizeLength = UnserializeUInt(pReader, pos, size);
  446. if (m_maxSizeLength <= 0)
  447. return E_FILE_FORMAT_INVALID;
  448. } else if (id == libwebm::kMkvDocType) {
  449. if (m_docType)
  450. return E_FILE_FORMAT_INVALID;
  451. status = UnserializeString(pReader, pos, size, m_docType);
  452. if (status) // error
  453. return status;
  454. } else if (id == libwebm::kMkvDocTypeVersion) {
  455. m_docTypeVersion = UnserializeUInt(pReader, pos, size);
  456. if (m_docTypeVersion <= 0)
  457. return E_FILE_FORMAT_INVALID;
  458. } else if (id == libwebm::kMkvDocTypeReadVersion) {
  459. m_docTypeReadVersion = UnserializeUInt(pReader, pos, size);
  460. if (m_docTypeReadVersion <= 0)
  461. return E_FILE_FORMAT_INVALID;
  462. }
  463. pos += size;
  464. }
  465. if (pos != end)
  466. return E_FILE_FORMAT_INVALID;
  467. // Make sure DocType, DocTypeReadVersion, and DocTypeVersion are valid.
  468. if (m_docType == NULL || m_docTypeReadVersion <= 0 || m_docTypeVersion <= 0)
  469. return E_FILE_FORMAT_INVALID;
  470. // Make sure EBMLMaxIDLength and EBMLMaxSizeLength are valid.
  471. if (m_maxIdLength <= 0 || m_maxIdLength > 4 || m_maxSizeLength <= 0 ||
  472. m_maxSizeLength > 8)
  473. return E_FILE_FORMAT_INVALID;
  474. return 0;
  475. }
  476. Segment::Segment(IMkvReader* pReader, long long elem_start,
  477. // long long elem_size,
  478. long long start, long long size)
  479. : m_pReader(pReader),
  480. m_element_start(elem_start),
  481. // m_element_size(elem_size),
  482. m_start(start),
  483. m_size(size),
  484. m_pos(start),
  485. m_pUnknownSize(0),
  486. m_pSeekHead(NULL),
  487. m_pInfo(NULL),
  488. m_pTracks(NULL),
  489. m_pCues(NULL),
  490. m_pChapters(NULL),
  491. m_pTags(NULL),
  492. m_clusters(NULL),
  493. m_clusterCount(0),
  494. m_clusterPreloadCount(0),
  495. m_clusterSize(0) {}
  496. Segment::~Segment() {
  497. const long count = m_clusterCount + m_clusterPreloadCount;
  498. Cluster** i = m_clusters;
  499. Cluster** j = m_clusters + count;
  500. while (i != j) {
  501. Cluster* const p = *i++;
  502. delete p;
  503. }
  504. delete[] m_clusters;
  505. delete m_pTracks;
  506. delete m_pInfo;
  507. delete m_pCues;
  508. delete m_pChapters;
  509. delete m_pTags;
  510. delete m_pSeekHead;
  511. }
  512. long long Segment::CreateInstance(IMkvReader* pReader, long long pos,
  513. Segment*& pSegment) {
  514. if (pReader == NULL || pos < 0)
  515. return E_PARSE_FAILED;
  516. pSegment = NULL;
  517. long long total, available;
  518. const long status = pReader->Length(&total, &available);
  519. if (status < 0) // error
  520. return status;
  521. if (available < 0)
  522. return -1;
  523. if ((total >= 0) && (available > total))
  524. return -1;
  525. // I would assume that in practice this loop would execute
  526. // exactly once, but we allow for other elements (e.g. Void)
  527. // to immediately follow the EBML header. This is fine for
  528. // the source filter case (since the entire file is available),
  529. // but in the splitter case over a network we should probably
  530. // just give up early. We could for example decide only to
  531. // execute this loop a maximum of, say, 10 times.
  532. // TODO:
  533. // There is an implied "give up early" by only parsing up
  534. // to the available limit. We do do that, but only if the
  535. // total file size is unknown. We could decide to always
  536. // use what's available as our limit (irrespective of whether
  537. // we happen to know the total file length). This would have
  538. // as its sense "parse this much of the file before giving up",
  539. // which a slightly different sense from "try to parse up to
  540. // 10 EMBL elements before giving up".
  541. for (;;) {
  542. if ((total >= 0) && (pos >= total))
  543. return E_FILE_FORMAT_INVALID;
  544. // Read ID
  545. long len;
  546. long long result = GetUIntLength(pReader, pos, len);
  547. if (result) // error, or too few available bytes
  548. return result;
  549. if ((total >= 0) && ((pos + len) > total))
  550. return E_FILE_FORMAT_INVALID;
  551. if ((pos + len) > available)
  552. return pos + len;
  553. const long long idpos = pos;
  554. const long long id = ReadID(pReader, pos, len);
  555. if (id < 0)
  556. return E_FILE_FORMAT_INVALID;
  557. pos += len; // consume ID
  558. // Read Size
  559. result = GetUIntLength(pReader, pos, len);
  560. if (result) // error, or too few available bytes
  561. return result;
  562. if ((total >= 0) && ((pos + len) > total))
  563. return E_FILE_FORMAT_INVALID;
  564. if ((pos + len) > available)
  565. return pos + len;
  566. long long size = ReadUInt(pReader, pos, len);
  567. if (size < 0) // error
  568. return size;
  569. pos += len; // consume length of size of element
  570. // Pos now points to start of payload
  571. // Handle "unknown size" for live streaming of webm files.
  572. const long long unknown_size = (1LL << (7 * len)) - 1;
  573. if (id == libwebm::kMkvSegment) {
  574. if (size == unknown_size)
  575. size = -1;
  576. else if (total < 0)
  577. size = -1;
  578. else if ((pos + size) > total)
  579. size = -1;
  580. pSegment = new (std::nothrow) Segment(pReader, idpos, pos, size);
  581. if (pSegment == NULL)
  582. return E_PARSE_FAILED;
  583. return 0; // success
  584. }
  585. if (size == unknown_size)
  586. return E_FILE_FORMAT_INVALID;
  587. if ((total >= 0) && ((pos + size) > total))
  588. return E_FILE_FORMAT_INVALID;
  589. if ((pos + size) > available)
  590. return pos + size;
  591. pos += size; // consume payload
  592. }
  593. }
  594. long long Segment::ParseHeaders() {
  595. // Outermost (level 0) segment object has been constructed,
  596. // and pos designates start of payload. We need to find the
  597. // inner (level 1) elements.
  598. long long total, available;
  599. const int status = m_pReader->Length(&total, &available);
  600. if (status < 0) // error
  601. return status;
  602. if (total > 0 && available > total)
  603. return E_FILE_FORMAT_INVALID;
  604. const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
  605. if ((segment_stop >= 0 && total >= 0 && segment_stop > total) ||
  606. (segment_stop >= 0 && m_pos > segment_stop)) {
  607. return E_FILE_FORMAT_INVALID;
  608. }
  609. for (;;) {
  610. if ((total >= 0) && (m_pos >= total))
  611. break;
  612. if ((segment_stop >= 0) && (m_pos >= segment_stop))
  613. break;
  614. long long pos = m_pos;
  615. const long long element_start = pos;
  616. // Avoid rolling over pos when very close to LLONG_MAX.
  617. unsigned long long rollover_check = pos + 1ULL;
  618. if (rollover_check > LLONG_MAX)
  619. return E_FILE_FORMAT_INVALID;
  620. if ((pos + 1) > available)
  621. return (pos + 1);
  622. long len;
  623. long long result = GetUIntLength(m_pReader, pos, len);
  624. if (result < 0) // error
  625. return result;
  626. if (result > 0) {
  627. // MkvReader doesn't have enough data to satisfy this read attempt.
  628. return (pos + 1);
  629. }
  630. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  631. return E_FILE_FORMAT_INVALID;
  632. if ((pos + len) > available)
  633. return pos + len;
  634. const long long idpos = pos;
  635. const long long id = ReadID(m_pReader, idpos, len);
  636. if (id < 0)
  637. return E_FILE_FORMAT_INVALID;
  638. if (id == libwebm::kMkvCluster)
  639. break;
  640. pos += len; // consume ID
  641. if ((pos + 1) > available)
  642. return (pos + 1);
  643. // Read Size
  644. result = GetUIntLength(m_pReader, pos, len);
  645. if (result < 0) // error
  646. return result;
  647. if (result > 0) {
  648. // MkvReader doesn't have enough data to satisfy this read attempt.
  649. return (pos + 1);
  650. }
  651. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  652. return E_FILE_FORMAT_INVALID;
  653. if ((pos + len) > available)
  654. return pos + len;
  655. const long long size = ReadUInt(m_pReader, pos, len);
  656. if (size < 0 || len < 1 || len > 8) {
  657. // TODO(tomfinegan): ReadUInt should return an error when len is < 1 or
  658. // len > 8 is true instead of checking this _everywhere_.
  659. return size;
  660. }
  661. pos += len; // consume length of size of element
  662. // Avoid rolling over pos when very close to LLONG_MAX.
  663. rollover_check = static_cast<unsigned long long>(pos) + size;
  664. if (rollover_check > LLONG_MAX)
  665. return E_FILE_FORMAT_INVALID;
  666. const long long element_size = size + pos - element_start;
  667. // Pos now points to start of payload
  668. if ((segment_stop >= 0) && ((pos + size) > segment_stop))
  669. return E_FILE_FORMAT_INVALID;
  670. // We read EBML elements either in total or nothing at all.
  671. if ((pos + size) > available)
  672. return pos + size;
  673. if (id == libwebm::kMkvInfo) {
  674. if (m_pInfo)
  675. return E_FILE_FORMAT_INVALID;
  676. m_pInfo = new (std::nothrow)
  677. SegmentInfo(this, pos, size, element_start, element_size);
  678. if (m_pInfo == NULL)
  679. return -1;
  680. const long status = m_pInfo->Parse();
  681. if (status)
  682. return status;
  683. } else if (id == libwebm::kMkvTracks) {
  684. if (m_pTracks)
  685. return E_FILE_FORMAT_INVALID;
  686. m_pTracks = new (std::nothrow)
  687. Tracks(this, pos, size, element_start, element_size);
  688. if (m_pTracks == NULL)
  689. return -1;
  690. const long status = m_pTracks->Parse();
  691. if (status)
  692. return status;
  693. } else if (id == libwebm::kMkvCues) {
  694. if (m_pCues == NULL) {
  695. m_pCues = new (std::nothrow)
  696. Cues(this, pos, size, element_start, element_size);
  697. if (m_pCues == NULL)
  698. return -1;
  699. }
  700. } else if (id == libwebm::kMkvSeekHead) {
  701. if (m_pSeekHead == NULL) {
  702. m_pSeekHead = new (std::nothrow)
  703. SeekHead(this, pos, size, element_start, element_size);
  704. if (m_pSeekHead == NULL)
  705. return -1;
  706. const long status = m_pSeekHead->Parse();
  707. if (status)
  708. return status;
  709. }
  710. } else if (id == libwebm::kMkvChapters) {
  711. if (m_pChapters == NULL) {
  712. m_pChapters = new (std::nothrow)
  713. Chapters(this, pos, size, element_start, element_size);
  714. if (m_pChapters == NULL)
  715. return -1;
  716. const long status = m_pChapters->Parse();
  717. if (status)
  718. return status;
  719. }
  720. } else if (id == libwebm::kMkvTags) {
  721. if (m_pTags == NULL) {
  722. m_pTags = new (std::nothrow)
  723. Tags(this, pos, size, element_start, element_size);
  724. if (m_pTags == NULL)
  725. return -1;
  726. const long status = m_pTags->Parse();
  727. if (status)
  728. return status;
  729. }
  730. }
  731. m_pos = pos + size; // consume payload
  732. }
  733. if (segment_stop >= 0 && m_pos > segment_stop)
  734. return E_FILE_FORMAT_INVALID;
  735. if (m_pInfo == NULL) // TODO: liberalize this behavior
  736. return E_FILE_FORMAT_INVALID;
  737. if (m_pTracks == NULL)
  738. return E_FILE_FORMAT_INVALID;
  739. return 0; // success
  740. }
  741. long Segment::LoadCluster(long long& pos, long& len) {
  742. for (;;) {
  743. const long result = DoLoadCluster(pos, len);
  744. if (result <= 1)
  745. return result;
  746. }
  747. }
  748. long Segment::DoLoadCluster(long long& pos, long& len) {
  749. if (m_pos < 0)
  750. return DoLoadClusterUnknownSize(pos, len);
  751. long long total, avail;
  752. long status = m_pReader->Length(&total, &avail);
  753. if (status < 0) // error
  754. return status;
  755. if (total >= 0 && avail > total)
  756. return E_FILE_FORMAT_INVALID;
  757. const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
  758. long long cluster_off = -1; // offset relative to start of segment
  759. long long cluster_size = -1; // size of cluster payload
  760. for (;;) {
  761. if ((total >= 0) && (m_pos >= total))
  762. return 1; // no more clusters
  763. if ((segment_stop >= 0) && (m_pos >= segment_stop))
  764. return 1; // no more clusters
  765. pos = m_pos;
  766. // Read ID
  767. if ((pos + 1) > avail) {
  768. len = 1;
  769. return E_BUFFER_NOT_FULL;
  770. }
  771. long long result = GetUIntLength(m_pReader, pos, len);
  772. if (result < 0) // error
  773. return static_cast<long>(result);
  774. if (result > 0)
  775. return E_BUFFER_NOT_FULL;
  776. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  777. return E_FILE_FORMAT_INVALID;
  778. if ((pos + len) > avail)
  779. return E_BUFFER_NOT_FULL;
  780. const long long idpos = pos;
  781. const long long id = ReadID(m_pReader, idpos, len);
  782. if (id < 0)
  783. return E_FILE_FORMAT_INVALID;
  784. pos += len; // consume ID
  785. // Read Size
  786. if ((pos + 1) > avail) {
  787. len = 1;
  788. return E_BUFFER_NOT_FULL;
  789. }
  790. result = GetUIntLength(m_pReader, pos, len);
  791. if (result < 0) // error
  792. return static_cast<long>(result);
  793. if (result > 0)
  794. return E_BUFFER_NOT_FULL;
  795. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  796. return E_FILE_FORMAT_INVALID;
  797. if ((pos + len) > avail)
  798. return E_BUFFER_NOT_FULL;
  799. const long long size = ReadUInt(m_pReader, pos, len);
  800. if (size < 0) // error
  801. return static_cast<long>(size);
  802. pos += len; // consume length of size of element
  803. // pos now points to start of payload
  804. if (size == 0) {
  805. // Missing element payload: move on.
  806. m_pos = pos;
  807. continue;
  808. }
  809. const long long unknown_size = (1LL << (7 * len)) - 1;
  810. if ((segment_stop >= 0) && (size != unknown_size) &&
  811. ((pos + size) > segment_stop)) {
  812. return E_FILE_FORMAT_INVALID;
  813. }
  814. if (id == libwebm::kMkvCues) {
  815. if (size == unknown_size) {
  816. // Cues element of unknown size: Not supported.
  817. return E_FILE_FORMAT_INVALID;
  818. }
  819. if (m_pCues == NULL) {
  820. const long long element_size = (pos - idpos) + size;
  821. m_pCues = new (std::nothrow) Cues(this, pos, size, idpos, element_size);
  822. if (m_pCues == NULL)
  823. return -1;
  824. }
  825. m_pos = pos + size; // consume payload
  826. continue;
  827. }
  828. if (id != libwebm::kMkvCluster) {
  829. // Besides the Segment, Libwebm allows only cluster elements of unknown
  830. // size. Fail the parse upon encountering a non-cluster element reporting
  831. // unknown size.
  832. if (size == unknown_size)
  833. return E_FILE_FORMAT_INVALID;
  834. m_pos = pos + size; // consume payload
  835. continue;
  836. }
  837. // We have a cluster.
  838. cluster_off = idpos - m_start; // relative pos
  839. if (size != unknown_size)
  840. cluster_size = size;
  841. break;
  842. }
  843. if (cluster_off < 0) {
  844. // No cluster, die.
  845. return E_FILE_FORMAT_INVALID;
  846. }
  847. long long pos_;
  848. long len_;
  849. status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_);
  850. if (status < 0) { // error, or underflow
  851. pos = pos_;
  852. len = len_;
  853. return status;
  854. }
  855. // status == 0 means "no block entries found"
  856. // status > 0 means "found at least one block entry"
  857. // TODO:
  858. // The issue here is that the segment increments its own
  859. // pos ptr past the most recent cluster parsed, and then
  860. // starts from there to parse the next cluster. If we
  861. // don't know the size of the current cluster, then we
  862. // must either parse its payload (as we do below), looking
  863. // for the cluster (or cues) ID to terminate the parse.
  864. // This isn't really what we want: rather, we really need
  865. // a way to create the curr cluster object immediately.
  866. // The pity is that cluster::parse can determine its own
  867. // boundary, and we largely duplicate that same logic here.
  868. //
  869. // Maybe we need to get rid of our look-ahead preloading
  870. // in source::parse???
  871. //
  872. // As we're parsing the blocks in the curr cluster
  873. //(in cluster::parse), we should have some way to signal
  874. // to the segment that we have determined the boundary,
  875. // so it can adjust its own segment::m_pos member.
  876. //
  877. // The problem is that we're asserting in asyncreadinit,
  878. // because we adjust the pos down to the curr seek pos,
  879. // and the resulting adjusted len is > 2GB. I'm suspicious
  880. // that this is even correct, but even if it is, we can't
  881. // be loading that much data in the cache anyway.
  882. const long idx = m_clusterCount;
  883. if (m_clusterPreloadCount > 0) {
  884. if (idx >= m_clusterSize)
  885. return E_FILE_FORMAT_INVALID;
  886. Cluster* const pCluster = m_clusters[idx];
  887. if (pCluster == NULL || pCluster->m_index >= 0)
  888. return E_FILE_FORMAT_INVALID;
  889. const long long off = pCluster->GetPosition();
  890. if (off < 0)
  891. return E_FILE_FORMAT_INVALID;
  892. if (off == cluster_off) { // preloaded already
  893. if (status == 0) // no entries found
  894. return E_FILE_FORMAT_INVALID;
  895. if (cluster_size >= 0)
  896. pos += cluster_size;
  897. else {
  898. const long long element_size = pCluster->GetElementSize();
  899. if (element_size <= 0)
  900. return E_FILE_FORMAT_INVALID; // TODO: handle this case
  901. pos = pCluster->m_element_start + element_size;
  902. }
  903. pCluster->m_index = idx; // move from preloaded to loaded
  904. ++m_clusterCount;
  905. --m_clusterPreloadCount;
  906. m_pos = pos; // consume payload
  907. if (segment_stop >= 0 && m_pos > segment_stop)
  908. return E_FILE_FORMAT_INVALID;
  909. return 0; // success
  910. }
  911. }
  912. if (status == 0) { // no entries found
  913. if (cluster_size >= 0)
  914. pos += cluster_size;
  915. if ((total >= 0) && (pos >= total)) {
  916. m_pos = total;
  917. return 1; // no more clusters
  918. }
  919. if ((segment_stop >= 0) && (pos >= segment_stop)) {
  920. m_pos = segment_stop;
  921. return 1; // no more clusters
  922. }
  923. m_pos = pos;
  924. return 2; // try again
  925. }
  926. // status > 0 means we have an entry
  927. Cluster* const pCluster = Cluster::Create(this, idx, cluster_off);
  928. if (pCluster == NULL)
  929. return -1;
  930. if (!AppendCluster(pCluster)) {
  931. delete pCluster;
  932. return -1;
  933. }
  934. if (cluster_size >= 0) {
  935. pos += cluster_size;
  936. m_pos = pos;
  937. if (segment_stop > 0 && m_pos > segment_stop)
  938. return E_FILE_FORMAT_INVALID;
  939. return 0;
  940. }
  941. m_pUnknownSize = pCluster;
  942. m_pos = -pos;
  943. return 0; // partial success, since we have a new cluster
  944. // status == 0 means "no block entries found"
  945. // pos designates start of payload
  946. // m_pos has NOT been adjusted yet (in case we need to come back here)
  947. }
  948. long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
  949. if (m_pos >= 0 || m_pUnknownSize == NULL)
  950. return E_PARSE_FAILED;
  951. const long status = m_pUnknownSize->Parse(pos, len);
  952. if (status < 0) // error or underflow
  953. return status;
  954. if (status == 0) // parsed a block
  955. return 2; // continue parsing
  956. const long long start = m_pUnknownSize->m_element_start;
  957. const long long size = m_pUnknownSize->GetElementSize();
  958. if (size < 0)
  959. return E_FILE_FORMAT_INVALID;
  960. pos = start + size;
  961. m_pos = pos;
  962. m_pUnknownSize = 0;
  963. return 2; // continue parsing
  964. }
  965. bool Segment::AppendCluster(Cluster* pCluster) {
  966. if (pCluster == NULL || pCluster->m_index < 0)
  967. return false;
  968. const long count = m_clusterCount + m_clusterPreloadCount;
  969. long& size = m_clusterSize;
  970. const long idx = pCluster->m_index;
  971. if (size < count || idx != m_clusterCount)
  972. return false;
  973. if (count >= size) {
  974. const long n = (size <= 0) ? 2048 : 2 * size;
  975. Cluster** const qq = new (std::nothrow) Cluster*[n];
  976. if (qq == NULL)
  977. return false;
  978. Cluster** q = qq;
  979. Cluster** p = m_clusters;
  980. Cluster** const pp = p + count;
  981. while (p != pp)
  982. *q++ = *p++;
  983. delete[] m_clusters;
  984. m_clusters = qq;
  985. size = n;
  986. }
  987. if (m_clusterPreloadCount > 0) {
  988. Cluster** const p = m_clusters + m_clusterCount;
  989. if (*p == NULL || (*p)->m_index >= 0)
  990. return false;
  991. Cluster** q = p + m_clusterPreloadCount;
  992. if (q >= (m_clusters + size))
  993. return false;
  994. for (;;) {
  995. Cluster** const qq = q - 1;
  996. if ((*qq)->m_index >= 0)
  997. return false;
  998. *q = *qq;
  999. q = qq;
  1000. if (q == p)
  1001. break;
  1002. }
  1003. }
  1004. m_clusters[idx] = pCluster;
  1005. ++m_clusterCount;
  1006. return true;
  1007. }
  1008. bool Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
  1009. if (pCluster == NULL || pCluster->m_index >= 0 || idx < m_clusterCount)
  1010. return false;
  1011. const long count = m_clusterCount + m_clusterPreloadCount;
  1012. long& size = m_clusterSize;
  1013. if (size < count)
  1014. return false;
  1015. if (count >= size) {
  1016. const long n = (size <= 0) ? 2048 : 2 * size;
  1017. Cluster** const qq = new (std::nothrow) Cluster*[n];
  1018. if (qq == NULL)
  1019. return false;
  1020. Cluster** q = qq;
  1021. Cluster** p = m_clusters;
  1022. Cluster** const pp = p + count;
  1023. while (p != pp)
  1024. *q++ = *p++;
  1025. delete[] m_clusters;
  1026. m_clusters = qq;
  1027. size = n;
  1028. }
  1029. if (m_clusters == NULL)
  1030. return false;
  1031. Cluster** const p = m_clusters + idx;
  1032. Cluster** q = m_clusters + count;
  1033. if (q < p || q >= (m_clusters + size))
  1034. return false;
  1035. while (q > p) {
  1036. Cluster** const qq = q - 1;
  1037. if ((*qq)->m_index >= 0)
  1038. return false;
  1039. *q = *qq;
  1040. q = qq;
  1041. }
  1042. m_clusters[idx] = pCluster;
  1043. ++m_clusterPreloadCount;
  1044. return true;
  1045. }
  1046. long Segment::Load() {
  1047. if (m_clusters != NULL || m_clusterSize != 0 || m_clusterCount != 0)
  1048. return E_PARSE_FAILED;
  1049. // Outermost (level 0) segment object has been constructed,
  1050. // and pos designates start of payload. We need to find the
  1051. // inner (level 1) elements.
  1052. const long long header_status = ParseHeaders();
  1053. if (header_status < 0) // error
  1054. return static_cast<long>(header_status);
  1055. if (header_status > 0) // underflow
  1056. return E_BUFFER_NOT_FULL;
  1057. if (m_pInfo == NULL || m_pTracks == NULL)
  1058. return E_FILE_FORMAT_INVALID;
  1059. for (;;) {
  1060. const long status = LoadCluster();
  1061. if (status < 0) // error
  1062. return status;
  1063. if (status >= 1) // no more clusters
  1064. return 0;
  1065. }
  1066. }
  1067. SeekHead::Entry::Entry() : id(0), pos(0), element_start(0), element_size(0) {}
  1068. SeekHead::SeekHead(Segment* pSegment, long long start, long long size_,
  1069. long long element_start, long long element_size)
  1070. : m_pSegment(pSegment),
  1071. m_start(start),
  1072. m_size(size_),
  1073. m_element_start(element_start),
  1074. m_element_size(element_size),
  1075. m_entries(0),
  1076. m_entry_count(0),
  1077. m_void_elements(0),
  1078. m_void_element_count(0) {}
  1079. SeekHead::~SeekHead() {
  1080. delete[] m_entries;
  1081. delete[] m_void_elements;
  1082. }
  1083. long SeekHead::Parse() {
  1084. IMkvReader* const pReader = m_pSegment->m_pReader;
  1085. long long pos = m_start;
  1086. const long long stop = m_start + m_size;
  1087. // first count the seek head entries
  1088. int entry_count = 0;
  1089. int void_element_count = 0;
  1090. while (pos < stop) {
  1091. long long id, size;
  1092. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  1093. if (status < 0) // error
  1094. return status;
  1095. if (id == libwebm::kMkvSeek)
  1096. ++entry_count;
  1097. else if (id == libwebm::kMkvVoid)
  1098. ++void_element_count;
  1099. pos += size; // consume payload
  1100. if (pos > stop)
  1101. return E_FILE_FORMAT_INVALID;
  1102. }
  1103. if (pos != stop)
  1104. return E_FILE_FORMAT_INVALID;
  1105. if (entry_count > 0) {
  1106. m_entries = new (std::nothrow) Entry[entry_count];
  1107. if (m_entries == NULL)
  1108. return -1;
  1109. }
  1110. if (void_element_count > 0) {
  1111. m_void_elements = new (std::nothrow) VoidElement[void_element_count];
  1112. if (m_void_elements == NULL)
  1113. return -1;
  1114. }
  1115. // now parse the entries and void elements
  1116. Entry* pEntry = m_entries;
  1117. VoidElement* pVoidElement = m_void_elements;
  1118. pos = m_start;
  1119. while (pos < stop) {
  1120. const long long idpos = pos;
  1121. long long id, size;
  1122. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  1123. if (status < 0) // error
  1124. return status;
  1125. if (id == libwebm::kMkvSeek && entry_count > 0) {
  1126. if (ParseEntry(pReader, pos, size, pEntry)) {
  1127. Entry& e = *pEntry++;
  1128. e.element_start = idpos;
  1129. e.element_size = (pos + size) - idpos;
  1130. }
  1131. } else if (id == libwebm::kMkvVoid && void_element_count > 0) {
  1132. VoidElement& e = *pVoidElement++;
  1133. e.element_start = idpos;
  1134. e.element_size = (pos + size) - idpos;
  1135. }
  1136. pos += size; // consume payload
  1137. if (pos > stop)
  1138. return E_FILE_FORMAT_INVALID;
  1139. }
  1140. if (pos != stop)
  1141. return E_FILE_FORMAT_INVALID;
  1142. ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
  1143. assert(count_ >= 0);
  1144. assert(count_ <= entry_count);
  1145. m_entry_count = static_cast<int>(count_);
  1146. count_ = ptrdiff_t(pVoidElement - m_void_elements);
  1147. assert(count_ >= 0);
  1148. assert(count_ <= void_element_count);
  1149. m_void_element_count = static_cast<int>(count_);
  1150. return 0;
  1151. }
  1152. int SeekHead::GetCount() const { return m_entry_count; }
  1153. const SeekHead::Entry* SeekHead::GetEntry(int idx) const {
  1154. if (idx < 0)
  1155. return 0;
  1156. if (idx >= m_entry_count)
  1157. return 0;
  1158. return m_entries + idx;
  1159. }
  1160. int SeekHead::GetVoidElementCount() const { return m_void_element_count; }
  1161. const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const {
  1162. if (idx < 0)
  1163. return 0;
  1164. if (idx >= m_void_element_count)
  1165. return 0;
  1166. return m_void_elements + idx;
  1167. }
  1168. long Segment::ParseCues(long long off, long long& pos, long& len) {
  1169. if (m_pCues)
  1170. return 0; // success
  1171. if (off < 0)
  1172. return -1;
  1173. long long total, avail;
  1174. const int status = m_pReader->Length(&total, &avail);
  1175. if (status < 0) // error
  1176. return status;
  1177. assert((total < 0) || (avail <= total));
  1178. pos = m_start + off;
  1179. if ((total < 0) || (pos >= total))
  1180. return 1; // don't bother parsing cues
  1181. const long long element_start = pos;
  1182. const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
  1183. if ((pos + 1) > avail) {
  1184. len = 1;
  1185. return E_BUFFER_NOT_FULL;
  1186. }
  1187. long long result = GetUIntLength(m_pReader, pos, len);
  1188. if (result < 0) // error
  1189. return static_cast<long>(result);
  1190. if (result > 0) // underflow (weird)
  1191. {
  1192. len = 1;
  1193. return E_BUFFER_NOT_FULL;
  1194. }
  1195. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  1196. return E_FILE_FORMAT_INVALID;
  1197. if ((pos + len) > avail)
  1198. return E_BUFFER_NOT_FULL;
  1199. const long long idpos = pos;
  1200. const long long id = ReadID(m_pReader, idpos, len);
  1201. if (id != libwebm::kMkvCues)
  1202. return E_FILE_FORMAT_INVALID;
  1203. pos += len; // consume ID
  1204. assert((segment_stop < 0) || (pos <= segment_stop));
  1205. // Read Size
  1206. if ((pos + 1) > avail) {
  1207. len = 1;
  1208. return E_BUFFER_NOT_FULL;
  1209. }
  1210. result = GetUIntLength(m_pReader, pos, len);
  1211. if (result < 0) // error
  1212. return static_cast<long>(result);
  1213. if (result > 0) // underflow (weird)
  1214. {
  1215. len = 1;
  1216. return E_BUFFER_NOT_FULL;
  1217. }
  1218. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  1219. return E_FILE_FORMAT_INVALID;
  1220. if ((pos + len) > avail)
  1221. return E_BUFFER_NOT_FULL;
  1222. const long long size = ReadUInt(m_pReader, pos, len);
  1223. if (size < 0) // error
  1224. return static_cast<long>(size);
  1225. if (size == 0) // weird, although technically not illegal
  1226. return 1; // done
  1227. pos += len; // consume length of size of element
  1228. assert((segment_stop < 0) || (pos <= segment_stop));
  1229. // Pos now points to start of payload
  1230. const long long element_stop = pos + size;
  1231. if ((segment_stop >= 0) && (element_stop > segment_stop))
  1232. return E_FILE_FORMAT_INVALID;
  1233. if ((total >= 0) && (element_stop > total))
  1234. return 1; // don't bother parsing anymore
  1235. len = static_cast<long>(size);
  1236. if (element_stop > avail)
  1237. return E_BUFFER_NOT_FULL;
  1238. const long long element_size = element_stop - element_start;
  1239. m_pCues =
  1240. new (std::nothrow) Cues(this, pos, size, element_start, element_size);
  1241. if (m_pCues == NULL)
  1242. return -1;
  1243. return 0; // success
  1244. }
  1245. bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_,
  1246. Entry* pEntry) {
  1247. if (size_ <= 0)
  1248. return false;
  1249. long long pos = start;
  1250. const long long stop = start + size_;
  1251. long len;
  1252. // parse the container for the level-1 element ID
  1253. const long long seekIdId = ReadID(pReader, pos, len);
  1254. if (seekIdId < 0)
  1255. return false;
  1256. if (seekIdId != libwebm::kMkvSeekID)
  1257. return false;
  1258. if ((pos + len) > stop)
  1259. return false;
  1260. pos += len; // consume SeekID id
  1261. const long long seekIdSize = ReadUInt(pReader, pos, len);
  1262. if (seekIdSize <= 0)
  1263. return false;
  1264. if ((pos + len) > stop)
  1265. return false;
  1266. pos += len; // consume size of field
  1267. if ((pos + seekIdSize) > stop)
  1268. return false;
  1269. pEntry->id = ReadID(pReader, pos, len); // payload
  1270. if (pEntry->id <= 0)
  1271. return false;
  1272. if (len != seekIdSize)
  1273. return false;
  1274. pos += seekIdSize; // consume SeekID payload
  1275. const long long seekPosId = ReadID(pReader, pos, len);
  1276. if (seekPosId != libwebm::kMkvSeekPosition)
  1277. return false;
  1278. if ((pos + len) > stop)
  1279. return false;
  1280. pos += len; // consume id
  1281. const long long seekPosSize = ReadUInt(pReader, pos, len);
  1282. if (seekPosSize <= 0)
  1283. return false;
  1284. if ((pos + len) > stop)
  1285. return false;
  1286. pos += len; // consume size
  1287. if ((pos + seekPosSize) > stop)
  1288. return false;
  1289. pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize);
  1290. if (pEntry->pos < 0)
  1291. return false;
  1292. pos += seekPosSize; // consume payload
  1293. if (pos != stop)
  1294. return false;
  1295. return true;
  1296. }
  1297. Cues::Cues(Segment* pSegment, long long start_, long long size_,
  1298. long long element_start, long long element_size)
  1299. : m_pSegment(pSegment),
  1300. m_start(start_),
  1301. m_size(size_),
  1302. m_element_start(element_start),
  1303. m_element_size(element_size),
  1304. m_cue_points(NULL),
  1305. m_count(0),
  1306. m_preload_count(0),
  1307. m_pos(start_) {}
  1308. Cues::~Cues() {
  1309. const long n = m_count + m_preload_count;
  1310. CuePoint** p = m_cue_points;
  1311. CuePoint** const q = p + n;
  1312. while (p != q) {
  1313. CuePoint* const pCP = *p++;
  1314. assert(pCP);
  1315. delete pCP;
  1316. }
  1317. delete[] m_cue_points;
  1318. }
  1319. long Cues::GetCount() const {
  1320. if (m_cue_points == NULL)
  1321. return -1;
  1322. return m_count; // TODO: really ignore preload count?
  1323. }
  1324. bool Cues::DoneParsing() const {
  1325. const long long stop = m_start + m_size;
  1326. return (m_pos >= stop);
  1327. }
  1328. bool Cues::Init() const {
  1329. if (m_cue_points)
  1330. return true;
  1331. if (m_count != 0 || m_preload_count != 0)
  1332. return false;
  1333. IMkvReader* const pReader = m_pSegment->m_pReader;
  1334. const long long stop = m_start + m_size;
  1335. long long pos = m_start;
  1336. long cue_points_size = 0;
  1337. while (pos < stop) {
  1338. const long long idpos = pos;
  1339. long len;
  1340. const long long id = ReadID(pReader, pos, len);
  1341. if (id < 0 || (pos + len) > stop) {
  1342. return false;
  1343. }
  1344. pos += len; // consume ID
  1345. const long long size = ReadUInt(pReader, pos, len);
  1346. if (size < 0 || (pos + len > stop)) {
  1347. return false;
  1348. }
  1349. pos += len; // consume Size field
  1350. if (pos + size > stop) {
  1351. return false;
  1352. }
  1353. if (id == libwebm::kMkvCuePoint) {
  1354. if (!PreloadCuePoint(cue_points_size, idpos))
  1355. return false;
  1356. }
  1357. pos += size; // skip payload
  1358. }
  1359. return true;
  1360. }
  1361. bool Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
  1362. if (m_count != 0)
  1363. return false;
  1364. if (m_preload_count >= cue_points_size) {
  1365. const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
  1366. CuePoint** const qq = new (std::nothrow) CuePoint*[n];
  1367. if (qq == NULL)
  1368. return false;
  1369. CuePoint** q = qq; // beginning of target
  1370. CuePoint** p = m_cue_points; // beginning of source
  1371. CuePoint** const pp = p + m_preload_count; // end of source
  1372. while (p != pp)
  1373. *q++ = *p++;
  1374. delete[] m_cue_points;
  1375. m_cue_points = qq;
  1376. cue_points_size = n;
  1377. }
  1378. CuePoint* const pCP = new (std::nothrow) CuePoint(m_preload_count, pos);
  1379. if (pCP == NULL)
  1380. return false;
  1381. m_cue_points[m_preload_count++] = pCP;
  1382. return true;
  1383. }
  1384. bool Cues::LoadCuePoint() const {
  1385. const long long stop = m_start + m_size;
  1386. if (m_pos >= stop)
  1387. return false; // nothing else to do
  1388. if (!Init()) {
  1389. m_pos = stop;
  1390. return false;
  1391. }
  1392. IMkvReader* const pReader = m_pSegment->m_pReader;
  1393. while (m_pos < stop) {
  1394. const long long idpos = m_pos;
  1395. long len;
  1396. const long long id = ReadID(pReader, m_pos, len);
  1397. if (id < 0 || (m_pos + len) > stop)
  1398. return false;
  1399. m_pos += len; // consume ID
  1400. const long long size = ReadUInt(pReader, m_pos, len);
  1401. if (size < 0 || (m_pos + len) > stop)
  1402. return false;
  1403. m_pos += len; // consume Size field
  1404. if ((m_pos + size) > stop)
  1405. return false;
  1406. if (id != libwebm::kMkvCuePoint) {
  1407. m_pos += size; // consume payload
  1408. if (m_pos > stop)
  1409. return false;
  1410. continue;
  1411. }
  1412. if (m_preload_count < 1)
  1413. return false;
  1414. CuePoint* const pCP = m_cue_points[m_count];
  1415. if (!pCP || (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)))
  1416. return false;
  1417. if (!pCP->Load(pReader)) {
  1418. m_pos = stop;
  1419. return false;
  1420. }
  1421. ++m_count;
  1422. --m_preload_count;
  1423. m_pos += size; // consume payload
  1424. if (m_pos > stop)
  1425. return false;
  1426. return true; // yes, we loaded a cue point
  1427. }
  1428. return false; // no, we did not load a cue point
  1429. }
  1430. bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP,
  1431. const CuePoint::TrackPosition*& pTP) const {
  1432. if (time_ns < 0 || pTrack == NULL || m_cue_points == NULL || m_count == 0)
  1433. return false;
  1434. CuePoint** const ii = m_cue_points;
  1435. CuePoint** i = ii;
  1436. CuePoint** const jj = ii + m_count;
  1437. CuePoint** j = jj;
  1438. pCP = *i;
  1439. if (pCP == NULL)
  1440. return false;
  1441. if (time_ns <= pCP->GetTime(m_pSegment)) {
  1442. pTP = pCP->Find(pTrack);
  1443. return (pTP != NULL);
  1444. }
  1445. while (i < j) {
  1446. // INVARIANT:
  1447. //[ii, i) <= time_ns
  1448. //[i, j) ?
  1449. //[j, jj) > time_ns
  1450. CuePoint** const k = i + (j - i) / 2;
  1451. if (k >= jj)
  1452. return false;
  1453. CuePoint* const pCP = *k;
  1454. if (pCP == NULL)
  1455. return false;
  1456. const long long t = pCP->GetTime(m_pSegment);
  1457. if (t <= time_ns)
  1458. i = k + 1;
  1459. else
  1460. j = k;
  1461. if (i > j)
  1462. return false;
  1463. }
  1464. if (i != j || i > jj || i <= ii)
  1465. return false;
  1466. pCP = *--i;
  1467. if (pCP == NULL || pCP->GetTime(m_pSegment) > time_ns)
  1468. return false;
  1469. // TODO: here and elsewhere, it's probably not correct to search
  1470. // for the cue point with this time, and then search for a matching
  1471. // track. In principle, the matching track could be on some earlier
  1472. // cue point, and with our current algorithm, we'd miss it. To make
  1473. // this bullet-proof, we'd need to create a secondary structure,
  1474. // with a list of cue points that apply to a track, and then search
  1475. // that track-based structure for a matching cue point.
  1476. pTP = pCP->Find(pTrack);
  1477. return (pTP != NULL);
  1478. }
  1479. const CuePoint* Cues::GetFirst() const {
  1480. if (m_cue_points == NULL || m_count == 0)
  1481. return NULL;
  1482. CuePoint* const* const pp = m_cue_points;
  1483. if (pp == NULL)
  1484. return NULL;
  1485. CuePoint* const pCP = pp[0];
  1486. if (pCP == NULL || pCP->GetTimeCode() < 0)
  1487. return NULL;
  1488. return pCP;
  1489. }
  1490. const CuePoint* Cues::GetLast() const {
  1491. if (m_cue_points == NULL || m_count <= 0)
  1492. return NULL;
  1493. const long index = m_count - 1;
  1494. CuePoint* const* const pp = m_cue_points;
  1495. if (pp == NULL)
  1496. return NULL;
  1497. CuePoint* const pCP = pp[index];
  1498. if (pCP == NULL || pCP->GetTimeCode() < 0)
  1499. return NULL;
  1500. return pCP;
  1501. }
  1502. const CuePoint* Cues::GetNext(const CuePoint* pCurr) const {
  1503. if (pCurr == NULL || pCurr->GetTimeCode() < 0 || m_cue_points == NULL ||
  1504. m_count < 1) {
  1505. return NULL;
  1506. }
  1507. long index = pCurr->m_index;
  1508. if (index >= m_count)
  1509. return NULL;
  1510. CuePoint* const* const pp = m_cue_points;
  1511. if (pp == NULL || pp[index] != pCurr)
  1512. return NULL;
  1513. ++index;
  1514. if (index >= m_count)
  1515. return NULL;
  1516. CuePoint* const pNext = pp[index];
  1517. if (pNext == NULL || pNext->GetTimeCode() < 0)
  1518. return NULL;
  1519. return pNext;
  1520. }
  1521. const BlockEntry* Cues::GetBlock(const CuePoint* pCP,
  1522. const CuePoint::TrackPosition* pTP) const {
  1523. if (pCP == NULL || pTP == NULL)
  1524. return NULL;
  1525. return m_pSegment->GetBlock(*pCP, *pTP);
  1526. }
  1527. const BlockEntry* Segment::GetBlock(const CuePoint& cp,
  1528. const CuePoint::TrackPosition& tp) {
  1529. Cluster** const ii = m_clusters;
  1530. Cluster** i = ii;
  1531. const long count = m_clusterCount + m_clusterPreloadCount;
  1532. Cluster** const jj = ii + count;
  1533. Cluster** j = jj;
  1534. while (i < j) {
  1535. // INVARIANT:
  1536. //[ii, i) < pTP->m_pos
  1537. //[i, j) ?
  1538. //[j, jj) > pTP->m_pos
  1539. Cluster** const k = i + (j - i) / 2;
  1540. assert(k < jj);
  1541. Cluster* const pCluster = *k;
  1542. assert(pCluster);
  1543. // const long long pos_ = pCluster->m_pos;
  1544. // assert(pos_);
  1545. // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
  1546. const long long pos = pCluster->GetPosition();
  1547. assert(pos >= 0);
  1548. if (pos < tp.m_pos)
  1549. i = k + 1;
  1550. else if (pos > tp.m_pos)
  1551. j = k;
  1552. else
  1553. return pCluster->GetEntry(cp, tp);
  1554. }
  1555. assert(i == j);
  1556. // assert(Cluster::HasBlockEntries(this, tp.m_pos));
  1557. Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1);
  1558. if (pCluster == NULL)
  1559. return NULL;
  1560. const ptrdiff_t idx = i - m_clusters;
  1561. if (!PreloadCluster(pCluster, idx)) {
  1562. delete pCluster;
  1563. return NULL;
  1564. }
  1565. assert(m_clusters);
  1566. assert(m_clusterPreloadCount > 0);
  1567. assert(m_clusters[idx] == pCluster);
  1568. return pCluster->GetEntry(cp, tp);
  1569. }
  1570. const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) {
  1571. if (requested_pos < 0)
  1572. return 0;
  1573. Cluster** const ii = m_clusters;
  1574. Cluster** i = ii;
  1575. const long count = m_clusterCount + m_clusterPreloadCount;
  1576. Cluster** const jj = ii + count;
  1577. Cluster** j = jj;
  1578. while (i < j) {
  1579. // INVARIANT:
  1580. //[ii, i) < pTP->m_pos
  1581. //[i, j) ?
  1582. //[j, jj) > pTP->m_pos
  1583. Cluster** const k = i + (j - i) / 2;
  1584. assert(k < jj);
  1585. Cluster* const pCluster = *k;
  1586. assert(pCluster);
  1587. // const long long pos_ = pCluster->m_pos;
  1588. // assert(pos_);
  1589. // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1);
  1590. const long long pos = pCluster->GetPosition();
  1591. assert(pos >= 0);
  1592. if (pos < requested_pos)
  1593. i = k + 1;
  1594. else if (pos > requested_pos)
  1595. j = k;
  1596. else
  1597. return pCluster;
  1598. }
  1599. assert(i == j);
  1600. // assert(Cluster::HasBlockEntries(this, tp.m_pos));
  1601. Cluster* const pCluster = Cluster::Create(this, -1, requested_pos);
  1602. if (pCluster == NULL)
  1603. return NULL;
  1604. const ptrdiff_t idx = i - m_clusters;
  1605. if (!PreloadCluster(pCluster, idx)) {
  1606. delete pCluster;
  1607. return NULL;
  1608. }
  1609. assert(m_clusters);
  1610. assert(m_clusterPreloadCount > 0);
  1611. assert(m_clusters[idx] == pCluster);
  1612. return pCluster;
  1613. }
  1614. CuePoint::CuePoint(long idx, long long pos)
  1615. : m_element_start(0),
  1616. m_element_size(0),
  1617. m_index(idx),
  1618. m_timecode(-1 * pos),
  1619. m_track_positions(NULL),
  1620. m_track_positions_count(0) {
  1621. assert(pos > 0);
  1622. }
  1623. CuePoint::~CuePoint() { delete[] m_track_positions; }
  1624. bool CuePoint::Load(IMkvReader* pReader) {
  1625. // odbgstream os;
  1626. // os << "CuePoint::Load(begin): timecode=" << m_timecode << endl;
  1627. if (m_timecode >= 0) // already loaded
  1628. return true;
  1629. assert(m_track_positions == NULL);
  1630. assert(m_track_positions_count == 0);
  1631. long long pos_ = -m_timecode;
  1632. const long long element_start = pos_;
  1633. long long stop;
  1634. {
  1635. long len;
  1636. const long long id = ReadID(pReader, pos_, len);
  1637. if (id != libwebm::kMkvCuePoint)
  1638. return false;
  1639. pos_ += len; // consume ID
  1640. const long long size = ReadUInt(pReader, pos_, len);
  1641. assert(size >= 0);
  1642. pos_ += len; // consume Size field
  1643. // pos_ now points to start of payload
  1644. stop = pos_ + size;
  1645. }
  1646. const long long element_size = stop - element_start;
  1647. long long pos = pos_;
  1648. // First count number of track positions
  1649. while (pos < stop) {
  1650. long len;
  1651. const long long id = ReadID(pReader, pos, len);
  1652. if ((id < 0) || (pos + len > stop)) {
  1653. return false;
  1654. }
  1655. pos += len; // consume ID
  1656. const long long size = ReadUInt(pReader, pos, len);
  1657. if ((size < 0) || (pos + len > stop)) {
  1658. return false;
  1659. }
  1660. pos += len; // consume Size field
  1661. if ((pos + size) > stop) {
  1662. return false;
  1663. }
  1664. if (id == libwebm::kMkvCueTime)
  1665. m_timecode = UnserializeUInt(pReader, pos, size);
  1666. else if (id == libwebm::kMkvCueTrackPositions)
  1667. ++m_track_positions_count;
  1668. pos += size; // consume payload
  1669. }
  1670. if (m_timecode < 0 || m_track_positions_count <= 0) {
  1671. return false;
  1672. }
  1673. // os << "CuePoint::Load(cont'd): idpos=" << idpos
  1674. // << " timecode=" << m_timecode
  1675. // << endl;
  1676. m_track_positions = new (std::nothrow) TrackPosition[m_track_positions_count];
  1677. if (m_track_positions == NULL)
  1678. return false;
  1679. // Now parse track positions
  1680. TrackPosition* p = m_track_positions;
  1681. pos = pos_;
  1682. while (pos < stop) {
  1683. long len;
  1684. const long long id = ReadID(pReader, pos, len);
  1685. if (id < 0 || (pos + len) > stop)
  1686. return false;
  1687. pos += len; // consume ID
  1688. const long long size = ReadUInt(pReader, pos, len);
  1689. assert(size >= 0);
  1690. assert((pos + len) <= stop);
  1691. pos += len; // consume Size field
  1692. assert((pos + size) <= stop);
  1693. if (id == libwebm::kMkvCueTrackPositions) {
  1694. TrackPosition& tp = *p++;
  1695. if (!tp.Parse(pReader, pos, size)) {
  1696. return false;
  1697. }
  1698. }
  1699. pos += size; // consume payload
  1700. if (pos > stop)
  1701. return false;
  1702. }
  1703. assert(size_t(p - m_track_positions) == m_track_positions_count);
  1704. m_element_start = element_start;
  1705. m_element_size = element_size;
  1706. return true;
  1707. }
  1708. bool CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_,
  1709. long long size_) {
  1710. const long long stop = start_ + size_;
  1711. long long pos = start_;
  1712. m_track = -1;
  1713. m_pos = -1;
  1714. m_block = 1; // default
  1715. while (pos < stop) {
  1716. long len;
  1717. const long long id = ReadID(pReader, pos, len);
  1718. if ((id < 0) || ((pos + len) > stop)) {
  1719. return false;
  1720. }
  1721. pos += len; // consume ID
  1722. const long long size = ReadUInt(pReader, pos, len);
  1723. if ((size < 0) || ((pos + len) > stop)) {
  1724. return false;
  1725. }
  1726. pos += len; // consume Size field
  1727. if ((pos + size) > stop) {
  1728. return false;
  1729. }
  1730. if (id == libwebm::kMkvCueTrack)
  1731. m_track = UnserializeUInt(pReader, pos, size);
  1732. else if (id == libwebm::kMkvCueClusterPosition)
  1733. m_pos = UnserializeUInt(pReader, pos, size);
  1734. else if (id == libwebm::kMkvCueBlockNumber)
  1735. m_block = UnserializeUInt(pReader, pos, size);
  1736. pos += size; // consume payload
  1737. }
  1738. if ((m_pos < 0) || (m_track <= 0)) {
  1739. return false;
  1740. }
  1741. return true;
  1742. }
  1743. const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const {
  1744. if (pTrack == NULL) {
  1745. return NULL;
  1746. }
  1747. const long long n = pTrack->GetNumber();
  1748. const TrackPosition* i = m_track_positions;
  1749. const TrackPosition* const j = i + m_track_positions_count;
  1750. while (i != j) {
  1751. const TrackPosition& p = *i++;
  1752. if (p.m_track == n)
  1753. return &p;
  1754. }
  1755. return NULL; // no matching track number found
  1756. }
  1757. long long CuePoint::GetTimeCode() const { return m_timecode; }
  1758. long long CuePoint::GetTime(const Segment* pSegment) const {
  1759. assert(pSegment);
  1760. assert(m_timecode >= 0);
  1761. const SegmentInfo* const pInfo = pSegment->GetInfo();
  1762. assert(pInfo);
  1763. const long long scale = pInfo->GetTimeCodeScale();
  1764. assert(scale >= 1);
  1765. const long long time = scale * m_timecode;
  1766. return time;
  1767. }
  1768. bool Segment::DoneParsing() const {
  1769. if (m_size < 0) {
  1770. long long total, avail;
  1771. const int status = m_pReader->Length(&total, &avail);
  1772. if (status < 0) // error
  1773. return true; // must assume done
  1774. if (total < 0)
  1775. return false; // assume live stream
  1776. return (m_pos >= total);
  1777. }
  1778. const long long stop = m_start + m_size;
  1779. return (m_pos >= stop);
  1780. }
  1781. const Cluster* Segment::GetFirst() const {
  1782. if ((m_clusters == NULL) || (m_clusterCount <= 0))
  1783. return &m_eos;
  1784. Cluster* const pCluster = m_clusters[0];
  1785. assert(pCluster);
  1786. return pCluster;
  1787. }
  1788. const Cluster* Segment::GetLast() const {
  1789. if ((m_clusters == NULL) || (m_clusterCount <= 0))
  1790. return &m_eos;
  1791. const long idx = m_clusterCount - 1;
  1792. Cluster* const pCluster = m_clusters[idx];
  1793. assert(pCluster);
  1794. return pCluster;
  1795. }
  1796. unsigned long Segment::GetCount() const { return m_clusterCount; }
  1797. const Cluster* Segment::GetNext(const Cluster* pCurr) {
  1798. assert(pCurr);
  1799. assert(pCurr != &m_eos);
  1800. assert(m_clusters);
  1801. long idx = pCurr->m_index;
  1802. if (idx >= 0) {
  1803. assert(m_clusterCount > 0);
  1804. assert(idx < m_clusterCount);
  1805. assert(pCurr == m_clusters[idx]);
  1806. ++idx;
  1807. if (idx >= m_clusterCount)
  1808. return &m_eos; // caller will LoadCluster as desired
  1809. Cluster* const pNext = m_clusters[idx];
  1810. assert(pNext);
  1811. assert(pNext->m_index >= 0);
  1812. assert(pNext->m_index == idx);
  1813. return pNext;
  1814. }
  1815. assert(m_clusterPreloadCount > 0);
  1816. long long pos = pCurr->m_element_start;
  1817. assert(m_size >= 0); // TODO
  1818. const long long stop = m_start + m_size; // end of segment
  1819. {
  1820. long len;
  1821. long long result = GetUIntLength(m_pReader, pos, len);
  1822. assert(result == 0);
  1823. assert((pos + len) <= stop); // TODO
  1824. if (result != 0)
  1825. return NULL;
  1826. const long long id = ReadID(m_pReader, pos, len);
  1827. if (id != libwebm::kMkvCluster)
  1828. return NULL;
  1829. pos += len; // consume ID
  1830. // Read Size
  1831. result = GetUIntLength(m_pReader, pos, len);
  1832. assert(result == 0); // TODO
  1833. assert((pos + len) <= stop); // TODO
  1834. const long long size = ReadUInt(m_pReader, pos, len);
  1835. assert(size > 0); // TODO
  1836. // assert((pCurr->m_size <= 0) || (pCurr->m_size == size));
  1837. pos += len; // consume length of size of element
  1838. assert((pos + size) <= stop); // TODO
  1839. // Pos now points to start of payload
  1840. pos += size; // consume payload
  1841. }
  1842. long long off_next = 0;
  1843. while (pos < stop) {
  1844. long len;
  1845. long long result = GetUIntLength(m_pReader, pos, len);
  1846. assert(result == 0);
  1847. assert((pos + len) <= stop); // TODO
  1848. if (result != 0)
  1849. return NULL;
  1850. const long long idpos = pos; // pos of next (potential) cluster
  1851. const long long id = ReadID(m_pReader, idpos, len);
  1852. if (id < 0)
  1853. return NULL;
  1854. pos += len; // consume ID
  1855. // Read Size
  1856. result = GetUIntLength(m_pReader, pos, len);
  1857. assert(result == 0); // TODO
  1858. assert((pos + len) <= stop); // TODO
  1859. const long long size = ReadUInt(m_pReader, pos, len);
  1860. assert(size >= 0); // TODO
  1861. pos += len; // consume length of size of element
  1862. assert((pos + size) <= stop); // TODO
  1863. // Pos now points to start of payload
  1864. if (size == 0) // weird
  1865. continue;
  1866. if (id == libwebm::kMkvCluster) {
  1867. const long long off_next_ = idpos - m_start;
  1868. long long pos_;
  1869. long len_;
  1870. const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_);
  1871. assert(status >= 0);
  1872. if (status > 0) {
  1873. off_next = off_next_;
  1874. break;
  1875. }
  1876. }
  1877. pos += size; // consume payload
  1878. }
  1879. if (off_next <= 0)
  1880. return 0;
  1881. Cluster** const ii = m_clusters + m_clusterCount;
  1882. Cluster** i = ii;
  1883. Cluster** const jj = ii + m_clusterPreloadCount;
  1884. Cluster** j = jj;
  1885. while (i < j) {
  1886. // INVARIANT:
  1887. //[0, i) < pos_next
  1888. //[i, j) ?
  1889. //[j, jj) > pos_next
  1890. Cluster** const k = i + (j - i) / 2;
  1891. assert(k < jj);
  1892. Cluster* const pNext = *k;
  1893. assert(pNext);
  1894. assert(pNext->m_index < 0);
  1895. // const long long pos_ = pNext->m_pos;
  1896. // assert(pos_);
  1897. // pos = pos_ * ((pos_ < 0) ? -1 : 1);
  1898. pos = pNext->GetPosition();
  1899. if (pos < off_next)
  1900. i = k + 1;
  1901. else if (pos > off_next)
  1902. j = k;
  1903. else
  1904. return pNext;
  1905. }
  1906. assert(i == j);
  1907. Cluster* const pNext = Cluster::Create(this, -1, off_next);
  1908. if (pNext == NULL)
  1909. return NULL;
  1910. const ptrdiff_t idx_next = i - m_clusters; // insertion position
  1911. if (!PreloadCluster(pNext, idx_next)) {
  1912. delete pNext;
  1913. return NULL;
  1914. }
  1915. assert(m_clusters);
  1916. assert(idx_next < m_clusterSize);
  1917. assert(m_clusters[idx_next] == pNext);
  1918. return pNext;
  1919. }
  1920. long Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult,
  1921. long long& pos, long& len) {
  1922. assert(pCurr);
  1923. assert(!pCurr->EOS());
  1924. assert(m_clusters);
  1925. pResult = 0;
  1926. if (pCurr->m_index >= 0) { // loaded (not merely preloaded)
  1927. assert(m_clusters[pCurr->m_index] == pCurr);
  1928. const long next_idx = pCurr->m_index + 1;
  1929. if (next_idx < m_clusterCount) {
  1930. pResult = m_clusters[next_idx];
  1931. return 0; // success
  1932. }
  1933. // curr cluster is last among loaded
  1934. const long result = LoadCluster(pos, len);
  1935. if (result < 0) // error or underflow
  1936. return result;
  1937. if (result > 0) // no more clusters
  1938. {
  1939. // pResult = &m_eos;
  1940. return 1;
  1941. }
  1942. pResult = GetLast();
  1943. return 0; // success
  1944. }
  1945. assert(m_pos > 0);
  1946. long long total, avail;
  1947. long status = m_pReader->Length(&total, &avail);
  1948. if (status < 0) // error
  1949. return status;
  1950. assert((total < 0) || (avail <= total));
  1951. const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
  1952. // interrogate curr cluster
  1953. pos = pCurr->m_element_start;
  1954. if (pCurr->m_element_size >= 0)
  1955. pos += pCurr->m_element_size;
  1956. else {
  1957. if ((pos + 1) > avail) {
  1958. len = 1;
  1959. return E_BUFFER_NOT_FULL;
  1960. }
  1961. long long result = GetUIntLength(m_pReader, pos, len);
  1962. if (result < 0) // error
  1963. return static_cast<long>(result);
  1964. if (result > 0) // weird
  1965. return E_BUFFER_NOT_FULL;
  1966. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  1967. return E_FILE_FORMAT_INVALID;
  1968. if ((pos + len) > avail)
  1969. return E_BUFFER_NOT_FULL;
  1970. const long long id = ReadUInt(m_pReader, pos, len);
  1971. if (id != libwebm::kMkvCluster)
  1972. return -1;
  1973. pos += len; // consume ID
  1974. // Read Size
  1975. if ((pos + 1) > avail) {
  1976. len = 1;
  1977. return E_BUFFER_NOT_FULL;
  1978. }
  1979. result = GetUIntLength(m_pReader, pos, len);
  1980. if (result < 0) // error
  1981. return static_cast<long>(result);
  1982. if (result > 0) // weird
  1983. return E_BUFFER_NOT_FULL;
  1984. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  1985. return E_FILE_FORMAT_INVALID;
  1986. if ((pos + len) > avail)
  1987. return E_BUFFER_NOT_FULL;
  1988. const long long size = ReadUInt(m_pReader, pos, len);
  1989. if (size < 0) // error
  1990. return static_cast<long>(size);
  1991. pos += len; // consume size field
  1992. const long long unknown_size = (1LL << (7 * len)) - 1;
  1993. if (size == unknown_size) // TODO: should never happen
  1994. return E_FILE_FORMAT_INVALID; // TODO: resolve this
  1995. // assert((pCurr->m_size <= 0) || (pCurr->m_size == size));
  1996. if ((segment_stop >= 0) && ((pos + size) > segment_stop))
  1997. return E_FILE_FORMAT_INVALID;
  1998. // Pos now points to start of payload
  1999. pos += size; // consume payload (that is, the current cluster)
  2000. if (segment_stop >= 0 && pos > segment_stop)
  2001. return E_FILE_FORMAT_INVALID;
  2002. // By consuming the payload, we are assuming that the curr
  2003. // cluster isn't interesting. That is, we don't bother checking
  2004. // whether the payload of the curr cluster is less than what
  2005. // happens to be available (obtained via IMkvReader::Length).
  2006. // Presumably the caller has already dispensed with the current
  2007. // cluster, and really does want the next cluster.
  2008. }
  2009. // pos now points to just beyond the last fully-loaded cluster
  2010. for (;;) {
  2011. const long status = DoParseNext(pResult, pos, len);
  2012. if (status <= 1)
  2013. return status;
  2014. }
  2015. }
  2016. long Segment::DoParseNext(const Cluster*& pResult, long long& pos, long& len) {
  2017. long long total, avail;
  2018. long status = m_pReader->Length(&total, &avail);
  2019. if (status < 0) // error
  2020. return status;
  2021. assert((total < 0) || (avail <= total));
  2022. const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
  2023. // Parse next cluster. This is strictly a parsing activity.
  2024. // Creation of a new cluster object happens later, after the
  2025. // parsing is done.
  2026. long long off_next = 0;
  2027. long long cluster_size = -1;
  2028. for (;;) {
  2029. if ((total >= 0) && (pos >= total))
  2030. return 1; // EOF
  2031. if ((segment_stop >= 0) && (pos >= segment_stop))
  2032. return 1; // EOF
  2033. if ((pos + 1) > avail) {
  2034. len = 1;
  2035. return E_BUFFER_NOT_FULL;
  2036. }
  2037. long long result = GetUIntLength(m_pReader, pos, len);
  2038. if (result < 0) // error
  2039. return static_cast<long>(result);
  2040. if (result > 0) // weird
  2041. return E_BUFFER_NOT_FULL;
  2042. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  2043. return E_FILE_FORMAT_INVALID;
  2044. if ((pos + len) > avail)
  2045. return E_BUFFER_NOT_FULL;
  2046. const long long idpos = pos; // absolute
  2047. const long long idoff = pos - m_start; // relative
  2048. const long long id = ReadID(m_pReader, idpos, len); // absolute
  2049. if (id < 0) // error
  2050. return static_cast<long>(id);
  2051. if (id == 0) // weird
  2052. return -1; // generic error
  2053. pos += len; // consume ID
  2054. // Read Size
  2055. if ((pos + 1) > avail) {
  2056. len = 1;
  2057. return E_BUFFER_NOT_FULL;
  2058. }
  2059. result = GetUIntLength(m_pReader, pos, len);
  2060. if (result < 0) // error
  2061. return static_cast<long>(result);
  2062. if (result > 0) // weird
  2063. return E_BUFFER_NOT_FULL;
  2064. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  2065. return E_FILE_FORMAT_INVALID;
  2066. if ((pos + len) > avail)
  2067. return E_BUFFER_NOT_FULL;
  2068. const long long size = ReadUInt(m_pReader, pos, len);
  2069. if (size < 0) // error
  2070. return static_cast<long>(size);
  2071. pos += len; // consume length of size of element
  2072. // Pos now points to start of payload
  2073. if (size == 0) // weird
  2074. continue;
  2075. const long long unknown_size = (1LL << (7 * len)) - 1;
  2076. if ((segment_stop >= 0) && (size != unknown_size) &&
  2077. ((pos + size) > segment_stop)) {
  2078. return E_FILE_FORMAT_INVALID;
  2079. }
  2080. if (id == libwebm::kMkvCues) {
  2081. if (size == unknown_size)
  2082. return E_FILE_FORMAT_INVALID;
  2083. const long long element_stop = pos + size;
  2084. if ((segment_stop >= 0) && (element_stop > segment_stop))
  2085. return E_FILE_FORMAT_INVALID;
  2086. const long long element_start = idpos;
  2087. const long long element_size = element_stop - element_start;
  2088. if (m_pCues == NULL) {
  2089. m_pCues = new (std::nothrow)
  2090. Cues(this, pos, size, element_start, element_size);
  2091. if (m_pCues == NULL)
  2092. return false;
  2093. }
  2094. pos += size; // consume payload
  2095. if (segment_stop >= 0 && pos > segment_stop)
  2096. return E_FILE_FORMAT_INVALID;
  2097. continue;
  2098. }
  2099. if (id != libwebm::kMkvCluster) { // not a Cluster ID
  2100. if (size == unknown_size)
  2101. return E_FILE_FORMAT_INVALID;
  2102. pos += size; // consume payload
  2103. if (segment_stop >= 0 && pos > segment_stop)
  2104. return E_FILE_FORMAT_INVALID;
  2105. continue;
  2106. }
  2107. // We have a cluster.
  2108. off_next = idoff;
  2109. if (size != unknown_size)
  2110. cluster_size = size;
  2111. break;
  2112. }
  2113. assert(off_next > 0); // have cluster
  2114. // We have parsed the next cluster.
  2115. // We have not created a cluster object yet. What we need
  2116. // to do now is determine whether it has already be preloaded
  2117. //(in which case, an object for this cluster has already been
  2118. // created), and if not, create a new cluster object.
  2119. Cluster** const ii = m_clusters + m_clusterCount;
  2120. Cluster** i = ii;
  2121. Cluster** const jj = ii + m_clusterPreloadCount;
  2122. Cluster** j = jj;
  2123. while (i < j) {
  2124. // INVARIANT:
  2125. //[0, i) < pos_next
  2126. //[i, j) ?
  2127. //[j, jj) > pos_next
  2128. Cluster** const k = i + (j - i) / 2;
  2129. assert(k < jj);
  2130. const Cluster* const pNext = *k;
  2131. assert(pNext);
  2132. assert(pNext->m_index < 0);
  2133. pos = pNext->GetPosition();
  2134. assert(pos >= 0);
  2135. if (pos < off_next)
  2136. i = k + 1;
  2137. else if (pos > off_next)
  2138. j = k;
  2139. else {
  2140. pResult = pNext;
  2141. return 0; // success
  2142. }
  2143. }
  2144. assert(i == j);
  2145. long long pos_;
  2146. long len_;
  2147. status = Cluster::HasBlockEntries(this, off_next, pos_, len_);
  2148. if (status < 0) { // error or underflow
  2149. pos = pos_;
  2150. len = len_;
  2151. return status;
  2152. }
  2153. if (status > 0) { // means "found at least one block entry"
  2154. Cluster* const pNext = Cluster::Create(this,
  2155. -1, // preloaded
  2156. off_next);
  2157. if (pNext == NULL)
  2158. return -1;
  2159. const ptrdiff_t idx_next = i - m_clusters; // insertion position
  2160. if (!PreloadCluster(pNext, idx_next)) {
  2161. delete pNext;
  2162. return -1;
  2163. }
  2164. assert(m_clusters);
  2165. assert(idx_next < m_clusterSize);
  2166. assert(m_clusters[idx_next] == pNext);
  2167. pResult = pNext;
  2168. return 0; // success
  2169. }
  2170. // status == 0 means "no block entries found"
  2171. if (cluster_size < 0) { // unknown size
  2172. const long long payload_pos = pos; // absolute pos of cluster payload
  2173. for (;;) { // determine cluster size
  2174. if ((total >= 0) && (pos >= total))
  2175. break;
  2176. if ((segment_stop >= 0) && (pos >= segment_stop))
  2177. break; // no more clusters
  2178. // Read ID
  2179. if ((pos + 1) > avail) {
  2180. len = 1;
  2181. return E_BUFFER_NOT_FULL;
  2182. }
  2183. long long result = GetUIntLength(m_pReader, pos, len);
  2184. if (result < 0) // error
  2185. return static_cast<long>(result);
  2186. if (result > 0) // weird
  2187. return E_BUFFER_NOT_FULL;
  2188. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  2189. return E_FILE_FORMAT_INVALID;
  2190. if ((pos + len) > avail)
  2191. return E_BUFFER_NOT_FULL;
  2192. const long long idpos = pos;
  2193. const long long id = ReadID(m_pReader, idpos, len);
  2194. if (id < 0) // error (or underflow)
  2195. return static_cast<long>(id);
  2196. // This is the distinguished set of ID's we use to determine
  2197. // that we have exhausted the sub-element's inside the cluster
  2198. // whose ID we parsed earlier.
  2199. if (id == libwebm::kMkvCluster || id == libwebm::kMkvCues)
  2200. break;
  2201. pos += len; // consume ID (of sub-element)
  2202. // Read Size
  2203. if ((pos + 1) > avail) {
  2204. len = 1;
  2205. return E_BUFFER_NOT_FULL;
  2206. }
  2207. result = GetUIntLength(m_pReader, pos, len);
  2208. if (result < 0) // error
  2209. return static_cast<long>(result);
  2210. if (result > 0) // weird
  2211. return E_BUFFER_NOT_FULL;
  2212. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  2213. return E_FILE_FORMAT_INVALID;
  2214. if ((pos + len) > avail)
  2215. return E_BUFFER_NOT_FULL;
  2216. const long long size = ReadUInt(m_pReader, pos, len);
  2217. if (size < 0) // error
  2218. return static_cast<long>(size);
  2219. pos += len; // consume size field of element
  2220. // pos now points to start of sub-element's payload
  2221. if (size == 0) // weird
  2222. continue;
  2223. const long long unknown_size = (1LL << (7 * len)) - 1;
  2224. if (size == unknown_size)
  2225. return E_FILE_FORMAT_INVALID; // not allowed for sub-elements
  2226. if ((segment_stop >= 0) && ((pos + size) > segment_stop)) // weird
  2227. return E_FILE_FORMAT_INVALID;
  2228. pos += size; // consume payload of sub-element
  2229. if (segment_stop >= 0 && pos > segment_stop)
  2230. return E_FILE_FORMAT_INVALID;
  2231. } // determine cluster size
  2232. cluster_size = pos - payload_pos;
  2233. assert(cluster_size >= 0); // TODO: handle cluster_size = 0
  2234. pos = payload_pos; // reset and re-parse original cluster
  2235. }
  2236. pos += cluster_size; // consume payload
  2237. if (segment_stop >= 0 && pos > segment_stop)
  2238. return E_FILE_FORMAT_INVALID;
  2239. return 2; // try to find a cluster that follows next
  2240. }
  2241. const Cluster* Segment::FindCluster(long long time_ns) const {
  2242. if ((m_clusters == NULL) || (m_clusterCount <= 0))
  2243. return &m_eos;
  2244. {
  2245. Cluster* const pCluster = m_clusters[0];
  2246. assert(pCluster);
  2247. assert(pCluster->m_index == 0);
  2248. if (time_ns <= pCluster->GetTime())
  2249. return pCluster;
  2250. }
  2251. // Binary search of cluster array
  2252. long i = 0;
  2253. long j = m_clusterCount;
  2254. while (i < j) {
  2255. // INVARIANT:
  2256. //[0, i) <= time_ns
  2257. //[i, j) ?
  2258. //[j, m_clusterCount) > time_ns
  2259. const long k = i + (j - i) / 2;
  2260. assert(k < m_clusterCount);
  2261. Cluster* const pCluster = m_clusters[k];
  2262. assert(pCluster);
  2263. assert(pCluster->m_index == k);
  2264. const long long t = pCluster->GetTime();
  2265. if (t <= time_ns)
  2266. i = k + 1;
  2267. else
  2268. j = k;
  2269. assert(i <= j);
  2270. }
  2271. assert(i == j);
  2272. assert(i > 0);
  2273. assert(i <= m_clusterCount);
  2274. const long k = i - 1;
  2275. Cluster* const pCluster = m_clusters[k];
  2276. assert(pCluster);
  2277. assert(pCluster->m_index == k);
  2278. assert(pCluster->GetTime() <= time_ns);
  2279. return pCluster;
  2280. }
  2281. const Tracks* Segment::GetTracks() const { return m_pTracks; }
  2282. const SegmentInfo* Segment::GetInfo() const { return m_pInfo; }
  2283. const Cues* Segment::GetCues() const { return m_pCues; }
  2284. const Chapters* Segment::GetChapters() const { return m_pChapters; }
  2285. const Tags* Segment::GetTags() const { return m_pTags; }
  2286. const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; }
  2287. long long Segment::GetDuration() const {
  2288. assert(m_pInfo);
  2289. return m_pInfo->GetDuration();
  2290. }
  2291. Chapters::Chapters(Segment* pSegment, long long payload_start,
  2292. long long payload_size, long long element_start,
  2293. long long element_size)
  2294. : m_pSegment(pSegment),
  2295. m_start(payload_start),
  2296. m_size(payload_size),
  2297. m_element_start(element_start),
  2298. m_element_size(element_size),
  2299. m_editions(NULL),
  2300. m_editions_size(0),
  2301. m_editions_count(0) {}
  2302. Chapters::~Chapters() {
  2303. while (m_editions_count > 0) {
  2304. Edition& e = m_editions[--m_editions_count];
  2305. e.Clear();
  2306. }
  2307. delete[] m_editions;
  2308. }
  2309. long Chapters::Parse() {
  2310. IMkvReader* const pReader = m_pSegment->m_pReader;
  2311. long long pos = m_start; // payload start
  2312. const long long stop = pos + m_size; // payload stop
  2313. while (pos < stop) {
  2314. long long id, size;
  2315. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2316. if (status < 0) // error
  2317. return status;
  2318. if (size == 0) // weird
  2319. continue;
  2320. if (id == libwebm::kMkvEditionEntry) {
  2321. status = ParseEdition(pos, size);
  2322. if (status < 0) // error
  2323. return status;
  2324. }
  2325. pos += size;
  2326. if (pos > stop)
  2327. return E_FILE_FORMAT_INVALID;
  2328. }
  2329. if (pos != stop)
  2330. return E_FILE_FORMAT_INVALID;
  2331. return 0;
  2332. }
  2333. int Chapters::GetEditionCount() const { return m_editions_count; }
  2334. const Chapters::Edition* Chapters::GetEdition(int idx) const {
  2335. if (idx < 0)
  2336. return NULL;
  2337. if (idx >= m_editions_count)
  2338. return NULL;
  2339. return m_editions + idx;
  2340. }
  2341. bool Chapters::ExpandEditionsArray() {
  2342. if (m_editions_size > m_editions_count)
  2343. return true; // nothing else to do
  2344. const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size;
  2345. Edition* const editions = new (std::nothrow) Edition[size];
  2346. if (editions == NULL)
  2347. return false;
  2348. for (int idx = 0; idx < m_editions_count; ++idx) {
  2349. m_editions[idx].ShallowCopy(editions[idx]);
  2350. }
  2351. delete[] m_editions;
  2352. m_editions = editions;
  2353. m_editions_size = size;
  2354. return true;
  2355. }
  2356. long Chapters::ParseEdition(long long pos, long long size) {
  2357. if (!ExpandEditionsArray())
  2358. return -1;
  2359. Edition& e = m_editions[m_editions_count++];
  2360. e.Init();
  2361. return e.Parse(m_pSegment->m_pReader, pos, size);
  2362. }
  2363. Chapters::Edition::Edition() {}
  2364. Chapters::Edition::~Edition() {}
  2365. int Chapters::Edition::GetAtomCount() const { return m_atoms_count; }
  2366. const Chapters::Atom* Chapters::Edition::GetAtom(int index) const {
  2367. if (index < 0)
  2368. return NULL;
  2369. if (index >= m_atoms_count)
  2370. return NULL;
  2371. return m_atoms + index;
  2372. }
  2373. void Chapters::Edition::Init() {
  2374. m_atoms = NULL;
  2375. m_atoms_size = 0;
  2376. m_atoms_count = 0;
  2377. }
  2378. void Chapters::Edition::ShallowCopy(Edition& rhs) const {
  2379. rhs.m_atoms = m_atoms;
  2380. rhs.m_atoms_size = m_atoms_size;
  2381. rhs.m_atoms_count = m_atoms_count;
  2382. }
  2383. void Chapters::Edition::Clear() {
  2384. while (m_atoms_count > 0) {
  2385. Atom& a = m_atoms[--m_atoms_count];
  2386. a.Clear();
  2387. }
  2388. delete[] m_atoms;
  2389. m_atoms = NULL;
  2390. m_atoms_size = 0;
  2391. }
  2392. long Chapters::Edition::Parse(IMkvReader* pReader, long long pos,
  2393. long long size) {
  2394. const long long stop = pos + size;
  2395. while (pos < stop) {
  2396. long long id, size;
  2397. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2398. if (status < 0) // error
  2399. return status;
  2400. if (size == 0)
  2401. continue;
  2402. if (id == libwebm::kMkvChapterAtom) {
  2403. status = ParseAtom(pReader, pos, size);
  2404. if (status < 0) // error
  2405. return status;
  2406. }
  2407. pos += size;
  2408. if (pos > stop)
  2409. return E_FILE_FORMAT_INVALID;
  2410. }
  2411. if (pos != stop)
  2412. return E_FILE_FORMAT_INVALID;
  2413. return 0;
  2414. }
  2415. long Chapters::Edition::ParseAtom(IMkvReader* pReader, long long pos,
  2416. long long size) {
  2417. if (!ExpandAtomsArray())
  2418. return -1;
  2419. Atom& a = m_atoms[m_atoms_count++];
  2420. a.Init();
  2421. return a.Parse(pReader, pos, size);
  2422. }
  2423. bool Chapters::Edition::ExpandAtomsArray() {
  2424. if (m_atoms_size > m_atoms_count)
  2425. return true; // nothing else to do
  2426. const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size;
  2427. Atom* const atoms = new (std::nothrow) Atom[size];
  2428. if (atoms == NULL)
  2429. return false;
  2430. for (int idx = 0; idx < m_atoms_count; ++idx) {
  2431. m_atoms[idx].ShallowCopy(atoms[idx]);
  2432. }
  2433. delete[] m_atoms;
  2434. m_atoms = atoms;
  2435. m_atoms_size = size;
  2436. return true;
  2437. }
  2438. Chapters::Atom::Atom() {}
  2439. Chapters::Atom::~Atom() {}
  2440. unsigned long long Chapters::Atom::GetUID() const { return m_uid; }
  2441. const char* Chapters::Atom::GetStringUID() const { return m_string_uid; }
  2442. long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; }
  2443. long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; }
  2444. long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const {
  2445. return GetTime(pChapters, m_start_timecode);
  2446. }
  2447. long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const {
  2448. return GetTime(pChapters, m_stop_timecode);
  2449. }
  2450. int Chapters::Atom::GetDisplayCount() const { return m_displays_count; }
  2451. const Chapters::Display* Chapters::Atom::GetDisplay(int index) const {
  2452. if (index < 0)
  2453. return NULL;
  2454. if (index >= m_displays_count)
  2455. return NULL;
  2456. return m_displays + index;
  2457. }
  2458. void Chapters::Atom::Init() {
  2459. m_string_uid = NULL;
  2460. m_uid = 0;
  2461. m_start_timecode = -1;
  2462. m_stop_timecode = -1;
  2463. m_displays = NULL;
  2464. m_displays_size = 0;
  2465. m_displays_count = 0;
  2466. }
  2467. void Chapters::Atom::ShallowCopy(Atom& rhs) const {
  2468. rhs.m_string_uid = m_string_uid;
  2469. rhs.m_uid = m_uid;
  2470. rhs.m_start_timecode = m_start_timecode;
  2471. rhs.m_stop_timecode = m_stop_timecode;
  2472. rhs.m_displays = m_displays;
  2473. rhs.m_displays_size = m_displays_size;
  2474. rhs.m_displays_count = m_displays_count;
  2475. }
  2476. void Chapters::Atom::Clear() {
  2477. delete[] m_string_uid;
  2478. m_string_uid = NULL;
  2479. while (m_displays_count > 0) {
  2480. Display& d = m_displays[--m_displays_count];
  2481. d.Clear();
  2482. }
  2483. delete[] m_displays;
  2484. m_displays = NULL;
  2485. m_displays_size = 0;
  2486. }
  2487. long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) {
  2488. const long long stop = pos + size;
  2489. while (pos < stop) {
  2490. long long id, size;
  2491. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2492. if (status < 0) // error
  2493. return status;
  2494. if (size == 0) // 0 length payload, skip.
  2495. continue;
  2496. if (id == libwebm::kMkvChapterDisplay) {
  2497. status = ParseDisplay(pReader, pos, size);
  2498. if (status < 0) // error
  2499. return status;
  2500. } else if (id == libwebm::kMkvChapterStringUID) {
  2501. status = UnserializeString(pReader, pos, size, m_string_uid);
  2502. if (status < 0) // error
  2503. return status;
  2504. } else if (id == libwebm::kMkvChapterUID) {
  2505. long long val;
  2506. status = UnserializeInt(pReader, pos, size, val);
  2507. if (status < 0) // error
  2508. return status;
  2509. m_uid = static_cast<unsigned long long>(val);
  2510. } else if (id == libwebm::kMkvChapterTimeStart) {
  2511. const long long val = UnserializeUInt(pReader, pos, size);
  2512. if (val < 0) // error
  2513. return static_cast<long>(val);
  2514. m_start_timecode = val;
  2515. } else if (id == libwebm::kMkvChapterTimeEnd) {
  2516. const long long val = UnserializeUInt(pReader, pos, size);
  2517. if (val < 0) // error
  2518. return static_cast<long>(val);
  2519. m_stop_timecode = val;
  2520. }
  2521. pos += size;
  2522. if (pos > stop)
  2523. return E_FILE_FORMAT_INVALID;
  2524. }
  2525. if (pos != stop)
  2526. return E_FILE_FORMAT_INVALID;
  2527. return 0;
  2528. }
  2529. long long Chapters::Atom::GetTime(const Chapters* pChapters,
  2530. long long timecode) {
  2531. if (pChapters == NULL)
  2532. return -1;
  2533. Segment* const pSegment = pChapters->m_pSegment;
  2534. if (pSegment == NULL) // weird
  2535. return -1;
  2536. const SegmentInfo* const pInfo = pSegment->GetInfo();
  2537. if (pInfo == NULL)
  2538. return -1;
  2539. const long long timecode_scale = pInfo->GetTimeCodeScale();
  2540. if (timecode_scale < 1) // weird
  2541. return -1;
  2542. if (timecode < 0)
  2543. return -1;
  2544. const long long result = timecode_scale * timecode;
  2545. return result;
  2546. }
  2547. long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos,
  2548. long long size) {
  2549. if (!ExpandDisplaysArray())
  2550. return -1;
  2551. Display& d = m_displays[m_displays_count++];
  2552. d.Init();
  2553. return d.Parse(pReader, pos, size);
  2554. }
  2555. bool Chapters::Atom::ExpandDisplaysArray() {
  2556. if (m_displays_size > m_displays_count)
  2557. return true; // nothing else to do
  2558. const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size;
  2559. Display* const displays = new (std::nothrow) Display[size];
  2560. if (displays == NULL)
  2561. return false;
  2562. for (int idx = 0; idx < m_displays_count; ++idx) {
  2563. m_displays[idx].ShallowCopy(displays[idx]);
  2564. }
  2565. delete[] m_displays;
  2566. m_displays = displays;
  2567. m_displays_size = size;
  2568. return true;
  2569. }
  2570. Chapters::Display::Display() {}
  2571. Chapters::Display::~Display() {}
  2572. const char* Chapters::Display::GetString() const { return m_string; }
  2573. const char* Chapters::Display::GetLanguage() const { return m_language; }
  2574. const char* Chapters::Display::GetCountry() const { return m_country; }
  2575. void Chapters::Display::Init() {
  2576. m_string = NULL;
  2577. m_language = NULL;
  2578. m_country = NULL;
  2579. }
  2580. void Chapters::Display::ShallowCopy(Display& rhs) const {
  2581. rhs.m_string = m_string;
  2582. rhs.m_language = m_language;
  2583. rhs.m_country = m_country;
  2584. }
  2585. void Chapters::Display::Clear() {
  2586. delete[] m_string;
  2587. m_string = NULL;
  2588. delete[] m_language;
  2589. m_language = NULL;
  2590. delete[] m_country;
  2591. m_country = NULL;
  2592. }
  2593. long Chapters::Display::Parse(IMkvReader* pReader, long long pos,
  2594. long long size) {
  2595. const long long stop = pos + size;
  2596. while (pos < stop) {
  2597. long long id, size;
  2598. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2599. if (status < 0) // error
  2600. return status;
  2601. if (size == 0) // No payload.
  2602. continue;
  2603. if (id == libwebm::kMkvChapString) {
  2604. status = UnserializeString(pReader, pos, size, m_string);
  2605. if (status)
  2606. return status;
  2607. } else if (id == libwebm::kMkvChapLanguage) {
  2608. status = UnserializeString(pReader, pos, size, m_language);
  2609. if (status)
  2610. return status;
  2611. } else if (id == libwebm::kMkvChapCountry) {
  2612. status = UnserializeString(pReader, pos, size, m_country);
  2613. if (status)
  2614. return status;
  2615. }
  2616. pos += size;
  2617. if (pos > stop)
  2618. return E_FILE_FORMAT_INVALID;
  2619. }
  2620. if (pos != stop)
  2621. return E_FILE_FORMAT_INVALID;
  2622. return 0;
  2623. }
  2624. Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size,
  2625. long long element_start, long long element_size)
  2626. : m_pSegment(pSegment),
  2627. m_start(payload_start),
  2628. m_size(payload_size),
  2629. m_element_start(element_start),
  2630. m_element_size(element_size),
  2631. m_tags(NULL),
  2632. m_tags_size(0),
  2633. m_tags_count(0) {}
  2634. Tags::~Tags() {
  2635. while (m_tags_count > 0) {
  2636. Tag& t = m_tags[--m_tags_count];
  2637. t.Clear();
  2638. }
  2639. delete[] m_tags;
  2640. }
  2641. long Tags::Parse() {
  2642. IMkvReader* const pReader = m_pSegment->m_pReader;
  2643. long long pos = m_start; // payload start
  2644. const long long stop = pos + m_size; // payload stop
  2645. while (pos < stop) {
  2646. long long id, size;
  2647. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2648. if (status < 0)
  2649. return status;
  2650. if (size == 0) // 0 length tag, read another
  2651. continue;
  2652. if (id == libwebm::kMkvTag) {
  2653. status = ParseTag(pos, size);
  2654. if (status < 0)
  2655. return status;
  2656. }
  2657. pos += size;
  2658. if (pos > stop)
  2659. return E_FILE_FORMAT_INVALID;
  2660. }
  2661. if (pos != stop)
  2662. return E_FILE_FORMAT_INVALID;
  2663. return 0;
  2664. }
  2665. int Tags::GetTagCount() const { return m_tags_count; }
  2666. const Tags::Tag* Tags::GetTag(int idx) const {
  2667. if (idx < 0)
  2668. return NULL;
  2669. if (idx >= m_tags_count)
  2670. return NULL;
  2671. return m_tags + idx;
  2672. }
  2673. bool Tags::ExpandTagsArray() {
  2674. if (m_tags_size > m_tags_count)
  2675. return true; // nothing else to do
  2676. const int size = (m_tags_size == 0) ? 1 : 2 * m_tags_size;
  2677. Tag* const tags = new (std::nothrow) Tag[size];
  2678. if (tags == NULL)
  2679. return false;
  2680. for (int idx = 0; idx < m_tags_count; ++idx) {
  2681. m_tags[idx].ShallowCopy(tags[idx]);
  2682. }
  2683. delete[] m_tags;
  2684. m_tags = tags;
  2685. m_tags_size = size;
  2686. return true;
  2687. }
  2688. long Tags::ParseTag(long long pos, long long size) {
  2689. if (!ExpandTagsArray())
  2690. return -1;
  2691. Tag& t = m_tags[m_tags_count++];
  2692. t.Init();
  2693. return t.Parse(m_pSegment->m_pReader, pos, size);
  2694. }
  2695. Tags::Tag::Tag() {}
  2696. Tags::Tag::~Tag() {}
  2697. int Tags::Tag::GetSimpleTagCount() const { return m_simple_tags_count; }
  2698. const Tags::SimpleTag* Tags::Tag::GetSimpleTag(int index) const {
  2699. if (index < 0)
  2700. return NULL;
  2701. if (index >= m_simple_tags_count)
  2702. return NULL;
  2703. return m_simple_tags + index;
  2704. }
  2705. void Tags::Tag::Init() {
  2706. m_simple_tags = NULL;
  2707. m_simple_tags_size = 0;
  2708. m_simple_tags_count = 0;
  2709. }
  2710. void Tags::Tag::ShallowCopy(Tag& rhs) const {
  2711. rhs.m_simple_tags = m_simple_tags;
  2712. rhs.m_simple_tags_size = m_simple_tags_size;
  2713. rhs.m_simple_tags_count = m_simple_tags_count;
  2714. }
  2715. void Tags::Tag::Clear() {
  2716. while (m_simple_tags_count > 0) {
  2717. SimpleTag& d = m_simple_tags[--m_simple_tags_count];
  2718. d.Clear();
  2719. }
  2720. delete[] m_simple_tags;
  2721. m_simple_tags = NULL;
  2722. m_simple_tags_size = 0;
  2723. }
  2724. long Tags::Tag::Parse(IMkvReader* pReader, long long pos, long long size) {
  2725. const long long stop = pos + size;
  2726. while (pos < stop) {
  2727. long long id, size;
  2728. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2729. if (status < 0)
  2730. return status;
  2731. if (size == 0) // 0 length tag, read another
  2732. continue;
  2733. if (id == libwebm::kMkvSimpleTag) {
  2734. status = ParseSimpleTag(pReader, pos, size);
  2735. if (status < 0)
  2736. return status;
  2737. }
  2738. pos += size;
  2739. if (pos > stop)
  2740. return E_FILE_FORMAT_INVALID;
  2741. }
  2742. if (pos != stop)
  2743. return E_FILE_FORMAT_INVALID;
  2744. return 0;
  2745. }
  2746. long Tags::Tag::ParseSimpleTag(IMkvReader* pReader, long long pos,
  2747. long long size) {
  2748. if (!ExpandSimpleTagsArray())
  2749. return -1;
  2750. SimpleTag& st = m_simple_tags[m_simple_tags_count++];
  2751. st.Init();
  2752. return st.Parse(pReader, pos, size);
  2753. }
  2754. bool Tags::Tag::ExpandSimpleTagsArray() {
  2755. if (m_simple_tags_size > m_simple_tags_count)
  2756. return true; // nothing else to do
  2757. const int size = (m_simple_tags_size == 0) ? 1 : 2 * m_simple_tags_size;
  2758. SimpleTag* const displays = new (std::nothrow) SimpleTag[size];
  2759. if (displays == NULL)
  2760. return false;
  2761. for (int idx = 0; idx < m_simple_tags_count; ++idx) {
  2762. m_simple_tags[idx].ShallowCopy(displays[idx]);
  2763. }
  2764. delete[] m_simple_tags;
  2765. m_simple_tags = displays;
  2766. m_simple_tags_size = size;
  2767. return true;
  2768. }
  2769. Tags::SimpleTag::SimpleTag() {}
  2770. Tags::SimpleTag::~SimpleTag() {}
  2771. const char* Tags::SimpleTag::GetTagName() const { return m_tag_name; }
  2772. const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; }
  2773. void Tags::SimpleTag::Init() {
  2774. m_tag_name = NULL;
  2775. m_tag_string = NULL;
  2776. }
  2777. void Tags::SimpleTag::ShallowCopy(SimpleTag& rhs) const {
  2778. rhs.m_tag_name = m_tag_name;
  2779. rhs.m_tag_string = m_tag_string;
  2780. }
  2781. void Tags::SimpleTag::Clear() {
  2782. delete[] m_tag_name;
  2783. m_tag_name = NULL;
  2784. delete[] m_tag_string;
  2785. m_tag_string = NULL;
  2786. }
  2787. long Tags::SimpleTag::Parse(IMkvReader* pReader, long long pos,
  2788. long long size) {
  2789. const long long stop = pos + size;
  2790. while (pos < stop) {
  2791. long long id, size;
  2792. long status = ParseElementHeader(pReader, pos, stop, id, size);
  2793. if (status < 0) // error
  2794. return status;
  2795. if (size == 0) // weird
  2796. continue;
  2797. if (id == libwebm::kMkvTagName) {
  2798. status = UnserializeString(pReader, pos, size, m_tag_name);
  2799. if (status)
  2800. return status;
  2801. } else if (id == libwebm::kMkvTagString) {
  2802. status = UnserializeString(pReader, pos, size, m_tag_string);
  2803. if (status)
  2804. return status;
  2805. }
  2806. pos += size;
  2807. if (pos > stop)
  2808. return E_FILE_FORMAT_INVALID;
  2809. }
  2810. if (pos != stop)
  2811. return E_FILE_FORMAT_INVALID;
  2812. return 0;
  2813. }
  2814. SegmentInfo::SegmentInfo(Segment* pSegment, long long start, long long size_,
  2815. long long element_start, long long element_size)
  2816. : m_pSegment(pSegment),
  2817. m_start(start),
  2818. m_size(size_),
  2819. m_element_start(element_start),
  2820. m_element_size(element_size),
  2821. m_pMuxingAppAsUTF8(NULL),
  2822. m_pWritingAppAsUTF8(NULL),
  2823. m_pTitleAsUTF8(NULL) {}
  2824. SegmentInfo::~SegmentInfo() {
  2825. delete[] m_pMuxingAppAsUTF8;
  2826. m_pMuxingAppAsUTF8 = NULL;
  2827. delete[] m_pWritingAppAsUTF8;
  2828. m_pWritingAppAsUTF8 = NULL;
  2829. delete[] m_pTitleAsUTF8;
  2830. m_pTitleAsUTF8 = NULL;
  2831. }
  2832. long SegmentInfo::Parse() {
  2833. assert(m_pMuxingAppAsUTF8 == NULL);
  2834. assert(m_pWritingAppAsUTF8 == NULL);
  2835. assert(m_pTitleAsUTF8 == NULL);
  2836. IMkvReader* const pReader = m_pSegment->m_pReader;
  2837. long long pos = m_start;
  2838. const long long stop = m_start + m_size;
  2839. m_timecodeScale = 1000000;
  2840. m_duration = -1;
  2841. while (pos < stop) {
  2842. long long id, size;
  2843. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  2844. if (status < 0) // error
  2845. return status;
  2846. if (id == libwebm::kMkvTimecodeScale) {
  2847. m_timecodeScale = UnserializeUInt(pReader, pos, size);
  2848. if (m_timecodeScale <= 0)
  2849. return E_FILE_FORMAT_INVALID;
  2850. } else if (id == libwebm::kMkvDuration) {
  2851. const long status = UnserializeFloat(pReader, pos, size, m_duration);
  2852. if (status < 0)
  2853. return status;
  2854. if (m_duration < 0)
  2855. return E_FILE_FORMAT_INVALID;
  2856. } else if (id == libwebm::kMkvMuxingApp) {
  2857. const long status =
  2858. UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8);
  2859. if (status)
  2860. return status;
  2861. } else if (id == libwebm::kMkvWritingApp) {
  2862. const long status =
  2863. UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8);
  2864. if (status)
  2865. return status;
  2866. } else if (id == libwebm::kMkvTitle) {
  2867. const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8);
  2868. if (status)
  2869. return status;
  2870. }
  2871. pos += size;
  2872. if (pos > stop)
  2873. return E_FILE_FORMAT_INVALID;
  2874. }
  2875. const double rollover_check = m_duration * m_timecodeScale;
  2876. if (rollover_check > static_cast<double>(LLONG_MAX))
  2877. return E_FILE_FORMAT_INVALID;
  2878. if (pos != stop)
  2879. return E_FILE_FORMAT_INVALID;
  2880. return 0;
  2881. }
  2882. long long SegmentInfo::GetTimeCodeScale() const { return m_timecodeScale; }
  2883. long long SegmentInfo::GetDuration() const {
  2884. if (m_duration < 0)
  2885. return -1;
  2886. assert(m_timecodeScale >= 1);
  2887. const double dd = double(m_duration) * double(m_timecodeScale);
  2888. const long long d = static_cast<long long>(dd);
  2889. return d;
  2890. }
  2891. const char* SegmentInfo::GetMuxingAppAsUTF8() const {
  2892. return m_pMuxingAppAsUTF8;
  2893. }
  2894. const char* SegmentInfo::GetWritingAppAsUTF8() const {
  2895. return m_pWritingAppAsUTF8;
  2896. }
  2897. const char* SegmentInfo::GetTitleAsUTF8() const { return m_pTitleAsUTF8; }
  2898. ///////////////////////////////////////////////////////////////
  2899. // ContentEncoding element
  2900. ContentEncoding::ContentCompression::ContentCompression()
  2901. : algo(0), settings(NULL), settings_len(0) {}
  2902. ContentEncoding::ContentCompression::~ContentCompression() {
  2903. delete[] settings;
  2904. }
  2905. ContentEncoding::ContentEncryption::ContentEncryption()
  2906. : algo(0),
  2907. key_id(NULL),
  2908. key_id_len(0),
  2909. signature(NULL),
  2910. signature_len(0),
  2911. sig_key_id(NULL),
  2912. sig_key_id_len(0),
  2913. sig_algo(0),
  2914. sig_hash_algo(0) {}
  2915. ContentEncoding::ContentEncryption::~ContentEncryption() {
  2916. delete[] key_id;
  2917. delete[] signature;
  2918. delete[] sig_key_id;
  2919. }
  2920. ContentEncoding::ContentEncoding()
  2921. : compression_entries_(NULL),
  2922. compression_entries_end_(NULL),
  2923. encryption_entries_(NULL),
  2924. encryption_entries_end_(NULL),
  2925. encoding_order_(0),
  2926. encoding_scope_(1),
  2927. encoding_type_(0) {}
  2928. ContentEncoding::~ContentEncoding() {
  2929. ContentCompression** comp_i = compression_entries_;
  2930. ContentCompression** const comp_j = compression_entries_end_;
  2931. while (comp_i != comp_j) {
  2932. ContentCompression* const comp = *comp_i++;
  2933. delete comp;
  2934. }
  2935. delete[] compression_entries_;
  2936. ContentEncryption** enc_i = encryption_entries_;
  2937. ContentEncryption** const enc_j = encryption_entries_end_;
  2938. while (enc_i != enc_j) {
  2939. ContentEncryption* const enc = *enc_i++;
  2940. delete enc;
  2941. }
  2942. delete[] encryption_entries_;
  2943. }
  2944. const ContentEncoding::ContentCompression*
  2945. ContentEncoding::GetCompressionByIndex(unsigned long idx) const {
  2946. const ptrdiff_t count = compression_entries_end_ - compression_entries_;
  2947. assert(count >= 0);
  2948. if (idx >= static_cast<unsigned long>(count))
  2949. return NULL;
  2950. return compression_entries_[idx];
  2951. }
  2952. unsigned long ContentEncoding::GetCompressionCount() const {
  2953. const ptrdiff_t count = compression_entries_end_ - compression_entries_;
  2954. assert(count >= 0);
  2955. return static_cast<unsigned long>(count);
  2956. }
  2957. const ContentEncoding::ContentEncryption* ContentEncoding::GetEncryptionByIndex(
  2958. unsigned long idx) const {
  2959. const ptrdiff_t count = encryption_entries_end_ - encryption_entries_;
  2960. assert(count >= 0);
  2961. if (idx >= static_cast<unsigned long>(count))
  2962. return NULL;
  2963. return encryption_entries_[idx];
  2964. }
  2965. unsigned long ContentEncoding::GetEncryptionCount() const {
  2966. const ptrdiff_t count = encryption_entries_end_ - encryption_entries_;
  2967. assert(count >= 0);
  2968. return static_cast<unsigned long>(count);
  2969. }
  2970. long ContentEncoding::ParseContentEncAESSettingsEntry(
  2971. long long start, long long size, IMkvReader* pReader,
  2972. ContentEncAESSettings* aes) {
  2973. assert(pReader);
  2974. assert(aes);
  2975. long long pos = start;
  2976. const long long stop = start + size;
  2977. while (pos < stop) {
  2978. long long id, size;
  2979. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  2980. if (status < 0) // error
  2981. return status;
  2982. if (id == libwebm::kMkvAESSettingsCipherMode) {
  2983. aes->cipher_mode = UnserializeUInt(pReader, pos, size);
  2984. if (aes->cipher_mode != 1)
  2985. return E_FILE_FORMAT_INVALID;
  2986. }
  2987. pos += size; // consume payload
  2988. if (pos > stop)
  2989. return E_FILE_FORMAT_INVALID;
  2990. }
  2991. return 0;
  2992. }
  2993. long ContentEncoding::ParseContentEncodingEntry(long long start, long long size,
  2994. IMkvReader* pReader) {
  2995. assert(pReader);
  2996. long long pos = start;
  2997. const long long stop = start + size;
  2998. // Count ContentCompression and ContentEncryption elements.
  2999. int compression_count = 0;
  3000. int encryption_count = 0;
  3001. while (pos < stop) {
  3002. long long id, size;
  3003. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3004. if (status < 0) // error
  3005. return status;
  3006. if (id == libwebm::kMkvContentCompression)
  3007. ++compression_count;
  3008. if (id == libwebm::kMkvContentEncryption)
  3009. ++encryption_count;
  3010. pos += size; // consume payload
  3011. if (pos > stop)
  3012. return E_FILE_FORMAT_INVALID;
  3013. }
  3014. if (compression_count <= 0 && encryption_count <= 0)
  3015. return -1;
  3016. if (compression_count > 0) {
  3017. compression_entries_ =
  3018. new (std::nothrow) ContentCompression*[compression_count];
  3019. if (!compression_entries_)
  3020. return -1;
  3021. compression_entries_end_ = compression_entries_;
  3022. }
  3023. if (encryption_count > 0) {
  3024. encryption_entries_ =
  3025. new (std::nothrow) ContentEncryption*[encryption_count];
  3026. if (!encryption_entries_) {
  3027. delete[] compression_entries_;
  3028. return -1;
  3029. }
  3030. encryption_entries_end_ = encryption_entries_;
  3031. }
  3032. pos = start;
  3033. while (pos < stop) {
  3034. long long id, size;
  3035. long status = ParseElementHeader(pReader, pos, stop, id, size);
  3036. if (status < 0) // error
  3037. return status;
  3038. if (id == libwebm::kMkvContentEncodingOrder) {
  3039. encoding_order_ = UnserializeUInt(pReader, pos, size);
  3040. } else if (id == libwebm::kMkvContentEncodingScope) {
  3041. encoding_scope_ = UnserializeUInt(pReader, pos, size);
  3042. if (encoding_scope_ < 1)
  3043. return -1;
  3044. } else if (id == libwebm::kMkvContentEncodingType) {
  3045. encoding_type_ = UnserializeUInt(pReader, pos, size);
  3046. } else if (id == libwebm::kMkvContentCompression) {
  3047. ContentCompression* const compression =
  3048. new (std::nothrow) ContentCompression();
  3049. if (!compression)
  3050. return -1;
  3051. status = ParseCompressionEntry(pos, size, pReader, compression);
  3052. if (status) {
  3053. delete compression;
  3054. return status;
  3055. }
  3056. *compression_entries_end_++ = compression;
  3057. } else if (id == libwebm::kMkvContentEncryption) {
  3058. ContentEncryption* const encryption =
  3059. new (std::nothrow) ContentEncryption();
  3060. if (!encryption)
  3061. return -1;
  3062. status = ParseEncryptionEntry(pos, size, pReader, encryption);
  3063. if (status) {
  3064. delete encryption;
  3065. return status;
  3066. }
  3067. *encryption_entries_end_++ = encryption;
  3068. }
  3069. pos += size; // consume payload
  3070. if (pos > stop)
  3071. return E_FILE_FORMAT_INVALID;
  3072. }
  3073. if (pos != stop)
  3074. return E_FILE_FORMAT_INVALID;
  3075. return 0;
  3076. }
  3077. long ContentEncoding::ParseCompressionEntry(long long start, long long size,
  3078. IMkvReader* pReader,
  3079. ContentCompression* compression) {
  3080. assert(pReader);
  3081. assert(compression);
  3082. long long pos = start;
  3083. const long long stop = start + size;
  3084. bool valid = false;
  3085. while (pos < stop) {
  3086. long long id, size;
  3087. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3088. if (status < 0) // error
  3089. return status;
  3090. if (id == libwebm::kMkvContentCompAlgo) {
  3091. long long algo = UnserializeUInt(pReader, pos, size);
  3092. if (algo < 0)
  3093. return E_FILE_FORMAT_INVALID;
  3094. compression->algo = algo;
  3095. valid = true;
  3096. } else if (id == libwebm::kMkvContentCompSettings) {
  3097. if (size <= 0)
  3098. return E_FILE_FORMAT_INVALID;
  3099. const size_t buflen = static_cast<size_t>(size);
  3100. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3101. if (buf == NULL)
  3102. return -1;
  3103. const int read_status =
  3104. pReader->Read(pos, static_cast<long>(buflen), buf);
  3105. if (read_status) {
  3106. delete[] buf;
  3107. return status;
  3108. }
  3109. compression->settings = buf;
  3110. compression->settings_len = buflen;
  3111. }
  3112. pos += size; // consume payload
  3113. if (pos > stop)
  3114. return E_FILE_FORMAT_INVALID;
  3115. }
  3116. // ContentCompAlgo is mandatory
  3117. if (!valid)
  3118. return E_FILE_FORMAT_INVALID;
  3119. return 0;
  3120. }
  3121. long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
  3122. IMkvReader* pReader,
  3123. ContentEncryption* encryption) {
  3124. assert(pReader);
  3125. assert(encryption);
  3126. long long pos = start;
  3127. const long long stop = start + size;
  3128. while (pos < stop) {
  3129. long long id, size;
  3130. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3131. if (status < 0) // error
  3132. return status;
  3133. if (id == libwebm::kMkvContentEncAlgo) {
  3134. encryption->algo = UnserializeUInt(pReader, pos, size);
  3135. if (encryption->algo != 5)
  3136. return E_FILE_FORMAT_INVALID;
  3137. } else if (id == libwebm::kMkvContentEncKeyID) {
  3138. delete[] encryption->key_id;
  3139. encryption->key_id = NULL;
  3140. encryption->key_id_len = 0;
  3141. if (size <= 0)
  3142. return E_FILE_FORMAT_INVALID;
  3143. const size_t buflen = static_cast<size_t>(size);
  3144. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3145. if (buf == NULL)
  3146. return -1;
  3147. const int read_status =
  3148. pReader->Read(pos, static_cast<long>(buflen), buf);
  3149. if (read_status) {
  3150. delete[] buf;
  3151. return status;
  3152. }
  3153. encryption->key_id = buf;
  3154. encryption->key_id_len = buflen;
  3155. } else if (id == libwebm::kMkvContentSignature) {
  3156. delete[] encryption->signature;
  3157. encryption->signature = NULL;
  3158. encryption->signature_len = 0;
  3159. if (size <= 0)
  3160. return E_FILE_FORMAT_INVALID;
  3161. const size_t buflen = static_cast<size_t>(size);
  3162. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3163. if (buf == NULL)
  3164. return -1;
  3165. const int read_status =
  3166. pReader->Read(pos, static_cast<long>(buflen), buf);
  3167. if (read_status) {
  3168. delete[] buf;
  3169. return status;
  3170. }
  3171. encryption->signature = buf;
  3172. encryption->signature_len = buflen;
  3173. } else if (id == libwebm::kMkvContentSigKeyID) {
  3174. delete[] encryption->sig_key_id;
  3175. encryption->sig_key_id = NULL;
  3176. encryption->sig_key_id_len = 0;
  3177. if (size <= 0)
  3178. return E_FILE_FORMAT_INVALID;
  3179. const size_t buflen = static_cast<size_t>(size);
  3180. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3181. if (buf == NULL)
  3182. return -1;
  3183. const int read_status =
  3184. pReader->Read(pos, static_cast<long>(buflen), buf);
  3185. if (read_status) {
  3186. delete[] buf;
  3187. return status;
  3188. }
  3189. encryption->sig_key_id = buf;
  3190. encryption->sig_key_id_len = buflen;
  3191. } else if (id == libwebm::kMkvContentSigAlgo) {
  3192. encryption->sig_algo = UnserializeUInt(pReader, pos, size);
  3193. } else if (id == libwebm::kMkvContentSigHashAlgo) {
  3194. encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
  3195. } else if (id == libwebm::kMkvContentEncAESSettings) {
  3196. const long status = ParseContentEncAESSettingsEntry(
  3197. pos, size, pReader, &encryption->aes_settings);
  3198. if (status)
  3199. return status;
  3200. }
  3201. pos += size; // consume payload
  3202. if (pos > stop)
  3203. return E_FILE_FORMAT_INVALID;
  3204. }
  3205. return 0;
  3206. }
  3207. Track::Track(Segment* pSegment, long long element_start, long long element_size)
  3208. : m_pSegment(pSegment),
  3209. m_element_start(element_start),
  3210. m_element_size(element_size),
  3211. content_encoding_entries_(NULL),
  3212. content_encoding_entries_end_(NULL) {}
  3213. Track::~Track() {
  3214. Info& info = const_cast<Info&>(m_info);
  3215. info.Clear();
  3216. ContentEncoding** i = content_encoding_entries_;
  3217. ContentEncoding** const j = content_encoding_entries_end_;
  3218. while (i != j) {
  3219. ContentEncoding* const encoding = *i++;
  3220. delete encoding;
  3221. }
  3222. delete[] content_encoding_entries_;
  3223. }
  3224. long Track::Create(Segment* pSegment, const Info& info, long long element_start,
  3225. long long element_size, Track*& pResult) {
  3226. if (pResult)
  3227. return -1;
  3228. Track* const pTrack =
  3229. new (std::nothrow) Track(pSegment, element_start, element_size);
  3230. if (pTrack == NULL)
  3231. return -1; // generic error
  3232. const int status = info.Copy(pTrack->m_info);
  3233. if (status) { // error
  3234. delete pTrack;
  3235. return status;
  3236. }
  3237. pResult = pTrack;
  3238. return 0; // success
  3239. }
  3240. Track::Info::Info()
  3241. : uid(0),
  3242. defaultDuration(0),
  3243. codecDelay(0),
  3244. seekPreRoll(0),
  3245. nameAsUTF8(NULL),
  3246. language(NULL),
  3247. codecId(NULL),
  3248. codecNameAsUTF8(NULL),
  3249. codecPrivate(NULL),
  3250. codecPrivateSize(0),
  3251. lacing(false) {}
  3252. Track::Info::~Info() { Clear(); }
  3253. void Track::Info::Clear() {
  3254. delete[] nameAsUTF8;
  3255. nameAsUTF8 = NULL;
  3256. delete[] language;
  3257. language = NULL;
  3258. delete[] codecId;
  3259. codecId = NULL;
  3260. delete[] codecPrivate;
  3261. codecPrivate = NULL;
  3262. codecPrivateSize = 0;
  3263. delete[] codecNameAsUTF8;
  3264. codecNameAsUTF8 = NULL;
  3265. }
  3266. int Track::Info::CopyStr(char* Info::*str, Info& dst_) const {
  3267. if (str == static_cast<char * Info::*>(NULL))
  3268. return -1;
  3269. char*& dst = dst_.*str;
  3270. if (dst) // should be NULL already
  3271. return -1;
  3272. const char* const src = this->*str;
  3273. if (src == NULL)
  3274. return 0;
  3275. const size_t len = strlen(src);
  3276. dst = SafeArrayAlloc<char>(1, len + 1);
  3277. if (dst == NULL)
  3278. return -1;
  3279. strcpy(dst, src);
  3280. return 0;
  3281. }
  3282. int Track::Info::Copy(Info& dst) const {
  3283. if (&dst == this)
  3284. return 0;
  3285. dst.type = type;
  3286. dst.number = number;
  3287. dst.defaultDuration = defaultDuration;
  3288. dst.codecDelay = codecDelay;
  3289. dst.seekPreRoll = seekPreRoll;
  3290. dst.uid = uid;
  3291. dst.lacing = lacing;
  3292. dst.settings = settings;
  3293. // We now copy the string member variables from src to dst.
  3294. // This involves memory allocation so in principle the operation
  3295. // can fail (indeed, that's why we have Info::Copy), so we must
  3296. // report this to the caller. An error return from this function
  3297. // therefore implies that the copy was only partially successful.
  3298. if (int status = CopyStr(&Info::nameAsUTF8, dst))
  3299. return status;
  3300. if (int status = CopyStr(&Info::language, dst))
  3301. return status;
  3302. if (int status = CopyStr(&Info::codecId, dst))
  3303. return status;
  3304. if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
  3305. return status;
  3306. if (codecPrivateSize > 0) {
  3307. if (codecPrivate == NULL)
  3308. return -1;
  3309. if (dst.codecPrivate)
  3310. return -1;
  3311. if (dst.codecPrivateSize != 0)
  3312. return -1;
  3313. dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize);
  3314. if (dst.codecPrivate == NULL)
  3315. return -1;
  3316. memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
  3317. dst.codecPrivateSize = codecPrivateSize;
  3318. }
  3319. return 0;
  3320. }
  3321. const BlockEntry* Track::GetEOS() const { return &m_eos; }
  3322. long Track::GetType() const { return m_info.type; }
  3323. long Track::GetNumber() const { return m_info.number; }
  3324. unsigned long long Track::GetUid() const { return m_info.uid; }
  3325. const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; }
  3326. const char* Track::GetLanguage() const { return m_info.language; }
  3327. const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }
  3328. const char* Track::GetCodecId() const { return m_info.codecId; }
  3329. const unsigned char* Track::GetCodecPrivate(size_t& size) const {
  3330. size = m_info.codecPrivateSize;
  3331. return m_info.codecPrivate;
  3332. }
  3333. bool Track::GetLacing() const { return m_info.lacing; }
  3334. unsigned long long Track::GetDefaultDuration() const {
  3335. return m_info.defaultDuration;
  3336. }
  3337. unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }
  3338. unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; }
  3339. long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
  3340. const Cluster* pCluster = m_pSegment->GetFirst();
  3341. for (int i = 0;;) {
  3342. if (pCluster == NULL) {
  3343. pBlockEntry = GetEOS();
  3344. return 1;
  3345. }
  3346. if (pCluster->EOS()) {
  3347. if (m_pSegment->DoneParsing()) {
  3348. pBlockEntry = GetEOS();
  3349. return 1;
  3350. }
  3351. pBlockEntry = 0;
  3352. return E_BUFFER_NOT_FULL;
  3353. }
  3354. long status = pCluster->GetFirst(pBlockEntry);
  3355. if (status < 0) // error
  3356. return status;
  3357. if (pBlockEntry == 0) { // empty cluster
  3358. pCluster = m_pSegment->GetNext(pCluster);
  3359. continue;
  3360. }
  3361. for (;;) {
  3362. const Block* const pBlock = pBlockEntry->GetBlock();
  3363. assert(pBlock);
  3364. const long long tn = pBlock->GetTrackNumber();
  3365. if ((tn == m_info.number) && VetEntry(pBlockEntry))
  3366. return 0;
  3367. const BlockEntry* pNextEntry;
  3368. status = pCluster->GetNext(pBlockEntry, pNextEntry);
  3369. if (status < 0) // error
  3370. return status;
  3371. if (pNextEntry == 0)
  3372. break;
  3373. pBlockEntry = pNextEntry;
  3374. }
  3375. ++i;
  3376. if (i >= 100)
  3377. break;
  3378. pCluster = m_pSegment->GetNext(pCluster);
  3379. }
  3380. // NOTE: if we get here, it means that we didn't find a block with
  3381. // a matching track number. We interpret that as an error (which
  3382. // might be too conservative).
  3383. pBlockEntry = GetEOS(); // so we can return a non-NULL value
  3384. return 1;
  3385. }
  3386. long Track::GetNext(const BlockEntry* pCurrEntry,
  3387. const BlockEntry*& pNextEntry) const {
  3388. assert(pCurrEntry);
  3389. assert(!pCurrEntry->EOS()); //?
  3390. const Block* const pCurrBlock = pCurrEntry->GetBlock();
  3391. assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number);
  3392. if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number)
  3393. return -1;
  3394. const Cluster* pCluster = pCurrEntry->GetCluster();
  3395. assert(pCluster);
  3396. assert(!pCluster->EOS());
  3397. long status = pCluster->GetNext(pCurrEntry, pNextEntry);
  3398. if (status < 0) // error
  3399. return status;
  3400. for (int i = 0;;) {
  3401. while (pNextEntry) {
  3402. const Block* const pNextBlock = pNextEntry->GetBlock();
  3403. assert(pNextBlock);
  3404. if (pNextBlock->GetTrackNumber() == m_info.number)
  3405. return 0;
  3406. pCurrEntry = pNextEntry;
  3407. status = pCluster->GetNext(pCurrEntry, pNextEntry);
  3408. if (status < 0) // error
  3409. return status;
  3410. }
  3411. pCluster = m_pSegment->GetNext(pCluster);
  3412. if (pCluster == NULL) {
  3413. pNextEntry = GetEOS();
  3414. return 1;
  3415. }
  3416. if (pCluster->EOS()) {
  3417. if (m_pSegment->DoneParsing()) {
  3418. pNextEntry = GetEOS();
  3419. return 1;
  3420. }
  3421. // TODO: there is a potential O(n^2) problem here: we tell the
  3422. // caller to (pre)load another cluster, which he does, but then he
  3423. // calls GetNext again, which repeats the same search. This is
  3424. // a pathological case, since the only way it can happen is if
  3425. // there exists a long sequence of clusters none of which contain a
  3426. // block from this track. One way around this problem is for the
  3427. // caller to be smarter when he loads another cluster: don't call
  3428. // us back until you have a cluster that contains a block from this
  3429. // track. (Of course, that's not cheap either, since our caller
  3430. // would have to scan the each cluster as it's loaded, so that
  3431. // would just push back the problem.)
  3432. pNextEntry = NULL;
  3433. return E_BUFFER_NOT_FULL;
  3434. }
  3435. status = pCluster->GetFirst(pNextEntry);
  3436. if (status < 0) // error
  3437. return status;
  3438. if (pNextEntry == NULL) // empty cluster
  3439. continue;
  3440. ++i;
  3441. if (i >= 100)
  3442. break;
  3443. }
  3444. // NOTE: if we get here, it means that we didn't find a block with
  3445. // a matching track number after lots of searching, so we give
  3446. // up trying.
  3447. pNextEntry = GetEOS(); // so we can return a non-NULL value
  3448. return 1;
  3449. }
  3450. bool Track::VetEntry(const BlockEntry* pBlockEntry) const {
  3451. assert(pBlockEntry);
  3452. const Block* const pBlock = pBlockEntry->GetBlock();
  3453. assert(pBlock);
  3454. assert(pBlock->GetTrackNumber() == m_info.number);
  3455. if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
  3456. return false;
  3457. // This function is used during a seek to determine whether the
  3458. // frame is a valid seek target. This default function simply
  3459. // returns true, which means all frames are valid seek targets.
  3460. // It gets overridden by the VideoTrack class, because only video
  3461. // keyframes can be used as seek target.
  3462. return true;
  3463. }
  3464. long Track::Seek(long long time_ns, const BlockEntry*& pResult) const {
  3465. const long status = GetFirst(pResult);
  3466. if (status < 0) // buffer underflow, etc
  3467. return status;
  3468. assert(pResult);
  3469. if (pResult->EOS())
  3470. return 0;
  3471. const Cluster* pCluster = pResult->GetCluster();
  3472. assert(pCluster);
  3473. assert(pCluster->GetIndex() >= 0);
  3474. if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
  3475. return 0;
  3476. Cluster** const clusters = m_pSegment->m_clusters;
  3477. assert(clusters);
  3478. const long count = m_pSegment->GetCount(); // loaded only, not preloaded
  3479. assert(count > 0);
  3480. Cluster** const i = clusters + pCluster->GetIndex();
  3481. assert(i);
  3482. assert(*i == pCluster);
  3483. assert(pCluster->GetTime() <= time_ns);
  3484. Cluster** const j = clusters + count;
  3485. Cluster** lo = i;
  3486. Cluster** hi = j;
  3487. while (lo < hi) {
  3488. // INVARIANT:
  3489. //[i, lo) <= time_ns
  3490. //[lo, hi) ?
  3491. //[hi, j) > time_ns
  3492. Cluster** const mid = lo + (hi - lo) / 2;
  3493. assert(mid < hi);
  3494. pCluster = *mid;
  3495. assert(pCluster);
  3496. assert(pCluster->GetIndex() >= 0);
  3497. assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
  3498. const long long t = pCluster->GetTime();
  3499. if (t <= time_ns)
  3500. lo = mid + 1;
  3501. else
  3502. hi = mid;
  3503. assert(lo <= hi);
  3504. }
  3505. assert(lo == hi);
  3506. assert(lo > i);
  3507. assert(lo <= j);
  3508. while (lo > i) {
  3509. pCluster = *--lo;
  3510. assert(pCluster);
  3511. assert(pCluster->GetTime() <= time_ns);
  3512. pResult = pCluster->GetEntry(this);
  3513. if ((pResult != 0) && !pResult->EOS())
  3514. return 0;
  3515. // landed on empty cluster (no entries)
  3516. }
  3517. pResult = GetEOS(); // weird
  3518. return 0;
  3519. }
  3520. const ContentEncoding* Track::GetContentEncodingByIndex(
  3521. unsigned long idx) const {
  3522. const ptrdiff_t count =
  3523. content_encoding_entries_end_ - content_encoding_entries_;
  3524. assert(count >= 0);
  3525. if (idx >= static_cast<unsigned long>(count))
  3526. return NULL;
  3527. return content_encoding_entries_[idx];
  3528. }
  3529. unsigned long Track::GetContentEncodingCount() const {
  3530. const ptrdiff_t count =
  3531. content_encoding_entries_end_ - content_encoding_entries_;
  3532. assert(count >= 0);
  3533. return static_cast<unsigned long>(count);
  3534. }
  3535. long Track::ParseContentEncodingsEntry(long long start, long long size) {
  3536. IMkvReader* const pReader = m_pSegment->m_pReader;
  3537. assert(pReader);
  3538. long long pos = start;
  3539. const long long stop = start + size;
  3540. // Count ContentEncoding elements.
  3541. int count = 0;
  3542. while (pos < stop) {
  3543. long long id, size;
  3544. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3545. if (status < 0) // error
  3546. return status;
  3547. // pos now designates start of element
  3548. if (id == libwebm::kMkvContentEncoding)
  3549. ++count;
  3550. pos += size; // consume payload
  3551. if (pos > stop)
  3552. return E_FILE_FORMAT_INVALID;
  3553. }
  3554. if (count <= 0)
  3555. return -1;
  3556. content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count];
  3557. if (!content_encoding_entries_)
  3558. return -1;
  3559. content_encoding_entries_end_ = content_encoding_entries_;
  3560. pos = start;
  3561. while (pos < stop) {
  3562. long long id, size;
  3563. long status = ParseElementHeader(pReader, pos, stop, id, size);
  3564. if (status < 0) // error
  3565. return status;
  3566. // pos now designates start of element
  3567. if (id == libwebm::kMkvContentEncoding) {
  3568. ContentEncoding* const content_encoding =
  3569. new (std::nothrow) ContentEncoding();
  3570. if (!content_encoding)
  3571. return -1;
  3572. status = content_encoding->ParseContentEncodingEntry(pos, size, pReader);
  3573. if (status) {
  3574. delete content_encoding;
  3575. return status;
  3576. }
  3577. *content_encoding_entries_end_++ = content_encoding;
  3578. }
  3579. pos += size; // consume payload
  3580. if (pos > stop)
  3581. return E_FILE_FORMAT_INVALID;
  3582. }
  3583. if (pos != stop)
  3584. return E_FILE_FORMAT_INVALID;
  3585. return 0;
  3586. }
  3587. Track::EOSBlock::EOSBlock() : BlockEntry(NULL, LONG_MIN) {}
  3588. BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; }
  3589. const Block* Track::EOSBlock::GetBlock() const { return NULL; }
  3590. bool PrimaryChromaticity::Parse(IMkvReader* reader, long long read_pos,
  3591. long long value_size, bool is_x,
  3592. PrimaryChromaticity** chromaticity) {
  3593. if (!reader)
  3594. return false;
  3595. if (!*chromaticity)
  3596. *chromaticity = new PrimaryChromaticity();
  3597. if (!*chromaticity)
  3598. return false;
  3599. PrimaryChromaticity* pc = *chromaticity;
  3600. float* value = is_x ? &pc->x : &pc->y;
  3601. double parser_value = 0;
  3602. const long long parse_status =
  3603. UnserializeFloat(reader, read_pos, value_size, parser_value);
  3604. // Valid range is [0, 1]. Make sure the double is representable as a float
  3605. // before casting.
  3606. if (parse_status < 0 || parser_value < 0.0 || parser_value > 1.0 ||
  3607. (parser_value > 0.0 && parser_value < FLT_MIN))
  3608. return false;
  3609. *value = static_cast<float>(parser_value);
  3610. return true;
  3611. }
  3612. bool MasteringMetadata::Parse(IMkvReader* reader, long long mm_start,
  3613. long long mm_size, MasteringMetadata** mm) {
  3614. if (!reader || *mm)
  3615. return false;
  3616. std::unique_ptr<MasteringMetadata> mm_ptr(new MasteringMetadata());
  3617. if (!mm_ptr.get())
  3618. return false;
  3619. const long long mm_end = mm_start + mm_size;
  3620. long long read_pos = mm_start;
  3621. while (read_pos < mm_end) {
  3622. long long child_id = 0;
  3623. long long child_size = 0;
  3624. const long long status =
  3625. ParseElementHeader(reader, read_pos, mm_end, child_id, child_size);
  3626. if (status < 0)
  3627. return false;
  3628. if (child_id == libwebm::kMkvLuminanceMax) {
  3629. double value = 0;
  3630. const long long value_parse_status =
  3631. UnserializeFloat(reader, read_pos, child_size, value);
  3632. if (value < -FLT_MAX || value > FLT_MAX ||
  3633. (value > 0.0 && value < FLT_MIN)) {
  3634. return false;
  3635. }
  3636. mm_ptr->luminance_max = static_cast<float>(value);
  3637. if (value_parse_status < 0 || mm_ptr->luminance_max < 0.0 ||
  3638. mm_ptr->luminance_max > 9999.99) {
  3639. return false;
  3640. }
  3641. } else if (child_id == libwebm::kMkvLuminanceMin) {
  3642. double value = 0;
  3643. const long long value_parse_status =
  3644. UnserializeFloat(reader, read_pos, child_size, value);
  3645. if (value < -FLT_MAX || value > FLT_MAX ||
  3646. (value > 0.0 && value < FLT_MIN)) {
  3647. return false;
  3648. }
  3649. mm_ptr->luminance_min = static_cast<float>(value);
  3650. if (value_parse_status < 0 || mm_ptr->luminance_min < 0.0 ||
  3651. mm_ptr->luminance_min > 999.9999) {
  3652. return false;
  3653. }
  3654. } else {
  3655. bool is_x = false;
  3656. PrimaryChromaticity** chromaticity;
  3657. switch (child_id) {
  3658. case libwebm::kMkvPrimaryRChromaticityX:
  3659. case libwebm::kMkvPrimaryRChromaticityY:
  3660. is_x = child_id == libwebm::kMkvPrimaryRChromaticityX;
  3661. chromaticity = &mm_ptr->r;
  3662. break;
  3663. case libwebm::kMkvPrimaryGChromaticityX:
  3664. case libwebm::kMkvPrimaryGChromaticityY:
  3665. is_x = child_id == libwebm::kMkvPrimaryGChromaticityX;
  3666. chromaticity = &mm_ptr->g;
  3667. break;
  3668. case libwebm::kMkvPrimaryBChromaticityX:
  3669. case libwebm::kMkvPrimaryBChromaticityY:
  3670. is_x = child_id == libwebm::kMkvPrimaryBChromaticityX;
  3671. chromaticity = &mm_ptr->b;
  3672. break;
  3673. case libwebm::kMkvWhitePointChromaticityX:
  3674. case libwebm::kMkvWhitePointChromaticityY:
  3675. is_x = child_id == libwebm::kMkvWhitePointChromaticityX;
  3676. chromaticity = &mm_ptr->white_point;
  3677. break;
  3678. default:
  3679. return false;
  3680. }
  3681. const bool value_parse_status = PrimaryChromaticity::Parse(
  3682. reader, read_pos, child_size, is_x, chromaticity);
  3683. if (!value_parse_status)
  3684. return false;
  3685. }
  3686. read_pos += child_size;
  3687. if (read_pos > mm_end)
  3688. return false;
  3689. }
  3690. *mm = mm_ptr.release();
  3691. return true;
  3692. }
  3693. bool Colour::Parse(IMkvReader* reader, long long colour_start,
  3694. long long colour_size, Colour** colour) {
  3695. if (!reader || *colour)
  3696. return false;
  3697. std::unique_ptr<Colour> colour_ptr(new Colour());
  3698. if (!colour_ptr.get())
  3699. return false;
  3700. const long long colour_end = colour_start + colour_size;
  3701. long long read_pos = colour_start;
  3702. while (read_pos < colour_end) {
  3703. long long child_id = 0;
  3704. long long child_size = 0;
  3705. const long status =
  3706. ParseElementHeader(reader, read_pos, colour_end, child_id, child_size);
  3707. if (status < 0)
  3708. return false;
  3709. if (child_id == libwebm::kMkvMatrixCoefficients) {
  3710. colour_ptr->matrix_coefficients =
  3711. UnserializeUInt(reader, read_pos, child_size);
  3712. if (colour_ptr->matrix_coefficients < 0)
  3713. return false;
  3714. } else if (child_id == libwebm::kMkvBitsPerChannel) {
  3715. colour_ptr->bits_per_channel =
  3716. UnserializeUInt(reader, read_pos, child_size);
  3717. if (colour_ptr->bits_per_channel < 0)
  3718. return false;
  3719. } else if (child_id == libwebm::kMkvChromaSubsamplingHorz) {
  3720. colour_ptr->chroma_subsampling_horz =
  3721. UnserializeUInt(reader, read_pos, child_size);
  3722. if (colour_ptr->chroma_subsampling_horz < 0)
  3723. return false;
  3724. } else if (child_id == libwebm::kMkvChromaSubsamplingVert) {
  3725. colour_ptr->chroma_subsampling_vert =
  3726. UnserializeUInt(reader, read_pos, child_size);
  3727. if (colour_ptr->chroma_subsampling_vert < 0)
  3728. return false;
  3729. } else if (child_id == libwebm::kMkvCbSubsamplingHorz) {
  3730. colour_ptr->cb_subsampling_horz =
  3731. UnserializeUInt(reader, read_pos, child_size);
  3732. if (colour_ptr->cb_subsampling_horz < 0)
  3733. return false;
  3734. } else if (child_id == libwebm::kMkvCbSubsamplingVert) {
  3735. colour_ptr->cb_subsampling_vert =
  3736. UnserializeUInt(reader, read_pos, child_size);
  3737. if (colour_ptr->cb_subsampling_vert < 0)
  3738. return false;
  3739. } else if (child_id == libwebm::kMkvChromaSitingHorz) {
  3740. colour_ptr->chroma_siting_horz =
  3741. UnserializeUInt(reader, read_pos, child_size);
  3742. if (colour_ptr->chroma_siting_horz < 0)
  3743. return false;
  3744. } else if (child_id == libwebm::kMkvChromaSitingVert) {
  3745. colour_ptr->chroma_siting_vert =
  3746. UnserializeUInt(reader, read_pos, child_size);
  3747. if (colour_ptr->chroma_siting_vert < 0)
  3748. return false;
  3749. } else if (child_id == libwebm::kMkvRange) {
  3750. colour_ptr->range = UnserializeUInt(reader, read_pos, child_size);
  3751. if (colour_ptr->range < 0)
  3752. return false;
  3753. } else if (child_id == libwebm::kMkvTransferCharacteristics) {
  3754. colour_ptr->transfer_characteristics =
  3755. UnserializeUInt(reader, read_pos, child_size);
  3756. if (colour_ptr->transfer_characteristics < 0)
  3757. return false;
  3758. } else if (child_id == libwebm::kMkvPrimaries) {
  3759. colour_ptr->primaries = UnserializeUInt(reader, read_pos, child_size);
  3760. if (colour_ptr->primaries < 0)
  3761. return false;
  3762. } else if (child_id == libwebm::kMkvMaxCLL) {
  3763. colour_ptr->max_cll = UnserializeUInt(reader, read_pos, child_size);
  3764. if (colour_ptr->max_cll < 0)
  3765. return false;
  3766. } else if (child_id == libwebm::kMkvMaxFALL) {
  3767. colour_ptr->max_fall = UnserializeUInt(reader, read_pos, child_size);
  3768. if (colour_ptr->max_fall < 0)
  3769. return false;
  3770. } else if (child_id == libwebm::kMkvMasteringMetadata) {
  3771. if (!MasteringMetadata::Parse(reader, read_pos, child_size,
  3772. &colour_ptr->mastering_metadata))
  3773. return false;
  3774. } else {
  3775. return false;
  3776. }
  3777. read_pos += child_size;
  3778. if (read_pos > colour_end)
  3779. return false;
  3780. }
  3781. *colour = colour_ptr.release();
  3782. return true;
  3783. }
  3784. bool Projection::Parse(IMkvReader* reader, long long start, long long size,
  3785. Projection** projection) {
  3786. if (!reader || *projection)
  3787. return false;
  3788. std::unique_ptr<Projection> projection_ptr(new Projection());
  3789. if (!projection_ptr.get())
  3790. return false;
  3791. const long long end = start + size;
  3792. long long read_pos = start;
  3793. while (read_pos < end) {
  3794. long long child_id = 0;
  3795. long long child_size = 0;
  3796. const long long status =
  3797. ParseElementHeader(reader, read_pos, end, child_id, child_size);
  3798. if (status < 0)
  3799. return false;
  3800. if (child_id == libwebm::kMkvProjectionType) {
  3801. long long projection_type = kTypeNotPresent;
  3802. projection_type = UnserializeUInt(reader, read_pos, child_size);
  3803. if (projection_type < 0)
  3804. return false;
  3805. projection_ptr->type = static_cast<ProjectionType>(projection_type);
  3806. } else if (child_id == libwebm::kMkvProjectionPrivate) {
  3807. unsigned char* data = SafeArrayAlloc<unsigned char>(1, child_size);
  3808. if (data == NULL)
  3809. return false;
  3810. const int status =
  3811. reader->Read(read_pos, static_cast<long>(child_size), data);
  3812. if (status) {
  3813. delete[] data;
  3814. return false;
  3815. }
  3816. projection_ptr->private_data = data;
  3817. projection_ptr->private_data_length = static_cast<size_t>(child_size);
  3818. } else {
  3819. double value = 0;
  3820. const long long value_parse_status =
  3821. UnserializeFloat(reader, read_pos, child_size, value);
  3822. // Make sure value is representable as a float before casting.
  3823. if (value_parse_status < 0 || value < -FLT_MAX || value > FLT_MAX ||
  3824. (value > 0.0 && value < FLT_MIN)) {
  3825. return false;
  3826. }
  3827. switch (child_id) {
  3828. case libwebm::kMkvProjectionPoseYaw:
  3829. projection_ptr->pose_yaw = static_cast<float>(value);
  3830. break;
  3831. case libwebm::kMkvProjectionPosePitch:
  3832. projection_ptr->pose_pitch = static_cast<float>(value);
  3833. break;
  3834. case libwebm::kMkvProjectionPoseRoll:
  3835. projection_ptr->pose_roll = static_cast<float>(value);
  3836. break;
  3837. default:
  3838. return false;
  3839. }
  3840. }
  3841. read_pos += child_size;
  3842. if (read_pos > end)
  3843. return false;
  3844. }
  3845. *projection = projection_ptr.release();
  3846. return true;
  3847. }
  3848. VideoTrack::VideoTrack(Segment* pSegment, long long element_start,
  3849. long long element_size)
  3850. : Track(pSegment, element_start, element_size),
  3851. m_colour(NULL),
  3852. m_projection(NULL) {}
  3853. VideoTrack::~VideoTrack() {
  3854. delete m_colour;
  3855. delete m_projection;
  3856. }
  3857. long VideoTrack::Parse(Segment* pSegment, const Info& info,
  3858. long long element_start, long long element_size,
  3859. VideoTrack*& pResult) {
  3860. if (pResult)
  3861. return -1;
  3862. if (info.type != Track::kVideo)
  3863. return -1;
  3864. long long width = 0;
  3865. long long height = 0;
  3866. long long display_width = 0;
  3867. long long display_height = 0;
  3868. long long display_unit = 0;
  3869. long long stereo_mode = 0;
  3870. double rate = 0.0;
  3871. IMkvReader* const pReader = pSegment->m_pReader;
  3872. const Settings& s = info.settings;
  3873. assert(s.start >= 0);
  3874. assert(s.size >= 0);
  3875. long long pos = s.start;
  3876. assert(pos >= 0);
  3877. const long long stop = pos + s.size;
  3878. Colour* colour = NULL;
  3879. Projection* projection = NULL;
  3880. while (pos < stop) {
  3881. long long id, size;
  3882. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3883. if (status < 0) // error
  3884. return status;
  3885. if (id == libwebm::kMkvPixelWidth) {
  3886. width = UnserializeUInt(pReader, pos, size);
  3887. if (width <= 0)
  3888. return E_FILE_FORMAT_INVALID;
  3889. } else if (id == libwebm::kMkvPixelHeight) {
  3890. height = UnserializeUInt(pReader, pos, size);
  3891. if (height <= 0)
  3892. return E_FILE_FORMAT_INVALID;
  3893. } else if (id == libwebm::kMkvDisplayWidth) {
  3894. display_width = UnserializeUInt(pReader, pos, size);
  3895. if (display_width <= 0)
  3896. return E_FILE_FORMAT_INVALID;
  3897. } else if (id == libwebm::kMkvDisplayHeight) {
  3898. display_height = UnserializeUInt(pReader, pos, size);
  3899. if (display_height <= 0)
  3900. return E_FILE_FORMAT_INVALID;
  3901. } else if (id == libwebm::kMkvDisplayUnit) {
  3902. display_unit = UnserializeUInt(pReader, pos, size);
  3903. if (display_unit < 0)
  3904. return E_FILE_FORMAT_INVALID;
  3905. } else if (id == libwebm::kMkvStereoMode) {
  3906. stereo_mode = UnserializeUInt(pReader, pos, size);
  3907. if (stereo_mode < 0)
  3908. return E_FILE_FORMAT_INVALID;
  3909. } else if (id == libwebm::kMkvFrameRate) {
  3910. const long status = UnserializeFloat(pReader, pos, size, rate);
  3911. if (status < 0)
  3912. return status;
  3913. if (rate <= 0)
  3914. return E_FILE_FORMAT_INVALID;
  3915. } else if (id == libwebm::kMkvColour) {
  3916. if (!Colour::Parse(pReader, pos, size, &colour))
  3917. return E_FILE_FORMAT_INVALID;
  3918. } else if (id == libwebm::kMkvProjection) {
  3919. if (!Projection::Parse(pReader, pos, size, &projection))
  3920. return E_FILE_FORMAT_INVALID;
  3921. }
  3922. pos += size; // consume payload
  3923. if (pos > stop)
  3924. return E_FILE_FORMAT_INVALID;
  3925. }
  3926. if (pos != stop)
  3927. return E_FILE_FORMAT_INVALID;
  3928. VideoTrack* const pTrack =
  3929. new (std::nothrow) VideoTrack(pSegment, element_start, element_size);
  3930. if (pTrack == NULL)
  3931. return -1; // generic error
  3932. const int status = info.Copy(pTrack->m_info);
  3933. if (status) { // error
  3934. delete pTrack;
  3935. return status;
  3936. }
  3937. pTrack->m_width = width;
  3938. pTrack->m_height = height;
  3939. pTrack->m_display_width = display_width;
  3940. pTrack->m_display_height = display_height;
  3941. pTrack->m_display_unit = display_unit;
  3942. pTrack->m_stereo_mode = stereo_mode;
  3943. pTrack->m_rate = rate;
  3944. pTrack->m_colour = colour;
  3945. pTrack->m_projection = projection;
  3946. pResult = pTrack;
  3947. return 0; // success
  3948. }
  3949. bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const {
  3950. return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey();
  3951. }
  3952. long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const {
  3953. const long status = GetFirst(pResult);
  3954. if (status < 0) // buffer underflow, etc
  3955. return status;
  3956. assert(pResult);
  3957. if (pResult->EOS())
  3958. return 0;
  3959. const Cluster* pCluster = pResult->GetCluster();
  3960. assert(pCluster);
  3961. assert(pCluster->GetIndex() >= 0);
  3962. if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
  3963. return 0;
  3964. Cluster** const clusters = m_pSegment->m_clusters;
  3965. assert(clusters);
  3966. const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded
  3967. assert(count > 0);
  3968. Cluster** const i = clusters + pCluster->GetIndex();
  3969. assert(i);
  3970. assert(*i == pCluster);
  3971. assert(pCluster->GetTime() <= time_ns);
  3972. Cluster** const j = clusters + count;
  3973. Cluster** lo = i;
  3974. Cluster** hi = j;
  3975. while (lo < hi) {
  3976. // INVARIANT:
  3977. //[i, lo) <= time_ns
  3978. //[lo, hi) ?
  3979. //[hi, j) > time_ns
  3980. Cluster** const mid = lo + (hi - lo) / 2;
  3981. assert(mid < hi);
  3982. pCluster = *mid;
  3983. assert(pCluster);
  3984. assert(pCluster->GetIndex() >= 0);
  3985. assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
  3986. const long long t = pCluster->GetTime();
  3987. if (t <= time_ns)
  3988. lo = mid + 1;
  3989. else
  3990. hi = mid;
  3991. assert(lo <= hi);
  3992. }
  3993. assert(lo == hi);
  3994. assert(lo > i);
  3995. assert(lo <= j);
  3996. pCluster = *--lo;
  3997. assert(pCluster);
  3998. assert(pCluster->GetTime() <= time_ns);
  3999. pResult = pCluster->GetEntry(this, time_ns);
  4000. if ((pResult != 0) && !pResult->EOS()) // found a keyframe
  4001. return 0;
  4002. while (lo != i) {
  4003. pCluster = *--lo;
  4004. assert(pCluster);
  4005. assert(pCluster->GetTime() <= time_ns);
  4006. pResult = pCluster->GetEntry(this, time_ns);
  4007. if ((pResult != 0) && !pResult->EOS())
  4008. return 0;
  4009. }
  4010. // weird: we're on the first cluster, but no keyframe found
  4011. // should never happen but we must return something anyway
  4012. pResult = GetEOS();
  4013. return 0;
  4014. }
  4015. Colour* VideoTrack::GetColour() const { return m_colour; }
  4016. Projection* VideoTrack::GetProjection() const { return m_projection; }
  4017. long long VideoTrack::GetWidth() const { return m_width; }
  4018. long long VideoTrack::GetHeight() const { return m_height; }
  4019. long long VideoTrack::GetDisplayWidth() const {
  4020. return m_display_width > 0 ? m_display_width : GetWidth();
  4021. }
  4022. long long VideoTrack::GetDisplayHeight() const {
  4023. return m_display_height > 0 ? m_display_height : GetHeight();
  4024. }
  4025. long long VideoTrack::GetDisplayUnit() const { return m_display_unit; }
  4026. long long VideoTrack::GetStereoMode() const { return m_stereo_mode; }
  4027. double VideoTrack::GetFrameRate() const { return m_rate; }
  4028. AudioTrack::AudioTrack(Segment* pSegment, long long element_start,
  4029. long long element_size)
  4030. : Track(pSegment, element_start, element_size) {}
  4031. long AudioTrack::Parse(Segment* pSegment, const Info& info,
  4032. long long element_start, long long element_size,
  4033. AudioTrack*& pResult) {
  4034. if (pResult)
  4035. return -1;
  4036. if (info.type != Track::kAudio)
  4037. return -1;
  4038. IMkvReader* const pReader = pSegment->m_pReader;
  4039. const Settings& s = info.settings;
  4040. assert(s.start >= 0);
  4041. assert(s.size >= 0);
  4042. long long pos = s.start;
  4043. assert(pos >= 0);
  4044. const long long stop = pos + s.size;
  4045. double rate = 8000.0; // MKV default
  4046. long long channels = 1;
  4047. long long bit_depth = 0;
  4048. while (pos < stop) {
  4049. long long id, size;
  4050. long status = ParseElementHeader(pReader, pos, stop, id, size);
  4051. if (status < 0) // error
  4052. return status;
  4053. if (id == libwebm::kMkvSamplingFrequency) {
  4054. status = UnserializeFloat(pReader, pos, size, rate);
  4055. if (status < 0)
  4056. return status;
  4057. if (rate <= 0)
  4058. return E_FILE_FORMAT_INVALID;
  4059. } else if (id == libwebm::kMkvChannels) {
  4060. channels = UnserializeUInt(pReader, pos, size);
  4061. if (channels <= 0)
  4062. return E_FILE_FORMAT_INVALID;
  4063. } else if (id == libwebm::kMkvBitDepth) {
  4064. bit_depth = UnserializeUInt(pReader, pos, size);
  4065. if (bit_depth <= 0)
  4066. return E_FILE_FORMAT_INVALID;
  4067. }
  4068. pos += size; // consume payload
  4069. if (pos > stop)
  4070. return E_FILE_FORMAT_INVALID;
  4071. }
  4072. if (pos != stop)
  4073. return E_FILE_FORMAT_INVALID;
  4074. AudioTrack* const pTrack =
  4075. new (std::nothrow) AudioTrack(pSegment, element_start, element_size);
  4076. if (pTrack == NULL)
  4077. return -1; // generic error
  4078. const int status = info.Copy(pTrack->m_info);
  4079. if (status) {
  4080. delete pTrack;
  4081. return status;
  4082. }
  4083. pTrack->m_rate = rate;
  4084. pTrack->m_channels = channels;
  4085. pTrack->m_bitDepth = bit_depth;
  4086. pResult = pTrack;
  4087. return 0; // success
  4088. }
  4089. double AudioTrack::GetSamplingRate() const { return m_rate; }
  4090. long long AudioTrack::GetChannels() const { return m_channels; }
  4091. long long AudioTrack::GetBitDepth() const { return m_bitDepth; }
  4092. Tracks::Tracks(Segment* pSegment, long long start, long long size_,
  4093. long long element_start, long long element_size)
  4094. : m_pSegment(pSegment),
  4095. m_start(start),
  4096. m_size(size_),
  4097. m_element_start(element_start),
  4098. m_element_size(element_size),
  4099. m_trackEntries(NULL),
  4100. m_trackEntriesEnd(NULL) {}
  4101. long Tracks::Parse() {
  4102. assert(m_trackEntries == NULL);
  4103. assert(m_trackEntriesEnd == NULL);
  4104. const long long stop = m_start + m_size;
  4105. IMkvReader* const pReader = m_pSegment->m_pReader;
  4106. int count = 0;
  4107. long long pos = m_start;
  4108. while (pos < stop) {
  4109. long long id, size;
  4110. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  4111. if (status < 0) // error
  4112. return status;
  4113. if (size == 0) // weird
  4114. continue;
  4115. if (id == libwebm::kMkvTrackEntry)
  4116. ++count;
  4117. pos += size; // consume payload
  4118. if (pos > stop)
  4119. return E_FILE_FORMAT_INVALID;
  4120. }
  4121. if (pos != stop)
  4122. return E_FILE_FORMAT_INVALID;
  4123. if (count <= 0)
  4124. return 0; // success
  4125. m_trackEntries = new (std::nothrow) Track*[count];
  4126. if (m_trackEntries == NULL)
  4127. return -1;
  4128. m_trackEntriesEnd = m_trackEntries;
  4129. pos = m_start;
  4130. while (pos < stop) {
  4131. const long long element_start = pos;
  4132. long long id, payload_size;
  4133. const long status =
  4134. ParseElementHeader(pReader, pos, stop, id, payload_size);
  4135. if (status < 0) // error
  4136. return status;
  4137. if (payload_size == 0) // weird
  4138. continue;
  4139. const long long payload_stop = pos + payload_size;
  4140. assert(payload_stop <= stop); // checked in ParseElement
  4141. const long long element_size = payload_stop - element_start;
  4142. if (id == libwebm::kMkvTrackEntry) {
  4143. Track*& pTrack = *m_trackEntriesEnd;
  4144. pTrack = NULL;
  4145. const long status = ParseTrackEntry(pos, payload_size, element_start,
  4146. element_size, pTrack);
  4147. if (status)
  4148. return status;
  4149. if (pTrack)
  4150. ++m_trackEntriesEnd;
  4151. }
  4152. pos = payload_stop;
  4153. if (pos > stop)
  4154. return E_FILE_FORMAT_INVALID;
  4155. }
  4156. if (pos != stop)
  4157. return E_FILE_FORMAT_INVALID;
  4158. return 0; // success
  4159. }
  4160. unsigned long Tracks::GetTracksCount() const {
  4161. const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries;
  4162. assert(result >= 0);
  4163. return static_cast<unsigned long>(result);
  4164. }
  4165. long Tracks::ParseTrackEntry(long long track_start, long long track_size,
  4166. long long element_start, long long element_size,
  4167. Track*& pResult) const {
  4168. if (pResult)
  4169. return -1;
  4170. IMkvReader* const pReader = m_pSegment->m_pReader;
  4171. long long pos = track_start;
  4172. const long long track_stop = track_start + track_size;
  4173. Track::Info info;
  4174. info.type = 0;
  4175. info.number = 0;
  4176. info.uid = 0;
  4177. info.defaultDuration = 0;
  4178. Track::Settings v;
  4179. v.start = -1;
  4180. v.size = -1;
  4181. Track::Settings a;
  4182. a.start = -1;
  4183. a.size = -1;
  4184. Track::Settings e; // content_encodings_settings;
  4185. e.start = -1;
  4186. e.size = -1;
  4187. long long lacing = 1; // default is true
  4188. while (pos < track_stop) {
  4189. long long id, size;
  4190. const long status = ParseElementHeader(pReader, pos, track_stop, id, size);
  4191. if (status < 0) // error
  4192. return status;
  4193. if (size < 0)
  4194. return E_FILE_FORMAT_INVALID;
  4195. const long long start = pos;
  4196. if (id == libwebm::kMkvVideo) {
  4197. v.start = start;
  4198. v.size = size;
  4199. } else if (id == libwebm::kMkvAudio) {
  4200. a.start = start;
  4201. a.size = size;
  4202. } else if (id == libwebm::kMkvContentEncodings) {
  4203. e.start = start;
  4204. e.size = size;
  4205. } else if (id == libwebm::kMkvTrackUID) {
  4206. if (size > 8)
  4207. return E_FILE_FORMAT_INVALID;
  4208. info.uid = 0;
  4209. long long pos_ = start;
  4210. const long long pos_end = start + size;
  4211. while (pos_ != pos_end) {
  4212. unsigned char b;
  4213. const int status = pReader->Read(pos_, 1, &b);
  4214. if (status)
  4215. return status;
  4216. info.uid <<= 8;
  4217. info.uid |= b;
  4218. ++pos_;
  4219. }
  4220. } else if (id == libwebm::kMkvTrackNumber) {
  4221. const long long num = UnserializeUInt(pReader, pos, size);
  4222. if ((num <= 0) || (num > 127))
  4223. return E_FILE_FORMAT_INVALID;
  4224. info.number = static_cast<long>(num);
  4225. } else if (id == libwebm::kMkvTrackType) {
  4226. const long long type = UnserializeUInt(pReader, pos, size);
  4227. if ((type <= 0) || (type > 254))
  4228. return E_FILE_FORMAT_INVALID;
  4229. info.type = static_cast<long>(type);
  4230. } else if (id == libwebm::kMkvName) {
  4231. const long status =
  4232. UnserializeString(pReader, pos, size, info.nameAsUTF8);
  4233. if (status)
  4234. return status;
  4235. } else if (id == libwebm::kMkvLanguage) {
  4236. const long status = UnserializeString(pReader, pos, size, info.language);
  4237. if (status)
  4238. return status;
  4239. } else if (id == libwebm::kMkvDefaultDuration) {
  4240. const long long duration = UnserializeUInt(pReader, pos, size);
  4241. if (duration < 0)
  4242. return E_FILE_FORMAT_INVALID;
  4243. info.defaultDuration = static_cast<unsigned long long>(duration);
  4244. } else if (id == libwebm::kMkvCodecID) {
  4245. const long status = UnserializeString(pReader, pos, size, info.codecId);
  4246. if (status)
  4247. return status;
  4248. } else if (id == libwebm::kMkvFlagLacing) {
  4249. lacing = UnserializeUInt(pReader, pos, size);
  4250. if ((lacing < 0) || (lacing > 1))
  4251. return E_FILE_FORMAT_INVALID;
  4252. } else if (id == libwebm::kMkvCodecPrivate) {
  4253. delete[] info.codecPrivate;
  4254. info.codecPrivate = NULL;
  4255. info.codecPrivateSize = 0;
  4256. const size_t buflen = static_cast<size_t>(size);
  4257. if (buflen) {
  4258. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  4259. if (buf == NULL)
  4260. return -1;
  4261. const int status = pReader->Read(pos, static_cast<long>(buflen), buf);
  4262. if (status) {
  4263. delete[] buf;
  4264. return status;
  4265. }
  4266. info.codecPrivate = buf;
  4267. info.codecPrivateSize = buflen;
  4268. }
  4269. } else if (id == libwebm::kMkvCodecName) {
  4270. const long status =
  4271. UnserializeString(pReader, pos, size, info.codecNameAsUTF8);
  4272. if (status)
  4273. return status;
  4274. } else if (id == libwebm::kMkvCodecDelay) {
  4275. info.codecDelay = UnserializeUInt(pReader, pos, size);
  4276. } else if (id == libwebm::kMkvSeekPreRoll) {
  4277. info.seekPreRoll = UnserializeUInt(pReader, pos, size);
  4278. }
  4279. pos += size; // consume payload
  4280. if (pos > track_stop)
  4281. return E_FILE_FORMAT_INVALID;
  4282. }
  4283. if (pos != track_stop)
  4284. return E_FILE_FORMAT_INVALID;
  4285. if (info.number <= 0) // not specified
  4286. return E_FILE_FORMAT_INVALID;
  4287. if (GetTrackByNumber(info.number))
  4288. return E_FILE_FORMAT_INVALID;
  4289. if (info.type <= 0) // not specified
  4290. return E_FILE_FORMAT_INVALID;
  4291. info.lacing = (lacing > 0) ? true : false;
  4292. if (info.type == Track::kVideo) {
  4293. if (v.start < 0)
  4294. return E_FILE_FORMAT_INVALID;
  4295. if (a.start >= 0)
  4296. return E_FILE_FORMAT_INVALID;
  4297. info.settings = v;
  4298. VideoTrack* pTrack = NULL;
  4299. const long status = VideoTrack::Parse(m_pSegment, info, element_start,
  4300. element_size, pTrack);
  4301. if (status)
  4302. return status;
  4303. pResult = pTrack;
  4304. assert(pResult);
  4305. if (e.start >= 0)
  4306. pResult->ParseContentEncodingsEntry(e.start, e.size);
  4307. } else if (info.type == Track::kAudio) {
  4308. if (a.start < 0)
  4309. return E_FILE_FORMAT_INVALID;
  4310. if (v.start >= 0)
  4311. return E_FILE_FORMAT_INVALID;
  4312. info.settings = a;
  4313. AudioTrack* pTrack = NULL;
  4314. const long status = AudioTrack::Parse(m_pSegment, info, element_start,
  4315. element_size, pTrack);
  4316. if (status)
  4317. return status;
  4318. pResult = pTrack;
  4319. assert(pResult);
  4320. if (e.start >= 0)
  4321. pResult->ParseContentEncodingsEntry(e.start, e.size);
  4322. } else {
  4323. // neither video nor audio - probably metadata or subtitles
  4324. if (a.start >= 0)
  4325. return E_FILE_FORMAT_INVALID;
  4326. if (v.start >= 0)
  4327. return E_FILE_FORMAT_INVALID;
  4328. if (info.type == Track::kMetadata && e.start >= 0)
  4329. return E_FILE_FORMAT_INVALID;
  4330. info.settings.start = -1;
  4331. info.settings.size = 0;
  4332. Track* pTrack = NULL;
  4333. const long status =
  4334. Track::Create(m_pSegment, info, element_start, element_size, pTrack);
  4335. if (status)
  4336. return status;
  4337. pResult = pTrack;
  4338. assert(pResult);
  4339. }
  4340. return 0; // success
  4341. }
  4342. Tracks::~Tracks() {
  4343. Track** i = m_trackEntries;
  4344. Track** const j = m_trackEntriesEnd;
  4345. while (i != j) {
  4346. Track* const pTrack = *i++;
  4347. delete pTrack;
  4348. }
  4349. delete[] m_trackEntries;
  4350. }
  4351. const Track* Tracks::GetTrackByNumber(long tn) const {
  4352. if (tn < 0)
  4353. return NULL;
  4354. Track** i = m_trackEntries;
  4355. Track** const j = m_trackEntriesEnd;
  4356. while (i != j) {
  4357. Track* const pTrack = *i++;
  4358. if (pTrack == NULL)
  4359. continue;
  4360. if (tn == pTrack->GetNumber())
  4361. return pTrack;
  4362. }
  4363. return NULL; // not found
  4364. }
  4365. const Track* Tracks::GetTrackByIndex(unsigned long idx) const {
  4366. const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
  4367. if (idx >= static_cast<unsigned long>(count))
  4368. return NULL;
  4369. return m_trackEntries[idx];
  4370. }
  4371. long Cluster::Load(long long& pos, long& len) const {
  4372. if (m_pSegment == NULL)
  4373. return E_PARSE_FAILED;
  4374. if (m_timecode >= 0) // at least partially loaded
  4375. return 0;
  4376. if (m_pos != m_element_start || m_element_size >= 0)
  4377. return E_PARSE_FAILED;
  4378. IMkvReader* const pReader = m_pSegment->m_pReader;
  4379. long long total, avail;
  4380. const int status = pReader->Length(&total, &avail);
  4381. if (status < 0) // error
  4382. return status;
  4383. if (total >= 0 && (avail > total || m_pos > total))
  4384. return E_FILE_FORMAT_INVALID;
  4385. pos = m_pos;
  4386. long long cluster_size = -1;
  4387. if ((pos + 1) > avail) {
  4388. len = 1;
  4389. return E_BUFFER_NOT_FULL;
  4390. }
  4391. long long result = GetUIntLength(pReader, pos, len);
  4392. if (result < 0) // error or underflow
  4393. return static_cast<long>(result);
  4394. if (result > 0)
  4395. return E_BUFFER_NOT_FULL;
  4396. if ((pos + len) > avail)
  4397. return E_BUFFER_NOT_FULL;
  4398. const long long id_ = ReadID(pReader, pos, len);
  4399. if (id_ < 0) // error
  4400. return static_cast<long>(id_);
  4401. if (id_ != libwebm::kMkvCluster)
  4402. return E_FILE_FORMAT_INVALID;
  4403. pos += len; // consume id
  4404. // read cluster size
  4405. if ((pos + 1) > avail) {
  4406. len = 1;
  4407. return E_BUFFER_NOT_FULL;
  4408. }
  4409. result = GetUIntLength(pReader, pos, len);
  4410. if (result < 0) // error
  4411. return static_cast<long>(result);
  4412. if (result > 0)
  4413. return E_BUFFER_NOT_FULL;
  4414. if ((pos + len) > avail)
  4415. return E_BUFFER_NOT_FULL;
  4416. const long long size = ReadUInt(pReader, pos, len);
  4417. if (size < 0) // error
  4418. return static_cast<long>(cluster_size);
  4419. if (size == 0)
  4420. return E_FILE_FORMAT_INVALID;
  4421. pos += len; // consume length of size of element
  4422. const long long unknown_size = (1LL << (7 * len)) - 1;
  4423. if (size != unknown_size)
  4424. cluster_size = size;
  4425. // pos points to start of payload
  4426. long long timecode = -1;
  4427. long long new_pos = -1;
  4428. bool bBlock = false;
  4429. long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
  4430. for (;;) {
  4431. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  4432. break;
  4433. // Parse ID
  4434. if ((pos + 1) > avail) {
  4435. len = 1;
  4436. return E_BUFFER_NOT_FULL;
  4437. }
  4438. long long result = GetUIntLength(pReader, pos, len);
  4439. if (result < 0) // error
  4440. return static_cast<long>(result);
  4441. if (result > 0)
  4442. return E_BUFFER_NOT_FULL;
  4443. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4444. return E_FILE_FORMAT_INVALID;
  4445. if ((pos + len) > avail)
  4446. return E_BUFFER_NOT_FULL;
  4447. const long long id = ReadID(pReader, pos, len);
  4448. if (id < 0) // error
  4449. return static_cast<long>(id);
  4450. if (id == 0)
  4451. return E_FILE_FORMAT_INVALID;
  4452. // This is the distinguished set of ID's we use to determine
  4453. // that we have exhausted the sub-element's inside the cluster
  4454. // whose ID we parsed earlier.
  4455. if (id == libwebm::kMkvCluster)
  4456. break;
  4457. if (id == libwebm::kMkvCues)
  4458. break;
  4459. pos += len; // consume ID field
  4460. // Parse Size
  4461. if ((pos + 1) > avail) {
  4462. len = 1;
  4463. return E_BUFFER_NOT_FULL;
  4464. }
  4465. result = GetUIntLength(pReader, pos, len);
  4466. if (result < 0) // error
  4467. return static_cast<long>(result);
  4468. if (result > 0)
  4469. return E_BUFFER_NOT_FULL;
  4470. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4471. return E_FILE_FORMAT_INVALID;
  4472. if ((pos + len) > avail)
  4473. return E_BUFFER_NOT_FULL;
  4474. const long long size = ReadUInt(pReader, pos, len);
  4475. if (size < 0) // error
  4476. return static_cast<long>(size);
  4477. const long long unknown_size = (1LL << (7 * len)) - 1;
  4478. if (size == unknown_size)
  4479. return E_FILE_FORMAT_INVALID;
  4480. pos += len; // consume size field
  4481. if ((cluster_stop >= 0) && (pos > cluster_stop))
  4482. return E_FILE_FORMAT_INVALID;
  4483. // pos now points to start of payload
  4484. if (size == 0)
  4485. continue;
  4486. if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
  4487. return E_FILE_FORMAT_INVALID;
  4488. if (id == libwebm::kMkvTimecode) {
  4489. len = static_cast<long>(size);
  4490. if ((pos + size) > avail)
  4491. return E_BUFFER_NOT_FULL;
  4492. timecode = UnserializeUInt(pReader, pos, size);
  4493. if (timecode < 0) // error (or underflow)
  4494. return static_cast<long>(timecode);
  4495. new_pos = pos + size;
  4496. if (bBlock)
  4497. break;
  4498. } else if (id == libwebm::kMkvBlockGroup) {
  4499. bBlock = true;
  4500. break;
  4501. } else if (id == libwebm::kMkvSimpleBlock) {
  4502. bBlock = true;
  4503. break;
  4504. }
  4505. pos += size; // consume payload
  4506. if (cluster_stop >= 0 && pos > cluster_stop)
  4507. return E_FILE_FORMAT_INVALID;
  4508. }
  4509. if (cluster_stop >= 0 && pos > cluster_stop)
  4510. return E_FILE_FORMAT_INVALID;
  4511. if (timecode < 0) // no timecode found
  4512. return E_FILE_FORMAT_INVALID;
  4513. if (!bBlock)
  4514. return E_FILE_FORMAT_INVALID;
  4515. m_pos = new_pos; // designates position just beyond timecode payload
  4516. m_timecode = timecode; // m_timecode >= 0 means we're partially loaded
  4517. if (cluster_size >= 0)
  4518. m_element_size = cluster_stop - m_element_start;
  4519. return 0;
  4520. }
  4521. long Cluster::Parse(long long& pos, long& len) const {
  4522. long status = Load(pos, len);
  4523. if (status < 0)
  4524. return status;
  4525. if (m_pos < m_element_start || m_timecode < 0)
  4526. return E_PARSE_FAILED;
  4527. const long long cluster_stop =
  4528. (m_element_size < 0) ? -1 : m_element_start + m_element_size;
  4529. if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
  4530. return 1; // nothing else to do
  4531. IMkvReader* const pReader = m_pSegment->m_pReader;
  4532. long long total, avail;
  4533. status = pReader->Length(&total, &avail);
  4534. if (status < 0) // error
  4535. return status;
  4536. if (total >= 0 && avail > total)
  4537. return E_FILE_FORMAT_INVALID;
  4538. pos = m_pos;
  4539. for (;;) {
  4540. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  4541. break;
  4542. if ((total >= 0) && (pos >= total)) {
  4543. if (m_element_size < 0)
  4544. m_element_size = pos - m_element_start;
  4545. break;
  4546. }
  4547. // Parse ID
  4548. if ((pos + 1) > avail) {
  4549. len = 1;
  4550. return E_BUFFER_NOT_FULL;
  4551. }
  4552. long long result = GetUIntLength(pReader, pos, len);
  4553. if (result < 0) // error
  4554. return static_cast<long>(result);
  4555. if (result > 0)
  4556. return E_BUFFER_NOT_FULL;
  4557. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4558. return E_FILE_FORMAT_INVALID;
  4559. if ((pos + len) > avail)
  4560. return E_BUFFER_NOT_FULL;
  4561. const long long id = ReadID(pReader, pos, len);
  4562. if (id < 0)
  4563. return E_FILE_FORMAT_INVALID;
  4564. // This is the distinguished set of ID's we use to determine
  4565. // that we have exhausted the sub-element's inside the cluster
  4566. // whose ID we parsed earlier.
  4567. if ((id == libwebm::kMkvCluster) || (id == libwebm::kMkvCues)) {
  4568. if (m_element_size < 0)
  4569. m_element_size = pos - m_element_start;
  4570. break;
  4571. }
  4572. pos += len; // consume ID field
  4573. // Parse Size
  4574. if ((pos + 1) > avail) {
  4575. len = 1;
  4576. return E_BUFFER_NOT_FULL;
  4577. }
  4578. result = GetUIntLength(pReader, pos, len);
  4579. if (result < 0) // error
  4580. return static_cast<long>(result);
  4581. if (result > 0)
  4582. return E_BUFFER_NOT_FULL;
  4583. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4584. return E_FILE_FORMAT_INVALID;
  4585. if ((pos + len) > avail)
  4586. return E_BUFFER_NOT_FULL;
  4587. const long long size = ReadUInt(pReader, pos, len);
  4588. if (size < 0) // error
  4589. return static_cast<long>(size);
  4590. const long long unknown_size = (1LL << (7 * len)) - 1;
  4591. if (size == unknown_size)
  4592. return E_FILE_FORMAT_INVALID;
  4593. pos += len; // consume size field
  4594. if ((cluster_stop >= 0) && (pos > cluster_stop))
  4595. return E_FILE_FORMAT_INVALID;
  4596. // pos now points to start of payload
  4597. if (size == 0)
  4598. continue;
  4599. // const long long block_start = pos;
  4600. const long long block_stop = pos + size;
  4601. if (cluster_stop >= 0) {
  4602. if (block_stop > cluster_stop) {
  4603. if (id == libwebm::kMkvBlockGroup || id == libwebm::kMkvSimpleBlock) {
  4604. return E_FILE_FORMAT_INVALID;
  4605. }
  4606. pos = cluster_stop;
  4607. break;
  4608. }
  4609. } else if ((total >= 0) && (block_stop > total)) {
  4610. m_element_size = total - m_element_start;
  4611. pos = total;
  4612. break;
  4613. } else if (block_stop > avail) {
  4614. len = static_cast<long>(size);
  4615. return E_BUFFER_NOT_FULL;
  4616. }
  4617. Cluster* const this_ = const_cast<Cluster*>(this);
  4618. if (id == libwebm::kMkvBlockGroup)
  4619. return this_->ParseBlockGroup(size, pos, len);
  4620. if (id == libwebm::kMkvSimpleBlock)
  4621. return this_->ParseSimpleBlock(size, pos, len);
  4622. pos += size; // consume payload
  4623. if (cluster_stop >= 0 && pos > cluster_stop)
  4624. return E_FILE_FORMAT_INVALID;
  4625. }
  4626. if (m_element_size < 1)
  4627. return E_FILE_FORMAT_INVALID;
  4628. m_pos = pos;
  4629. if (cluster_stop >= 0 && m_pos > cluster_stop)
  4630. return E_FILE_FORMAT_INVALID;
  4631. if (m_entries_count > 0) {
  4632. const long idx = m_entries_count - 1;
  4633. const BlockEntry* const pLast = m_entries[idx];
  4634. if (pLast == NULL)
  4635. return E_PARSE_FAILED;
  4636. const Block* const pBlock = pLast->GetBlock();
  4637. if (pBlock == NULL)
  4638. return E_PARSE_FAILED;
  4639. const long long start = pBlock->m_start;
  4640. if ((total >= 0) && (start > total))
  4641. return E_PARSE_FAILED; // defend against trucated stream
  4642. const long long size = pBlock->m_size;
  4643. const long long stop = start + size;
  4644. if (cluster_stop >= 0 && stop > cluster_stop)
  4645. return E_FILE_FORMAT_INVALID;
  4646. if ((total >= 0) && (stop > total))
  4647. return E_PARSE_FAILED; // defend against trucated stream
  4648. }
  4649. return 1; // no more entries
  4650. }
  4651. long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
  4652. long& len) {
  4653. const long long block_start = pos;
  4654. const long long block_stop = pos + block_size;
  4655. IMkvReader* const pReader = m_pSegment->m_pReader;
  4656. long long total, avail;
  4657. long status = pReader->Length(&total, &avail);
  4658. if (status < 0) // error
  4659. return status;
  4660. assert((total < 0) || (avail <= total));
  4661. // parse track number
  4662. if ((pos + 1) > avail) {
  4663. len = 1;
  4664. return E_BUFFER_NOT_FULL;
  4665. }
  4666. long long result = GetUIntLength(pReader, pos, len);
  4667. if (result < 0) // error
  4668. return static_cast<long>(result);
  4669. if (result > 0) // weird
  4670. return E_BUFFER_NOT_FULL;
  4671. if ((pos + len) > block_stop)
  4672. return E_FILE_FORMAT_INVALID;
  4673. if ((pos + len) > avail)
  4674. return E_BUFFER_NOT_FULL;
  4675. const long long track = ReadUInt(pReader, pos, len);
  4676. if (track < 0) // error
  4677. return static_cast<long>(track);
  4678. if (track == 0)
  4679. return E_FILE_FORMAT_INVALID;
  4680. pos += len; // consume track number
  4681. if ((pos + 2) > block_stop)
  4682. return E_FILE_FORMAT_INVALID;
  4683. if ((pos + 2) > avail) {
  4684. len = 2;
  4685. return E_BUFFER_NOT_FULL;
  4686. }
  4687. pos += 2; // consume timecode
  4688. if ((pos + 1) > block_stop)
  4689. return E_FILE_FORMAT_INVALID;
  4690. if ((pos + 1) > avail) {
  4691. len = 1;
  4692. return E_BUFFER_NOT_FULL;
  4693. }
  4694. unsigned char flags;
  4695. status = pReader->Read(pos, 1, &flags);
  4696. if (status < 0) { // error or underflow
  4697. len = 1;
  4698. return status;
  4699. }
  4700. ++pos; // consume flags byte
  4701. assert(pos <= avail);
  4702. if (pos >= block_stop)
  4703. return E_FILE_FORMAT_INVALID;
  4704. const int lacing = int(flags & 0x06) >> 1;
  4705. if ((lacing != 0) && (block_stop > avail)) {
  4706. len = static_cast<long>(block_stop - pos);
  4707. return E_BUFFER_NOT_FULL;
  4708. }
  4709. status = CreateBlock(libwebm::kMkvSimpleBlock, block_start, block_size,
  4710. 0); // DiscardPadding
  4711. if (status != 0)
  4712. return status;
  4713. m_pos = block_stop;
  4714. return 0; // success
  4715. }
  4716. long Cluster::ParseBlockGroup(long long payload_size, long long& pos,
  4717. long& len) {
  4718. const long long payload_start = pos;
  4719. const long long payload_stop = pos + payload_size;
  4720. IMkvReader* const pReader = m_pSegment->m_pReader;
  4721. long long total, avail;
  4722. long status = pReader->Length(&total, &avail);
  4723. if (status < 0) // error
  4724. return status;
  4725. assert((total < 0) || (avail <= total));
  4726. if ((total >= 0) && (payload_stop > total))
  4727. return E_FILE_FORMAT_INVALID;
  4728. if (payload_stop > avail) {
  4729. len = static_cast<long>(payload_size);
  4730. return E_BUFFER_NOT_FULL;
  4731. }
  4732. long long discard_padding = 0;
  4733. while (pos < payload_stop) {
  4734. // parse sub-block element ID
  4735. if ((pos + 1) > avail) {
  4736. len = 1;
  4737. return E_BUFFER_NOT_FULL;
  4738. }
  4739. long long result = GetUIntLength(pReader, pos, len);
  4740. if (result < 0) // error
  4741. return static_cast<long>(result);
  4742. if (result > 0) // weird
  4743. return E_BUFFER_NOT_FULL;
  4744. if ((pos + len) > payload_stop)
  4745. return E_FILE_FORMAT_INVALID;
  4746. if ((pos + len) > avail)
  4747. return E_BUFFER_NOT_FULL;
  4748. const long long id = ReadID(pReader, pos, len);
  4749. if (id < 0) // error
  4750. return static_cast<long>(id);
  4751. if (id == 0) // not a valid ID
  4752. return E_FILE_FORMAT_INVALID;
  4753. pos += len; // consume ID field
  4754. // Parse Size
  4755. if ((pos + 1) > avail) {
  4756. len = 1;
  4757. return E_BUFFER_NOT_FULL;
  4758. }
  4759. result = GetUIntLength(pReader, pos, len);
  4760. if (result < 0) // error
  4761. return static_cast<long>(result);
  4762. if (result > 0) // weird
  4763. return E_BUFFER_NOT_FULL;
  4764. if ((pos + len) > payload_stop)
  4765. return E_FILE_FORMAT_INVALID;
  4766. if ((pos + len) > avail)
  4767. return E_BUFFER_NOT_FULL;
  4768. const long long size = ReadUInt(pReader, pos, len);
  4769. if (size < 0) // error
  4770. return static_cast<long>(size);
  4771. pos += len; // consume size field
  4772. // pos now points to start of sub-block group payload
  4773. if (pos > payload_stop)
  4774. return E_FILE_FORMAT_INVALID;
  4775. if (size == 0) // weird
  4776. continue;
  4777. const long long unknown_size = (1LL << (7 * len)) - 1;
  4778. if (size == unknown_size)
  4779. return E_FILE_FORMAT_INVALID;
  4780. if (id == libwebm::kMkvDiscardPadding) {
  4781. status = UnserializeInt(pReader, pos, size, discard_padding);
  4782. if (status < 0) // error
  4783. return status;
  4784. }
  4785. if (id != libwebm::kMkvBlock) {
  4786. pos += size; // consume sub-part of block group
  4787. if (pos > payload_stop)
  4788. return E_FILE_FORMAT_INVALID;
  4789. continue;
  4790. }
  4791. const long long block_stop = pos + size;
  4792. if (block_stop > payload_stop)
  4793. return E_FILE_FORMAT_INVALID;
  4794. // parse track number
  4795. if ((pos + 1) > avail) {
  4796. len = 1;
  4797. return E_BUFFER_NOT_FULL;
  4798. }
  4799. result = GetUIntLength(pReader, pos, len);
  4800. if (result < 0) // error
  4801. return static_cast<long>(result);
  4802. if (result > 0) // weird
  4803. return E_BUFFER_NOT_FULL;
  4804. if ((pos + len) > block_stop)
  4805. return E_FILE_FORMAT_INVALID;
  4806. if ((pos + len) > avail)
  4807. return E_BUFFER_NOT_FULL;
  4808. const long long track = ReadUInt(pReader, pos, len);
  4809. if (track < 0) // error
  4810. return static_cast<long>(track);
  4811. if (track == 0)
  4812. return E_FILE_FORMAT_INVALID;
  4813. pos += len; // consume track number
  4814. if ((pos + 2) > block_stop)
  4815. return E_FILE_FORMAT_INVALID;
  4816. if ((pos + 2) > avail) {
  4817. len = 2;
  4818. return E_BUFFER_NOT_FULL;
  4819. }
  4820. pos += 2; // consume timecode
  4821. if ((pos + 1) > block_stop)
  4822. return E_FILE_FORMAT_INVALID;
  4823. if ((pos + 1) > avail) {
  4824. len = 1;
  4825. return E_BUFFER_NOT_FULL;
  4826. }
  4827. unsigned char flags;
  4828. status = pReader->Read(pos, 1, &flags);
  4829. if (status < 0) { // error or underflow
  4830. len = 1;
  4831. return status;
  4832. }
  4833. ++pos; // consume flags byte
  4834. assert(pos <= avail);
  4835. if (pos >= block_stop)
  4836. return E_FILE_FORMAT_INVALID;
  4837. const int lacing = int(flags & 0x06) >> 1;
  4838. if ((lacing != 0) && (block_stop > avail)) {
  4839. len = static_cast<long>(block_stop - pos);
  4840. return E_BUFFER_NOT_FULL;
  4841. }
  4842. pos = block_stop; // consume block-part of block group
  4843. if (pos > payload_stop)
  4844. return E_FILE_FORMAT_INVALID;
  4845. }
  4846. if (pos != payload_stop)
  4847. return E_FILE_FORMAT_INVALID;
  4848. status = CreateBlock(libwebm::kMkvBlockGroup, payload_start, payload_size,
  4849. discard_padding);
  4850. if (status != 0)
  4851. return status;
  4852. m_pos = payload_stop;
  4853. return 0; // success
  4854. }
  4855. long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const {
  4856. assert(m_pos >= m_element_start);
  4857. pEntry = NULL;
  4858. if (index < 0)
  4859. return -1; // generic error
  4860. if (m_entries_count < 0)
  4861. return E_BUFFER_NOT_FULL;
  4862. assert(m_entries);
  4863. assert(m_entries_size > 0);
  4864. assert(m_entries_count <= m_entries_size);
  4865. if (index < m_entries_count) {
  4866. pEntry = m_entries[index];
  4867. assert(pEntry);
  4868. return 1; // found entry
  4869. }
  4870. if (m_element_size < 0) // we don't know cluster end yet
  4871. return E_BUFFER_NOT_FULL; // underflow
  4872. const long long element_stop = m_element_start + m_element_size;
  4873. if (m_pos >= element_stop)
  4874. return 0; // nothing left to parse
  4875. return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed
  4876. }
  4877. Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) {
  4878. if (!pSegment || off < 0)
  4879. return NULL;
  4880. const long long element_start = pSegment->m_start + off;
  4881. Cluster* const pCluster =
  4882. new (std::nothrow) Cluster(pSegment, idx, element_start);
  4883. return pCluster;
  4884. }
  4885. Cluster::Cluster()
  4886. : m_pSegment(NULL),
  4887. m_element_start(0),
  4888. m_index(0),
  4889. m_pos(0),
  4890. m_element_size(0),
  4891. m_timecode(0),
  4892. m_entries(NULL),
  4893. m_entries_size(0),
  4894. m_entries_count(0) // means "no entries"
  4895. {}
  4896. Cluster::Cluster(Segment* pSegment, long idx, long long element_start
  4897. /* long long element_size */)
  4898. : m_pSegment(pSegment),
  4899. m_element_start(element_start),
  4900. m_index(idx),
  4901. m_pos(element_start),
  4902. m_element_size(-1 /* element_size */),
  4903. m_timecode(-1),
  4904. m_entries(NULL),
  4905. m_entries_size(0),
  4906. m_entries_count(-1) // means "has not been parsed yet"
  4907. {}
  4908. Cluster::~Cluster() {
  4909. if (m_entries_count <= 0) {
  4910. delete[] m_entries;
  4911. return;
  4912. }
  4913. BlockEntry** i = m_entries;
  4914. BlockEntry** const j = m_entries + m_entries_count;
  4915. while (i != j) {
  4916. BlockEntry* p = *i++;
  4917. assert(p);
  4918. delete p;
  4919. }
  4920. delete[] m_entries;
  4921. }
  4922. bool Cluster::EOS() const { return (m_pSegment == NULL); }
  4923. long Cluster::GetIndex() const { return m_index; }
  4924. long long Cluster::GetPosition() const {
  4925. const long long pos = m_element_start - m_pSegment->m_start;
  4926. assert(pos >= 0);
  4927. return pos;
  4928. }
  4929. long long Cluster::GetElementSize() const { return m_element_size; }
  4930. long Cluster::HasBlockEntries(
  4931. const Segment* pSegment,
  4932. long long off, // relative to start of segment payload
  4933. long long& pos, long& len) {
  4934. assert(pSegment);
  4935. assert(off >= 0); // relative to segment
  4936. IMkvReader* const pReader = pSegment->m_pReader;
  4937. long long total, avail;
  4938. long status = pReader->Length(&total, &avail);
  4939. if (status < 0) // error
  4940. return status;
  4941. assert((total < 0) || (avail <= total));
  4942. pos = pSegment->m_start + off; // absolute
  4943. if ((total >= 0) && (pos >= total))
  4944. return 0; // we don't even have a complete cluster
  4945. const long long segment_stop =
  4946. (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size;
  4947. long long cluster_stop = -1; // interpreted later to mean "unknown size"
  4948. {
  4949. if ((pos + 1) > avail) {
  4950. len = 1;
  4951. return E_BUFFER_NOT_FULL;
  4952. }
  4953. long long result = GetUIntLength(pReader, pos, len);
  4954. if (result < 0) // error
  4955. return static_cast<long>(result);
  4956. if (result > 0) // need more data
  4957. return E_BUFFER_NOT_FULL;
  4958. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  4959. return E_FILE_FORMAT_INVALID;
  4960. if ((total >= 0) && ((pos + len) > total))
  4961. return 0;
  4962. if ((pos + len) > avail)
  4963. return E_BUFFER_NOT_FULL;
  4964. const long long id = ReadID(pReader, pos, len);
  4965. if (id < 0) // error
  4966. return static_cast<long>(id);
  4967. if (id != libwebm::kMkvCluster)
  4968. return E_PARSE_FAILED;
  4969. pos += len; // consume Cluster ID field
  4970. // read size field
  4971. if ((pos + 1) > avail) {
  4972. len = 1;
  4973. return E_BUFFER_NOT_FULL;
  4974. }
  4975. result = GetUIntLength(pReader, pos, len);
  4976. if (result < 0) // error
  4977. return static_cast<long>(result);
  4978. if (result > 0) // weird
  4979. return E_BUFFER_NOT_FULL;
  4980. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  4981. return E_FILE_FORMAT_INVALID;
  4982. if ((total >= 0) && ((pos + len) > total))
  4983. return 0;
  4984. if ((pos + len) > avail)
  4985. return E_BUFFER_NOT_FULL;
  4986. const long long size = ReadUInt(pReader, pos, len);
  4987. if (size < 0) // error
  4988. return static_cast<long>(size);
  4989. if (size == 0)
  4990. return 0; // cluster does not have entries
  4991. pos += len; // consume size field
  4992. // pos now points to start of payload
  4993. const long long unknown_size = (1LL << (7 * len)) - 1;
  4994. if (size != unknown_size) {
  4995. cluster_stop = pos + size;
  4996. assert(cluster_stop >= 0);
  4997. if ((segment_stop >= 0) && (cluster_stop > segment_stop))
  4998. return E_FILE_FORMAT_INVALID;
  4999. if ((total >= 0) && (cluster_stop > total))
  5000. // return E_FILE_FORMAT_INVALID; //too conservative
  5001. return 0; // cluster does not have any entries
  5002. }
  5003. }
  5004. for (;;) {
  5005. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  5006. return 0; // no entries detected
  5007. if ((pos + 1) > avail) {
  5008. len = 1;
  5009. return E_BUFFER_NOT_FULL;
  5010. }
  5011. long long result = GetUIntLength(pReader, pos, len);
  5012. if (result < 0) // error
  5013. return static_cast<long>(result);
  5014. if (result > 0) // need more data
  5015. return E_BUFFER_NOT_FULL;
  5016. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  5017. return E_FILE_FORMAT_INVALID;
  5018. if ((pos + len) > avail)
  5019. return E_BUFFER_NOT_FULL;
  5020. const long long id = ReadID(pReader, pos, len);
  5021. if (id < 0) // error
  5022. return static_cast<long>(id);
  5023. // This is the distinguished set of ID's we use to determine
  5024. // that we have exhausted the sub-element's inside the cluster
  5025. // whose ID we parsed earlier.
  5026. if (id == libwebm::kMkvCluster)
  5027. return 0; // no entries found
  5028. if (id == libwebm::kMkvCues)
  5029. return 0; // no entries found
  5030. pos += len; // consume id field
  5031. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  5032. return E_FILE_FORMAT_INVALID;
  5033. // read size field
  5034. if ((pos + 1) > avail) {
  5035. len = 1;
  5036. return E_BUFFER_NOT_FULL;
  5037. }
  5038. result = GetUIntLength(pReader, pos, len);
  5039. if (result < 0) // error
  5040. return static_cast<long>(result);
  5041. if (result > 0) // underflow
  5042. return E_BUFFER_NOT_FULL;
  5043. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  5044. return E_FILE_FORMAT_INVALID;
  5045. if ((pos + len) > avail)
  5046. return E_BUFFER_NOT_FULL;
  5047. const long long size = ReadUInt(pReader, pos, len);
  5048. if (size < 0) // error
  5049. return static_cast<long>(size);
  5050. pos += len; // consume size field
  5051. // pos now points to start of payload
  5052. if ((cluster_stop >= 0) && (pos > cluster_stop))
  5053. return E_FILE_FORMAT_INVALID;
  5054. if (size == 0) // weird
  5055. continue;
  5056. const long long unknown_size = (1LL << (7 * len)) - 1;
  5057. if (size == unknown_size)
  5058. return E_FILE_FORMAT_INVALID; // not supported inside cluster
  5059. if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
  5060. return E_FILE_FORMAT_INVALID;
  5061. if (id == libwebm::kMkvBlockGroup)
  5062. return 1; // have at least one entry
  5063. if (id == libwebm::kMkvSimpleBlock)
  5064. return 1; // have at least one entry
  5065. pos += size; // consume payload
  5066. if (cluster_stop >= 0 && pos > cluster_stop)
  5067. return E_FILE_FORMAT_INVALID;
  5068. }
  5069. }
  5070. long long Cluster::GetTimeCode() const {
  5071. long long pos;
  5072. long len;
  5073. const long status = Load(pos, len);
  5074. if (status < 0) // error
  5075. return status;
  5076. return m_timecode;
  5077. }
  5078. long long Cluster::GetTime() const {
  5079. const long long tc = GetTimeCode();
  5080. if (tc < 0)
  5081. return tc;
  5082. const SegmentInfo* const pInfo = m_pSegment->GetInfo();
  5083. assert(pInfo);
  5084. const long long scale = pInfo->GetTimeCodeScale();
  5085. assert(scale >= 1);
  5086. const long long t = m_timecode * scale;
  5087. return t;
  5088. }
  5089. long long Cluster::GetFirstTime() const {
  5090. const BlockEntry* pEntry;
  5091. const long status = GetFirst(pEntry);
  5092. if (status < 0) // error
  5093. return status;
  5094. if (pEntry == NULL) // empty cluster
  5095. return GetTime();
  5096. const Block* const pBlock = pEntry->GetBlock();
  5097. assert(pBlock);
  5098. return pBlock->GetTime(this);
  5099. }
  5100. long long Cluster::GetLastTime() const {
  5101. const BlockEntry* pEntry;
  5102. const long status = GetLast(pEntry);
  5103. if (status < 0) // error
  5104. return status;
  5105. if (pEntry == NULL) // empty cluster
  5106. return GetTime();
  5107. const Block* const pBlock = pEntry->GetBlock();
  5108. assert(pBlock);
  5109. return pBlock->GetTime(this);
  5110. }
  5111. long Cluster::CreateBlock(long long id,
  5112. long long pos, // absolute pos of payload
  5113. long long size, long long discard_padding) {
  5114. if (id != libwebm::kMkvBlockGroup && id != libwebm::kMkvSimpleBlock)
  5115. return E_PARSE_FAILED;
  5116. if (m_entries_count < 0) { // haven't parsed anything yet
  5117. assert(m_entries == NULL);
  5118. assert(m_entries_size == 0);
  5119. m_entries_size = 1024;
  5120. m_entries = new (std::nothrow) BlockEntry*[m_entries_size];
  5121. if (m_entries == NULL)
  5122. return -1;
  5123. m_entries_count = 0;
  5124. } else {
  5125. assert(m_entries);
  5126. assert(m_entries_size > 0);
  5127. assert(m_entries_count <= m_entries_size);
  5128. if (m_entries_count >= m_entries_size) {
  5129. const long entries_size = 2 * m_entries_size;
  5130. BlockEntry** const entries = new (std::nothrow) BlockEntry*[entries_size];
  5131. if (entries == NULL)
  5132. return -1;
  5133. BlockEntry** src = m_entries;
  5134. BlockEntry** const src_end = src + m_entries_count;
  5135. BlockEntry** dst = entries;
  5136. while (src != src_end)
  5137. *dst++ = *src++;
  5138. delete[] m_entries;
  5139. m_entries = entries;
  5140. m_entries_size = entries_size;
  5141. }
  5142. }
  5143. if (id == libwebm::kMkvBlockGroup)
  5144. return CreateBlockGroup(pos, size, discard_padding);
  5145. else
  5146. return CreateSimpleBlock(pos, size);
  5147. }
  5148. long Cluster::CreateBlockGroup(long long start_offset, long long size,
  5149. long long discard_padding) {
  5150. assert(m_entries);
  5151. assert(m_entries_size > 0);
  5152. assert(m_entries_count >= 0);
  5153. assert(m_entries_count < m_entries_size);
  5154. IMkvReader* const pReader = m_pSegment->m_pReader;
  5155. long long pos = start_offset;
  5156. const long long stop = start_offset + size;
  5157. // For WebM files, there is a bias towards previous reference times
  5158. //(in order to support alt-ref frames, which refer back to the previous
  5159. // keyframe). Normally a 0 value is not possible, but here we tenatively
  5160. // allow 0 as the value of a reference frame, with the interpretation
  5161. // that this is a "previous" reference time.
  5162. long long prev = 1; // nonce
  5163. long long next = 0; // nonce
  5164. long long duration = -1; // really, this is unsigned
  5165. long long bpos = -1;
  5166. long long bsize = -1;
  5167. while (pos < stop) {
  5168. long len;
  5169. const long long id = ReadID(pReader, pos, len);
  5170. if (id < 0 || (pos + len) > stop)
  5171. return E_FILE_FORMAT_INVALID;
  5172. pos += len; // consume ID
  5173. const long long size = ReadUInt(pReader, pos, len);
  5174. assert(size >= 0); // TODO
  5175. assert((pos + len) <= stop);
  5176. pos += len; // consume size
  5177. if (id == libwebm::kMkvBlock) {
  5178. if (bpos < 0) { // Block ID
  5179. bpos = pos;
  5180. bsize = size;
  5181. }
  5182. } else if (id == libwebm::kMkvBlockDuration) {
  5183. if (size > 8)
  5184. return E_FILE_FORMAT_INVALID;
  5185. duration = UnserializeUInt(pReader, pos, size);
  5186. if (duration < 0)
  5187. return E_FILE_FORMAT_INVALID;
  5188. } else if (id == libwebm::kMkvReferenceBlock) {
  5189. if (size > 8 || size <= 0)
  5190. return E_FILE_FORMAT_INVALID;
  5191. const long size_ = static_cast<long>(size);
  5192. long long time;
  5193. long status = UnserializeInt(pReader, pos, size_, time);
  5194. assert(status == 0);
  5195. if (status != 0)
  5196. return -1;
  5197. if (time <= 0) // see note above
  5198. prev = time;
  5199. else
  5200. next = time;
  5201. }
  5202. pos += size; // consume payload
  5203. if (pos > stop)
  5204. return E_FILE_FORMAT_INVALID;
  5205. }
  5206. if (bpos < 0)
  5207. return E_FILE_FORMAT_INVALID;
  5208. if (pos != stop)
  5209. return E_FILE_FORMAT_INVALID;
  5210. assert(bsize >= 0);
  5211. const long idx = m_entries_count;
  5212. BlockEntry** const ppEntry = m_entries + idx;
  5213. BlockEntry*& pEntry = *ppEntry;
  5214. pEntry = new (std::nothrow)
  5215. BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding);
  5216. if (pEntry == NULL)
  5217. return -1; // generic error
  5218. BlockGroup* const p = static_cast<BlockGroup*>(pEntry);
  5219. const long status = p->Parse();
  5220. if (status == 0) { // success
  5221. ++m_entries_count;
  5222. return 0;
  5223. }
  5224. delete pEntry;
  5225. pEntry = 0;
  5226. return status;
  5227. }
  5228. long Cluster::CreateSimpleBlock(long long st, long long sz) {
  5229. assert(m_entries);
  5230. assert(m_entries_size > 0);
  5231. assert(m_entries_count >= 0);
  5232. assert(m_entries_count < m_entries_size);
  5233. const long idx = m_entries_count;
  5234. BlockEntry** const ppEntry = m_entries + idx;
  5235. BlockEntry*& pEntry = *ppEntry;
  5236. pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz);
  5237. if (pEntry == NULL)
  5238. return -1; // generic error
  5239. SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry);
  5240. const long status = p->Parse();
  5241. if (status == 0) {
  5242. ++m_entries_count;
  5243. return 0;
  5244. }
  5245. delete pEntry;
  5246. pEntry = 0;
  5247. return status;
  5248. }
  5249. long Cluster::GetFirst(const BlockEntry*& pFirst) const {
  5250. if (m_entries_count <= 0) {
  5251. long long pos;
  5252. long len;
  5253. const long status = Parse(pos, len);
  5254. if (status < 0) { // error
  5255. pFirst = NULL;
  5256. return status;
  5257. }
  5258. if (m_entries_count <= 0) { // empty cluster
  5259. pFirst = NULL;
  5260. return 0;
  5261. }
  5262. }
  5263. assert(m_entries);
  5264. pFirst = m_entries[0];
  5265. assert(pFirst);
  5266. return 0; // success
  5267. }
  5268. long Cluster::GetLast(const BlockEntry*& pLast) const {
  5269. for (;;) {
  5270. long long pos;
  5271. long len;
  5272. const long status = Parse(pos, len);
  5273. if (status < 0) { // error
  5274. pLast = NULL;
  5275. return status;
  5276. }
  5277. if (status > 0) // no new block
  5278. break;
  5279. }
  5280. if (m_entries_count <= 0) {
  5281. pLast = NULL;
  5282. return 0;
  5283. }
  5284. assert(m_entries);
  5285. const long idx = m_entries_count - 1;
  5286. pLast = m_entries[idx];
  5287. assert(pLast);
  5288. return 0;
  5289. }
  5290. long Cluster::GetNext(const BlockEntry* pCurr, const BlockEntry*& pNext) const {
  5291. assert(pCurr);
  5292. assert(m_entries);
  5293. assert(m_entries_count > 0);
  5294. size_t idx = pCurr->GetIndex();
  5295. assert(idx < size_t(m_entries_count));
  5296. assert(m_entries[idx] == pCurr);
  5297. ++idx;
  5298. if (idx >= size_t(m_entries_count)) {
  5299. long long pos;
  5300. long len;
  5301. const long status = Parse(pos, len);
  5302. if (status < 0) { // error
  5303. pNext = NULL;
  5304. return status;
  5305. }
  5306. if (status > 0) {
  5307. pNext = NULL;
  5308. return 0;
  5309. }
  5310. assert(m_entries);
  5311. assert(m_entries_count > 0);
  5312. assert(idx < size_t(m_entries_count));
  5313. }
  5314. pNext = m_entries[idx];
  5315. assert(pNext);
  5316. return 0;
  5317. }
  5318. long Cluster::GetEntryCount() const { return m_entries_count; }
  5319. const BlockEntry* Cluster::GetEntry(const Track* pTrack,
  5320. long long time_ns) const {
  5321. assert(pTrack);
  5322. if (m_pSegment == NULL) // this is the special EOS cluster
  5323. return pTrack->GetEOS();
  5324. const BlockEntry* pResult = pTrack->GetEOS();
  5325. long index = 0;
  5326. for (;;) {
  5327. if (index >= m_entries_count) {
  5328. long long pos;
  5329. long len;
  5330. const long status = Parse(pos, len);
  5331. assert(status >= 0);
  5332. if (status > 0) // completely parsed, and no more entries
  5333. return pResult;
  5334. if (status < 0) // should never happen
  5335. return 0;
  5336. assert(m_entries);
  5337. assert(index < m_entries_count);
  5338. }
  5339. const BlockEntry* const pEntry = m_entries[index];
  5340. assert(pEntry);
  5341. assert(!pEntry->EOS());
  5342. const Block* const pBlock = pEntry->GetBlock();
  5343. assert(pBlock);
  5344. if (pBlock->GetTrackNumber() != pTrack->GetNumber()) {
  5345. ++index;
  5346. continue;
  5347. }
  5348. if (pTrack->VetEntry(pEntry)) {
  5349. if (time_ns < 0) // just want first candidate block
  5350. return pEntry;
  5351. const long long ns = pBlock->GetTime(this);
  5352. if (ns > time_ns)
  5353. return pResult;
  5354. pResult = pEntry; // have a candidate
  5355. } else if (time_ns >= 0) {
  5356. const long long ns = pBlock->GetTime(this);
  5357. if (ns > time_ns)
  5358. return pResult;
  5359. }
  5360. ++index;
  5361. }
  5362. }
  5363. const BlockEntry* Cluster::GetEntry(const CuePoint& cp,
  5364. const CuePoint::TrackPosition& tp) const {
  5365. assert(m_pSegment);
  5366. const long long tc = cp.GetTimeCode();
  5367. if (tp.m_block > 0) {
  5368. const long block = static_cast<long>(tp.m_block);
  5369. const long index = block - 1;
  5370. while (index >= m_entries_count) {
  5371. long long pos;
  5372. long len;
  5373. const long status = Parse(pos, len);
  5374. if (status < 0) // TODO: can this happen?
  5375. return NULL;
  5376. if (status > 0) // nothing remains to be parsed
  5377. return NULL;
  5378. }
  5379. const BlockEntry* const pEntry = m_entries[index];
  5380. assert(pEntry);
  5381. assert(!pEntry->EOS());
  5382. const Block* const pBlock = pEntry->GetBlock();
  5383. assert(pBlock);
  5384. if ((pBlock->GetTrackNumber() == tp.m_track) &&
  5385. (pBlock->GetTimeCode(this) == tc)) {
  5386. return pEntry;
  5387. }
  5388. }
  5389. long index = 0;
  5390. for (;;) {
  5391. if (index >= m_entries_count) {
  5392. long long pos;
  5393. long len;
  5394. const long status = Parse(pos, len);
  5395. if (status < 0) // TODO: can this happen?
  5396. return NULL;
  5397. if (status > 0) // nothing remains to be parsed
  5398. return NULL;
  5399. assert(m_entries);
  5400. assert(index < m_entries_count);
  5401. }
  5402. const BlockEntry* const pEntry = m_entries[index];
  5403. assert(pEntry);
  5404. assert(!pEntry->EOS());
  5405. const Block* const pBlock = pEntry->GetBlock();
  5406. assert(pBlock);
  5407. if (pBlock->GetTrackNumber() != tp.m_track) {
  5408. ++index;
  5409. continue;
  5410. }
  5411. const long long tc_ = pBlock->GetTimeCode(this);
  5412. if (tc_ < tc) {
  5413. ++index;
  5414. continue;
  5415. }
  5416. if (tc_ > tc)
  5417. return NULL;
  5418. const Tracks* const pTracks = m_pSegment->GetTracks();
  5419. assert(pTracks);
  5420. const long tn = static_cast<long>(tp.m_track);
  5421. const Track* const pTrack = pTracks->GetTrackByNumber(tn);
  5422. if (pTrack == NULL)
  5423. return NULL;
  5424. const long long type = pTrack->GetType();
  5425. if (type == 2) // audio
  5426. return pEntry;
  5427. if (type != 1) // not video
  5428. return NULL;
  5429. if (!pBlock->IsKey())
  5430. return NULL;
  5431. return pEntry;
  5432. }
  5433. }
  5434. BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) {}
  5435. BlockEntry::~BlockEntry() {}
  5436. const Cluster* BlockEntry::GetCluster() const { return m_pCluster; }
  5437. long BlockEntry::GetIndex() const { return m_index; }
  5438. SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start,
  5439. long long size)
  5440. : BlockEntry(pCluster, idx), m_block(start, size, 0) {}
  5441. long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); }
  5442. BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; }
  5443. const Block* SimpleBlock::GetBlock() const { return &m_block; }
  5444. BlockGroup::BlockGroup(Cluster* pCluster, long idx, long long block_start,
  5445. long long block_size, long long prev, long long next,
  5446. long long duration, long long discard_padding)
  5447. : BlockEntry(pCluster, idx),
  5448. m_block(block_start, block_size, discard_padding),
  5449. m_prev(prev),
  5450. m_next(next),
  5451. m_duration(duration) {}
  5452. long BlockGroup::Parse() {
  5453. const long status = m_block.Parse(m_pCluster);
  5454. if (status)
  5455. return status;
  5456. m_block.SetKey((m_prev > 0) && (m_next <= 0));
  5457. return 0;
  5458. }
  5459. BlockEntry::Kind BlockGroup::GetKind() const { return kBlockGroup; }
  5460. const Block* BlockGroup::GetBlock() const { return &m_block; }
  5461. long long BlockGroup::GetPrevTimeCode() const { return m_prev; }
  5462. long long BlockGroup::GetNextTimeCode() const { return m_next; }
  5463. long long BlockGroup::GetDurationTimeCode() const { return m_duration; }
  5464. Block::Block(long long start, long long size_, long long discard_padding)
  5465. : m_start(start),
  5466. m_size(size_),
  5467. m_track(0),
  5468. m_timecode(-1),
  5469. m_flags(0),
  5470. m_frames(NULL),
  5471. m_frame_count(-1),
  5472. m_discard_padding(discard_padding) {}
  5473. Block::~Block() { delete[] m_frames; }
  5474. long Block::Parse(const Cluster* pCluster) {
  5475. if (pCluster == NULL)
  5476. return -1;
  5477. if (pCluster->m_pSegment == NULL)
  5478. return -1;
  5479. assert(m_start >= 0);
  5480. assert(m_size >= 0);
  5481. assert(m_track <= 0);
  5482. assert(m_frames == NULL);
  5483. assert(m_frame_count <= 0);
  5484. long long pos = m_start;
  5485. const long long stop = m_start + m_size;
  5486. long len;
  5487. IMkvReader* const pReader = pCluster->m_pSegment->m_pReader;
  5488. m_track = ReadUInt(pReader, pos, len);
  5489. if (m_track <= 0)
  5490. return E_FILE_FORMAT_INVALID;
  5491. if ((pos + len) > stop)
  5492. return E_FILE_FORMAT_INVALID;
  5493. pos += len; // consume track number
  5494. if ((stop - pos) < 2)
  5495. return E_FILE_FORMAT_INVALID;
  5496. long status;
  5497. long long value;
  5498. status = UnserializeInt(pReader, pos, 2, value);
  5499. if (status)
  5500. return E_FILE_FORMAT_INVALID;
  5501. if (value < SHRT_MIN)
  5502. return E_FILE_FORMAT_INVALID;
  5503. if (value > SHRT_MAX)
  5504. return E_FILE_FORMAT_INVALID;
  5505. m_timecode = static_cast<short>(value);
  5506. pos += 2;
  5507. if ((stop - pos) <= 0)
  5508. return E_FILE_FORMAT_INVALID;
  5509. status = pReader->Read(pos, 1, &m_flags);
  5510. if (status)
  5511. return E_FILE_FORMAT_INVALID;
  5512. const int lacing = int(m_flags & 0x06) >> 1;
  5513. ++pos; // consume flags byte
  5514. if (lacing == 0) { // no lacing
  5515. if (pos > stop)
  5516. return E_FILE_FORMAT_INVALID;
  5517. m_frame_count = 1;
  5518. m_frames = new (std::nothrow) Frame[m_frame_count];
  5519. if (m_frames == NULL)
  5520. return -1;
  5521. Frame& f = m_frames[0];
  5522. f.pos = pos;
  5523. const long long frame_size = stop - pos;
  5524. if (frame_size > LONG_MAX || frame_size <= 0)
  5525. return E_FILE_FORMAT_INVALID;
  5526. f.len = static_cast<long>(frame_size);
  5527. return 0; // success
  5528. }
  5529. if (pos >= stop)
  5530. return E_FILE_FORMAT_INVALID;
  5531. unsigned char biased_count;
  5532. status = pReader->Read(pos, 1, &biased_count);
  5533. if (status)
  5534. return E_FILE_FORMAT_INVALID;
  5535. ++pos; // consume frame count
  5536. if (pos > stop)
  5537. return E_FILE_FORMAT_INVALID;
  5538. m_frame_count = int(biased_count) + 1;
  5539. m_frames = new (std::nothrow) Frame[m_frame_count];
  5540. if (m_frames == NULL)
  5541. return -1;
  5542. if (!m_frames)
  5543. return E_FILE_FORMAT_INVALID;
  5544. if (lacing == 1) { // Xiph
  5545. Frame* pf = m_frames;
  5546. Frame* const pf_end = pf + m_frame_count;
  5547. long long size = 0;
  5548. int frame_count = m_frame_count;
  5549. while (frame_count > 1) {
  5550. long frame_size = 0;
  5551. for (;;) {
  5552. unsigned char val;
  5553. if (pos >= stop)
  5554. return E_FILE_FORMAT_INVALID;
  5555. status = pReader->Read(pos, 1, &val);
  5556. if (status)
  5557. return E_FILE_FORMAT_INVALID;
  5558. ++pos; // consume xiph size byte
  5559. frame_size += val;
  5560. if (val < 255)
  5561. break;
  5562. }
  5563. Frame& f = *pf++;
  5564. assert(pf < pf_end);
  5565. if (pf >= pf_end)
  5566. return E_FILE_FORMAT_INVALID;
  5567. f.pos = 0; // patch later
  5568. if (frame_size <= 0)
  5569. return E_FILE_FORMAT_INVALID;
  5570. f.len = frame_size;
  5571. size += frame_size; // contribution of this frame
  5572. --frame_count;
  5573. }
  5574. if (pf >= pf_end || pos > stop)
  5575. return E_FILE_FORMAT_INVALID;
  5576. {
  5577. Frame& f = *pf++;
  5578. if (pf != pf_end)
  5579. return E_FILE_FORMAT_INVALID;
  5580. f.pos = 0; // patch later
  5581. const long long total_size = stop - pos;
  5582. if (total_size < size)
  5583. return E_FILE_FORMAT_INVALID;
  5584. const long long frame_size = total_size - size;
  5585. if (frame_size > LONG_MAX || frame_size <= 0)
  5586. return E_FILE_FORMAT_INVALID;
  5587. f.len = static_cast<long>(frame_size);
  5588. }
  5589. pf = m_frames;
  5590. while (pf != pf_end) {
  5591. Frame& f = *pf++;
  5592. assert((pos + f.len) <= stop);
  5593. if ((pos + f.len) > stop)
  5594. return E_FILE_FORMAT_INVALID;
  5595. f.pos = pos;
  5596. pos += f.len;
  5597. }
  5598. assert(pos == stop);
  5599. if (pos != stop)
  5600. return E_FILE_FORMAT_INVALID;
  5601. } else if (lacing == 2) { // fixed-size lacing
  5602. if (pos >= stop)
  5603. return E_FILE_FORMAT_INVALID;
  5604. const long long total_size = stop - pos;
  5605. if ((total_size % m_frame_count) != 0)
  5606. return E_FILE_FORMAT_INVALID;
  5607. const long long frame_size = total_size / m_frame_count;
  5608. if (frame_size > LONG_MAX || frame_size <= 0)
  5609. return E_FILE_FORMAT_INVALID;
  5610. Frame* pf = m_frames;
  5611. Frame* const pf_end = pf + m_frame_count;
  5612. while (pf != pf_end) {
  5613. assert((pos + frame_size) <= stop);
  5614. if ((pos + frame_size) > stop)
  5615. return E_FILE_FORMAT_INVALID;
  5616. Frame& f = *pf++;
  5617. f.pos = pos;
  5618. f.len = static_cast<long>(frame_size);
  5619. pos += frame_size;
  5620. }
  5621. assert(pos == stop);
  5622. if (pos != stop)
  5623. return E_FILE_FORMAT_INVALID;
  5624. } else {
  5625. assert(lacing == 3); // EBML lacing
  5626. if (pos >= stop)
  5627. return E_FILE_FORMAT_INVALID;
  5628. long long size = 0;
  5629. int frame_count = m_frame_count;
  5630. long long frame_size = ReadUInt(pReader, pos, len);
  5631. if (frame_size <= 0)
  5632. return E_FILE_FORMAT_INVALID;
  5633. if (frame_size > LONG_MAX)
  5634. return E_FILE_FORMAT_INVALID;
  5635. if ((pos + len) > stop)
  5636. return E_FILE_FORMAT_INVALID;
  5637. pos += len; // consume length of size of first frame
  5638. if ((pos + frame_size) > stop)
  5639. return E_FILE_FORMAT_INVALID;
  5640. Frame* pf = m_frames;
  5641. Frame* const pf_end = pf + m_frame_count;
  5642. {
  5643. Frame& curr = *pf;
  5644. curr.pos = 0; // patch later
  5645. curr.len = static_cast<long>(frame_size);
  5646. size += curr.len; // contribution of this frame
  5647. }
  5648. --frame_count;
  5649. while (frame_count > 1) {
  5650. if (pos >= stop)
  5651. return E_FILE_FORMAT_INVALID;
  5652. assert(pf < pf_end);
  5653. if (pf >= pf_end)
  5654. return E_FILE_FORMAT_INVALID;
  5655. const Frame& prev = *pf++;
  5656. assert(prev.len == frame_size);
  5657. if (prev.len != frame_size)
  5658. return E_FILE_FORMAT_INVALID;
  5659. assert(pf < pf_end);
  5660. if (pf >= pf_end)
  5661. return E_FILE_FORMAT_INVALID;
  5662. Frame& curr = *pf;
  5663. curr.pos = 0; // patch later
  5664. const long long delta_size_ = ReadUInt(pReader, pos, len);
  5665. if (delta_size_ < 0)
  5666. return E_FILE_FORMAT_INVALID;
  5667. if ((pos + len) > stop)
  5668. return E_FILE_FORMAT_INVALID;
  5669. pos += len; // consume length of (delta) size
  5670. if (pos > stop)
  5671. return E_FILE_FORMAT_INVALID;
  5672. const long exp = 7 * len - 1;
  5673. const long long bias = (1LL << exp) - 1LL;
  5674. const long long delta_size = delta_size_ - bias;
  5675. frame_size += delta_size;
  5676. if (frame_size <= 0)
  5677. return E_FILE_FORMAT_INVALID;
  5678. if (frame_size > LONG_MAX)
  5679. return E_FILE_FORMAT_INVALID;
  5680. curr.len = static_cast<long>(frame_size);
  5681. // Check if size + curr.len could overflow.
  5682. if (size > LLONG_MAX - curr.len) {
  5683. return E_FILE_FORMAT_INVALID;
  5684. }
  5685. size += curr.len; // contribution of this frame
  5686. --frame_count;
  5687. }
  5688. // parse last frame
  5689. if (frame_count > 0) {
  5690. if (pos > stop || pf >= pf_end)
  5691. return E_FILE_FORMAT_INVALID;
  5692. const Frame& prev = *pf++;
  5693. assert(prev.len == frame_size);
  5694. if (prev.len != frame_size)
  5695. return E_FILE_FORMAT_INVALID;
  5696. if (pf >= pf_end)
  5697. return E_FILE_FORMAT_INVALID;
  5698. Frame& curr = *pf++;
  5699. if (pf != pf_end)
  5700. return E_FILE_FORMAT_INVALID;
  5701. curr.pos = 0; // patch later
  5702. const long long total_size = stop - pos;
  5703. if (total_size < size)
  5704. return E_FILE_FORMAT_INVALID;
  5705. frame_size = total_size - size;
  5706. if (frame_size > LONG_MAX || frame_size <= 0)
  5707. return E_FILE_FORMAT_INVALID;
  5708. curr.len = static_cast<long>(frame_size);
  5709. }
  5710. pf = m_frames;
  5711. while (pf != pf_end) {
  5712. Frame& f = *pf++;
  5713. if ((pos + f.len) > stop)
  5714. return E_FILE_FORMAT_INVALID;
  5715. f.pos = pos;
  5716. pos += f.len;
  5717. }
  5718. if (pos != stop)
  5719. return E_FILE_FORMAT_INVALID;
  5720. }
  5721. return 0; // success
  5722. }
  5723. long long Block::GetTimeCode(const Cluster* pCluster) const {
  5724. if (pCluster == 0)
  5725. return m_timecode;
  5726. const long long tc0 = pCluster->GetTimeCode();
  5727. assert(tc0 >= 0);
  5728. // Check if tc0 + m_timecode would overflow.
  5729. if (tc0 < 0 || LLONG_MAX - tc0 < m_timecode) {
  5730. return -1;
  5731. }
  5732. const long long tc = tc0 + m_timecode;
  5733. return tc; // unscaled timecode units
  5734. }
  5735. long long Block::GetTime(const Cluster* pCluster) const {
  5736. assert(pCluster);
  5737. const long long tc = GetTimeCode(pCluster);
  5738. const Segment* const pSegment = pCluster->m_pSegment;
  5739. const SegmentInfo* const pInfo = pSegment->GetInfo();
  5740. assert(pInfo);
  5741. const long long scale = pInfo->GetTimeCodeScale();
  5742. assert(scale >= 1);
  5743. // Check if tc * scale could overflow.
  5744. if (tc != 0 && scale > LLONG_MAX / tc) {
  5745. return -1;
  5746. }
  5747. const long long ns = tc * scale;
  5748. return ns;
  5749. }
  5750. long long Block::GetTrackNumber() const { return m_track; }
  5751. bool Block::IsKey() const {
  5752. return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
  5753. }
  5754. void Block::SetKey(bool bKey) {
  5755. if (bKey)
  5756. m_flags |= static_cast<unsigned char>(1 << 7);
  5757. else
  5758. m_flags &= 0x7F;
  5759. }
  5760. bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); }
  5761. Block::Lacing Block::GetLacing() const {
  5762. const int value = int(m_flags & 0x06) >> 1;
  5763. return static_cast<Lacing>(value);
  5764. }
  5765. int Block::GetFrameCount() const { return m_frame_count; }
  5766. const Block::Frame& Block::GetFrame(int idx) const {
  5767. assert(idx >= 0);
  5768. assert(idx < m_frame_count);
  5769. const Frame& f = m_frames[idx];
  5770. assert(f.pos > 0);
  5771. assert(f.len > 0);
  5772. return f;
  5773. }
  5774. long Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const {
  5775. assert(pReader);
  5776. assert(buf);
  5777. const long status = pReader->Read(pos, len, buf);
  5778. return status;
  5779. }
  5780. long long Block::GetDiscardPadding() const { return m_discard_padding; }
  5781. } // namespace mkvparser