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.

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