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.

2181 lines
75KB

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