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.

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