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.

2130 lines
73KB

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