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.

2090 lines
72KB

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