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.

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