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.

2068 lines
71KB

  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 DEBUG_METADATA
  25. //#define MOV_EXPORT_ALL_METADATA
  26. #include "libavutil/intreadwrite.h"
  27. #include "libavutil/avstring.h"
  28. #include "avformat.h"
  29. #include "riff.h"
  30. #include "isom.h"
  31. #include "libavcodec/mpeg4audio.h"
  32. #include "libavcodec/mpegaudiodata.h"
  33. #if CONFIG_ZLIB
  34. #include <zlib.h>
  35. #endif
  36. /*
  37. * First version by Francois Revol revol@free.fr
  38. * Seek function by Gael Chardon gael.dev@4now.net
  39. *
  40. * Features and limitations:
  41. * - reads most of the QT files I have (at least the structure),
  42. * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
  43. * - the code is quite ugly... maybe I won't do it recursive next time :-)
  44. *
  45. * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
  46. * when coding this :) (it's a writer anyway)
  47. *
  48. * Reference documents:
  49. * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
  50. * Apple:
  51. * http://developer.apple.com/documentation/QuickTime/QTFF/
  52. * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
  53. * QuickTime is a trademark of Apple (AFAIK :))
  54. */
  55. #include "qtpalette.h"
  56. #undef NDEBUG
  57. #include <assert.h>
  58. /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
  59. /* those functions parse an atom */
  60. /* return code:
  61. 0: continue to parse next atom
  62. <0: error occurred, exit
  63. */
  64. /* links atom IDs to parse functions */
  65. typedef struct MOVParseTableEntry {
  66. uint32_t type;
  67. int (*parse)(MOVContext *ctx, ByteIOContext *pb, MOVAtom atom);
  68. } MOVParseTableEntry;
  69. static const MOVParseTableEntry mov_default_parse_table[];
  70. static int mov_metadata_trkn(MOVContext *c, ByteIOContext *pb, unsigned len)
  71. {
  72. char buf[16];
  73. get_be16(pb); // unknown
  74. snprintf(buf, sizeof(buf), "%d", get_be16(pb));
  75. av_metadata_set(&c->fc->metadata, "track", buf);
  76. get_be16(pb); // total tracks
  77. return 0;
  78. }
  79. static int mov_read_udta_string(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  80. {
  81. #ifdef MOV_EXPORT_ALL_METADATA
  82. char tmp_key[5];
  83. #endif
  84. char str[1024], key2[16], language[4] = {0};
  85. const char *key = NULL;
  86. uint16_t str_size;
  87. int (*parse)(MOVContext*, ByteIOContext*, unsigned) = NULL;
  88. switch (atom.type) {
  89. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  90. case MKTAG(0xa9,'a','u','t'):
  91. case MKTAG(0xa9,'A','R','T'):
  92. case MKTAG(0xa9,'w','r','t'): key = "author"; break;
  93. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  94. case MKTAG(0xa9,'c','m','t'):
  95. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  96. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  97. case MKTAG(0xa9,'d','a','y'): key = "year"; break;
  98. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  99. case MKTAG(0xa9,'t','o','o'):
  100. case MKTAG(0xa9,'e','n','c'): key = "muxer"; break;
  101. case MKTAG( 't','r','k','n'): key = "track";
  102. parse = mov_metadata_trkn; break;
  103. }
  104. if (c->itunes_metadata && atom.size > 8) {
  105. int data_size = get_be32(pb);
  106. int tag = get_le32(pb);
  107. if (tag == MKTAG('d','a','t','a')) {
  108. get_be32(pb); // type
  109. get_be32(pb); // unknown
  110. str_size = data_size - 16;
  111. atom.size -= 16;
  112. } else return 0;
  113. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  114. str_size = get_be16(pb); // string length
  115. ff_mov_lang_to_iso639(get_be16(pb), language);
  116. atom.size -= 4;
  117. } else
  118. str_size = atom.size;
  119. #ifdef MOV_EXPORT_ALL_METADATA
  120. if (!key) {
  121. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  122. key = tmp_key;
  123. }
  124. #endif
  125. if (!key)
  126. return 0;
  127. if (atom.size < 0)
  128. return -1;
  129. str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
  130. if (parse)
  131. parse(c, pb, str_size);
  132. else {
  133. get_buffer(pb, str, str_size);
  134. str[str_size] = 0;
  135. av_metadata_set(&c->fc->metadata, key, str);
  136. if (*language && strcmp(language, "und")) {
  137. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  138. av_metadata_set(&c->fc->metadata, key2, str);
  139. }
  140. }
  141. #ifdef DEBUG_METADATA
  142. av_log(c->fc, AV_LOG_DEBUG, "lang \"%3s\" ", language);
  143. av_log(c->fc, AV_LOG_DEBUG, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %lld\n",
  144. key, str, (char*)&atom.type, str_size, atom.size);
  145. #endif
  146. return 0;
  147. }
  148. static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  149. {
  150. int64_t total_size = 0;
  151. MOVAtom a;
  152. int i;
  153. int err = 0;
  154. a.offset = atom.offset;
  155. if (atom.size < 0)
  156. atom.size = INT64_MAX;
  157. while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
  158. int (*parse)(MOVContext*, ByteIOContext*, MOVAtom) = NULL;
  159. a.size = atom.size;
  160. a.type=0;
  161. if(atom.size >= 8) {
  162. a.size = get_be32(pb);
  163. a.type = get_le32(pb);
  164. }
  165. total_size += 8;
  166. a.offset += 8;
  167. dprintf(c->fc, "type: %08x %.4s sz: %"PRIx64" %"PRIx64" %"PRIx64"\n",
  168. a.type, (char*)&a.type, a.size, atom.size, total_size);
  169. if (a.size == 1) { /* 64 bit extended size */
  170. a.size = get_be64(pb) - 8;
  171. a.offset += 8;
  172. total_size += 8;
  173. }
  174. if (a.size == 0) {
  175. a.size = atom.size - total_size;
  176. if (a.size <= 8)
  177. break;
  178. }
  179. a.size -= 8;
  180. if(a.size < 0)
  181. break;
  182. a.size = FFMIN(a.size, atom.size - total_size);
  183. for (i = 0; mov_default_parse_table[i].type; i++)
  184. if (mov_default_parse_table[i].type == a.type) {
  185. parse = mov_default_parse_table[i].parse;
  186. break;
  187. }
  188. // container is user data
  189. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  190. atom.type == MKTAG('i','l','s','t')))
  191. parse = mov_read_udta_string;
  192. if (!parse) { /* skip leaf atoms data */
  193. url_fskip(pb, a.size);
  194. } else {
  195. int64_t start_pos = url_ftell(pb);
  196. int64_t left;
  197. err = parse(c, pb, a);
  198. if (url_is_streamed(pb) && c->found_moov && c->found_mdat)
  199. break;
  200. left = a.size - url_ftell(pb) + start_pos;
  201. if (left > 0) /* skip garbage at atom end */
  202. url_fskip(pb, left);
  203. }
  204. a.offset += a.size;
  205. total_size += a.size;
  206. }
  207. if (!err && total_size < atom.size && atom.size < 0x7ffff)
  208. url_fskip(pb, atom.size - total_size);
  209. return err;
  210. }
  211. static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  212. {
  213. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  214. MOVStreamContext *sc = st->priv_data;
  215. int entries, i, j;
  216. get_be32(pb); // version + flags
  217. entries = get_be32(pb);
  218. if (entries >= UINT_MAX / sizeof(*sc->drefs))
  219. return -1;
  220. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  221. if (!sc->drefs)
  222. return AVERROR(ENOMEM);
  223. sc->drefs_count = entries;
  224. for (i = 0; i < sc->drefs_count; i++) {
  225. MOVDref *dref = &sc->drefs[i];
  226. uint32_t size = get_be32(pb);
  227. int64_t next = url_ftell(pb) + size - 4;
  228. dref->type = get_le32(pb);
  229. get_be32(pb); // version + flags
  230. dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  231. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  232. /* macintosh alias record */
  233. uint16_t volume_len, len;
  234. char volume[28];
  235. int16_t type;
  236. url_fskip(pb, 10);
  237. volume_len = get_byte(pb);
  238. volume_len = FFMIN(volume_len, 27);
  239. get_buffer(pb, volume, 27);
  240. volume[volume_len] = 0;
  241. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);
  242. url_fskip(pb, 112);
  243. for (type = 0; type != -1 && url_ftell(pb) < next; ) {
  244. type = get_be16(pb);
  245. len = get_be16(pb);
  246. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  247. if (len&1)
  248. len += 1;
  249. if (type == 2) { // absolute path
  250. av_free(dref->path);
  251. dref->path = av_mallocz(len+1);
  252. if (!dref->path)
  253. return AVERROR(ENOMEM);
  254. get_buffer(pb, dref->path, len);
  255. if (len > volume_len && !strncmp(dref->path, volume, volume_len)) {
  256. len -= volume_len;
  257. memmove(dref->path, dref->path+volume_len, len);
  258. dref->path[len] = 0;
  259. }
  260. for (j = 0; j < len; j++)
  261. if (dref->path[j] == ':')
  262. dref->path[j] = '/';
  263. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  264. } else
  265. url_fskip(pb, len);
  266. }
  267. }
  268. url_fseek(pb, next, SEEK_SET);
  269. }
  270. return 0;
  271. }
  272. static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  273. {
  274. AVStream *st;
  275. uint32_t type;
  276. uint32_t ctype;
  277. if (c->fc->nb_streams < 1) // meta before first trak
  278. return 0;
  279. st = c->fc->streams[c->fc->nb_streams-1];
  280. get_byte(pb); /* version */
  281. get_be24(pb); /* flags */
  282. /* component type */
  283. ctype = get_le32(pb);
  284. type = get_le32(pb); /* component subtype */
  285. dprintf(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  286. dprintf(c->fc, "stype= %.4s\n", (char*)&type);
  287. if (type == MKTAG('v','i','d','e'))
  288. st->codec->codec_type = CODEC_TYPE_VIDEO;
  289. else if(type == MKTAG('s','o','u','n'))
  290. st->codec->codec_type = CODEC_TYPE_AUDIO;
  291. else if(type == MKTAG('m','1','a',' '))
  292. st->codec->codec_id = CODEC_ID_MP2;
  293. else if(type == MKTAG('s','u','b','p'))
  294. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  295. get_be32(pb); /* component manufacture */
  296. get_be32(pb); /* component flags */
  297. get_be32(pb); /* component flags mask */
  298. if(atom.size <= 24)
  299. return 0; /* nothing left to read */
  300. url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
  301. return 0;
  302. }
  303. static int mp4_read_descr_len(ByteIOContext *pb)
  304. {
  305. int len = 0;
  306. int count = 4;
  307. while (count--) {
  308. int c = get_byte(pb);
  309. len = (len << 7) | (c & 0x7f);
  310. if (!(c & 0x80))
  311. break;
  312. }
  313. return len;
  314. }
  315. static int mp4_read_descr(MOVContext *c, ByteIOContext *pb, int *tag)
  316. {
  317. int len;
  318. *tag = get_byte(pb);
  319. len = mp4_read_descr_len(pb);
  320. dprintf(c->fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
  321. return len;
  322. }
  323. #define MP4ESDescrTag 0x03
  324. #define MP4DecConfigDescrTag 0x04
  325. #define MP4DecSpecificDescrTag 0x05
  326. static const AVCodecTag mp4_audio_types[] = {
  327. { CODEC_ID_MP3ON4, 29 }, /* old mp3on4 draft */
  328. { CODEC_ID_MP3ON4, 32 }, /* layer 1 */
  329. { CODEC_ID_MP3ON4, 33 }, /* layer 2 */
  330. { CODEC_ID_MP3ON4, 34 }, /* layer 3 */
  331. { CODEC_ID_NONE, 0 },
  332. };
  333. static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  334. {
  335. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  336. int tag, len;
  337. get_be32(pb); /* version + flags */
  338. len = mp4_read_descr(c, pb, &tag);
  339. if (tag == MP4ESDescrTag) {
  340. get_be16(pb); /* ID */
  341. get_byte(pb); /* priority */
  342. } else
  343. get_be16(pb); /* ID */
  344. len = mp4_read_descr(c, pb, &tag);
  345. if (tag == MP4DecConfigDescrTag) {
  346. int object_type_id = get_byte(pb);
  347. get_byte(pb); /* stream type */
  348. get_be24(pb); /* buffer size db */
  349. get_be32(pb); /* max bitrate */
  350. get_be32(pb); /* avg bitrate */
  351. st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);
  352. dprintf(c->fc, "esds object type id %d\n", object_type_id);
  353. len = mp4_read_descr(c, pb, &tag);
  354. if (tag == MP4DecSpecificDescrTag) {
  355. dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);
  356. if((uint64_t)len > (1<<30))
  357. return -1;
  358. st->codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
  359. if (!st->codec->extradata)
  360. return AVERROR(ENOMEM);
  361. get_buffer(pb, st->codec->extradata, len);
  362. st->codec->extradata_size = len;
  363. if (st->codec->codec_id == CODEC_ID_AAC) {
  364. MPEG4AudioConfig cfg;
  365. ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
  366. st->codec->extradata_size);
  367. if (cfg.chan_config > 7)
  368. return -1;
  369. st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
  370. if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
  371. st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];
  372. else
  373. st->codec->sample_rate = cfg.sample_rate; // ext sample rate ?
  374. dprintf(c->fc, "mp4a config channels %d obj %d ext obj %d "
  375. "sample rate %d ext sample rate %d\n", st->codec->channels,
  376. cfg.object_type, cfg.ext_object_type,
  377. cfg.sample_rate, cfg.ext_sample_rate);
  378. if (!(st->codec->codec_id = codec_get_id(mp4_audio_types,
  379. cfg.object_type)))
  380. st->codec->codec_id = CODEC_ID_AAC;
  381. }
  382. }
  383. }
  384. return 0;
  385. }
  386. static int mov_read_pasp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  387. {
  388. const int num = get_be32(pb);
  389. const int den = get_be32(pb);
  390. AVStream * const st = c->fc->streams[c->fc->nb_streams-1];
  391. if (den != 0) {
  392. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  393. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num))
  394. av_log(c->fc, AV_LOG_WARNING,
  395. "sample aspect ratio already set to %d:%d, overriding by 'pasp' atom\n",
  396. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);
  397. st->sample_aspect_ratio.num = num;
  398. st->sample_aspect_ratio.den = den;
  399. }
  400. return 0;
  401. }
  402. /* this atom contains actual media data */
  403. static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  404. {
  405. if(atom.size == 0) /* wrong one (MP4) */
  406. return 0;
  407. c->found_mdat=1;
  408. return 0; /* now go for moov */
  409. }
  410. static int mov_read_ftyp(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  411. {
  412. uint32_t type = get_le32(pb);
  413. if (type != MKTAG('q','t',' ',' '))
  414. c->isom = 1;
  415. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  416. get_be32(pb); /* minor version */
  417. url_fskip(pb, atom.size - 8);
  418. return 0;
  419. }
  420. /* this atom should contain all header atoms */
  421. static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  422. {
  423. if (mov_read_default(c, pb, atom) < 0)
  424. return -1;
  425. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  426. /* so we don't parse the whole file if over a network */
  427. c->found_moov=1;
  428. return 0; /* now go for mdat */
  429. }
  430. static int mov_read_moof(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  431. {
  432. c->fragment.moof_offset = url_ftell(pb) - 8;
  433. dprintf(c->fc, "moof offset %llx\n", c->fragment.moof_offset);
  434. return mov_read_default(c, pb, atom);
  435. }
  436. static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  437. {
  438. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  439. MOVStreamContext *sc = st->priv_data;
  440. int version = get_byte(pb);
  441. char language[4] = {0};
  442. unsigned lang;
  443. if (version > 1)
  444. return -1; /* unsupported */
  445. get_be24(pb); /* flags */
  446. if (version == 1) {
  447. get_be64(pb);
  448. get_be64(pb);
  449. } else {
  450. get_be32(pb); /* creation time */
  451. get_be32(pb); /* modification time */
  452. }
  453. sc->time_scale = get_be32(pb);
  454. st->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
  455. lang = get_be16(pb); /* language */
  456. if (ff_mov_lang_to_iso639(lang, language))
  457. av_metadata_set(&st->metadata, "language", language);
  458. get_be16(pb); /* quality */
  459. return 0;
  460. }
  461. static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  462. {
  463. int version = get_byte(pb); /* version */
  464. get_be24(pb); /* flags */
  465. if (version == 1) {
  466. get_be64(pb);
  467. get_be64(pb);
  468. } else {
  469. get_be32(pb); /* creation time */
  470. get_be32(pb); /* modification time */
  471. }
  472. c->time_scale = get_be32(pb); /* time scale */
  473. dprintf(c->fc, "time scale = %i\n", c->time_scale);
  474. c->duration = (version == 1) ? get_be64(pb) : get_be32(pb); /* duration */
  475. get_be32(pb); /* preferred scale */
  476. get_be16(pb); /* preferred volume */
  477. url_fskip(pb, 10); /* reserved */
  478. url_fskip(pb, 36); /* display matrix */
  479. get_be32(pb); /* preview time */
  480. get_be32(pb); /* preview duration */
  481. get_be32(pb); /* poster time */
  482. get_be32(pb); /* selection time */
  483. get_be32(pb); /* selection duration */
  484. get_be32(pb); /* current time */
  485. get_be32(pb); /* next track ID */
  486. return 0;
  487. }
  488. static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  489. {
  490. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  491. if((uint64_t)atom.size > (1<<30))
  492. return -1;
  493. // currently SVQ3 decoder expect full STSD header - so let's fake it
  494. // this should be fixed and just SMI header should be passed
  495. av_free(st->codec->extradata);
  496. st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
  497. if (!st->codec->extradata)
  498. return AVERROR(ENOMEM);
  499. st->codec->extradata_size = 0x5a + atom.size;
  500. memcpy(st->codec->extradata, "SVQ3", 4); // fake
  501. get_buffer(pb, st->codec->extradata + 0x5a, atom.size);
  502. dprintf(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
  503. return 0;
  504. }
  505. static int mov_read_enda(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  506. {
  507. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  508. int little_endian = get_be16(pb);
  509. dprintf(c->fc, "enda %d\n", little_endian);
  510. if (little_endian == 1) {
  511. switch (st->codec->codec_id) {
  512. case CODEC_ID_PCM_S24BE:
  513. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  514. break;
  515. case CODEC_ID_PCM_S32BE:
  516. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  517. break;
  518. case CODEC_ID_PCM_F32BE:
  519. st->codec->codec_id = CODEC_ID_PCM_F32LE;
  520. break;
  521. case CODEC_ID_PCM_F64BE:
  522. st->codec->codec_id = CODEC_ID_PCM_F64LE;
  523. break;
  524. default:
  525. break;
  526. }
  527. }
  528. return 0;
  529. }
  530. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  531. static int mov_read_extradata(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  532. {
  533. AVStream *st;
  534. uint64_t size;
  535. uint8_t *buf;
  536. if (c->fc->nb_streams < 1) // will happen with jp2 files
  537. return 0;
  538. st= c->fc->streams[c->fc->nb_streams-1];
  539. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  540. if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  541. return -1;
  542. buf= av_realloc(st->codec->extradata, size);
  543. if(!buf)
  544. return -1;
  545. st->codec->extradata= buf;
  546. buf+= st->codec->extradata_size;
  547. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  548. AV_WB32( buf , atom.size + 8);
  549. AV_WL32( buf + 4, atom.type);
  550. get_buffer(pb, buf + 8, atom.size);
  551. return 0;
  552. }
  553. static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  554. {
  555. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  556. if((uint64_t)atom.size > (1<<30))
  557. return -1;
  558. if (st->codec->codec_id == CODEC_ID_QDM2) {
  559. // pass all frma atom to codec, needed at least for QDM2
  560. av_free(st->codec->extradata);
  561. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  562. if (!st->codec->extradata)
  563. return AVERROR(ENOMEM);
  564. st->codec->extradata_size = atom.size;
  565. get_buffer(pb, st->codec->extradata, atom.size);
  566. } else if (atom.size > 8) { /* to read frma, esds atoms */
  567. if (mov_read_default(c, pb, atom) < 0)
  568. return -1;
  569. } else
  570. url_fskip(pb, atom.size);
  571. return 0;
  572. }
  573. /**
  574. * This function reads atom content and puts data in extradata without tag
  575. * nor size unlike mov_read_extradata.
  576. */
  577. static int mov_read_glbl(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  578. {
  579. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  580. if((uint64_t)atom.size > (1<<30))
  581. return -1;
  582. av_free(st->codec->extradata);
  583. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  584. if (!st->codec->extradata)
  585. return AVERROR(ENOMEM);
  586. st->codec->extradata_size = atom.size;
  587. get_buffer(pb, st->codec->extradata, atom.size);
  588. return 0;
  589. }
  590. static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  591. {
  592. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  593. MOVStreamContext *sc = st->priv_data;
  594. unsigned int i, entries;
  595. get_byte(pb); /* version */
  596. get_be24(pb); /* flags */
  597. entries = get_be32(pb);
  598. if(entries >= UINT_MAX/sizeof(int64_t))
  599. return -1;
  600. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  601. if (!sc->chunk_offsets)
  602. return AVERROR(ENOMEM);
  603. sc->chunk_count = entries;
  604. if (atom.type == MKTAG('s','t','c','o'))
  605. for(i=0; i<entries; i++)
  606. sc->chunk_offsets[i] = get_be32(pb);
  607. else if (atom.type == MKTAG('c','o','6','4'))
  608. for(i=0; i<entries; i++)
  609. sc->chunk_offsets[i] = get_be64(pb);
  610. else
  611. return -1;
  612. return 0;
  613. }
  614. /**
  615. * Compute codec id for 'lpcm' tag.
  616. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  617. */
  618. static enum CodecID mov_get_lpcm_codec_id(int bps, int flags)
  619. {
  620. if (flags & 1) { // floating point
  621. if (flags & 2) { // big endian
  622. if (bps == 32) return CODEC_ID_PCM_F32BE;
  623. else if (bps == 64) return CODEC_ID_PCM_F64BE;
  624. } else {
  625. if (bps == 32) return CODEC_ID_PCM_F32LE;
  626. else if (bps == 64) return CODEC_ID_PCM_F64LE;
  627. }
  628. } else {
  629. if (flags & 2) {
  630. if (bps == 8)
  631. // signed integer
  632. if (flags & 4) return CODEC_ID_PCM_S8;
  633. else return CODEC_ID_PCM_U8;
  634. else if (bps == 16) return CODEC_ID_PCM_S16BE;
  635. else if (bps == 24) return CODEC_ID_PCM_S24BE;
  636. else if (bps == 32) return CODEC_ID_PCM_S32BE;
  637. } else {
  638. if (bps == 8)
  639. if (flags & 4) return CODEC_ID_PCM_S8;
  640. else return CODEC_ID_PCM_U8;
  641. else if (bps == 16) return CODEC_ID_PCM_S16LE;
  642. else if (bps == 24) return CODEC_ID_PCM_S24LE;
  643. else if (bps == 32) return CODEC_ID_PCM_S32LE;
  644. }
  645. }
  646. return CODEC_ID_NONE;
  647. }
  648. static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  649. {
  650. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  651. MOVStreamContext *sc = st->priv_data;
  652. int j, entries, pseudo_stream_id;
  653. get_byte(pb); /* version */
  654. get_be24(pb); /* flags */
  655. entries = get_be32(pb);
  656. for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
  657. //Parsing Sample description table
  658. enum CodecID id;
  659. int dref_id;
  660. MOVAtom a = { 0, 0, 0 };
  661. int64_t start_pos = url_ftell(pb);
  662. int size = get_be32(pb); /* size */
  663. uint32_t format = get_le32(pb); /* data format */
  664. get_be32(pb); /* reserved */
  665. get_be16(pb); /* reserved */
  666. dref_id = get_be16(pb);
  667. if (st->codec->codec_tag &&
  668. st->codec->codec_tag != format &&
  669. (c->fc->video_codec_id ? codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
  670. : st->codec->codec_tag != MKTAG('j','p','e','g'))
  671. ){
  672. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  673. * export it as a separate AVStream but this needs a few changes
  674. * in the MOV demuxer, patch welcome. */
  675. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  676. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  677. continue;
  678. }
  679. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  680. sc->dref_id= dref_id;
  681. st->codec->codec_tag = format;
  682. id = codec_get_id(codec_movaudio_tags, format);
  683. if (id<=0 && (format&0xFFFF) == 'm'+('s'<<8))
  684. id = codec_get_id(codec_wav_tags, bswap_32(format)&0xFFFF);
  685. if (st->codec->codec_type != CODEC_TYPE_VIDEO && id > 0) {
  686. st->codec->codec_type = CODEC_TYPE_AUDIO;
  687. } else if (st->codec->codec_type != CODEC_TYPE_AUDIO && /* do not overwrite codec type */
  688. format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
  689. id = codec_get_id(codec_movvideo_tags, format);
  690. if (id <= 0)
  691. id = codec_get_id(codec_bmp_tags, format);
  692. if (id > 0)
  693. st->codec->codec_type = CODEC_TYPE_VIDEO;
  694. else if(st->codec->codec_type == CODEC_TYPE_DATA){
  695. id = codec_get_id(ff_codec_movsubtitle_tags, format);
  696. if(id > 0)
  697. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  698. }
  699. }
  700. dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
  701. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  702. (format >> 24) & 0xff, st->codec->codec_type);
  703. if(st->codec->codec_type==CODEC_TYPE_VIDEO) {
  704. uint8_t codec_name[32];
  705. unsigned int color_depth;
  706. int color_greyscale;
  707. st->codec->codec_id = id;
  708. get_be16(pb); /* version */
  709. get_be16(pb); /* revision level */
  710. get_be32(pb); /* vendor */
  711. get_be32(pb); /* temporal quality */
  712. get_be32(pb); /* spatial quality */
  713. st->codec->width = get_be16(pb); /* width */
  714. st->codec->height = get_be16(pb); /* height */
  715. get_be32(pb); /* horiz resolution */
  716. get_be32(pb); /* vert resolution */
  717. get_be32(pb); /* data size, always 0 */
  718. get_be16(pb); /* frames per samples */
  719. get_buffer(pb, codec_name, 32); /* codec name, pascal string */
  720. if (codec_name[0] <= 31) {
  721. memcpy(st->codec->codec_name, &codec_name[1],codec_name[0]);
  722. st->codec->codec_name[codec_name[0]] = 0;
  723. }
  724. st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
  725. st->codec->color_table_id = get_be16(pb); /* colortable id */
  726. dprintf(c->fc, "depth %d, ctab id %d\n",
  727. st->codec->bits_per_coded_sample, st->codec->color_table_id);
  728. /* figure out the palette situation */
  729. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  730. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  731. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  732. if ((color_depth == 2) || (color_depth == 4) ||
  733. (color_depth == 8)) {
  734. /* for palette traversal */
  735. unsigned int color_start, color_count, color_end;
  736. unsigned char r, g, b;
  737. st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
  738. if (color_greyscale) {
  739. int color_index, color_dec;
  740. /* compute the greyscale palette */
  741. st->codec->bits_per_coded_sample = color_depth;
  742. color_count = 1 << color_depth;
  743. color_index = 255;
  744. color_dec = 256 / (color_count - 1);
  745. for (j = 0; j < color_count; j++) {
  746. r = g = b = color_index;
  747. st->codec->palctrl->palette[j] =
  748. (r << 16) | (g << 8) | (b);
  749. color_index -= color_dec;
  750. if (color_index < 0)
  751. color_index = 0;
  752. }
  753. } else if (st->codec->color_table_id) {
  754. const uint8_t *color_table;
  755. /* if flag bit 3 is set, use the default palette */
  756. color_count = 1 << color_depth;
  757. if (color_depth == 2)
  758. color_table = ff_qt_default_palette_4;
  759. else if (color_depth == 4)
  760. color_table = ff_qt_default_palette_16;
  761. else
  762. color_table = ff_qt_default_palette_256;
  763. for (j = 0; j < color_count; j++) {
  764. r = color_table[j * 4 + 0];
  765. g = color_table[j * 4 + 1];
  766. b = color_table[j * 4 + 2];
  767. st->codec->palctrl->palette[j] =
  768. (r << 16) | (g << 8) | (b);
  769. }
  770. } else {
  771. /* load the palette from the file */
  772. color_start = get_be32(pb);
  773. color_count = get_be16(pb);
  774. color_end = get_be16(pb);
  775. if ((color_start <= 255) &&
  776. (color_end <= 255)) {
  777. for (j = color_start; j <= color_end; j++) {
  778. /* each R, G, or B component is 16 bits;
  779. * only use the top 8 bits; skip alpha bytes
  780. * up front */
  781. get_byte(pb);
  782. get_byte(pb);
  783. r = get_byte(pb);
  784. get_byte(pb);
  785. g = get_byte(pb);
  786. get_byte(pb);
  787. b = get_byte(pb);
  788. get_byte(pb);
  789. st->codec->palctrl->palette[j] =
  790. (r << 16) | (g << 8) | (b);
  791. }
  792. }
  793. }
  794. st->codec->palctrl->palette_changed = 1;
  795. }
  796. } else if(st->codec->codec_type==CODEC_TYPE_AUDIO) {
  797. int bits_per_sample, flags;
  798. uint16_t version = get_be16(pb);
  799. st->codec->codec_id = id;
  800. get_be16(pb); /* revision level */
  801. get_be32(pb); /* vendor */
  802. st->codec->channels = get_be16(pb); /* channel count */
  803. dprintf(c->fc, "audio channels %d\n", st->codec->channels);
  804. st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
  805. sc->audio_cid = get_be16(pb);
  806. get_be16(pb); /* packet size = 0 */
  807. st->codec->sample_rate = ((get_be32(pb) >> 16));
  808. //Read QT version 1 fields. In version 0 these do not exist.
  809. dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
  810. if(!c->isom) {
  811. if(version==1) {
  812. sc->samples_per_frame = get_be32(pb);
  813. get_be32(pb); /* bytes per packet */
  814. sc->bytes_per_frame = get_be32(pb);
  815. get_be32(pb); /* bytes per sample */
  816. } else if(version==2) {
  817. get_be32(pb); /* sizeof struct only */
  818. st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
  819. st->codec->channels = get_be32(pb);
  820. get_be32(pb); /* always 0x7F000000 */
  821. st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
  822. flags = get_be32(pb); /* lcpm format specific flag */
  823. sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
  824. sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
  825. if (format == MKTAG('l','p','c','m'))
  826. st->codec->codec_id = mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  827. }
  828. }
  829. switch (st->codec->codec_id) {
  830. case CODEC_ID_PCM_S8:
  831. case CODEC_ID_PCM_U8:
  832. if (st->codec->bits_per_coded_sample == 16)
  833. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  834. break;
  835. case CODEC_ID_PCM_S16LE:
  836. case CODEC_ID_PCM_S16BE:
  837. if (st->codec->bits_per_coded_sample == 8)
  838. st->codec->codec_id = CODEC_ID_PCM_S8;
  839. else if (st->codec->bits_per_coded_sample == 24)
  840. st->codec->codec_id =
  841. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  842. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  843. break;
  844. /* set values for old format before stsd version 1 appeared */
  845. case CODEC_ID_MACE3:
  846. sc->samples_per_frame = 6;
  847. sc->bytes_per_frame = 2*st->codec->channels;
  848. break;
  849. case CODEC_ID_MACE6:
  850. sc->samples_per_frame = 6;
  851. sc->bytes_per_frame = 1*st->codec->channels;
  852. break;
  853. case CODEC_ID_ADPCM_IMA_QT:
  854. sc->samples_per_frame = 64;
  855. sc->bytes_per_frame = 34*st->codec->channels;
  856. break;
  857. case CODEC_ID_GSM:
  858. sc->samples_per_frame = 160;
  859. sc->bytes_per_frame = 33;
  860. break;
  861. default:
  862. break;
  863. }
  864. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  865. if (bits_per_sample) {
  866. st->codec->bits_per_coded_sample = bits_per_sample;
  867. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  868. }
  869. } else if(st->codec->codec_type==CODEC_TYPE_SUBTITLE){
  870. // ttxt stsd contains display flags, justification, background
  871. // color, fonts, and default styles, so fake an atom to read it
  872. MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
  873. mov_read_glbl(c, pb, fake_atom);
  874. st->codec->codec_id= id;
  875. st->codec->width = sc->width;
  876. st->codec->height = sc->height;
  877. } else {
  878. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  879. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  880. }
  881. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  882. a.size = size - (url_ftell(pb) - start_pos);
  883. if (a.size > 8) {
  884. if (mov_read_default(c, pb, a) < 0)
  885. return -1;
  886. } else if (a.size > 0)
  887. url_fskip(pb, a.size);
  888. }
  889. if(st->codec->codec_type==CODEC_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  890. st->codec->sample_rate= sc->time_scale;
  891. /* special codec parameters handling */
  892. switch (st->codec->codec_id) {
  893. #if CONFIG_DV_DEMUXER
  894. case CODEC_ID_DVAUDIO:
  895. c->dv_fctx = avformat_alloc_context();
  896. c->dv_demux = dv_init_demux(c->dv_fctx);
  897. if (!c->dv_demux) {
  898. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  899. return -1;
  900. }
  901. sc->dv_audio_container = 1;
  902. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  903. break;
  904. #endif
  905. /* no ifdef since parameters are always those */
  906. case CODEC_ID_QCELP:
  907. st->codec->frame_size= 160;
  908. st->codec->channels= 1; /* really needed */
  909. break;
  910. case CODEC_ID_AMR_NB:
  911. case CODEC_ID_AMR_WB:
  912. st->codec->frame_size= sc->samples_per_frame;
  913. st->codec->channels= 1; /* really needed */
  914. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  915. if (st->codec->codec_id == CODEC_ID_AMR_NB)
  916. st->codec->sample_rate = 8000;
  917. else if (st->codec->codec_id == CODEC_ID_AMR_WB)
  918. st->codec->sample_rate = 16000;
  919. break;
  920. case CODEC_ID_MP2:
  921. case CODEC_ID_MP3:
  922. st->codec->codec_type = CODEC_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  923. st->need_parsing = AVSTREAM_PARSE_FULL;
  924. break;
  925. case CODEC_ID_GSM:
  926. case CODEC_ID_ADPCM_MS:
  927. case CODEC_ID_ADPCM_IMA_WAV:
  928. st->codec->block_align = sc->bytes_per_frame;
  929. break;
  930. case CODEC_ID_ALAC:
  931. if (st->codec->extradata_size == 36) {
  932. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  933. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  934. }
  935. break;
  936. default:
  937. break;
  938. }
  939. return 0;
  940. }
  941. static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  942. {
  943. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  944. MOVStreamContext *sc = st->priv_data;
  945. unsigned int i, entries;
  946. get_byte(pb); /* version */
  947. get_be24(pb); /* flags */
  948. entries = get_be32(pb);
  949. dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  950. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  951. return -1;
  952. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  953. if (!sc->stsc_data)
  954. return AVERROR(ENOMEM);
  955. sc->stsc_count = entries;
  956. for(i=0; i<entries; i++) {
  957. sc->stsc_data[i].first = get_be32(pb);
  958. sc->stsc_data[i].count = get_be32(pb);
  959. sc->stsc_data[i].id = get_be32(pb);
  960. }
  961. return 0;
  962. }
  963. static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  964. {
  965. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  966. MOVStreamContext *sc = st->priv_data;
  967. unsigned int i, entries;
  968. get_byte(pb); /* version */
  969. get_be24(pb); /* flags */
  970. entries = get_be32(pb);
  971. dprintf(c->fc, "keyframe_count = %d\n", entries);
  972. if(entries >= UINT_MAX / sizeof(int))
  973. return -1;
  974. sc->keyframes = av_malloc(entries * sizeof(int));
  975. if (!sc->keyframes)
  976. return AVERROR(ENOMEM);
  977. sc->keyframe_count = entries;
  978. for(i=0; i<entries; i++) {
  979. sc->keyframes[i] = get_be32(pb);
  980. //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  981. }
  982. return 0;
  983. }
  984. static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  985. {
  986. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  987. MOVStreamContext *sc = st->priv_data;
  988. unsigned int i, entries, sample_size;
  989. get_byte(pb); /* version */
  990. get_be24(pb); /* flags */
  991. sample_size = get_be32(pb);
  992. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  993. sc->sample_size = sample_size;
  994. entries = get_be32(pb);
  995. dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  996. sc->sample_count = entries;
  997. if (sample_size)
  998. return 0;
  999. if(entries >= UINT_MAX / sizeof(int))
  1000. return -1;
  1001. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1002. if (!sc->sample_sizes)
  1003. return AVERROR(ENOMEM);
  1004. for(i=0; i<entries; i++)
  1005. sc->sample_sizes[i] = get_be32(pb);
  1006. return 0;
  1007. }
  1008. static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1009. {
  1010. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1011. MOVStreamContext *sc = st->priv_data;
  1012. unsigned int i, entries;
  1013. int64_t duration=0;
  1014. int64_t total_sample_count=0;
  1015. get_byte(pb); /* version */
  1016. get_be24(pb); /* flags */
  1017. entries = get_be32(pb);
  1018. dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1019. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1020. return -1;
  1021. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1022. if (!sc->stts_data)
  1023. return AVERROR(ENOMEM);
  1024. sc->stts_count = entries;
  1025. for(i=0; i<entries; i++) {
  1026. int sample_duration;
  1027. int sample_count;
  1028. sample_count=get_be32(pb);
  1029. sample_duration = get_be32(pb);
  1030. sc->stts_data[i].count= sample_count;
  1031. sc->stts_data[i].duration= sample_duration;
  1032. sc->time_rate= av_gcd(sc->time_rate, sample_duration);
  1033. dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1034. duration+=(int64_t)sample_duration*sample_count;
  1035. total_sample_count+=sample_count;
  1036. }
  1037. st->nb_frames= total_sample_count;
  1038. if(duration)
  1039. st->duration= duration;
  1040. return 0;
  1041. }
  1042. static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1043. {
  1044. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1045. MOVStreamContext *sc = st->priv_data;
  1046. unsigned int i, entries;
  1047. get_byte(pb); /* version */
  1048. get_be24(pb); /* flags */
  1049. entries = get_be32(pb);
  1050. dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1051. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1052. return -1;
  1053. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1054. if (!sc->ctts_data)
  1055. return AVERROR(ENOMEM);
  1056. sc->ctts_count = entries;
  1057. for(i=0; i<entries; i++) {
  1058. int count =get_be32(pb);
  1059. int duration =get_be32(pb);
  1060. if (duration < 0) {
  1061. sc->wrong_dts = 1;
  1062. st->codec->has_b_frames = 1;
  1063. }
  1064. sc->ctts_data[i].count = count;
  1065. sc->ctts_data[i].duration= duration;
  1066. sc->time_rate= av_gcd(sc->time_rate, FFABS(duration));
  1067. }
  1068. return 0;
  1069. }
  1070. static void mov_build_index(MOVContext *mov, AVStream *st)
  1071. {
  1072. MOVStreamContext *sc = st->priv_data;
  1073. int64_t current_offset;
  1074. int64_t current_dts = 0;
  1075. unsigned int stts_index = 0;
  1076. unsigned int stsc_index = 0;
  1077. unsigned int stss_index = 0;
  1078. unsigned int i, j;
  1079. /* adjust first dts according to edit list */
  1080. if (sc->time_offset) {
  1081. assert(sc->time_offset % sc->time_rate == 0);
  1082. current_dts = - (sc->time_offset / sc->time_rate);
  1083. }
  1084. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1085. if (!(st->codec->codec_type == CODEC_TYPE_AUDIO &&
  1086. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1087. unsigned int current_sample = 0;
  1088. unsigned int stts_sample = 0;
  1089. unsigned int keyframe, sample_size;
  1090. unsigned int distance = 0;
  1091. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1092. st->nb_frames = sc->sample_count;
  1093. for (i = 0; i < sc->chunk_count; i++) {
  1094. current_offset = sc->chunk_offsets[i];
  1095. if (stsc_index + 1 < sc->stsc_count &&
  1096. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1097. stsc_index++;
  1098. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1099. if (current_sample >= sc->sample_count) {
  1100. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1101. return;
  1102. }
  1103. keyframe = !sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index];
  1104. if (keyframe) {
  1105. distance = 0;
  1106. if (stss_index + 1 < sc->keyframe_count)
  1107. stss_index++;
  1108. }
  1109. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1110. if(sc->pseudo_stream_id == -1 ||
  1111. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1112. av_add_index_entry(st, current_offset, current_dts, sample_size, distance,
  1113. keyframe ? AVINDEX_KEYFRAME : 0);
  1114. dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1115. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1116. current_offset, current_dts, sample_size, distance, keyframe);
  1117. }
  1118. current_offset += sample_size;
  1119. assert(sc->stts_data[stts_index].duration % sc->time_rate == 0);
  1120. current_dts += sc->stts_data[stts_index].duration / sc->time_rate;
  1121. distance++;
  1122. stts_sample++;
  1123. current_sample++;
  1124. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1125. stts_sample = 0;
  1126. stts_index++;
  1127. }
  1128. }
  1129. }
  1130. } else { /* read whole chunk */
  1131. unsigned int chunk_samples, chunk_size, chunk_duration;
  1132. unsigned int frames = 1;
  1133. for (i = 0; i < sc->chunk_count; i++) {
  1134. current_offset = sc->chunk_offsets[i];
  1135. if (stsc_index + 1 < sc->stsc_count &&
  1136. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1137. stsc_index++;
  1138. chunk_samples = sc->stsc_data[stsc_index].count;
  1139. /* get chunk size, beware of alaw/ulaw/mace */
  1140. if (sc->samples_per_frame > 0 &&
  1141. (chunk_samples * sc->bytes_per_frame % sc->samples_per_frame == 0)) {
  1142. if (sc->samples_per_frame < 160)
  1143. chunk_size = chunk_samples * sc->bytes_per_frame / sc->samples_per_frame;
  1144. else {
  1145. chunk_size = sc->bytes_per_frame;
  1146. frames = chunk_samples / sc->samples_per_frame;
  1147. chunk_samples = sc->samples_per_frame;
  1148. }
  1149. } else
  1150. chunk_size = chunk_samples * sc->sample_size;
  1151. for (j = 0; j < frames; j++) {
  1152. av_add_index_entry(st, current_offset, current_dts, chunk_size, 0, AVINDEX_KEYFRAME);
  1153. /* get chunk duration */
  1154. chunk_duration = 0;
  1155. while (chunk_samples > 0) {
  1156. if (chunk_samples < sc->stts_data[stts_index].count) {
  1157. chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
  1158. sc->stts_data[stts_index].count -= chunk_samples;
  1159. break;
  1160. } else {
  1161. chunk_duration += sc->stts_data[stts_index].duration * chunk_samples;
  1162. chunk_samples -= sc->stts_data[stts_index].count;
  1163. if (stts_index + 1 < sc->stts_count)
  1164. stts_index++;
  1165. }
  1166. }
  1167. current_offset += sc->bytes_per_frame;
  1168. dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1169. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1170. chunk_size, chunk_duration);
  1171. assert(chunk_duration % sc->time_rate == 0);
  1172. current_dts += chunk_duration / sc->time_rate;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1178. {
  1179. AVStream *st;
  1180. MOVStreamContext *sc;
  1181. int ret;
  1182. st = av_new_stream(c->fc, c->fc->nb_streams);
  1183. if (!st) return AVERROR(ENOMEM);
  1184. sc = av_mallocz(sizeof(MOVStreamContext));
  1185. if (!sc) return AVERROR(ENOMEM);
  1186. st->priv_data = sc;
  1187. st->codec->codec_type = CODEC_TYPE_DATA;
  1188. sc->ffindex = st->index;
  1189. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1190. return ret;
  1191. /* sanity checks */
  1192. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1193. (!sc->sample_size && !sc->sample_count))) {
  1194. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1195. st->index);
  1196. return 0;
  1197. }
  1198. if (!sc->time_rate)
  1199. sc->time_rate = 1;
  1200. if (!sc->time_scale)
  1201. sc->time_scale = c->time_scale;
  1202. av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);
  1203. if (st->codec->codec_type == CODEC_TYPE_AUDIO &&
  1204. !st->codec->frame_size && sc->stts_count == 1) {
  1205. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1206. st->codec->sample_rate, sc->time_scale);
  1207. dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
  1208. }
  1209. if (st->duration != AV_NOPTS_VALUE) {
  1210. assert(st->duration % sc->time_rate == 0);
  1211. st->duration /= sc->time_rate;
  1212. }
  1213. mov_build_index(c, st);
  1214. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1215. if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)
  1216. av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",
  1217. st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));
  1218. } else
  1219. sc->pb = c->fc->pb;
  1220. switch (st->codec->codec_id) {
  1221. #if CONFIG_H261_DECODER
  1222. case CODEC_ID_H261:
  1223. #endif
  1224. #if CONFIG_H263_DECODER
  1225. case CODEC_ID_H263:
  1226. #endif
  1227. #if CONFIG_MPEG4_DECODER
  1228. case CODEC_ID_MPEG4:
  1229. #endif
  1230. st->codec->width = 0; /* let decoder init width/height */
  1231. st->codec->height= 0;
  1232. break;
  1233. }
  1234. /* Do not need those anymore. */
  1235. av_freep(&sc->chunk_offsets);
  1236. av_freep(&sc->stsc_data);
  1237. av_freep(&sc->sample_sizes);
  1238. av_freep(&sc->keyframes);
  1239. av_freep(&sc->stts_data);
  1240. return 0;
  1241. }
  1242. static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1243. {
  1244. int ret;
  1245. c->itunes_metadata = 1;
  1246. ret = mov_read_default(c, pb, atom);
  1247. c->itunes_metadata = 0;
  1248. return ret;
  1249. }
  1250. static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1251. {
  1252. while (atom.size > 8) {
  1253. uint32_t tag = get_le32(pb);
  1254. atom.size -= 4;
  1255. if (tag == MKTAG('h','d','l','r')) {
  1256. url_fseek(pb, -8, SEEK_CUR);
  1257. atom.size += 8;
  1258. return mov_read_default(c, pb, atom);
  1259. }
  1260. }
  1261. return 0;
  1262. }
  1263. static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1264. {
  1265. int i;
  1266. int width;
  1267. int height;
  1268. int64_t disp_transform[2];
  1269. int display_matrix[3][2];
  1270. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1271. MOVStreamContext *sc = st->priv_data;
  1272. int version = get_byte(pb);
  1273. get_be24(pb); /* flags */
  1274. /*
  1275. MOV_TRACK_ENABLED 0x0001
  1276. MOV_TRACK_IN_MOVIE 0x0002
  1277. MOV_TRACK_IN_PREVIEW 0x0004
  1278. MOV_TRACK_IN_POSTER 0x0008
  1279. */
  1280. if (version == 1) {
  1281. get_be64(pb);
  1282. get_be64(pb);
  1283. } else {
  1284. get_be32(pb); /* creation time */
  1285. get_be32(pb); /* modification time */
  1286. }
  1287. st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
  1288. get_be32(pb); /* reserved */
  1289. /* highlevel (considering edits) duration in movie timebase */
  1290. (version == 1) ? get_be64(pb) : get_be32(pb);
  1291. get_be32(pb); /* reserved */
  1292. get_be32(pb); /* reserved */
  1293. get_be16(pb); /* layer */
  1294. get_be16(pb); /* alternate group */
  1295. get_be16(pb); /* volume */
  1296. get_be16(pb); /* reserved */
  1297. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1298. // they're kept in fixed point format through all calculations
  1299. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1300. for (i = 0; i < 3; i++) {
  1301. display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
  1302. display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
  1303. get_be32(pb); // 2.30 fixed point (not used)
  1304. }
  1305. width = get_be32(pb); // 16.16 fixed point track width
  1306. height = get_be32(pb); // 16.16 fixed point track height
  1307. sc->width = width >> 16;
  1308. sc->height = height >> 16;
  1309. //transform the display width/height according to the matrix
  1310. // skip this if the display matrix is the default identity matrix
  1311. // to keep the same scale, use [width height 1<<16]
  1312. if (width && height &&
  1313. (display_matrix[0][0] != 65536 || display_matrix[0][1] ||
  1314. display_matrix[1][0] || display_matrix[1][1] != 65536 ||
  1315. display_matrix[2][0] || display_matrix[2][1])) {
  1316. for (i = 0; i < 2; i++)
  1317. disp_transform[i] =
  1318. (int64_t) width * display_matrix[0][i] +
  1319. (int64_t) height * display_matrix[1][i] +
  1320. ((int64_t) display_matrix[2][i] << 16);
  1321. //sample aspect ratio is new width/height divided by old width/height
  1322. st->sample_aspect_ratio = av_d2q(
  1323. ((double) disp_transform[0] * height) /
  1324. ((double) disp_transform[1] * width), INT_MAX);
  1325. }
  1326. return 0;
  1327. }
  1328. static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1329. {
  1330. MOVFragment *frag = &c->fragment;
  1331. MOVTrackExt *trex = NULL;
  1332. int flags, track_id, i;
  1333. get_byte(pb); /* version */
  1334. flags = get_be24(pb);
  1335. track_id = get_be32(pb);
  1336. if (!track_id)
  1337. return -1;
  1338. frag->track_id = track_id;
  1339. for (i = 0; i < c->trex_count; i++)
  1340. if (c->trex_data[i].track_id == frag->track_id) {
  1341. trex = &c->trex_data[i];
  1342. break;
  1343. }
  1344. if (!trex) {
  1345. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1346. return -1;
  1347. }
  1348. if (flags & 0x01) frag->base_data_offset = get_be64(pb);
  1349. else frag->base_data_offset = frag->moof_offset;
  1350. if (flags & 0x02) frag->stsd_id = get_be32(pb);
  1351. else frag->stsd_id = trex->stsd_id;
  1352. frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
  1353. frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
  1354. frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
  1355. dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
  1356. return 0;
  1357. }
  1358. static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1359. {
  1360. MOVTrackExt *trex;
  1361. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1362. return -1;
  1363. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1364. if (!trex)
  1365. return AVERROR(ENOMEM);
  1366. c->trex_data = trex;
  1367. trex = &c->trex_data[c->trex_count++];
  1368. get_byte(pb); /* version */
  1369. get_be24(pb); /* flags */
  1370. trex->track_id = get_be32(pb);
  1371. trex->stsd_id = get_be32(pb);
  1372. trex->duration = get_be32(pb);
  1373. trex->size = get_be32(pb);
  1374. trex->flags = get_be32(pb);
  1375. return 0;
  1376. }
  1377. static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1378. {
  1379. MOVFragment *frag = &c->fragment;
  1380. AVStream *st = NULL;
  1381. MOVStreamContext *sc;
  1382. uint64_t offset;
  1383. int64_t dts;
  1384. int data_offset = 0;
  1385. unsigned entries, first_sample_flags = frag->flags;
  1386. int flags, distance, i;
  1387. for (i = 0; i < c->fc->nb_streams; i++) {
  1388. if (c->fc->streams[i]->id == frag->track_id) {
  1389. st = c->fc->streams[i];
  1390. break;
  1391. }
  1392. }
  1393. if (!st) {
  1394. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1395. return -1;
  1396. }
  1397. sc = st->priv_data;
  1398. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1399. return 0;
  1400. get_byte(pb); /* version */
  1401. flags = get_be24(pb);
  1402. entries = get_be32(pb);
  1403. dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1404. if (flags & 0x001) data_offset = get_be32(pb);
  1405. if (flags & 0x004) first_sample_flags = get_be32(pb);
  1406. if (flags & 0x800) {
  1407. MOVStts *ctts_data;
  1408. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1409. return -1;
  1410. ctts_data = av_realloc(sc->ctts_data,
  1411. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1412. if (!ctts_data)
  1413. return AVERROR(ENOMEM);
  1414. sc->ctts_data = ctts_data;
  1415. }
  1416. dts = st->duration;
  1417. offset = frag->base_data_offset + data_offset;
  1418. distance = 0;
  1419. dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1420. for (i = 0; i < entries; i++) {
  1421. unsigned sample_size = frag->size;
  1422. int sample_flags = i ? frag->flags : first_sample_flags;
  1423. unsigned sample_duration = frag->duration;
  1424. int keyframe;
  1425. if (flags & 0x100) sample_duration = get_be32(pb);
  1426. if (flags & 0x200) sample_size = get_be32(pb);
  1427. if (flags & 0x400) sample_flags = get_be32(pb);
  1428. if (flags & 0x800) {
  1429. sc->ctts_data[sc->ctts_count].count = 1;
  1430. sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
  1431. sc->ctts_count++;
  1432. }
  1433. if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||
  1434. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1435. distance = 0;
  1436. av_add_index_entry(st, offset, dts, sample_size, distance,
  1437. keyframe ? AVINDEX_KEYFRAME : 0);
  1438. dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1439. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1440. offset, dts, sample_size, distance, keyframe);
  1441. distance++;
  1442. assert(sample_duration % sc->time_rate == 0);
  1443. dts += sample_duration / sc->time_rate;
  1444. offset += sample_size;
  1445. }
  1446. frag->moof_offset = offset;
  1447. st->duration = dts;
  1448. return 0;
  1449. }
  1450. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1451. /* like the files created with Adobe Premiere 5.0, for samples see */
  1452. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1453. static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1454. {
  1455. int err;
  1456. if (atom.size < 8)
  1457. return 0; /* continue */
  1458. if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1459. url_fskip(pb, atom.size - 4);
  1460. return 0;
  1461. }
  1462. atom.type = get_le32(pb);
  1463. atom.offset += 8;
  1464. atom.size -= 8;
  1465. if (atom.type != MKTAG('m','d','a','t')) {
  1466. url_fskip(pb, atom.size);
  1467. return 0;
  1468. }
  1469. err = mov_read_mdat(c, pb, atom);
  1470. return err;
  1471. }
  1472. static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1473. {
  1474. #if CONFIG_ZLIB
  1475. ByteIOContext ctx;
  1476. uint8_t *cmov_data;
  1477. uint8_t *moov_data; /* uncompressed data */
  1478. long cmov_len, moov_len;
  1479. int ret = -1;
  1480. get_be32(pb); /* dcom atom */
  1481. if (get_le32(pb) != MKTAG('d','c','o','m'))
  1482. return -1;
  1483. if (get_le32(pb) != MKTAG('z','l','i','b')) {
  1484. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1485. return -1;
  1486. }
  1487. get_be32(pb); /* cmvd atom */
  1488. if (get_le32(pb) != MKTAG('c','m','v','d'))
  1489. return -1;
  1490. moov_len = get_be32(pb); /* uncompressed size */
  1491. cmov_len = atom.size - 6 * 4;
  1492. cmov_data = av_malloc(cmov_len);
  1493. if (!cmov_data)
  1494. return AVERROR(ENOMEM);
  1495. moov_data = av_malloc(moov_len);
  1496. if (!moov_data) {
  1497. av_free(cmov_data);
  1498. return AVERROR(ENOMEM);
  1499. }
  1500. get_buffer(pb, cmov_data, cmov_len);
  1501. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1502. goto free_and_return;
  1503. if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1504. goto free_and_return;
  1505. atom.type = MKTAG('m','o','o','v');
  1506. atom.offset = 0;
  1507. atom.size = moov_len;
  1508. #ifdef DEBUG
  1509. // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
  1510. #endif
  1511. ret = mov_read_default(c, &ctx, atom);
  1512. free_and_return:
  1513. av_free(moov_data);
  1514. av_free(cmov_data);
  1515. return ret;
  1516. #else
  1517. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1518. return -1;
  1519. #endif
  1520. }
  1521. /* edit list atom */
  1522. static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1523. {
  1524. MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1525. int i, edit_count;
  1526. get_byte(pb); /* version */
  1527. get_be24(pb); /* flags */
  1528. edit_count = get_be32(pb); /* entries */
  1529. for(i=0; i<edit_count; i++){
  1530. int time;
  1531. get_be32(pb); /* Track duration */
  1532. time = get_be32(pb); /* Media time */
  1533. get_be32(pb); /* Media rate */
  1534. if (i == 0 && time != -1) {
  1535. sc->time_offset = time;
  1536. sc->time_rate = av_gcd(sc->time_rate, time);
  1537. }
  1538. }
  1539. if(edit_count > 1)
  1540. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1541. "a/v desync might occur, patch welcome\n");
  1542. dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1543. return 0;
  1544. }
  1545. static const MOVParseTableEntry mov_default_parse_table[] = {
  1546. { MKTAG('a','v','s','s'), mov_read_extradata },
  1547. { MKTAG('c','o','6','4'), mov_read_stco },
  1548. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1549. { MKTAG('d','i','n','f'), mov_read_default },
  1550. { MKTAG('d','r','e','f'), mov_read_dref },
  1551. { MKTAG('e','d','t','s'), mov_read_default },
  1552. { MKTAG('e','l','s','t'), mov_read_elst },
  1553. { MKTAG('e','n','d','a'), mov_read_enda },
  1554. { MKTAG('f','i','e','l'), mov_read_extradata },
  1555. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1556. { MKTAG('g','l','b','l'), mov_read_glbl },
  1557. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1558. { MKTAG('i','l','s','t'), mov_read_ilst },
  1559. { MKTAG('j','p','2','h'), mov_read_extradata },
  1560. { MKTAG('m','d','a','t'), mov_read_mdat },
  1561. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1562. { MKTAG('m','d','i','a'), mov_read_default },
  1563. { MKTAG('m','e','t','a'), mov_read_meta },
  1564. { MKTAG('m','i','n','f'), mov_read_default },
  1565. { MKTAG('m','o','o','f'), mov_read_moof },
  1566. { MKTAG('m','o','o','v'), mov_read_moov },
  1567. { MKTAG('m','v','e','x'), mov_read_default },
  1568. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1569. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1570. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1571. { MKTAG('a','v','c','C'), mov_read_glbl },
  1572. { MKTAG('p','a','s','p'), mov_read_pasp },
  1573. { MKTAG('s','t','b','l'), mov_read_default },
  1574. { MKTAG('s','t','c','o'), mov_read_stco },
  1575. { MKTAG('s','t','s','c'), mov_read_stsc },
  1576. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1577. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1578. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1579. { MKTAG('s','t','t','s'), mov_read_stts },
  1580. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1581. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1582. { MKTAG('t','r','a','k'), mov_read_trak },
  1583. { MKTAG('t','r','a','f'), mov_read_default },
  1584. { MKTAG('t','r','e','x'), mov_read_trex },
  1585. { MKTAG('t','r','u','n'), mov_read_trun },
  1586. { MKTAG('u','d','t','a'), mov_read_default },
  1587. { MKTAG('w','a','v','e'), mov_read_wave },
  1588. { MKTAG('e','s','d','s'), mov_read_esds },
  1589. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1590. { MKTAG('c','m','o','v'), mov_read_cmov },
  1591. { 0, NULL }
  1592. };
  1593. static int mov_probe(AVProbeData *p)
  1594. {
  1595. unsigned int offset;
  1596. uint32_t tag;
  1597. int score = 0;
  1598. /* check file header */
  1599. offset = 0;
  1600. for(;;) {
  1601. /* ignore invalid offset */
  1602. if ((offset + 8) > (unsigned int)p->buf_size)
  1603. return score;
  1604. tag = AV_RL32(p->buf + offset + 4);
  1605. switch(tag) {
  1606. /* check for obvious tags */
  1607. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  1608. case MKTAG('m','o','o','v'):
  1609. case MKTAG('m','d','a','t'):
  1610. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  1611. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  1612. case MKTAG('f','t','y','p'):
  1613. return AVPROBE_SCORE_MAX;
  1614. /* those are more common words, so rate then a bit less */
  1615. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  1616. case MKTAG('w','i','d','e'):
  1617. case MKTAG('f','r','e','e'):
  1618. case MKTAG('j','u','n','k'):
  1619. case MKTAG('p','i','c','t'):
  1620. return AVPROBE_SCORE_MAX - 5;
  1621. case MKTAG(0x82,0x82,0x7f,0x7d):
  1622. case MKTAG('s','k','i','p'):
  1623. case MKTAG('u','u','i','d'):
  1624. case MKTAG('p','r','f','l'):
  1625. offset = AV_RB32(p->buf+offset) + offset;
  1626. /* if we only find those cause probedata is too small at least rate them */
  1627. score = AVPROBE_SCORE_MAX - 50;
  1628. break;
  1629. default:
  1630. /* unrecognized tag */
  1631. return score;
  1632. }
  1633. }
  1634. return score;
  1635. }
  1636. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1637. {
  1638. MOVContext *mov = s->priv_data;
  1639. ByteIOContext *pb = s->pb;
  1640. int err;
  1641. MOVAtom atom = { 0, 0, 0 };
  1642. mov->fc = s;
  1643. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  1644. if(!url_is_streamed(pb))
  1645. atom.size = url_fsize(pb);
  1646. else
  1647. atom.size = INT64_MAX;
  1648. /* check MOV header */
  1649. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  1650. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  1651. return err;
  1652. }
  1653. if (!mov->found_moov) {
  1654. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  1655. return -1;
  1656. }
  1657. dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
  1658. return 0;
  1659. }
  1660. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  1661. {
  1662. MOVContext *mov = s->priv_data;
  1663. MOVStreamContext *sc = 0;
  1664. AVIndexEntry *sample = 0;
  1665. int64_t best_dts = INT64_MAX;
  1666. int i, ret;
  1667. retry:
  1668. for (i = 0; i < s->nb_streams; i++) {
  1669. AVStream *st = s->streams[i];
  1670. MOVStreamContext *msc = st->priv_data;
  1671. if (st->discard != AVDISCARD_ALL && msc->pb && msc->current_sample < st->nb_index_entries) {
  1672. AVIndexEntry *current_sample = &st->index_entries[msc->current_sample];
  1673. int64_t dts = av_rescale(current_sample->timestamp * (int64_t)msc->time_rate,
  1674. AV_TIME_BASE, msc->time_scale);
  1675. dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  1676. if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
  1677. (!url_is_streamed(s->pb) &&
  1678. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  1679. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  1680. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  1681. sample = current_sample;
  1682. best_dts = dts;
  1683. sc = msc;
  1684. }
  1685. }
  1686. }
  1687. if (!sample) {
  1688. mov->found_mdat = 0;
  1689. if (!url_is_streamed(s->pb) ||
  1690. mov_read_default(mov, s->pb, (MOVAtom){ 0, 0, INT64_MAX }) < 0 ||
  1691. url_feof(s->pb))
  1692. return -1;
  1693. dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
  1694. goto retry;
  1695. }
  1696. /* must be done just before reading, to avoid infinite loop on sample */
  1697. sc->current_sample++;
  1698. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  1699. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  1700. sc->ffindex, sample->pos);
  1701. return -1;
  1702. }
  1703. ret = av_get_packet(sc->pb, pkt, sample->size);
  1704. if (ret < 0)
  1705. return ret;
  1706. #if CONFIG_DV_DEMUXER
  1707. if (mov->dv_demux && sc->dv_audio_container) {
  1708. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  1709. av_free(pkt->data);
  1710. pkt->size = 0;
  1711. if (dv_get_packet(mov->dv_demux, pkt) < 0)
  1712. return -1;
  1713. }
  1714. #endif
  1715. pkt->stream_index = sc->ffindex;
  1716. pkt->dts = sample->timestamp;
  1717. if (sc->ctts_data) {
  1718. assert(sc->ctts_data[sc->ctts_index].duration % sc->time_rate == 0);
  1719. pkt->pts = pkt->dts + sc->ctts_data[sc->ctts_index].duration / sc->time_rate;
  1720. /* update ctts context */
  1721. sc->ctts_sample++;
  1722. if (sc->ctts_index < sc->ctts_count &&
  1723. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  1724. sc->ctts_index++;
  1725. sc->ctts_sample = 0;
  1726. }
  1727. if (sc->wrong_dts)
  1728. pkt->dts = AV_NOPTS_VALUE;
  1729. } else {
  1730. AVStream *st = s->streams[sc->ffindex];
  1731. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  1732. st->index_entries[sc->current_sample].timestamp : st->duration;
  1733. pkt->duration = next_dts - pkt->dts;
  1734. pkt->pts = pkt->dts;
  1735. }
  1736. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? PKT_FLAG_KEY : 0;
  1737. pkt->pos = sample->pos;
  1738. dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  1739. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  1740. return 0;
  1741. }
  1742. static int mov_seek_stream(AVStream *st, int64_t timestamp, int flags)
  1743. {
  1744. MOVStreamContext *sc = st->priv_data;
  1745. int sample, time_sample;
  1746. int i;
  1747. sample = av_index_search_timestamp(st, timestamp, flags);
  1748. dprintf(st->codec, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  1749. if (sample < 0) /* not sure what to do */
  1750. return -1;
  1751. sc->current_sample = sample;
  1752. dprintf(st->codec, "stream %d, found sample %d\n", st->index, sc->current_sample);
  1753. /* adjust ctts index */
  1754. if (sc->ctts_data) {
  1755. time_sample = 0;
  1756. for (i = 0; i < sc->ctts_count; i++) {
  1757. int next = time_sample + sc->ctts_data[i].count;
  1758. if (next > sc->current_sample) {
  1759. sc->ctts_index = i;
  1760. sc->ctts_sample = sc->current_sample - time_sample;
  1761. break;
  1762. }
  1763. time_sample = next;
  1764. }
  1765. }
  1766. return sample;
  1767. }
  1768. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  1769. {
  1770. AVStream *st;
  1771. int64_t seek_timestamp, timestamp;
  1772. int sample;
  1773. int i;
  1774. if (stream_index >= s->nb_streams)
  1775. return -1;
  1776. if (sample_time < 0)
  1777. sample_time = 0;
  1778. st = s->streams[stream_index];
  1779. sample = mov_seek_stream(st, sample_time, flags);
  1780. if (sample < 0)
  1781. return -1;
  1782. /* adjust seek timestamp to found sample timestamp */
  1783. seek_timestamp = st->index_entries[sample].timestamp;
  1784. for (i = 0; i < s->nb_streams; i++) {
  1785. st = s->streams[i];
  1786. if (stream_index == i || st->discard == AVDISCARD_ALL)
  1787. continue;
  1788. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  1789. mov_seek_stream(st, timestamp, flags);
  1790. }
  1791. return 0;
  1792. }
  1793. static int mov_read_close(AVFormatContext *s)
  1794. {
  1795. MOVContext *mov = s->priv_data;
  1796. int i, j;
  1797. for (i = 0; i < s->nb_streams; i++) {
  1798. AVStream *st = s->streams[i];
  1799. MOVStreamContext *sc = st->priv_data;
  1800. av_freep(&sc->ctts_data);
  1801. for (j = 0; j < sc->drefs_count; j++)
  1802. av_freep(&sc->drefs[j].path);
  1803. av_freep(&sc->drefs);
  1804. if (sc->pb && sc->pb != s->pb)
  1805. url_fclose(sc->pb);
  1806. av_freep(&st->codec->palctrl);
  1807. }
  1808. if (mov->dv_demux) {
  1809. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  1810. av_freep(&mov->dv_fctx->streams[i]->codec);
  1811. av_freep(&mov->dv_fctx->streams[i]);
  1812. }
  1813. av_freep(&mov->dv_fctx);
  1814. av_freep(&mov->dv_demux);
  1815. }
  1816. av_freep(&mov->trex_data);
  1817. return 0;
  1818. }
  1819. AVInputFormat mov_demuxer = {
  1820. "mov,mp4,m4a,3gp,3g2,mj2",
  1821. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  1822. sizeof(MOVContext),
  1823. mov_probe,
  1824. mov_read_header,
  1825. mov_read_packet,
  1826. mov_read_close,
  1827. mov_read_seek,
  1828. };