mov.c 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536
  1. /*
  2. * MOV demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
  5. *
  6. * first version by Francois Revol <revol@free.fr>
  7. * seek function by Gael Chardon <gael.dev@4now.net>
  8. *
  9. * This file is part of FFmpeg.
  10. *
  11. * FFmpeg is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * FFmpeg is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with FFmpeg; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. #include <inttypes.h>
  26. #include <limits.h>
  27. #include <stdint.h>
  28. #include "libavutil/attributes.h"
  29. #include "libavutil/channel_layout.h"
  30. #include "libavutil/internal.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libavutil/intfloat.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/time_internal.h"
  35. #include "libavutil/avassert.h"
  36. #include "libavutil/avstring.h"
  37. #include "libavutil/dict.h"
  38. #include "libavutil/display.h"
  39. #include "libavutil/opt.h"
  40. #include "libavutil/aes.h"
  41. #include "libavutil/aes_ctr.h"
  42. #include "libavutil/pixdesc.h"
  43. #include "libavutil/sha.h"
  44. #include "libavutil/spherical.h"
  45. #include "libavutil/stereo3d.h"
  46. #include "libavutil/timecode.h"
  47. #include "libavcodec/ac3tab.h"
  48. #include "libavcodec/flac.h"
  49. #include "libavcodec/mpegaudiodecheader.h"
  50. #include "avformat.h"
  51. #include "internal.h"
  52. #include "avio_internal.h"
  53. #include "riff.h"
  54. #include "isom.h"
  55. #include "libavcodec/get_bits.h"
  56. #include "id3v1.h"
  57. #include "mov_chan.h"
  58. #include "replaygain.h"
  59. #if CONFIG_ZLIB
  60. #include <zlib.h>
  61. #endif
  62. #include "qtpalette.h"
  63. /* those functions parse an atom */
  64. /* links atom IDs to parse functions */
  65. typedef struct MOVParseTableEntry {
  66. uint32_t type;
  67. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  68. } MOVParseTableEntry;
  69. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  70. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  71. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  72. unsigned len, const char *key)
  73. {
  74. char buf[16];
  75. short current, total = 0;
  76. avio_rb16(pb); // unknown
  77. current = avio_rb16(pb);
  78. if (len >= 6)
  79. total = avio_rb16(pb);
  80. if (!total)
  81. snprintf(buf, sizeof(buf), "%d", current);
  82. else
  83. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  84. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  85. av_dict_set(&c->fc->metadata, key, buf, 0);
  86. return 0;
  87. }
  88. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  89. unsigned len, const char *key)
  90. {
  91. /* bypass padding bytes */
  92. avio_r8(pb);
  93. avio_r8(pb);
  94. avio_r8(pb);
  95. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  96. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  97. return 0;
  98. }
  99. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  100. unsigned len, const char *key)
  101. {
  102. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  103. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  104. return 0;
  105. }
  106. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  107. unsigned len, const char *key)
  108. {
  109. short genre;
  110. avio_r8(pb); // unknown
  111. genre = avio_r8(pb);
  112. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  113. return 0;
  114. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  115. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  116. return 0;
  117. }
  118. static const uint32_t mac_to_unicode[128] = {
  119. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  120. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  121. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  122. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  123. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  124. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  125. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  126. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  127. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  128. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  129. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  130. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  131. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  132. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  133. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  134. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  135. };
  136. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  137. char *dst, int dstlen)
  138. {
  139. char *p = dst;
  140. char *end = dst+dstlen-1;
  141. int i;
  142. for (i = 0; i < len; i++) {
  143. uint8_t t, c = avio_r8(pb);
  144. if (c < 0x80 && p < end)
  145. *p++ = c;
  146. else if (p < end)
  147. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  148. }
  149. *p = 0;
  150. return p - dst;
  151. }
  152. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  153. {
  154. AVPacket pkt;
  155. AVStream *st;
  156. MOVStreamContext *sc;
  157. enum AVCodecID id;
  158. int ret;
  159. switch (type) {
  160. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  161. case 0xe: id = AV_CODEC_ID_PNG; break;
  162. case 0x1b: id = AV_CODEC_ID_BMP; break;
  163. default:
  164. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  165. avio_skip(pb, len);
  166. return 0;
  167. }
  168. st = avformat_new_stream(c->fc, NULL);
  169. if (!st)
  170. return AVERROR(ENOMEM);
  171. sc = av_mallocz(sizeof(*sc));
  172. if (!sc)
  173. return AVERROR(ENOMEM);
  174. st->priv_data = sc;
  175. ret = av_get_packet(pb, &pkt, len);
  176. if (ret < 0)
  177. return ret;
  178. if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
  179. if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
  180. id = AV_CODEC_ID_PNG;
  181. } else {
  182. id = AV_CODEC_ID_MJPEG;
  183. }
  184. }
  185. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  186. st->attached_pic = pkt;
  187. st->attached_pic.stream_index = st->index;
  188. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  189. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  190. st->codecpar->codec_id = id;
  191. return 0;
  192. }
  193. // 3GPP TS 26.244
  194. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  195. {
  196. char language[4] = { 0 };
  197. char buf[200], place[100];
  198. uint16_t langcode = 0;
  199. double longitude, latitude, altitude;
  200. const char *key = "location";
  201. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
  202. av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
  203. return AVERROR_INVALIDDATA;
  204. }
  205. avio_skip(pb, 4); // version+flags
  206. langcode = avio_rb16(pb);
  207. ff_mov_lang_to_iso639(langcode, language);
  208. len -= 6;
  209. len -= avio_get_str(pb, len, place, sizeof(place));
  210. if (len < 1) {
  211. av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
  212. return AVERROR_INVALIDDATA;
  213. }
  214. avio_skip(pb, 1); // role
  215. len -= 1;
  216. if (len < 12) {
  217. av_log(c->fc, AV_LOG_ERROR,
  218. "loci too short (%u bytes left, need at least %d)\n", len, 12);
  219. return AVERROR_INVALIDDATA;
  220. }
  221. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  222. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  223. altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  224. // Try to output in the same format as the ?xyz field
  225. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
  226. if (altitude)
  227. av_strlcatf(buf, sizeof(buf), "%+f", altitude);
  228. av_strlcatf(buf, sizeof(buf), "/%s", place);
  229. if (*language && strcmp(language, "und")) {
  230. char key2[16];
  231. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  232. av_dict_set(&c->fc->metadata, key2, buf, 0);
  233. }
  234. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  235. return av_dict_set(&c->fc->metadata, key, buf, 0);
  236. }
  237. static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len)
  238. {
  239. int i, n_hmmt;
  240. if (len < 2)
  241. return 0;
  242. if (c->ignore_chapters)
  243. return 0;
  244. n_hmmt = avio_rb32(pb);
  245. for (i = 0; i < n_hmmt && !pb->eof_reached; i++) {
  246. int moment_time = avio_rb32(pb);
  247. avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL);
  248. }
  249. return 0;
  250. }
  251. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  252. {
  253. char tmp_key[5];
  254. char key2[32], language[4] = {0};
  255. char *str = NULL;
  256. const char *key = NULL;
  257. uint16_t langcode = 0;
  258. uint32_t data_type = 0, str_size, str_size_alloc;
  259. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  260. int raw = 0;
  261. int num = 0;
  262. switch (atom.type) {
  263. case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
  264. case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
  265. case MKTAG( 'X','M','P','_'):
  266. if (c->export_xmp) { key = "xmp"; raw = 1; } break;
  267. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  268. case MKTAG( 'a','k','I','D'): key = "account_type";
  269. parse = mov_metadata_int8_no_padding; break;
  270. case MKTAG( 'a','p','I','D'): key = "account_id"; break;
  271. case MKTAG( 'c','a','t','g'): key = "category"; break;
  272. case MKTAG( 'c','p','i','l'): key = "compilation";
  273. parse = mov_metadata_int8_no_padding; break;
  274. case MKTAG( 'c','p','r','t'): key = "copyright"; break;
  275. case MKTAG( 'd','e','s','c'): key = "description"; break;
  276. case MKTAG( 'd','i','s','k'): key = "disc";
  277. parse = mov_metadata_track_or_disc_number; break;
  278. case MKTAG( 'e','g','i','d'): key = "episode_uid";
  279. parse = mov_metadata_int8_no_padding; break;
  280. case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break;
  281. case MKTAG( 'g','n','r','e'): key = "genre";
  282. parse = mov_metadata_gnre; break;
  283. case MKTAG( 'h','d','v','d'): key = "hd_video";
  284. parse = mov_metadata_int8_no_padding; break;
  285. case MKTAG( 'H','M','M','T'):
  286. return mov_metadata_hmmt(c, pb, atom.size);
  287. case MKTAG( 'k','e','y','w'): key = "keywords"; break;
  288. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  289. case MKTAG( 'l','o','c','i'):
  290. return mov_metadata_loci(c, pb, atom.size);
  291. case MKTAG( 'p','c','s','t'): key = "podcast";
  292. parse = mov_metadata_int8_no_padding; break;
  293. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  294. parse = mov_metadata_int8_no_padding; break;
  295. case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
  296. case MKTAG( 'r','t','n','g'): key = "rating";
  297. parse = mov_metadata_int8_no_padding; break;
  298. case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
  299. case MKTAG( 's','o','a','l'): key = "sort_album"; break;
  300. case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
  301. case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
  302. case MKTAG( 's','o','n','m'): key = "sort_name"; break;
  303. case MKTAG( 's','o','s','n'): key = "sort_show"; break;
  304. case MKTAG( 's','t','i','k'): key = "media_type";
  305. parse = mov_metadata_int8_no_padding; break;
  306. case MKTAG( 't','r','k','n'): key = "track";
  307. parse = mov_metadata_track_or_disc_number; break;
  308. case MKTAG( 't','v','e','n'): key = "episode_id"; break;
  309. case MKTAG( 't','v','e','s'): key = "episode_sort";
  310. parse = mov_metadata_int8_bypass_padding; break;
  311. case MKTAG( 't','v','n','n'): key = "network"; break;
  312. case MKTAG( 't','v','s','h'): key = "show"; break;
  313. case MKTAG( 't','v','s','n'): key = "season_number";
  314. parse = mov_metadata_int8_bypass_padding; break;
  315. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  316. case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
  317. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  318. case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
  319. case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
  320. case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
  321. case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
  322. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  323. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  324. case MKTAG(0xa9,'d','i','r'): key = "director"; break;
  325. case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
  326. case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
  327. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  328. case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
  329. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  330. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  331. case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
  332. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  333. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  334. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  335. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  336. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  337. case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
  338. case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
  339. case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
  340. case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
  341. case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
  342. case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
  343. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  344. case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
  345. case MKTAG(0xa9,'t','r','k'): key = "track"; break;
  346. case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
  347. case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
  348. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  349. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  350. }
  351. retry:
  352. if (c->itunes_metadata && atom.size > 8) {
  353. int data_size = avio_rb32(pb);
  354. int tag = avio_rl32(pb);
  355. if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
  356. data_type = avio_rb32(pb); // type
  357. avio_rb32(pb); // unknown
  358. str_size = data_size - 16;
  359. atom.size -= 16;
  360. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  361. int ret = mov_read_covr(c, pb, data_type, str_size);
  362. if (ret < 0) {
  363. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  364. }
  365. return ret;
  366. } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
  367. uint32_t index = AV_RB32(&atom.type);
  368. if (index < c->meta_keys_count && index > 0) {
  369. key = c->meta_keys[index];
  370. } else {
  371. av_log(c->fc, AV_LOG_WARNING,
  372. "The index of 'data' is out of range: %d < 1 or >= %d.\n",
  373. index, c->meta_keys_count);
  374. }
  375. }
  376. } else return 0;
  377. } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
  378. str_size = avio_rb16(pb); // string length
  379. if (str_size > atom.size) {
  380. raw = 1;
  381. avio_seek(pb, -2, SEEK_CUR);
  382. av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
  383. goto retry;
  384. }
  385. langcode = avio_rb16(pb);
  386. ff_mov_lang_to_iso639(langcode, language);
  387. atom.size -= 4;
  388. } else
  389. str_size = atom.size;
  390. if (c->export_all && !key) {
  391. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  392. key = tmp_key;
  393. }
  394. if (!key)
  395. return 0;
  396. if (atom.size < 0 || str_size >= INT_MAX/2)
  397. return AVERROR_INVALIDDATA;
  398. // Allocates enough space if data_type is a int32 or float32 number, otherwise
  399. // worst-case requirement for output string in case of utf8 coded input
  400. num = (data_type >= 21 && data_type <= 23);
  401. str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
  402. str = av_mallocz(str_size_alloc);
  403. if (!str)
  404. return AVERROR(ENOMEM);
  405. if (parse)
  406. parse(c, pb, str_size, key);
  407. else {
  408. if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
  409. mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  410. } else if (data_type == 21) { // BE signed integer, variable size
  411. int val = 0;
  412. if (str_size == 1)
  413. val = (int8_t)avio_r8(pb);
  414. else if (str_size == 2)
  415. val = (int16_t)avio_rb16(pb);
  416. else if (str_size == 3)
  417. val = ((int32_t)(avio_rb24(pb)<<8))>>8;
  418. else if (str_size == 4)
  419. val = (int32_t)avio_rb32(pb);
  420. if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) {
  421. av_log(c->fc, AV_LOG_ERROR,
  422. "Failed to store the number (%d) in string.\n", val);
  423. av_free(str);
  424. return AVERROR_INVALIDDATA;
  425. }
  426. } else if (data_type == 22) { // BE unsigned integer, variable size
  427. unsigned int val = 0;
  428. if (str_size == 1)
  429. val = avio_r8(pb);
  430. else if (str_size == 2)
  431. val = avio_rb16(pb);
  432. else if (str_size == 3)
  433. val = avio_rb24(pb);
  434. else if (str_size == 4)
  435. val = avio_rb32(pb);
  436. if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) {
  437. av_log(c->fc, AV_LOG_ERROR,
  438. "Failed to store the number (%u) in string.\n", val);
  439. av_free(str);
  440. return AVERROR_INVALIDDATA;
  441. }
  442. } else if (data_type == 23 && str_size >= 4) { // BE float32
  443. float val = av_int2float(avio_rb32(pb));
  444. if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
  445. av_log(c->fc, AV_LOG_ERROR,
  446. "Failed to store the float32 number (%f) in string.\n", val);
  447. av_free(str);
  448. return AVERROR_INVALIDDATA;
  449. }
  450. } else {
  451. int ret = ffio_read_size(pb, str, str_size);
  452. if (ret < 0) {
  453. av_free(str);
  454. return ret;
  455. }
  456. str[str_size] = 0;
  457. }
  458. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  459. av_dict_set(&c->fc->metadata, key, str, 0);
  460. if (*language && strcmp(language, "und")) {
  461. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  462. av_dict_set(&c->fc->metadata, key2, str, 0);
  463. }
  464. if (!strcmp(key, "encoder")) {
  465. int major, minor, micro;
  466. if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
  467. c->handbrake_version = 1000000*major + 1000*minor + micro;
  468. }
  469. }
  470. }
  471. av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
  472. av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  473. key, str, (char*)&atom.type, str_size_alloc, atom.size);
  474. av_freep(&str);
  475. return 0;
  476. }
  477. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  478. {
  479. int64_t start;
  480. int i, nb_chapters, str_len, version;
  481. char str[256+1];
  482. int ret;
  483. if (c->ignore_chapters)
  484. return 0;
  485. if ((atom.size -= 5) < 0)
  486. return 0;
  487. version = avio_r8(pb);
  488. avio_rb24(pb);
  489. if (version)
  490. avio_rb32(pb); // ???
  491. nb_chapters = avio_r8(pb);
  492. for (i = 0; i < nb_chapters; i++) {
  493. if (atom.size < 9)
  494. return 0;
  495. start = avio_rb64(pb);
  496. str_len = avio_r8(pb);
  497. if ((atom.size -= 9+str_len) < 0)
  498. return 0;
  499. ret = ffio_read_size(pb, str, str_len);
  500. if (ret < 0)
  501. return ret;
  502. str[str_len] = 0;
  503. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  504. }
  505. return 0;
  506. }
  507. #define MIN_DATA_ENTRY_BOX_SIZE 12
  508. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  509. {
  510. AVStream *st;
  511. MOVStreamContext *sc;
  512. int entries, i, j;
  513. if (c->fc->nb_streams < 1)
  514. return 0;
  515. st = c->fc->streams[c->fc->nb_streams-1];
  516. sc = st->priv_data;
  517. avio_rb32(pb); // version + flags
  518. entries = avio_rb32(pb);
  519. if (!entries ||
  520. entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  521. entries >= UINT_MAX / sizeof(*sc->drefs))
  522. return AVERROR_INVALIDDATA;
  523. sc->drefs_count = 0;
  524. av_free(sc->drefs);
  525. sc->drefs_count = 0;
  526. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  527. if (!sc->drefs)
  528. return AVERROR(ENOMEM);
  529. sc->drefs_count = entries;
  530. for (i = 0; i < entries; i++) {
  531. MOVDref *dref = &sc->drefs[i];
  532. uint32_t size = avio_rb32(pb);
  533. int64_t next = avio_tell(pb) + size - 4;
  534. if (size < 12)
  535. return AVERROR_INVALIDDATA;
  536. dref->type = avio_rl32(pb);
  537. avio_rb32(pb); // version + flags
  538. av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
  539. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  540. /* macintosh alias record */
  541. uint16_t volume_len, len;
  542. int16_t type;
  543. int ret;
  544. avio_skip(pb, 10);
  545. volume_len = avio_r8(pb);
  546. volume_len = FFMIN(volume_len, 27);
  547. ret = ffio_read_size(pb, dref->volume, 27);
  548. if (ret < 0)
  549. return ret;
  550. dref->volume[volume_len] = 0;
  551. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  552. avio_skip(pb, 12);
  553. len = avio_r8(pb);
  554. len = FFMIN(len, 63);
  555. ret = ffio_read_size(pb, dref->filename, 63);
  556. if (ret < 0)
  557. return ret;
  558. dref->filename[len] = 0;
  559. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  560. avio_skip(pb, 16);
  561. /* read next level up_from_alias/down_to_target */
  562. dref->nlvl_from = avio_rb16(pb);
  563. dref->nlvl_to = avio_rb16(pb);
  564. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  565. dref->nlvl_from, dref->nlvl_to);
  566. avio_skip(pb, 16);
  567. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  568. if(avio_feof(pb))
  569. return AVERROR_EOF;
  570. type = avio_rb16(pb);
  571. len = avio_rb16(pb);
  572. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  573. if (len&1)
  574. len += 1;
  575. if (type == 2) { // absolute path
  576. av_free(dref->path);
  577. dref->path = av_mallocz(len+1);
  578. if (!dref->path)
  579. return AVERROR(ENOMEM);
  580. ret = ffio_read_size(pb, dref->path, len);
  581. if (ret < 0) {
  582. av_freep(&dref->path);
  583. return ret;
  584. }
  585. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  586. len -= volume_len;
  587. memmove(dref->path, dref->path+volume_len, len);
  588. dref->path[len] = 0;
  589. }
  590. // trim string of any ending zeros
  591. for (j = len - 1; j >= 0; j--) {
  592. if (dref->path[j] == 0)
  593. len--;
  594. else
  595. break;
  596. }
  597. for (j = 0; j < len; j++)
  598. if (dref->path[j] == ':' || dref->path[j] == 0)
  599. dref->path[j] = '/';
  600. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  601. } else if (type == 0) { // directory name
  602. av_free(dref->dir);
  603. dref->dir = av_malloc(len+1);
  604. if (!dref->dir)
  605. return AVERROR(ENOMEM);
  606. ret = ffio_read_size(pb, dref->dir, len);
  607. if (ret < 0) {
  608. av_freep(&dref->dir);
  609. return ret;
  610. }
  611. dref->dir[len] = 0;
  612. for (j = 0; j < len; j++)
  613. if (dref->dir[j] == ':')
  614. dref->dir[j] = '/';
  615. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  616. } else
  617. avio_skip(pb, len);
  618. }
  619. } else {
  620. av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08x size %d\n",
  621. dref->type, size);
  622. entries--;
  623. i--;
  624. }
  625. avio_seek(pb, next, SEEK_SET);
  626. }
  627. return 0;
  628. }
  629. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  630. {
  631. AVStream *st;
  632. uint32_t type;
  633. uint32_t av_unused ctype;
  634. int64_t title_size;
  635. char *title_str;
  636. int ret;
  637. avio_r8(pb); /* version */
  638. avio_rb24(pb); /* flags */
  639. /* component type */
  640. ctype = avio_rl32(pb);
  641. type = avio_rl32(pb); /* component subtype */
  642. av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  643. av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
  644. if (c->trak_index < 0) { // meta not inside a trak
  645. if (type == MKTAG('m','d','t','a')) {
  646. c->found_hdlr_mdta = 1;
  647. }
  648. return 0;
  649. }
  650. st = c->fc->streams[c->fc->nb_streams-1];
  651. if (type == MKTAG('v','i','d','e'))
  652. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  653. else if (type == MKTAG('s','o','u','n'))
  654. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  655. else if (type == MKTAG('m','1','a',' '))
  656. st->codecpar->codec_id = AV_CODEC_ID_MP2;
  657. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  658. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  659. avio_rb32(pb); /* component manufacture */
  660. avio_rb32(pb); /* component flags */
  661. avio_rb32(pb); /* component flags mask */
  662. title_size = atom.size - 24;
  663. if (title_size > 0) {
  664. if (title_size > FFMIN(INT_MAX, SIZE_MAX-1))
  665. return AVERROR_INVALIDDATA;
  666. title_str = av_malloc(title_size + 1); /* Add null terminator */
  667. if (!title_str)
  668. return AVERROR(ENOMEM);
  669. ret = ffio_read_size(pb, title_str, title_size);
  670. if (ret < 0) {
  671. av_freep(&title_str);
  672. return ret;
  673. }
  674. title_str[title_size] = 0;
  675. if (title_str[0]) {
  676. int off = (!c->isom && title_str[0] == title_size - 1);
  677. av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
  678. }
  679. av_freep(&title_str);
  680. }
  681. return 0;
  682. }
  683. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  684. {
  685. AVStream *st;
  686. int tag;
  687. if (fc->nb_streams < 1)
  688. return 0;
  689. st = fc->streams[fc->nb_streams-1];
  690. avio_rb32(pb); /* version + flags */
  691. ff_mp4_read_descr(fc, pb, &tag);
  692. if (tag == MP4ESDescrTag) {
  693. ff_mp4_parse_es_descr(pb, NULL);
  694. } else
  695. avio_rb16(pb); /* ID */
  696. ff_mp4_read_descr(fc, pb, &tag);
  697. if (tag == MP4DecConfigDescrTag)
  698. ff_mp4_read_dec_config_descr(fc, st, pb);
  699. return 0;
  700. }
  701. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  702. {
  703. return ff_mov_read_esds(c->fc, pb);
  704. }
  705. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  706. {
  707. AVStream *st;
  708. enum AVAudioServiceType *ast;
  709. int ac3info, acmod, lfeon, bsmod;
  710. if (c->fc->nb_streams < 1)
  711. return 0;
  712. st = c->fc->streams[c->fc->nb_streams-1];
  713. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  714. sizeof(*ast));
  715. if (!ast)
  716. return AVERROR(ENOMEM);
  717. ac3info = avio_rb24(pb);
  718. bsmod = (ac3info >> 14) & 0x7;
  719. acmod = (ac3info >> 11) & 0x7;
  720. lfeon = (ac3info >> 10) & 0x1;
  721. st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  722. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  723. if (lfeon)
  724. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  725. *ast = bsmod;
  726. if (st->codecpar->channels > 1 && bsmod == 0x7)
  727. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  728. #if FF_API_LAVF_AVCTX
  729. FF_DISABLE_DEPRECATION_WARNINGS
  730. st->codec->audio_service_type = *ast;
  731. FF_ENABLE_DEPRECATION_WARNINGS
  732. #endif
  733. return 0;
  734. }
  735. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  736. {
  737. AVStream *st;
  738. enum AVAudioServiceType *ast;
  739. int eac3info, acmod, lfeon, bsmod;
  740. if (c->fc->nb_streams < 1)
  741. return 0;
  742. st = c->fc->streams[c->fc->nb_streams-1];
  743. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  744. sizeof(*ast));
  745. if (!ast)
  746. return AVERROR(ENOMEM);
  747. /* No need to parse fields for additional independent substreams and its
  748. * associated dependent substreams since libavcodec's E-AC-3 decoder
  749. * does not support them yet. */
  750. avio_rb16(pb); /* data_rate and num_ind_sub */
  751. eac3info = avio_rb24(pb);
  752. bsmod = (eac3info >> 12) & 0x1f;
  753. acmod = (eac3info >> 9) & 0x7;
  754. lfeon = (eac3info >> 8) & 0x1;
  755. st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  756. if (lfeon)
  757. st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY;
  758. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  759. *ast = bsmod;
  760. if (st->codecpar->channels > 1 && bsmod == 0x7)
  761. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  762. #if FF_API_LAVF_AVCTX
  763. FF_DISABLE_DEPRECATION_WARNINGS
  764. st->codec->audio_service_type = *ast;
  765. FF_ENABLE_DEPRECATION_WARNINGS
  766. #endif
  767. return 0;
  768. }
  769. static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  770. {
  771. const uint32_t ddts_size = 20;
  772. AVStream *st = NULL;
  773. uint8_t *buf = NULL;
  774. uint32_t frame_duration_code = 0;
  775. uint32_t channel_layout_code = 0;
  776. GetBitContext gb;
  777. buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
  778. if (!buf) {
  779. return AVERROR(ENOMEM);
  780. }
  781. if (avio_read(pb, buf, ddts_size) < ddts_size) {
  782. av_free(buf);
  783. return AVERROR_INVALIDDATA;
  784. }
  785. init_get_bits(&gb, buf, 8*ddts_size);
  786. if (c->fc->nb_streams < 1) {
  787. return 0;
  788. }
  789. st = c->fc->streams[c->fc->nb_streams-1];
  790. st->codecpar->sample_rate = get_bits_long(&gb, 32);
  791. if (st->codecpar->sample_rate <= 0) {
  792. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  793. return AVERROR_INVALIDDATA;
  794. }
  795. skip_bits_long(&gb, 32); /* max bitrate */
  796. st->codecpar->bit_rate = get_bits_long(&gb, 32);
  797. st->codecpar->bits_per_coded_sample = get_bits(&gb, 8);
  798. frame_duration_code = get_bits(&gb, 2);
  799. skip_bits(&gb, 30); /* various fields */
  800. channel_layout_code = get_bits(&gb, 16);
  801. st->codecpar->frame_size =
  802. (frame_duration_code == 0) ? 512 :
  803. (frame_duration_code == 1) ? 1024 :
  804. (frame_duration_code == 2) ? 2048 :
  805. (frame_duration_code == 3) ? 4096 : 0;
  806. if (channel_layout_code > 0xff) {
  807. av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
  808. }
  809. st->codecpar->channel_layout =
  810. ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
  811. ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
  812. ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
  813. ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
  814. ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
  815. ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
  816. st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout);
  817. return 0;
  818. }
  819. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  820. {
  821. AVStream *st;
  822. if (c->fc->nb_streams < 1)
  823. return 0;
  824. st = c->fc->streams[c->fc->nb_streams-1];
  825. if (atom.size < 16)
  826. return 0;
  827. /* skip version and flags */
  828. avio_skip(pb, 4);
  829. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  830. return 0;
  831. }
  832. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  833. {
  834. AVStream *st;
  835. int ret;
  836. if (c->fc->nb_streams < 1)
  837. return 0;
  838. st = c->fc->streams[c->fc->nb_streams-1];
  839. if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0)
  840. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  841. return ret;
  842. }
  843. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  844. {
  845. const int num = avio_rb32(pb);
  846. const int den = avio_rb32(pb);
  847. AVStream *st;
  848. if (c->fc->nb_streams < 1)
  849. return 0;
  850. st = c->fc->streams[c->fc->nb_streams-1];
  851. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  852. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  853. av_log(c->fc, AV_LOG_WARNING,
  854. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  855. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  856. num, den);
  857. } else if (den != 0) {
  858. av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
  859. num, den, 32767);
  860. }
  861. return 0;
  862. }
  863. /* this atom contains actual media data */
  864. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  865. {
  866. if (atom.size == 0) /* wrong one (MP4) */
  867. return 0;
  868. c->found_mdat=1;
  869. return 0; /* now go for moov */
  870. }
  871. #define DRM_BLOB_SIZE 56
  872. static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  873. {
  874. uint8_t intermediate_key[20];
  875. uint8_t intermediate_iv[20];
  876. uint8_t input[64];
  877. uint8_t output[64];
  878. uint8_t file_checksum[20];
  879. uint8_t calculated_checksum[20];
  880. struct AVSHA *sha;
  881. int i;
  882. int ret = 0;
  883. uint8_t *activation_bytes = c->activation_bytes;
  884. uint8_t *fixed_key = c->audible_fixed_key;
  885. c->aax_mode = 1;
  886. sha = av_sha_alloc();
  887. if (!sha)
  888. return AVERROR(ENOMEM);
  889. c->aes_decrypt = av_aes_alloc();
  890. if (!c->aes_decrypt) {
  891. ret = AVERROR(ENOMEM);
  892. goto fail;
  893. }
  894. /* drm blob processing */
  895. avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
  896. avio_read(pb, input, DRM_BLOB_SIZE);
  897. avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
  898. avio_read(pb, file_checksum, 20);
  899. av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
  900. for (i = 0; i < 20; i++)
  901. av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]);
  902. av_log(c->fc, AV_LOG_INFO, "\n");
  903. /* verify activation data */
  904. if (!activation_bytes) {
  905. av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
  906. ret = 0; /* allow ffprobe to continue working on .aax files */
  907. goto fail;
  908. }
  909. if (c->activation_bytes_size != 4) {
  910. av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
  911. ret = AVERROR(EINVAL);
  912. goto fail;
  913. }
  914. /* verify fixed key */
  915. if (c->audible_fixed_key_size != 16) {
  916. av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
  917. ret = AVERROR(EINVAL);
  918. goto fail;
  919. }
  920. /* AAX (and AAX+) key derivation */
  921. av_sha_init(sha, 160);
  922. av_sha_update(sha, fixed_key, 16);
  923. av_sha_update(sha, activation_bytes, 4);
  924. av_sha_final(sha, intermediate_key);
  925. av_sha_init(sha, 160);
  926. av_sha_update(sha, fixed_key, 16);
  927. av_sha_update(sha, intermediate_key, 20);
  928. av_sha_update(sha, activation_bytes, 4);
  929. av_sha_final(sha, intermediate_iv);
  930. av_sha_init(sha, 160);
  931. av_sha_update(sha, intermediate_key, 16);
  932. av_sha_update(sha, intermediate_iv, 16);
  933. av_sha_final(sha, calculated_checksum);
  934. if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
  935. av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
  936. ret = AVERROR_INVALIDDATA;
  937. goto fail;
  938. }
  939. av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
  940. av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
  941. for (i = 0; i < 4; i++) {
  942. // file data (in output) is stored in big-endian mode
  943. if (activation_bytes[i] != output[3 - i]) { // critical error
  944. av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
  945. ret = AVERROR_INVALIDDATA;
  946. goto fail;
  947. }
  948. }
  949. memcpy(c->file_key, output + 8, 16);
  950. memcpy(input, output + 26, 16);
  951. av_sha_init(sha, 160);
  952. av_sha_update(sha, input, 16);
  953. av_sha_update(sha, c->file_key, 16);
  954. av_sha_update(sha, fixed_key, 16);
  955. av_sha_final(sha, c->file_iv);
  956. fail:
  957. av_free(sha);
  958. return ret;
  959. }
  960. // Audible AAX (and AAX+) bytestream decryption
  961. static int aax_filter(uint8_t *input, int size, MOVContext *c)
  962. {
  963. int blocks = 0;
  964. unsigned char iv[16];
  965. memcpy(iv, c->file_iv, 16); // iv is overwritten
  966. blocks = size >> 4; // trailing bytes are not encrypted!
  967. av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
  968. av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
  969. return 0;
  970. }
  971. /* read major brand, minor version and compatible brands and store them as metadata */
  972. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  973. {
  974. uint32_t minor_ver;
  975. int comp_brand_size;
  976. char* comp_brands_str;
  977. uint8_t type[5] = {0};
  978. int ret = ffio_read_size(pb, type, 4);
  979. if (ret < 0)
  980. return ret;
  981. if (strcmp(type, "qt "))
  982. c->isom = 1;
  983. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  984. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  985. minor_ver = avio_rb32(pb); /* minor version */
  986. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  987. comp_brand_size = atom.size - 8;
  988. if (comp_brand_size < 0)
  989. return AVERROR_INVALIDDATA;
  990. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  991. if (!comp_brands_str)
  992. return AVERROR(ENOMEM);
  993. ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
  994. if (ret < 0) {
  995. av_freep(&comp_brands_str);
  996. return ret;
  997. }
  998. comp_brands_str[comp_brand_size] = 0;
  999. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  1000. av_freep(&comp_brands_str);
  1001. return 0;
  1002. }
  1003. /* this atom should contain all header atoms */
  1004. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1005. {
  1006. int ret;
  1007. if (c->found_moov) {
  1008. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  1009. avio_skip(pb, atom.size);
  1010. return 0;
  1011. }
  1012. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1013. return ret;
  1014. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  1015. /* so we don't parse the whole file if over a network */
  1016. c->found_moov=1;
  1017. return 0; /* now go for mdat */
  1018. }
  1019. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1020. {
  1021. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  1022. c->has_looked_for_mfra = 1;
  1023. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  1024. int ret;
  1025. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  1026. "for a mfra\n");
  1027. if ((ret = mov_read_mfra(c, pb)) < 0) {
  1028. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  1029. "read the mfra (may be a live ismv)\n");
  1030. }
  1031. } else {
  1032. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  1033. "seekable, can not look for mfra\n");
  1034. }
  1035. }
  1036. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  1037. av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  1038. return mov_read_default(c, pb, atom);
  1039. }
  1040. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  1041. {
  1042. if (time) {
  1043. if(time >= 2082844800)
  1044. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  1045. avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000);
  1046. }
  1047. }
  1048. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1049. {
  1050. AVStream *st;
  1051. MOVStreamContext *sc;
  1052. int version;
  1053. char language[4] = {0};
  1054. unsigned lang;
  1055. int64_t creation_time;
  1056. if (c->fc->nb_streams < 1)
  1057. return 0;
  1058. st = c->fc->streams[c->fc->nb_streams-1];
  1059. sc = st->priv_data;
  1060. if (sc->time_scale) {
  1061. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  1062. return AVERROR_INVALIDDATA;
  1063. }
  1064. version = avio_r8(pb);
  1065. if (version > 1) {
  1066. avpriv_request_sample(c->fc, "Version %d", version);
  1067. return AVERROR_PATCHWELCOME;
  1068. }
  1069. avio_rb24(pb); /* flags */
  1070. if (version == 1) {
  1071. creation_time = avio_rb64(pb);
  1072. avio_rb64(pb);
  1073. } else {
  1074. creation_time = avio_rb32(pb);
  1075. avio_rb32(pb); /* modification time */
  1076. }
  1077. mov_metadata_creation_time(&st->metadata, creation_time);
  1078. sc->time_scale = avio_rb32(pb);
  1079. if (sc->time_scale <= 0) {
  1080. av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d\n", sc->time_scale);
  1081. return AVERROR_INVALIDDATA;
  1082. }
  1083. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1084. lang = avio_rb16(pb); /* language */
  1085. if (ff_mov_lang_to_iso639(lang, language))
  1086. av_dict_set(&st->metadata, "language", language, 0);
  1087. avio_rb16(pb); /* quality */
  1088. return 0;
  1089. }
  1090. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1091. {
  1092. int i;
  1093. int64_t creation_time;
  1094. int version = avio_r8(pb); /* version */
  1095. avio_rb24(pb); /* flags */
  1096. if (version == 1) {
  1097. creation_time = avio_rb64(pb);
  1098. avio_rb64(pb);
  1099. } else {
  1100. creation_time = avio_rb32(pb);
  1101. avio_rb32(pb); /* modification time */
  1102. }
  1103. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  1104. c->time_scale = avio_rb32(pb); /* time scale */
  1105. if (c->time_scale <= 0) {
  1106. av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d\n", c->time_scale);
  1107. return AVERROR_INVALIDDATA;
  1108. }
  1109. av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
  1110. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1111. // set the AVCodecContext duration because the duration of individual tracks
  1112. // may be inaccurate
  1113. if (c->time_scale > 0 && !c->trex_data)
  1114. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  1115. avio_rb32(pb); /* preferred scale */
  1116. avio_rb16(pb); /* preferred volume */
  1117. avio_skip(pb, 10); /* reserved */
  1118. /* movie display matrix, store it in main context and use it later on */
  1119. for (i = 0; i < 3; i++) {
  1120. c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1121. c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1122. c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  1123. }
  1124. avio_rb32(pb); /* preview time */
  1125. avio_rb32(pb); /* preview duration */
  1126. avio_rb32(pb); /* poster time */
  1127. avio_rb32(pb); /* selection time */
  1128. avio_rb32(pb); /* selection duration */
  1129. avio_rb32(pb); /* current time */
  1130. avio_rb32(pb); /* next track ID */
  1131. return 0;
  1132. }
  1133. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1134. {
  1135. AVStream *st;
  1136. int little_endian;
  1137. if (c->fc->nb_streams < 1)
  1138. return 0;
  1139. st = c->fc->streams[c->fc->nb_streams-1];
  1140. little_endian = avio_rb16(pb) & 0xFF;
  1141. av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
  1142. if (little_endian == 1) {
  1143. switch (st->codecpar->codec_id) {
  1144. case AV_CODEC_ID_PCM_S24BE:
  1145. st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
  1146. break;
  1147. case AV_CODEC_ID_PCM_S32BE:
  1148. st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
  1149. break;
  1150. case AV_CODEC_ID_PCM_F32BE:
  1151. st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
  1152. break;
  1153. case AV_CODEC_ID_PCM_F64BE:
  1154. st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE;
  1155. break;
  1156. default:
  1157. break;
  1158. }
  1159. }
  1160. return 0;
  1161. }
  1162. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1163. {
  1164. AVStream *st;
  1165. char color_parameter_type[5] = { 0 };
  1166. uint16_t color_primaries, color_trc, color_matrix;
  1167. int ret;
  1168. if (c->fc->nb_streams < 1)
  1169. return 0;
  1170. st = c->fc->streams[c->fc->nb_streams - 1];
  1171. ret = ffio_read_size(pb, color_parameter_type, 4);
  1172. if (ret < 0)
  1173. return ret;
  1174. if (strncmp(color_parameter_type, "nclx", 4) &&
  1175. strncmp(color_parameter_type, "nclc", 4)) {
  1176. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  1177. color_parameter_type);
  1178. return 0;
  1179. }
  1180. color_primaries = avio_rb16(pb);
  1181. color_trc = avio_rb16(pb);
  1182. color_matrix = avio_rb16(pb);
  1183. av_log(c->fc, AV_LOG_TRACE,
  1184. "%s: pri %d trc %d matrix %d",
  1185. color_parameter_type, color_primaries, color_trc, color_matrix);
  1186. if (!strncmp(color_parameter_type, "nclx", 4)) {
  1187. uint8_t color_range = avio_r8(pb) >> 7;
  1188. av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
  1189. if (color_range)
  1190. st->codecpar->color_range = AVCOL_RANGE_JPEG;
  1191. else
  1192. st->codecpar->color_range = AVCOL_RANGE_MPEG;
  1193. }
  1194. if (!av_color_primaries_name(color_primaries))
  1195. color_primaries = AVCOL_PRI_UNSPECIFIED;
  1196. if (!av_color_transfer_name(color_trc))
  1197. color_trc = AVCOL_TRC_UNSPECIFIED;
  1198. if (!av_color_space_name(color_matrix))
  1199. color_matrix = AVCOL_SPC_UNSPECIFIED;
  1200. st->codecpar->color_primaries = color_primaries;
  1201. st->codecpar->color_trc = color_trc;
  1202. st->codecpar->color_space = color_matrix;
  1203. av_log(c->fc, AV_LOG_TRACE, "\n");
  1204. return 0;
  1205. }
  1206. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1207. {
  1208. AVStream *st;
  1209. unsigned mov_field_order;
  1210. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1211. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1212. return 0;
  1213. st = c->fc->streams[c->fc->nb_streams-1];
  1214. if (atom.size < 2)
  1215. return AVERROR_INVALIDDATA;
  1216. mov_field_order = avio_rb16(pb);
  1217. if ((mov_field_order & 0xFF00) == 0x0100)
  1218. decoded_field_order = AV_FIELD_PROGRESSIVE;
  1219. else if ((mov_field_order & 0xFF00) == 0x0200) {
  1220. switch (mov_field_order & 0xFF) {
  1221. case 0x01: decoded_field_order = AV_FIELD_TT;
  1222. break;
  1223. case 0x06: decoded_field_order = AV_FIELD_BB;
  1224. break;
  1225. case 0x09: decoded_field_order = AV_FIELD_TB;
  1226. break;
  1227. case 0x0E: decoded_field_order = AV_FIELD_BT;
  1228. break;
  1229. }
  1230. }
  1231. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1232. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1233. }
  1234. st->codecpar->field_order = decoded_field_order;
  1235. return 0;
  1236. }
  1237. static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
  1238. {
  1239. int err = 0;
  1240. uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1241. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1242. return AVERROR_INVALIDDATA;
  1243. if ((err = av_reallocp(&par->extradata, size)) < 0) {
  1244. par->extradata_size = 0;
  1245. return err;
  1246. }
  1247. par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1248. return 0;
  1249. }
  1250. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1251. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1252. AVCodecParameters *par, uint8_t *buf)
  1253. {
  1254. int64_t result = atom.size;
  1255. int err;
  1256. AV_WB32(buf , atom.size + 8);
  1257. AV_WL32(buf + 4, atom.type);
  1258. err = ffio_read_size(pb, buf + 8, atom.size);
  1259. if (err < 0) {
  1260. par->extradata_size -= atom.size;
  1261. return err;
  1262. } else if (err < atom.size) {
  1263. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1264. par->extradata_size -= atom.size - err;
  1265. result = err;
  1266. }
  1267. memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1268. return result;
  1269. }
  1270. /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
  1271. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1272. enum AVCodecID codec_id)
  1273. {
  1274. AVStream *st;
  1275. uint64_t original_size;
  1276. int err;
  1277. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1278. return 0;
  1279. st = c->fc->streams[c->fc->nb_streams-1];
  1280. if (st->codecpar->codec_id != codec_id)
  1281. return 0; /* unexpected codec_id - don't mess with extradata */
  1282. original_size = st->codecpar->extradata_size;
  1283. err = mov_realloc_extradata(st->codecpar, atom);
  1284. if (err)
  1285. return err;
  1286. err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
  1287. if (err < 0)
  1288. return err;
  1289. return 0; // Note: this is the original behavior to ignore truncation.
  1290. }
  1291. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1292. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1293. {
  1294. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1295. }
  1296. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1297. {
  1298. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1299. }
  1300. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1301. {
  1302. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1303. }
  1304. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1305. {
  1306. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1307. }
  1308. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1309. {
  1310. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1311. if(ret == 0)
  1312. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1313. return ret;
  1314. }
  1315. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1316. {
  1317. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1318. if (!ret && c->fc->nb_streams >= 1) {
  1319. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1320. if (par->extradata_size >= 40) {
  1321. par->height = AV_RB16(&par->extradata[36]);
  1322. par->width = AV_RB16(&par->extradata[38]);
  1323. }
  1324. }
  1325. return ret;
  1326. }
  1327. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1328. {
  1329. if (c->fc->nb_streams >= 1) {
  1330. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1331. if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1332. par->codec_id == AV_CODEC_ID_H264 &&
  1333. atom.size > 11) {
  1334. int cid;
  1335. avio_skip(pb, 10);
  1336. cid = avio_rb16(pb);
  1337. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1338. if (cid == 0xd4d || cid == 0xd4e)
  1339. par->width = 1440;
  1340. return 0;
  1341. } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') ||
  1342. par->codec_tag == MKTAG('A', 'V', 'd', 'n')) &&
  1343. atom.size >= 24) {
  1344. int num, den;
  1345. avio_skip(pb, 12);
  1346. num = avio_rb32(pb);
  1347. den = avio_rb32(pb);
  1348. if (num <= 0 || den <= 0)
  1349. return 0;
  1350. switch (avio_rb32(pb)) {
  1351. case 2:
  1352. if (den >= INT_MAX / 2)
  1353. return 0;
  1354. den *= 2;
  1355. case 1:
  1356. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
  1357. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
  1358. default:
  1359. return 0;
  1360. }
  1361. }
  1362. }
  1363. return mov_read_avid(c, pb, atom);
  1364. }
  1365. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1366. {
  1367. int ret = 0;
  1368. int length = 0;
  1369. uint64_t original_size;
  1370. if (c->fc->nb_streams >= 1) {
  1371. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1372. if (par->codec_id == AV_CODEC_ID_H264)
  1373. return 0;
  1374. if (atom.size == 16) {
  1375. original_size = par->extradata_size;
  1376. ret = mov_realloc_extradata(par, atom);
  1377. if (!ret) {
  1378. length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
  1379. if (length == atom.size) {
  1380. const uint8_t range_value = par->extradata[original_size + 19];
  1381. switch (range_value) {
  1382. case 1:
  1383. par->color_range = AVCOL_RANGE_MPEG;
  1384. break;
  1385. case 2:
  1386. par->color_range = AVCOL_RANGE_JPEG;
  1387. break;
  1388. default:
  1389. av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1390. break;
  1391. }
  1392. ff_dlog(c, "color_range: %d\n", par->color_range);
  1393. } else {
  1394. /* For some reason the whole atom was not added to the extradata */
  1395. av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1396. }
  1397. } else {
  1398. av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1399. }
  1400. } else {
  1401. av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1402. }
  1403. }
  1404. return ret;
  1405. }
  1406. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1407. {
  1408. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1409. }
  1410. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1411. {
  1412. AVStream *st;
  1413. int ret;
  1414. if (c->fc->nb_streams < 1)
  1415. return 0;
  1416. st = c->fc->streams[c->fc->nb_streams-1];
  1417. if ((uint64_t)atom.size > (1<<30))
  1418. return AVERROR_INVALIDDATA;
  1419. if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
  1420. st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
  1421. st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
  1422. // pass all frma atom to codec, needed at least for QDMC and QDM2
  1423. av_freep(&st->codecpar->extradata);
  1424. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1425. if (ret < 0)
  1426. return ret;
  1427. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1428. if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1429. uint64_t buffer;
  1430. ret = ffio_ensure_seekback(pb, 8);
  1431. if (ret < 0)
  1432. return ret;
  1433. buffer = avio_rb64(pb);
  1434. atom.size -= 8;
  1435. if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1436. && buffer >> 32 <= atom.size
  1437. && buffer >> 32 >= 8) {
  1438. avio_skip(pb, -8);
  1439. atom.size += 8;
  1440. } else if (!st->codecpar->extradata_size) {
  1441. #define ALAC_EXTRADATA_SIZE 36
  1442. st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1443. if (!st->codecpar->extradata)
  1444. return AVERROR(ENOMEM);
  1445. st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
  1446. AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
  1447. AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
  1448. AV_WB64(st->codecpar->extradata + 12, buffer);
  1449. avio_read(pb, st->codecpar->extradata + 20, 16);
  1450. avio_skip(pb, atom.size - 24);
  1451. return 0;
  1452. }
  1453. }
  1454. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1455. return ret;
  1456. } else
  1457. avio_skip(pb, atom.size);
  1458. return 0;
  1459. }
  1460. /**
  1461. * This function reads atom content and puts data in extradata without tag
  1462. * nor size unlike mov_read_extradata.
  1463. */
  1464. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1465. {
  1466. AVStream *st;
  1467. int ret;
  1468. if (c->fc->nb_streams < 1)
  1469. return 0;
  1470. st = c->fc->streams[c->fc->nb_streams-1];
  1471. if ((uint64_t)atom.size > (1<<30))
  1472. return AVERROR_INVALIDDATA;
  1473. if (atom.size >= 10) {
  1474. // Broken files created by legacy versions of libavformat will
  1475. // wrap a whole fiel atom inside of a glbl atom.
  1476. unsigned size = avio_rb32(pb);
  1477. unsigned type = avio_rl32(pb);
  1478. avio_seek(pb, -8, SEEK_CUR);
  1479. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1480. return mov_read_default(c, pb, atom);
  1481. }
  1482. if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
  1483. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1484. return 0;
  1485. }
  1486. av_freep(&st->codecpar->extradata);
  1487. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1488. if (ret < 0)
  1489. return ret;
  1490. return 0;
  1491. }
  1492. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1493. {
  1494. AVStream *st;
  1495. uint8_t profile_level;
  1496. int ret;
  1497. if (c->fc->nb_streams < 1)
  1498. return 0;
  1499. st = c->fc->streams[c->fc->nb_streams-1];
  1500. if (atom.size >= (1<<28) || atom.size < 7)
  1501. return AVERROR_INVALIDDATA;
  1502. profile_level = avio_r8(pb);
  1503. if ((profile_level & 0xf0) != 0xc0)
  1504. return 0;
  1505. avio_seek(pb, 6, SEEK_CUR);
  1506. av_freep(&st->codecpar->extradata);
  1507. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
  1508. if (ret < 0)
  1509. return ret;
  1510. return 0;
  1511. }
  1512. /**
  1513. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1514. * but can have extradata appended at the end after the 40 bytes belonging
  1515. * to the struct.
  1516. */
  1517. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1518. {
  1519. AVStream *st;
  1520. int ret;
  1521. if (c->fc->nb_streams < 1)
  1522. return 0;
  1523. if (atom.size <= 40)
  1524. return 0;
  1525. st = c->fc->streams[c->fc->nb_streams-1];
  1526. if ((uint64_t)atom.size > (1<<30))
  1527. return AVERROR_INVALIDDATA;
  1528. avio_skip(pb, 40);
  1529. av_freep(&st->codecpar->extradata);
  1530. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
  1531. if (ret < 0)
  1532. return ret;
  1533. return 0;
  1534. }
  1535. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1536. {
  1537. AVStream *st;
  1538. MOVStreamContext *sc;
  1539. unsigned int i, entries;
  1540. if (c->fc->nb_streams < 1)
  1541. return 0;
  1542. st = c->fc->streams[c->fc->nb_streams-1];
  1543. sc = st->priv_data;
  1544. avio_r8(pb); /* version */
  1545. avio_rb24(pb); /* flags */
  1546. entries = avio_rb32(pb);
  1547. if (!entries)
  1548. return 0;
  1549. if (sc->chunk_offsets)
  1550. av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1551. av_free(sc->chunk_offsets);
  1552. sc->chunk_count = 0;
  1553. sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1554. if (!sc->chunk_offsets)
  1555. return AVERROR(ENOMEM);
  1556. sc->chunk_count = entries;
  1557. if (atom.type == MKTAG('s','t','c','o'))
  1558. for (i = 0; i < entries && !pb->eof_reached; i++)
  1559. sc->chunk_offsets[i] = avio_rb32(pb);
  1560. else if (atom.type == MKTAG('c','o','6','4'))
  1561. for (i = 0; i < entries && !pb->eof_reached; i++)
  1562. sc->chunk_offsets[i] = avio_rb64(pb);
  1563. else
  1564. return AVERROR_INVALIDDATA;
  1565. sc->chunk_count = i;
  1566. if (pb->eof_reached)
  1567. return AVERROR_EOF;
  1568. return 0;
  1569. }
  1570. /**
  1571. * Compute codec id for 'lpcm' tag.
  1572. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1573. */
  1574. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1575. {
  1576. /* lpcm flags:
  1577. * 0x1 = float
  1578. * 0x2 = big-endian
  1579. * 0x4 = signed
  1580. */
  1581. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1582. }
  1583. static int mov_codec_id(AVStream *st, uint32_t format)
  1584. {
  1585. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1586. if (id <= 0 &&
  1587. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1588. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1589. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1590. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1591. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1592. } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
  1593. /* skip old ASF MPEG-4 tag */
  1594. format && format != MKTAG('m','p','4','s')) {
  1595. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1596. if (id <= 0)
  1597. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1598. if (id > 0)
  1599. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1600. else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
  1601. (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1602. st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
  1603. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1604. if (id > 0)
  1605. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1606. }
  1607. }
  1608. st->codecpar->codec_tag = format;
  1609. return id;
  1610. }
  1611. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1612. AVStream *st, MOVStreamContext *sc)
  1613. {
  1614. uint8_t codec_name[32] = { 0 };
  1615. int64_t stsd_start;
  1616. unsigned int len;
  1617. /* The first 16 bytes of the video sample description are already
  1618. * read in ff_mov_read_stsd_entries() */
  1619. stsd_start = avio_tell(pb) - 16;
  1620. avio_rb16(pb); /* version */
  1621. avio_rb16(pb); /* revision level */
  1622. avio_rb32(pb); /* vendor */
  1623. avio_rb32(pb); /* temporal quality */
  1624. avio_rb32(pb); /* spatial quality */
  1625. st->codecpar->width = avio_rb16(pb); /* width */
  1626. st->codecpar->height = avio_rb16(pb); /* height */
  1627. avio_rb32(pb); /* horiz resolution */
  1628. avio_rb32(pb); /* vert resolution */
  1629. avio_rb32(pb); /* data size, always 0 */
  1630. avio_rb16(pb); /* frames per samples */
  1631. len = avio_r8(pb); /* codec name, pascal string */
  1632. if (len > 31)
  1633. len = 31;
  1634. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1635. if (len < 31)
  1636. avio_skip(pb, 31 - len);
  1637. if (codec_name[0])
  1638. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1639. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1640. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1641. st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
  1642. st->codecpar->width &= ~1;
  1643. st->codecpar->height &= ~1;
  1644. }
  1645. /* Flash Media Server uses tag H.263 with Sorenson Spark */
  1646. if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
  1647. !memcmp(codec_name, "Sorenson H263", 13))
  1648. st->codecpar->codec_id = AV_CODEC_ID_FLV1;
  1649. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1650. avio_seek(pb, stsd_start, SEEK_SET);
  1651. if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
  1652. st->codecpar->bits_per_coded_sample &= 0x1F;
  1653. sc->has_palette = 1;
  1654. }
  1655. }
  1656. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1657. AVStream *st, MOVStreamContext *sc)
  1658. {
  1659. int bits_per_sample, flags;
  1660. uint16_t version = avio_rb16(pb);
  1661. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1662. avio_rb16(pb); /* revision level */
  1663. avio_rb32(pb); /* vendor */
  1664. st->codecpar->channels = avio_rb16(pb); /* channel count */
  1665. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1666. av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
  1667. sc->audio_cid = avio_rb16(pb);
  1668. avio_rb16(pb); /* packet size = 0 */
  1669. st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
  1670. // Read QT version 1 fields. In version 0 these do not exist.
  1671. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1672. if (!c->isom ||
  1673. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1674. if (version == 1) {
  1675. sc->samples_per_frame = avio_rb32(pb);
  1676. avio_rb32(pb); /* bytes per packet */
  1677. sc->bytes_per_frame = avio_rb32(pb);
  1678. avio_rb32(pb); /* bytes per sample */
  1679. } else if (version == 2) {
  1680. avio_rb32(pb); /* sizeof struct only */
  1681. st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
  1682. st->codecpar->channels = avio_rb32(pb);
  1683. avio_rb32(pb); /* always 0x7F000000 */
  1684. st->codecpar->bits_per_coded_sample = avio_rb32(pb);
  1685. flags = avio_rb32(pb); /* lpcm format specific flag */
  1686. sc->bytes_per_frame = avio_rb32(pb);
  1687. sc->samples_per_frame = avio_rb32(pb);
  1688. if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
  1689. st->codecpar->codec_id =
  1690. ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
  1691. flags);
  1692. }
  1693. if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1694. /* can't correctly handle variable sized packet as audio unit */
  1695. switch (st->codecpar->codec_id) {
  1696. case AV_CODEC_ID_MP2:
  1697. case AV_CODEC_ID_MP3:
  1698. st->need_parsing = AVSTREAM_PARSE_FULL;
  1699. break;
  1700. }
  1701. }
  1702. }
  1703. if (sc->format == 0) {
  1704. if (st->codecpar->bits_per_coded_sample == 8)
  1705. st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
  1706. else if (st->codecpar->bits_per_coded_sample == 16)
  1707. st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
  1708. }
  1709. switch (st->codecpar->codec_id) {
  1710. case AV_CODEC_ID_PCM_S8:
  1711. case AV_CODEC_ID_PCM_U8:
  1712. if (st->codecpar->bits_per_coded_sample == 16)
  1713. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
  1714. break;
  1715. case AV_CODEC_ID_PCM_S16LE:
  1716. case AV_CODEC_ID_PCM_S16BE:
  1717. if (st->codecpar->bits_per_coded_sample == 8)
  1718. st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
  1719. else if (st->codecpar->bits_per_coded_sample == 24)
  1720. st->codecpar->codec_id =
  1721. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1722. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1723. else if (st->codecpar->bits_per_coded_sample == 32)
  1724. st->codecpar->codec_id =
  1725. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1726. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1727. break;
  1728. /* set values for old format before stsd version 1 appeared */
  1729. case AV_CODEC_ID_MACE3:
  1730. sc->samples_per_frame = 6;
  1731. sc->bytes_per_frame = 2 * st->codecpar->channels;
  1732. break;
  1733. case AV_CODEC_ID_MACE6:
  1734. sc->samples_per_frame = 6;
  1735. sc->bytes_per_frame = 1 * st->codecpar->channels;
  1736. break;
  1737. case AV_CODEC_ID_ADPCM_IMA_QT:
  1738. sc->samples_per_frame = 64;
  1739. sc->bytes_per_frame = 34 * st->codecpar->channels;
  1740. break;
  1741. case AV_CODEC_ID_GSM:
  1742. sc->samples_per_frame = 160;
  1743. sc->bytes_per_frame = 33;
  1744. break;
  1745. default:
  1746. break;
  1747. }
  1748. bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
  1749. if (bits_per_sample) {
  1750. st->codecpar->bits_per_coded_sample = bits_per_sample;
  1751. sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
  1752. }
  1753. }
  1754. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1755. AVStream *st, MOVStreamContext *sc,
  1756. int64_t size)
  1757. {
  1758. // ttxt stsd contains display flags, justification, background
  1759. // color, fonts, and default styles, so fake an atom to read it
  1760. MOVAtom fake_atom = { .size = size };
  1761. // mp4s contains a regular esds atom
  1762. if (st->codecpar->codec_tag != AV_RL32("mp4s"))
  1763. mov_read_glbl(c, pb, fake_atom);
  1764. st->codecpar->width = sc->width;
  1765. st->codecpar->height = sc->height;
  1766. }
  1767. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1768. {
  1769. uint8_t r, g, b;
  1770. int y, cb, cr;
  1771. y = (ycbcr >> 16) & 0xFF;
  1772. cr = (ycbcr >> 8) & 0xFF;
  1773. cb = ycbcr & 0xFF;
  1774. b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
  1775. g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
  1776. r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
  1777. return (r << 16) | (g << 8) | b;
  1778. }
  1779. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1780. {
  1781. char buf[256] = {0};
  1782. uint8_t *src = st->codecpar->extradata;
  1783. int i;
  1784. if (st->codecpar->extradata_size != 64)
  1785. return 0;
  1786. if (st->codecpar->width > 0 && st->codecpar->height > 0)
  1787. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1788. st->codecpar->width, st->codecpar->height);
  1789. av_strlcat(buf, "palette: ", sizeof(buf));
  1790. for (i = 0; i < 16; i++) {
  1791. uint32_t yuv = AV_RB32(src + i * 4);
  1792. uint32_t rgba = yuv_to_rgba(yuv);
  1793. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1794. }
  1795. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1796. return 0;
  1797. av_freep(&st->codecpar->extradata);
  1798. st->codecpar->extradata_size = 0;
  1799. st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1800. if (!st->codecpar->extradata)
  1801. return AVERROR(ENOMEM);
  1802. st->codecpar->extradata_size = strlen(buf);
  1803. memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
  1804. return 0;
  1805. }
  1806. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1807. AVStream *st, MOVStreamContext *sc,
  1808. int64_t size)
  1809. {
  1810. int ret;
  1811. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  1812. if ((int)size != size)
  1813. return AVERROR(ENOMEM);
  1814. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  1815. if (ret < 0)
  1816. return ret;
  1817. if (size > 16) {
  1818. MOVStreamContext *tmcd_ctx = st->priv_data;
  1819. int val;
  1820. val = AV_RB32(st->codecpar->extradata + 4);
  1821. tmcd_ctx->tmcd_flags = val;
  1822. st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
  1823. st->avg_frame_rate.den = 1;
  1824. #if FF_API_LAVF_AVCTX
  1825. FF_DISABLE_DEPRECATION_WARNINGS
  1826. st->codec->time_base = av_inv_q(st->avg_frame_rate);
  1827. FF_ENABLE_DEPRECATION_WARNINGS
  1828. #endif
  1829. /* adjust for per frame dur in counter mode */
  1830. if (tmcd_ctx->tmcd_flags & 0x0008) {
  1831. int timescale = AV_RB32(st->codecpar->extradata + 8);
  1832. int framedur = AV_RB32(st->codecpar->extradata + 12);
  1833. st->avg_frame_rate.num *= timescale;
  1834. st->avg_frame_rate.den *= framedur;
  1835. #if FF_API_LAVF_AVCTX
  1836. FF_DISABLE_DEPRECATION_WARNINGS
  1837. st->codec->time_base.den *= timescale;
  1838. st->codec->time_base.num *= framedur;
  1839. FF_ENABLE_DEPRECATION_WARNINGS
  1840. #endif
  1841. }
  1842. if (size > 30) {
  1843. uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
  1844. uint32_t format = AV_RB32(st->codecpar->extradata + 22);
  1845. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1846. uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
  1847. if (str_size > 0 && size >= (int)str_size + 26) {
  1848. char *reel_name = av_malloc(str_size + 1);
  1849. if (!reel_name)
  1850. return AVERROR(ENOMEM);
  1851. memcpy(reel_name, st->codecpar->extradata + 30, str_size);
  1852. reel_name[str_size] = 0; /* Add null terminator */
  1853. /* don't add reel_name if emtpy string */
  1854. if (*reel_name == 0) {
  1855. av_free(reel_name);
  1856. } else {
  1857. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. }
  1863. } else {
  1864. /* other codec type, just skip (rtp, mp4s ...) */
  1865. avio_skip(pb, size);
  1866. }
  1867. return 0;
  1868. }
  1869. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1870. AVStream *st, MOVStreamContext *sc)
  1871. {
  1872. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1873. !st->codecpar->sample_rate && sc->time_scale > 1)
  1874. st->codecpar->sample_rate = sc->time_scale;
  1875. /* special codec parameters handling */
  1876. switch (st->codecpar->codec_id) {
  1877. #if CONFIG_DV_DEMUXER
  1878. case AV_CODEC_ID_DVAUDIO:
  1879. c->dv_fctx = avformat_alloc_context();
  1880. if (!c->dv_fctx) {
  1881. av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  1882. return AVERROR(ENOMEM);
  1883. }
  1884. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1885. if (!c->dv_demux) {
  1886. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1887. return AVERROR(ENOMEM);
  1888. }
  1889. sc->dv_audio_container = 1;
  1890. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
  1891. break;
  1892. #endif
  1893. /* no ifdef since parameters are always those */
  1894. case AV_CODEC_ID_QCELP:
  1895. st->codecpar->channels = 1;
  1896. // force sample rate for qcelp when not stored in mov
  1897. if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
  1898. st->codecpar->sample_rate = 8000;
  1899. // FIXME: Why is the following needed for some files?
  1900. sc->samples_per_frame = 160;
  1901. if (!sc->bytes_per_frame)
  1902. sc->bytes_per_frame = 35;
  1903. break;
  1904. case AV_CODEC_ID_AMR_NB:
  1905. st->codecpar->channels = 1;
  1906. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1907. st->codecpar->sample_rate = 8000;
  1908. break;
  1909. case AV_CODEC_ID_AMR_WB:
  1910. st->codecpar->channels = 1;
  1911. st->codecpar->sample_rate = 16000;
  1912. break;
  1913. case AV_CODEC_ID_MP2:
  1914. case AV_CODEC_ID_MP3:
  1915. /* force type after stsd for m1a hdlr */
  1916. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1917. break;
  1918. case AV_CODEC_ID_GSM:
  1919. case AV_CODEC_ID_ADPCM_MS:
  1920. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1921. case AV_CODEC_ID_ILBC:
  1922. case AV_CODEC_ID_MACE3:
  1923. case AV_CODEC_ID_MACE6:
  1924. case AV_CODEC_ID_QDM2:
  1925. st->codecpar->block_align = sc->bytes_per_frame;
  1926. break;
  1927. case AV_CODEC_ID_ALAC:
  1928. if (st->codecpar->extradata_size == 36) {
  1929. st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
  1930. st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
  1931. }
  1932. break;
  1933. case AV_CODEC_ID_AC3:
  1934. case AV_CODEC_ID_EAC3:
  1935. case AV_CODEC_ID_MPEG1VIDEO:
  1936. case AV_CODEC_ID_VC1:
  1937. case AV_CODEC_ID_VP9:
  1938. st->need_parsing = AVSTREAM_PARSE_FULL;
  1939. break;
  1940. default:
  1941. break;
  1942. }
  1943. return 0;
  1944. }
  1945. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1946. int codec_tag, int format,
  1947. int64_t size)
  1948. {
  1949. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1950. if (codec_tag &&
  1951. (codec_tag != format &&
  1952. // AVID 1:1 samples with differing data format and codec tag exist
  1953. (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) &&
  1954. // prores is allowed to have differing data format and codec tag
  1955. codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") &&
  1956. // so is dv (sigh)
  1957. codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") &&
  1958. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1959. : codec_tag != MKTAG('j','p','e','g')))) {
  1960. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1961. * export it as a separate AVStream but this needs a few changes
  1962. * in the MOV demuxer, patch welcome. */
  1963. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1964. avio_skip(pb, size);
  1965. return 1;
  1966. }
  1967. return 0;
  1968. }
  1969. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1970. {
  1971. AVStream *st;
  1972. MOVStreamContext *sc;
  1973. int pseudo_stream_id;
  1974. if (c->fc->nb_streams < 1)
  1975. return 0;
  1976. st = c->fc->streams[c->fc->nb_streams-1];
  1977. sc = st->priv_data;
  1978. for (pseudo_stream_id = 0;
  1979. pseudo_stream_id < entries && !pb->eof_reached;
  1980. pseudo_stream_id++) {
  1981. //Parsing Sample description table
  1982. enum AVCodecID id;
  1983. int ret, dref_id = 1;
  1984. MOVAtom a = { AV_RL32("stsd") };
  1985. int64_t start_pos = avio_tell(pb);
  1986. int64_t size = avio_rb32(pb); /* size */
  1987. uint32_t format = avio_rl32(pb); /* data format */
  1988. if (size >= 16) {
  1989. avio_rb32(pb); /* reserved */
  1990. avio_rb16(pb); /* reserved */
  1991. dref_id = avio_rb16(pb);
  1992. } else if (size <= 7) {
  1993. av_log(c->fc, AV_LOG_ERROR,
  1994. "invalid size %"PRId64" in stsd\n", size);
  1995. return AVERROR_INVALIDDATA;
  1996. }
  1997. if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
  1998. size - (avio_tell(pb) - start_pos)))
  1999. continue;
  2000. sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
  2001. sc->dref_id= dref_id;
  2002. sc->format = format;
  2003. id = mov_codec_id(st, format);
  2004. av_log(c->fc, AV_LOG_TRACE,
  2005. "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
  2006. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  2007. (format >> 24) & 0xff, format, st->codecpar->codec_type);
  2008. if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
  2009. st->codecpar->codec_id = id;
  2010. mov_parse_stsd_video(c, pb, st, sc);
  2011. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
  2012. st->codecpar->codec_id = id;
  2013. mov_parse_stsd_audio(c, pb, st, sc);
  2014. if (st->codecpar->sample_rate < 0) {
  2015. av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate);
  2016. return AVERROR_INVALIDDATA;
  2017. }
  2018. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
  2019. st->codecpar->codec_id = id;
  2020. mov_parse_stsd_subtitle(c, pb, st, sc,
  2021. size - (avio_tell(pb) - start_pos));
  2022. } else {
  2023. ret = mov_parse_stsd_data(c, pb, st, sc,
  2024. size - (avio_tell(pb) - start_pos));
  2025. if (ret < 0)
  2026. return ret;
  2027. }
  2028. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  2029. a.size = size - (avio_tell(pb) - start_pos);
  2030. if (a.size > 8) {
  2031. if ((ret = mov_read_default(c, pb, a)) < 0)
  2032. return ret;
  2033. } else if (a.size > 0)
  2034. avio_skip(pb, a.size);
  2035. if (sc->extradata) {
  2036. int extra_size = st->codecpar->extradata_size;
  2037. /* Move the current stream extradata to the stream context one. */
  2038. sc->extradata_size[pseudo_stream_id] = extra_size;
  2039. sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE);
  2040. if (!sc->extradata[pseudo_stream_id])
  2041. return AVERROR(ENOMEM);
  2042. memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size);
  2043. av_freep(&st->codecpar->extradata);
  2044. st->codecpar->extradata_size = 0;
  2045. }
  2046. }
  2047. if (pb->eof_reached)
  2048. return AVERROR_EOF;
  2049. return 0;
  2050. }
  2051. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2052. {
  2053. AVStream *st;
  2054. MOVStreamContext *sc;
  2055. int ret, entries;
  2056. if (c->fc->nb_streams < 1)
  2057. return 0;
  2058. st = c->fc->streams[c->fc->nb_streams - 1];
  2059. sc = st->priv_data;
  2060. avio_r8(pb); /* version */
  2061. avio_rb24(pb); /* flags */
  2062. entries = avio_rb32(pb);
  2063. if (entries <= 0) {
  2064. av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
  2065. return AVERROR_INVALIDDATA;
  2066. }
  2067. if (sc->extradata) {
  2068. av_log(c->fc, AV_LOG_ERROR, "Duplicate STSD\n");
  2069. return AVERROR_INVALIDDATA;
  2070. }
  2071. /* Prepare space for hosting multiple extradata. */
  2072. sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
  2073. sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
  2074. if (!sc->extradata_size || !sc->extradata) {
  2075. ret = AVERROR(ENOMEM);
  2076. goto fail;
  2077. }
  2078. ret = ff_mov_read_stsd_entries(c, pb, entries);
  2079. if (ret < 0)
  2080. return ret;
  2081. sc->stsd_count = entries;
  2082. /* Restore back the primary extradata. */
  2083. av_freep(&st->codecpar->extradata);
  2084. st->codecpar->extradata_size = sc->extradata_size[0];
  2085. if (sc->extradata_size[0]) {
  2086. st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
  2087. if (!st->codecpar->extradata)
  2088. return AVERROR(ENOMEM);
  2089. memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
  2090. }
  2091. return mov_finalize_stsd_codec(c, pb, st, sc);
  2092. fail:
  2093. av_freep(&sc->extradata);
  2094. av_freep(&sc->extradata_size);
  2095. return ret;
  2096. }
  2097. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2098. {
  2099. AVStream *st;
  2100. MOVStreamContext *sc;
  2101. unsigned int i, entries;
  2102. if (c->fc->nb_streams < 1)
  2103. return 0;
  2104. st = c->fc->streams[c->fc->nb_streams-1];
  2105. sc = st->priv_data;
  2106. avio_r8(pb); /* version */
  2107. avio_rb24(pb); /* flags */
  2108. entries = avio_rb32(pb);
  2109. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  2110. if (!entries)
  2111. return 0;
  2112. if (sc->stsc_data)
  2113. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2114. av_free(sc->stsc_data);
  2115. sc->stsc_count = 0;
  2116. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2117. if (!sc->stsc_data)
  2118. return AVERROR(ENOMEM);
  2119. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2120. sc->stsc_data[i].first = avio_rb32(pb);
  2121. sc->stsc_data[i].count = avio_rb32(pb);
  2122. sc->stsc_data[i].id = avio_rb32(pb);
  2123. }
  2124. sc->stsc_count = i;
  2125. if (pb->eof_reached)
  2126. return AVERROR_EOF;
  2127. return 0;
  2128. }
  2129. #define mov_stsc_index_valid(index, count) ((index) < (count) - 1)
  2130. /* Compute the samples value for the stsc entry at the given index. */
  2131. static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index)
  2132. {
  2133. int chunk_count;
  2134. if (mov_stsc_index_valid(index, sc->stsc_count))
  2135. chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
  2136. else
  2137. chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
  2138. return sc->stsc_data[index].count * chunk_count;
  2139. }
  2140. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2141. {
  2142. AVStream *st;
  2143. MOVStreamContext *sc;
  2144. unsigned i, entries;
  2145. if (c->fc->nb_streams < 1)
  2146. return 0;
  2147. st = c->fc->streams[c->fc->nb_streams-1];
  2148. sc = st->priv_data;
  2149. avio_rb32(pb); // version + flags
  2150. entries = avio_rb32(pb);
  2151. if (sc->stps_data)
  2152. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2153. av_free(sc->stps_data);
  2154. sc->stps_count = 0;
  2155. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2156. if (!sc->stps_data)
  2157. return AVERROR(ENOMEM);
  2158. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2159. sc->stps_data[i] = avio_rb32(pb);
  2160. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  2161. }
  2162. sc->stps_count = i;
  2163. if (pb->eof_reached)
  2164. return AVERROR_EOF;
  2165. return 0;
  2166. }
  2167. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2168. {
  2169. AVStream *st;
  2170. MOVStreamContext *sc;
  2171. unsigned int i, entries;
  2172. if (c->fc->nb_streams < 1)
  2173. return 0;
  2174. st = c->fc->streams[c->fc->nb_streams-1];
  2175. sc = st->priv_data;
  2176. avio_r8(pb); /* version */
  2177. avio_rb24(pb); /* flags */
  2178. entries = avio_rb32(pb);
  2179. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2180. if (!entries)
  2181. {
  2182. sc->keyframe_absent = 1;
  2183. if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2184. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2185. return 0;
  2186. }
  2187. if (sc->keyframes)
  2188. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2189. if (entries >= UINT_MAX / sizeof(int))
  2190. return AVERROR_INVALIDDATA;
  2191. av_freep(&sc->keyframes);
  2192. sc->keyframe_count = 0;
  2193. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2194. if (!sc->keyframes)
  2195. return AVERROR(ENOMEM);
  2196. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2197. sc->keyframes[i] = avio_rb32(pb);
  2198. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2199. }
  2200. sc->keyframe_count = i;
  2201. if (pb->eof_reached)
  2202. return AVERROR_EOF;
  2203. return 0;
  2204. }
  2205. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2206. {
  2207. AVStream *st;
  2208. MOVStreamContext *sc;
  2209. unsigned int i, entries, sample_size, field_size, num_bytes;
  2210. GetBitContext gb;
  2211. unsigned char* buf;
  2212. int ret;
  2213. if (c->fc->nb_streams < 1)
  2214. return 0;
  2215. st = c->fc->streams[c->fc->nb_streams-1];
  2216. sc = st->priv_data;
  2217. avio_r8(pb); /* version */
  2218. avio_rb24(pb); /* flags */
  2219. if (atom.type == MKTAG('s','t','s','z')) {
  2220. sample_size = avio_rb32(pb);
  2221. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2222. sc->sample_size = sample_size;
  2223. sc->stsz_sample_size = sample_size;
  2224. field_size = 32;
  2225. } else {
  2226. sample_size = 0;
  2227. avio_rb24(pb); /* reserved */
  2228. field_size = avio_r8(pb);
  2229. }
  2230. entries = avio_rb32(pb);
  2231. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2232. sc->sample_count = entries;
  2233. if (sample_size)
  2234. return 0;
  2235. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2236. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2237. return AVERROR_INVALIDDATA;
  2238. }
  2239. if (!entries)
  2240. return 0;
  2241. if (entries >= (UINT_MAX - 4) / field_size)
  2242. return AVERROR_INVALIDDATA;
  2243. if (sc->sample_sizes)
  2244. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2245. av_free(sc->sample_sizes);
  2246. sc->sample_count = 0;
  2247. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2248. if (!sc->sample_sizes)
  2249. return AVERROR(ENOMEM);
  2250. num_bytes = (entries*field_size+4)>>3;
  2251. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2252. if (!buf) {
  2253. av_freep(&sc->sample_sizes);
  2254. return AVERROR(ENOMEM);
  2255. }
  2256. ret = ffio_read_size(pb, buf, num_bytes);
  2257. if (ret < 0) {
  2258. av_freep(&sc->sample_sizes);
  2259. av_free(buf);
  2260. return ret;
  2261. }
  2262. init_get_bits(&gb, buf, 8*num_bytes);
  2263. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2264. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2265. sc->data_size += sc->sample_sizes[i];
  2266. }
  2267. sc->sample_count = i;
  2268. av_free(buf);
  2269. if (pb->eof_reached)
  2270. return AVERROR_EOF;
  2271. return 0;
  2272. }
  2273. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2274. {
  2275. AVStream *st;
  2276. MOVStreamContext *sc;
  2277. unsigned int i, entries;
  2278. int64_t duration=0;
  2279. int64_t total_sample_count=0;
  2280. if (c->fc->nb_streams < 1)
  2281. return 0;
  2282. st = c->fc->streams[c->fc->nb_streams-1];
  2283. sc = st->priv_data;
  2284. avio_r8(pb); /* version */
  2285. avio_rb24(pb); /* flags */
  2286. entries = avio_rb32(pb);
  2287. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2288. c->fc->nb_streams-1, entries);
  2289. if (sc->stts_data)
  2290. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2291. av_free(sc->stts_data);
  2292. sc->stts_count = 0;
  2293. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2294. if (!sc->stts_data)
  2295. return AVERROR(ENOMEM);
  2296. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2297. int sample_duration;
  2298. int sample_count;
  2299. sample_count=avio_rb32(pb);
  2300. sample_duration = avio_rb32(pb);
  2301. if (sample_count < 0) {
  2302. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2303. return AVERROR_INVALIDDATA;
  2304. }
  2305. sc->stts_data[i].count= sample_count;
  2306. sc->stts_data[i].duration= sample_duration;
  2307. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2308. sample_count, sample_duration);
  2309. if ( i+1 == entries
  2310. && i
  2311. && sample_count == 1
  2312. && total_sample_count > 100
  2313. && sample_duration/10 > duration / total_sample_count)
  2314. sample_duration = duration / total_sample_count;
  2315. duration+=(int64_t)sample_duration*sample_count;
  2316. total_sample_count+=sample_count;
  2317. }
  2318. sc->stts_count = i;
  2319. sc->duration_for_fps += duration;
  2320. sc->nb_frames_for_fps += total_sample_count;
  2321. if (pb->eof_reached)
  2322. return AVERROR_EOF;
  2323. st->nb_frames= total_sample_count;
  2324. if (duration)
  2325. st->duration= duration;
  2326. sc->track_end = duration;
  2327. return 0;
  2328. }
  2329. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2330. {
  2331. if (duration < 0) {
  2332. if (duration == INT_MIN) {
  2333. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2334. duration++;
  2335. }
  2336. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2337. }
  2338. }
  2339. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2340. {
  2341. AVStream *st;
  2342. MOVStreamContext *sc;
  2343. unsigned int i, entries, ctts_count = 0;
  2344. if (c->fc->nb_streams < 1)
  2345. return 0;
  2346. st = c->fc->streams[c->fc->nb_streams-1];
  2347. sc = st->priv_data;
  2348. avio_r8(pb); /* version */
  2349. avio_rb24(pb); /* flags */
  2350. entries = avio_rb32(pb);
  2351. av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2352. if (!entries)
  2353. return 0;
  2354. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2355. return AVERROR_INVALIDDATA;
  2356. av_freep(&sc->ctts_data);
  2357. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2358. if (!sc->ctts_data)
  2359. return AVERROR(ENOMEM);
  2360. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2361. int count =avio_rb32(pb);
  2362. int duration =avio_rb32(pb);
  2363. if (count <= 0) {
  2364. av_log(c->fc, AV_LOG_TRACE,
  2365. "ignoring CTTS entry with count=%d duration=%d\n",
  2366. count, duration);
  2367. continue;
  2368. }
  2369. sc->ctts_data[ctts_count].count = count;
  2370. sc->ctts_data[ctts_count].duration = duration;
  2371. ctts_count++;
  2372. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2373. count, duration);
  2374. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2375. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2376. av_freep(&sc->ctts_data);
  2377. sc->ctts_count = 0;
  2378. return 0;
  2379. }
  2380. if (i+2<entries)
  2381. mov_update_dts_shift(sc, duration);
  2382. }
  2383. sc->ctts_count = ctts_count;
  2384. if (pb->eof_reached)
  2385. return AVERROR_EOF;
  2386. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2387. return 0;
  2388. }
  2389. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2390. {
  2391. AVStream *st;
  2392. MOVStreamContext *sc;
  2393. unsigned int i, entries;
  2394. uint8_t version;
  2395. uint32_t grouping_type;
  2396. if (c->fc->nb_streams < 1)
  2397. return 0;
  2398. st = c->fc->streams[c->fc->nb_streams-1];
  2399. sc = st->priv_data;
  2400. version = avio_r8(pb); /* version */
  2401. avio_rb24(pb); /* flags */
  2402. grouping_type = avio_rl32(pb);
  2403. if (grouping_type != MKTAG( 'r','a','p',' '))
  2404. return 0; /* only support 'rap ' grouping */
  2405. if (version == 1)
  2406. avio_rb32(pb); /* grouping_type_parameter */
  2407. entries = avio_rb32(pb);
  2408. if (!entries)
  2409. return 0;
  2410. if (sc->rap_group)
  2411. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2412. av_free(sc->rap_group);
  2413. sc->rap_group_count = 0;
  2414. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2415. if (!sc->rap_group)
  2416. return AVERROR(ENOMEM);
  2417. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2418. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2419. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2420. }
  2421. sc->rap_group_count = i;
  2422. return pb->eof_reached ? AVERROR_EOF : 0;
  2423. }
  2424. /**
  2425. * Get ith edit list entry (media time, duration).
  2426. */
  2427. static int get_edit_list_entry(MOVContext *mov,
  2428. const MOVStreamContext *msc,
  2429. unsigned int edit_list_index,
  2430. int64_t *edit_list_media_time,
  2431. int64_t *edit_list_duration,
  2432. int64_t global_timescale)
  2433. {
  2434. if (edit_list_index == msc->elst_count) {
  2435. return 0;
  2436. }
  2437. *edit_list_media_time = msc->elst_data[edit_list_index].time;
  2438. *edit_list_duration = msc->elst_data[edit_list_index].duration;
  2439. /* duration is in global timescale units;convert to msc timescale */
  2440. if (global_timescale == 0) {
  2441. avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
  2442. return 0;
  2443. }
  2444. *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
  2445. global_timescale);
  2446. return 1;
  2447. }
  2448. /**
  2449. * Find the closest previous frame to the timestamp, in e_old index
  2450. * entries. Searching for just any frame / just key frames can be controlled by
  2451. * last argument 'flag'.
  2452. * Returns the index of the entry in st->index_entries if successful,
  2453. * else returns -1.
  2454. */
  2455. static int64_t find_prev_closest_index(AVStream *st,
  2456. AVIndexEntry *e_old,
  2457. int nb_old,
  2458. int64_t timestamp,
  2459. int flag)
  2460. {
  2461. AVIndexEntry *e_keep = st->index_entries;
  2462. int nb_keep = st->nb_index_entries;
  2463. int64_t found = -1;
  2464. int64_t i = 0;
  2465. st->index_entries = e_old;
  2466. st->nb_index_entries = nb_old;
  2467. found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
  2468. // Keep going backwards in the index entries until the timestamp is the same.
  2469. if (found >= 0) {
  2470. for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
  2471. i--) {
  2472. if ((flag & AVSEEK_FLAG_ANY) ||
  2473. (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
  2474. found = i - 1;
  2475. }
  2476. }
  2477. }
  2478. /* restore AVStream state*/
  2479. st->index_entries = e_keep;
  2480. st->nb_index_entries = nb_keep;
  2481. return found;
  2482. }
  2483. /**
  2484. * Add index entry with the given values, to the end of st->index_entries.
  2485. * Returns the new size st->index_entries if successful, else returns -1.
  2486. *
  2487. * This function is similar to ff_add_index_entry in libavformat/utils.c
  2488. * except that here we are always unconditionally adding an index entry to
  2489. * the end, instead of searching the entries list and skipping the add if
  2490. * there is an existing entry with the same timestamp.
  2491. * This is needed because the mov_fix_index calls this func with the same
  2492. * unincremented timestamp for successive discarded frames.
  2493. */
  2494. static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
  2495. int size, int distance, int flags)
  2496. {
  2497. AVIndexEntry *entries, *ie;
  2498. int64_t index = -1;
  2499. const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
  2500. // Double the allocation each time, to lower memory fragmentation.
  2501. // Another difference from ff_add_index_entry function.
  2502. const size_t requested_size =
  2503. min_size_needed > st->index_entries_allocated_size ?
  2504. FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
  2505. min_size_needed;
  2506. if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  2507. return -1;
  2508. entries = av_fast_realloc(st->index_entries,
  2509. &st->index_entries_allocated_size,
  2510. requested_size);
  2511. if(!entries)
  2512. return -1;
  2513. st->index_entries= entries;
  2514. index= st->nb_index_entries++;
  2515. ie= &entries[index];
  2516. ie->pos = pos;
  2517. ie->timestamp = timestamp;
  2518. ie->min_distance= distance;
  2519. ie->size= size;
  2520. ie->flags = flags;
  2521. return index;
  2522. }
  2523. /**
  2524. * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
  2525. * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
  2526. */
  2527. static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
  2528. int64_t* frame_duration_buffer,
  2529. int frame_duration_buffer_size) {
  2530. int i = 0;
  2531. av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
  2532. for (i = 0; i < frame_duration_buffer_size; i++) {
  2533. end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
  2534. st->index_entries[end_index - 1 - i].timestamp = end_ts;
  2535. }
  2536. }
  2537. /**
  2538. * Append a new ctts entry to ctts_data.
  2539. * Returns the new ctts_count if successful, else returns -1.
  2540. */
  2541. static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
  2542. int count, int duration)
  2543. {
  2544. MOVStts *ctts_buf_new;
  2545. const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
  2546. const size_t requested_size =
  2547. min_size_needed > *allocated_size ?
  2548. FFMAX(min_size_needed, 2 * (*allocated_size)) :
  2549. min_size_needed;
  2550. if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
  2551. return -1;
  2552. ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
  2553. if(!ctts_buf_new)
  2554. return -1;
  2555. *ctts_data = ctts_buf_new;
  2556. ctts_buf_new[*ctts_count].count = count;
  2557. ctts_buf_new[*ctts_count].duration = duration;
  2558. *ctts_count = (*ctts_count) + 1;
  2559. return *ctts_count;
  2560. }
  2561. static void mov_current_sample_inc(MOVStreamContext *sc)
  2562. {
  2563. sc->current_sample++;
  2564. sc->current_index++;
  2565. if (sc->index_ranges &&
  2566. sc->current_index >= sc->current_index_range->end &&
  2567. sc->current_index_range->end) {
  2568. sc->current_index_range++;
  2569. sc->current_index = sc->current_index_range->start;
  2570. }
  2571. }
  2572. static void mov_current_sample_dec(MOVStreamContext *sc)
  2573. {
  2574. sc->current_sample--;
  2575. sc->current_index--;
  2576. if (sc->index_ranges &&
  2577. sc->current_index < sc->current_index_range->start &&
  2578. sc->current_index_range > sc->index_ranges) {
  2579. sc->current_index_range--;
  2580. sc->current_index = sc->current_index_range->end - 1;
  2581. }
  2582. }
  2583. static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
  2584. {
  2585. int64_t range_size;
  2586. sc->current_sample = current_sample;
  2587. sc->current_index = current_sample;
  2588. if (!sc->index_ranges) {
  2589. return;
  2590. }
  2591. for (sc->current_index_range = sc->index_ranges;
  2592. sc->current_index_range->end;
  2593. sc->current_index_range++) {
  2594. range_size = sc->current_index_range->end - sc->current_index_range->start;
  2595. if (range_size > current_sample) {
  2596. sc->current_index = sc->current_index_range->start + current_sample;
  2597. break;
  2598. }
  2599. current_sample -= range_size;
  2600. }
  2601. }
  2602. /**
  2603. * Fix st->index_entries, so that it contains only the entries (and the entries
  2604. * which are needed to decode them) that fall in the edit list time ranges.
  2605. * Also fixes the timestamps of the index entries to match the timeline
  2606. * specified the edit lists.
  2607. */
  2608. static void mov_fix_index(MOVContext *mov, AVStream *st)
  2609. {
  2610. MOVStreamContext *msc = st->priv_data;
  2611. AVIndexEntry *e_old = st->index_entries;
  2612. int nb_old = st->nb_index_entries;
  2613. const AVIndexEntry *e_old_end = e_old + nb_old;
  2614. const AVIndexEntry *current = NULL;
  2615. MOVStts *ctts_data_old = msc->ctts_data;
  2616. int64_t ctts_index_old = 0;
  2617. int64_t ctts_sample_old = 0;
  2618. int64_t ctts_count_old = msc->ctts_count;
  2619. int64_t edit_list_media_time = 0;
  2620. int64_t edit_list_duration = 0;
  2621. int64_t frame_duration = 0;
  2622. int64_t edit_list_dts_counter = 0;
  2623. int64_t edit_list_dts_entry_end = 0;
  2624. int64_t edit_list_start_ctts_sample = 0;
  2625. int64_t curr_cts;
  2626. int64_t edit_list_index = 0;
  2627. int64_t index;
  2628. int64_t index_ctts_count;
  2629. int flags;
  2630. unsigned int ctts_allocated_size = 0;
  2631. int64_t start_dts = 0;
  2632. int64_t edit_list_media_time_dts = 0;
  2633. int64_t edit_list_start_encountered = 0;
  2634. int64_t search_timestamp = 0;
  2635. int64_t* frame_duration_buffer = NULL;
  2636. int num_discarded_begin = 0;
  2637. int first_non_zero_audio_edit = -1;
  2638. int packet_skip_samples = 0;
  2639. MOVIndexRange *current_index_range;
  2640. if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
  2641. return;
  2642. }
  2643. // allocate the index ranges array
  2644. msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
  2645. if (!msc->index_ranges) {
  2646. av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
  2647. return;
  2648. }
  2649. msc->current_index_range = msc->index_ranges;
  2650. current_index_range = msc->index_ranges - 1;
  2651. // Clean AVStream from traces of old index
  2652. st->index_entries = NULL;
  2653. st->index_entries_allocated_size = 0;
  2654. st->nb_index_entries = 0;
  2655. // Clean ctts fields of MOVStreamContext
  2656. msc->ctts_data = NULL;
  2657. msc->ctts_count = 0;
  2658. msc->ctts_index = 0;
  2659. msc->ctts_sample = 0;
  2660. // If the dts_shift is positive (in case of negative ctts values in mov),
  2661. // then negate the DTS by dts_shift
  2662. if (msc->dts_shift > 0)
  2663. edit_list_dts_entry_end -= msc->dts_shift;
  2664. // Offset the DTS by ctts[0] to make the PTS of the first frame 0
  2665. if (ctts_data_old && ctts_count_old > 0) {
  2666. edit_list_dts_entry_end -= ctts_data_old[0].duration;
  2667. av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by ctts[%d].duration: %d\n", 0, ctts_data_old[0].duration);
  2668. }
  2669. start_dts = edit_list_dts_entry_end;
  2670. while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
  2671. &edit_list_duration, mov->time_scale)) {
  2672. av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
  2673. st->index, edit_list_index, edit_list_media_time, edit_list_duration);
  2674. edit_list_index++;
  2675. edit_list_dts_counter = edit_list_dts_entry_end;
  2676. edit_list_dts_entry_end += edit_list_duration;
  2677. num_discarded_begin = 0;
  2678. if (edit_list_media_time == -1) {
  2679. continue;
  2680. }
  2681. // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
  2682. // according to the edit list below.
  2683. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2684. if (first_non_zero_audio_edit < 0) {
  2685. first_non_zero_audio_edit = 1;
  2686. } else {
  2687. first_non_zero_audio_edit = 0;
  2688. }
  2689. if (first_non_zero_audio_edit > 0)
  2690. st->skip_samples = msc->start_pad = 0;
  2691. }
  2692. //find closest previous key frame
  2693. edit_list_media_time_dts = edit_list_media_time;
  2694. if (msc->dts_shift > 0) {
  2695. edit_list_media_time_dts -= msc->dts_shift;
  2696. }
  2697. // While reordering frame index according to edit list we must handle properly
  2698. // the scenario when edit list entry starts from none key frame.
  2699. // We find closest previous key frame and preserve it and consequent frames in index.
  2700. // All frames which are outside edit list entry time boundaries will be dropped after decoding.
  2701. search_timestamp = edit_list_media_time_dts;
  2702. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2703. // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
  2704. // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
  2705. // edit_list_media_time to cover the decoder delay.
  2706. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
  2707. }
  2708. index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);
  2709. if (index == -1) {
  2710. av_log(mov->fc, AV_LOG_WARNING,
  2711. "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
  2712. st->index, edit_list_index, search_timestamp);
  2713. index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);
  2714. if (index == -1) {
  2715. av_log(mov->fc, AV_LOG_WARNING,
  2716. "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"
  2717. "Rounding edit list media time to zero.\n",
  2718. st->index, edit_list_index, search_timestamp);
  2719. index = 0;
  2720. edit_list_media_time = 0;
  2721. }
  2722. }
  2723. current = e_old + index;
  2724. ctts_index_old = 0;
  2725. ctts_sample_old = 0;
  2726. // set ctts_index properly for the found key frame
  2727. for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
  2728. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2729. ctts_sample_old++;
  2730. if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
  2731. ctts_index_old++;
  2732. ctts_sample_old = 0;
  2733. }
  2734. }
  2735. }
  2736. edit_list_start_ctts_sample = ctts_sample_old;
  2737. // Iterate over index and arrange it according to edit list
  2738. edit_list_start_encountered = 0;
  2739. for (; current < e_old_end; current++, index++) {
  2740. // check if frame outside edit list mark it for discard
  2741. frame_duration = (current + 1 < e_old_end) ?
  2742. ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
  2743. flags = current->flags;
  2744. // frames (pts) before or after edit list
  2745. curr_cts = current->timestamp + msc->dts_shift;
  2746. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2747. av_log(mov->fc, AV_LOG_DEBUG, "shifted frame pts, curr_cts: %"PRId64" @ %"PRId64", ctts: %d, ctts_count: %"PRId64"\n",
  2748. curr_cts, ctts_index_old, ctts_data_old[ctts_index_old].duration, ctts_count_old);
  2749. curr_cts += ctts_data_old[ctts_index_old].duration;
  2750. ctts_sample_old++;
  2751. if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
  2752. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2753. &ctts_allocated_size,
  2754. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2755. ctts_data_old[ctts_index_old].duration) == -1) {
  2756. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2757. ctts_index_old,
  2758. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2759. ctts_data_old[ctts_index_old].duration);
  2760. break;
  2761. }
  2762. ctts_index_old++;
  2763. ctts_sample_old = 0;
  2764. edit_list_start_ctts_sample = 0;
  2765. }
  2766. }
  2767. if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
  2768. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
  2769. curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
  2770. first_non_zero_audio_edit > 0) {
  2771. packet_skip_samples = edit_list_media_time - curr_cts;
  2772. st->skip_samples += packet_skip_samples;
  2773. // Shift the index entry timestamp by packet_skip_samples to be correct.
  2774. edit_list_dts_counter -= packet_skip_samples;
  2775. if (edit_list_start_encountered == 0) {
  2776. edit_list_start_encountered = 1;
  2777. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2778. // discarded packets.
  2779. if (frame_duration_buffer) {
  2780. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2781. frame_duration_buffer, num_discarded_begin);
  2782. av_freep(&frame_duration_buffer);
  2783. }
  2784. }
  2785. av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
  2786. } else {
  2787. flags |= AVINDEX_DISCARD_FRAME;
  2788. av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
  2789. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
  2790. num_discarded_begin++;
  2791. frame_duration_buffer = av_realloc(frame_duration_buffer,
  2792. num_discarded_begin * sizeof(int64_t));
  2793. if (!frame_duration_buffer) {
  2794. av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
  2795. break;
  2796. }
  2797. frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
  2798. // Increment skip_samples for the first non-zero audio edit list
  2799. if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
  2800. st->skip_samples += frame_duration;
  2801. msc->start_pad = st->skip_samples;
  2802. }
  2803. }
  2804. }
  2805. } else if (edit_list_start_encountered == 0) {
  2806. edit_list_start_encountered = 1;
  2807. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2808. // discarded packets.
  2809. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
  2810. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2811. frame_duration_buffer, num_discarded_begin);
  2812. av_freep(&frame_duration_buffer);
  2813. }
  2814. }
  2815. if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
  2816. current->min_distance, flags) == -1) {
  2817. av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
  2818. break;
  2819. }
  2820. // Update the index ranges array
  2821. if (current_index_range < msc->index_ranges || index != current_index_range->end) {
  2822. current_index_range++;
  2823. current_index_range->start = index;
  2824. }
  2825. current_index_range->end = index + 1;
  2826. // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
  2827. if (edit_list_start_encountered > 0) {
  2828. edit_list_dts_counter = edit_list_dts_counter + frame_duration;
  2829. }
  2830. // Break when found first key frame after edit entry completion
  2831. if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
  2832. ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
  2833. if (ctts_data_old && ctts_sample_old != 0) {
  2834. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2835. &ctts_allocated_size,
  2836. ctts_sample_old - edit_list_start_ctts_sample,
  2837. ctts_data_old[ctts_index_old].duration) == -1) {
  2838. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2839. ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
  2840. ctts_data_old[ctts_index_old].duration);
  2841. break;
  2842. }
  2843. }
  2844. break;
  2845. }
  2846. }
  2847. }
  2848. // Update av stream length
  2849. st->duration = edit_list_dts_entry_end - start_dts;
  2850. // Free the old index and the old CTTS structures
  2851. av_free(e_old);
  2852. av_free(ctts_data_old);
  2853. // Null terminate the index ranges array
  2854. current_index_range++;
  2855. current_index_range->start = 0;
  2856. current_index_range->end = 0;
  2857. msc->current_index = msc->index_ranges[0].start;
  2858. }
  2859. static void mov_build_index(MOVContext *mov, AVStream *st)
  2860. {
  2861. MOVStreamContext *sc = st->priv_data;
  2862. int64_t current_offset;
  2863. int64_t current_dts = 0;
  2864. unsigned int stts_index = 0;
  2865. unsigned int stsc_index = 0;
  2866. unsigned int stss_index = 0;
  2867. unsigned int stps_index = 0;
  2868. unsigned int i, j;
  2869. uint64_t stream_size = 0;
  2870. if (sc->elst_count) {
  2871. int i, edit_start_index = 0;
  2872. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2873. int64_t start_time = 0; // start time of the media
  2874. for (i = 0; i < sc->elst_count; i++) {
  2875. const MOVElst *e = &sc->elst_data[i];
  2876. if (i == 0 && e->time == -1) {
  2877. /* if empty, the first entry is the start time of the stream
  2878. * relative to the presentation itself */
  2879. empty_duration = e->duration;
  2880. edit_start_index = 1;
  2881. } else if (i == edit_start_index && e->time >= 0) {
  2882. start_time = e->time;
  2883. }
  2884. }
  2885. /* adjust first dts according to edit list */
  2886. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2887. if (empty_duration)
  2888. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2889. sc->time_offset = start_time - empty_duration;
  2890. }
  2891. }
  2892. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2893. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  2894. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2895. unsigned int current_sample = 0;
  2896. unsigned int stts_sample = 0;
  2897. unsigned int sample_size;
  2898. unsigned int distance = 0;
  2899. unsigned int rap_group_index = 0;
  2900. unsigned int rap_group_sample = 0;
  2901. int64_t last_dts = 0;
  2902. int64_t dts_correction = 0;
  2903. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2904. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2905. current_dts -= sc->dts_shift;
  2906. last_dts = current_dts;
  2907. if (!sc->sample_count || st->nb_index_entries)
  2908. return;
  2909. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2910. return;
  2911. if (av_reallocp_array(&st->index_entries,
  2912. st->nb_index_entries + sc->sample_count,
  2913. sizeof(*st->index_entries)) < 0) {
  2914. st->nb_index_entries = 0;
  2915. return;
  2916. }
  2917. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2918. for (i = 0; i < sc->chunk_count; i++) {
  2919. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2920. current_offset = sc->chunk_offsets[i];
  2921. while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  2922. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2923. stsc_index++;
  2924. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2925. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2926. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2927. sc->stsz_sample_size = sc->sample_size;
  2928. }
  2929. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2930. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2931. sc->stsz_sample_size = sc->sample_size;
  2932. }
  2933. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2934. int keyframe = 0;
  2935. if (current_sample >= sc->sample_count) {
  2936. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2937. return;
  2938. }
  2939. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2940. keyframe = 1;
  2941. if (stss_index + 1 < sc->keyframe_count)
  2942. stss_index++;
  2943. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2944. keyframe = 1;
  2945. if (stps_index + 1 < sc->stps_count)
  2946. stps_index++;
  2947. }
  2948. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2949. if (sc->rap_group[rap_group_index].index > 0)
  2950. keyframe = 1;
  2951. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2952. rap_group_sample = 0;
  2953. rap_group_index++;
  2954. }
  2955. }
  2956. if (sc->keyframe_absent
  2957. && !sc->stps_count
  2958. && !rap_group_present
  2959. && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2960. keyframe = 1;
  2961. if (keyframe)
  2962. distance = 0;
  2963. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2964. if (sc->pseudo_stream_id == -1 ||
  2965. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2966. AVIndexEntry *e;
  2967. if (sample_size > 0x3FFFFFFF) {
  2968. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  2969. return;
  2970. }
  2971. e = &st->index_entries[st->nb_index_entries++];
  2972. e->pos = current_offset;
  2973. e->timestamp = current_dts;
  2974. e->size = sample_size;
  2975. e->min_distance = distance;
  2976. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2977. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2978. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2979. current_offset, current_dts, sample_size, distance, keyframe);
  2980. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2981. ff_rfps_add_frame(mov->fc, st, current_dts);
  2982. }
  2983. current_offset += sample_size;
  2984. stream_size += sample_size;
  2985. /* A negative sample duration is invalid based on the spec,
  2986. * but some samples need it to correct the DTS. */
  2987. if (sc->stts_data[stts_index].duration < 0) {
  2988. av_log(mov->fc, AV_LOG_WARNING,
  2989. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2990. sc->stts_data[stts_index].duration, stts_index,
  2991. st->index);
  2992. dts_correction += sc->stts_data[stts_index].duration - 1;
  2993. sc->stts_data[stts_index].duration = 1;
  2994. }
  2995. current_dts += sc->stts_data[stts_index].duration;
  2996. if (!dts_correction || current_dts + dts_correction > last_dts) {
  2997. current_dts += dts_correction;
  2998. dts_correction = 0;
  2999. } else {
  3000. /* Avoid creating non-monotonous DTS */
  3001. dts_correction += current_dts - last_dts - 1;
  3002. current_dts = last_dts + 1;
  3003. }
  3004. last_dts = current_dts;
  3005. distance++;
  3006. stts_sample++;
  3007. current_sample++;
  3008. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  3009. stts_sample = 0;
  3010. stts_index++;
  3011. }
  3012. }
  3013. }
  3014. if (st->duration > 0)
  3015. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  3016. } else {
  3017. unsigned chunk_samples, total = 0;
  3018. // compute total chunk count
  3019. for (i = 0; i < sc->stsc_count; i++) {
  3020. unsigned count, chunk_count;
  3021. chunk_samples = sc->stsc_data[i].count;
  3022. if (i != sc->stsc_count - 1 &&
  3023. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  3024. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  3025. return;
  3026. }
  3027. if (sc->samples_per_frame >= 160) { // gsm
  3028. count = chunk_samples / sc->samples_per_frame;
  3029. } else if (sc->samples_per_frame > 1) {
  3030. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  3031. count = (chunk_samples+samples-1) / samples;
  3032. } else {
  3033. count = (chunk_samples+1023) / 1024;
  3034. }
  3035. if (mov_stsc_index_valid(i, sc->stsc_count))
  3036. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  3037. else
  3038. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  3039. total += chunk_count * count;
  3040. }
  3041. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  3042. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  3043. return;
  3044. if (av_reallocp_array(&st->index_entries,
  3045. st->nb_index_entries + total,
  3046. sizeof(*st->index_entries)) < 0) {
  3047. st->nb_index_entries = 0;
  3048. return;
  3049. }
  3050. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  3051. // populate index
  3052. for (i = 0; i < sc->chunk_count; i++) {
  3053. current_offset = sc->chunk_offsets[i];
  3054. if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  3055. i + 1 == sc->stsc_data[stsc_index + 1].first)
  3056. stsc_index++;
  3057. chunk_samples = sc->stsc_data[stsc_index].count;
  3058. while (chunk_samples > 0) {
  3059. AVIndexEntry *e;
  3060. unsigned size, samples;
  3061. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  3062. avpriv_request_sample(mov->fc,
  3063. "Zero bytes per frame, but %d samples per frame",
  3064. sc->samples_per_frame);
  3065. return;
  3066. }
  3067. if (sc->samples_per_frame >= 160) { // gsm
  3068. samples = sc->samples_per_frame;
  3069. size = sc->bytes_per_frame;
  3070. } else {
  3071. if (sc->samples_per_frame > 1) {
  3072. samples = FFMIN((1024 / sc->samples_per_frame)*
  3073. sc->samples_per_frame, chunk_samples);
  3074. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  3075. } else {
  3076. samples = FFMIN(1024, chunk_samples);
  3077. size = samples * sc->sample_size;
  3078. }
  3079. }
  3080. if (st->nb_index_entries >= total) {
  3081. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  3082. return;
  3083. }
  3084. if (size > 0x3FFFFFFF) {
  3085. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  3086. return;
  3087. }
  3088. e = &st->index_entries[st->nb_index_entries++];
  3089. e->pos = current_offset;
  3090. e->timestamp = current_dts;
  3091. e->size = size;
  3092. e->min_distance = 0;
  3093. e->flags = AVINDEX_KEYFRAME;
  3094. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  3095. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  3096. size, samples);
  3097. current_offset += size;
  3098. current_dts += samples;
  3099. chunk_samples -= samples;
  3100. }
  3101. }
  3102. }
  3103. // Fix index according to edit lists.
  3104. mov_fix_index(mov, st);
  3105. }
  3106. static int test_same_origin(const char *src, const char *ref) {
  3107. char src_proto[64];
  3108. char ref_proto[64];
  3109. char src_auth[256];
  3110. char ref_auth[256];
  3111. char src_host[256];
  3112. char ref_host[256];
  3113. int src_port=-1;
  3114. int ref_port=-1;
  3115. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  3116. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  3117. if (strlen(src) == 0) {
  3118. return -1;
  3119. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  3120. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  3121. strlen(src_host) + 1 >= sizeof(src_host) ||
  3122. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  3123. return 0;
  3124. } else if (strcmp(src_proto, ref_proto) ||
  3125. strcmp(src_auth, ref_auth) ||
  3126. strcmp(src_host, ref_host) ||
  3127. src_port != ref_port) {
  3128. return 0;
  3129. } else
  3130. return 1;
  3131. }
  3132. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  3133. {
  3134. /* try relative path, we do not try the absolute because it can leak information about our
  3135. system to an attacker */
  3136. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  3137. char filename[1025];
  3138. const char *src_path;
  3139. int i, l;
  3140. /* find a source dir */
  3141. src_path = strrchr(src, '/');
  3142. if (src_path)
  3143. src_path++;
  3144. else
  3145. src_path = src;
  3146. /* find a next level down to target */
  3147. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  3148. if (ref->path[l] == '/') {
  3149. if (i == ref->nlvl_to - 1)
  3150. break;
  3151. else
  3152. i++;
  3153. }
  3154. /* compose filename if next level down to target was found */
  3155. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  3156. memcpy(filename, src, src_path - src);
  3157. filename[src_path - src] = 0;
  3158. for (i = 1; i < ref->nlvl_from; i++)
  3159. av_strlcat(filename, "../", sizeof(filename));
  3160. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  3161. if (!c->use_absolute_path) {
  3162. int same_origin = test_same_origin(src, filename);
  3163. if (!same_origin) {
  3164. av_log(c->fc, AV_LOG_ERROR,
  3165. "Reference with mismatching origin, %s not tried for security reasons, "
  3166. "set demuxer option use_absolute_path to allow it anyway\n",
  3167. ref->path);
  3168. return AVERROR(ENOENT);
  3169. }
  3170. if(strstr(ref->path + l + 1, "..") ||
  3171. strstr(ref->path + l + 1, ":") ||
  3172. (ref->nlvl_from > 1 && same_origin < 0) ||
  3173. (filename[0] == '/' && src_path == src))
  3174. return AVERROR(ENOENT);
  3175. }
  3176. if (strlen(filename) + 1 == sizeof(filename))
  3177. return AVERROR(ENOENT);
  3178. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  3179. return 0;
  3180. }
  3181. } else if (c->use_absolute_path) {
  3182. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  3183. "this is a possible security issue\n");
  3184. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  3185. return 0;
  3186. } else {
  3187. av_log(c->fc, AV_LOG_ERROR,
  3188. "Absolute path %s not tried for security reasons, "
  3189. "set demuxer option use_absolute_path to allow absolute paths\n",
  3190. ref->path);
  3191. }
  3192. return AVERROR(ENOENT);
  3193. }
  3194. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  3195. {
  3196. if (sc->time_scale <= 0) {
  3197. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  3198. sc->time_scale = c->time_scale;
  3199. if (sc->time_scale <= 0)
  3200. sc->time_scale = 1;
  3201. }
  3202. }
  3203. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3204. {
  3205. AVStream *st;
  3206. MOVStreamContext *sc;
  3207. int ret;
  3208. st = avformat_new_stream(c->fc, NULL);
  3209. if (!st) return AVERROR(ENOMEM);
  3210. st->id = c->fc->nb_streams;
  3211. sc = av_mallocz(sizeof(MOVStreamContext));
  3212. if (!sc) return AVERROR(ENOMEM);
  3213. st->priv_data = sc;
  3214. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  3215. sc->ffindex = st->index;
  3216. c->trak_index = st->index;
  3217. if ((ret = mov_read_default(c, pb, atom)) < 0)
  3218. return ret;
  3219. c->trak_index = -1;
  3220. /* sanity checks */
  3221. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  3222. (!sc->sample_size && !sc->sample_count))) {
  3223. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  3224. st->index);
  3225. return 0;
  3226. }
  3227. fix_timescale(c, sc);
  3228. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  3229. mov_build_index(c, st);
  3230. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  3231. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  3232. if (c->enable_drefs) {
  3233. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  3234. av_log(c->fc, AV_LOG_ERROR,
  3235. "stream %d, error opening alias: path='%s', dir='%s', "
  3236. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  3237. st->index, dref->path, dref->dir, dref->filename,
  3238. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3239. } else {
  3240. av_log(c->fc, AV_LOG_WARNING,
  3241. "Skipped opening external track: "
  3242. "stream %d, alias: path='%s', dir='%s', "
  3243. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  3244. "Set enable_drefs to allow this.\n",
  3245. st->index, dref->path, dref->dir, dref->filename,
  3246. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3247. }
  3248. } else {
  3249. sc->pb = c->fc->pb;
  3250. sc->pb_is_copied = 1;
  3251. }
  3252. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3253. if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
  3254. sc->height && sc->width &&
  3255. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  3256. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  3257. ((double)st->codecpar->width * sc->height), INT_MAX);
  3258. }
  3259. #if FF_API_R_FRAME_RATE
  3260. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  3261. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  3262. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  3263. #endif
  3264. }
  3265. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  3266. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  3267. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  3268. ret = ff_generate_avci_extradata(st);
  3269. if (ret < 0)
  3270. return ret;
  3271. }
  3272. switch (st->codecpar->codec_id) {
  3273. #if CONFIG_H261_DECODER
  3274. case AV_CODEC_ID_H261:
  3275. #endif
  3276. #if CONFIG_H263_DECODER
  3277. case AV_CODEC_ID_H263:
  3278. #endif
  3279. #if CONFIG_MPEG4_DECODER
  3280. case AV_CODEC_ID_MPEG4:
  3281. #endif
  3282. st->codecpar->width = 0; /* let decoder init width/height */
  3283. st->codecpar->height= 0;
  3284. break;
  3285. }
  3286. // If the duration of the mp3 packets is not constant, then they could need a parser
  3287. if (st->codecpar->codec_id == AV_CODEC_ID_MP3
  3288. && sc->stts_count > 3
  3289. && sc->stts_count*10 > st->nb_frames
  3290. && sc->time_scale == st->codecpar->sample_rate) {
  3291. st->need_parsing = AVSTREAM_PARSE_FULL;
  3292. }
  3293. /* Do not need those anymore. */
  3294. av_freep(&sc->chunk_offsets);
  3295. av_freep(&sc->sample_sizes);
  3296. av_freep(&sc->keyframes);
  3297. av_freep(&sc->stts_data);
  3298. av_freep(&sc->stps_data);
  3299. av_freep(&sc->elst_data);
  3300. av_freep(&sc->rap_group);
  3301. return 0;
  3302. }
  3303. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3304. {
  3305. int ret;
  3306. c->itunes_metadata = 1;
  3307. ret = mov_read_default(c, pb, atom);
  3308. c->itunes_metadata = 0;
  3309. return ret;
  3310. }
  3311. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3312. {
  3313. uint32_t count;
  3314. uint32_t i;
  3315. if (atom.size < 8)
  3316. return 0;
  3317. avio_skip(pb, 4);
  3318. count = avio_rb32(pb);
  3319. if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
  3320. av_log(c->fc, AV_LOG_ERROR,
  3321. "The 'keys' atom with the invalid key count: %d\n", count);
  3322. return AVERROR_INVALIDDATA;
  3323. }
  3324. c->meta_keys_count = count + 1;
  3325. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  3326. if (!c->meta_keys)
  3327. return AVERROR(ENOMEM);
  3328. for (i = 1; i <= count; ++i) {
  3329. uint32_t key_size = avio_rb32(pb);
  3330. uint32_t type = avio_rl32(pb);
  3331. if (key_size < 8) {
  3332. av_log(c->fc, AV_LOG_ERROR,
  3333. "The key# %d in meta has invalid size: %d\n", i, key_size);
  3334. return AVERROR_INVALIDDATA;
  3335. }
  3336. key_size -= 8;
  3337. if (type != MKTAG('m','d','t','a')) {
  3338. avio_skip(pb, key_size);
  3339. }
  3340. c->meta_keys[i] = av_mallocz(key_size + 1);
  3341. if (!c->meta_keys[i])
  3342. return AVERROR(ENOMEM);
  3343. avio_read(pb, c->meta_keys[i], key_size);
  3344. }
  3345. return 0;
  3346. }
  3347. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3348. {
  3349. int64_t end = avio_tell(pb) + atom.size;
  3350. uint8_t *key = NULL, *val = NULL, *mean = NULL;
  3351. int i;
  3352. int ret = 0;
  3353. AVStream *st;
  3354. MOVStreamContext *sc;
  3355. if (c->fc->nb_streams < 1)
  3356. return 0;
  3357. st = c->fc->streams[c->fc->nb_streams-1];
  3358. sc = st->priv_data;
  3359. for (i = 0; i < 3; i++) {
  3360. uint8_t **p;
  3361. uint32_t len, tag;
  3362. if (end - avio_tell(pb) <= 12)
  3363. break;
  3364. len = avio_rb32(pb);
  3365. tag = avio_rl32(pb);
  3366. avio_skip(pb, 4); // flags
  3367. if (len < 12 || len - 12 > end - avio_tell(pb))
  3368. break;
  3369. len -= 12;
  3370. if (tag == MKTAG('m', 'e', 'a', 'n'))
  3371. p = &mean;
  3372. else if (tag == MKTAG('n', 'a', 'm', 'e'))
  3373. p = &key;
  3374. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  3375. avio_skip(pb, 4);
  3376. len -= 4;
  3377. p = &val;
  3378. } else
  3379. break;
  3380. *p = av_malloc(len + 1);
  3381. if (!*p)
  3382. break;
  3383. ret = ffio_read_size(pb, *p, len);
  3384. if (ret < 0) {
  3385. av_freep(p);
  3386. break;
  3387. }
  3388. (*p)[len] = 0;
  3389. }
  3390. if (mean && key && val) {
  3391. if (strcmp(key, "iTunSMPB") == 0) {
  3392. int priming, remainder, samples;
  3393. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  3394. if(priming>0 && priming<16384)
  3395. sc->start_pad = priming;
  3396. }
  3397. }
  3398. if (strcmp(key, "cdec") != 0) {
  3399. av_dict_set(&c->fc->metadata, key, val,
  3400. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  3401. key = val = NULL;
  3402. }
  3403. } else {
  3404. av_log(c->fc, AV_LOG_VERBOSE,
  3405. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  3406. }
  3407. avio_seek(pb, end, SEEK_SET);
  3408. av_freep(&key);
  3409. av_freep(&val);
  3410. av_freep(&mean);
  3411. return ret;
  3412. }
  3413. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3414. {
  3415. while (atom.size > 8) {
  3416. uint32_t tag = avio_rl32(pb);
  3417. atom.size -= 4;
  3418. if (tag == MKTAG('h','d','l','r')) {
  3419. avio_seek(pb, -8, SEEK_CUR);
  3420. atom.size += 8;
  3421. return mov_read_default(c, pb, atom);
  3422. }
  3423. }
  3424. return 0;
  3425. }
  3426. // return 1 when matrix is identity, 0 otherwise
  3427. #define IS_MATRIX_IDENT(matrix) \
  3428. ( (matrix)[0][0] == (1 << 16) && \
  3429. (matrix)[1][1] == (1 << 16) && \
  3430. (matrix)[2][2] == (1 << 30) && \
  3431. !(matrix)[0][1] && !(matrix)[0][2] && \
  3432. !(matrix)[1][0] && !(matrix)[1][2] && \
  3433. !(matrix)[2][0] && !(matrix)[2][1])
  3434. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3435. {
  3436. int i, j, e;
  3437. int width;
  3438. int height;
  3439. int display_matrix[3][3];
  3440. int res_display_matrix[3][3] = { { 0 } };
  3441. AVStream *st;
  3442. MOVStreamContext *sc;
  3443. int version;
  3444. int flags;
  3445. if (c->fc->nb_streams < 1)
  3446. return 0;
  3447. st = c->fc->streams[c->fc->nb_streams-1];
  3448. sc = st->priv_data;
  3449. version = avio_r8(pb);
  3450. flags = avio_rb24(pb);
  3451. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  3452. if (version == 1) {
  3453. avio_rb64(pb);
  3454. avio_rb64(pb);
  3455. } else {
  3456. avio_rb32(pb); /* creation time */
  3457. avio_rb32(pb); /* modification time */
  3458. }
  3459. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  3460. avio_rb32(pb); /* reserved */
  3461. /* highlevel (considering edits) duration in movie timebase */
  3462. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  3463. avio_rb32(pb); /* reserved */
  3464. avio_rb32(pb); /* reserved */
  3465. avio_rb16(pb); /* layer */
  3466. avio_rb16(pb); /* alternate group */
  3467. avio_rb16(pb); /* volume */
  3468. avio_rb16(pb); /* reserved */
  3469. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  3470. // they're kept in fixed point format through all calculations
  3471. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  3472. // side data, but the scale factor is not needed to calculate aspect ratio
  3473. for (i = 0; i < 3; i++) {
  3474. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  3475. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  3476. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  3477. }
  3478. width = avio_rb32(pb); // 16.16 fixed point track width
  3479. height = avio_rb32(pb); // 16.16 fixed point track height
  3480. sc->width = width >> 16;
  3481. sc->height = height >> 16;
  3482. // apply the moov display matrix (after the tkhd one)
  3483. for (i = 0; i < 3; i++) {
  3484. const int sh[3] = { 16, 16, 30 };
  3485. for (j = 0; j < 3; j++) {
  3486. for (e = 0; e < 3; e++) {
  3487. res_display_matrix[i][j] +=
  3488. ((int64_t) display_matrix[i][e] *
  3489. c->movie_display_matrix[e][j]) >> sh[e];
  3490. }
  3491. }
  3492. }
  3493. // save the matrix when it is not the default identity
  3494. if (!IS_MATRIX_IDENT(res_display_matrix)) {
  3495. double rotate;
  3496. av_freep(&sc->display_matrix);
  3497. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  3498. if (!sc->display_matrix)
  3499. return AVERROR(ENOMEM);
  3500. for (i = 0; i < 3; i++)
  3501. for (j = 0; j < 3; j++)
  3502. sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
  3503. rotate = av_display_rotation_get(sc->display_matrix);
  3504. if (!isnan(rotate)) {
  3505. char rotate_buf[64];
  3506. rotate = -rotate;
  3507. if (rotate < 0) // for backward compatibility
  3508. rotate += 360;
  3509. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  3510. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  3511. }
  3512. }
  3513. // transform the display width/height according to the matrix
  3514. // to keep the same scale, use [width height 1<<16]
  3515. if (width && height && sc->display_matrix) {
  3516. double disp_transform[2];
  3517. for (i = 0; i < 2; i++)
  3518. disp_transform[i] = hypot(sc->display_matrix[0 + i],
  3519. sc->display_matrix[3 + i]);
  3520. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  3521. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3522. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3523. st->sample_aspect_ratio = av_d2q(
  3524. disp_transform[0] / disp_transform[1],
  3525. INT_MAX);
  3526. }
  3527. return 0;
  3528. }
  3529. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3530. {
  3531. MOVFragment *frag = &c->fragment;
  3532. MOVTrackExt *trex = NULL;
  3533. MOVFragmentIndex* index = NULL;
  3534. int flags, track_id, i, found = 0;
  3535. avio_r8(pb); /* version */
  3536. flags = avio_rb24(pb);
  3537. track_id = avio_rb32(pb);
  3538. if (!track_id)
  3539. return AVERROR_INVALIDDATA;
  3540. frag->track_id = track_id;
  3541. for (i = 0; i < c->trex_count; i++)
  3542. if (c->trex_data[i].track_id == frag->track_id) {
  3543. trex = &c->trex_data[i];
  3544. break;
  3545. }
  3546. if (!trex) {
  3547. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3548. return AVERROR_INVALIDDATA;
  3549. }
  3550. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3551. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3552. frag->moof_offset : frag->implicit_offset;
  3553. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3554. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3555. avio_rb32(pb) : trex->duration;
  3556. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  3557. avio_rb32(pb) : trex->size;
  3558. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3559. avio_rb32(pb) : trex->flags;
  3560. frag->time = AV_NOPTS_VALUE;
  3561. for (i = 0; i < c->fragment_index_count; i++) {
  3562. int j;
  3563. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3564. if (candidate->track_id == frag->track_id) {
  3565. av_log(c->fc, AV_LOG_DEBUG,
  3566. "found fragment index for track %u\n", frag->track_id);
  3567. index = candidate;
  3568. for (j = index->current_item; j < index->item_count; j++) {
  3569. if (frag->implicit_offset == index->items[j].moof_offset) {
  3570. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3571. "for track %u and moof_offset %"PRId64"\n",
  3572. frag->track_id, index->items[j].moof_offset);
  3573. frag->time = index->items[j].time;
  3574. index->current_item = j + 1;
  3575. found = 1;
  3576. break;
  3577. }
  3578. }
  3579. if (found)
  3580. break;
  3581. }
  3582. }
  3583. if (index && !found) {
  3584. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3585. "it doesn't have an (in-order) entry for moof_offset "
  3586. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3587. }
  3588. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3589. return 0;
  3590. }
  3591. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3592. {
  3593. unsigned i, num;
  3594. void *new_tracks;
  3595. num = atom.size / 4;
  3596. if (!(new_tracks = av_malloc_array(num, sizeof(int))))
  3597. return AVERROR(ENOMEM);
  3598. av_free(c->chapter_tracks);
  3599. c->chapter_tracks = new_tracks;
  3600. c->nb_chapter_tracks = num;
  3601. for (i = 0; i < num && !pb->eof_reached; i++)
  3602. c->chapter_tracks[i] = avio_rb32(pb);
  3603. return 0;
  3604. }
  3605. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3606. {
  3607. MOVTrackExt *trex;
  3608. int err;
  3609. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3610. return AVERROR_INVALIDDATA;
  3611. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3612. sizeof(*c->trex_data))) < 0) {
  3613. c->trex_count = 0;
  3614. return err;
  3615. }
  3616. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3617. trex = &c->trex_data[c->trex_count++];
  3618. avio_r8(pb); /* version */
  3619. avio_rb24(pb); /* flags */
  3620. trex->track_id = avio_rb32(pb);
  3621. trex->stsd_id = avio_rb32(pb);
  3622. trex->duration = avio_rb32(pb);
  3623. trex->size = avio_rb32(pb);
  3624. trex->flags = avio_rb32(pb);
  3625. return 0;
  3626. }
  3627. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3628. {
  3629. MOVFragment *frag = &c->fragment;
  3630. AVStream *st = NULL;
  3631. MOVStreamContext *sc;
  3632. int version, i;
  3633. for (i = 0; i < c->fc->nb_streams; i++) {
  3634. if (c->fc->streams[i]->id == frag->track_id) {
  3635. st = c->fc->streams[i];
  3636. break;
  3637. }
  3638. }
  3639. if (!st) {
  3640. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3641. return AVERROR_INVALIDDATA;
  3642. }
  3643. sc = st->priv_data;
  3644. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3645. return 0;
  3646. version = avio_r8(pb);
  3647. avio_rb24(pb); /* flags */
  3648. if (version) {
  3649. sc->track_end = avio_rb64(pb);
  3650. } else {
  3651. sc->track_end = avio_rb32(pb);
  3652. }
  3653. return 0;
  3654. }
  3655. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3656. {
  3657. MOVFragment *frag = &c->fragment;
  3658. AVStream *st = NULL;
  3659. MOVStreamContext *sc;
  3660. MOVStts *ctts_data;
  3661. uint64_t offset;
  3662. int64_t dts;
  3663. int data_offset = 0;
  3664. unsigned entries, first_sample_flags = frag->flags;
  3665. int flags, distance, i, err;
  3666. for (i = 0; i < c->fc->nb_streams; i++) {
  3667. if (c->fc->streams[i]->id == frag->track_id) {
  3668. st = c->fc->streams[i];
  3669. break;
  3670. }
  3671. }
  3672. if (!st) {
  3673. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3674. return AVERROR_INVALIDDATA;
  3675. }
  3676. sc = st->priv_data;
  3677. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3678. return 0;
  3679. avio_r8(pb); /* version */
  3680. flags = avio_rb24(pb);
  3681. entries = avio_rb32(pb);
  3682. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3683. /* Always assume the presence of composition time offsets.
  3684. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3685. * 1) in the initial movie, there are no samples.
  3686. * 2) in the first movie fragment, there is only one sample without composition time offset.
  3687. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  3688. if (!sc->ctts_count && sc->sample_count)
  3689. {
  3690. /* Complement ctts table if moov atom doesn't have ctts atom. */
  3691. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3692. if (!ctts_data)
  3693. return AVERROR(ENOMEM);
  3694. sc->ctts_data = ctts_data;
  3695. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3696. sc->ctts_data[sc->ctts_count].duration = 0;
  3697. sc->ctts_count++;
  3698. }
  3699. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3700. return AVERROR_INVALIDDATA;
  3701. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3702. sizeof(*sc->ctts_data))) < 0) {
  3703. sc->ctts_count = 0;
  3704. return err;
  3705. }
  3706. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3707. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3708. dts = sc->track_end - sc->time_offset;
  3709. offset = frag->base_data_offset + data_offset;
  3710. distance = 0;
  3711. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3712. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3713. unsigned sample_size = frag->size;
  3714. int sample_flags = i ? frag->flags : first_sample_flags;
  3715. unsigned sample_duration = frag->duration;
  3716. int keyframe = 0;
  3717. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3718. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3719. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3720. sc->ctts_data[sc->ctts_count].count = 1;
  3721. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3722. avio_rb32(pb) : 0;
  3723. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3724. if (frag->time != AV_NOPTS_VALUE) {
  3725. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3726. int64_t pts = frag->time;
  3727. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3728. " sc->dts_shift %d ctts.duration %d"
  3729. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3730. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3731. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3732. dts = pts - sc->dts_shift;
  3733. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3734. dts -= sc->ctts_data[sc->ctts_count].duration;
  3735. } else {
  3736. dts -= sc->time_offset;
  3737. }
  3738. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3739. } else {
  3740. dts = frag->time - sc->time_offset;
  3741. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3742. ", using it for dts\n", dts);
  3743. }
  3744. frag->time = AV_NOPTS_VALUE;
  3745. }
  3746. sc->ctts_count++;
  3747. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  3748. keyframe = 1;
  3749. else
  3750. keyframe =
  3751. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3752. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3753. if (keyframe)
  3754. distance = 0;
  3755. err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3756. keyframe ? AVINDEX_KEYFRAME : 0);
  3757. if (err < 0) {
  3758. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3759. }
  3760. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3761. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3762. offset, dts, sample_size, distance, keyframe);
  3763. distance++;
  3764. dts += sample_duration;
  3765. offset += sample_size;
  3766. sc->data_size += sample_size;
  3767. sc->duration_for_fps += sample_duration;
  3768. sc->nb_frames_for_fps ++;
  3769. }
  3770. if (pb->eof_reached)
  3771. return AVERROR_EOF;
  3772. frag->implicit_offset = offset;
  3773. sc->track_end = dts + sc->time_offset;
  3774. if (st->duration < sc->track_end)
  3775. st->duration = sc->track_end;
  3776. return 0;
  3777. }
  3778. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3779. {
  3780. int64_t offset = avio_tell(pb) + atom.size, pts;
  3781. uint8_t version;
  3782. unsigned i, track_id;
  3783. AVStream *st = NULL;
  3784. AVStream *ref_st;
  3785. MOVStreamContext *sc, *ref_sc;
  3786. MOVFragmentIndex *index = NULL;
  3787. MOVFragmentIndex **tmp;
  3788. AVRational timescale;
  3789. version = avio_r8(pb);
  3790. if (version > 1) {
  3791. avpriv_request_sample(c->fc, "sidx version %u", version);
  3792. return 0;
  3793. }
  3794. avio_rb24(pb); // flags
  3795. track_id = avio_rb32(pb); // Reference ID
  3796. for (i = 0; i < c->fc->nb_streams; i++) {
  3797. if (c->fc->streams[i]->id == track_id) {
  3798. st = c->fc->streams[i];
  3799. break;
  3800. }
  3801. }
  3802. if (!st) {
  3803. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  3804. return 0;
  3805. }
  3806. sc = st->priv_data;
  3807. timescale = av_make_q(1, avio_rb32(pb));
  3808. if (timescale.den <= 0) {
  3809. av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
  3810. return AVERROR_INVALIDDATA;
  3811. }
  3812. if (version == 0) {
  3813. pts = avio_rb32(pb);
  3814. offset += avio_rb32(pb);
  3815. } else {
  3816. pts = avio_rb64(pb);
  3817. offset += avio_rb64(pb);
  3818. }
  3819. avio_rb16(pb); // reserved
  3820. index = av_mallocz(sizeof(MOVFragmentIndex));
  3821. if (!index)
  3822. return AVERROR(ENOMEM);
  3823. index->track_id = track_id;
  3824. index->item_count = avio_rb16(pb);
  3825. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3826. if (!index->items) {
  3827. av_freep(&index);
  3828. return AVERROR(ENOMEM);
  3829. }
  3830. for (i = 0; i < index->item_count; i++) {
  3831. uint32_t size = avio_rb32(pb);
  3832. uint32_t duration = avio_rb32(pb);
  3833. if (size & 0x80000000) {
  3834. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3835. av_freep(&index->items);
  3836. av_freep(&index);
  3837. return AVERROR_PATCHWELCOME;
  3838. }
  3839. avio_rb32(pb); // sap_flags
  3840. index->items[i].moof_offset = offset;
  3841. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3842. offset += size;
  3843. pts += duration;
  3844. }
  3845. st->duration = sc->track_end = pts;
  3846. tmp = av_realloc_array(c->fragment_index_data,
  3847. c->fragment_index_count + 1,
  3848. sizeof(MOVFragmentIndex*));
  3849. if (!tmp) {
  3850. av_freep(&index->items);
  3851. av_freep(&index);
  3852. return AVERROR(ENOMEM);
  3853. }
  3854. c->fragment_index_data = tmp;
  3855. c->fragment_index_data[c->fragment_index_count++] = index;
  3856. sc->has_sidx = 1;
  3857. if (offset == avio_size(pb)) {
  3858. for (i = 0; i < c->fc->nb_streams; i++) {
  3859. if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) {
  3860. ref_st = c->fc->streams[i];
  3861. ref_sc = ref_st->priv_data;
  3862. break;
  3863. }
  3864. }
  3865. for (i = 0; i < c->fc->nb_streams; i++) {
  3866. st = c->fc->streams[i];
  3867. sc = st->priv_data;
  3868. if (!sc->has_sidx) {
  3869. st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
  3870. }
  3871. }
  3872. c->fragment_index_complete = 1;
  3873. }
  3874. return 0;
  3875. }
  3876. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3877. /* like the files created with Adobe Premiere 5.0, for samples see */
  3878. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3879. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3880. {
  3881. int err;
  3882. if (atom.size < 8)
  3883. return 0; /* continue */
  3884. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3885. avio_skip(pb, atom.size - 4);
  3886. return 0;
  3887. }
  3888. atom.type = avio_rl32(pb);
  3889. atom.size -= 8;
  3890. if (atom.type != MKTAG('m','d','a','t')) {
  3891. avio_skip(pb, atom.size);
  3892. return 0;
  3893. }
  3894. err = mov_read_mdat(c, pb, atom);
  3895. return err;
  3896. }
  3897. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3898. {
  3899. #if CONFIG_ZLIB
  3900. AVIOContext ctx;
  3901. uint8_t *cmov_data;
  3902. uint8_t *moov_data; /* uncompressed data */
  3903. long cmov_len, moov_len;
  3904. int ret = -1;
  3905. avio_rb32(pb); /* dcom atom */
  3906. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3907. return AVERROR_INVALIDDATA;
  3908. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3909. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3910. return AVERROR_INVALIDDATA;
  3911. }
  3912. avio_rb32(pb); /* cmvd atom */
  3913. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3914. return AVERROR_INVALIDDATA;
  3915. moov_len = avio_rb32(pb); /* uncompressed size */
  3916. cmov_len = atom.size - 6 * 4;
  3917. cmov_data = av_malloc(cmov_len);
  3918. if (!cmov_data)
  3919. return AVERROR(ENOMEM);
  3920. moov_data = av_malloc(moov_len);
  3921. if (!moov_data) {
  3922. av_free(cmov_data);
  3923. return AVERROR(ENOMEM);
  3924. }
  3925. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3926. if (ret < 0)
  3927. goto free_and_return;
  3928. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3929. goto free_and_return;
  3930. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3931. goto free_and_return;
  3932. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3933. atom.type = MKTAG('m','o','o','v');
  3934. atom.size = moov_len;
  3935. ret = mov_read_default(c, &ctx, atom);
  3936. free_and_return:
  3937. av_free(moov_data);
  3938. av_free(cmov_data);
  3939. return ret;
  3940. #else
  3941. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3942. return AVERROR(ENOSYS);
  3943. #endif
  3944. }
  3945. /* edit list atom */
  3946. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3947. {
  3948. MOVStreamContext *sc;
  3949. int i, edit_count, version;
  3950. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3951. return 0;
  3952. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3953. version = avio_r8(pb); /* version */
  3954. avio_rb24(pb); /* flags */
  3955. edit_count = avio_rb32(pb); /* entries */
  3956. if (!edit_count)
  3957. return 0;
  3958. if (sc->elst_data)
  3959. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3960. av_free(sc->elst_data);
  3961. sc->elst_count = 0;
  3962. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3963. if (!sc->elst_data)
  3964. return AVERROR(ENOMEM);
  3965. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3966. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3967. MOVElst *e = &sc->elst_data[i];
  3968. if (version == 1) {
  3969. e->duration = avio_rb64(pb);
  3970. e->time = avio_rb64(pb);
  3971. } else {
  3972. e->duration = avio_rb32(pb); /* segment duration */
  3973. e->time = (int32_t)avio_rb32(pb); /* media time */
  3974. }
  3975. e->rate = avio_rb32(pb) / 65536.0;
  3976. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3977. e->duration, e->time, e->rate);
  3978. if (e->time < 0 && e->time != -1 &&
  3979. c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  3980. av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
  3981. c->fc->nb_streams-1, i, e->time);
  3982. return AVERROR_INVALIDDATA;
  3983. }
  3984. }
  3985. sc->elst_count = i;
  3986. return 0;
  3987. }
  3988. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3989. {
  3990. MOVStreamContext *sc;
  3991. if (c->fc->nb_streams < 1)
  3992. return AVERROR_INVALIDDATA;
  3993. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3994. sc->timecode_track = avio_rb32(pb);
  3995. return 0;
  3996. }
  3997. static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3998. {
  3999. AVStream *st;
  4000. MOVStreamContext *sc;
  4001. enum AVStereo3DType type;
  4002. int mode;
  4003. if (c->fc->nb_streams < 1)
  4004. return 0;
  4005. st = c->fc->streams[c->fc->nb_streams - 1];
  4006. sc = st->priv_data;
  4007. if (atom.size < 5) {
  4008. av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
  4009. return AVERROR_INVALIDDATA;
  4010. }
  4011. avio_skip(pb, 4); /* version + flags */
  4012. mode = avio_r8(pb);
  4013. switch (mode) {
  4014. case 0:
  4015. type = AV_STEREO3D_2D;
  4016. break;
  4017. case 1:
  4018. type = AV_STEREO3D_TOPBOTTOM;
  4019. break;
  4020. case 2:
  4021. type = AV_STEREO3D_SIDEBYSIDE;
  4022. break;
  4023. default:
  4024. av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
  4025. return 0;
  4026. }
  4027. sc->stereo3d = av_stereo3d_alloc();
  4028. if (!sc->stereo3d)
  4029. return AVERROR(ENOMEM);
  4030. sc->stereo3d->type = type;
  4031. return 0;
  4032. }
  4033. static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4034. {
  4035. AVStream *st;
  4036. MOVStreamContext *sc;
  4037. int size, layout;
  4038. int32_t yaw, pitch, roll;
  4039. uint32_t l = 0, t = 0, r = 0, b = 0;
  4040. uint32_t tag, padding = 0;
  4041. enum AVSphericalProjection projection;
  4042. if (c->fc->nb_streams < 1)
  4043. return 0;
  4044. st = c->fc->streams[c->fc->nb_streams - 1];
  4045. sc = st->priv_data;
  4046. if (atom.size < 8) {
  4047. av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
  4048. return AVERROR_INVALIDDATA;
  4049. }
  4050. size = avio_rb32(pb);
  4051. if (size <= 12 || size > atom.size)
  4052. return AVERROR_INVALIDDATA;
  4053. tag = avio_rl32(pb);
  4054. if (tag != MKTAG('s','v','h','d')) {
  4055. av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
  4056. return 0;
  4057. }
  4058. avio_skip(pb, 4); /* version + flags */
  4059. avio_skip(pb, size - 12); /* metadata_source */
  4060. size = avio_rb32(pb);
  4061. if (size > atom.size)
  4062. return AVERROR_INVALIDDATA;
  4063. tag = avio_rl32(pb);
  4064. if (tag != MKTAG('p','r','o','j')) {
  4065. av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
  4066. return 0;
  4067. }
  4068. size = avio_rb32(pb);
  4069. if (size > atom.size)
  4070. return AVERROR_INVALIDDATA;
  4071. tag = avio_rl32(pb);
  4072. if (tag != MKTAG('p','r','h','d')) {
  4073. av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
  4074. return 0;
  4075. }
  4076. avio_skip(pb, 4); /* version + flags */
  4077. /* 16.16 fixed point */
  4078. yaw = avio_rb32(pb);
  4079. pitch = avio_rb32(pb);
  4080. roll = avio_rb32(pb);
  4081. size = avio_rb32(pb);
  4082. if (size > atom.size)
  4083. return AVERROR_INVALIDDATA;
  4084. tag = avio_rl32(pb);
  4085. avio_skip(pb, 4); /* version + flags */
  4086. switch (tag) {
  4087. case MKTAG('c','b','m','p'):
  4088. layout = avio_rb32(pb);
  4089. if (layout) {
  4090. av_log(c->fc, AV_LOG_WARNING,
  4091. "Unsupported cubemap layout %d\n", layout);
  4092. return 0;
  4093. }
  4094. projection = AV_SPHERICAL_CUBEMAP;
  4095. padding = avio_rb32(pb);
  4096. break;
  4097. case MKTAG('e','q','u','i'):
  4098. t = avio_rb32(pb);
  4099. b = avio_rb32(pb);
  4100. l = avio_rb32(pb);
  4101. r = avio_rb32(pb);
  4102. if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
  4103. av_log(c->fc, AV_LOG_ERROR,
  4104. "Invalid bounding rectangle coordinates "
  4105. "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
  4106. return AVERROR_INVALIDDATA;
  4107. }
  4108. if (l || t || r || b)
  4109. projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
  4110. else
  4111. projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4112. break;
  4113. default:
  4114. av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
  4115. return 0;
  4116. }
  4117. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4118. if (!sc->spherical)
  4119. return AVERROR(ENOMEM);
  4120. sc->spherical->projection = projection;
  4121. sc->spherical->yaw = yaw;
  4122. sc->spherical->pitch = pitch;
  4123. sc->spherical->roll = roll;
  4124. sc->spherical->padding = padding;
  4125. sc->spherical->bound_left = l;
  4126. sc->spherical->bound_top = t;
  4127. sc->spherical->bound_right = r;
  4128. sc->spherical->bound_bottom = b;
  4129. return 0;
  4130. }
  4131. static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
  4132. {
  4133. int ret = 0;
  4134. uint8_t *buffer = av_malloc(len + 1);
  4135. const char *val;
  4136. if (!buffer)
  4137. return AVERROR(ENOMEM);
  4138. buffer[len] = '\0';
  4139. ret = ffio_read_size(pb, buffer, len);
  4140. if (ret < 0)
  4141. goto out;
  4142. /* Check for mandatory keys and values, try to support XML as best-effort */
  4143. if (av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
  4144. (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
  4145. av_stristr(val, "true") &&
  4146. (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
  4147. av_stristr(val, "true") &&
  4148. (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
  4149. av_stristr(val, "equirectangular")) {
  4150. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4151. if (!sc->spherical)
  4152. goto out;
  4153. sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4154. if (av_stristr(buffer, "<GSpherical:StereoMode>")) {
  4155. enum AVStereo3DType mode;
  4156. if (av_stristr(buffer, "left-right"))
  4157. mode = AV_STEREO3D_SIDEBYSIDE;
  4158. else if (av_stristr(buffer, "top-bottom"))
  4159. mode = AV_STEREO3D_TOPBOTTOM;
  4160. else
  4161. mode = AV_STEREO3D_2D;
  4162. sc->stereo3d = av_stereo3d_alloc();
  4163. if (!sc->stereo3d)
  4164. goto out;
  4165. sc->stereo3d->type = mode;
  4166. }
  4167. /* orientation */
  4168. val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
  4169. if (val)
  4170. sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
  4171. val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
  4172. if (val)
  4173. sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
  4174. val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
  4175. if (val)
  4176. sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
  4177. }
  4178. out:
  4179. av_free(buffer);
  4180. return ret;
  4181. }
  4182. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4183. {
  4184. AVStream *st;
  4185. MOVStreamContext *sc;
  4186. int64_t ret;
  4187. uint8_t uuid[16];
  4188. static const uint8_t uuid_isml_manifest[] = {
  4189. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  4190. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  4191. };
  4192. static const uint8_t uuid_xmp[] = {
  4193. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  4194. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  4195. };
  4196. static const uint8_t uuid_spherical[] = {
  4197. 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
  4198. 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
  4199. };
  4200. if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
  4201. return AVERROR_INVALIDDATA;
  4202. if (c->fc->nb_streams < 1)
  4203. return 0;
  4204. st = c->fc->streams[c->fc->nb_streams - 1];
  4205. sc = st->priv_data;
  4206. ret = avio_read(pb, uuid, sizeof(uuid));
  4207. if (ret < 0) {
  4208. return ret;
  4209. } else if (ret != sizeof(uuid)) {
  4210. return AVERROR_INVALIDDATA;
  4211. }
  4212. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  4213. uint8_t *buffer, *ptr;
  4214. char *endptr;
  4215. size_t len = atom.size - sizeof(uuid);
  4216. if (len < 4) {
  4217. return AVERROR_INVALIDDATA;
  4218. }
  4219. ret = avio_skip(pb, 4); // zeroes
  4220. len -= 4;
  4221. buffer = av_mallocz(len + 1);
  4222. if (!buffer) {
  4223. return AVERROR(ENOMEM);
  4224. }
  4225. ret = avio_read(pb, buffer, len);
  4226. if (ret < 0) {
  4227. av_free(buffer);
  4228. return ret;
  4229. } else if (ret != len) {
  4230. av_free(buffer);
  4231. return AVERROR_INVALIDDATA;
  4232. }
  4233. ptr = buffer;
  4234. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  4235. ptr += sizeof("systemBitrate=\"") - 1;
  4236. c->bitrates_count++;
  4237. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  4238. if (!c->bitrates) {
  4239. c->bitrates_count = 0;
  4240. av_free(buffer);
  4241. return AVERROR(ENOMEM);
  4242. }
  4243. errno = 0;
  4244. ret = strtol(ptr, &endptr, 10);
  4245. if (ret < 0 || errno || *endptr != '"') {
  4246. c->bitrates[c->bitrates_count - 1] = 0;
  4247. } else {
  4248. c->bitrates[c->bitrates_count - 1] = ret;
  4249. }
  4250. }
  4251. av_free(buffer);
  4252. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  4253. uint8_t *buffer;
  4254. size_t len = atom.size - sizeof(uuid);
  4255. if (c->export_xmp) {
  4256. buffer = av_mallocz(len + 1);
  4257. if (!buffer) {
  4258. return AVERROR(ENOMEM);
  4259. }
  4260. ret = avio_read(pb, buffer, len);
  4261. if (ret < 0) {
  4262. av_free(buffer);
  4263. return ret;
  4264. } else if (ret != len) {
  4265. av_free(buffer);
  4266. return AVERROR_INVALIDDATA;
  4267. }
  4268. buffer[len] = '\0';
  4269. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  4270. av_free(buffer);
  4271. } else {
  4272. // skip all uuid atom, which makes it fast for long uuid-xmp file
  4273. ret = avio_skip(pb, len);
  4274. if (ret < 0)
  4275. return ret;
  4276. }
  4277. } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
  4278. size_t len = atom.size - sizeof(uuid);
  4279. ret = mov_parse_uuid_spherical(sc, pb, len);
  4280. if (ret < 0)
  4281. return ret;
  4282. if (!sc->spherical)
  4283. av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); }
  4284. return 0;
  4285. }
  4286. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4287. {
  4288. int ret;
  4289. uint8_t content[16];
  4290. if (atom.size < 8)
  4291. return 0;
  4292. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  4293. if (ret < 0)
  4294. return ret;
  4295. if ( !c->found_moov
  4296. && !c->found_mdat
  4297. && !memcmp(content, "Anevia\x1A\x1A", 8)
  4298. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  4299. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  4300. }
  4301. return 0;
  4302. }
  4303. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4304. {
  4305. uint32_t format = avio_rl32(pb);
  4306. MOVStreamContext *sc;
  4307. enum AVCodecID id;
  4308. AVStream *st;
  4309. if (c->fc->nb_streams < 1)
  4310. return 0;
  4311. st = c->fc->streams[c->fc->nb_streams - 1];
  4312. sc = st->priv_data;
  4313. switch (sc->format)
  4314. {
  4315. case MKTAG('e','n','c','v'): // encrypted video
  4316. case MKTAG('e','n','c','a'): // encrypted audio
  4317. id = mov_codec_id(st, format);
  4318. if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
  4319. st->codecpar->codec_id != id) {
  4320. av_log(c->fc, AV_LOG_WARNING,
  4321. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  4322. (char*)&format, st->codecpar->codec_id);
  4323. break;
  4324. }
  4325. st->codecpar->codec_id = id;
  4326. sc->format = format;
  4327. break;
  4328. default:
  4329. if (format != sc->format) {
  4330. av_log(c->fc, AV_LOG_WARNING,
  4331. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  4332. (char*)&format, (char*)&sc->format);
  4333. }
  4334. break;
  4335. }
  4336. return 0;
  4337. }
  4338. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4339. {
  4340. AVStream *st;
  4341. MOVStreamContext *sc;
  4342. size_t auxiliary_info_size;
  4343. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4344. return 0;
  4345. st = c->fc->streams[c->fc->nb_streams - 1];
  4346. sc = st->priv_data;
  4347. if (sc->cenc.aes_ctr) {
  4348. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  4349. return AVERROR_INVALIDDATA;
  4350. }
  4351. avio_r8(pb); /* version */
  4352. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  4353. avio_rb32(pb); /* entries */
  4354. if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
  4355. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
  4356. return AVERROR_INVALIDDATA;
  4357. }
  4358. /* save the auxiliary info as is */
  4359. auxiliary_info_size = atom.size - 8;
  4360. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  4361. if (!sc->cenc.auxiliary_info) {
  4362. return AVERROR(ENOMEM);
  4363. }
  4364. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  4365. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  4366. sc->cenc.auxiliary_info_index = 0;
  4367. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  4368. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  4369. return AVERROR_INVALIDDATA;
  4370. }
  4371. /* initialize the cipher */
  4372. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  4373. if (!sc->cenc.aes_ctr) {
  4374. return AVERROR(ENOMEM);
  4375. }
  4376. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  4377. }
  4378. static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4379. {
  4380. AVStream *st;
  4381. MOVStreamContext *sc;
  4382. size_t data_size;
  4383. int atom_header_size;
  4384. int flags;
  4385. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4386. return 0;
  4387. st = c->fc->streams[c->fc->nb_streams - 1];
  4388. sc = st->priv_data;
  4389. if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
  4390. av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
  4391. return AVERROR_INVALIDDATA;
  4392. }
  4393. atom_header_size = 9;
  4394. avio_r8(pb); /* version */
  4395. flags = avio_rb24(pb);
  4396. if ((flags & 0x01) != 0) {
  4397. atom_header_size += 8;
  4398. avio_rb32(pb); /* info type */
  4399. avio_rb32(pb); /* info type param */
  4400. }
  4401. sc->cenc.auxiliary_info_default_size = avio_r8(pb);
  4402. avio_rb32(pb); /* entries */
  4403. if (atom.size <= atom_header_size) {
  4404. return 0;
  4405. }
  4406. if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
  4407. av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
  4408. return AVERROR_INVALIDDATA;
  4409. }
  4410. /* save the auxiliary info sizes as is */
  4411. data_size = atom.size - atom_header_size;
  4412. sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
  4413. if (!sc->cenc.auxiliary_info_sizes) {
  4414. return AVERROR(ENOMEM);
  4415. }
  4416. sc->cenc.auxiliary_info_sizes_count = data_size;
  4417. if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
  4418. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
  4419. return AVERROR_INVALIDDATA;
  4420. }
  4421. return 0;
  4422. }
  4423. static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4424. {
  4425. AVStream *st;
  4426. int last, type, size, ret;
  4427. uint8_t buf[4];
  4428. if (c->fc->nb_streams < 1)
  4429. return 0;
  4430. st = c->fc->streams[c->fc->nb_streams-1];
  4431. if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
  4432. return AVERROR_INVALIDDATA;
  4433. /* Check FlacSpecificBox version. */
  4434. if (avio_r8(pb) != 0)
  4435. return AVERROR_INVALIDDATA;
  4436. avio_rb24(pb); /* Flags */
  4437. avio_read(pb, buf, sizeof(buf));
  4438. flac_parse_block_header(buf, &last, &type, &size);
  4439. if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
  4440. av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
  4441. return AVERROR_INVALIDDATA;
  4442. }
  4443. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  4444. if (ret < 0)
  4445. return ret;
  4446. if (!last)
  4447. av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
  4448. return 0;
  4449. }
  4450. static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
  4451. {
  4452. size_t auxiliary_info_seek_offset = 0;
  4453. int i;
  4454. if (sc->cenc.auxiliary_info_default_size) {
  4455. auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
  4456. } else if (sc->cenc.auxiliary_info_sizes) {
  4457. if (index > sc->cenc.auxiliary_info_sizes_count) {
  4458. av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
  4459. index, sc->cenc.auxiliary_info_sizes_count);
  4460. return AVERROR_INVALIDDATA;
  4461. }
  4462. for (i = 0; i < index; i++) {
  4463. auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
  4464. }
  4465. }
  4466. if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
  4467. av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
  4468. auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
  4469. return AVERROR_INVALIDDATA;
  4470. }
  4471. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
  4472. sc->cenc.auxiliary_info_index = index;
  4473. return 0;
  4474. }
  4475. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
  4476. {
  4477. uint32_t encrypted_bytes;
  4478. uint16_t subsample_count;
  4479. uint16_t clear_bytes;
  4480. uint8_t* input_end = input + size;
  4481. int ret;
  4482. if (index != sc->cenc.auxiliary_info_index) {
  4483. ret = mov_seek_auxiliary_info(c, sc, index);
  4484. if (ret < 0) {
  4485. return ret;
  4486. }
  4487. }
  4488. /* read the iv */
  4489. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4490. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  4491. return AVERROR_INVALIDDATA;
  4492. }
  4493. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  4494. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  4495. if (!sc->cenc.use_subsamples)
  4496. {
  4497. /* decrypt the whole packet */
  4498. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  4499. return 0;
  4500. }
  4501. /* read the subsample count */
  4502. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4503. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  4504. return AVERROR_INVALIDDATA;
  4505. }
  4506. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  4507. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4508. for (; subsample_count > 0; subsample_count--)
  4509. {
  4510. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4511. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  4512. return AVERROR_INVALIDDATA;
  4513. }
  4514. /* read the number of clear / encrypted bytes */
  4515. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  4516. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4517. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  4518. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  4519. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  4520. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  4521. return AVERROR_INVALIDDATA;
  4522. }
  4523. /* skip the clear bytes */
  4524. input += clear_bytes;
  4525. /* decrypt the encrypted bytes */
  4526. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  4527. input += encrypted_bytes;
  4528. }
  4529. if (input < input_end) {
  4530. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  4531. return AVERROR_INVALIDDATA;
  4532. }
  4533. sc->cenc.auxiliary_info_index++;
  4534. return 0;
  4535. }
  4536. static const MOVParseTableEntry mov_default_parse_table[] = {
  4537. { MKTAG('A','C','L','R'), mov_read_aclr },
  4538. { MKTAG('A','P','R','G'), mov_read_avid },
  4539. { MKTAG('A','A','L','P'), mov_read_avid },
  4540. { MKTAG('A','R','E','S'), mov_read_ares },
  4541. { MKTAG('a','v','s','s'), mov_read_avss },
  4542. { MKTAG('c','h','p','l'), mov_read_chpl },
  4543. { MKTAG('c','o','6','4'), mov_read_stco },
  4544. { MKTAG('c','o','l','r'), mov_read_colr },
  4545. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  4546. { MKTAG('d','i','n','f'), mov_read_default },
  4547. { MKTAG('D','p','x','E'), mov_read_dpxe },
  4548. { MKTAG('d','r','e','f'), mov_read_dref },
  4549. { MKTAG('e','d','t','s'), mov_read_default },
  4550. { MKTAG('e','l','s','t'), mov_read_elst },
  4551. { MKTAG('e','n','d','a'), mov_read_enda },
  4552. { MKTAG('f','i','e','l'), mov_read_fiel },
  4553. { MKTAG('a','d','r','m'), mov_read_adrm },
  4554. { MKTAG('f','t','y','p'), mov_read_ftyp },
  4555. { MKTAG('g','l','b','l'), mov_read_glbl },
  4556. { MKTAG('h','d','l','r'), mov_read_hdlr },
  4557. { MKTAG('i','l','s','t'), mov_read_ilst },
  4558. { MKTAG('j','p','2','h'), mov_read_jp2h },
  4559. { MKTAG('m','d','a','t'), mov_read_mdat },
  4560. { MKTAG('m','d','h','d'), mov_read_mdhd },
  4561. { MKTAG('m','d','i','a'), mov_read_default },
  4562. { MKTAG('m','e','t','a'), mov_read_meta },
  4563. { MKTAG('m','i','n','f'), mov_read_default },
  4564. { MKTAG('m','o','o','f'), mov_read_moof },
  4565. { MKTAG('m','o','o','v'), mov_read_moov },
  4566. { MKTAG('m','v','e','x'), mov_read_default },
  4567. { MKTAG('m','v','h','d'), mov_read_mvhd },
  4568. { MKTAG('S','M','I',' '), mov_read_svq3 },
  4569. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  4570. { MKTAG('a','v','c','C'), mov_read_glbl },
  4571. { MKTAG('p','a','s','p'), mov_read_pasp },
  4572. { MKTAG('s','i','d','x'), mov_read_sidx },
  4573. { MKTAG('s','t','b','l'), mov_read_default },
  4574. { MKTAG('s','t','c','o'), mov_read_stco },
  4575. { MKTAG('s','t','p','s'), mov_read_stps },
  4576. { MKTAG('s','t','r','f'), mov_read_strf },
  4577. { MKTAG('s','t','s','c'), mov_read_stsc },
  4578. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  4579. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  4580. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  4581. { MKTAG('s','t','t','s'), mov_read_stts },
  4582. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  4583. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  4584. { MKTAG('t','f','d','t'), mov_read_tfdt },
  4585. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  4586. { MKTAG('t','r','a','k'), mov_read_trak },
  4587. { MKTAG('t','r','a','f'), mov_read_default },
  4588. { MKTAG('t','r','e','f'), mov_read_default },
  4589. { MKTAG('t','m','c','d'), mov_read_tmcd },
  4590. { MKTAG('c','h','a','p'), mov_read_chap },
  4591. { MKTAG('t','r','e','x'), mov_read_trex },
  4592. { MKTAG('t','r','u','n'), mov_read_trun },
  4593. { MKTAG('u','d','t','a'), mov_read_default },
  4594. { MKTAG('w','a','v','e'), mov_read_wave },
  4595. { MKTAG('e','s','d','s'), mov_read_esds },
  4596. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  4597. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  4598. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  4599. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  4600. { MKTAG('w','f','e','x'), mov_read_wfex },
  4601. { MKTAG('c','m','o','v'), mov_read_cmov },
  4602. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  4603. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  4604. { MKTAG('s','b','g','p'), mov_read_sbgp },
  4605. { MKTAG('h','v','c','C'), mov_read_glbl },
  4606. { MKTAG('u','u','i','d'), mov_read_uuid },
  4607. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  4608. { MKTAG('f','r','e','e'), mov_read_free },
  4609. { MKTAG('-','-','-','-'), mov_read_custom },
  4610. { MKTAG('s','i','n','f'), mov_read_default },
  4611. { MKTAG('f','r','m','a'), mov_read_frma },
  4612. { MKTAG('s','e','n','c'), mov_read_senc },
  4613. { MKTAG('s','a','i','z'), mov_read_saiz },
  4614. { MKTAG('d','f','L','a'), mov_read_dfla },
  4615. { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
  4616. { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
  4617. { 0, NULL }
  4618. };
  4619. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4620. {
  4621. int64_t total_size = 0;
  4622. MOVAtom a;
  4623. int i;
  4624. if (c->atom_depth > 10) {
  4625. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  4626. return AVERROR_INVALIDDATA;
  4627. }
  4628. c->atom_depth ++;
  4629. if (atom.size < 0)
  4630. atom.size = INT64_MAX;
  4631. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  4632. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  4633. a.size = atom.size;
  4634. a.type=0;
  4635. if (atom.size >= 8) {
  4636. a.size = avio_rb32(pb);
  4637. a.type = avio_rl32(pb);
  4638. if (a.type == MKTAG('f','r','e','e') &&
  4639. a.size >= 8 &&
  4640. c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
  4641. c->moov_retry) {
  4642. uint8_t buf[8];
  4643. uint32_t *type = (uint32_t *)buf + 1;
  4644. if (avio_read(pb, buf, 8) != 8)
  4645. return AVERROR_INVALIDDATA;
  4646. avio_seek(pb, -8, SEEK_CUR);
  4647. if (*type == MKTAG('m','v','h','d') ||
  4648. *type == MKTAG('c','m','o','v')) {
  4649. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  4650. a.type = MKTAG('m','o','o','v');
  4651. }
  4652. }
  4653. if (atom.type != MKTAG('r','o','o','t') &&
  4654. atom.type != MKTAG('m','o','o','v'))
  4655. {
  4656. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  4657. {
  4658. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  4659. avio_skip(pb, -8);
  4660. c->atom_depth --;
  4661. return 0;
  4662. }
  4663. }
  4664. total_size += 8;
  4665. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  4666. a.size = avio_rb64(pb) - 8;
  4667. total_size += 8;
  4668. }
  4669. }
  4670. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  4671. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  4672. if (a.size == 0) {
  4673. a.size = atom.size - total_size + 8;
  4674. }
  4675. a.size -= 8;
  4676. if (a.size < 0)
  4677. break;
  4678. a.size = FFMIN(a.size, atom.size - total_size);
  4679. for (i = 0; mov_default_parse_table[i].type; i++)
  4680. if (mov_default_parse_table[i].type == a.type) {
  4681. parse = mov_default_parse_table[i].parse;
  4682. break;
  4683. }
  4684. // container is user data
  4685. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  4686. atom.type == MKTAG('i','l','s','t')))
  4687. parse = mov_read_udta_string;
  4688. // Supports parsing the QuickTime Metadata Keys.
  4689. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  4690. if (!parse && c->found_hdlr_mdta &&
  4691. atom.type == MKTAG('m','e','t','a') &&
  4692. a.type == MKTAG('k','e','y','s')) {
  4693. parse = mov_read_keys;
  4694. }
  4695. if (!parse) { /* skip leaf atoms data */
  4696. avio_skip(pb, a.size);
  4697. } else {
  4698. int64_t start_pos = avio_tell(pb);
  4699. int64_t left;
  4700. int err = parse(c, pb, a);
  4701. if (err < 0) {
  4702. c->atom_depth --;
  4703. return err;
  4704. }
  4705. if (c->found_moov && c->found_mdat &&
  4706. ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  4707. start_pos + a.size == avio_size(pb))) {
  4708. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  4709. c->next_root_atom = start_pos + a.size;
  4710. c->atom_depth --;
  4711. return 0;
  4712. }
  4713. left = a.size - avio_tell(pb) + start_pos;
  4714. if (left > 0) /* skip garbage at atom end */
  4715. avio_skip(pb, left);
  4716. else if (left < 0) {
  4717. av_log(c->fc, AV_LOG_WARNING,
  4718. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  4719. (char*)&a.type, -left);
  4720. avio_seek(pb, left, SEEK_CUR);
  4721. }
  4722. }
  4723. total_size += a.size;
  4724. }
  4725. if (total_size < atom.size && atom.size < 0x7ffff)
  4726. avio_skip(pb, atom.size - total_size);
  4727. c->atom_depth --;
  4728. return 0;
  4729. }
  4730. static int mov_probe(AVProbeData *p)
  4731. {
  4732. int64_t offset;
  4733. uint32_t tag;
  4734. int score = 0;
  4735. int moov_offset = -1;
  4736. /* check file header */
  4737. offset = 0;
  4738. for (;;) {
  4739. /* ignore invalid offset */
  4740. if ((offset + 8) > (unsigned int)p->buf_size)
  4741. break;
  4742. tag = AV_RL32(p->buf + offset + 4);
  4743. switch(tag) {
  4744. /* check for obvious tags */
  4745. case MKTAG('m','o','o','v'):
  4746. moov_offset = offset + 4;
  4747. case MKTAG('m','d','a','t'):
  4748. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  4749. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  4750. case MKTAG('f','t','y','p'):
  4751. if (AV_RB32(p->buf+offset) < 8 &&
  4752. (AV_RB32(p->buf+offset) != 1 ||
  4753. offset + 12 > (unsigned int)p->buf_size ||
  4754. AV_RB64(p->buf+offset + 8) == 0)) {
  4755. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4756. } else if (tag == MKTAG('f','t','y','p') &&
  4757. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  4758. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  4759. )) {
  4760. score = FFMAX(score, 5);
  4761. } else {
  4762. score = AVPROBE_SCORE_MAX;
  4763. }
  4764. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4765. break;
  4766. /* those are more common words, so rate then a bit less */
  4767. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  4768. case MKTAG('w','i','d','e'):
  4769. case MKTAG('f','r','e','e'):
  4770. case MKTAG('j','u','n','k'):
  4771. case MKTAG('p','i','c','t'):
  4772. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  4773. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4774. break;
  4775. case MKTAG(0x82,0x82,0x7f,0x7d):
  4776. case MKTAG('s','k','i','p'):
  4777. case MKTAG('u','u','i','d'):
  4778. case MKTAG('p','r','f','l'):
  4779. /* if we only find those cause probedata is too small at least rate them */
  4780. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4781. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4782. break;
  4783. default:
  4784. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4785. }
  4786. }
  4787. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  4788. /* moov atom in the header - we should make sure that this is not a
  4789. * MOV-packed MPEG-PS */
  4790. offset = moov_offset;
  4791. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  4792. /* We found an actual hdlr atom */
  4793. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  4794. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  4795. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  4796. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  4797. /* We found a media handler reference atom describing an
  4798. * MPEG-PS-in-MOV, return a
  4799. * low score to force expanding the probe window until
  4800. * mpegps_probe finds what it needs */
  4801. return 5;
  4802. }else
  4803. /* Keep looking */
  4804. offset+=2;
  4805. }
  4806. }
  4807. return score;
  4808. }
  4809. // must be done after parsing all trak because there's no order requirement
  4810. static void mov_read_chapters(AVFormatContext *s)
  4811. {
  4812. MOVContext *mov = s->priv_data;
  4813. AVStream *st;
  4814. MOVStreamContext *sc;
  4815. int64_t cur_pos;
  4816. int i, j;
  4817. int chapter_track;
  4818. for (j = 0; j < mov->nb_chapter_tracks; j++) {
  4819. chapter_track = mov->chapter_tracks[j];
  4820. st = NULL;
  4821. for (i = 0; i < s->nb_streams; i++)
  4822. if (s->streams[i]->id == chapter_track) {
  4823. st = s->streams[i];
  4824. break;
  4825. }
  4826. if (!st) {
  4827. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  4828. continue;
  4829. }
  4830. sc = st->priv_data;
  4831. cur_pos = avio_tell(sc->pb);
  4832. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  4833. st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
  4834. if (st->nb_index_entries) {
  4835. // Retrieve the first frame, if possible
  4836. AVPacket pkt;
  4837. AVIndexEntry *sample = &st->index_entries[0];
  4838. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4839. av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
  4840. goto finish;
  4841. }
  4842. if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
  4843. goto finish;
  4844. st->attached_pic = pkt;
  4845. st->attached_pic.stream_index = st->index;
  4846. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  4847. }
  4848. } else {
  4849. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  4850. st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
  4851. st->discard = AVDISCARD_ALL;
  4852. for (i = 0; i < st->nb_index_entries; i++) {
  4853. AVIndexEntry *sample = &st->index_entries[i];
  4854. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  4855. uint8_t *title;
  4856. uint16_t ch;
  4857. int len, title_len;
  4858. if (end < sample->timestamp) {
  4859. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  4860. end = AV_NOPTS_VALUE;
  4861. }
  4862. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4863. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  4864. goto finish;
  4865. }
  4866. // the first two bytes are the length of the title
  4867. len = avio_rb16(sc->pb);
  4868. if (len > sample->size-2)
  4869. continue;
  4870. title_len = 2*len + 1;
  4871. if (!(title = av_mallocz(title_len)))
  4872. goto finish;
  4873. // The samples could theoretically be in any encoding if there's an encd
  4874. // atom following, but in practice are only utf-8 or utf-16, distinguished
  4875. // instead by the presence of a BOM
  4876. if (!len) {
  4877. title[0] = 0;
  4878. } else {
  4879. ch = avio_rb16(sc->pb);
  4880. if (ch == 0xfeff)
  4881. avio_get_str16be(sc->pb, len, title, title_len);
  4882. else if (ch == 0xfffe)
  4883. avio_get_str16le(sc->pb, len, title, title_len);
  4884. else {
  4885. AV_WB16(title, ch);
  4886. if (len == 1 || len == 2)
  4887. title[len] = 0;
  4888. else
  4889. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  4890. }
  4891. }
  4892. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  4893. av_freep(&title);
  4894. }
  4895. }
  4896. finish:
  4897. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4898. }
  4899. }
  4900. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  4901. uint32_t value, int flags)
  4902. {
  4903. AVTimecode tc;
  4904. char buf[AV_TIMECODE_STR_SIZE];
  4905. AVRational rate = st->avg_frame_rate;
  4906. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  4907. if (ret < 0)
  4908. return ret;
  4909. av_dict_set(&st->metadata, "timecode",
  4910. av_timecode_make_string(&tc, buf, value), 0);
  4911. return 0;
  4912. }
  4913. static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
  4914. {
  4915. MOVStreamContext *sc = st->priv_data;
  4916. char buf[AV_TIMECODE_STR_SIZE];
  4917. int64_t cur_pos = avio_tell(sc->pb);
  4918. int hh, mm, ss, ff, drop;
  4919. if (!st->nb_index_entries)
  4920. return -1;
  4921. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4922. avio_skip(s->pb, 13);
  4923. hh = avio_r8(s->pb);
  4924. mm = avio_r8(s->pb);
  4925. ss = avio_r8(s->pb);
  4926. drop = avio_r8(s->pb);
  4927. ff = avio_r8(s->pb);
  4928. snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
  4929. hh, mm, ss, drop ? ';' : ':', ff);
  4930. av_dict_set(&st->metadata, "timecode", buf, 0);
  4931. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4932. return 0;
  4933. }
  4934. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  4935. {
  4936. MOVStreamContext *sc = st->priv_data;
  4937. int flags = 0;
  4938. int64_t cur_pos = avio_tell(sc->pb);
  4939. uint32_t value;
  4940. if (!st->nb_index_entries)
  4941. return -1;
  4942. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4943. value = avio_rb32(s->pb);
  4944. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  4945. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  4946. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  4947. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  4948. * not the case) and thus assume "frame number format" instead of QT one.
  4949. * No sample with tmcd track can be found with a QT timecode at the moment,
  4950. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  4951. * format). */
  4952. parse_timecode_in_framenum_format(s, st, value, flags);
  4953. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4954. return 0;
  4955. }
  4956. static int mov_read_close(AVFormatContext *s)
  4957. {
  4958. MOVContext *mov = s->priv_data;
  4959. int i, j;
  4960. for (i = 0; i < s->nb_streams; i++) {
  4961. AVStream *st = s->streams[i];
  4962. MOVStreamContext *sc = st->priv_data;
  4963. if (!sc)
  4964. continue;
  4965. av_freep(&sc->ctts_data);
  4966. for (j = 0; j < sc->drefs_count; j++) {
  4967. av_freep(&sc->drefs[j].path);
  4968. av_freep(&sc->drefs[j].dir);
  4969. }
  4970. av_freep(&sc->drefs);
  4971. sc->drefs_count = 0;
  4972. if (!sc->pb_is_copied)
  4973. ff_format_io_close(s, &sc->pb);
  4974. sc->pb = NULL;
  4975. av_freep(&sc->chunk_offsets);
  4976. av_freep(&sc->stsc_data);
  4977. av_freep(&sc->sample_sizes);
  4978. av_freep(&sc->keyframes);
  4979. av_freep(&sc->stts_data);
  4980. av_freep(&sc->stps_data);
  4981. av_freep(&sc->elst_data);
  4982. av_freep(&sc->rap_group);
  4983. av_freep(&sc->display_matrix);
  4984. av_freep(&sc->index_ranges);
  4985. if (sc->extradata)
  4986. for (j = 0; j < sc->stsd_count; j++)
  4987. av_free(sc->extradata[j]);
  4988. av_freep(&sc->extradata);
  4989. av_freep(&sc->extradata_size);
  4990. av_freep(&sc->cenc.auxiliary_info);
  4991. av_freep(&sc->cenc.auxiliary_info_sizes);
  4992. av_aes_ctr_free(sc->cenc.aes_ctr);
  4993. av_freep(&sc->stereo3d);
  4994. av_freep(&sc->spherical);
  4995. }
  4996. if (mov->dv_demux) {
  4997. avformat_free_context(mov->dv_fctx);
  4998. mov->dv_fctx = NULL;
  4999. }
  5000. if (mov->meta_keys) {
  5001. for (i = 1; i < mov->meta_keys_count; i++) {
  5002. av_freep(&mov->meta_keys[i]);
  5003. }
  5004. av_freep(&mov->meta_keys);
  5005. }
  5006. av_freep(&mov->trex_data);
  5007. av_freep(&mov->bitrates);
  5008. for (i = 0; i < mov->fragment_index_count; i++) {
  5009. MOVFragmentIndex* index = mov->fragment_index_data[i];
  5010. av_freep(&index->items);
  5011. av_freep(&mov->fragment_index_data[i]);
  5012. }
  5013. av_freep(&mov->fragment_index_data);
  5014. av_freep(&mov->aes_decrypt);
  5015. return 0;
  5016. }
  5017. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  5018. {
  5019. int i;
  5020. for (i = 0; i < s->nb_streams; i++) {
  5021. AVStream *st = s->streams[i];
  5022. MOVStreamContext *sc = st->priv_data;
  5023. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  5024. sc->timecode_track == tmcd_id)
  5025. return 1;
  5026. }
  5027. return 0;
  5028. }
  5029. /* look for a tmcd track not referenced by any video track, and export it globally */
  5030. static void export_orphan_timecode(AVFormatContext *s)
  5031. {
  5032. int i;
  5033. for (i = 0; i < s->nb_streams; i++) {
  5034. AVStream *st = s->streams[i];
  5035. if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
  5036. !tmcd_is_referenced(s, i + 1)) {
  5037. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  5038. if (tcr) {
  5039. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  5040. break;
  5041. }
  5042. }
  5043. }
  5044. }
  5045. static int read_tfra(MOVContext *mov, AVIOContext *f)
  5046. {
  5047. MOVFragmentIndex* index = NULL;
  5048. int version, fieldlength, i, j;
  5049. int64_t pos = avio_tell(f);
  5050. uint32_t size = avio_rb32(f);
  5051. void *tmp;
  5052. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  5053. return 1;
  5054. }
  5055. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  5056. index = av_mallocz(sizeof(MOVFragmentIndex));
  5057. if (!index) {
  5058. return AVERROR(ENOMEM);
  5059. }
  5060. tmp = av_realloc_array(mov->fragment_index_data,
  5061. mov->fragment_index_count + 1,
  5062. sizeof(MOVFragmentIndex*));
  5063. if (!tmp) {
  5064. av_freep(&index);
  5065. return AVERROR(ENOMEM);
  5066. }
  5067. mov->fragment_index_data = tmp;
  5068. mov->fragment_index_data[mov->fragment_index_count++] = index;
  5069. version = avio_r8(f);
  5070. avio_rb24(f);
  5071. index->track_id = avio_rb32(f);
  5072. fieldlength = avio_rb32(f);
  5073. index->item_count = avio_rb32(f);
  5074. index->items = av_mallocz_array(
  5075. index->item_count, sizeof(MOVFragmentIndexItem));
  5076. if (!index->items) {
  5077. index->item_count = 0;
  5078. return AVERROR(ENOMEM);
  5079. }
  5080. for (i = 0; i < index->item_count; i++) {
  5081. int64_t time, offset;
  5082. if (version == 1) {
  5083. time = avio_rb64(f);
  5084. offset = avio_rb64(f);
  5085. } else {
  5086. time = avio_rb32(f);
  5087. offset = avio_rb32(f);
  5088. }
  5089. index->items[i].time = time;
  5090. index->items[i].moof_offset = offset;
  5091. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  5092. avio_r8(f);
  5093. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  5094. avio_r8(f);
  5095. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  5096. avio_r8(f);
  5097. }
  5098. avio_seek(f, pos + size, SEEK_SET);
  5099. return 0;
  5100. }
  5101. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  5102. {
  5103. int64_t stream_size = avio_size(f);
  5104. int64_t original_pos = avio_tell(f);
  5105. int64_t seek_ret;
  5106. int32_t mfra_size;
  5107. int ret = -1;
  5108. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  5109. ret = seek_ret;
  5110. goto fail;
  5111. }
  5112. mfra_size = avio_rb32(f);
  5113. if (mfra_size < 0 || mfra_size > stream_size) {
  5114. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  5115. goto fail;
  5116. }
  5117. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  5118. ret = seek_ret;
  5119. goto fail;
  5120. }
  5121. if (avio_rb32(f) != mfra_size) {
  5122. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  5123. goto fail;
  5124. }
  5125. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  5126. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  5127. goto fail;
  5128. }
  5129. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  5130. do {
  5131. ret = read_tfra(c, f);
  5132. if (ret < 0)
  5133. goto fail;
  5134. } while (!ret);
  5135. ret = 0;
  5136. fail:
  5137. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  5138. if (seek_ret < 0) {
  5139. av_log(c->fc, AV_LOG_ERROR,
  5140. "failed to seek back after looking for mfra\n");
  5141. ret = seek_ret;
  5142. }
  5143. return ret;
  5144. }
  5145. static int mov_read_header(AVFormatContext *s)
  5146. {
  5147. MOVContext *mov = s->priv_data;
  5148. AVIOContext *pb = s->pb;
  5149. int j, err;
  5150. MOVAtom atom = { AV_RL32("root") };
  5151. int i;
  5152. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  5153. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  5154. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  5155. return AVERROR(EINVAL);
  5156. }
  5157. mov->fc = s;
  5158. mov->trak_index = -1;
  5159. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  5160. if (pb->seekable & AVIO_SEEKABLE_NORMAL)
  5161. atom.size = avio_size(pb);
  5162. else
  5163. atom.size = INT64_MAX;
  5164. /* check MOV header */
  5165. do {
  5166. if (mov->moov_retry)
  5167. avio_seek(pb, 0, SEEK_SET);
  5168. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  5169. av_log(s, AV_LOG_ERROR, "error reading header\n");
  5170. mov_read_close(s);
  5171. return err;
  5172. }
  5173. } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
  5174. if (!mov->found_moov) {
  5175. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  5176. mov_read_close(s);
  5177. return AVERROR_INVALIDDATA;
  5178. }
  5179. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  5180. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  5181. if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
  5182. mov_read_chapters(s);
  5183. for (i = 0; i < s->nb_streams; i++)
  5184. if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
  5185. mov_read_timecode_track(s, s->streams[i]);
  5186. } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
  5187. mov_read_rtmd_track(s, s->streams[i]);
  5188. }
  5189. }
  5190. /* copy timecode metadata from tmcd tracks to the related video streams */
  5191. for (i = 0; i < s->nb_streams; i++) {
  5192. AVStream *st = s->streams[i];
  5193. MOVStreamContext *sc = st->priv_data;
  5194. if (sc->timecode_track > 0) {
  5195. AVDictionaryEntry *tcr;
  5196. int tmcd_st_id = -1;
  5197. for (j = 0; j < s->nb_streams; j++)
  5198. if (s->streams[j]->id == sc->timecode_track)
  5199. tmcd_st_id = j;
  5200. if (tmcd_st_id < 0 || tmcd_st_id == i)
  5201. continue;
  5202. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  5203. if (tcr)
  5204. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  5205. }
  5206. }
  5207. export_orphan_timecode(s);
  5208. for (i = 0; i < s->nb_streams; i++) {
  5209. AVStream *st = s->streams[i];
  5210. MOVStreamContext *sc = st->priv_data;
  5211. fix_timescale(mov, sc);
  5212. if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  5213. st->skip_samples = sc->start_pad;
  5214. }
  5215. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  5216. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  5217. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  5218. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5219. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  5220. st->codecpar->width = sc->width;
  5221. st->codecpar->height = sc->height;
  5222. }
  5223. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  5224. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  5225. return err;
  5226. }
  5227. }
  5228. if (mov->handbrake_version &&
  5229. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  5230. st->codecpar->codec_id == AV_CODEC_ID_MP3
  5231. ) {
  5232. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  5233. st->need_parsing = AVSTREAM_PARSE_FULL;
  5234. }
  5235. }
  5236. if (mov->trex_data) {
  5237. for (i = 0; i < s->nb_streams; i++) {
  5238. AVStream *st = s->streams[i];
  5239. MOVStreamContext *sc = st->priv_data;
  5240. if (st->duration > 0) {
  5241. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  5242. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  5243. sc->data_size, sc->time_scale);
  5244. mov_read_close(s);
  5245. return AVERROR_INVALIDDATA;
  5246. }
  5247. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  5248. }
  5249. }
  5250. }
  5251. if (mov->use_mfra_for > 0) {
  5252. for (i = 0; i < s->nb_streams; i++) {
  5253. AVStream *st = s->streams[i];
  5254. MOVStreamContext *sc = st->priv_data;
  5255. if (sc->duration_for_fps > 0) {
  5256. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  5257. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  5258. sc->data_size, sc->time_scale);
  5259. mov_read_close(s);
  5260. return AVERROR_INVALIDDATA;
  5261. }
  5262. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
  5263. sc->duration_for_fps;
  5264. }
  5265. }
  5266. }
  5267. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  5268. if (mov->bitrates[i]) {
  5269. s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
  5270. }
  5271. }
  5272. ff_rfps_calculate(s);
  5273. for (i = 0; i < s->nb_streams; i++) {
  5274. AVStream *st = s->streams[i];
  5275. MOVStreamContext *sc = st->priv_data;
  5276. switch (st->codecpar->codec_type) {
  5277. case AVMEDIA_TYPE_AUDIO:
  5278. err = ff_replaygain_export(st, s->metadata);
  5279. if (err < 0) {
  5280. mov_read_close(s);
  5281. return err;
  5282. }
  5283. break;
  5284. case AVMEDIA_TYPE_VIDEO:
  5285. if (sc->display_matrix) {
  5286. err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
  5287. sizeof(int32_t) * 9);
  5288. if (err < 0)
  5289. return err;
  5290. sc->display_matrix = NULL;
  5291. }
  5292. if (sc->stereo3d) {
  5293. err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
  5294. (uint8_t *)sc->stereo3d,
  5295. sizeof(*sc->stereo3d));
  5296. if (err < 0)
  5297. return err;
  5298. sc->stereo3d = NULL;
  5299. }
  5300. if (sc->spherical) {
  5301. err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
  5302. (uint8_t *)sc->spherical,
  5303. sc->spherical_size);
  5304. if (err < 0)
  5305. return err;
  5306. sc->spherical = NULL;
  5307. }
  5308. break;
  5309. }
  5310. }
  5311. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  5312. return 0;
  5313. }
  5314. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  5315. {
  5316. AVIndexEntry *sample = NULL;
  5317. int64_t best_dts = INT64_MAX;
  5318. int i;
  5319. for (i = 0; i < s->nb_streams; i++) {
  5320. AVStream *avst = s->streams[i];
  5321. MOVStreamContext *msc = avst->priv_data;
  5322. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  5323. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  5324. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  5325. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  5326. if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
  5327. ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  5328. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  5329. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  5330. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  5331. sample = current_sample;
  5332. best_dts = dts;
  5333. *st = avst;
  5334. }
  5335. }
  5336. }
  5337. return sample;
  5338. }
  5339. static int should_retry(AVIOContext *pb, int error_code) {
  5340. if (error_code == AVERROR_EOF || avio_feof(pb))
  5341. return 0;
  5342. return 1;
  5343. }
  5344. static int mov_switch_root(AVFormatContext *s, int64_t target)
  5345. {
  5346. MOVContext *mov = s->priv_data;
  5347. int i, j;
  5348. int already_read = 0;
  5349. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  5350. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  5351. return AVERROR_INVALIDDATA;
  5352. }
  5353. mov->next_root_atom = 0;
  5354. for (i = 0; i < mov->fragment_index_count; i++) {
  5355. MOVFragmentIndex *index = mov->fragment_index_data[i];
  5356. int found = 0;
  5357. for (j = 0; j < index->item_count; j++) {
  5358. MOVFragmentIndexItem *item = &index->items[j];
  5359. if (found) {
  5360. mov->next_root_atom = item->moof_offset;
  5361. break; // Advance to next index in outer loop
  5362. } else if (item->moof_offset == target) {
  5363. index->current_item = FFMIN(j, index->current_item);
  5364. if (item->headers_read)
  5365. already_read = 1;
  5366. item->headers_read = 1;
  5367. found = 1;
  5368. }
  5369. }
  5370. if (!found)
  5371. index->current_item = 0;
  5372. }
  5373. if (already_read)
  5374. return 0;
  5375. mov->found_mdat = 0;
  5376. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  5377. avio_feof(s->pb))
  5378. return AVERROR_EOF;
  5379. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  5380. return 1;
  5381. }
  5382. static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
  5383. {
  5384. uint8_t *side, *extradata;
  5385. int extradata_size;
  5386. /* Save the current index. */
  5387. sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
  5388. /* Notify the decoder that extradata changed. */
  5389. extradata_size = sc->extradata_size[sc->last_stsd_index];
  5390. extradata = sc->extradata[sc->last_stsd_index];
  5391. if (extradata_size > 0 && extradata) {
  5392. side = av_packet_new_side_data(pkt,
  5393. AV_PKT_DATA_NEW_EXTRADATA,
  5394. extradata_size);
  5395. if (!side)
  5396. return AVERROR(ENOMEM);
  5397. memcpy(side, extradata, extradata_size);
  5398. }
  5399. return 0;
  5400. }
  5401. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  5402. {
  5403. MOVContext *mov = s->priv_data;
  5404. MOVStreamContext *sc;
  5405. AVIndexEntry *sample;
  5406. AVStream *st = NULL;
  5407. int64_t current_index;
  5408. int ret;
  5409. mov->fc = s;
  5410. retry:
  5411. sample = mov_find_next_sample(s, &st);
  5412. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  5413. if (!mov->next_root_atom)
  5414. return AVERROR_EOF;
  5415. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  5416. return ret;
  5417. goto retry;
  5418. }
  5419. sc = st->priv_data;
  5420. /* must be done just before reading, to avoid infinite loop on sample */
  5421. current_index = sc->current_index;
  5422. mov_current_sample_inc(sc);
  5423. if (mov->next_root_atom) {
  5424. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  5425. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  5426. }
  5427. if (st->discard != AVDISCARD_ALL) {
  5428. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  5429. if (ret64 != sample->pos) {
  5430. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  5431. sc->ffindex, sample->pos);
  5432. if (should_retry(sc->pb, ret64)) {
  5433. mov_current_sample_dec(sc);
  5434. }
  5435. return AVERROR_INVALIDDATA;
  5436. }
  5437. if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
  5438. av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
  5439. goto retry;
  5440. }
  5441. ret = av_get_packet(sc->pb, pkt, sample->size);
  5442. if (ret < 0) {
  5443. if (should_retry(sc->pb, ret)) {
  5444. mov_current_sample_dec(sc);
  5445. }
  5446. return ret;
  5447. }
  5448. if (sc->has_palette) {
  5449. uint8_t *pal;
  5450. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  5451. if (!pal) {
  5452. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  5453. } else {
  5454. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  5455. sc->has_palette = 0;
  5456. }
  5457. }
  5458. #if CONFIG_DV_DEMUXER
  5459. if (mov->dv_demux && sc->dv_audio_container) {
  5460. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  5461. av_freep(&pkt->data);
  5462. pkt->size = 0;
  5463. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  5464. if (ret < 0)
  5465. return ret;
  5466. }
  5467. #endif
  5468. if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
  5469. if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
  5470. st->need_parsing = AVSTREAM_PARSE_FULL;
  5471. }
  5472. }
  5473. pkt->stream_index = sc->ffindex;
  5474. pkt->dts = sample->timestamp;
  5475. if (sample->flags & AVINDEX_DISCARD_FRAME) {
  5476. pkt->flags |= AV_PKT_FLAG_DISCARD;
  5477. }
  5478. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  5479. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  5480. /* update ctts context */
  5481. sc->ctts_sample++;
  5482. if (sc->ctts_index < sc->ctts_count &&
  5483. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  5484. sc->ctts_index++;
  5485. sc->ctts_sample = 0;
  5486. }
  5487. } else {
  5488. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  5489. st->index_entries[sc->current_sample].timestamp : st->duration;
  5490. pkt->duration = next_dts - pkt->dts;
  5491. pkt->pts = pkt->dts;
  5492. }
  5493. if (st->discard == AVDISCARD_ALL)
  5494. goto retry;
  5495. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  5496. pkt->pos = sample->pos;
  5497. /* Multiple stsd handling. */
  5498. if (sc->stsc_data) {
  5499. /* Keep track of the stsc index for the given sample, then check
  5500. * if the stsd index is different from the last used one. */
  5501. sc->stsc_sample++;
  5502. if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
  5503. mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
  5504. sc->stsc_index++;
  5505. sc->stsc_sample = 0;
  5506. /* Do not check indexes after a switch. */
  5507. } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
  5508. sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
  5509. sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
  5510. ret = mov_change_extradata(sc, pkt);
  5511. if (ret < 0)
  5512. return ret;
  5513. }
  5514. }
  5515. if (mov->aax_mode)
  5516. aax_filter(pkt->data, pkt->size, mov);
  5517. if (sc->cenc.aes_ctr) {
  5518. ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
  5519. if (ret) {
  5520. return ret;
  5521. }
  5522. }
  5523. return 0;
  5524. }
  5525. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  5526. {
  5527. MOVContext *mov = s->priv_data;
  5528. MOVStreamContext *sc = st->priv_data;
  5529. int i, j;
  5530. if (!mov->fragment_index_complete)
  5531. return 0;
  5532. for (i = 0; i < mov->fragment_index_count; i++) {
  5533. if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) {
  5534. MOVFragmentIndex *index = mov->fragment_index_data[i];
  5535. for (j = index->item_count - 1; j >= 0; j--) {
  5536. if (index->items[j].time <= timestamp) {
  5537. if (index->items[j].headers_read)
  5538. return 0;
  5539. return mov_switch_root(s, index->items[j].moof_offset);
  5540. }
  5541. }
  5542. }
  5543. }
  5544. return 0;
  5545. }
  5546. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  5547. {
  5548. MOVStreamContext *sc = st->priv_data;
  5549. int sample, time_sample;
  5550. int i;
  5551. int ret = mov_seek_fragment(s, st, timestamp);
  5552. if (ret < 0)
  5553. return ret;
  5554. sample = av_index_search_timestamp(st, timestamp, flags);
  5555. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  5556. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  5557. sample = 0;
  5558. if (sample < 0) /* not sure what to do */
  5559. return AVERROR_INVALIDDATA;
  5560. mov_current_sample_set(sc, sample);
  5561. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  5562. /* adjust ctts index */
  5563. if (sc->ctts_data) {
  5564. time_sample = 0;
  5565. for (i = 0; i < sc->ctts_count; i++) {
  5566. int next = time_sample + sc->ctts_data[i].count;
  5567. if (next > sc->current_sample) {
  5568. sc->ctts_index = i;
  5569. sc->ctts_sample = sc->current_sample - time_sample;
  5570. break;
  5571. }
  5572. time_sample = next;
  5573. }
  5574. }
  5575. /* adjust stsd index */
  5576. time_sample = 0;
  5577. for (i = 0; i < sc->stsc_count; i++) {
  5578. int next = time_sample + mov_get_stsc_samples(sc, i);
  5579. if (next > sc->current_sample) {
  5580. sc->stsc_index = i;
  5581. sc->stsc_sample = sc->current_sample - time_sample;
  5582. break;
  5583. }
  5584. time_sample = next;
  5585. }
  5586. return sample;
  5587. }
  5588. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  5589. {
  5590. MOVContext *mc = s->priv_data;
  5591. AVStream *st;
  5592. int sample;
  5593. int i;
  5594. if (stream_index >= s->nb_streams)
  5595. return AVERROR_INVALIDDATA;
  5596. st = s->streams[stream_index];
  5597. sample = mov_seek_stream(s, st, sample_time, flags);
  5598. if (sample < 0)
  5599. return sample;
  5600. if (mc->seek_individually) {
  5601. /* adjust seek timestamp to found sample timestamp */
  5602. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  5603. for (i = 0; i < s->nb_streams; i++) {
  5604. int64_t timestamp;
  5605. MOVStreamContext *sc = s->streams[i]->priv_data;
  5606. st = s->streams[i];
  5607. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  5608. if (stream_index == i)
  5609. continue;
  5610. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  5611. mov_seek_stream(s, st, timestamp, flags);
  5612. }
  5613. } else {
  5614. for (i = 0; i < s->nb_streams; i++) {
  5615. MOVStreamContext *sc;
  5616. st = s->streams[i];
  5617. sc = st->priv_data;
  5618. mov_current_sample_set(sc, 0);
  5619. }
  5620. while (1) {
  5621. MOVStreamContext *sc;
  5622. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  5623. if (!entry)
  5624. return AVERROR_INVALIDDATA;
  5625. sc = st->priv_data;
  5626. if (sc->ffindex == stream_index && sc->current_sample == sample)
  5627. break;
  5628. mov_current_sample_inc(sc);
  5629. }
  5630. }
  5631. return 0;
  5632. }
  5633. #define OFFSET(x) offsetof(MOVContext, x)
  5634. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  5635. static const AVOption mov_options[] = {
  5636. {"use_absolute_path",
  5637. "allow using absolute path when opening alias, this is a possible security issue",
  5638. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5639. 0, 1, FLAGS},
  5640. {"seek_streams_individually",
  5641. "Seek each stream individually to the to the closest point",
  5642. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  5643. 0, 1, FLAGS},
  5644. {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5645. 0, 1, FLAGS},
  5646. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5647. 0, 1, FLAGS},
  5648. {"use_mfra_for",
  5649. "use mfra for fragment timestamps",
  5650. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  5651. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  5652. "use_mfra_for"},
  5653. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  5654. FLAGS, "use_mfra_for" },
  5655. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  5656. FLAGS, "use_mfra_for" },
  5657. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  5658. FLAGS, "use_mfra_for" },
  5659. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  5660. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5661. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  5662. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5663. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  5664. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5665. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  5666. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  5667. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  5668. .flags = AV_OPT_FLAG_DECODING_PARAM },
  5669. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5670. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  5671. {.i64 = 0}, 0, 1, FLAGS },
  5672. { NULL },
  5673. };
  5674. static const AVClass mov_class = {
  5675. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  5676. .item_name = av_default_item_name,
  5677. .option = mov_options,
  5678. .version = LIBAVUTIL_VERSION_INT,
  5679. };
  5680. AVInputFormat ff_mov_demuxer = {
  5681. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  5682. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5683. .priv_class = &mov_class,
  5684. .priv_data_size = sizeof(MOVContext),
  5685. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  5686. .read_probe = mov_probe,
  5687. .read_header = mov_read_header,
  5688. .read_packet = mov_read_packet,
  5689. .read_close = mov_read_close,
  5690. .read_seek = mov_read_seek,
  5691. .flags = AVFMT_NO_BYTE_SEEK,
  5692. };