mkvparser.cc 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071
  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. compression_entries_ = NULL;
  3028. return -1;
  3029. }
  3030. encryption_entries_end_ = encryption_entries_;
  3031. }
  3032. pos = start;
  3033. while (pos < stop) {
  3034. long long id, size;
  3035. long status = ParseElementHeader(pReader, pos, stop, id, size);
  3036. if (status < 0) // error
  3037. return status;
  3038. if (id == libwebm::kMkvContentEncodingOrder) {
  3039. encoding_order_ = UnserializeUInt(pReader, pos, size);
  3040. } else if (id == libwebm::kMkvContentEncodingScope) {
  3041. encoding_scope_ = UnserializeUInt(pReader, pos, size);
  3042. if (encoding_scope_ < 1)
  3043. return -1;
  3044. } else if (id == libwebm::kMkvContentEncodingType) {
  3045. encoding_type_ = UnserializeUInt(pReader, pos, size);
  3046. } else if (id == libwebm::kMkvContentCompression) {
  3047. ContentCompression* const compression =
  3048. new (std::nothrow) ContentCompression();
  3049. if (!compression)
  3050. return -1;
  3051. status = ParseCompressionEntry(pos, size, pReader, compression);
  3052. if (status) {
  3053. delete compression;
  3054. return status;
  3055. }
  3056. assert(compression_count > 0);
  3057. *compression_entries_end_++ = compression;
  3058. } else if (id == libwebm::kMkvContentEncryption) {
  3059. ContentEncryption* const encryption =
  3060. new (std::nothrow) ContentEncryption();
  3061. if (!encryption)
  3062. return -1;
  3063. status = ParseEncryptionEntry(pos, size, pReader, encryption);
  3064. if (status) {
  3065. delete encryption;
  3066. return status;
  3067. }
  3068. assert(encryption_count > 0);
  3069. *encryption_entries_end_++ = encryption;
  3070. }
  3071. pos += size; // consume payload
  3072. if (pos > stop)
  3073. return E_FILE_FORMAT_INVALID;
  3074. }
  3075. if (pos != stop)
  3076. return E_FILE_FORMAT_INVALID;
  3077. return 0;
  3078. }
  3079. long ContentEncoding::ParseCompressionEntry(long long start, long long size,
  3080. IMkvReader* pReader,
  3081. ContentCompression* compression) {
  3082. assert(pReader);
  3083. assert(compression);
  3084. long long pos = start;
  3085. const long long stop = start + size;
  3086. bool valid = false;
  3087. while (pos < stop) {
  3088. long long id, size;
  3089. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3090. if (status < 0) // error
  3091. return status;
  3092. if (id == libwebm::kMkvContentCompAlgo) {
  3093. long long algo = UnserializeUInt(pReader, pos, size);
  3094. if (algo < 0)
  3095. return E_FILE_FORMAT_INVALID;
  3096. compression->algo = algo;
  3097. valid = true;
  3098. } else if (id == libwebm::kMkvContentCompSettings) {
  3099. if (size <= 0)
  3100. return E_FILE_FORMAT_INVALID;
  3101. const size_t buflen = static_cast<size_t>(size);
  3102. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3103. if (buf == NULL)
  3104. return -1;
  3105. const int read_status =
  3106. pReader->Read(pos, static_cast<long>(buflen), buf);
  3107. if (read_status) {
  3108. delete[] buf;
  3109. return status;
  3110. }
  3111. // There should be only one settings element per content compression.
  3112. if (compression->settings != NULL) {
  3113. delete[] buf;
  3114. return E_FILE_FORMAT_INVALID;
  3115. }
  3116. compression->settings = buf;
  3117. compression->settings_len = buflen;
  3118. }
  3119. pos += size; // consume payload
  3120. if (pos > stop)
  3121. return E_FILE_FORMAT_INVALID;
  3122. }
  3123. // ContentCompAlgo is mandatory
  3124. if (!valid)
  3125. return E_FILE_FORMAT_INVALID;
  3126. return 0;
  3127. }
  3128. long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
  3129. IMkvReader* pReader,
  3130. ContentEncryption* encryption) {
  3131. assert(pReader);
  3132. assert(encryption);
  3133. long long pos = start;
  3134. const long long stop = start + size;
  3135. while (pos < stop) {
  3136. long long id, size;
  3137. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3138. if (status < 0) // error
  3139. return status;
  3140. if (id == libwebm::kMkvContentEncAlgo) {
  3141. encryption->algo = UnserializeUInt(pReader, pos, size);
  3142. if (encryption->algo != 5)
  3143. return E_FILE_FORMAT_INVALID;
  3144. } else if (id == libwebm::kMkvContentEncKeyID) {
  3145. delete[] encryption->key_id;
  3146. encryption->key_id = NULL;
  3147. encryption->key_id_len = 0;
  3148. if (size <= 0)
  3149. return E_FILE_FORMAT_INVALID;
  3150. const size_t buflen = static_cast<size_t>(size);
  3151. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3152. if (buf == NULL)
  3153. return -1;
  3154. const int read_status =
  3155. pReader->Read(pos, static_cast<long>(buflen), buf);
  3156. if (read_status) {
  3157. delete[] buf;
  3158. return status;
  3159. }
  3160. encryption->key_id = buf;
  3161. encryption->key_id_len = buflen;
  3162. } else if (id == libwebm::kMkvContentSignature) {
  3163. delete[] encryption->signature;
  3164. encryption->signature = NULL;
  3165. encryption->signature_len = 0;
  3166. if (size <= 0)
  3167. return E_FILE_FORMAT_INVALID;
  3168. const size_t buflen = static_cast<size_t>(size);
  3169. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3170. if (buf == NULL)
  3171. return -1;
  3172. const int read_status =
  3173. pReader->Read(pos, static_cast<long>(buflen), buf);
  3174. if (read_status) {
  3175. delete[] buf;
  3176. return status;
  3177. }
  3178. encryption->signature = buf;
  3179. encryption->signature_len = buflen;
  3180. } else if (id == libwebm::kMkvContentSigKeyID) {
  3181. delete[] encryption->sig_key_id;
  3182. encryption->sig_key_id = NULL;
  3183. encryption->sig_key_id_len = 0;
  3184. if (size <= 0)
  3185. return E_FILE_FORMAT_INVALID;
  3186. const size_t buflen = static_cast<size_t>(size);
  3187. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  3188. if (buf == NULL)
  3189. return -1;
  3190. const int read_status =
  3191. pReader->Read(pos, static_cast<long>(buflen), buf);
  3192. if (read_status) {
  3193. delete[] buf;
  3194. return status;
  3195. }
  3196. encryption->sig_key_id = buf;
  3197. encryption->sig_key_id_len = buflen;
  3198. } else if (id == libwebm::kMkvContentSigAlgo) {
  3199. encryption->sig_algo = UnserializeUInt(pReader, pos, size);
  3200. } else if (id == libwebm::kMkvContentSigHashAlgo) {
  3201. encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
  3202. } else if (id == libwebm::kMkvContentEncAESSettings) {
  3203. const long status = ParseContentEncAESSettingsEntry(
  3204. pos, size, pReader, &encryption->aes_settings);
  3205. if (status)
  3206. return status;
  3207. }
  3208. pos += size; // consume payload
  3209. if (pos > stop)
  3210. return E_FILE_FORMAT_INVALID;
  3211. }
  3212. return 0;
  3213. }
  3214. Track::Track(Segment* pSegment, long long element_start, long long element_size)
  3215. : m_pSegment(pSegment),
  3216. m_element_start(element_start),
  3217. m_element_size(element_size),
  3218. content_encoding_entries_(NULL),
  3219. content_encoding_entries_end_(NULL) {}
  3220. Track::~Track() {
  3221. Info& info = const_cast<Info&>(m_info);
  3222. info.Clear();
  3223. ContentEncoding** i = content_encoding_entries_;
  3224. ContentEncoding** const j = content_encoding_entries_end_;
  3225. while (i != j) {
  3226. ContentEncoding* const encoding = *i++;
  3227. delete encoding;
  3228. }
  3229. delete[] content_encoding_entries_;
  3230. }
  3231. long Track::Create(Segment* pSegment, const Info& info, long long element_start,
  3232. long long element_size, Track*& pResult) {
  3233. if (pResult)
  3234. return -1;
  3235. Track* const pTrack =
  3236. new (std::nothrow) Track(pSegment, element_start, element_size);
  3237. if (pTrack == NULL)
  3238. return -1; // generic error
  3239. const int status = info.Copy(pTrack->m_info);
  3240. if (status) { // error
  3241. delete pTrack;
  3242. return status;
  3243. }
  3244. pResult = pTrack;
  3245. return 0; // success
  3246. }
  3247. Track::Info::Info()
  3248. : uid(0),
  3249. defaultDuration(0),
  3250. codecDelay(0),
  3251. seekPreRoll(0),
  3252. nameAsUTF8(NULL),
  3253. language(NULL),
  3254. codecId(NULL),
  3255. codecNameAsUTF8(NULL),
  3256. codecPrivate(NULL),
  3257. codecPrivateSize(0),
  3258. lacing(false) {}
  3259. Track::Info::~Info() { Clear(); }
  3260. void Track::Info::Clear() {
  3261. delete[] nameAsUTF8;
  3262. nameAsUTF8 = NULL;
  3263. delete[] language;
  3264. language = NULL;
  3265. delete[] codecId;
  3266. codecId = NULL;
  3267. delete[] codecPrivate;
  3268. codecPrivate = NULL;
  3269. codecPrivateSize = 0;
  3270. delete[] codecNameAsUTF8;
  3271. codecNameAsUTF8 = NULL;
  3272. }
  3273. int Track::Info::CopyStr(char* Info::*str, Info& dst_) const {
  3274. if (str == static_cast<char * Info::*>(NULL))
  3275. return -1;
  3276. char*& dst = dst_.*str;
  3277. if (dst) // should be NULL already
  3278. return -1;
  3279. const char* const src = this->*str;
  3280. if (src == NULL)
  3281. return 0;
  3282. const size_t len = strlen(src);
  3283. dst = SafeArrayAlloc<char>(1, len + 1);
  3284. if (dst == NULL)
  3285. return -1;
  3286. strcpy(dst, src);
  3287. return 0;
  3288. }
  3289. int Track::Info::Copy(Info& dst) const {
  3290. if (&dst == this)
  3291. return 0;
  3292. dst.type = type;
  3293. dst.number = number;
  3294. dst.defaultDuration = defaultDuration;
  3295. dst.codecDelay = codecDelay;
  3296. dst.seekPreRoll = seekPreRoll;
  3297. dst.uid = uid;
  3298. dst.lacing = lacing;
  3299. dst.settings = settings;
  3300. // We now copy the string member variables from src to dst.
  3301. // This involves memory allocation so in principle the operation
  3302. // can fail (indeed, that's why we have Info::Copy), so we must
  3303. // report this to the caller. An error return from this function
  3304. // therefore implies that the copy was only partially successful.
  3305. if (int status = CopyStr(&Info::nameAsUTF8, dst))
  3306. return status;
  3307. if (int status = CopyStr(&Info::language, dst))
  3308. return status;
  3309. if (int status = CopyStr(&Info::codecId, dst))
  3310. return status;
  3311. if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
  3312. return status;
  3313. if (codecPrivateSize > 0) {
  3314. if (codecPrivate == NULL)
  3315. return -1;
  3316. if (dst.codecPrivate)
  3317. return -1;
  3318. if (dst.codecPrivateSize != 0)
  3319. return -1;
  3320. dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize);
  3321. if (dst.codecPrivate == NULL)
  3322. return -1;
  3323. memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
  3324. dst.codecPrivateSize = codecPrivateSize;
  3325. }
  3326. return 0;
  3327. }
  3328. const BlockEntry* Track::GetEOS() const { return &m_eos; }
  3329. long Track::GetType() const { return m_info.type; }
  3330. long Track::GetNumber() const { return m_info.number; }
  3331. unsigned long long Track::GetUid() const { return m_info.uid; }
  3332. const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; }
  3333. const char* Track::GetLanguage() const { return m_info.language; }
  3334. const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }
  3335. const char* Track::GetCodecId() const { return m_info.codecId; }
  3336. const unsigned char* Track::GetCodecPrivate(size_t& size) const {
  3337. size = m_info.codecPrivateSize;
  3338. return m_info.codecPrivate;
  3339. }
  3340. bool Track::GetLacing() const { return m_info.lacing; }
  3341. unsigned long long Track::GetDefaultDuration() const {
  3342. return m_info.defaultDuration;
  3343. }
  3344. unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }
  3345. unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; }
  3346. long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
  3347. const Cluster* pCluster = m_pSegment->GetFirst();
  3348. for (int i = 0;;) {
  3349. if (pCluster == NULL) {
  3350. pBlockEntry = GetEOS();
  3351. return 1;
  3352. }
  3353. if (pCluster->EOS()) {
  3354. if (m_pSegment->DoneParsing()) {
  3355. pBlockEntry = GetEOS();
  3356. return 1;
  3357. }
  3358. pBlockEntry = 0;
  3359. return E_BUFFER_NOT_FULL;
  3360. }
  3361. long status = pCluster->GetFirst(pBlockEntry);
  3362. if (status < 0) // error
  3363. return status;
  3364. if (pBlockEntry == 0) { // empty cluster
  3365. pCluster = m_pSegment->GetNext(pCluster);
  3366. continue;
  3367. }
  3368. for (;;) {
  3369. const Block* const pBlock = pBlockEntry->GetBlock();
  3370. assert(pBlock);
  3371. const long long tn = pBlock->GetTrackNumber();
  3372. if ((tn == m_info.number) && VetEntry(pBlockEntry))
  3373. return 0;
  3374. const BlockEntry* pNextEntry;
  3375. status = pCluster->GetNext(pBlockEntry, pNextEntry);
  3376. if (status < 0) // error
  3377. return status;
  3378. if (pNextEntry == 0)
  3379. break;
  3380. pBlockEntry = pNextEntry;
  3381. }
  3382. ++i;
  3383. if (i >= 100)
  3384. break;
  3385. pCluster = m_pSegment->GetNext(pCluster);
  3386. }
  3387. // NOTE: if we get here, it means that we didn't find a block with
  3388. // a matching track number. We interpret that as an error (which
  3389. // might be too conservative).
  3390. pBlockEntry = GetEOS(); // so we can return a non-NULL value
  3391. return 1;
  3392. }
  3393. long Track::GetNext(const BlockEntry* pCurrEntry,
  3394. const BlockEntry*& pNextEntry) const {
  3395. assert(pCurrEntry);
  3396. assert(!pCurrEntry->EOS()); //?
  3397. const Block* const pCurrBlock = pCurrEntry->GetBlock();
  3398. assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number);
  3399. if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number)
  3400. return -1;
  3401. const Cluster* pCluster = pCurrEntry->GetCluster();
  3402. assert(pCluster);
  3403. assert(!pCluster->EOS());
  3404. long status = pCluster->GetNext(pCurrEntry, pNextEntry);
  3405. if (status < 0) // error
  3406. return status;
  3407. for (int i = 0;;) {
  3408. while (pNextEntry) {
  3409. const Block* const pNextBlock = pNextEntry->GetBlock();
  3410. assert(pNextBlock);
  3411. if (pNextBlock->GetTrackNumber() == m_info.number)
  3412. return 0;
  3413. pCurrEntry = pNextEntry;
  3414. status = pCluster->GetNext(pCurrEntry, pNextEntry);
  3415. if (status < 0) // error
  3416. return status;
  3417. }
  3418. pCluster = m_pSegment->GetNext(pCluster);
  3419. if (pCluster == NULL) {
  3420. pNextEntry = GetEOS();
  3421. return 1;
  3422. }
  3423. if (pCluster->EOS()) {
  3424. if (m_pSegment->DoneParsing()) {
  3425. pNextEntry = GetEOS();
  3426. return 1;
  3427. }
  3428. // TODO: there is a potential O(n^2) problem here: we tell the
  3429. // caller to (pre)load another cluster, which he does, but then he
  3430. // calls GetNext again, which repeats the same search. This is
  3431. // a pathological case, since the only way it can happen is if
  3432. // there exists a long sequence of clusters none of which contain a
  3433. // block from this track. One way around this problem is for the
  3434. // caller to be smarter when he loads another cluster: don't call
  3435. // us back until you have a cluster that contains a block from this
  3436. // track. (Of course, that's not cheap either, since our caller
  3437. // would have to scan the each cluster as it's loaded, so that
  3438. // would just push back the problem.)
  3439. pNextEntry = NULL;
  3440. return E_BUFFER_NOT_FULL;
  3441. }
  3442. status = pCluster->GetFirst(pNextEntry);
  3443. if (status < 0) // error
  3444. return status;
  3445. if (pNextEntry == NULL) // empty cluster
  3446. continue;
  3447. ++i;
  3448. if (i >= 100)
  3449. break;
  3450. }
  3451. // NOTE: if we get here, it means that we didn't find a block with
  3452. // a matching track number after lots of searching, so we give
  3453. // up trying.
  3454. pNextEntry = GetEOS(); // so we can return a non-NULL value
  3455. return 1;
  3456. }
  3457. bool Track::VetEntry(const BlockEntry* pBlockEntry) const {
  3458. assert(pBlockEntry);
  3459. const Block* const pBlock = pBlockEntry->GetBlock();
  3460. assert(pBlock);
  3461. assert(pBlock->GetTrackNumber() == m_info.number);
  3462. if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
  3463. return false;
  3464. // This function is used during a seek to determine whether the
  3465. // frame is a valid seek target. This default function simply
  3466. // returns true, which means all frames are valid seek targets.
  3467. // It gets overridden by the VideoTrack class, because only video
  3468. // keyframes can be used as seek target.
  3469. return true;
  3470. }
  3471. long Track::Seek(long long time_ns, const BlockEntry*& pResult) const {
  3472. const long status = GetFirst(pResult);
  3473. if (status < 0) // buffer underflow, etc
  3474. return status;
  3475. assert(pResult);
  3476. if (pResult->EOS())
  3477. return 0;
  3478. const Cluster* pCluster = pResult->GetCluster();
  3479. assert(pCluster);
  3480. assert(pCluster->GetIndex() >= 0);
  3481. if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
  3482. return 0;
  3483. Cluster** const clusters = m_pSegment->m_clusters;
  3484. assert(clusters);
  3485. const long count = m_pSegment->GetCount(); // loaded only, not preloaded
  3486. assert(count > 0);
  3487. Cluster** const i = clusters + pCluster->GetIndex();
  3488. assert(i);
  3489. assert(*i == pCluster);
  3490. assert(pCluster->GetTime() <= time_ns);
  3491. Cluster** const j = clusters + count;
  3492. Cluster** lo = i;
  3493. Cluster** hi = j;
  3494. while (lo < hi) {
  3495. // INVARIANT:
  3496. //[i, lo) <= time_ns
  3497. //[lo, hi) ?
  3498. //[hi, j) > time_ns
  3499. Cluster** const mid = lo + (hi - lo) / 2;
  3500. assert(mid < hi);
  3501. pCluster = *mid;
  3502. assert(pCluster);
  3503. assert(pCluster->GetIndex() >= 0);
  3504. assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
  3505. const long long t = pCluster->GetTime();
  3506. if (t <= time_ns)
  3507. lo = mid + 1;
  3508. else
  3509. hi = mid;
  3510. assert(lo <= hi);
  3511. }
  3512. assert(lo == hi);
  3513. assert(lo > i);
  3514. assert(lo <= j);
  3515. while (lo > i) {
  3516. pCluster = *--lo;
  3517. assert(pCluster);
  3518. assert(pCluster->GetTime() <= time_ns);
  3519. pResult = pCluster->GetEntry(this);
  3520. if ((pResult != 0) && !pResult->EOS())
  3521. return 0;
  3522. // landed on empty cluster (no entries)
  3523. }
  3524. pResult = GetEOS(); // weird
  3525. return 0;
  3526. }
  3527. const ContentEncoding* Track::GetContentEncodingByIndex(
  3528. unsigned long idx) const {
  3529. const ptrdiff_t count =
  3530. content_encoding_entries_end_ - content_encoding_entries_;
  3531. assert(count >= 0);
  3532. if (idx >= static_cast<unsigned long>(count))
  3533. return NULL;
  3534. return content_encoding_entries_[idx];
  3535. }
  3536. unsigned long Track::GetContentEncodingCount() const {
  3537. const ptrdiff_t count =
  3538. content_encoding_entries_end_ - content_encoding_entries_;
  3539. assert(count >= 0);
  3540. return static_cast<unsigned long>(count);
  3541. }
  3542. long Track::ParseContentEncodingsEntry(long long start, long long size) {
  3543. IMkvReader* const pReader = m_pSegment->m_pReader;
  3544. assert(pReader);
  3545. long long pos = start;
  3546. const long long stop = start + size;
  3547. // Count ContentEncoding elements.
  3548. int count = 0;
  3549. while (pos < stop) {
  3550. long long id, size;
  3551. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3552. if (status < 0) // error
  3553. return status;
  3554. // pos now designates start of element
  3555. if (id == libwebm::kMkvContentEncoding)
  3556. ++count;
  3557. pos += size; // consume payload
  3558. if (pos > stop)
  3559. return E_FILE_FORMAT_INVALID;
  3560. }
  3561. if (count <= 0)
  3562. return -1;
  3563. content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count];
  3564. if (!content_encoding_entries_)
  3565. return -1;
  3566. content_encoding_entries_end_ = content_encoding_entries_;
  3567. pos = start;
  3568. while (pos < stop) {
  3569. long long id, size;
  3570. long status = ParseElementHeader(pReader, pos, stop, id, size);
  3571. if (status < 0) // error
  3572. return status;
  3573. // pos now designates start of element
  3574. if (id == libwebm::kMkvContentEncoding) {
  3575. ContentEncoding* const content_encoding =
  3576. new (std::nothrow) ContentEncoding();
  3577. if (!content_encoding)
  3578. return -1;
  3579. status = content_encoding->ParseContentEncodingEntry(pos, size, pReader);
  3580. if (status) {
  3581. delete content_encoding;
  3582. return status;
  3583. }
  3584. *content_encoding_entries_end_++ = content_encoding;
  3585. }
  3586. pos += size; // consume payload
  3587. if (pos > stop)
  3588. return E_FILE_FORMAT_INVALID;
  3589. }
  3590. if (pos != stop)
  3591. return E_FILE_FORMAT_INVALID;
  3592. return 0;
  3593. }
  3594. Track::EOSBlock::EOSBlock() : BlockEntry(NULL, LONG_MIN) {}
  3595. BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; }
  3596. const Block* Track::EOSBlock::GetBlock() const { return NULL; }
  3597. bool PrimaryChromaticity::Parse(IMkvReader* reader, long long read_pos,
  3598. long long value_size, bool is_x,
  3599. PrimaryChromaticity** chromaticity) {
  3600. if (!reader)
  3601. return false;
  3602. if (!*chromaticity)
  3603. *chromaticity = new PrimaryChromaticity();
  3604. if (!*chromaticity)
  3605. return false;
  3606. PrimaryChromaticity* pc = *chromaticity;
  3607. float* value = is_x ? &pc->x : &pc->y;
  3608. double parser_value = 0;
  3609. const long long parse_status =
  3610. UnserializeFloat(reader, read_pos, value_size, parser_value);
  3611. // Valid range is [0, 1]. Make sure the double is representable as a float
  3612. // before casting.
  3613. if (parse_status < 0 || parser_value < 0.0 || parser_value > 1.0 ||
  3614. (parser_value > 0.0 && parser_value < FLT_MIN))
  3615. return false;
  3616. *value = static_cast<float>(parser_value);
  3617. return true;
  3618. }
  3619. bool MasteringMetadata::Parse(IMkvReader* reader, long long mm_start,
  3620. long long mm_size, MasteringMetadata** mm) {
  3621. if (!reader || *mm)
  3622. return false;
  3623. std::unique_ptr<MasteringMetadata> mm_ptr(new MasteringMetadata());
  3624. if (!mm_ptr.get())
  3625. return false;
  3626. const long long mm_end = mm_start + mm_size;
  3627. long long read_pos = mm_start;
  3628. while (read_pos < mm_end) {
  3629. long long child_id = 0;
  3630. long long child_size = 0;
  3631. const long long status =
  3632. ParseElementHeader(reader, read_pos, mm_end, child_id, child_size);
  3633. if (status < 0)
  3634. return false;
  3635. if (child_id == libwebm::kMkvLuminanceMax) {
  3636. double value = 0;
  3637. const long long value_parse_status =
  3638. UnserializeFloat(reader, read_pos, child_size, value);
  3639. if (value < -FLT_MAX || value > FLT_MAX ||
  3640. (value > 0.0 && value < FLT_MIN)) {
  3641. return false;
  3642. }
  3643. mm_ptr->luminance_max = static_cast<float>(value);
  3644. if (value_parse_status < 0 || mm_ptr->luminance_max < 0.0 ||
  3645. mm_ptr->luminance_max > 9999.99) {
  3646. return false;
  3647. }
  3648. } else if (child_id == libwebm::kMkvLuminanceMin) {
  3649. double value = 0;
  3650. const long long value_parse_status =
  3651. UnserializeFloat(reader, read_pos, child_size, value);
  3652. if (value < -FLT_MAX || value > FLT_MAX ||
  3653. (value > 0.0 && value < FLT_MIN)) {
  3654. return false;
  3655. }
  3656. mm_ptr->luminance_min = static_cast<float>(value);
  3657. if (value_parse_status < 0 || mm_ptr->luminance_min < 0.0 ||
  3658. mm_ptr->luminance_min > 999.9999) {
  3659. return false;
  3660. }
  3661. } else {
  3662. bool is_x = false;
  3663. PrimaryChromaticity** chromaticity;
  3664. switch (child_id) {
  3665. case libwebm::kMkvPrimaryRChromaticityX:
  3666. case libwebm::kMkvPrimaryRChromaticityY:
  3667. is_x = child_id == libwebm::kMkvPrimaryRChromaticityX;
  3668. chromaticity = &mm_ptr->r;
  3669. break;
  3670. case libwebm::kMkvPrimaryGChromaticityX:
  3671. case libwebm::kMkvPrimaryGChromaticityY:
  3672. is_x = child_id == libwebm::kMkvPrimaryGChromaticityX;
  3673. chromaticity = &mm_ptr->g;
  3674. break;
  3675. case libwebm::kMkvPrimaryBChromaticityX:
  3676. case libwebm::kMkvPrimaryBChromaticityY:
  3677. is_x = child_id == libwebm::kMkvPrimaryBChromaticityX;
  3678. chromaticity = &mm_ptr->b;
  3679. break;
  3680. case libwebm::kMkvWhitePointChromaticityX:
  3681. case libwebm::kMkvWhitePointChromaticityY:
  3682. is_x = child_id == libwebm::kMkvWhitePointChromaticityX;
  3683. chromaticity = &mm_ptr->white_point;
  3684. break;
  3685. default:
  3686. return false;
  3687. }
  3688. const bool value_parse_status = PrimaryChromaticity::Parse(
  3689. reader, read_pos, child_size, is_x, chromaticity);
  3690. if (!value_parse_status)
  3691. return false;
  3692. }
  3693. read_pos += child_size;
  3694. if (read_pos > mm_end)
  3695. return false;
  3696. }
  3697. *mm = mm_ptr.release();
  3698. return true;
  3699. }
  3700. bool Colour::Parse(IMkvReader* reader, long long colour_start,
  3701. long long colour_size, Colour** colour) {
  3702. if (!reader || *colour)
  3703. return false;
  3704. std::unique_ptr<Colour> colour_ptr(new Colour());
  3705. if (!colour_ptr.get())
  3706. return false;
  3707. const long long colour_end = colour_start + colour_size;
  3708. long long read_pos = colour_start;
  3709. while (read_pos < colour_end) {
  3710. long long child_id = 0;
  3711. long long child_size = 0;
  3712. const long status =
  3713. ParseElementHeader(reader, read_pos, colour_end, child_id, child_size);
  3714. if (status < 0)
  3715. return false;
  3716. if (child_id == libwebm::kMkvMatrixCoefficients) {
  3717. colour_ptr->matrix_coefficients =
  3718. UnserializeUInt(reader, read_pos, child_size);
  3719. if (colour_ptr->matrix_coefficients < 0)
  3720. return false;
  3721. } else if (child_id == libwebm::kMkvBitsPerChannel) {
  3722. colour_ptr->bits_per_channel =
  3723. UnserializeUInt(reader, read_pos, child_size);
  3724. if (colour_ptr->bits_per_channel < 0)
  3725. return false;
  3726. } else if (child_id == libwebm::kMkvChromaSubsamplingHorz) {
  3727. colour_ptr->chroma_subsampling_horz =
  3728. UnserializeUInt(reader, read_pos, child_size);
  3729. if (colour_ptr->chroma_subsampling_horz < 0)
  3730. return false;
  3731. } else if (child_id == libwebm::kMkvChromaSubsamplingVert) {
  3732. colour_ptr->chroma_subsampling_vert =
  3733. UnserializeUInt(reader, read_pos, child_size);
  3734. if (colour_ptr->chroma_subsampling_vert < 0)
  3735. return false;
  3736. } else if (child_id == libwebm::kMkvCbSubsamplingHorz) {
  3737. colour_ptr->cb_subsampling_horz =
  3738. UnserializeUInt(reader, read_pos, child_size);
  3739. if (colour_ptr->cb_subsampling_horz < 0)
  3740. return false;
  3741. } else if (child_id == libwebm::kMkvCbSubsamplingVert) {
  3742. colour_ptr->cb_subsampling_vert =
  3743. UnserializeUInt(reader, read_pos, child_size);
  3744. if (colour_ptr->cb_subsampling_vert < 0)
  3745. return false;
  3746. } else if (child_id == libwebm::kMkvChromaSitingHorz) {
  3747. colour_ptr->chroma_siting_horz =
  3748. UnserializeUInt(reader, read_pos, child_size);
  3749. if (colour_ptr->chroma_siting_horz < 0)
  3750. return false;
  3751. } else if (child_id == libwebm::kMkvChromaSitingVert) {
  3752. colour_ptr->chroma_siting_vert =
  3753. UnserializeUInt(reader, read_pos, child_size);
  3754. if (colour_ptr->chroma_siting_vert < 0)
  3755. return false;
  3756. } else if (child_id == libwebm::kMkvRange) {
  3757. colour_ptr->range = UnserializeUInt(reader, read_pos, child_size);
  3758. if (colour_ptr->range < 0)
  3759. return false;
  3760. } else if (child_id == libwebm::kMkvTransferCharacteristics) {
  3761. colour_ptr->transfer_characteristics =
  3762. UnserializeUInt(reader, read_pos, child_size);
  3763. if (colour_ptr->transfer_characteristics < 0)
  3764. return false;
  3765. } else if (child_id == libwebm::kMkvPrimaries) {
  3766. colour_ptr->primaries = UnserializeUInt(reader, read_pos, child_size);
  3767. if (colour_ptr->primaries < 0)
  3768. return false;
  3769. } else if (child_id == libwebm::kMkvMaxCLL) {
  3770. colour_ptr->max_cll = UnserializeUInt(reader, read_pos, child_size);
  3771. if (colour_ptr->max_cll < 0)
  3772. return false;
  3773. } else if (child_id == libwebm::kMkvMaxFALL) {
  3774. colour_ptr->max_fall = UnserializeUInt(reader, read_pos, child_size);
  3775. if (colour_ptr->max_fall < 0)
  3776. return false;
  3777. } else if (child_id == libwebm::kMkvMasteringMetadata) {
  3778. if (!MasteringMetadata::Parse(reader, read_pos, child_size,
  3779. &colour_ptr->mastering_metadata))
  3780. return false;
  3781. } else {
  3782. return false;
  3783. }
  3784. read_pos += child_size;
  3785. if (read_pos > colour_end)
  3786. return false;
  3787. }
  3788. *colour = colour_ptr.release();
  3789. return true;
  3790. }
  3791. bool Projection::Parse(IMkvReader* reader, long long start, long long size,
  3792. Projection** projection) {
  3793. if (!reader || *projection)
  3794. return false;
  3795. std::unique_ptr<Projection> projection_ptr(new Projection());
  3796. if (!projection_ptr.get())
  3797. return false;
  3798. const long long end = start + size;
  3799. long long read_pos = start;
  3800. while (read_pos < end) {
  3801. long long child_id = 0;
  3802. long long child_size = 0;
  3803. const long long status =
  3804. ParseElementHeader(reader, read_pos, end, child_id, child_size);
  3805. if (status < 0)
  3806. return false;
  3807. if (child_id == libwebm::kMkvProjectionType) {
  3808. long long projection_type = kTypeNotPresent;
  3809. projection_type = UnserializeUInt(reader, read_pos, child_size);
  3810. if (projection_type < 0)
  3811. return false;
  3812. projection_ptr->type = static_cast<ProjectionType>(projection_type);
  3813. } else if (child_id == libwebm::kMkvProjectionPrivate) {
  3814. unsigned char* data = SafeArrayAlloc<unsigned char>(1, child_size);
  3815. if (data == NULL)
  3816. return false;
  3817. const int status =
  3818. reader->Read(read_pos, static_cast<long>(child_size), data);
  3819. if (status) {
  3820. delete[] data;
  3821. return false;
  3822. }
  3823. projection_ptr->private_data = data;
  3824. projection_ptr->private_data_length = static_cast<size_t>(child_size);
  3825. } else {
  3826. double value = 0;
  3827. const long long value_parse_status =
  3828. UnserializeFloat(reader, read_pos, child_size, value);
  3829. // Make sure value is representable as a float before casting.
  3830. if (value_parse_status < 0 || value < -FLT_MAX || value > FLT_MAX ||
  3831. (value > 0.0 && value < FLT_MIN)) {
  3832. return false;
  3833. }
  3834. switch (child_id) {
  3835. case libwebm::kMkvProjectionPoseYaw:
  3836. projection_ptr->pose_yaw = static_cast<float>(value);
  3837. break;
  3838. case libwebm::kMkvProjectionPosePitch:
  3839. projection_ptr->pose_pitch = static_cast<float>(value);
  3840. break;
  3841. case libwebm::kMkvProjectionPoseRoll:
  3842. projection_ptr->pose_roll = static_cast<float>(value);
  3843. break;
  3844. default:
  3845. return false;
  3846. }
  3847. }
  3848. read_pos += child_size;
  3849. if (read_pos > end)
  3850. return false;
  3851. }
  3852. *projection = projection_ptr.release();
  3853. return true;
  3854. }
  3855. VideoTrack::VideoTrack(Segment* pSegment, long long element_start,
  3856. long long element_size)
  3857. : Track(pSegment, element_start, element_size),
  3858. m_colour_space(NULL),
  3859. m_colour(NULL),
  3860. m_projection(NULL) {}
  3861. VideoTrack::~VideoTrack() {
  3862. delete m_colour;
  3863. delete m_projection;
  3864. }
  3865. long VideoTrack::Parse(Segment* pSegment, const Info& info,
  3866. long long element_start, long long element_size,
  3867. VideoTrack*& pResult) {
  3868. if (pResult)
  3869. return -1;
  3870. if (info.type != Track::kVideo)
  3871. return -1;
  3872. long long width = 0;
  3873. long long height = 0;
  3874. long long display_width = 0;
  3875. long long display_height = 0;
  3876. long long display_unit = 0;
  3877. long long stereo_mode = 0;
  3878. double rate = 0.0;
  3879. char* colour_space = NULL;
  3880. IMkvReader* const pReader = pSegment->m_pReader;
  3881. const Settings& s = info.settings;
  3882. assert(s.start >= 0);
  3883. assert(s.size >= 0);
  3884. long long pos = s.start;
  3885. assert(pos >= 0);
  3886. const long long stop = pos + s.size;
  3887. std::unique_ptr<Colour> colour_ptr;
  3888. std::unique_ptr<Projection> projection_ptr;
  3889. while (pos < stop) {
  3890. long long id, size;
  3891. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  3892. if (status < 0) // error
  3893. return status;
  3894. if (id == libwebm::kMkvPixelWidth) {
  3895. width = UnserializeUInt(pReader, pos, size);
  3896. if (width <= 0)
  3897. return E_FILE_FORMAT_INVALID;
  3898. } else if (id == libwebm::kMkvPixelHeight) {
  3899. height = UnserializeUInt(pReader, pos, size);
  3900. if (height <= 0)
  3901. return E_FILE_FORMAT_INVALID;
  3902. } else if (id == libwebm::kMkvDisplayWidth) {
  3903. display_width = UnserializeUInt(pReader, pos, size);
  3904. if (display_width <= 0)
  3905. return E_FILE_FORMAT_INVALID;
  3906. } else if (id == libwebm::kMkvDisplayHeight) {
  3907. display_height = UnserializeUInt(pReader, pos, size);
  3908. if (display_height <= 0)
  3909. return E_FILE_FORMAT_INVALID;
  3910. } else if (id == libwebm::kMkvDisplayUnit) {
  3911. display_unit = UnserializeUInt(pReader, pos, size);
  3912. if (display_unit < 0)
  3913. return E_FILE_FORMAT_INVALID;
  3914. } else if (id == libwebm::kMkvStereoMode) {
  3915. stereo_mode = UnserializeUInt(pReader, pos, size);
  3916. if (stereo_mode < 0)
  3917. return E_FILE_FORMAT_INVALID;
  3918. } else if (id == libwebm::kMkvFrameRate) {
  3919. const long status = UnserializeFloat(pReader, pos, size, rate);
  3920. if (status < 0)
  3921. return status;
  3922. if (rate <= 0)
  3923. return E_FILE_FORMAT_INVALID;
  3924. } else if (id == libwebm::kMkvColour) {
  3925. Colour* colour = NULL;
  3926. if (!Colour::Parse(pReader, pos, size, &colour)) {
  3927. return E_FILE_FORMAT_INVALID;
  3928. } else {
  3929. colour_ptr.reset(colour);
  3930. }
  3931. } else if (id == libwebm::kMkvProjection) {
  3932. Projection* projection = NULL;
  3933. if (!Projection::Parse(pReader, pos, size, &projection)) {
  3934. return E_FILE_FORMAT_INVALID;
  3935. } else {
  3936. projection_ptr.reset(projection);
  3937. }
  3938. } else if (id == libwebm::kMkvColourSpace) {
  3939. const long status = UnserializeString(pReader, pos, size, colour_space);
  3940. if (status < 0)
  3941. return status;
  3942. }
  3943. pos += size; // consume payload
  3944. if (pos > stop)
  3945. return E_FILE_FORMAT_INVALID;
  3946. }
  3947. if (pos != stop)
  3948. return E_FILE_FORMAT_INVALID;
  3949. VideoTrack* const pTrack =
  3950. new (std::nothrow) VideoTrack(pSegment, element_start, element_size);
  3951. if (pTrack == NULL)
  3952. return -1; // generic error
  3953. const int status = info.Copy(pTrack->m_info);
  3954. if (status) { // error
  3955. delete pTrack;
  3956. return status;
  3957. }
  3958. pTrack->m_width = width;
  3959. pTrack->m_height = height;
  3960. pTrack->m_display_width = display_width;
  3961. pTrack->m_display_height = display_height;
  3962. pTrack->m_display_unit = display_unit;
  3963. pTrack->m_stereo_mode = stereo_mode;
  3964. pTrack->m_rate = rate;
  3965. pTrack->m_colour = colour_ptr.release();
  3966. pTrack->m_colour_space = colour_space;
  3967. pTrack->m_projection = projection_ptr.release();
  3968. pResult = pTrack;
  3969. return 0; // success
  3970. }
  3971. bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const {
  3972. return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey();
  3973. }
  3974. long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const {
  3975. const long status = GetFirst(pResult);
  3976. if (status < 0) // buffer underflow, etc
  3977. return status;
  3978. assert(pResult);
  3979. if (pResult->EOS())
  3980. return 0;
  3981. const Cluster* pCluster = pResult->GetCluster();
  3982. assert(pCluster);
  3983. assert(pCluster->GetIndex() >= 0);
  3984. if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
  3985. return 0;
  3986. Cluster** const clusters = m_pSegment->m_clusters;
  3987. assert(clusters);
  3988. const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded
  3989. assert(count > 0);
  3990. Cluster** const i = clusters + pCluster->GetIndex();
  3991. assert(i);
  3992. assert(*i == pCluster);
  3993. assert(pCluster->GetTime() <= time_ns);
  3994. Cluster** const j = clusters + count;
  3995. Cluster** lo = i;
  3996. Cluster** hi = j;
  3997. while (lo < hi) {
  3998. // INVARIANT:
  3999. //[i, lo) <= time_ns
  4000. //[lo, hi) ?
  4001. //[hi, j) > time_ns
  4002. Cluster** const mid = lo + (hi - lo) / 2;
  4003. assert(mid < hi);
  4004. pCluster = *mid;
  4005. assert(pCluster);
  4006. assert(pCluster->GetIndex() >= 0);
  4007. assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
  4008. const long long t = pCluster->GetTime();
  4009. if (t <= time_ns)
  4010. lo = mid + 1;
  4011. else
  4012. hi = mid;
  4013. assert(lo <= hi);
  4014. }
  4015. assert(lo == hi);
  4016. assert(lo > i);
  4017. assert(lo <= j);
  4018. pCluster = *--lo;
  4019. assert(pCluster);
  4020. assert(pCluster->GetTime() <= time_ns);
  4021. pResult = pCluster->GetEntry(this, time_ns);
  4022. if ((pResult != 0) && !pResult->EOS()) // found a keyframe
  4023. return 0;
  4024. while (lo != i) {
  4025. pCluster = *--lo;
  4026. assert(pCluster);
  4027. assert(pCluster->GetTime() <= time_ns);
  4028. pResult = pCluster->GetEntry(this, time_ns);
  4029. if ((pResult != 0) && !pResult->EOS())
  4030. return 0;
  4031. }
  4032. // weird: we're on the first cluster, but no keyframe found
  4033. // should never happen but we must return something anyway
  4034. pResult = GetEOS();
  4035. return 0;
  4036. }
  4037. Colour* VideoTrack::GetColour() const { return m_colour; }
  4038. Projection* VideoTrack::GetProjection() const { return m_projection; }
  4039. long long VideoTrack::GetWidth() const { return m_width; }
  4040. long long VideoTrack::GetHeight() const { return m_height; }
  4041. long long VideoTrack::GetDisplayWidth() const {
  4042. return m_display_width > 0 ? m_display_width : GetWidth();
  4043. }
  4044. long long VideoTrack::GetDisplayHeight() const {
  4045. return m_display_height > 0 ? m_display_height : GetHeight();
  4046. }
  4047. long long VideoTrack::GetDisplayUnit() const { return m_display_unit; }
  4048. long long VideoTrack::GetStereoMode() const { return m_stereo_mode; }
  4049. double VideoTrack::GetFrameRate() const { return m_rate; }
  4050. AudioTrack::AudioTrack(Segment* pSegment, long long element_start,
  4051. long long element_size)
  4052. : Track(pSegment, element_start, element_size) {}
  4053. long AudioTrack::Parse(Segment* pSegment, const Info& info,
  4054. long long element_start, long long element_size,
  4055. AudioTrack*& pResult) {
  4056. if (pResult)
  4057. return -1;
  4058. if (info.type != Track::kAudio)
  4059. return -1;
  4060. IMkvReader* const pReader = pSegment->m_pReader;
  4061. const Settings& s = info.settings;
  4062. assert(s.start >= 0);
  4063. assert(s.size >= 0);
  4064. long long pos = s.start;
  4065. assert(pos >= 0);
  4066. const long long stop = pos + s.size;
  4067. double rate = 8000.0; // MKV default
  4068. long long channels = 1;
  4069. long long bit_depth = 0;
  4070. while (pos < stop) {
  4071. long long id, size;
  4072. long status = ParseElementHeader(pReader, pos, stop, id, size);
  4073. if (status < 0) // error
  4074. return status;
  4075. if (id == libwebm::kMkvSamplingFrequency) {
  4076. status = UnserializeFloat(pReader, pos, size, rate);
  4077. if (status < 0)
  4078. return status;
  4079. if (rate <= 0)
  4080. return E_FILE_FORMAT_INVALID;
  4081. } else if (id == libwebm::kMkvChannels) {
  4082. channels = UnserializeUInt(pReader, pos, size);
  4083. if (channels <= 0)
  4084. return E_FILE_FORMAT_INVALID;
  4085. } else if (id == libwebm::kMkvBitDepth) {
  4086. bit_depth = UnserializeUInt(pReader, pos, size);
  4087. if (bit_depth <= 0)
  4088. return E_FILE_FORMAT_INVALID;
  4089. }
  4090. pos += size; // consume payload
  4091. if (pos > stop)
  4092. return E_FILE_FORMAT_INVALID;
  4093. }
  4094. if (pos != stop)
  4095. return E_FILE_FORMAT_INVALID;
  4096. AudioTrack* const pTrack =
  4097. new (std::nothrow) AudioTrack(pSegment, element_start, element_size);
  4098. if (pTrack == NULL)
  4099. return -1; // generic error
  4100. const int status = info.Copy(pTrack->m_info);
  4101. if (status) {
  4102. delete pTrack;
  4103. return status;
  4104. }
  4105. pTrack->m_rate = rate;
  4106. pTrack->m_channels = channels;
  4107. pTrack->m_bitDepth = bit_depth;
  4108. pResult = pTrack;
  4109. return 0; // success
  4110. }
  4111. double AudioTrack::GetSamplingRate() const { return m_rate; }
  4112. long long AudioTrack::GetChannels() const { return m_channels; }
  4113. long long AudioTrack::GetBitDepth() const { return m_bitDepth; }
  4114. Tracks::Tracks(Segment* pSegment, long long start, long long size_,
  4115. long long element_start, long long element_size)
  4116. : m_pSegment(pSegment),
  4117. m_start(start),
  4118. m_size(size_),
  4119. m_element_start(element_start),
  4120. m_element_size(element_size),
  4121. m_trackEntries(NULL),
  4122. m_trackEntriesEnd(NULL) {}
  4123. long Tracks::Parse() {
  4124. assert(m_trackEntries == NULL);
  4125. assert(m_trackEntriesEnd == NULL);
  4126. const long long stop = m_start + m_size;
  4127. IMkvReader* const pReader = m_pSegment->m_pReader;
  4128. int count = 0;
  4129. long long pos = m_start;
  4130. while (pos < stop) {
  4131. long long id, size;
  4132. const long status = ParseElementHeader(pReader, pos, stop, id, size);
  4133. if (status < 0) // error
  4134. return status;
  4135. if (size == 0) // weird
  4136. continue;
  4137. if (id == libwebm::kMkvTrackEntry)
  4138. ++count;
  4139. pos += size; // consume payload
  4140. if (pos > stop)
  4141. return E_FILE_FORMAT_INVALID;
  4142. }
  4143. if (pos != stop)
  4144. return E_FILE_FORMAT_INVALID;
  4145. if (count <= 0)
  4146. return 0; // success
  4147. m_trackEntries = new (std::nothrow) Track*[count];
  4148. if (m_trackEntries == NULL)
  4149. return -1;
  4150. m_trackEntriesEnd = m_trackEntries;
  4151. pos = m_start;
  4152. while (pos < stop) {
  4153. const long long element_start = pos;
  4154. long long id, payload_size;
  4155. const long status =
  4156. ParseElementHeader(pReader, pos, stop, id, payload_size);
  4157. if (status < 0) // error
  4158. return status;
  4159. if (payload_size == 0) // weird
  4160. continue;
  4161. const long long payload_stop = pos + payload_size;
  4162. assert(payload_stop <= stop); // checked in ParseElement
  4163. const long long element_size = payload_stop - element_start;
  4164. if (id == libwebm::kMkvTrackEntry) {
  4165. Track*& pTrack = *m_trackEntriesEnd;
  4166. pTrack = NULL;
  4167. const long status = ParseTrackEntry(pos, payload_size, element_start,
  4168. element_size, pTrack);
  4169. if (status)
  4170. return status;
  4171. if (pTrack)
  4172. ++m_trackEntriesEnd;
  4173. }
  4174. pos = payload_stop;
  4175. if (pos > stop)
  4176. return E_FILE_FORMAT_INVALID;
  4177. }
  4178. if (pos != stop)
  4179. return E_FILE_FORMAT_INVALID;
  4180. return 0; // success
  4181. }
  4182. unsigned long Tracks::GetTracksCount() const {
  4183. const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries;
  4184. assert(result >= 0);
  4185. return static_cast<unsigned long>(result);
  4186. }
  4187. long Tracks::ParseTrackEntry(long long track_start, long long track_size,
  4188. long long element_start, long long element_size,
  4189. Track*& pResult) const {
  4190. if (pResult)
  4191. return -1;
  4192. IMkvReader* const pReader = m_pSegment->m_pReader;
  4193. long long pos = track_start;
  4194. const long long track_stop = track_start + track_size;
  4195. Track::Info info;
  4196. info.type = 0;
  4197. info.number = 0;
  4198. info.uid = 0;
  4199. info.defaultDuration = 0;
  4200. Track::Settings v;
  4201. v.start = -1;
  4202. v.size = -1;
  4203. Track::Settings a;
  4204. a.start = -1;
  4205. a.size = -1;
  4206. Track::Settings e; // content_encodings_settings;
  4207. e.start = -1;
  4208. e.size = -1;
  4209. long long lacing = 1; // default is true
  4210. while (pos < track_stop) {
  4211. long long id, size;
  4212. const long status = ParseElementHeader(pReader, pos, track_stop, id, size);
  4213. if (status < 0) // error
  4214. return status;
  4215. if (size < 0)
  4216. return E_FILE_FORMAT_INVALID;
  4217. const long long start = pos;
  4218. if (id == libwebm::kMkvVideo) {
  4219. v.start = start;
  4220. v.size = size;
  4221. } else if (id == libwebm::kMkvAudio) {
  4222. a.start = start;
  4223. a.size = size;
  4224. } else if (id == libwebm::kMkvContentEncodings) {
  4225. e.start = start;
  4226. e.size = size;
  4227. } else if (id == libwebm::kMkvTrackUID) {
  4228. if (size > 8)
  4229. return E_FILE_FORMAT_INVALID;
  4230. info.uid = 0;
  4231. long long pos_ = start;
  4232. const long long pos_end = start + size;
  4233. while (pos_ != pos_end) {
  4234. unsigned char b;
  4235. const int status = pReader->Read(pos_, 1, &b);
  4236. if (status)
  4237. return status;
  4238. info.uid <<= 8;
  4239. info.uid |= b;
  4240. ++pos_;
  4241. }
  4242. } else if (id == libwebm::kMkvTrackNumber) {
  4243. const long long num = UnserializeUInt(pReader, pos, size);
  4244. if ((num <= 0) || (num > 127))
  4245. return E_FILE_FORMAT_INVALID;
  4246. info.number = static_cast<long>(num);
  4247. } else if (id == libwebm::kMkvTrackType) {
  4248. const long long type = UnserializeUInt(pReader, pos, size);
  4249. if ((type <= 0) || (type > 254))
  4250. return E_FILE_FORMAT_INVALID;
  4251. info.type = static_cast<long>(type);
  4252. } else if (id == libwebm::kMkvName) {
  4253. const long status =
  4254. UnserializeString(pReader, pos, size, info.nameAsUTF8);
  4255. if (status)
  4256. return status;
  4257. } else if (id == libwebm::kMkvLanguage) {
  4258. const long status = UnserializeString(pReader, pos, size, info.language);
  4259. if (status)
  4260. return status;
  4261. } else if (id == libwebm::kMkvDefaultDuration) {
  4262. const long long duration = UnserializeUInt(pReader, pos, size);
  4263. if (duration < 0)
  4264. return E_FILE_FORMAT_INVALID;
  4265. info.defaultDuration = static_cast<unsigned long long>(duration);
  4266. } else if (id == libwebm::kMkvCodecID) {
  4267. const long status = UnserializeString(pReader, pos, size, info.codecId);
  4268. if (status)
  4269. return status;
  4270. } else if (id == libwebm::kMkvFlagLacing) {
  4271. lacing = UnserializeUInt(pReader, pos, size);
  4272. if ((lacing < 0) || (lacing > 1))
  4273. return E_FILE_FORMAT_INVALID;
  4274. } else if (id == libwebm::kMkvCodecPrivate) {
  4275. delete[] info.codecPrivate;
  4276. info.codecPrivate = NULL;
  4277. info.codecPrivateSize = 0;
  4278. const size_t buflen = static_cast<size_t>(size);
  4279. if (buflen) {
  4280. unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen);
  4281. if (buf == NULL)
  4282. return -1;
  4283. const int status = pReader->Read(pos, static_cast<long>(buflen), buf);
  4284. if (status) {
  4285. delete[] buf;
  4286. return status;
  4287. }
  4288. info.codecPrivate = buf;
  4289. info.codecPrivateSize = buflen;
  4290. }
  4291. } else if (id == libwebm::kMkvCodecName) {
  4292. const long status =
  4293. UnserializeString(pReader, pos, size, info.codecNameAsUTF8);
  4294. if (status)
  4295. return status;
  4296. } else if (id == libwebm::kMkvCodecDelay) {
  4297. info.codecDelay = UnserializeUInt(pReader, pos, size);
  4298. } else if (id == libwebm::kMkvSeekPreRoll) {
  4299. info.seekPreRoll = UnserializeUInt(pReader, pos, size);
  4300. }
  4301. pos += size; // consume payload
  4302. if (pos > track_stop)
  4303. return E_FILE_FORMAT_INVALID;
  4304. }
  4305. if (pos != track_stop)
  4306. return E_FILE_FORMAT_INVALID;
  4307. if (info.number <= 0) // not specified
  4308. return E_FILE_FORMAT_INVALID;
  4309. if (GetTrackByNumber(info.number))
  4310. return E_FILE_FORMAT_INVALID;
  4311. if (info.type <= 0) // not specified
  4312. return E_FILE_FORMAT_INVALID;
  4313. info.lacing = (lacing > 0) ? true : false;
  4314. if (info.type == Track::kVideo) {
  4315. if (v.start < 0)
  4316. return E_FILE_FORMAT_INVALID;
  4317. if (a.start >= 0)
  4318. return E_FILE_FORMAT_INVALID;
  4319. info.settings = v;
  4320. VideoTrack* pTrack = NULL;
  4321. const long status = VideoTrack::Parse(m_pSegment, info, element_start,
  4322. element_size, pTrack);
  4323. if (status)
  4324. return status;
  4325. pResult = pTrack;
  4326. assert(pResult);
  4327. if (e.start >= 0)
  4328. pResult->ParseContentEncodingsEntry(e.start, e.size);
  4329. } else if (info.type == Track::kAudio) {
  4330. if (a.start < 0)
  4331. return E_FILE_FORMAT_INVALID;
  4332. if (v.start >= 0)
  4333. return E_FILE_FORMAT_INVALID;
  4334. info.settings = a;
  4335. AudioTrack* pTrack = NULL;
  4336. const long status = AudioTrack::Parse(m_pSegment, info, element_start,
  4337. element_size, pTrack);
  4338. if (status)
  4339. return status;
  4340. pResult = pTrack;
  4341. assert(pResult);
  4342. if (e.start >= 0)
  4343. pResult->ParseContentEncodingsEntry(e.start, e.size);
  4344. } else {
  4345. // neither video nor audio - probably metadata or subtitles
  4346. if (a.start >= 0)
  4347. return E_FILE_FORMAT_INVALID;
  4348. if (v.start >= 0)
  4349. return E_FILE_FORMAT_INVALID;
  4350. if (info.type == Track::kMetadata && e.start >= 0)
  4351. return E_FILE_FORMAT_INVALID;
  4352. info.settings.start = -1;
  4353. info.settings.size = 0;
  4354. Track* pTrack = NULL;
  4355. const long status =
  4356. Track::Create(m_pSegment, info, element_start, element_size, pTrack);
  4357. if (status)
  4358. return status;
  4359. pResult = pTrack;
  4360. assert(pResult);
  4361. }
  4362. return 0; // success
  4363. }
  4364. Tracks::~Tracks() {
  4365. Track** i = m_trackEntries;
  4366. Track** const j = m_trackEntriesEnd;
  4367. while (i != j) {
  4368. Track* const pTrack = *i++;
  4369. delete pTrack;
  4370. }
  4371. delete[] m_trackEntries;
  4372. }
  4373. const Track* Tracks::GetTrackByNumber(long tn) const {
  4374. if (tn < 0)
  4375. return NULL;
  4376. Track** i = m_trackEntries;
  4377. Track** const j = m_trackEntriesEnd;
  4378. while (i != j) {
  4379. Track* const pTrack = *i++;
  4380. if (pTrack == NULL)
  4381. continue;
  4382. if (tn == pTrack->GetNumber())
  4383. return pTrack;
  4384. }
  4385. return NULL; // not found
  4386. }
  4387. const Track* Tracks::GetTrackByIndex(unsigned long idx) const {
  4388. const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
  4389. if (idx >= static_cast<unsigned long>(count))
  4390. return NULL;
  4391. return m_trackEntries[idx];
  4392. }
  4393. long Cluster::Load(long long& pos, long& len) const {
  4394. if (m_pSegment == NULL)
  4395. return E_PARSE_FAILED;
  4396. if (m_timecode >= 0) // at least partially loaded
  4397. return 0;
  4398. if (m_pos != m_element_start || m_element_size >= 0)
  4399. return E_PARSE_FAILED;
  4400. IMkvReader* const pReader = m_pSegment->m_pReader;
  4401. long long total, avail;
  4402. const int status = pReader->Length(&total, &avail);
  4403. if (status < 0) // error
  4404. return status;
  4405. if (total >= 0 && (avail > total || m_pos > total))
  4406. return E_FILE_FORMAT_INVALID;
  4407. pos = m_pos;
  4408. long long cluster_size = -1;
  4409. if ((pos + 1) > avail) {
  4410. len = 1;
  4411. return E_BUFFER_NOT_FULL;
  4412. }
  4413. long long result = GetUIntLength(pReader, pos, len);
  4414. if (result < 0) // error or underflow
  4415. return static_cast<long>(result);
  4416. if (result > 0)
  4417. return E_BUFFER_NOT_FULL;
  4418. if ((pos + len) > avail)
  4419. return E_BUFFER_NOT_FULL;
  4420. const long long id_ = ReadID(pReader, pos, len);
  4421. if (id_ < 0) // error
  4422. return static_cast<long>(id_);
  4423. if (id_ != libwebm::kMkvCluster)
  4424. return E_FILE_FORMAT_INVALID;
  4425. pos += len; // consume id
  4426. // read cluster size
  4427. if ((pos + 1) > avail) {
  4428. len = 1;
  4429. return E_BUFFER_NOT_FULL;
  4430. }
  4431. result = GetUIntLength(pReader, pos, len);
  4432. if (result < 0) // error
  4433. return static_cast<long>(result);
  4434. if (result > 0)
  4435. return E_BUFFER_NOT_FULL;
  4436. if ((pos + len) > avail)
  4437. return E_BUFFER_NOT_FULL;
  4438. const long long size = ReadUInt(pReader, pos, len);
  4439. if (size < 0) // error
  4440. return static_cast<long>(cluster_size);
  4441. if (size == 0)
  4442. return E_FILE_FORMAT_INVALID;
  4443. pos += len; // consume length of size of element
  4444. const long long unknown_size = (1LL << (7 * len)) - 1;
  4445. if (size != unknown_size)
  4446. cluster_size = size;
  4447. // pos points to start of payload
  4448. long long timecode = -1;
  4449. long long new_pos = -1;
  4450. bool bBlock = false;
  4451. long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
  4452. for (;;) {
  4453. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  4454. break;
  4455. // Parse ID
  4456. if ((pos + 1) > avail) {
  4457. len = 1;
  4458. return E_BUFFER_NOT_FULL;
  4459. }
  4460. long long result = GetUIntLength(pReader, pos, len);
  4461. if (result < 0) // error
  4462. return static_cast<long>(result);
  4463. if (result > 0)
  4464. return E_BUFFER_NOT_FULL;
  4465. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4466. return E_FILE_FORMAT_INVALID;
  4467. if ((pos + len) > avail)
  4468. return E_BUFFER_NOT_FULL;
  4469. const long long id = ReadID(pReader, pos, len);
  4470. if (id < 0) // error
  4471. return static_cast<long>(id);
  4472. if (id == 0)
  4473. return E_FILE_FORMAT_INVALID;
  4474. // This is the distinguished set of ID's we use to determine
  4475. // that we have exhausted the sub-element's inside the cluster
  4476. // whose ID we parsed earlier.
  4477. if (id == libwebm::kMkvCluster)
  4478. break;
  4479. if (id == libwebm::kMkvCues)
  4480. break;
  4481. pos += len; // consume ID field
  4482. // Parse Size
  4483. if ((pos + 1) > avail) {
  4484. len = 1;
  4485. return E_BUFFER_NOT_FULL;
  4486. }
  4487. result = GetUIntLength(pReader, pos, len);
  4488. if (result < 0) // error
  4489. return static_cast<long>(result);
  4490. if (result > 0)
  4491. return E_BUFFER_NOT_FULL;
  4492. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4493. return E_FILE_FORMAT_INVALID;
  4494. if ((pos + len) > avail)
  4495. return E_BUFFER_NOT_FULL;
  4496. const long long size = ReadUInt(pReader, pos, len);
  4497. if (size < 0) // error
  4498. return static_cast<long>(size);
  4499. const long long unknown_size = (1LL << (7 * len)) - 1;
  4500. if (size == unknown_size)
  4501. return E_FILE_FORMAT_INVALID;
  4502. pos += len; // consume size field
  4503. if ((cluster_stop >= 0) && (pos > cluster_stop))
  4504. return E_FILE_FORMAT_INVALID;
  4505. // pos now points to start of payload
  4506. if (size == 0)
  4507. continue;
  4508. if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
  4509. return E_FILE_FORMAT_INVALID;
  4510. if (id == libwebm::kMkvTimecode) {
  4511. len = static_cast<long>(size);
  4512. if ((pos + size) > avail)
  4513. return E_BUFFER_NOT_FULL;
  4514. timecode = UnserializeUInt(pReader, pos, size);
  4515. if (timecode < 0) // error (or underflow)
  4516. return static_cast<long>(timecode);
  4517. new_pos = pos + size;
  4518. if (bBlock)
  4519. break;
  4520. } else if (id == libwebm::kMkvBlockGroup) {
  4521. bBlock = true;
  4522. break;
  4523. } else if (id == libwebm::kMkvSimpleBlock) {
  4524. bBlock = true;
  4525. break;
  4526. }
  4527. pos += size; // consume payload
  4528. if (cluster_stop >= 0 && pos > cluster_stop)
  4529. return E_FILE_FORMAT_INVALID;
  4530. }
  4531. if (cluster_stop >= 0 && pos > cluster_stop)
  4532. return E_FILE_FORMAT_INVALID;
  4533. if (timecode < 0) // no timecode found
  4534. return E_FILE_FORMAT_INVALID;
  4535. if (!bBlock)
  4536. return E_FILE_FORMAT_INVALID;
  4537. m_pos = new_pos; // designates position just beyond timecode payload
  4538. m_timecode = timecode; // m_timecode >= 0 means we're partially loaded
  4539. if (cluster_size >= 0)
  4540. m_element_size = cluster_stop - m_element_start;
  4541. return 0;
  4542. }
  4543. long Cluster::Parse(long long& pos, long& len) const {
  4544. long status = Load(pos, len);
  4545. if (status < 0)
  4546. return status;
  4547. if (m_pos < m_element_start || m_timecode < 0)
  4548. return E_PARSE_FAILED;
  4549. const long long cluster_stop =
  4550. (m_element_size < 0) ? -1 : m_element_start + m_element_size;
  4551. if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
  4552. return 1; // nothing else to do
  4553. IMkvReader* const pReader = m_pSegment->m_pReader;
  4554. long long total, avail;
  4555. status = pReader->Length(&total, &avail);
  4556. if (status < 0) // error
  4557. return status;
  4558. if (total >= 0 && avail > total)
  4559. return E_FILE_FORMAT_INVALID;
  4560. pos = m_pos;
  4561. for (;;) {
  4562. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  4563. break;
  4564. if ((total >= 0) && (pos >= total)) {
  4565. if (m_element_size < 0)
  4566. m_element_size = pos - m_element_start;
  4567. break;
  4568. }
  4569. // Parse ID
  4570. if ((pos + 1) > avail) {
  4571. len = 1;
  4572. return E_BUFFER_NOT_FULL;
  4573. }
  4574. long long result = GetUIntLength(pReader, pos, len);
  4575. if (result < 0) // error
  4576. return static_cast<long>(result);
  4577. if (result > 0)
  4578. return E_BUFFER_NOT_FULL;
  4579. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4580. return E_FILE_FORMAT_INVALID;
  4581. if ((pos + len) > avail)
  4582. return E_BUFFER_NOT_FULL;
  4583. const long long id = ReadID(pReader, pos, len);
  4584. if (id < 0)
  4585. return E_FILE_FORMAT_INVALID;
  4586. // This is the distinguished set of ID's we use to determine
  4587. // that we have exhausted the sub-element's inside the cluster
  4588. // whose ID we parsed earlier.
  4589. if ((id == libwebm::kMkvCluster) || (id == libwebm::kMkvCues)) {
  4590. if (m_element_size < 0)
  4591. m_element_size = pos - m_element_start;
  4592. break;
  4593. }
  4594. pos += len; // consume ID field
  4595. // Parse Size
  4596. if ((pos + 1) > avail) {
  4597. len = 1;
  4598. return E_BUFFER_NOT_FULL;
  4599. }
  4600. result = GetUIntLength(pReader, pos, len);
  4601. if (result < 0) // error
  4602. return static_cast<long>(result);
  4603. if (result > 0)
  4604. return E_BUFFER_NOT_FULL;
  4605. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  4606. return E_FILE_FORMAT_INVALID;
  4607. if ((pos + len) > avail)
  4608. return E_BUFFER_NOT_FULL;
  4609. const long long size = ReadUInt(pReader, pos, len);
  4610. if (size < 0) // error
  4611. return static_cast<long>(size);
  4612. const long long unknown_size = (1LL << (7 * len)) - 1;
  4613. if (size == unknown_size)
  4614. return E_FILE_FORMAT_INVALID;
  4615. pos += len; // consume size field
  4616. if ((cluster_stop >= 0) && (pos > cluster_stop))
  4617. return E_FILE_FORMAT_INVALID;
  4618. // pos now points to start of payload
  4619. if (size == 0)
  4620. continue;
  4621. // const long long block_start = pos;
  4622. const long long block_stop = pos + size;
  4623. if (cluster_stop >= 0) {
  4624. if (block_stop > cluster_stop) {
  4625. if (id == libwebm::kMkvBlockGroup || id == libwebm::kMkvSimpleBlock) {
  4626. return E_FILE_FORMAT_INVALID;
  4627. }
  4628. pos = cluster_stop;
  4629. break;
  4630. }
  4631. } else if ((total >= 0) && (block_stop > total)) {
  4632. m_element_size = total - m_element_start;
  4633. pos = total;
  4634. break;
  4635. } else if (block_stop > avail) {
  4636. len = static_cast<long>(size);
  4637. return E_BUFFER_NOT_FULL;
  4638. }
  4639. Cluster* const this_ = const_cast<Cluster*>(this);
  4640. if (id == libwebm::kMkvBlockGroup)
  4641. return this_->ParseBlockGroup(size, pos, len);
  4642. if (id == libwebm::kMkvSimpleBlock)
  4643. return this_->ParseSimpleBlock(size, pos, len);
  4644. pos += size; // consume payload
  4645. if (cluster_stop >= 0 && pos > cluster_stop)
  4646. return E_FILE_FORMAT_INVALID;
  4647. }
  4648. if (m_element_size < 1)
  4649. return E_FILE_FORMAT_INVALID;
  4650. m_pos = pos;
  4651. if (cluster_stop >= 0 && m_pos > cluster_stop)
  4652. return E_FILE_FORMAT_INVALID;
  4653. if (m_entries_count > 0) {
  4654. const long idx = m_entries_count - 1;
  4655. const BlockEntry* const pLast = m_entries[idx];
  4656. if (pLast == NULL)
  4657. return E_PARSE_FAILED;
  4658. const Block* const pBlock = pLast->GetBlock();
  4659. if (pBlock == NULL)
  4660. return E_PARSE_FAILED;
  4661. const long long start = pBlock->m_start;
  4662. if ((total >= 0) && (start > total))
  4663. return E_PARSE_FAILED; // defend against trucated stream
  4664. const long long size = pBlock->m_size;
  4665. const long long stop = start + size;
  4666. if (cluster_stop >= 0 && stop > cluster_stop)
  4667. return E_FILE_FORMAT_INVALID;
  4668. if ((total >= 0) && (stop > total))
  4669. return E_PARSE_FAILED; // defend against trucated stream
  4670. }
  4671. return 1; // no more entries
  4672. }
  4673. long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
  4674. long& len) {
  4675. const long long block_start = pos;
  4676. const long long block_stop = pos + block_size;
  4677. IMkvReader* const pReader = m_pSegment->m_pReader;
  4678. long long total, avail;
  4679. long status = pReader->Length(&total, &avail);
  4680. if (status < 0) // error
  4681. return status;
  4682. assert((total < 0) || (avail <= total));
  4683. // parse track number
  4684. if ((pos + 1) > avail) {
  4685. len = 1;
  4686. return E_BUFFER_NOT_FULL;
  4687. }
  4688. long long result = GetUIntLength(pReader, pos, len);
  4689. if (result < 0) // error
  4690. return static_cast<long>(result);
  4691. if (result > 0) // weird
  4692. return E_BUFFER_NOT_FULL;
  4693. if ((pos + len) > block_stop)
  4694. return E_FILE_FORMAT_INVALID;
  4695. if ((pos + len) > avail)
  4696. return E_BUFFER_NOT_FULL;
  4697. const long long track = ReadUInt(pReader, pos, len);
  4698. if (track < 0) // error
  4699. return static_cast<long>(track);
  4700. if (track == 0)
  4701. return E_FILE_FORMAT_INVALID;
  4702. pos += len; // consume track number
  4703. if ((pos + 2) > block_stop)
  4704. return E_FILE_FORMAT_INVALID;
  4705. if ((pos + 2) > avail) {
  4706. len = 2;
  4707. return E_BUFFER_NOT_FULL;
  4708. }
  4709. pos += 2; // consume timecode
  4710. if ((pos + 1) > block_stop)
  4711. return E_FILE_FORMAT_INVALID;
  4712. if ((pos + 1) > avail) {
  4713. len = 1;
  4714. return E_BUFFER_NOT_FULL;
  4715. }
  4716. unsigned char flags;
  4717. status = pReader->Read(pos, 1, &flags);
  4718. if (status < 0) { // error or underflow
  4719. len = 1;
  4720. return status;
  4721. }
  4722. ++pos; // consume flags byte
  4723. assert(pos <= avail);
  4724. if (pos >= block_stop)
  4725. return E_FILE_FORMAT_INVALID;
  4726. const int lacing = int(flags & 0x06) >> 1;
  4727. if ((lacing != 0) && (block_stop > avail)) {
  4728. len = static_cast<long>(block_stop - pos);
  4729. return E_BUFFER_NOT_FULL;
  4730. }
  4731. status = CreateBlock(libwebm::kMkvSimpleBlock, block_start, block_size,
  4732. 0); // DiscardPadding
  4733. if (status != 0)
  4734. return status;
  4735. m_pos = block_stop;
  4736. return 0; // success
  4737. }
  4738. long Cluster::ParseBlockGroup(long long payload_size, long long& pos,
  4739. long& len) {
  4740. const long long payload_start = pos;
  4741. const long long payload_stop = pos + payload_size;
  4742. IMkvReader* const pReader = m_pSegment->m_pReader;
  4743. long long total, avail;
  4744. long status = pReader->Length(&total, &avail);
  4745. if (status < 0) // error
  4746. return status;
  4747. assert((total < 0) || (avail <= total));
  4748. if ((total >= 0) && (payload_stop > total))
  4749. return E_FILE_FORMAT_INVALID;
  4750. if (payload_stop > avail) {
  4751. len = static_cast<long>(payload_size);
  4752. return E_BUFFER_NOT_FULL;
  4753. }
  4754. long long discard_padding = 0;
  4755. while (pos < payload_stop) {
  4756. // parse sub-block element ID
  4757. if ((pos + 1) > avail) {
  4758. len = 1;
  4759. return E_BUFFER_NOT_FULL;
  4760. }
  4761. long long result = GetUIntLength(pReader, pos, len);
  4762. if (result < 0) // error
  4763. return static_cast<long>(result);
  4764. if (result > 0) // weird
  4765. return E_BUFFER_NOT_FULL;
  4766. if ((pos + len) > payload_stop)
  4767. return E_FILE_FORMAT_INVALID;
  4768. if ((pos + len) > avail)
  4769. return E_BUFFER_NOT_FULL;
  4770. const long long id = ReadID(pReader, pos, len);
  4771. if (id < 0) // error
  4772. return static_cast<long>(id);
  4773. if (id == 0) // not a valid ID
  4774. return E_FILE_FORMAT_INVALID;
  4775. pos += len; // consume ID field
  4776. // Parse Size
  4777. if ((pos + 1) > avail) {
  4778. len = 1;
  4779. return E_BUFFER_NOT_FULL;
  4780. }
  4781. result = GetUIntLength(pReader, pos, len);
  4782. if (result < 0) // error
  4783. return static_cast<long>(result);
  4784. if (result > 0) // weird
  4785. return E_BUFFER_NOT_FULL;
  4786. if ((pos + len) > payload_stop)
  4787. return E_FILE_FORMAT_INVALID;
  4788. if ((pos + len) > avail)
  4789. return E_BUFFER_NOT_FULL;
  4790. const long long size = ReadUInt(pReader, pos, len);
  4791. if (size < 0) // error
  4792. return static_cast<long>(size);
  4793. pos += len; // consume size field
  4794. // pos now points to start of sub-block group payload
  4795. if (pos > payload_stop)
  4796. return E_FILE_FORMAT_INVALID;
  4797. if (size == 0) // weird
  4798. continue;
  4799. const long long unknown_size = (1LL << (7 * len)) - 1;
  4800. if (size == unknown_size)
  4801. return E_FILE_FORMAT_INVALID;
  4802. if (id == libwebm::kMkvDiscardPadding) {
  4803. status = UnserializeInt(pReader, pos, size, discard_padding);
  4804. if (status < 0) // error
  4805. return status;
  4806. }
  4807. if (id != libwebm::kMkvBlock) {
  4808. pos += size; // consume sub-part of block group
  4809. if (pos > payload_stop)
  4810. return E_FILE_FORMAT_INVALID;
  4811. continue;
  4812. }
  4813. const long long block_stop = pos + size;
  4814. if (block_stop > payload_stop)
  4815. return E_FILE_FORMAT_INVALID;
  4816. // parse track number
  4817. if ((pos + 1) > avail) {
  4818. len = 1;
  4819. return E_BUFFER_NOT_FULL;
  4820. }
  4821. result = GetUIntLength(pReader, pos, len);
  4822. if (result < 0) // error
  4823. return static_cast<long>(result);
  4824. if (result > 0) // weird
  4825. return E_BUFFER_NOT_FULL;
  4826. if ((pos + len) > block_stop)
  4827. return E_FILE_FORMAT_INVALID;
  4828. if ((pos + len) > avail)
  4829. return E_BUFFER_NOT_FULL;
  4830. const long long track = ReadUInt(pReader, pos, len);
  4831. if (track < 0) // error
  4832. return static_cast<long>(track);
  4833. if (track == 0)
  4834. return E_FILE_FORMAT_INVALID;
  4835. pos += len; // consume track number
  4836. if ((pos + 2) > block_stop)
  4837. return E_FILE_FORMAT_INVALID;
  4838. if ((pos + 2) > avail) {
  4839. len = 2;
  4840. return E_BUFFER_NOT_FULL;
  4841. }
  4842. pos += 2; // consume timecode
  4843. if ((pos + 1) > block_stop)
  4844. return E_FILE_FORMAT_INVALID;
  4845. if ((pos + 1) > avail) {
  4846. len = 1;
  4847. return E_BUFFER_NOT_FULL;
  4848. }
  4849. unsigned char flags;
  4850. status = pReader->Read(pos, 1, &flags);
  4851. if (status < 0) { // error or underflow
  4852. len = 1;
  4853. return status;
  4854. }
  4855. ++pos; // consume flags byte
  4856. assert(pos <= avail);
  4857. if (pos >= block_stop)
  4858. return E_FILE_FORMAT_INVALID;
  4859. const int lacing = int(flags & 0x06) >> 1;
  4860. if ((lacing != 0) && (block_stop > avail)) {
  4861. len = static_cast<long>(block_stop - pos);
  4862. return E_BUFFER_NOT_FULL;
  4863. }
  4864. pos = block_stop; // consume block-part of block group
  4865. if (pos > payload_stop)
  4866. return E_FILE_FORMAT_INVALID;
  4867. }
  4868. if (pos != payload_stop)
  4869. return E_FILE_FORMAT_INVALID;
  4870. status = CreateBlock(libwebm::kMkvBlockGroup, payload_start, payload_size,
  4871. discard_padding);
  4872. if (status != 0)
  4873. return status;
  4874. m_pos = payload_stop;
  4875. return 0; // success
  4876. }
  4877. long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const {
  4878. assert(m_pos >= m_element_start);
  4879. pEntry = NULL;
  4880. if (index < 0)
  4881. return -1; // generic error
  4882. if (m_entries_count < 0)
  4883. return E_BUFFER_NOT_FULL;
  4884. assert(m_entries);
  4885. assert(m_entries_size > 0);
  4886. assert(m_entries_count <= m_entries_size);
  4887. if (index < m_entries_count) {
  4888. pEntry = m_entries[index];
  4889. assert(pEntry);
  4890. return 1; // found entry
  4891. }
  4892. if (m_element_size < 0) // we don't know cluster end yet
  4893. return E_BUFFER_NOT_FULL; // underflow
  4894. const long long element_stop = m_element_start + m_element_size;
  4895. if (m_pos >= element_stop)
  4896. return 0; // nothing left to parse
  4897. return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed
  4898. }
  4899. Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) {
  4900. if (!pSegment || off < 0)
  4901. return NULL;
  4902. const long long element_start = pSegment->m_start + off;
  4903. Cluster* const pCluster =
  4904. new (std::nothrow) Cluster(pSegment, idx, element_start);
  4905. return pCluster;
  4906. }
  4907. Cluster::Cluster()
  4908. : m_pSegment(NULL),
  4909. m_element_start(0),
  4910. m_index(0),
  4911. m_pos(0),
  4912. m_element_size(0),
  4913. m_timecode(0),
  4914. m_entries(NULL),
  4915. m_entries_size(0),
  4916. m_entries_count(0) // means "no entries"
  4917. {}
  4918. Cluster::Cluster(Segment* pSegment, long idx, long long element_start
  4919. /* long long element_size */)
  4920. : m_pSegment(pSegment),
  4921. m_element_start(element_start),
  4922. m_index(idx),
  4923. m_pos(element_start),
  4924. m_element_size(-1 /* element_size */),
  4925. m_timecode(-1),
  4926. m_entries(NULL),
  4927. m_entries_size(0),
  4928. m_entries_count(-1) // means "has not been parsed yet"
  4929. {}
  4930. Cluster::~Cluster() {
  4931. if (m_entries_count <= 0) {
  4932. delete[] m_entries;
  4933. return;
  4934. }
  4935. BlockEntry** i = m_entries;
  4936. BlockEntry** const j = m_entries + m_entries_count;
  4937. while (i != j) {
  4938. BlockEntry* p = *i++;
  4939. assert(p);
  4940. delete p;
  4941. }
  4942. delete[] m_entries;
  4943. }
  4944. bool Cluster::EOS() const { return (m_pSegment == NULL); }
  4945. long Cluster::GetIndex() const { return m_index; }
  4946. long long Cluster::GetPosition() const {
  4947. const long long pos = m_element_start - m_pSegment->m_start;
  4948. assert(pos >= 0);
  4949. return pos;
  4950. }
  4951. long long Cluster::GetElementSize() const { return m_element_size; }
  4952. long Cluster::HasBlockEntries(
  4953. const Segment* pSegment,
  4954. long long off, // relative to start of segment payload
  4955. long long& pos, long& len) {
  4956. assert(pSegment);
  4957. assert(off >= 0); // relative to segment
  4958. IMkvReader* const pReader = pSegment->m_pReader;
  4959. long long total, avail;
  4960. long status = pReader->Length(&total, &avail);
  4961. if (status < 0) // error
  4962. return status;
  4963. assert((total < 0) || (avail <= total));
  4964. pos = pSegment->m_start + off; // absolute
  4965. if ((total >= 0) && (pos >= total))
  4966. return 0; // we don't even have a complete cluster
  4967. const long long segment_stop =
  4968. (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size;
  4969. long long cluster_stop = -1; // interpreted later to mean "unknown size"
  4970. {
  4971. if ((pos + 1) > avail) {
  4972. len = 1;
  4973. return E_BUFFER_NOT_FULL;
  4974. }
  4975. long long result = GetUIntLength(pReader, pos, len);
  4976. if (result < 0) // error
  4977. return static_cast<long>(result);
  4978. if (result > 0) // need more data
  4979. return E_BUFFER_NOT_FULL;
  4980. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  4981. return E_FILE_FORMAT_INVALID;
  4982. if ((total >= 0) && ((pos + len) > total))
  4983. return 0;
  4984. if ((pos + len) > avail)
  4985. return E_BUFFER_NOT_FULL;
  4986. const long long id = ReadID(pReader, pos, len);
  4987. if (id < 0) // error
  4988. return static_cast<long>(id);
  4989. if (id != libwebm::kMkvCluster)
  4990. return E_PARSE_FAILED;
  4991. pos += len; // consume Cluster ID field
  4992. // read size field
  4993. if ((pos + 1) > avail) {
  4994. len = 1;
  4995. return E_BUFFER_NOT_FULL;
  4996. }
  4997. result = GetUIntLength(pReader, pos, len);
  4998. if (result < 0) // error
  4999. return static_cast<long>(result);
  5000. if (result > 0) // weird
  5001. return E_BUFFER_NOT_FULL;
  5002. if ((segment_stop >= 0) && ((pos + len) > segment_stop))
  5003. return E_FILE_FORMAT_INVALID;
  5004. if ((total >= 0) && ((pos + len) > total))
  5005. return 0;
  5006. if ((pos + len) > avail)
  5007. return E_BUFFER_NOT_FULL;
  5008. const long long size = ReadUInt(pReader, pos, len);
  5009. if (size < 0) // error
  5010. return static_cast<long>(size);
  5011. if (size == 0)
  5012. return 0; // cluster does not have entries
  5013. pos += len; // consume size field
  5014. // pos now points to start of payload
  5015. const long long unknown_size = (1LL << (7 * len)) - 1;
  5016. if (size != unknown_size) {
  5017. cluster_stop = pos + size;
  5018. assert(cluster_stop >= 0);
  5019. if ((segment_stop >= 0) && (cluster_stop > segment_stop))
  5020. return E_FILE_FORMAT_INVALID;
  5021. if ((total >= 0) && (cluster_stop > total))
  5022. // return E_FILE_FORMAT_INVALID; //too conservative
  5023. return 0; // cluster does not have any entries
  5024. }
  5025. }
  5026. for (;;) {
  5027. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  5028. return 0; // no entries detected
  5029. if ((pos + 1) > avail) {
  5030. len = 1;
  5031. return E_BUFFER_NOT_FULL;
  5032. }
  5033. long long result = GetUIntLength(pReader, pos, len);
  5034. if (result < 0) // error
  5035. return static_cast<long>(result);
  5036. if (result > 0) // need more data
  5037. return E_BUFFER_NOT_FULL;
  5038. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  5039. return E_FILE_FORMAT_INVALID;
  5040. if ((pos + len) > avail)
  5041. return E_BUFFER_NOT_FULL;
  5042. const long long id = ReadID(pReader, pos, len);
  5043. if (id < 0) // error
  5044. return static_cast<long>(id);
  5045. // This is the distinguished set of ID's we use to determine
  5046. // that we have exhausted the sub-element's inside the cluster
  5047. // whose ID we parsed earlier.
  5048. if (id == libwebm::kMkvCluster)
  5049. return 0; // no entries found
  5050. if (id == libwebm::kMkvCues)
  5051. return 0; // no entries found
  5052. pos += len; // consume id field
  5053. if ((cluster_stop >= 0) && (pos >= cluster_stop))
  5054. return E_FILE_FORMAT_INVALID;
  5055. // read size field
  5056. if ((pos + 1) > avail) {
  5057. len = 1;
  5058. return E_BUFFER_NOT_FULL;
  5059. }
  5060. result = GetUIntLength(pReader, pos, len);
  5061. if (result < 0) // error
  5062. return static_cast<long>(result);
  5063. if (result > 0) // underflow
  5064. return E_BUFFER_NOT_FULL;
  5065. if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
  5066. return E_FILE_FORMAT_INVALID;
  5067. if ((pos + len) > avail)
  5068. return E_BUFFER_NOT_FULL;
  5069. const long long size = ReadUInt(pReader, pos, len);
  5070. if (size < 0) // error
  5071. return static_cast<long>(size);
  5072. pos += len; // consume size field
  5073. // pos now points to start of payload
  5074. if ((cluster_stop >= 0) && (pos > cluster_stop))
  5075. return E_FILE_FORMAT_INVALID;
  5076. if (size == 0) // weird
  5077. continue;
  5078. const long long unknown_size = (1LL << (7 * len)) - 1;
  5079. if (size == unknown_size)
  5080. return E_FILE_FORMAT_INVALID; // not supported inside cluster
  5081. if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
  5082. return E_FILE_FORMAT_INVALID;
  5083. if (id == libwebm::kMkvBlockGroup)
  5084. return 1; // have at least one entry
  5085. if (id == libwebm::kMkvSimpleBlock)
  5086. return 1; // have at least one entry
  5087. pos += size; // consume payload
  5088. if (cluster_stop >= 0 && pos > cluster_stop)
  5089. return E_FILE_FORMAT_INVALID;
  5090. }
  5091. }
  5092. long long Cluster::GetTimeCode() const {
  5093. long long pos;
  5094. long len;
  5095. const long status = Load(pos, len);
  5096. if (status < 0) // error
  5097. return status;
  5098. return m_timecode;
  5099. }
  5100. long long Cluster::GetTime() const {
  5101. const long long tc = GetTimeCode();
  5102. if (tc < 0)
  5103. return tc;
  5104. const SegmentInfo* const pInfo = m_pSegment->GetInfo();
  5105. assert(pInfo);
  5106. const long long scale = pInfo->GetTimeCodeScale();
  5107. assert(scale >= 1);
  5108. const long long t = m_timecode * scale;
  5109. return t;
  5110. }
  5111. long long Cluster::GetFirstTime() const {
  5112. const BlockEntry* pEntry;
  5113. const long status = GetFirst(pEntry);
  5114. if (status < 0) // error
  5115. return status;
  5116. if (pEntry == NULL) // empty cluster
  5117. return GetTime();
  5118. const Block* const pBlock = pEntry->GetBlock();
  5119. assert(pBlock);
  5120. return pBlock->GetTime(this);
  5121. }
  5122. long long Cluster::GetLastTime() const {
  5123. const BlockEntry* pEntry;
  5124. const long status = GetLast(pEntry);
  5125. if (status < 0) // error
  5126. return status;
  5127. if (pEntry == NULL) // empty cluster
  5128. return GetTime();
  5129. const Block* const pBlock = pEntry->GetBlock();
  5130. assert(pBlock);
  5131. return pBlock->GetTime(this);
  5132. }
  5133. long Cluster::CreateBlock(long long id,
  5134. long long pos, // absolute pos of payload
  5135. long long size, long long discard_padding) {
  5136. if (id != libwebm::kMkvBlockGroup && id != libwebm::kMkvSimpleBlock)
  5137. return E_PARSE_FAILED;
  5138. if (m_entries_count < 0) { // haven't parsed anything yet
  5139. assert(m_entries == NULL);
  5140. assert(m_entries_size == 0);
  5141. m_entries_size = 1024;
  5142. m_entries = new (std::nothrow) BlockEntry*[m_entries_size];
  5143. if (m_entries == NULL)
  5144. return -1;
  5145. m_entries_count = 0;
  5146. } else {
  5147. assert(m_entries);
  5148. assert(m_entries_size > 0);
  5149. assert(m_entries_count <= m_entries_size);
  5150. if (m_entries_count >= m_entries_size) {
  5151. const long entries_size = 2 * m_entries_size;
  5152. BlockEntry** const entries = new (std::nothrow) BlockEntry*[entries_size];
  5153. if (entries == NULL)
  5154. return -1;
  5155. BlockEntry** src = m_entries;
  5156. BlockEntry** const src_end = src + m_entries_count;
  5157. BlockEntry** dst = entries;
  5158. while (src != src_end)
  5159. *dst++ = *src++;
  5160. delete[] m_entries;
  5161. m_entries = entries;
  5162. m_entries_size = entries_size;
  5163. }
  5164. }
  5165. if (id == libwebm::kMkvBlockGroup)
  5166. return CreateBlockGroup(pos, size, discard_padding);
  5167. else
  5168. return CreateSimpleBlock(pos, size);
  5169. }
  5170. long Cluster::CreateBlockGroup(long long start_offset, long long size,
  5171. long long discard_padding) {
  5172. assert(m_entries);
  5173. assert(m_entries_size > 0);
  5174. assert(m_entries_count >= 0);
  5175. assert(m_entries_count < m_entries_size);
  5176. IMkvReader* const pReader = m_pSegment->m_pReader;
  5177. long long pos = start_offset;
  5178. const long long stop = start_offset + size;
  5179. // For WebM files, there is a bias towards previous reference times
  5180. //(in order to support alt-ref frames, which refer back to the previous
  5181. // keyframe). Normally a 0 value is not possible, but here we tenatively
  5182. // allow 0 as the value of a reference frame, with the interpretation
  5183. // that this is a "previous" reference time.
  5184. long long prev = 1; // nonce
  5185. long long next = 0; // nonce
  5186. long long duration = -1; // really, this is unsigned
  5187. long long bpos = -1;
  5188. long long bsize = -1;
  5189. while (pos < stop) {
  5190. long len;
  5191. const long long id = ReadID(pReader, pos, len);
  5192. if (id < 0 || (pos + len) > stop)
  5193. return E_FILE_FORMAT_INVALID;
  5194. pos += len; // consume ID
  5195. const long long size = ReadUInt(pReader, pos, len);
  5196. assert(size >= 0); // TODO
  5197. assert((pos + len) <= stop);
  5198. pos += len; // consume size
  5199. if (id == libwebm::kMkvBlock) {
  5200. if (bpos < 0) { // Block ID
  5201. bpos = pos;
  5202. bsize = size;
  5203. }
  5204. } else if (id == libwebm::kMkvBlockDuration) {
  5205. if (size > 8)
  5206. return E_FILE_FORMAT_INVALID;
  5207. duration = UnserializeUInt(pReader, pos, size);
  5208. if (duration < 0)
  5209. return E_FILE_FORMAT_INVALID;
  5210. } else if (id == libwebm::kMkvReferenceBlock) {
  5211. if (size > 8 || size <= 0)
  5212. return E_FILE_FORMAT_INVALID;
  5213. const long size_ = static_cast<long>(size);
  5214. long long time;
  5215. long status = UnserializeInt(pReader, pos, size_, time);
  5216. assert(status == 0);
  5217. if (status != 0)
  5218. return -1;
  5219. if (time <= 0) // see note above
  5220. prev = time;
  5221. else
  5222. next = time;
  5223. }
  5224. pos += size; // consume payload
  5225. if (pos > stop)
  5226. return E_FILE_FORMAT_INVALID;
  5227. }
  5228. if (bpos < 0)
  5229. return E_FILE_FORMAT_INVALID;
  5230. if (pos != stop)
  5231. return E_FILE_FORMAT_INVALID;
  5232. assert(bsize >= 0);
  5233. const long idx = m_entries_count;
  5234. BlockEntry** const ppEntry = m_entries + idx;
  5235. BlockEntry*& pEntry = *ppEntry;
  5236. pEntry = new (std::nothrow)
  5237. BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding);
  5238. if (pEntry == NULL)
  5239. return -1; // generic error
  5240. BlockGroup* const p = static_cast<BlockGroup*>(pEntry);
  5241. const long status = p->Parse();
  5242. if (status == 0) { // success
  5243. ++m_entries_count;
  5244. return 0;
  5245. }
  5246. delete pEntry;
  5247. pEntry = 0;
  5248. return status;
  5249. }
  5250. long Cluster::CreateSimpleBlock(long long st, long long sz) {
  5251. assert(m_entries);
  5252. assert(m_entries_size > 0);
  5253. assert(m_entries_count >= 0);
  5254. assert(m_entries_count < m_entries_size);
  5255. const long idx = m_entries_count;
  5256. BlockEntry** const ppEntry = m_entries + idx;
  5257. BlockEntry*& pEntry = *ppEntry;
  5258. pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz);
  5259. if (pEntry == NULL)
  5260. return -1; // generic error
  5261. SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry);
  5262. const long status = p->Parse();
  5263. if (status == 0) {
  5264. ++m_entries_count;
  5265. return 0;
  5266. }
  5267. delete pEntry;
  5268. pEntry = 0;
  5269. return status;
  5270. }
  5271. long Cluster::GetFirst(const BlockEntry*& pFirst) const {
  5272. if (m_entries_count <= 0) {
  5273. long long pos;
  5274. long len;
  5275. const long status = Parse(pos, len);
  5276. if (status < 0) { // error
  5277. pFirst = NULL;
  5278. return status;
  5279. }
  5280. if (m_entries_count <= 0) { // empty cluster
  5281. pFirst = NULL;
  5282. return 0;
  5283. }
  5284. }
  5285. assert(m_entries);
  5286. pFirst = m_entries[0];
  5287. assert(pFirst);
  5288. return 0; // success
  5289. }
  5290. long Cluster::GetLast(const BlockEntry*& pLast) const {
  5291. for (;;) {
  5292. long long pos;
  5293. long len;
  5294. const long status = Parse(pos, len);
  5295. if (status < 0) { // error
  5296. pLast = NULL;
  5297. return status;
  5298. }
  5299. if (status > 0) // no new block
  5300. break;
  5301. }
  5302. if (m_entries_count <= 0) {
  5303. pLast = NULL;
  5304. return 0;
  5305. }
  5306. assert(m_entries);
  5307. const long idx = m_entries_count - 1;
  5308. pLast = m_entries[idx];
  5309. assert(pLast);
  5310. return 0;
  5311. }
  5312. long Cluster::GetNext(const BlockEntry* pCurr, const BlockEntry*& pNext) const {
  5313. assert(pCurr);
  5314. assert(m_entries);
  5315. assert(m_entries_count > 0);
  5316. size_t idx = pCurr->GetIndex();
  5317. assert(idx < size_t(m_entries_count));
  5318. assert(m_entries[idx] == pCurr);
  5319. ++idx;
  5320. if (idx >= size_t(m_entries_count)) {
  5321. long long pos;
  5322. long len;
  5323. const long status = Parse(pos, len);
  5324. if (status < 0) { // error
  5325. pNext = NULL;
  5326. return status;
  5327. }
  5328. if (status > 0) {
  5329. pNext = NULL;
  5330. return 0;
  5331. }
  5332. assert(m_entries);
  5333. assert(m_entries_count > 0);
  5334. assert(idx < size_t(m_entries_count));
  5335. }
  5336. pNext = m_entries[idx];
  5337. assert(pNext);
  5338. return 0;
  5339. }
  5340. long Cluster::GetEntryCount() const { return m_entries_count; }
  5341. const BlockEntry* Cluster::GetEntry(const Track* pTrack,
  5342. long long time_ns) const {
  5343. assert(pTrack);
  5344. if (m_pSegment == NULL) // this is the special EOS cluster
  5345. return pTrack->GetEOS();
  5346. const BlockEntry* pResult = pTrack->GetEOS();
  5347. long index = 0;
  5348. for (;;) {
  5349. if (index >= m_entries_count) {
  5350. long long pos;
  5351. long len;
  5352. const long status = Parse(pos, len);
  5353. assert(status >= 0);
  5354. if (status > 0) // completely parsed, and no more entries
  5355. return pResult;
  5356. if (status < 0) // should never happen
  5357. return 0;
  5358. assert(m_entries);
  5359. assert(index < m_entries_count);
  5360. }
  5361. const BlockEntry* const pEntry = m_entries[index];
  5362. assert(pEntry);
  5363. assert(!pEntry->EOS());
  5364. const Block* const pBlock = pEntry->GetBlock();
  5365. assert(pBlock);
  5366. if (pBlock->GetTrackNumber() != pTrack->GetNumber()) {
  5367. ++index;
  5368. continue;
  5369. }
  5370. if (pTrack->VetEntry(pEntry)) {
  5371. if (time_ns < 0) // just want first candidate block
  5372. return pEntry;
  5373. const long long ns = pBlock->GetTime(this);
  5374. if (ns > time_ns)
  5375. return pResult;
  5376. pResult = pEntry; // have a candidate
  5377. } else if (time_ns >= 0) {
  5378. const long long ns = pBlock->GetTime(this);
  5379. if (ns > time_ns)
  5380. return pResult;
  5381. }
  5382. ++index;
  5383. }
  5384. }
  5385. const BlockEntry* Cluster::GetEntry(const CuePoint& cp,
  5386. const CuePoint::TrackPosition& tp) const {
  5387. assert(m_pSegment);
  5388. const long long tc = cp.GetTimeCode();
  5389. if (tp.m_block > 0) {
  5390. const long block = static_cast<long>(tp.m_block);
  5391. const long index = block - 1;
  5392. while (index >= m_entries_count) {
  5393. long long pos;
  5394. long len;
  5395. const long status = Parse(pos, len);
  5396. if (status < 0) // TODO: can this happen?
  5397. return NULL;
  5398. if (status > 0) // nothing remains to be parsed
  5399. return NULL;
  5400. }
  5401. const BlockEntry* const pEntry = m_entries[index];
  5402. assert(pEntry);
  5403. assert(!pEntry->EOS());
  5404. const Block* const pBlock = pEntry->GetBlock();
  5405. assert(pBlock);
  5406. if ((pBlock->GetTrackNumber() == tp.m_track) &&
  5407. (pBlock->GetTimeCode(this) == tc)) {
  5408. return pEntry;
  5409. }
  5410. }
  5411. long index = 0;
  5412. for (;;) {
  5413. if (index >= m_entries_count) {
  5414. long long pos;
  5415. long len;
  5416. const long status = Parse(pos, len);
  5417. if (status < 0) // TODO: can this happen?
  5418. return NULL;
  5419. if (status > 0) // nothing remains to be parsed
  5420. return NULL;
  5421. assert(m_entries);
  5422. assert(index < m_entries_count);
  5423. }
  5424. const BlockEntry* const pEntry = m_entries[index];
  5425. assert(pEntry);
  5426. assert(!pEntry->EOS());
  5427. const Block* const pBlock = pEntry->GetBlock();
  5428. assert(pBlock);
  5429. if (pBlock->GetTrackNumber() != tp.m_track) {
  5430. ++index;
  5431. continue;
  5432. }
  5433. const long long tc_ = pBlock->GetTimeCode(this);
  5434. if (tc_ < tc) {
  5435. ++index;
  5436. continue;
  5437. }
  5438. if (tc_ > tc)
  5439. return NULL;
  5440. const Tracks* const pTracks = m_pSegment->GetTracks();
  5441. assert(pTracks);
  5442. const long tn = static_cast<long>(tp.m_track);
  5443. const Track* const pTrack = pTracks->GetTrackByNumber(tn);
  5444. if (pTrack == NULL)
  5445. return NULL;
  5446. const long long type = pTrack->GetType();
  5447. if (type == 2) // audio
  5448. return pEntry;
  5449. if (type != 1) // not video
  5450. return NULL;
  5451. if (!pBlock->IsKey())
  5452. return NULL;
  5453. return pEntry;
  5454. }
  5455. }
  5456. BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) {}
  5457. BlockEntry::~BlockEntry() {}
  5458. const Cluster* BlockEntry::GetCluster() const { return m_pCluster; }
  5459. long BlockEntry::GetIndex() const { return m_index; }
  5460. SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start,
  5461. long long size)
  5462. : BlockEntry(pCluster, idx), m_block(start, size, 0) {}
  5463. long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); }
  5464. BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; }
  5465. const Block* SimpleBlock::GetBlock() const { return &m_block; }
  5466. BlockGroup::BlockGroup(Cluster* pCluster, long idx, long long block_start,
  5467. long long block_size, long long prev, long long next,
  5468. long long duration, long long discard_padding)
  5469. : BlockEntry(pCluster, idx),
  5470. m_block(block_start, block_size, discard_padding),
  5471. m_prev(prev),
  5472. m_next(next),
  5473. m_duration(duration) {}
  5474. long BlockGroup::Parse() {
  5475. const long status = m_block.Parse(m_pCluster);
  5476. if (status)
  5477. return status;
  5478. m_block.SetKey((m_prev > 0) && (m_next <= 0));
  5479. return 0;
  5480. }
  5481. BlockEntry::Kind BlockGroup::GetKind() const { return kBlockGroup; }
  5482. const Block* BlockGroup::GetBlock() const { return &m_block; }
  5483. long long BlockGroup::GetPrevTimeCode() const { return m_prev; }
  5484. long long BlockGroup::GetNextTimeCode() const { return m_next; }
  5485. long long BlockGroup::GetDurationTimeCode() const { return m_duration; }
  5486. Block::Block(long long start, long long size_, long long discard_padding)
  5487. : m_start(start),
  5488. m_size(size_),
  5489. m_track(0),
  5490. m_timecode(-1),
  5491. m_flags(0),
  5492. m_frames(NULL),
  5493. m_frame_count(-1),
  5494. m_discard_padding(discard_padding) {}
  5495. Block::~Block() { delete[] m_frames; }
  5496. long Block::Parse(const Cluster* pCluster) {
  5497. if (pCluster == NULL)
  5498. return -1;
  5499. if (pCluster->m_pSegment == NULL)
  5500. return -1;
  5501. assert(m_start >= 0);
  5502. assert(m_size >= 0);
  5503. assert(m_track <= 0);
  5504. assert(m_frames == NULL);
  5505. assert(m_frame_count <= 0);
  5506. long long pos = m_start;
  5507. const long long stop = m_start + m_size;
  5508. long len;
  5509. IMkvReader* const pReader = pCluster->m_pSegment->m_pReader;
  5510. m_track = ReadUInt(pReader, pos, len);
  5511. if (m_track <= 0)
  5512. return E_FILE_FORMAT_INVALID;
  5513. if ((pos + len) > stop)
  5514. return E_FILE_FORMAT_INVALID;
  5515. pos += len; // consume track number
  5516. if ((stop - pos) < 2)
  5517. return E_FILE_FORMAT_INVALID;
  5518. long status;
  5519. long long value;
  5520. status = UnserializeInt(pReader, pos, 2, value);
  5521. if (status)
  5522. return E_FILE_FORMAT_INVALID;
  5523. if (value < SHRT_MIN)
  5524. return E_FILE_FORMAT_INVALID;
  5525. if (value > SHRT_MAX)
  5526. return E_FILE_FORMAT_INVALID;
  5527. m_timecode = static_cast<short>(value);
  5528. pos += 2;
  5529. if ((stop - pos) <= 0)
  5530. return E_FILE_FORMAT_INVALID;
  5531. status = pReader->Read(pos, 1, &m_flags);
  5532. if (status)
  5533. return E_FILE_FORMAT_INVALID;
  5534. const int lacing = int(m_flags & 0x06) >> 1;
  5535. ++pos; // consume flags byte
  5536. if (lacing == 0) { // no lacing
  5537. if (pos > stop)
  5538. return E_FILE_FORMAT_INVALID;
  5539. m_frame_count = 1;
  5540. m_frames = new (std::nothrow) Frame[m_frame_count];
  5541. if (m_frames == NULL)
  5542. return -1;
  5543. Frame& f = m_frames[0];
  5544. f.pos = pos;
  5545. const long long frame_size = stop - pos;
  5546. if (frame_size > LONG_MAX || frame_size <= 0)
  5547. return E_FILE_FORMAT_INVALID;
  5548. f.len = static_cast<long>(frame_size);
  5549. return 0; // success
  5550. }
  5551. if (pos >= stop)
  5552. return E_FILE_FORMAT_INVALID;
  5553. unsigned char biased_count;
  5554. status = pReader->Read(pos, 1, &biased_count);
  5555. if (status)
  5556. return E_FILE_FORMAT_INVALID;
  5557. ++pos; // consume frame count
  5558. if (pos > stop)
  5559. return E_FILE_FORMAT_INVALID;
  5560. m_frame_count = int(biased_count) + 1;
  5561. m_frames = new (std::nothrow) Frame[m_frame_count];
  5562. if (m_frames == NULL)
  5563. return -1;
  5564. if (!m_frames)
  5565. return E_FILE_FORMAT_INVALID;
  5566. if (lacing == 1) { // Xiph
  5567. Frame* pf = m_frames;
  5568. Frame* const pf_end = pf + m_frame_count;
  5569. long long size = 0;
  5570. int frame_count = m_frame_count;
  5571. while (frame_count > 1) {
  5572. long frame_size = 0;
  5573. for (;;) {
  5574. unsigned char val;
  5575. if (pos >= stop)
  5576. return E_FILE_FORMAT_INVALID;
  5577. status = pReader->Read(pos, 1, &val);
  5578. if (status)
  5579. return E_FILE_FORMAT_INVALID;
  5580. ++pos; // consume xiph size byte
  5581. frame_size += val;
  5582. if (val < 255)
  5583. break;
  5584. }
  5585. Frame& f = *pf++;
  5586. assert(pf < pf_end);
  5587. if (pf >= pf_end)
  5588. return E_FILE_FORMAT_INVALID;
  5589. f.pos = 0; // patch later
  5590. if (frame_size <= 0)
  5591. return E_FILE_FORMAT_INVALID;
  5592. f.len = frame_size;
  5593. size += frame_size; // contribution of this frame
  5594. --frame_count;
  5595. }
  5596. if (pf >= pf_end || pos > stop)
  5597. return E_FILE_FORMAT_INVALID;
  5598. {
  5599. Frame& f = *pf++;
  5600. if (pf != pf_end)
  5601. return E_FILE_FORMAT_INVALID;
  5602. f.pos = 0; // patch later
  5603. const long long total_size = stop - pos;
  5604. if (total_size < size)
  5605. return E_FILE_FORMAT_INVALID;
  5606. const long long frame_size = total_size - size;
  5607. if (frame_size > LONG_MAX || frame_size <= 0)
  5608. return E_FILE_FORMAT_INVALID;
  5609. f.len = static_cast<long>(frame_size);
  5610. }
  5611. pf = m_frames;
  5612. while (pf != pf_end) {
  5613. Frame& f = *pf++;
  5614. assert((pos + f.len) <= stop);
  5615. if ((pos + f.len) > stop)
  5616. return E_FILE_FORMAT_INVALID;
  5617. f.pos = pos;
  5618. pos += f.len;
  5619. }
  5620. assert(pos == stop);
  5621. if (pos != stop)
  5622. return E_FILE_FORMAT_INVALID;
  5623. } else if (lacing == 2) { // fixed-size lacing
  5624. if (pos >= stop)
  5625. return E_FILE_FORMAT_INVALID;
  5626. const long long total_size = stop - pos;
  5627. if ((total_size % m_frame_count) != 0)
  5628. return E_FILE_FORMAT_INVALID;
  5629. const long long frame_size = total_size / m_frame_count;
  5630. if (frame_size > LONG_MAX || frame_size <= 0)
  5631. return E_FILE_FORMAT_INVALID;
  5632. Frame* pf = m_frames;
  5633. Frame* const pf_end = pf + m_frame_count;
  5634. while (pf != pf_end) {
  5635. assert((pos + frame_size) <= stop);
  5636. if ((pos + frame_size) > stop)
  5637. return E_FILE_FORMAT_INVALID;
  5638. Frame& f = *pf++;
  5639. f.pos = pos;
  5640. f.len = static_cast<long>(frame_size);
  5641. pos += frame_size;
  5642. }
  5643. assert(pos == stop);
  5644. if (pos != stop)
  5645. return E_FILE_FORMAT_INVALID;
  5646. } else {
  5647. assert(lacing == 3); // EBML lacing
  5648. if (pos >= stop)
  5649. return E_FILE_FORMAT_INVALID;
  5650. long long size = 0;
  5651. int frame_count = m_frame_count;
  5652. long long frame_size = ReadUInt(pReader, pos, len);
  5653. if (frame_size <= 0)
  5654. return E_FILE_FORMAT_INVALID;
  5655. if (frame_size > LONG_MAX)
  5656. return E_FILE_FORMAT_INVALID;
  5657. if ((pos + len) > stop)
  5658. return E_FILE_FORMAT_INVALID;
  5659. pos += len; // consume length of size of first frame
  5660. if ((pos + frame_size) > stop)
  5661. return E_FILE_FORMAT_INVALID;
  5662. Frame* pf = m_frames;
  5663. Frame* const pf_end = pf + m_frame_count;
  5664. {
  5665. Frame& curr = *pf;
  5666. curr.pos = 0; // patch later
  5667. curr.len = static_cast<long>(frame_size);
  5668. size += curr.len; // contribution of this frame
  5669. }
  5670. --frame_count;
  5671. while (frame_count > 1) {
  5672. if (pos >= stop)
  5673. return E_FILE_FORMAT_INVALID;
  5674. assert(pf < pf_end);
  5675. if (pf >= pf_end)
  5676. return E_FILE_FORMAT_INVALID;
  5677. const Frame& prev = *pf++;
  5678. assert(prev.len == frame_size);
  5679. if (prev.len != frame_size)
  5680. return E_FILE_FORMAT_INVALID;
  5681. assert(pf < pf_end);
  5682. if (pf >= pf_end)
  5683. return E_FILE_FORMAT_INVALID;
  5684. Frame& curr = *pf;
  5685. curr.pos = 0; // patch later
  5686. const long long delta_size_ = ReadUInt(pReader, pos, len);
  5687. if (delta_size_ < 0)
  5688. return E_FILE_FORMAT_INVALID;
  5689. if ((pos + len) > stop)
  5690. return E_FILE_FORMAT_INVALID;
  5691. pos += len; // consume length of (delta) size
  5692. if (pos > stop)
  5693. return E_FILE_FORMAT_INVALID;
  5694. const long exp = 7 * len - 1;
  5695. const long long bias = (1LL << exp) - 1LL;
  5696. const long long delta_size = delta_size_ - bias;
  5697. frame_size += delta_size;
  5698. if (frame_size <= 0)
  5699. return E_FILE_FORMAT_INVALID;
  5700. if (frame_size > LONG_MAX)
  5701. return E_FILE_FORMAT_INVALID;
  5702. curr.len = static_cast<long>(frame_size);
  5703. // Check if size + curr.len could overflow.
  5704. if (size > LLONG_MAX - curr.len) {
  5705. return E_FILE_FORMAT_INVALID;
  5706. }
  5707. size += curr.len; // contribution of this frame
  5708. --frame_count;
  5709. }
  5710. // parse last frame
  5711. if (frame_count > 0) {
  5712. if (pos > stop || pf >= pf_end)
  5713. return E_FILE_FORMAT_INVALID;
  5714. const Frame& prev = *pf++;
  5715. assert(prev.len == frame_size);
  5716. if (prev.len != frame_size)
  5717. return E_FILE_FORMAT_INVALID;
  5718. if (pf >= pf_end)
  5719. return E_FILE_FORMAT_INVALID;
  5720. Frame& curr = *pf++;
  5721. if (pf != pf_end)
  5722. return E_FILE_FORMAT_INVALID;
  5723. curr.pos = 0; // patch later
  5724. const long long total_size = stop - pos;
  5725. if (total_size < size)
  5726. return E_FILE_FORMAT_INVALID;
  5727. frame_size = total_size - size;
  5728. if (frame_size > LONG_MAX || frame_size <= 0)
  5729. return E_FILE_FORMAT_INVALID;
  5730. curr.len = static_cast<long>(frame_size);
  5731. }
  5732. pf = m_frames;
  5733. while (pf != pf_end) {
  5734. Frame& f = *pf++;
  5735. if ((pos + f.len) > stop)
  5736. return E_FILE_FORMAT_INVALID;
  5737. f.pos = pos;
  5738. pos += f.len;
  5739. }
  5740. if (pos != stop)
  5741. return E_FILE_FORMAT_INVALID;
  5742. }
  5743. return 0; // success
  5744. }
  5745. long long Block::GetTimeCode(const Cluster* pCluster) const {
  5746. if (pCluster == 0)
  5747. return m_timecode;
  5748. const long long tc0 = pCluster->GetTimeCode();
  5749. assert(tc0 >= 0);
  5750. // Check if tc0 + m_timecode would overflow.
  5751. if (tc0 < 0 || LLONG_MAX - tc0 < m_timecode) {
  5752. return -1;
  5753. }
  5754. const long long tc = tc0 + m_timecode;
  5755. return tc; // unscaled timecode units
  5756. }
  5757. long long Block::GetTime(const Cluster* pCluster) const {
  5758. assert(pCluster);
  5759. const long long tc = GetTimeCode(pCluster);
  5760. const Segment* const pSegment = pCluster->m_pSegment;
  5761. const SegmentInfo* const pInfo = pSegment->GetInfo();
  5762. assert(pInfo);
  5763. const long long scale = pInfo->GetTimeCodeScale();
  5764. assert(scale >= 1);
  5765. // Check if tc * scale could overflow.
  5766. if (tc != 0 && scale > LLONG_MAX / tc) {
  5767. return -1;
  5768. }
  5769. const long long ns = tc * scale;
  5770. return ns;
  5771. }
  5772. long long Block::GetTrackNumber() const { return m_track; }
  5773. bool Block::IsKey() const {
  5774. return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
  5775. }
  5776. void Block::SetKey(bool bKey) {
  5777. if (bKey)
  5778. m_flags |= static_cast<unsigned char>(1 << 7);
  5779. else
  5780. m_flags &= 0x7F;
  5781. }
  5782. bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); }
  5783. Block::Lacing Block::GetLacing() const {
  5784. const int value = int(m_flags & 0x06) >> 1;
  5785. return static_cast<Lacing>(value);
  5786. }
  5787. int Block::GetFrameCount() const { return m_frame_count; }
  5788. const Block::Frame& Block::GetFrame(int idx) const {
  5789. assert(idx >= 0);
  5790. assert(idx < m_frame_count);
  5791. const Frame& f = m_frames[idx];
  5792. assert(f.pos > 0);
  5793. assert(f.len > 0);
  5794. return f;
  5795. }
  5796. long Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const {
  5797. assert(pReader);
  5798. assert(buf);
  5799. const long status = pReader->Read(pos, len, buf);
  5800. return status;
  5801. }
  5802. long long Block::GetDiscardPadding() const { return m_discard_padding; }
  5803. } // namespace mkvparser