You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2697 lines
90KB

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