mov.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991
  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. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <limits.h>
  23. //#define DEBUG
  24. //#define MOV_EXPORT_ALL_METADATA
  25. #include "libavutil/audioconvert.h"
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/intfloat.h"
  28. #include "libavutil/mathematics.h"
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/dict.h"
  31. #include "libavutil/opt.h"
  32. #include "libavcodec/ac3tab.h"
  33. #include "avformat.h"
  34. #include "internal.h"
  35. #include "avio_internal.h"
  36. #include "riff.h"
  37. #include "isom.h"
  38. #include "libavcodec/get_bits.h"
  39. #include "libavcodec/timecode.h"
  40. #include "id3v1.h"
  41. #include "mov_chan.h"
  42. #if CONFIG_ZLIB
  43. #include <zlib.h>
  44. #endif
  45. /*
  46. * First version by Francois Revol revol@free.fr
  47. * Seek function by Gael Chardon gael.dev@4now.net
  48. */
  49. #include "qtpalette.h"
  50. #undef NDEBUG
  51. #include <assert.h>
  52. /* those functions parse an atom */
  53. /* links atom IDs to parse functions */
  54. typedef struct MOVParseTableEntry {
  55. uint32_t type;
  56. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  57. } MOVParseTableEntry;
  58. static const MOVParseTableEntry mov_default_parse_table[];
  59. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  60. unsigned len, const char *key)
  61. {
  62. char buf[16];
  63. short current, total = 0;
  64. avio_rb16(pb); // unknown
  65. current = avio_rb16(pb);
  66. if (len >= 6)
  67. total = avio_rb16(pb);
  68. if (!total)
  69. snprintf(buf, sizeof(buf), "%d", current);
  70. else
  71. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  72. av_dict_set(&c->fc->metadata, key, buf, 0);
  73. return 0;
  74. }
  75. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  76. unsigned len, const char *key)
  77. {
  78. char buf[16];
  79. /* bypass padding bytes */
  80. avio_r8(pb);
  81. avio_r8(pb);
  82. avio_r8(pb);
  83. snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
  84. av_dict_set(&c->fc->metadata, key, buf, 0);
  85. return 0;
  86. }
  87. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  88. unsigned len, const char *key)
  89. {
  90. char buf[16];
  91. snprintf(buf, sizeof(buf), "%d", avio_r8(pb));
  92. av_dict_set(&c->fc->metadata, key, buf, 0);
  93. return 0;
  94. }
  95. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  96. unsigned len, const char *key)
  97. {
  98. short genre;
  99. char buf[20];
  100. avio_r8(pb); // unknown
  101. genre = avio_r8(pb);
  102. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  103. return 0;
  104. snprintf(buf, sizeof(buf), "%s", ff_id3v1_genre_str[genre-1]);
  105. av_dict_set(&c->fc->metadata, key, buf, 0);
  106. return 0;
  107. }
  108. static const uint32_t mac_to_unicode[128] = {
  109. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  110. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  111. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  112. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  113. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  114. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  115. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  116. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  117. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  118. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  119. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  120. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  121. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  122. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  123. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  124. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  125. };
  126. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  127. char *dst, int dstlen)
  128. {
  129. char *p = dst;
  130. char *end = dst+dstlen-1;
  131. int i;
  132. for (i = 0; i < len; i++) {
  133. uint8_t t, c = avio_r8(pb);
  134. if (c < 0x80 && p < end)
  135. *p++ = c;
  136. else if (p < end)
  137. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  138. }
  139. *p = 0;
  140. return p - dst;
  141. }
  142. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  143. {
  144. #ifdef MOV_EXPORT_ALL_METADATA
  145. char tmp_key[5];
  146. #endif
  147. char str[1024], key2[16], language[4] = {0};
  148. const char *key = NULL;
  149. uint16_t str_size, langcode = 0;
  150. uint32_t data_type = 0;
  151. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  152. switch (atom.type) {
  153. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  154. case MKTAG(0xa9,'a','u','t'):
  155. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  156. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  157. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  158. case MKTAG( 'c','p','r','t'):
  159. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  160. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  161. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  162. case MKTAG(0xa9,'c','m','t'):
  163. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  164. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  165. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  166. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  167. case MKTAG( 'g','n','r','e'): key = "genre";
  168. parse = mov_metadata_gnre; break;
  169. case MKTAG(0xa9,'t','o','o'):
  170. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  171. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  172. case MKTAG( 'd','e','s','c'): key = "description";break;
  173. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  174. case MKTAG( 't','v','s','h'): key = "show"; break;
  175. case MKTAG( 't','v','e','n'): key = "episode_id";break;
  176. case MKTAG( 't','v','n','n'): key = "network"; break;
  177. case MKTAG( 't','r','k','n'): key = "track";
  178. parse = mov_metadata_track_or_disc_number; break;
  179. case MKTAG( 'd','i','s','k'): key = "disc";
  180. parse = mov_metadata_track_or_disc_number; break;
  181. case MKTAG( 't','v','e','s'): key = "episode_sort";
  182. parse = mov_metadata_int8_bypass_padding; break;
  183. case MKTAG( 't','v','s','n'): key = "season_number";
  184. parse = mov_metadata_int8_bypass_padding; break;
  185. case MKTAG( 's','t','i','k'): key = "media_type";
  186. parse = mov_metadata_int8_no_padding; break;
  187. case MKTAG( 'h','d','v','d'): key = "hd_video";
  188. parse = mov_metadata_int8_no_padding; break;
  189. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  190. parse = mov_metadata_int8_no_padding; break;
  191. }
  192. if (c->itunes_metadata && atom.size > 8) {
  193. int data_size = avio_rb32(pb);
  194. int tag = avio_rl32(pb);
  195. if (tag == MKTAG('d','a','t','a')) {
  196. data_type = avio_rb32(pb); // type
  197. avio_rb32(pb); // unknown
  198. str_size = data_size - 16;
  199. atom.size -= 16;
  200. } else return 0;
  201. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  202. str_size = avio_rb16(pb); // string length
  203. langcode = avio_rb16(pb);
  204. ff_mov_lang_to_iso639(langcode, language);
  205. atom.size -= 4;
  206. } else
  207. str_size = atom.size;
  208. #ifdef MOV_EXPORT_ALL_METADATA
  209. if (!key) {
  210. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  211. key = tmp_key;
  212. }
  213. #endif
  214. if (!key)
  215. return 0;
  216. if (atom.size < 0 || str_size >= INT_MAX/2)
  217. return AVERROR_INVALIDDATA;
  218. str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
  219. if (parse)
  220. parse(c, pb, str_size, key);
  221. else {
  222. if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded
  223. mov_read_mac_string(c, pb, str_size, str, sizeof(str));
  224. } else {
  225. avio_read(pb, str, str_size);
  226. str[str_size] = 0;
  227. }
  228. av_dict_set(&c->fc->metadata, key, str, 0);
  229. if (*language && strcmp(language, "und")) {
  230. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  231. av_dict_set(&c->fc->metadata, key2, str, 0);
  232. }
  233. }
  234. av_dlog(c->fc, "lang \"%3s\" ", language);
  235. av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  236. key, str, (char*)&atom.type, str_size, atom.size);
  237. return 0;
  238. }
  239. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  240. {
  241. int64_t start;
  242. int i, nb_chapters, str_len, version;
  243. char str[256+1];
  244. if ((atom.size -= 5) < 0)
  245. return 0;
  246. version = avio_r8(pb);
  247. avio_rb24(pb);
  248. if (version)
  249. avio_rb32(pb); // ???
  250. nb_chapters = avio_r8(pb);
  251. for (i = 0; i < nb_chapters; i++) {
  252. if (atom.size < 9)
  253. return 0;
  254. start = avio_rb64(pb);
  255. str_len = avio_r8(pb);
  256. if ((atom.size -= 9+str_len) < 0)
  257. return 0;
  258. avio_read(pb, str, str_len);
  259. str[str_len] = 0;
  260. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  261. }
  262. return 0;
  263. }
  264. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  265. {
  266. int64_t total_size = 0;
  267. MOVAtom a;
  268. int i;
  269. if (atom.size < 0)
  270. atom.size = INT64_MAX;
  271. while (total_size + 8 <= atom.size && !url_feof(pb)) {
  272. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  273. a.size = atom.size;
  274. a.type=0;
  275. if (atom.size >= 8) {
  276. a.size = avio_rb32(pb);
  277. a.type = avio_rl32(pb);
  278. total_size += 8;
  279. if (a.size == 1) { /* 64 bit extended size */
  280. a.size = avio_rb64(pb) - 8;
  281. total_size += 8;
  282. }
  283. }
  284. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  285. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  286. if (a.size == 0) {
  287. a.size = atom.size - total_size + 8;
  288. }
  289. a.size -= 8;
  290. if (a.size < 0)
  291. break;
  292. a.size = FFMIN(a.size, atom.size - total_size);
  293. for (i = 0; mov_default_parse_table[i].type; i++)
  294. if (mov_default_parse_table[i].type == a.type) {
  295. parse = mov_default_parse_table[i].parse;
  296. break;
  297. }
  298. // container is user data
  299. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  300. atom.type == MKTAG('i','l','s','t')))
  301. parse = mov_read_udta_string;
  302. if (!parse) { /* skip leaf atoms data */
  303. avio_skip(pb, a.size);
  304. } else {
  305. int64_t start_pos = avio_tell(pb);
  306. int64_t left;
  307. int err = parse(c, pb, a);
  308. if (err < 0)
  309. return err;
  310. if (c->found_moov && c->found_mdat &&
  311. (!pb->seekable || start_pos + a.size == avio_size(pb)))
  312. return 0;
  313. left = a.size - avio_tell(pb) + start_pos;
  314. if (left > 0) /* skip garbage at atom end */
  315. avio_skip(pb, left);
  316. else if (left < 0) {
  317. av_log(c->fc, AV_LOG_WARNING,
  318. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  319. (char*)&a.type, -left);
  320. avio_seek(pb, left, SEEK_CUR);
  321. }
  322. }
  323. total_size += a.size;
  324. }
  325. if (total_size < atom.size && atom.size < 0x7ffff)
  326. avio_skip(pb, atom.size - total_size);
  327. return 0;
  328. }
  329. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  330. {
  331. AVStream *st;
  332. MOVStreamContext *sc;
  333. int entries, i, j;
  334. if (c->fc->nb_streams < 1)
  335. return 0;
  336. st = c->fc->streams[c->fc->nb_streams-1];
  337. sc = st->priv_data;
  338. avio_rb32(pb); // version + flags
  339. entries = avio_rb32(pb);
  340. if (entries >= UINT_MAX / sizeof(*sc->drefs))
  341. return AVERROR_INVALIDDATA;
  342. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  343. if (!sc->drefs)
  344. return AVERROR(ENOMEM);
  345. sc->drefs_count = entries;
  346. for (i = 0; i < sc->drefs_count; i++) {
  347. MOVDref *dref = &sc->drefs[i];
  348. uint32_t size = avio_rb32(pb);
  349. int64_t next = avio_tell(pb) + size - 4;
  350. if (size < 12)
  351. return AVERROR_INVALIDDATA;
  352. dref->type = avio_rl32(pb);
  353. avio_rb32(pb); // version + flags
  354. av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  355. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  356. /* macintosh alias record */
  357. uint16_t volume_len, len;
  358. int16_t type;
  359. avio_skip(pb, 10);
  360. volume_len = avio_r8(pb);
  361. volume_len = FFMIN(volume_len, 27);
  362. avio_read(pb, dref->volume, 27);
  363. dref->volume[volume_len] = 0;
  364. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  365. avio_skip(pb, 12);
  366. len = avio_r8(pb);
  367. len = FFMIN(len, 63);
  368. avio_read(pb, dref->filename, 63);
  369. dref->filename[len] = 0;
  370. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  371. avio_skip(pb, 16);
  372. /* read next level up_from_alias/down_to_target */
  373. dref->nlvl_from = avio_rb16(pb);
  374. dref->nlvl_to = avio_rb16(pb);
  375. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  376. dref->nlvl_from, dref->nlvl_to);
  377. avio_skip(pb, 16);
  378. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  379. if(url_feof(pb))
  380. return AVERROR_EOF;
  381. type = avio_rb16(pb);
  382. len = avio_rb16(pb);
  383. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  384. if (len&1)
  385. len += 1;
  386. if (type == 2) { // absolute path
  387. av_free(dref->path);
  388. dref->path = av_mallocz(len+1);
  389. if (!dref->path)
  390. return AVERROR(ENOMEM);
  391. avio_read(pb, dref->path, len);
  392. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  393. len -= volume_len;
  394. memmove(dref->path, dref->path+volume_len, len);
  395. dref->path[len] = 0;
  396. }
  397. for (j = 0; j < len; j++)
  398. if (dref->path[j] == ':')
  399. dref->path[j] = '/';
  400. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  401. } else if (type == 0) { // directory name
  402. av_free(dref->dir);
  403. dref->dir = av_malloc(len+1);
  404. if (!dref->dir)
  405. return AVERROR(ENOMEM);
  406. avio_read(pb, dref->dir, len);
  407. dref->dir[len] = 0;
  408. for (j = 0; j < len; j++)
  409. if (dref->dir[j] == ':')
  410. dref->dir[j] = '/';
  411. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  412. } else
  413. avio_skip(pb, len);
  414. }
  415. }
  416. avio_seek(pb, next, SEEK_SET);
  417. }
  418. return 0;
  419. }
  420. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  421. {
  422. AVStream *st;
  423. uint32_t type;
  424. uint32_t av_unused ctype;
  425. int title_size;
  426. char *title_str;
  427. if (c->fc->nb_streams < 1) // meta before first trak
  428. return 0;
  429. st = c->fc->streams[c->fc->nb_streams-1];
  430. avio_r8(pb); /* version */
  431. avio_rb24(pb); /* flags */
  432. /* component type */
  433. ctype = avio_rl32(pb);
  434. type = avio_rl32(pb); /* component subtype */
  435. av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  436. av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
  437. if (type == MKTAG('v','i','d','e'))
  438. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  439. else if (type == MKTAG('s','o','u','n'))
  440. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  441. else if (type == MKTAG('m','1','a',' '))
  442. st->codec->codec_id = CODEC_ID_MP2;
  443. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  444. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  445. avio_rb32(pb); /* component manufacture */
  446. avio_rb32(pb); /* component flags */
  447. avio_rb32(pb); /* component flags mask */
  448. title_size = atom.size - 24;
  449. if (title_size > 0) {
  450. title_str = av_malloc(title_size + 1); /* Add null terminator */
  451. if (!title_str)
  452. return AVERROR(ENOMEM);
  453. avio_read(pb, title_str, title_size);
  454. title_str[title_size] = 0;
  455. av_dict_set(&st->metadata, "handler_name", title_str, 0);
  456. av_freep(&title_str);
  457. }
  458. return 0;
  459. }
  460. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
  461. {
  462. AVStream *st;
  463. int tag;
  464. if (fc->nb_streams < 1)
  465. return 0;
  466. st = fc->streams[fc->nb_streams-1];
  467. avio_rb32(pb); /* version + flags */
  468. ff_mp4_read_descr(fc, pb, &tag);
  469. if (tag == MP4ESDescrTag) {
  470. ff_mp4_parse_es_descr(pb, NULL);
  471. } else
  472. avio_rb16(pb); /* ID */
  473. ff_mp4_read_descr(fc, pb, &tag);
  474. if (tag == MP4DecConfigDescrTag)
  475. ff_mp4_read_dec_config_descr(fc, st, pb);
  476. return 0;
  477. }
  478. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  479. {
  480. return ff_mov_read_esds(c->fc, pb, atom);
  481. }
  482. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  483. {
  484. AVStream *st;
  485. int ac3info, acmod, lfeon, bsmod;
  486. if (c->fc->nb_streams < 1)
  487. return 0;
  488. st = c->fc->streams[c->fc->nb_streams-1];
  489. ac3info = avio_rb24(pb);
  490. bsmod = (ac3info >> 14) & 0x7;
  491. acmod = (ac3info >> 11) & 0x7;
  492. lfeon = (ac3info >> 10) & 0x1;
  493. st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  494. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  495. if (lfeon)
  496. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  497. st->codec->audio_service_type = bsmod;
  498. if (st->codec->channels > 1 && bsmod == 0x7)
  499. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  500. return 0;
  501. }
  502. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  503. {
  504. AVStream *st;
  505. uint8_t version;
  506. uint32_t flags, layout_tag, bitmap, num_descr, label_mask;
  507. int i;
  508. if (c->fc->nb_streams < 1)
  509. return 0;
  510. st = c->fc->streams[c->fc->nb_streams-1];
  511. if (atom.size < 16)
  512. return 0;
  513. version = avio_r8(pb);
  514. flags = avio_rb24(pb);
  515. layout_tag = avio_rb32(pb);
  516. bitmap = avio_rb32(pb);
  517. num_descr = avio_rb32(pb);
  518. if (atom.size < 16ULL + num_descr * 20ULL)
  519. return 0;
  520. av_dlog(c->fc, "chan: size=%" PRId64 " version=%u flags=%u layout=%u bitmap=%u num_descr=%u\n",
  521. atom.size, version, flags, layout_tag, bitmap, num_descr);
  522. label_mask = 0;
  523. for (i = 0; i < num_descr; i++) {
  524. uint32_t label, cflags;
  525. label = avio_rb32(pb); // mChannelLabel
  526. cflags = avio_rb32(pb); // mChannelFlags
  527. avio_rl32(pb); // mCoordinates[0]
  528. avio_rl32(pb); // mCoordinates[1]
  529. avio_rl32(pb); // mCoordinates[2]
  530. if (layout_tag == 0) {
  531. uint32_t mask_incr = ff_mov_get_channel_label(label);
  532. if (mask_incr == 0) {
  533. label_mask = 0;
  534. break;
  535. }
  536. label_mask |= mask_incr;
  537. }
  538. }
  539. if (layout_tag == 0)
  540. st->codec->channel_layout = label_mask;
  541. else
  542. st->codec->channel_layout = ff_mov_get_channel_layout(layout_tag, bitmap);
  543. return 0;
  544. }
  545. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  546. {
  547. AVStream *st;
  548. if (c->fc->nb_streams < 1)
  549. return 0;
  550. st = c->fc->streams[c->fc->nb_streams-1];
  551. ff_get_wav_header(pb, st->codec, atom.size);
  552. return 0;
  553. }
  554. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  555. {
  556. const int num = avio_rb32(pb);
  557. const int den = avio_rb32(pb);
  558. AVStream *st;
  559. if (c->fc->nb_streams < 1)
  560. return 0;
  561. st = c->fc->streams[c->fc->nb_streams-1];
  562. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  563. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  564. av_log(c->fc, AV_LOG_WARNING,
  565. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  566. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  567. num, den);
  568. } else if (den != 0) {
  569. st->sample_aspect_ratio.num = num;
  570. st->sample_aspect_ratio.den = den;
  571. }
  572. return 0;
  573. }
  574. /* this atom contains actual media data */
  575. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  576. {
  577. if (atom.size == 0) /* wrong one (MP4) */
  578. return 0;
  579. c->found_mdat=1;
  580. return 0; /* now go for moov */
  581. }
  582. /* read major brand, minor version and compatible brands and store them as metadata */
  583. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  584. {
  585. uint32_t minor_ver;
  586. int comp_brand_size;
  587. char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
  588. char* comp_brands_str;
  589. uint8_t type[5] = {0};
  590. avio_read(pb, type, 4);
  591. if (strcmp(type, "qt "))
  592. c->isom = 1;
  593. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  594. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  595. minor_ver = avio_rb32(pb); /* minor version */
  596. snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
  597. av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
  598. comp_brand_size = atom.size - 8;
  599. if (comp_brand_size < 0)
  600. return AVERROR_INVALIDDATA;
  601. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  602. if (!comp_brands_str)
  603. return AVERROR(ENOMEM);
  604. avio_read(pb, comp_brands_str, comp_brand_size);
  605. comp_brands_str[comp_brand_size] = 0;
  606. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  607. av_freep(&comp_brands_str);
  608. return 0;
  609. }
  610. /* this atom should contain all header atoms */
  611. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  612. {
  613. int ret;
  614. if ((ret = mov_read_default(c, pb, atom)) < 0)
  615. return ret;
  616. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  617. /* so we don't parse the whole file if over a network */
  618. c->found_moov=1;
  619. return 0; /* now go for mdat */
  620. }
  621. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  622. {
  623. c->fragment.moof_offset = avio_tell(pb) - 8;
  624. av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  625. return mov_read_default(c, pb, atom);
  626. }
  627. static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
  628. {
  629. char buffer[32];
  630. if (time) {
  631. struct tm *ptm;
  632. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  633. ptm = gmtime(&time);
  634. if (!ptm) return;
  635. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  636. av_dict_set(metadata, "creation_time", buffer, 0);
  637. }
  638. }
  639. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  640. {
  641. AVStream *st;
  642. MOVStreamContext *sc;
  643. int version;
  644. char language[4] = {0};
  645. unsigned lang;
  646. time_t creation_time;
  647. if (c->fc->nb_streams < 1)
  648. return 0;
  649. st = c->fc->streams[c->fc->nb_streams-1];
  650. sc = st->priv_data;
  651. if (sc->time_scale) {
  652. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  653. return AVERROR_INVALIDDATA;
  654. }
  655. version = avio_r8(pb);
  656. if (version > 1) {
  657. av_log_ask_for_sample(c, "unsupported version %d\n", version);
  658. return AVERROR_PATCHWELCOME;
  659. }
  660. avio_rb24(pb); /* flags */
  661. if (version == 1) {
  662. creation_time = avio_rb64(pb);
  663. avio_rb64(pb);
  664. } else {
  665. creation_time = avio_rb32(pb);
  666. avio_rb32(pb); /* modification time */
  667. }
  668. mov_metadata_creation_time(&st->metadata, creation_time);
  669. sc->time_scale = avio_rb32(pb);
  670. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  671. lang = avio_rb16(pb); /* language */
  672. if (ff_mov_lang_to_iso639(lang, language))
  673. av_dict_set(&st->metadata, "language", language, 0);
  674. avio_rb16(pb); /* quality */
  675. return 0;
  676. }
  677. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  678. {
  679. time_t creation_time;
  680. int version = avio_r8(pb); /* version */
  681. avio_rb24(pb); /* flags */
  682. if (version == 1) {
  683. creation_time = avio_rb64(pb);
  684. avio_rb64(pb);
  685. } else {
  686. creation_time = avio_rb32(pb);
  687. avio_rb32(pb); /* modification time */
  688. }
  689. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  690. c->time_scale = avio_rb32(pb); /* time scale */
  691. av_dlog(c->fc, "time scale = %i\n", c->time_scale);
  692. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  693. // set the AVCodecContext duration because the duration of individual tracks
  694. // may be inaccurate
  695. if (c->time_scale > 0 && !c->trex_data)
  696. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  697. avio_rb32(pb); /* preferred scale */
  698. avio_rb16(pb); /* preferred volume */
  699. avio_skip(pb, 10); /* reserved */
  700. avio_skip(pb, 36); /* display matrix */
  701. avio_rb32(pb); /* preview time */
  702. avio_rb32(pb); /* preview duration */
  703. avio_rb32(pb); /* poster time */
  704. avio_rb32(pb); /* selection time */
  705. avio_rb32(pb); /* selection duration */
  706. avio_rb32(pb); /* current time */
  707. avio_rb32(pb); /* next track ID */
  708. return 0;
  709. }
  710. static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  711. {
  712. AVStream *st;
  713. if (c->fc->nb_streams < 1)
  714. return 0;
  715. st = c->fc->streams[c->fc->nb_streams-1];
  716. if ((uint64_t)atom.size > (1<<30))
  717. return AVERROR_INVALIDDATA;
  718. // currently SVQ3 decoder expect full STSD header - so let's fake it
  719. // this should be fixed and just SMI header should be passed
  720. av_free(st->codec->extradata);
  721. st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
  722. if (!st->codec->extradata)
  723. return AVERROR(ENOMEM);
  724. st->codec->extradata_size = 0x5a + atom.size;
  725. memcpy(st->codec->extradata, "SVQ3", 4); // fake
  726. avio_read(pb, st->codec->extradata + 0x5a, atom.size);
  727. av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
  728. return 0;
  729. }
  730. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  731. {
  732. AVStream *st;
  733. int little_endian;
  734. if (c->fc->nb_streams < 1)
  735. return 0;
  736. st = c->fc->streams[c->fc->nb_streams-1];
  737. little_endian = avio_rb16(pb) & 0xFF;
  738. av_dlog(c->fc, "enda %d\n", little_endian);
  739. if (little_endian == 1) {
  740. switch (st->codec->codec_id) {
  741. case CODEC_ID_PCM_S24BE:
  742. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  743. break;
  744. case CODEC_ID_PCM_S32BE:
  745. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  746. break;
  747. case CODEC_ID_PCM_F32BE:
  748. st->codec->codec_id = CODEC_ID_PCM_F32LE;
  749. break;
  750. case CODEC_ID_PCM_F64BE:
  751. st->codec->codec_id = CODEC_ID_PCM_F64LE;
  752. break;
  753. default:
  754. break;
  755. }
  756. }
  757. return 0;
  758. }
  759. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  760. {
  761. AVStream *st;
  762. unsigned mov_field_order;
  763. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  764. if (c->fc->nb_streams < 1) // will happen with jp2 files
  765. return 0;
  766. st = c->fc->streams[c->fc->nb_streams-1];
  767. if (atom.size < 2)
  768. return AVERROR_INVALIDDATA;
  769. mov_field_order = avio_rb16(pb);
  770. if ((mov_field_order & 0xFF00) == 0x0100)
  771. decoded_field_order = AV_FIELD_PROGRESSIVE;
  772. else if ((mov_field_order & 0xFF00) == 0x0200) {
  773. switch (mov_field_order & 0xFF) {
  774. case 0x01: decoded_field_order = AV_FIELD_TT;
  775. break;
  776. case 0x06: decoded_field_order = AV_FIELD_BB;
  777. break;
  778. case 0x09: decoded_field_order = AV_FIELD_TB;
  779. break;
  780. case 0x0E: decoded_field_order = AV_FIELD_BT;
  781. break;
  782. }
  783. }
  784. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  785. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  786. }
  787. st->codec->field_order = decoded_field_order;
  788. return 0;
  789. }
  790. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  791. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  792. enum CodecID codec_id)
  793. {
  794. AVStream *st;
  795. uint64_t size;
  796. uint8_t *buf;
  797. if (c->fc->nb_streams < 1) // will happen with jp2 files
  798. return 0;
  799. st= c->fc->streams[c->fc->nb_streams-1];
  800. if (st->codec->codec_id != codec_id)
  801. return 0; /* unexpected codec_id - don't mess with extradata */
  802. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  803. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  804. return AVERROR_INVALIDDATA;
  805. buf= av_realloc(st->codec->extradata, size);
  806. if (!buf)
  807. return AVERROR(ENOMEM);
  808. st->codec->extradata= buf;
  809. buf+= st->codec->extradata_size;
  810. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  811. AV_WB32( buf , atom.size + 8);
  812. AV_WL32( buf + 4, atom.type);
  813. avio_read(pb, buf + 8, atom.size);
  814. return 0;
  815. }
  816. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  817. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  818. {
  819. return mov_read_extradata(c, pb, atom, CODEC_ID_ALAC);
  820. }
  821. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  822. {
  823. return mov_read_extradata(c, pb, atom, CODEC_ID_AVS);
  824. }
  825. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  826. {
  827. return mov_read_extradata(c, pb, atom, CODEC_ID_JPEG2000);
  828. }
  829. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  830. {
  831. AVStream *st;
  832. if (c->fc->nb_streams < 1)
  833. return 0;
  834. st = c->fc->streams[c->fc->nb_streams-1];
  835. if ((uint64_t)atom.size > (1<<30))
  836. return AVERROR_INVALIDDATA;
  837. if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
  838. // pass all frma atom to codec, needed at least for QDMC and QDM2
  839. av_free(st->codec->extradata);
  840. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  841. if (!st->codec->extradata)
  842. return AVERROR(ENOMEM);
  843. st->codec->extradata_size = atom.size;
  844. avio_read(pb, st->codec->extradata, atom.size);
  845. } else if (atom.size > 8) { /* to read frma, esds atoms */
  846. int ret;
  847. if ((ret = mov_read_default(c, pb, atom)) < 0)
  848. return ret;
  849. } else
  850. avio_skip(pb, atom.size);
  851. return 0;
  852. }
  853. /**
  854. * This function reads atom content and puts data in extradata without tag
  855. * nor size unlike mov_read_extradata.
  856. */
  857. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  858. {
  859. AVStream *st;
  860. if (c->fc->nb_streams < 1)
  861. return 0;
  862. st = c->fc->streams[c->fc->nb_streams-1];
  863. if ((uint64_t)atom.size > (1<<30))
  864. return AVERROR_INVALIDDATA;
  865. if (atom.size >= 10) {
  866. // Broken files created by legacy versions of Libav and FFmpeg will
  867. // wrap a whole fiel atom inside of a glbl atom.
  868. unsigned size = avio_rb32(pb);
  869. unsigned type = avio_rl32(pb);
  870. avio_seek(pb, -8, SEEK_CUR);
  871. if (type == MKTAG('f','i','e','l') && size == atom.size)
  872. return mov_read_default(c, pb, atom);
  873. }
  874. av_free(st->codec->extradata);
  875. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  876. if (!st->codec->extradata)
  877. return AVERROR(ENOMEM);
  878. st->codec->extradata_size = atom.size;
  879. avio_read(pb, st->codec->extradata, atom.size);
  880. return 0;
  881. }
  882. /**
  883. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  884. * but can have extradata appended at the end after the 40 bytes belonging
  885. * to the struct.
  886. */
  887. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  888. {
  889. AVStream *st;
  890. if (c->fc->nb_streams < 1)
  891. return 0;
  892. if (atom.size <= 40)
  893. return 0;
  894. st = c->fc->streams[c->fc->nb_streams-1];
  895. if ((uint64_t)atom.size > (1<<30))
  896. return AVERROR_INVALIDDATA;
  897. av_free(st->codec->extradata);
  898. st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
  899. if (!st->codec->extradata)
  900. return AVERROR(ENOMEM);
  901. st->codec->extradata_size = atom.size - 40;
  902. avio_skip(pb, 40);
  903. avio_read(pb, st->codec->extradata, atom.size - 40);
  904. return 0;
  905. }
  906. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  907. {
  908. AVStream *st;
  909. MOVStreamContext *sc;
  910. unsigned int i, entries;
  911. if (c->fc->nb_streams < 1)
  912. return 0;
  913. st = c->fc->streams[c->fc->nb_streams-1];
  914. sc = st->priv_data;
  915. avio_r8(pb); /* version */
  916. avio_rb24(pb); /* flags */
  917. entries = avio_rb32(pb);
  918. if (!entries)
  919. return 0;
  920. if (entries >= UINT_MAX/sizeof(int64_t))
  921. return AVERROR_INVALIDDATA;
  922. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  923. if (!sc->chunk_offsets)
  924. return AVERROR(ENOMEM);
  925. sc->chunk_count = entries;
  926. if (atom.type == MKTAG('s','t','c','o'))
  927. for (i=0; i<entries; i++)
  928. sc->chunk_offsets[i] = avio_rb32(pb);
  929. else if (atom.type == MKTAG('c','o','6','4'))
  930. for (i=0; i<entries; i++)
  931. sc->chunk_offsets[i] = avio_rb64(pb);
  932. else
  933. return AVERROR_INVALIDDATA;
  934. return 0;
  935. }
  936. /**
  937. * Compute codec id for 'lpcm' tag.
  938. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  939. */
  940. enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  941. {
  942. if (flags & 1) { // floating point
  943. if (flags & 2) { // big endian
  944. if (bps == 32) return CODEC_ID_PCM_F32BE;
  945. else if (bps == 64) return CODEC_ID_PCM_F64BE;
  946. } else {
  947. if (bps == 32) return CODEC_ID_PCM_F32LE;
  948. else if (bps == 64) return CODEC_ID_PCM_F64LE;
  949. }
  950. } else {
  951. if (flags & 2) {
  952. if (bps == 8)
  953. // signed integer
  954. if (flags & 4) return CODEC_ID_PCM_S8;
  955. else return CODEC_ID_PCM_U8;
  956. else if (bps == 16) return CODEC_ID_PCM_S16BE;
  957. else if (bps == 24) return CODEC_ID_PCM_S24BE;
  958. else if (bps == 32) return CODEC_ID_PCM_S32BE;
  959. } else {
  960. if (bps == 8)
  961. if (flags & 4) return CODEC_ID_PCM_S8;
  962. else return CODEC_ID_PCM_U8;
  963. else if (bps == 16) return CODEC_ID_PCM_S16LE;
  964. else if (bps == 24) return CODEC_ID_PCM_S24LE;
  965. else if (bps == 32) return CODEC_ID_PCM_S32LE;
  966. }
  967. }
  968. return CODEC_ID_NONE;
  969. }
  970. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  971. {
  972. AVStream *st;
  973. MOVStreamContext *sc;
  974. int j, pseudo_stream_id;
  975. if (c->fc->nb_streams < 1)
  976. return 0;
  977. st = c->fc->streams[c->fc->nb_streams-1];
  978. sc = st->priv_data;
  979. for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
  980. //Parsing Sample description table
  981. enum CodecID id;
  982. int dref_id = 1;
  983. MOVAtom a = { AV_RL32("stsd") };
  984. int64_t start_pos = avio_tell(pb);
  985. int size = avio_rb32(pb); /* size */
  986. uint32_t format = avio_rl32(pb); /* data format */
  987. if (size >= 16) {
  988. avio_rb32(pb); /* reserved */
  989. avio_rb16(pb); /* reserved */
  990. dref_id = avio_rb16(pb);
  991. }else if (size <= 0){
  992. av_log(c->fc, AV_LOG_ERROR, "invalid size %d in stsd\n", size);
  993. return -1;
  994. }
  995. if (st->codec->codec_tag &&
  996. st->codec->codec_tag != format &&
  997. (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
  998. : st->codec->codec_tag != MKTAG('j','p','e','g'))
  999. ){
  1000. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1001. * export it as a separate AVStream but this needs a few changes
  1002. * in the MOV demuxer, patch welcome. */
  1003. multiple_stsd:
  1004. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1005. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  1006. continue;
  1007. }
  1008. /* we cannot demux concatenated h264 streams because of different extradata */
  1009. if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
  1010. goto multiple_stsd;
  1011. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1012. sc->dref_id= dref_id;
  1013. st->codec->codec_tag = format;
  1014. id = ff_codec_get_id(codec_movaudio_tags, format);
  1015. if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
  1016. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
  1017. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1018. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1019. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
  1020. format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
  1021. id = ff_codec_get_id(codec_movvideo_tags, format);
  1022. if (id <= 0)
  1023. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1024. if (id > 0)
  1025. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1026. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){
  1027. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1028. if (id > 0)
  1029. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1030. }
  1031. }
  1032. av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
  1033. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1034. (format >> 24) & 0xff, st->codec->codec_type);
  1035. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1036. unsigned int color_depth, len;
  1037. int color_greyscale;
  1038. st->codec->codec_id = id;
  1039. avio_rb16(pb); /* version */
  1040. avio_rb16(pb); /* revision level */
  1041. avio_rb32(pb); /* vendor */
  1042. avio_rb32(pb); /* temporal quality */
  1043. avio_rb32(pb); /* spatial quality */
  1044. st->codec->width = avio_rb16(pb); /* width */
  1045. st->codec->height = avio_rb16(pb); /* height */
  1046. avio_rb32(pb); /* horiz resolution */
  1047. avio_rb32(pb); /* vert resolution */
  1048. avio_rb32(pb); /* data size, always 0 */
  1049. avio_rb16(pb); /* frames per samples */
  1050. len = avio_r8(pb); /* codec name, pascal string */
  1051. if (len > 31)
  1052. len = 31;
  1053. mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
  1054. if (len < 31)
  1055. avio_skip(pb, 31 - len);
  1056. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1057. if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
  1058. st->codec->codec_tag=MKTAG('I', '4', '2', '0');
  1059. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1060. st->codec->color_table_id = avio_rb16(pb); /* colortable id */
  1061. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1062. st->codec->bits_per_coded_sample, st->codec->color_table_id);
  1063. /* figure out the palette situation */
  1064. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1065. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1066. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1067. if ((color_depth == 2) || (color_depth == 4) ||
  1068. (color_depth == 8)) {
  1069. /* for palette traversal */
  1070. unsigned int color_start, color_count, color_end;
  1071. unsigned char a, r, g, b;
  1072. if (color_greyscale) {
  1073. int color_index, color_dec;
  1074. /* compute the greyscale palette */
  1075. st->codec->bits_per_coded_sample = color_depth;
  1076. color_count = 1 << color_depth;
  1077. color_index = 255;
  1078. color_dec = 256 / (color_count - 1);
  1079. for (j = 0; j < color_count; j++) {
  1080. if (id == CODEC_ID_CINEPAK){
  1081. r = g = b = color_count - 1 - color_index;
  1082. }else
  1083. r = g = b = color_index;
  1084. sc->palette[j] =
  1085. (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1086. color_index -= color_dec;
  1087. if (color_index < 0)
  1088. color_index = 0;
  1089. }
  1090. } else if (st->codec->color_table_id) {
  1091. const uint8_t *color_table;
  1092. /* if flag bit 3 is set, use the default palette */
  1093. color_count = 1 << color_depth;
  1094. if (color_depth == 2)
  1095. color_table = ff_qt_default_palette_4;
  1096. else if (color_depth == 4)
  1097. color_table = ff_qt_default_palette_16;
  1098. else
  1099. color_table = ff_qt_default_palette_256;
  1100. for (j = 0; j < color_count; j++) {
  1101. r = color_table[j * 3 + 0];
  1102. g = color_table[j * 3 + 1];
  1103. b = color_table[j * 3 + 2];
  1104. sc->palette[j] =
  1105. (0xFFU << 24) | (r << 16) | (g << 8) | (b);
  1106. }
  1107. } else {
  1108. /* load the palette from the file */
  1109. color_start = avio_rb32(pb);
  1110. color_count = avio_rb16(pb);
  1111. color_end = avio_rb16(pb);
  1112. if ((color_start <= 255) &&
  1113. (color_end <= 255)) {
  1114. for (j = color_start; j <= color_end; j++) {
  1115. /* each A, R, G, or B component is 16 bits;
  1116. * only use the top 8 bits */
  1117. a = avio_r8(pb);
  1118. avio_r8(pb);
  1119. r = avio_r8(pb);
  1120. avio_r8(pb);
  1121. g = avio_r8(pb);
  1122. avio_r8(pb);
  1123. b = avio_r8(pb);
  1124. avio_r8(pb);
  1125. sc->palette[j] =
  1126. (a << 24 ) | (r << 16) | (g << 8) | (b);
  1127. }
  1128. }
  1129. }
  1130. sc->has_palette = 1;
  1131. }
  1132. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1133. int bits_per_sample, flags;
  1134. uint16_t version = avio_rb16(pb);
  1135. st->codec->codec_id = id;
  1136. avio_rb16(pb); /* revision level */
  1137. avio_rb32(pb); /* vendor */
  1138. st->codec->channels = avio_rb16(pb); /* channel count */
  1139. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1140. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1141. sc->audio_cid = avio_rb16(pb);
  1142. avio_rb16(pb); /* packet size = 0 */
  1143. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1144. //Read QT version 1 fields. In version 0 these do not exist.
  1145. av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
  1146. if (!c->isom) {
  1147. if (version==1) {
  1148. sc->samples_per_frame = avio_rb32(pb);
  1149. avio_rb32(pb); /* bytes per packet */
  1150. sc->bytes_per_frame = avio_rb32(pb);
  1151. avio_rb32(pb); /* bytes per sample */
  1152. } else if (version==2) {
  1153. avio_rb32(pb); /* sizeof struct only */
  1154. st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
  1155. st->codec->channels = avio_rb32(pb);
  1156. avio_rb32(pb); /* always 0x7F000000 */
  1157. st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
  1158. flags = avio_rb32(pb); /* lpcm format specific flag */
  1159. sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
  1160. sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
  1161. if (format == MKTAG('l','p','c','m'))
  1162. st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  1163. }
  1164. }
  1165. switch (st->codec->codec_id) {
  1166. case CODEC_ID_PCM_S8:
  1167. case CODEC_ID_PCM_U8:
  1168. if (st->codec->bits_per_coded_sample == 16)
  1169. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  1170. break;
  1171. case CODEC_ID_PCM_S16LE:
  1172. case CODEC_ID_PCM_S16BE:
  1173. if (st->codec->bits_per_coded_sample == 8)
  1174. st->codec->codec_id = CODEC_ID_PCM_S8;
  1175. else if (st->codec->bits_per_coded_sample == 24)
  1176. st->codec->codec_id =
  1177. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  1178. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  1179. break;
  1180. /* set values for old format before stsd version 1 appeared */
  1181. case CODEC_ID_MACE3:
  1182. sc->samples_per_frame = 6;
  1183. sc->bytes_per_frame = 2*st->codec->channels;
  1184. break;
  1185. case CODEC_ID_MACE6:
  1186. sc->samples_per_frame = 6;
  1187. sc->bytes_per_frame = 1*st->codec->channels;
  1188. break;
  1189. case CODEC_ID_ADPCM_IMA_QT:
  1190. sc->samples_per_frame = 64;
  1191. sc->bytes_per_frame = 34*st->codec->channels;
  1192. break;
  1193. case CODEC_ID_GSM:
  1194. sc->samples_per_frame = 160;
  1195. sc->bytes_per_frame = 33;
  1196. break;
  1197. default:
  1198. break;
  1199. }
  1200. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1201. if (bits_per_sample) {
  1202. st->codec->bits_per_coded_sample = bits_per_sample;
  1203. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1204. }
  1205. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1206. // ttxt stsd contains display flags, justification, background
  1207. // color, fonts, and default styles, so fake an atom to read it
  1208. MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
  1209. if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
  1210. mov_read_glbl(c, pb, fake_atom);
  1211. st->codec->codec_id= id;
  1212. st->codec->width = sc->width;
  1213. st->codec->height = sc->height;
  1214. } else {
  1215. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1216. int val;
  1217. avio_rb32(pb); /* reserved */
  1218. val = avio_rb32(pb); /* flags */
  1219. if (val & 1)
  1220. st->codec->flags2 |= CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1221. avio_rb32(pb); /* time scale */
  1222. avio_rb32(pb); /* frame duration */
  1223. st->codec->time_base.den = avio_r8(pb); /* number of frame */
  1224. st->codec->time_base.num = 1;
  1225. }
  1226. /* other codec type, just skip (rtp, mp4s, ...) */
  1227. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  1228. }
  1229. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  1230. a.size = size - (avio_tell(pb) - start_pos);
  1231. if (a.size > 8) {
  1232. int ret;
  1233. if ((ret = mov_read_default(c, pb, a)) < 0)
  1234. return ret;
  1235. } else if (a.size > 0)
  1236. avio_skip(pb, a.size);
  1237. }
  1238. if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  1239. st->codec->sample_rate= sc->time_scale;
  1240. /* special codec parameters handling */
  1241. switch (st->codec->codec_id) {
  1242. #if CONFIG_DV_DEMUXER
  1243. case CODEC_ID_DVAUDIO:
  1244. c->dv_fctx = avformat_alloc_context();
  1245. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1246. if (!c->dv_demux) {
  1247. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1248. return AVERROR(ENOMEM);
  1249. }
  1250. sc->dv_audio_container = 1;
  1251. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  1252. break;
  1253. #endif
  1254. /* no ifdef since parameters are always those */
  1255. case CODEC_ID_QCELP:
  1256. // force sample rate for qcelp when not stored in mov
  1257. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1258. st->codec->sample_rate = 8000;
  1259. st->codec->frame_size= 160;
  1260. st->codec->channels= 1; /* really needed */
  1261. break;
  1262. case CODEC_ID_AMR_NB:
  1263. st->codec->channels= 1; /* really needed */
  1264. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1265. st->codec->sample_rate = 8000;
  1266. /* force frame_size, too, samples_per_frame isn't always set properly */
  1267. st->codec->frame_size = 160;
  1268. break;
  1269. case CODEC_ID_AMR_WB:
  1270. st->codec->channels = 1;
  1271. st->codec->sample_rate = 16000;
  1272. st->codec->frame_size = 320;
  1273. break;
  1274. case CODEC_ID_MP2:
  1275. case CODEC_ID_MP3:
  1276. st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  1277. st->need_parsing = AVSTREAM_PARSE_FULL;
  1278. break;
  1279. case CODEC_ID_GSM:
  1280. case CODEC_ID_ADPCM_MS:
  1281. case CODEC_ID_ADPCM_IMA_WAV:
  1282. st->codec->frame_size = sc->samples_per_frame;
  1283. st->codec->block_align = sc->bytes_per_frame;
  1284. break;
  1285. case CODEC_ID_ALAC:
  1286. if (st->codec->extradata_size == 36) {
  1287. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  1288. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1289. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1290. }
  1291. break;
  1292. case CODEC_ID_AC3:
  1293. st->need_parsing = AVSTREAM_PARSE_FULL;
  1294. break;
  1295. case CODEC_ID_MPEG1VIDEO:
  1296. st->need_parsing = AVSTREAM_PARSE_FULL;
  1297. break;
  1298. default:
  1299. break;
  1300. }
  1301. return 0;
  1302. }
  1303. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1304. {
  1305. int entries;
  1306. avio_r8(pb); /* version */
  1307. avio_rb24(pb); /* flags */
  1308. entries = avio_rb32(pb);
  1309. return ff_mov_read_stsd_entries(c, pb, entries);
  1310. }
  1311. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1312. {
  1313. AVStream *st;
  1314. MOVStreamContext *sc;
  1315. unsigned int i, entries;
  1316. if (c->fc->nb_streams < 1)
  1317. return 0;
  1318. st = c->fc->streams[c->fc->nb_streams-1];
  1319. sc = st->priv_data;
  1320. avio_r8(pb); /* version */
  1321. avio_rb24(pb); /* flags */
  1322. entries = avio_rb32(pb);
  1323. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1324. if (!entries)
  1325. return 0;
  1326. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1327. return AVERROR_INVALIDDATA;
  1328. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1329. if (!sc->stsc_data)
  1330. return AVERROR(ENOMEM);
  1331. sc->stsc_count = entries;
  1332. for (i=0; i<entries; i++) {
  1333. sc->stsc_data[i].first = avio_rb32(pb);
  1334. sc->stsc_data[i].count = avio_rb32(pb);
  1335. sc->stsc_data[i].id = avio_rb32(pb);
  1336. }
  1337. return 0;
  1338. }
  1339. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1340. {
  1341. AVStream *st;
  1342. MOVStreamContext *sc;
  1343. unsigned i, entries;
  1344. if (c->fc->nb_streams < 1)
  1345. return 0;
  1346. st = c->fc->streams[c->fc->nb_streams-1];
  1347. sc = st->priv_data;
  1348. avio_rb32(pb); // version + flags
  1349. entries = avio_rb32(pb);
  1350. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1351. return AVERROR_INVALIDDATA;
  1352. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1353. if (!sc->stps_data)
  1354. return AVERROR(ENOMEM);
  1355. sc->stps_count = entries;
  1356. for (i = 0; i < entries; i++) {
  1357. sc->stps_data[i] = avio_rb32(pb);
  1358. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1359. }
  1360. return 0;
  1361. }
  1362. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1363. {
  1364. AVStream *st;
  1365. MOVStreamContext *sc;
  1366. unsigned int i, entries;
  1367. if (c->fc->nb_streams < 1)
  1368. return 0;
  1369. st = c->fc->streams[c->fc->nb_streams-1];
  1370. sc = st->priv_data;
  1371. avio_r8(pb); /* version */
  1372. avio_rb24(pb); /* flags */
  1373. entries = avio_rb32(pb);
  1374. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1375. if (!entries)
  1376. return 0;
  1377. if (entries >= UINT_MAX / sizeof(int))
  1378. return AVERROR_INVALIDDATA;
  1379. av_freep(&sc->keyframes);
  1380. sc->keyframes = av_malloc(entries * sizeof(int));
  1381. if (!sc->keyframes)
  1382. return AVERROR(ENOMEM);
  1383. sc->keyframe_count = entries;
  1384. for (i=0; i<entries; i++) {
  1385. sc->keyframes[i] = avio_rb32(pb);
  1386. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1387. }
  1388. return 0;
  1389. }
  1390. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1391. {
  1392. AVStream *st;
  1393. MOVStreamContext *sc;
  1394. unsigned int i, entries, sample_size, field_size, num_bytes;
  1395. GetBitContext gb;
  1396. unsigned char* buf;
  1397. if (c->fc->nb_streams < 1)
  1398. return 0;
  1399. st = c->fc->streams[c->fc->nb_streams-1];
  1400. sc = st->priv_data;
  1401. avio_r8(pb); /* version */
  1402. avio_rb24(pb); /* flags */
  1403. if (atom.type == MKTAG('s','t','s','z')) {
  1404. sample_size = avio_rb32(pb);
  1405. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1406. sc->sample_size = sample_size;
  1407. field_size = 32;
  1408. } else {
  1409. sample_size = 0;
  1410. avio_rb24(pb); /* reserved */
  1411. field_size = avio_r8(pb);
  1412. }
  1413. entries = avio_rb32(pb);
  1414. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1415. sc->sample_count = entries;
  1416. if (sample_size)
  1417. return 0;
  1418. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1419. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1420. return AVERROR_INVALIDDATA;
  1421. }
  1422. if (!entries)
  1423. return 0;
  1424. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1425. return AVERROR_INVALIDDATA;
  1426. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1427. if (!sc->sample_sizes)
  1428. return AVERROR(ENOMEM);
  1429. num_bytes = (entries*field_size+4)>>3;
  1430. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1431. if (!buf) {
  1432. av_freep(&sc->sample_sizes);
  1433. return AVERROR(ENOMEM);
  1434. }
  1435. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1436. av_freep(&sc->sample_sizes);
  1437. av_free(buf);
  1438. return AVERROR_INVALIDDATA;
  1439. }
  1440. init_get_bits(&gb, buf, 8*num_bytes);
  1441. for (i = 0; i < entries; i++) {
  1442. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1443. sc->data_size += sc->sample_sizes[i];
  1444. }
  1445. av_free(buf);
  1446. return 0;
  1447. }
  1448. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1449. {
  1450. AVStream *st;
  1451. MOVStreamContext *sc;
  1452. unsigned int i, entries;
  1453. int64_t duration=0;
  1454. int64_t total_sample_count=0;
  1455. if (c->fc->nb_streams < 1)
  1456. return 0;
  1457. st = c->fc->streams[c->fc->nb_streams-1];
  1458. sc = st->priv_data;
  1459. avio_r8(pb); /* version */
  1460. avio_rb24(pb); /* flags */
  1461. entries = avio_rb32(pb);
  1462. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1463. c->fc->nb_streams-1, entries);
  1464. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1465. return -1;
  1466. av_free(sc->stts_data);
  1467. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1468. if (!sc->stts_data)
  1469. return AVERROR(ENOMEM);
  1470. sc->stts_count = entries;
  1471. for (i=0; i<entries; i++) {
  1472. int sample_duration;
  1473. int sample_count;
  1474. sample_count=avio_rb32(pb);
  1475. sample_duration = avio_rb32(pb);
  1476. /* sample_duration < 0 is invalid based on the spec */
  1477. if (sample_duration < 0) {
  1478. av_log(c->fc, AV_LOG_ERROR, "Invalid SampleDelta in STTS %d\n", sample_duration);
  1479. sample_duration = 1;
  1480. }
  1481. if (sample_count < 0) {
  1482. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1483. return AVERROR_INVALIDDATA;
  1484. }
  1485. sc->stts_data[i].count= sample_count;
  1486. sc->stts_data[i].duration= sample_duration;
  1487. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1488. sample_count, sample_duration);
  1489. duration+=(int64_t)sample_duration*sample_count;
  1490. total_sample_count+=sample_count;
  1491. }
  1492. st->nb_frames= total_sample_count;
  1493. if (duration)
  1494. st->duration= duration;
  1495. return 0;
  1496. }
  1497. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1498. {
  1499. AVStream *st;
  1500. MOVStreamContext *sc;
  1501. unsigned int i, entries;
  1502. if (c->fc->nb_streams < 1)
  1503. return 0;
  1504. st = c->fc->streams[c->fc->nb_streams-1];
  1505. sc = st->priv_data;
  1506. avio_r8(pb); /* version */
  1507. avio_rb24(pb); /* flags */
  1508. entries = avio_rb32(pb);
  1509. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1510. if (!entries)
  1511. return 0;
  1512. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1513. return AVERROR_INVALIDDATA;
  1514. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1515. if (!sc->ctts_data)
  1516. return AVERROR(ENOMEM);
  1517. sc->ctts_count = entries;
  1518. for (i=0; i<entries; i++) {
  1519. int count =avio_rb32(pb);
  1520. int duration =avio_rb32(pb);
  1521. sc->ctts_data[i].count = count;
  1522. sc->ctts_data[i].duration= duration;
  1523. if (duration < 0 && i+2<entries)
  1524. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1525. }
  1526. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1527. return 0;
  1528. }
  1529. static void mov_build_index(MOVContext *mov, AVStream *st)
  1530. {
  1531. MOVStreamContext *sc = st->priv_data;
  1532. int64_t current_offset;
  1533. int64_t current_dts = 0;
  1534. unsigned int stts_index = 0;
  1535. unsigned int stsc_index = 0;
  1536. unsigned int stss_index = 0;
  1537. unsigned int stps_index = 0;
  1538. unsigned int i, j;
  1539. uint64_t stream_size = 0;
  1540. AVIndexEntry *mem;
  1541. /* adjust first dts according to edit list */
  1542. if ((sc->empty_duration || sc->start_time) && mov->time_scale > 0) {
  1543. if (sc->empty_duration)
  1544. sc->empty_duration = av_rescale(sc->empty_duration, sc->time_scale, mov->time_scale);
  1545. sc->time_offset = sc->start_time - sc->empty_duration;
  1546. current_dts = -sc->time_offset;
  1547. if (sc->ctts_data && sc->stts_data &&
  1548. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1549. /* more than 16 frames delay, dts are likely wrong
  1550. this happens with files created by iMovie */
  1551. sc->wrong_dts = 1;
  1552. st->codec->has_b_frames = 1;
  1553. }
  1554. }
  1555. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1556. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1557. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1558. unsigned int current_sample = 0;
  1559. unsigned int stts_sample = 0;
  1560. unsigned int sample_size;
  1561. unsigned int distance = 0;
  1562. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1563. current_dts -= sc->dts_shift;
  1564. if (!sc->sample_count)
  1565. return;
  1566. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1567. return;
  1568. mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
  1569. if (!mem)
  1570. return;
  1571. st->index_entries = mem;
  1572. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1573. for (i = 0; i < sc->chunk_count; i++) {
  1574. current_offset = sc->chunk_offsets[i];
  1575. while (stsc_index + 1 < sc->stsc_count &&
  1576. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1577. stsc_index++;
  1578. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1579. int keyframe = 0;
  1580. if (current_sample >= sc->sample_count) {
  1581. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1582. return;
  1583. }
  1584. if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
  1585. keyframe = 1;
  1586. if (stss_index + 1 < sc->keyframe_count)
  1587. stss_index++;
  1588. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1589. keyframe = 1;
  1590. if (stps_index + 1 < sc->stps_count)
  1591. stps_index++;
  1592. }
  1593. if (keyframe)
  1594. distance = 0;
  1595. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1596. if (sc->pseudo_stream_id == -1 ||
  1597. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1598. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1599. e->pos = current_offset;
  1600. e->timestamp = current_dts;
  1601. e->size = sample_size;
  1602. e->min_distance = distance;
  1603. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1604. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1605. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1606. current_offset, current_dts, sample_size, distance, keyframe);
  1607. }
  1608. current_offset += sample_size;
  1609. stream_size += sample_size;
  1610. current_dts += sc->stts_data[stts_index].duration;
  1611. distance++;
  1612. stts_sample++;
  1613. current_sample++;
  1614. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1615. stts_sample = 0;
  1616. stts_index++;
  1617. }
  1618. }
  1619. }
  1620. if (st->duration > 0)
  1621. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1622. } else {
  1623. unsigned chunk_samples, total = 0;
  1624. // compute total chunk count
  1625. for (i = 0; i < sc->stsc_count; i++) {
  1626. unsigned count, chunk_count;
  1627. chunk_samples = sc->stsc_data[i].count;
  1628. if (i != sc->stsc_count - 1 &&
  1629. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1630. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1631. return;
  1632. }
  1633. if (sc->samples_per_frame >= 160) { // gsm
  1634. count = chunk_samples / sc->samples_per_frame;
  1635. } else if (sc->samples_per_frame > 1) {
  1636. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1637. count = (chunk_samples+samples-1) / samples;
  1638. } else {
  1639. count = (chunk_samples+1023) / 1024;
  1640. }
  1641. if (i < sc->stsc_count - 1)
  1642. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1643. else
  1644. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1645. total += chunk_count * count;
  1646. }
  1647. av_dlog(mov->fc, "chunk count %d\n", total);
  1648. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1649. return;
  1650. mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
  1651. if (!mem)
  1652. return;
  1653. st->index_entries = mem;
  1654. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  1655. // populate index
  1656. for (i = 0; i < sc->chunk_count; i++) {
  1657. current_offset = sc->chunk_offsets[i];
  1658. if (stsc_index + 1 < sc->stsc_count &&
  1659. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1660. stsc_index++;
  1661. chunk_samples = sc->stsc_data[stsc_index].count;
  1662. while (chunk_samples > 0) {
  1663. AVIndexEntry *e;
  1664. unsigned size, samples;
  1665. if (sc->samples_per_frame >= 160) { // gsm
  1666. samples = sc->samples_per_frame;
  1667. size = sc->bytes_per_frame;
  1668. } else {
  1669. if (sc->samples_per_frame > 1) {
  1670. samples = FFMIN((1024 / sc->samples_per_frame)*
  1671. sc->samples_per_frame, chunk_samples);
  1672. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1673. } else {
  1674. samples = FFMIN(1024, chunk_samples);
  1675. size = samples * sc->sample_size;
  1676. }
  1677. }
  1678. if (st->nb_index_entries >= total) {
  1679. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1680. return;
  1681. }
  1682. e = &st->index_entries[st->nb_index_entries++];
  1683. e->pos = current_offset;
  1684. e->timestamp = current_dts;
  1685. e->size = size;
  1686. e->min_distance = 0;
  1687. e->flags = AVINDEX_KEYFRAME;
  1688. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1689. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1690. size, samples);
  1691. current_offset += size;
  1692. current_dts += samples;
  1693. chunk_samples -= samples;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref,
  1699. AVIOInterruptCB *int_cb, int use_absolute_path, AVFormatContext *fc)
  1700. {
  1701. /* try relative path, we do not try the absolute because it can leak information about our
  1702. system to an attacker */
  1703. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1704. char filename[1024];
  1705. const char *src_path;
  1706. int i, l;
  1707. /* find a source dir */
  1708. src_path = strrchr(src, '/');
  1709. if (src_path)
  1710. src_path++;
  1711. else
  1712. src_path = src;
  1713. /* find a next level down to target */
  1714. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1715. if (ref->path[l] == '/') {
  1716. if (i == ref->nlvl_to - 1)
  1717. break;
  1718. else
  1719. i++;
  1720. }
  1721. /* compose filename if next level down to target was found */
  1722. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1723. memcpy(filename, src, src_path - src);
  1724. filename[src_path - src] = 0;
  1725. for (i = 1; i < ref->nlvl_from; i++)
  1726. av_strlcat(filename, "../", 1024);
  1727. av_strlcat(filename, ref->path + l + 1, 1024);
  1728. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  1729. return 0;
  1730. }
  1731. } else if (use_absolute_path) {
  1732. av_log(fc, AV_LOG_WARNING, "Using absolute path on user request, "
  1733. "this is a possible security issue\n");
  1734. if (!avio_open2(pb, ref->path, AVIO_FLAG_READ, int_cb, NULL))
  1735. return 0;
  1736. }
  1737. return AVERROR(ENOENT);
  1738. }
  1739. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1740. {
  1741. AVStream *st;
  1742. MOVStreamContext *sc;
  1743. int ret;
  1744. st = avformat_new_stream(c->fc, NULL);
  1745. if (!st) return AVERROR(ENOMEM);
  1746. st->id = c->fc->nb_streams;
  1747. sc = av_mallocz(sizeof(MOVStreamContext));
  1748. if (!sc) return AVERROR(ENOMEM);
  1749. st->priv_data = sc;
  1750. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1751. sc->ffindex = st->index;
  1752. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1753. return ret;
  1754. /* sanity checks */
  1755. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1756. (!sc->sample_size && !sc->sample_count))) {
  1757. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1758. st->index);
  1759. return 0;
  1760. }
  1761. if (sc->time_scale <= 0) {
  1762. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1763. sc->time_scale = c->time_scale;
  1764. if (sc->time_scale <= 0)
  1765. sc->time_scale = 1;
  1766. }
  1767. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  1768. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1769. !st->codec->frame_size && sc->stts_count == 1) {
  1770. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1771. st->codec->sample_rate, sc->time_scale);
  1772. av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
  1773. }
  1774. mov_build_index(c, st);
  1775. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1776. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1777. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback,
  1778. c->use_absolute_path, c->fc) < 0)
  1779. av_log(c->fc, AV_LOG_ERROR,
  1780. "stream %d, error opening alias: path='%s', dir='%s', "
  1781. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1782. st->index, dref->path, dref->dir, dref->filename,
  1783. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1784. } else
  1785. sc->pb = c->fc->pb;
  1786. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1787. if (!st->sample_aspect_ratio.num &&
  1788. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1789. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1790. ((double)st->codec->width * sc->height), INT_MAX);
  1791. }
  1792. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1793. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1794. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  1795. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  1796. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  1797. }
  1798. switch (st->codec->codec_id) {
  1799. #if CONFIG_H261_DECODER
  1800. case CODEC_ID_H261:
  1801. #endif
  1802. #if CONFIG_H263_DECODER
  1803. case CODEC_ID_H263:
  1804. #endif
  1805. #if CONFIG_MPEG4_DECODER
  1806. case CODEC_ID_MPEG4:
  1807. #endif
  1808. st->codec->width = 0; /* let decoder init width/height */
  1809. st->codec->height= 0;
  1810. break;
  1811. }
  1812. /* Do not need those anymore. */
  1813. av_freep(&sc->chunk_offsets);
  1814. av_freep(&sc->stsc_data);
  1815. av_freep(&sc->sample_sizes);
  1816. av_freep(&sc->keyframes);
  1817. av_freep(&sc->stts_data);
  1818. av_freep(&sc->stps_data);
  1819. return 0;
  1820. }
  1821. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1822. {
  1823. int ret;
  1824. c->itunes_metadata = 1;
  1825. ret = mov_read_default(c, pb, atom);
  1826. c->itunes_metadata = 0;
  1827. return ret;
  1828. }
  1829. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1830. {
  1831. while (atom.size > 8) {
  1832. uint32_t tag = avio_rl32(pb);
  1833. atom.size -= 4;
  1834. if (tag == MKTAG('h','d','l','r')) {
  1835. avio_seek(pb, -8, SEEK_CUR);
  1836. atom.size += 8;
  1837. return mov_read_default(c, pb, atom);
  1838. }
  1839. }
  1840. return 0;
  1841. }
  1842. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1843. {
  1844. int i;
  1845. int width;
  1846. int height;
  1847. int64_t disp_transform[2];
  1848. int display_matrix[3][2];
  1849. AVStream *st;
  1850. MOVStreamContext *sc;
  1851. int version;
  1852. if (c->fc->nb_streams < 1)
  1853. return 0;
  1854. st = c->fc->streams[c->fc->nb_streams-1];
  1855. sc = st->priv_data;
  1856. version = avio_r8(pb);
  1857. avio_rb24(pb); /* flags */
  1858. /*
  1859. MOV_TRACK_ENABLED 0x0001
  1860. MOV_TRACK_IN_MOVIE 0x0002
  1861. MOV_TRACK_IN_PREVIEW 0x0004
  1862. MOV_TRACK_IN_POSTER 0x0008
  1863. */
  1864. if (version == 1) {
  1865. avio_rb64(pb);
  1866. avio_rb64(pb);
  1867. } else {
  1868. avio_rb32(pb); /* creation time */
  1869. avio_rb32(pb); /* modification time */
  1870. }
  1871. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  1872. avio_rb32(pb); /* reserved */
  1873. /* highlevel (considering edits) duration in movie timebase */
  1874. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  1875. avio_rb32(pb); /* reserved */
  1876. avio_rb32(pb); /* reserved */
  1877. avio_rb16(pb); /* layer */
  1878. avio_rb16(pb); /* alternate group */
  1879. avio_rb16(pb); /* volume */
  1880. avio_rb16(pb); /* reserved */
  1881. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1882. // they're kept in fixed point format through all calculations
  1883. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1884. for (i = 0; i < 3; i++) {
  1885. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1886. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1887. avio_rb32(pb); // 2.30 fixed point (not used)
  1888. }
  1889. width = avio_rb32(pb); // 16.16 fixed point track width
  1890. height = avio_rb32(pb); // 16.16 fixed point track height
  1891. sc->width = width >> 16;
  1892. sc->height = height >> 16;
  1893. //Assign clockwise rotate values based on transform matrix so that
  1894. //we can compensate for iPhone orientation during capture.
  1895. if (display_matrix[1][0] == -65536 && display_matrix[0][1] == 65536) {
  1896. av_dict_set(&st->metadata, "rotate", "90", 0);
  1897. }
  1898. if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
  1899. av_dict_set(&st->metadata, "rotate", "180", 0);
  1900. }
  1901. if (display_matrix[1][0] == 65536 && display_matrix[0][1] == -65536) {
  1902. av_dict_set(&st->metadata, "rotate", "270", 0);
  1903. }
  1904. // transform the display width/height according to the matrix
  1905. // skip this if the display matrix is the default identity matrix
  1906. // or if it is rotating the picture, ex iPhone 3GS
  1907. // to keep the same scale, use [width height 1<<16]
  1908. if (width && height &&
  1909. ((display_matrix[0][0] != 65536 ||
  1910. display_matrix[1][1] != 65536) &&
  1911. !display_matrix[0][1] &&
  1912. !display_matrix[1][0] &&
  1913. !display_matrix[2][0] && !display_matrix[2][1])) {
  1914. for (i = 0; i < 2; i++)
  1915. disp_transform[i] =
  1916. (int64_t) width * display_matrix[0][i] +
  1917. (int64_t) height * display_matrix[1][i] +
  1918. ((int64_t) display_matrix[2][i] << 16);
  1919. //sample aspect ratio is new width/height divided by old width/height
  1920. st->sample_aspect_ratio = av_d2q(
  1921. ((double) disp_transform[0] * height) /
  1922. ((double) disp_transform[1] * width), INT_MAX);
  1923. }
  1924. return 0;
  1925. }
  1926. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1927. {
  1928. MOVFragment *frag = &c->fragment;
  1929. MOVTrackExt *trex = NULL;
  1930. int flags, track_id, i;
  1931. avio_r8(pb); /* version */
  1932. flags = avio_rb24(pb);
  1933. track_id = avio_rb32(pb);
  1934. if (!track_id)
  1935. return AVERROR_INVALIDDATA;
  1936. frag->track_id = track_id;
  1937. for (i = 0; i < c->trex_count; i++)
  1938. if (c->trex_data[i].track_id == frag->track_id) {
  1939. trex = &c->trex_data[i];
  1940. break;
  1941. }
  1942. if (!trex) {
  1943. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1944. return AVERROR_INVALIDDATA;
  1945. }
  1946. if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
  1947. else frag->base_data_offset = frag->moof_offset;
  1948. if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
  1949. else frag->stsd_id = trex->stsd_id;
  1950. frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
  1951. frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
  1952. frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
  1953. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  1954. return 0;
  1955. }
  1956. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1957. {
  1958. c->chapter_track = avio_rb32(pb);
  1959. return 0;
  1960. }
  1961. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1962. {
  1963. MOVTrackExt *trex;
  1964. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1965. return AVERROR_INVALIDDATA;
  1966. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1967. if (!trex)
  1968. return AVERROR(ENOMEM);
  1969. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  1970. c->trex_data = trex;
  1971. trex = &c->trex_data[c->trex_count++];
  1972. avio_r8(pb); /* version */
  1973. avio_rb24(pb); /* flags */
  1974. trex->track_id = avio_rb32(pb);
  1975. trex->stsd_id = avio_rb32(pb);
  1976. trex->duration = avio_rb32(pb);
  1977. trex->size = avio_rb32(pb);
  1978. trex->flags = avio_rb32(pb);
  1979. return 0;
  1980. }
  1981. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1982. {
  1983. MOVFragment *frag = &c->fragment;
  1984. AVStream *st = NULL;
  1985. MOVStreamContext *sc;
  1986. MOVStts *ctts_data;
  1987. uint64_t offset;
  1988. int64_t dts;
  1989. int data_offset = 0;
  1990. unsigned entries, first_sample_flags = frag->flags;
  1991. int flags, distance, i;
  1992. for (i = 0; i < c->fc->nb_streams; i++) {
  1993. if (c->fc->streams[i]->id == frag->track_id) {
  1994. st = c->fc->streams[i];
  1995. break;
  1996. }
  1997. }
  1998. if (!st) {
  1999. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2000. return AVERROR_INVALIDDATA;
  2001. }
  2002. sc = st->priv_data;
  2003. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  2004. return 0;
  2005. avio_r8(pb); /* version */
  2006. flags = avio_rb24(pb);
  2007. entries = avio_rb32(pb);
  2008. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  2009. /* Always assume the presence of composition time offsets.
  2010. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2011. * 1) in the initial movie, there are no samples.
  2012. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2013. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2014. if (!sc->ctts_count && sc->sample_count)
  2015. {
  2016. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2017. ctts_data = av_malloc(sizeof(*sc->ctts_data));
  2018. if (!ctts_data)
  2019. return AVERROR(ENOMEM);
  2020. sc->ctts_data = ctts_data;
  2021. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2022. sc->ctts_data[sc->ctts_count].duration = 0;
  2023. sc->ctts_count++;
  2024. }
  2025. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2026. return AVERROR_INVALIDDATA;
  2027. ctts_data = av_realloc(sc->ctts_data,
  2028. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  2029. if (!ctts_data)
  2030. return AVERROR(ENOMEM);
  2031. sc->ctts_data = ctts_data;
  2032. if (flags & 0x001) data_offset = avio_rb32(pb);
  2033. if (flags & 0x004) first_sample_flags = avio_rb32(pb);
  2034. dts = st->duration - sc->time_offset;
  2035. offset = frag->base_data_offset + data_offset;
  2036. distance = 0;
  2037. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  2038. for (i = 0; i < entries; i++) {
  2039. unsigned sample_size = frag->size;
  2040. int sample_flags = i ? frag->flags : first_sample_flags;
  2041. unsigned sample_duration = frag->duration;
  2042. int keyframe;
  2043. if (flags & 0x100) sample_duration = avio_rb32(pb);
  2044. if (flags & 0x200) sample_size = avio_rb32(pb);
  2045. if (flags & 0x400) sample_flags = avio_rb32(pb);
  2046. sc->ctts_data[sc->ctts_count].count = 1;
  2047. sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
  2048. sc->ctts_count++;
  2049. if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
  2050. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  2051. distance = 0;
  2052. av_add_index_entry(st, offset, dts, sample_size, distance,
  2053. keyframe ? AVINDEX_KEYFRAME : 0);
  2054. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2055. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2056. offset, dts, sample_size, distance, keyframe);
  2057. distance++;
  2058. dts += sample_duration;
  2059. offset += sample_size;
  2060. sc->data_size += sample_size;
  2061. }
  2062. frag->moof_offset = offset;
  2063. st->duration = dts + sc->time_offset;
  2064. return 0;
  2065. }
  2066. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2067. /* like the files created with Adobe Premiere 5.0, for samples see */
  2068. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2069. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2070. {
  2071. int err;
  2072. if (atom.size < 8)
  2073. return 0; /* continue */
  2074. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2075. avio_skip(pb, atom.size - 4);
  2076. return 0;
  2077. }
  2078. atom.type = avio_rl32(pb);
  2079. atom.size -= 8;
  2080. if (atom.type != MKTAG('m','d','a','t')) {
  2081. avio_skip(pb, atom.size);
  2082. return 0;
  2083. }
  2084. err = mov_read_mdat(c, pb, atom);
  2085. return err;
  2086. }
  2087. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2088. {
  2089. #if CONFIG_ZLIB
  2090. AVIOContext ctx;
  2091. uint8_t *cmov_data;
  2092. uint8_t *moov_data; /* uncompressed data */
  2093. long cmov_len, moov_len;
  2094. int ret = -1;
  2095. avio_rb32(pb); /* dcom atom */
  2096. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2097. return AVERROR_INVALIDDATA;
  2098. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2099. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  2100. return AVERROR_INVALIDDATA;
  2101. }
  2102. avio_rb32(pb); /* cmvd atom */
  2103. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2104. return AVERROR_INVALIDDATA;
  2105. moov_len = avio_rb32(pb); /* uncompressed size */
  2106. cmov_len = atom.size - 6 * 4;
  2107. cmov_data = av_malloc(cmov_len);
  2108. if (!cmov_data)
  2109. return AVERROR(ENOMEM);
  2110. moov_data = av_malloc(moov_len);
  2111. if (!moov_data) {
  2112. av_free(cmov_data);
  2113. return AVERROR(ENOMEM);
  2114. }
  2115. avio_read(pb, cmov_data, cmov_len);
  2116. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2117. goto free_and_return;
  2118. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2119. goto free_and_return;
  2120. atom.type = MKTAG('m','o','o','v');
  2121. atom.size = moov_len;
  2122. ret = mov_read_default(c, &ctx, atom);
  2123. free_and_return:
  2124. av_free(moov_data);
  2125. av_free(cmov_data);
  2126. return ret;
  2127. #else
  2128. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2129. return AVERROR(ENOSYS);
  2130. #endif
  2131. }
  2132. /* edit list atom */
  2133. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2134. {
  2135. MOVStreamContext *sc;
  2136. int i, edit_count, version, edit_start_index = 0;
  2137. if (c->fc->nb_streams < 1)
  2138. return 0;
  2139. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2140. version = avio_r8(pb); /* version */
  2141. avio_rb24(pb); /* flags */
  2142. edit_count = avio_rb32(pb); /* entries */
  2143. if ((uint64_t)edit_count*12+8 > atom.size)
  2144. return AVERROR_INVALIDDATA;
  2145. for (i=0; i<edit_count; i++){
  2146. int64_t time;
  2147. int64_t duration;
  2148. if (version == 1) {
  2149. duration = avio_rb64(pb);
  2150. time = avio_rb64(pb);
  2151. } else {
  2152. duration = avio_rb32(pb); /* segment duration */
  2153. time = (int32_t)avio_rb32(pb); /* media time */
  2154. }
  2155. avio_rb32(pb); /* Media rate */
  2156. if (i == 0 && time == -1) {
  2157. sc->empty_duration = duration;
  2158. edit_start_index = 1;
  2159. } else if (i == edit_start_index && time >= 0)
  2160. sc->start_time = time;
  2161. }
  2162. if (edit_count > 1)
  2163. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2164. "a/v desync might occur, patch welcome\n");
  2165. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2166. return 0;
  2167. }
  2168. static int mov_read_chan2(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2169. {
  2170. if (atom.size < 16)
  2171. return 0;
  2172. avio_skip(pb, 4);
  2173. ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
  2174. return 0;
  2175. }
  2176. static const MOVParseTableEntry mov_default_parse_table[] = {
  2177. { MKTAG('a','v','s','s'), mov_read_avss },
  2178. { MKTAG('c','h','p','l'), mov_read_chpl },
  2179. { MKTAG('c','o','6','4'), mov_read_stco },
  2180. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2181. { MKTAG('d','i','n','f'), mov_read_default },
  2182. { MKTAG('d','r','e','f'), mov_read_dref },
  2183. { MKTAG('e','d','t','s'), mov_read_default },
  2184. { MKTAG('e','l','s','t'), mov_read_elst },
  2185. { MKTAG('e','n','d','a'), mov_read_enda },
  2186. { MKTAG('f','i','e','l'), mov_read_fiel },
  2187. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2188. { MKTAG('g','l','b','l'), mov_read_glbl },
  2189. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2190. { MKTAG('i','l','s','t'), mov_read_ilst },
  2191. { MKTAG('j','p','2','h'), mov_read_jp2h },
  2192. { MKTAG('m','d','a','t'), mov_read_mdat },
  2193. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2194. { MKTAG('m','d','i','a'), mov_read_default },
  2195. { MKTAG('m','e','t','a'), mov_read_meta },
  2196. { MKTAG('m','i','n','f'), mov_read_default },
  2197. { MKTAG('m','o','o','f'), mov_read_moof },
  2198. { MKTAG('m','o','o','v'), mov_read_moov },
  2199. { MKTAG('m','v','e','x'), mov_read_default },
  2200. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2201. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  2202. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  2203. { MKTAG('a','v','c','C'), mov_read_glbl },
  2204. { MKTAG('p','a','s','p'), mov_read_pasp },
  2205. { MKTAG('s','t','b','l'), mov_read_default },
  2206. { MKTAG('s','t','c','o'), mov_read_stco },
  2207. { MKTAG('s','t','p','s'), mov_read_stps },
  2208. { MKTAG('s','t','r','f'), mov_read_strf },
  2209. { MKTAG('s','t','s','c'), mov_read_stsc },
  2210. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2211. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2212. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2213. { MKTAG('s','t','t','s'), mov_read_stts },
  2214. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2215. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2216. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2217. { MKTAG('t','r','a','k'), mov_read_trak },
  2218. { MKTAG('t','r','a','f'), mov_read_default },
  2219. { MKTAG('t','r','e','f'), mov_read_default },
  2220. { MKTAG('c','h','a','p'), mov_read_chap },
  2221. { MKTAG('t','r','e','x'), mov_read_trex },
  2222. { MKTAG('t','r','u','n'), mov_read_trun },
  2223. { MKTAG('u','d','t','a'), mov_read_default },
  2224. { MKTAG('w','a','v','e'), mov_read_wave },
  2225. { MKTAG('e','s','d','s'), mov_read_esds },
  2226. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2227. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2228. { MKTAG('w','f','e','x'), mov_read_wfex },
  2229. { MKTAG('c','m','o','v'), mov_read_cmov },
  2230. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2231. { 0, NULL }
  2232. };
  2233. static int mov_probe(AVProbeData *p)
  2234. {
  2235. unsigned int offset;
  2236. uint32_t tag;
  2237. int score = 0;
  2238. /* check file header */
  2239. offset = 0;
  2240. for (;;) {
  2241. /* ignore invalid offset */
  2242. if ((offset + 8) > (unsigned int)p->buf_size)
  2243. return score;
  2244. tag = AV_RL32(p->buf + offset + 4);
  2245. switch(tag) {
  2246. /* check for obvious tags */
  2247. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2248. case MKTAG('m','o','o','v'):
  2249. case MKTAG('m','d','a','t'):
  2250. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2251. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2252. case MKTAG('f','t','y','p'):
  2253. return AVPROBE_SCORE_MAX;
  2254. /* those are more common words, so rate then a bit less */
  2255. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2256. case MKTAG('w','i','d','e'):
  2257. case MKTAG('f','r','e','e'):
  2258. case MKTAG('j','u','n','k'):
  2259. case MKTAG('p','i','c','t'):
  2260. return AVPROBE_SCORE_MAX - 5;
  2261. case MKTAG(0x82,0x82,0x7f,0x7d):
  2262. case MKTAG('s','k','i','p'):
  2263. case MKTAG('u','u','i','d'):
  2264. case MKTAG('p','r','f','l'):
  2265. offset = AV_RB32(p->buf+offset) + offset;
  2266. /* if we only find those cause probedata is too small at least rate them */
  2267. score = AVPROBE_SCORE_MAX - 50;
  2268. break;
  2269. default:
  2270. /* unrecognized tag */
  2271. return score;
  2272. }
  2273. }
  2274. }
  2275. // must be done after parsing all trak because there's no order requirement
  2276. static void mov_read_chapters(AVFormatContext *s)
  2277. {
  2278. MOVContext *mov = s->priv_data;
  2279. AVStream *st = NULL;
  2280. MOVStreamContext *sc;
  2281. int64_t cur_pos;
  2282. int i;
  2283. for (i = 0; i < s->nb_streams; i++)
  2284. if (s->streams[i]->id == mov->chapter_track) {
  2285. st = s->streams[i];
  2286. break;
  2287. }
  2288. if (!st) {
  2289. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2290. return;
  2291. }
  2292. st->discard = AVDISCARD_ALL;
  2293. sc = st->priv_data;
  2294. cur_pos = avio_tell(sc->pb);
  2295. for (i = 0; i < st->nb_index_entries; i++) {
  2296. AVIndexEntry *sample = &st->index_entries[i];
  2297. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2298. uint8_t *title;
  2299. uint16_t ch;
  2300. int len, title_len;
  2301. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2302. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2303. goto finish;
  2304. }
  2305. // the first two bytes are the length of the title
  2306. len = avio_rb16(sc->pb);
  2307. if (len > sample->size-2)
  2308. continue;
  2309. title_len = 2*len + 1;
  2310. if (!(title = av_mallocz(title_len)))
  2311. goto finish;
  2312. // The samples could theoretically be in any encoding if there's an encd
  2313. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2314. // instead by the presence of a BOM
  2315. if (!len) {
  2316. title[0] = 0;
  2317. } else {
  2318. ch = avio_rb16(sc->pb);
  2319. if (ch == 0xfeff)
  2320. avio_get_str16be(sc->pb, len, title, title_len);
  2321. else if (ch == 0xfffe)
  2322. avio_get_str16le(sc->pb, len, title, title_len);
  2323. else {
  2324. AV_WB16(title, ch);
  2325. if (len == 1 || len == 2)
  2326. title[len] = 0;
  2327. else
  2328. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  2329. }
  2330. }
  2331. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2332. av_freep(&title);
  2333. }
  2334. finish:
  2335. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2336. }
  2337. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  2338. uint32_t value)
  2339. {
  2340. char buf[16];
  2341. struct ff_timecode tc = {
  2342. .drop = st->codec->flags2 & CODEC_FLAG2_DROP_FRAME_TIMECODE,
  2343. .rate = (AVRational){st->codec->time_base.den,
  2344. st->codec->time_base.num},
  2345. };
  2346. if (avpriv_check_timecode_rate(s, tc.rate, tc.drop) < 0)
  2347. return AVERROR(EINVAL);
  2348. av_dict_set(&st->metadata, "timecode",
  2349. avpriv_timecode_to_string(buf, &tc, value), 0);
  2350. return 0;
  2351. }
  2352. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  2353. {
  2354. MOVStreamContext *sc = st->priv_data;
  2355. int64_t cur_pos = avio_tell(sc->pb);
  2356. uint32_t value;
  2357. if (!st->nb_index_entries)
  2358. return -1;
  2359. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  2360. value = avio_rb32(s->pb);
  2361. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  2362. * not the case) and thus assume "frame number format" instead of QT one.
  2363. * No sample with tmcd track can be found with a QT timecode at the moment,
  2364. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  2365. * format). */
  2366. parse_timecode_in_framenum_format(s, st, value);
  2367. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2368. return 0;
  2369. }
  2370. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  2371. {
  2372. MOVContext *mov = s->priv_data;
  2373. AVIOContext *pb = s->pb;
  2374. int err;
  2375. MOVAtom atom = { AV_RL32("root") };
  2376. mov->fc = s;
  2377. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2378. if (pb->seekable)
  2379. atom.size = avio_size(pb);
  2380. else
  2381. atom.size = INT64_MAX;
  2382. /* check MOV header */
  2383. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2384. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2385. return err;
  2386. }
  2387. if (!mov->found_moov) {
  2388. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2389. return AVERROR_INVALIDDATA;
  2390. }
  2391. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2392. if (pb->seekable) {
  2393. int i;
  2394. if (mov->chapter_track > 0)
  2395. mov_read_chapters(s);
  2396. for (i = 0; i < s->nb_streams; i++)
  2397. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  2398. mov_read_timecode_track(s, s->streams[i]);
  2399. }
  2400. if (mov->trex_data) {
  2401. int i;
  2402. for (i = 0; i < s->nb_streams; i++) {
  2403. AVStream *st = s->streams[i];
  2404. MOVStreamContext *sc = st->priv_data;
  2405. if (st->duration)
  2406. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  2407. }
  2408. }
  2409. return 0;
  2410. }
  2411. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2412. {
  2413. AVIndexEntry *sample = NULL;
  2414. int64_t best_dts = INT64_MAX;
  2415. int i;
  2416. for (i = 0; i < s->nb_streams; i++) {
  2417. AVStream *avst = s->streams[i];
  2418. MOVStreamContext *msc = avst->priv_data;
  2419. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2420. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2421. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2422. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2423. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2424. (s->pb->seekable &&
  2425. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2426. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2427. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2428. sample = current_sample;
  2429. best_dts = dts;
  2430. *st = avst;
  2431. }
  2432. }
  2433. }
  2434. return sample;
  2435. }
  2436. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2437. {
  2438. MOVContext *mov = s->priv_data;
  2439. MOVStreamContext *sc;
  2440. AVIndexEntry *sample;
  2441. AVStream *st = NULL;
  2442. int ret;
  2443. mov->fc = s;
  2444. retry:
  2445. sample = mov_find_next_sample(s, &st);
  2446. if (!sample) {
  2447. mov->found_mdat = 0;
  2448. if (s->pb->seekable||
  2449. mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2450. url_feof(s->pb))
  2451. return AVERROR_EOF;
  2452. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  2453. goto retry;
  2454. }
  2455. sc = st->priv_data;
  2456. /* must be done just before reading, to avoid infinite loop on sample */
  2457. sc->current_sample++;
  2458. if (st->discard != AVDISCARD_ALL) {
  2459. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2460. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2461. sc->ffindex, sample->pos);
  2462. return AVERROR_INVALIDDATA;
  2463. }
  2464. ret = av_get_packet(sc->pb, pkt, sample->size);
  2465. if (ret < 0)
  2466. return ret;
  2467. if (sc->has_palette) {
  2468. uint8_t *pal;
  2469. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  2470. if (!pal) {
  2471. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  2472. } else {
  2473. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  2474. sc->has_palette = 0;
  2475. }
  2476. }
  2477. #if CONFIG_DV_DEMUXER
  2478. if (mov->dv_demux && sc->dv_audio_container) {
  2479. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  2480. av_free(pkt->data);
  2481. pkt->size = 0;
  2482. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  2483. if (ret < 0)
  2484. return ret;
  2485. }
  2486. #endif
  2487. }
  2488. pkt->stream_index = sc->ffindex;
  2489. pkt->dts = sample->timestamp;
  2490. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  2491. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2492. /* update ctts context */
  2493. sc->ctts_sample++;
  2494. if (sc->ctts_index < sc->ctts_count &&
  2495. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2496. sc->ctts_index++;
  2497. sc->ctts_sample = 0;
  2498. }
  2499. if (sc->wrong_dts)
  2500. pkt->dts = AV_NOPTS_VALUE;
  2501. } else {
  2502. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2503. st->index_entries[sc->current_sample].timestamp : st->duration;
  2504. pkt->duration = next_dts - pkt->dts;
  2505. pkt->pts = pkt->dts;
  2506. }
  2507. if (st->discard == AVDISCARD_ALL)
  2508. goto retry;
  2509. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2510. pkt->pos = sample->pos;
  2511. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2512. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2513. return 0;
  2514. }
  2515. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2516. {
  2517. MOVStreamContext *sc = st->priv_data;
  2518. int sample, time_sample;
  2519. int i;
  2520. sample = av_index_search_timestamp(st, timestamp, flags);
  2521. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2522. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2523. sample = 0;
  2524. if (sample < 0) /* not sure what to do */
  2525. return AVERROR_INVALIDDATA;
  2526. sc->current_sample = sample;
  2527. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2528. /* adjust ctts index */
  2529. if (sc->ctts_data) {
  2530. time_sample = 0;
  2531. for (i = 0; i < sc->ctts_count; i++) {
  2532. int next = time_sample + sc->ctts_data[i].count;
  2533. if (next > sc->current_sample) {
  2534. sc->ctts_index = i;
  2535. sc->ctts_sample = sc->current_sample - time_sample;
  2536. break;
  2537. }
  2538. time_sample = next;
  2539. }
  2540. }
  2541. return sample;
  2542. }
  2543. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2544. {
  2545. AVStream *st;
  2546. int64_t seek_timestamp, timestamp;
  2547. int sample;
  2548. int i;
  2549. if (stream_index >= s->nb_streams)
  2550. return AVERROR_INVALIDDATA;
  2551. if (sample_time < 0)
  2552. sample_time = 0;
  2553. st = s->streams[stream_index];
  2554. sample = mov_seek_stream(s, st, sample_time, flags);
  2555. if (sample < 0)
  2556. return sample;
  2557. /* adjust seek timestamp to found sample timestamp */
  2558. seek_timestamp = st->index_entries[sample].timestamp;
  2559. for (i = 0; i < s->nb_streams; i++) {
  2560. st = s->streams[i];
  2561. if (stream_index == i)
  2562. continue;
  2563. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2564. mov_seek_stream(s, st, timestamp, flags);
  2565. }
  2566. return 0;
  2567. }
  2568. static int mov_read_close(AVFormatContext *s)
  2569. {
  2570. MOVContext *mov = s->priv_data;
  2571. int i, j;
  2572. for (i = 0; i < s->nb_streams; i++) {
  2573. AVStream *st = s->streams[i];
  2574. MOVStreamContext *sc = st->priv_data;
  2575. av_freep(&sc->ctts_data);
  2576. for (j = 0; j < sc->drefs_count; j++) {
  2577. av_freep(&sc->drefs[j].path);
  2578. av_freep(&sc->drefs[j].dir);
  2579. }
  2580. av_freep(&sc->drefs);
  2581. if (sc->pb && sc->pb != s->pb)
  2582. avio_close(sc->pb);
  2583. }
  2584. if (mov->dv_demux) {
  2585. for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2586. av_freep(&mov->dv_fctx->streams[i]->codec);
  2587. av_freep(&mov->dv_fctx->streams[i]);
  2588. }
  2589. av_freep(&mov->dv_fctx);
  2590. av_freep(&mov->dv_demux);
  2591. }
  2592. av_freep(&mov->trex_data);
  2593. return 0;
  2594. }
  2595. static const AVOption options[] = {
  2596. {"use_absolute_path",
  2597. "allow using absolute path when opening alias, this is a possible security issue",
  2598. offsetof(MOVContext, use_absolute_path), FF_OPT_TYPE_INT, {.dbl = 0},
  2599. 0, 1, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_DECODING_PARAM},
  2600. {NULL}
  2601. };
  2602. static const AVClass class = {"mov,mp4,m4a,3gp,3g2,mj2", av_default_item_name, options, LIBAVUTIL_VERSION_INT};
  2603. AVInputFormat ff_mov_demuxer = {
  2604. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  2605. .long_name = NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  2606. .priv_data_size = sizeof(MOVContext),
  2607. .read_probe = mov_probe,
  2608. .read_header = mov_read_header,
  2609. .read_packet = mov_read_packet,
  2610. .read_close = mov_read_close,
  2611. .read_seek = mov_read_seek,
  2612. .priv_class = &class,
  2613. };