mkvparser.cc 188 KB

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