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.

2280 lines
76KB

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