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.

2631 lines
88KB

  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 MOV_EXPORT_ALL_METADATA
  25. #include "libavutil/intreadwrite.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/dict.h"
  28. #include "avformat.h"
  29. #include "avio_internal.h"
  30. #include "riff.h"
  31. #include "isom.h"
  32. #include "libavcodec/get_bits.h"
  33. #if CONFIG_ZLIB
  34. #include <zlib.h>
  35. #endif
  36. /*
  37. * First version by Francois Revol revol@free.fr
  38. * Seek function by Gael Chardon gael.dev@4now.net
  39. *
  40. * Features and limitations:
  41. * - reads most of the QT files I have (at least the structure),
  42. * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
  43. * - the code is quite ugly... maybe I won't do it recursive next time :-)
  44. *
  45. * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
  46. * when coding this :) (it's a writer anyway)
  47. *
  48. * Reference documents:
  49. * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
  50. * Apple:
  51. * http://developer.apple.com/documentation/QuickTime/QTFF/
  52. * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
  53. * QuickTime is a trademark of Apple (AFAIK :))
  54. */
  55. #include "qtpalette.h"
  56. #undef NDEBUG
  57. #include <assert.h>
  58. /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
  59. /* those functions parse an atom */
  60. /* return code:
  61. 0: continue to parse next atom
  62. <0: error occurred, exit
  63. */
  64. /* links atom IDs to parse functions */
  65. typedef struct MOVParseTableEntry {
  66. uint32_t type;
  67. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  68. } MOVParseTableEntry;
  69. static const MOVParseTableEntry mov_default_parse_table[];
  70. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *type)
  71. {
  72. char buf[16];
  73. avio_rb16(pb); // unknown
  74. snprintf(buf, sizeof(buf), "%d", avio_rb16(pb));
  75. av_dict_set(&c->fc->metadata, type, buf, 0);
  76. avio_rb16(pb); // total tracks/discs
  77. return 0;
  78. }
  79. static const uint32_t mac_to_unicode[128] = {
  80. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  81. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  82. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  83. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  84. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  85. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  86. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  87. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  88. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  89. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  90. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  91. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  92. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  93. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  94. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  95. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  96. };
  97. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  98. char *dst, int dstlen)
  99. {
  100. char *p = dst;
  101. char *end = dst+dstlen-1;
  102. int i;
  103. for (i = 0; i < len; i++) {
  104. uint8_t t, c = avio_r8(pb);
  105. if (c < 0x80 && p < end)
  106. *p++ = c;
  107. else
  108. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  109. }
  110. *p = 0;
  111. return p - dst;
  112. }
  113. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  114. {
  115. #ifdef MOV_EXPORT_ALL_METADATA
  116. char tmp_key[5];
  117. #endif
  118. char str[1024], key2[16], language[4] = {0};
  119. const char *key = NULL;
  120. uint16_t str_size, langcode = 0;
  121. uint32_t data_type = 0;
  122. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char *) = NULL;
  123. switch (atom.type) {
  124. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  125. case MKTAG(0xa9,'a','u','t'):
  126. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  127. case MKTAG( 'a','A','R','T'): key = "album_artist";break;
  128. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  129. case MKTAG( 'c','p','r','t'):
  130. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  131. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  132. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  133. case MKTAG(0xa9,'c','m','t'):
  134. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  135. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  136. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  137. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  138. case MKTAG(0xa9,'t','o','o'):
  139. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  140. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  141. case MKTAG( 'd','e','s','c'): key = "description";break;
  142. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  143. case MKTAG( 't','v','s','h'): key = "show"; break;
  144. case MKTAG( 't','v','e','n'): key = "episode_id";break;
  145. case MKTAG( 't','v','n','n'): key = "network"; break;
  146. case MKTAG( 't','r','k','n'): key = "track";
  147. parse = mov_metadata_track_or_disc_number; break;
  148. case MKTAG( 'd','i','s','k'): key = "disc";
  149. parse = mov_metadata_track_or_disc_number; break;
  150. }
  151. if (c->itunes_metadata && atom.size > 8) {
  152. int data_size = avio_rb32(pb);
  153. int tag = avio_rl32(pb);
  154. if (tag == MKTAG('d','a','t','a')) {
  155. data_type = avio_rb32(pb); // type
  156. avio_rb32(pb); // unknown
  157. str_size = data_size - 16;
  158. atom.size -= 16;
  159. } else return 0;
  160. } else if (atom.size > 4 && key && !c->itunes_metadata) {
  161. str_size = avio_rb16(pb); // string length
  162. langcode = avio_rb16(pb);
  163. ff_mov_lang_to_iso639(langcode, language);
  164. atom.size -= 4;
  165. } else
  166. str_size = atom.size;
  167. #ifdef MOV_EXPORT_ALL_METADATA
  168. if (!key) {
  169. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  170. key = tmp_key;
  171. }
  172. #endif
  173. if (!key)
  174. return 0;
  175. if (atom.size < 0)
  176. return -1;
  177. str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);
  178. if (parse)
  179. parse(c, pb, str_size, key);
  180. else {
  181. if (data_type == 3 || (data_type == 0 && langcode < 0x800)) { // MAC Encoded
  182. mov_read_mac_string(c, pb, str_size, str, sizeof(str));
  183. } else {
  184. avio_read(pb, str, str_size);
  185. str[str_size] = 0;
  186. }
  187. av_dict_set(&c->fc->metadata, key, str, 0);
  188. if (*language && strcmp(language, "und")) {
  189. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  190. av_dict_set(&c->fc->metadata, key2, str, 0);
  191. }
  192. }
  193. av_dlog(c->fc, "lang \"%3s\" ", language);
  194. av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  195. key, str, (char*)&atom.type, str_size, atom.size);
  196. return 0;
  197. }
  198. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  199. {
  200. int64_t start;
  201. int i, nb_chapters, str_len, version;
  202. char str[256+1];
  203. if ((atom.size -= 5) < 0)
  204. return 0;
  205. version = avio_r8(pb);
  206. avio_rb24(pb);
  207. if (version)
  208. avio_rb32(pb); // ???
  209. nb_chapters = avio_r8(pb);
  210. for (i = 0; i < nb_chapters; i++) {
  211. if (atom.size < 9)
  212. return 0;
  213. start = avio_rb64(pb);
  214. str_len = avio_r8(pb);
  215. if ((atom.size -= 9+str_len) < 0)
  216. return 0;
  217. avio_read(pb, str, str_len);
  218. str[str_len] = 0;
  219. ff_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  220. }
  221. return 0;
  222. }
  223. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  224. {
  225. int64_t total_size = 0;
  226. MOVAtom a;
  227. int i;
  228. if (atom.size < 0)
  229. atom.size = INT64_MAX;
  230. while (total_size + 8 < atom.size && !url_feof(pb)) {
  231. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  232. a.size = atom.size;
  233. a.type=0;
  234. if(atom.size >= 8) {
  235. a.size = avio_rb32(pb);
  236. a.type = avio_rl32(pb);
  237. }
  238. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  239. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  240. total_size += 8;
  241. if (a.size == 1) { /* 64 bit extended size */
  242. a.size = avio_rb64(pb) - 8;
  243. total_size += 8;
  244. }
  245. if (a.size == 0) {
  246. a.size = atom.size - total_size;
  247. if (a.size <= 8)
  248. break;
  249. }
  250. a.size -= 8;
  251. if(a.size < 0)
  252. break;
  253. a.size = FFMIN(a.size, atom.size - total_size);
  254. for (i = 0; mov_default_parse_table[i].type; i++)
  255. if (mov_default_parse_table[i].type == a.type) {
  256. parse = mov_default_parse_table[i].parse;
  257. break;
  258. }
  259. // container is user data
  260. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  261. atom.type == MKTAG('i','l','s','t')))
  262. parse = mov_read_udta_string;
  263. if (!parse) { /* skip leaf atoms data */
  264. avio_skip(pb, a.size);
  265. } else {
  266. int64_t start_pos = avio_tell(pb);
  267. int64_t left;
  268. int err = parse(c, pb, a);
  269. if (err < 0)
  270. return err;
  271. if (c->found_moov && c->found_mdat &&
  272. (!pb->seekable || start_pos + a.size == avio_size(pb)))
  273. return 0;
  274. left = a.size - avio_tell(pb) + start_pos;
  275. if (left > 0) /* skip garbage at atom end */
  276. avio_skip(pb, left);
  277. }
  278. total_size += a.size;
  279. }
  280. if (total_size < atom.size && atom.size < 0x7ffff)
  281. avio_skip(pb, atom.size - total_size);
  282. return 0;
  283. }
  284. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  285. {
  286. AVStream *st;
  287. MOVStreamContext *sc;
  288. int entries, i, j;
  289. if (c->fc->nb_streams < 1)
  290. return 0;
  291. st = c->fc->streams[c->fc->nb_streams-1];
  292. sc = st->priv_data;
  293. avio_rb32(pb); // version + flags
  294. entries = avio_rb32(pb);
  295. if (entries >= UINT_MAX / sizeof(*sc->drefs))
  296. return -1;
  297. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  298. if (!sc->drefs)
  299. return AVERROR(ENOMEM);
  300. sc->drefs_count = entries;
  301. for (i = 0; i < sc->drefs_count; i++) {
  302. MOVDref *dref = &sc->drefs[i];
  303. uint32_t size = avio_rb32(pb);
  304. int64_t next = avio_tell(pb) + size - 4;
  305. if (size < 12)
  306. return -1;
  307. dref->type = avio_rl32(pb);
  308. avio_rb32(pb); // version + flags
  309. av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
  310. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  311. /* macintosh alias record */
  312. uint16_t volume_len, len;
  313. int16_t type;
  314. avio_skip(pb, 10);
  315. volume_len = avio_r8(pb);
  316. volume_len = FFMIN(volume_len, 27);
  317. avio_read(pb, dref->volume, 27);
  318. dref->volume[volume_len] = 0;
  319. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  320. avio_skip(pb, 12);
  321. len = avio_r8(pb);
  322. len = FFMIN(len, 63);
  323. avio_read(pb, dref->filename, 63);
  324. dref->filename[len] = 0;
  325. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  326. avio_skip(pb, 16);
  327. /* read next level up_from_alias/down_to_target */
  328. dref->nlvl_from = avio_rb16(pb);
  329. dref->nlvl_to = avio_rb16(pb);
  330. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  331. dref->nlvl_from, dref->nlvl_to);
  332. avio_skip(pb, 16);
  333. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  334. type = avio_rb16(pb);
  335. len = avio_rb16(pb);
  336. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  337. if (len&1)
  338. len += 1;
  339. if (type == 2) { // absolute path
  340. av_free(dref->path);
  341. dref->path = av_mallocz(len+1);
  342. if (!dref->path)
  343. return AVERROR(ENOMEM);
  344. avio_read(pb, dref->path, len);
  345. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  346. len -= volume_len;
  347. memmove(dref->path, dref->path+volume_len, len);
  348. dref->path[len] = 0;
  349. }
  350. for (j = 0; j < len; j++)
  351. if (dref->path[j] == ':')
  352. dref->path[j] = '/';
  353. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  354. } else if (type == 0) { // directory name
  355. av_free(dref->dir);
  356. dref->dir = av_malloc(len+1);
  357. if (!dref->dir)
  358. return AVERROR(ENOMEM);
  359. avio_read(pb, dref->dir, len);
  360. dref->dir[len] = 0;
  361. for (j = 0; j < len; j++)
  362. if (dref->dir[j] == ':')
  363. dref->dir[j] = '/';
  364. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  365. } else
  366. avio_skip(pb, len);
  367. }
  368. }
  369. avio_seek(pb, next, SEEK_SET);
  370. }
  371. return 0;
  372. }
  373. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  374. {
  375. AVStream *st;
  376. uint32_t type;
  377. uint32_t av_unused ctype;
  378. if (c->fc->nb_streams < 1) // meta before first trak
  379. return 0;
  380. st = c->fc->streams[c->fc->nb_streams-1];
  381. avio_r8(pb); /* version */
  382. avio_rb24(pb); /* flags */
  383. /* component type */
  384. ctype = avio_rl32(pb);
  385. type = avio_rl32(pb); /* component subtype */
  386. av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  387. av_dlog(c->fc, "stype= %.4s\n", (char*)&type);
  388. if (type == MKTAG('v','i','d','e'))
  389. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  390. else if(type == MKTAG('s','o','u','n'))
  391. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  392. else if(type == MKTAG('m','1','a',' '))
  393. st->codec->codec_id = CODEC_ID_MP2;
  394. else if(type == MKTAG('s','u','b','p'))
  395. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  396. avio_rb32(pb); /* component manufacture */
  397. avio_rb32(pb); /* component flags */
  398. avio_rb32(pb); /* component flags mask */
  399. return 0;
  400. }
  401. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
  402. {
  403. AVStream *st;
  404. int tag;
  405. if (fc->nb_streams < 1)
  406. return 0;
  407. st = fc->streams[fc->nb_streams-1];
  408. avio_rb32(pb); /* version + flags */
  409. ff_mp4_read_descr(fc, pb, &tag);
  410. if (tag == MP4ESDescrTag) {
  411. avio_rb16(pb); /* ID */
  412. avio_r8(pb); /* priority */
  413. } else
  414. avio_rb16(pb); /* ID */
  415. ff_mp4_read_descr(fc, pb, &tag);
  416. if (tag == MP4DecConfigDescrTag)
  417. ff_mp4_read_dec_config_descr(fc, st, pb);
  418. return 0;
  419. }
  420. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  421. {
  422. return ff_mov_read_esds(c->fc, pb, atom);
  423. }
  424. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  425. {
  426. AVStream *st;
  427. int ac3info, acmod, lfeon, bsmod;
  428. if (c->fc->nb_streams < 1)
  429. return 0;
  430. st = c->fc->streams[c->fc->nb_streams-1];
  431. ac3info = avio_rb24(pb);
  432. bsmod = (ac3info >> 14) & 0x7;
  433. acmod = (ac3info >> 11) & 0x7;
  434. lfeon = (ac3info >> 10) & 0x1;
  435. st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  436. st->codec->audio_service_type = bsmod;
  437. if (st->codec->channels > 1 && bsmod == 0x7)
  438. st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  439. return 0;
  440. }
  441. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  442. {
  443. AVStream *st;
  444. if (c->fc->nb_streams < 1)
  445. return 0;
  446. st = c->fc->streams[c->fc->nb_streams-1];
  447. ff_get_wav_header(pb, st->codec, atom.size);
  448. return 0;
  449. }
  450. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  451. {
  452. const int num = avio_rb32(pb);
  453. const int den = avio_rb32(pb);
  454. AVStream *st;
  455. if (c->fc->nb_streams < 1)
  456. return 0;
  457. st = c->fc->streams[c->fc->nb_streams-1];
  458. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  459. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  460. av_log(c->fc, AV_LOG_WARNING,
  461. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  462. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  463. num, den);
  464. } else if (den != 0) {
  465. st->sample_aspect_ratio.num = num;
  466. st->sample_aspect_ratio.den = den;
  467. }
  468. return 0;
  469. }
  470. /* this atom contains actual media data */
  471. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  472. {
  473. if(atom.size == 0) /* wrong one (MP4) */
  474. return 0;
  475. c->found_mdat=1;
  476. return 0; /* now go for moov */
  477. }
  478. /* read major brand, minor version and compatible brands and store them as metadata */
  479. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  480. {
  481. uint32_t minor_ver;
  482. int comp_brand_size;
  483. char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */
  484. char* comp_brands_str;
  485. uint8_t type[5] = {0};
  486. avio_read(pb, type, 4);
  487. if (strcmp(type, "qt "))
  488. c->isom = 1;
  489. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  490. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  491. minor_ver = avio_rb32(pb); /* minor version */
  492. snprintf(minor_ver_str, sizeof(minor_ver_str), "%d", minor_ver);
  493. av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);
  494. comp_brand_size = atom.size - 8;
  495. if (comp_brand_size < 0)
  496. return -1;
  497. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  498. if (!comp_brands_str)
  499. return AVERROR(ENOMEM);
  500. avio_read(pb, comp_brands_str, comp_brand_size);
  501. comp_brands_str[comp_brand_size] = 0;
  502. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  503. av_freep(&comp_brands_str);
  504. return 0;
  505. }
  506. /* this atom should contain all header atoms */
  507. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  508. {
  509. if (mov_read_default(c, pb, atom) < 0)
  510. return -1;
  511. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  512. /* so we don't parse the whole file if over a network */
  513. c->found_moov=1;
  514. return 0; /* now go for mdat */
  515. }
  516. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  517. {
  518. c->fragment.moof_offset = avio_tell(pb) - 8;
  519. av_dlog(c->fc, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  520. return mov_read_default(c, pb, atom);
  521. }
  522. static void mov_metadata_creation_time(AVDictionary **metadata, time_t time)
  523. {
  524. char buffer[32];
  525. if (time) {
  526. struct tm *ptm;
  527. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  528. ptm = gmtime(&time);
  529. if (!ptm) return;
  530. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm);
  531. av_dict_set(metadata, "creation_time", buffer, 0);
  532. }
  533. }
  534. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  535. {
  536. AVStream *st;
  537. MOVStreamContext *sc;
  538. int version;
  539. char language[4] = {0};
  540. unsigned lang;
  541. time_t creation_time;
  542. if (c->fc->nb_streams < 1)
  543. return 0;
  544. st = c->fc->streams[c->fc->nb_streams-1];
  545. sc = st->priv_data;
  546. version = avio_r8(pb);
  547. if (version > 1)
  548. return -1; /* unsupported */
  549. avio_rb24(pb); /* flags */
  550. if (version == 1) {
  551. creation_time = avio_rb64(pb);
  552. avio_rb64(pb);
  553. } else {
  554. creation_time = avio_rb32(pb);
  555. avio_rb32(pb); /* modification time */
  556. }
  557. mov_metadata_creation_time(&st->metadata, creation_time);
  558. sc->time_scale = avio_rb32(pb);
  559. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  560. lang = avio_rb16(pb); /* language */
  561. if (ff_mov_lang_to_iso639(lang, language))
  562. av_dict_set(&st->metadata, "language", language, 0);
  563. avio_rb16(pb); /* quality */
  564. return 0;
  565. }
  566. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  567. {
  568. time_t creation_time;
  569. int version = avio_r8(pb); /* version */
  570. avio_rb24(pb); /* flags */
  571. if (version == 1) {
  572. creation_time = avio_rb64(pb);
  573. avio_rb64(pb);
  574. } else {
  575. creation_time = avio_rb32(pb);
  576. avio_rb32(pb); /* modification time */
  577. }
  578. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  579. c->time_scale = avio_rb32(pb); /* time scale */
  580. av_dlog(c->fc, "time scale = %i\n", c->time_scale);
  581. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  582. avio_rb32(pb); /* preferred scale */
  583. avio_rb16(pb); /* preferred volume */
  584. avio_skip(pb, 10); /* reserved */
  585. avio_skip(pb, 36); /* display matrix */
  586. avio_rb32(pb); /* preview time */
  587. avio_rb32(pb); /* preview duration */
  588. avio_rb32(pb); /* poster time */
  589. avio_rb32(pb); /* selection time */
  590. avio_rb32(pb); /* selection duration */
  591. avio_rb32(pb); /* current time */
  592. avio_rb32(pb); /* next track ID */
  593. return 0;
  594. }
  595. static int mov_read_smi(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  596. {
  597. AVStream *st;
  598. if (c->fc->nb_streams < 1)
  599. return 0;
  600. st = c->fc->streams[c->fc->nb_streams-1];
  601. if((uint64_t)atom.size > (1<<30))
  602. return -1;
  603. // currently SVQ3 decoder expect full STSD header - so let's fake it
  604. // this should be fixed and just SMI header should be passed
  605. av_free(st->codec->extradata);
  606. st->codec->extradata = av_mallocz(atom.size + 0x5a + FF_INPUT_BUFFER_PADDING_SIZE);
  607. if (!st->codec->extradata)
  608. return AVERROR(ENOMEM);
  609. st->codec->extradata_size = 0x5a + atom.size;
  610. memcpy(st->codec->extradata, "SVQ3", 4); // fake
  611. avio_read(pb, st->codec->extradata + 0x5a, atom.size);
  612. av_dlog(c->fc, "Reading SMI %"PRId64" %s\n", atom.size, st->codec->extradata + 0x5a);
  613. return 0;
  614. }
  615. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  616. {
  617. AVStream *st;
  618. int little_endian;
  619. if (c->fc->nb_streams < 1)
  620. return 0;
  621. st = c->fc->streams[c->fc->nb_streams-1];
  622. little_endian = avio_rb16(pb) & 0xFF;
  623. av_dlog(c->fc, "enda %d\n", little_endian);
  624. if (little_endian == 1) {
  625. switch (st->codec->codec_id) {
  626. case CODEC_ID_PCM_S24BE:
  627. st->codec->codec_id = CODEC_ID_PCM_S24LE;
  628. break;
  629. case CODEC_ID_PCM_S32BE:
  630. st->codec->codec_id = CODEC_ID_PCM_S32LE;
  631. break;
  632. case CODEC_ID_PCM_F32BE:
  633. st->codec->codec_id = CODEC_ID_PCM_F32LE;
  634. break;
  635. case CODEC_ID_PCM_F64BE:
  636. st->codec->codec_id = CODEC_ID_PCM_F64LE;
  637. break;
  638. default:
  639. break;
  640. }
  641. }
  642. return 0;
  643. }
  644. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  645. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  646. {
  647. AVStream *st;
  648. uint64_t size;
  649. uint8_t *buf;
  650. if (c->fc->nb_streams < 1) // will happen with jp2 files
  651. return 0;
  652. st= c->fc->streams[c->fc->nb_streams-1];
  653. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  654. if(size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  655. return -1;
  656. buf= av_realloc(st->codec->extradata, size);
  657. if(!buf)
  658. return -1;
  659. st->codec->extradata= buf;
  660. buf+= st->codec->extradata_size;
  661. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  662. AV_WB32( buf , atom.size + 8);
  663. AV_WL32( buf + 4, atom.type);
  664. avio_read(pb, buf + 8, atom.size);
  665. return 0;
  666. }
  667. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  668. {
  669. AVStream *st;
  670. if (c->fc->nb_streams < 1)
  671. return 0;
  672. st = c->fc->streams[c->fc->nb_streams-1];
  673. if((uint64_t)atom.size > (1<<30))
  674. return -1;
  675. if (st->codec->codec_id == CODEC_ID_QDM2 || st->codec->codec_id == CODEC_ID_QDMC) {
  676. // pass all frma atom to codec, needed at least for QDMC and QDM2
  677. av_free(st->codec->extradata);
  678. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  679. if (!st->codec->extradata)
  680. return AVERROR(ENOMEM);
  681. st->codec->extradata_size = atom.size;
  682. avio_read(pb, st->codec->extradata, atom.size);
  683. } else if (atom.size > 8) { /* to read frma, esds atoms */
  684. if (mov_read_default(c, pb, atom) < 0)
  685. return -1;
  686. } else
  687. avio_skip(pb, atom.size);
  688. return 0;
  689. }
  690. /**
  691. * This function reads atom content and puts data in extradata without tag
  692. * nor size unlike mov_read_extradata.
  693. */
  694. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  695. {
  696. AVStream *st;
  697. if (c->fc->nb_streams < 1)
  698. return 0;
  699. st = c->fc->streams[c->fc->nb_streams-1];
  700. if((uint64_t)atom.size > (1<<30))
  701. return -1;
  702. av_free(st->codec->extradata);
  703. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  704. if (!st->codec->extradata)
  705. return AVERROR(ENOMEM);
  706. st->codec->extradata_size = atom.size;
  707. avio_read(pb, st->codec->extradata, atom.size);
  708. return 0;
  709. }
  710. /**
  711. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  712. * but can have extradata appended at the end after the 40 bytes belonging
  713. * to the struct.
  714. */
  715. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  716. {
  717. AVStream *st;
  718. if (c->fc->nb_streams < 1)
  719. return 0;
  720. if (atom.size <= 40)
  721. return 0;
  722. st = c->fc->streams[c->fc->nb_streams-1];
  723. if((uint64_t)atom.size > (1<<30))
  724. return -1;
  725. av_free(st->codec->extradata);
  726. st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
  727. if (!st->codec->extradata)
  728. return AVERROR(ENOMEM);
  729. st->codec->extradata_size = atom.size - 40;
  730. avio_skip(pb, 40);
  731. avio_read(pb, st->codec->extradata, atom.size - 40);
  732. return 0;
  733. }
  734. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  735. {
  736. AVStream *st;
  737. MOVStreamContext *sc;
  738. unsigned int i, entries;
  739. if (c->fc->nb_streams < 1)
  740. return 0;
  741. st = c->fc->streams[c->fc->nb_streams-1];
  742. sc = st->priv_data;
  743. avio_r8(pb); /* version */
  744. avio_rb24(pb); /* flags */
  745. entries = avio_rb32(pb);
  746. if(entries >= UINT_MAX/sizeof(int64_t))
  747. return -1;
  748. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  749. if (!sc->chunk_offsets)
  750. return AVERROR(ENOMEM);
  751. sc->chunk_count = entries;
  752. if (atom.type == MKTAG('s','t','c','o'))
  753. for(i=0; i<entries; i++)
  754. sc->chunk_offsets[i] = avio_rb32(pb);
  755. else if (atom.type == MKTAG('c','o','6','4'))
  756. for(i=0; i<entries; i++)
  757. sc->chunk_offsets[i] = avio_rb64(pb);
  758. else
  759. return -1;
  760. return 0;
  761. }
  762. /**
  763. * Compute codec id for 'lpcm' tag.
  764. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  765. */
  766. enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  767. {
  768. if (flags & 1) { // floating point
  769. if (flags & 2) { // big endian
  770. if (bps == 32) return CODEC_ID_PCM_F32BE;
  771. else if (bps == 64) return CODEC_ID_PCM_F64BE;
  772. } else {
  773. if (bps == 32) return CODEC_ID_PCM_F32LE;
  774. else if (bps == 64) return CODEC_ID_PCM_F64LE;
  775. }
  776. } else {
  777. if (flags & 2) {
  778. if (bps == 8)
  779. // signed integer
  780. if (flags & 4) return CODEC_ID_PCM_S8;
  781. else return CODEC_ID_PCM_U8;
  782. else if (bps == 16) return CODEC_ID_PCM_S16BE;
  783. else if (bps == 24) return CODEC_ID_PCM_S24BE;
  784. else if (bps == 32) return CODEC_ID_PCM_S32BE;
  785. } else {
  786. if (bps == 8)
  787. if (flags & 4) return CODEC_ID_PCM_S8;
  788. else return CODEC_ID_PCM_U8;
  789. else if (bps == 16) return CODEC_ID_PCM_S16LE;
  790. else if (bps == 24) return CODEC_ID_PCM_S24LE;
  791. else if (bps == 32) return CODEC_ID_PCM_S32LE;
  792. }
  793. }
  794. return CODEC_ID_NONE;
  795. }
  796. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  797. {
  798. AVStream *st;
  799. MOVStreamContext *sc;
  800. int j, pseudo_stream_id;
  801. if (c->fc->nb_streams < 1)
  802. return 0;
  803. st = c->fc->streams[c->fc->nb_streams-1];
  804. sc = st->priv_data;
  805. for(pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {
  806. //Parsing Sample description table
  807. enum CodecID id;
  808. int dref_id = 1;
  809. MOVAtom a = { AV_RL32("stsd") };
  810. int64_t start_pos = avio_tell(pb);
  811. int size = avio_rb32(pb); /* size */
  812. uint32_t format = avio_rl32(pb); /* data format */
  813. if (size >= 16) {
  814. avio_rb32(pb); /* reserved */
  815. avio_rb16(pb); /* reserved */
  816. dref_id = avio_rb16(pb);
  817. }
  818. if (st->codec->codec_tag &&
  819. st->codec->codec_tag != format &&
  820. (c->fc->video_codec_id ? ff_codec_get_id(codec_movvideo_tags, format) != c->fc->video_codec_id
  821. : st->codec->codec_tag != MKTAG('j','p','e','g'))
  822. ){
  823. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  824. * export it as a separate AVStream but this needs a few changes
  825. * in the MOV demuxer, patch welcome. */
  826. multiple_stsd:
  827. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  828. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  829. continue;
  830. }
  831. /* we cannot demux concatenated h264 streams because of different extradata */
  832. if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
  833. goto multiple_stsd;
  834. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  835. sc->dref_id= dref_id;
  836. st->codec->codec_tag = format;
  837. id = ff_codec_get_id(codec_movaudio_tags, format);
  838. if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
  839. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
  840. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  841. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  842. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
  843. format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
  844. id = ff_codec_get_id(codec_movvideo_tags, format);
  845. if (id <= 0)
  846. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  847. if (id > 0)
  848. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  849. else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
  850. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  851. if(id > 0)
  852. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  853. }
  854. }
  855. av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
  856. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  857. (format >> 24) & 0xff, st->codec->codec_type);
  858. if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  859. unsigned int color_depth, len;
  860. int color_greyscale;
  861. st->codec->codec_id = id;
  862. avio_rb16(pb); /* version */
  863. avio_rb16(pb); /* revision level */
  864. avio_rb32(pb); /* vendor */
  865. avio_rb32(pb); /* temporal quality */
  866. avio_rb32(pb); /* spatial quality */
  867. st->codec->width = avio_rb16(pb); /* width */
  868. st->codec->height = avio_rb16(pb); /* height */
  869. avio_rb32(pb); /* horiz resolution */
  870. avio_rb32(pb); /* vert resolution */
  871. avio_rb32(pb); /* data size, always 0 */
  872. avio_rb16(pb); /* frames per samples */
  873. len = avio_r8(pb); /* codec name, pascal string */
  874. if (len > 31)
  875. len = 31;
  876. mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
  877. if (len < 31)
  878. avio_skip(pb, 31 - len);
  879. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  880. if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
  881. st->codec->codec_tag=MKTAG('I', '4', '2', '0');
  882. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  883. st->codec->color_table_id = avio_rb16(pb); /* colortable id */
  884. av_dlog(c->fc, "depth %d, ctab id %d\n",
  885. st->codec->bits_per_coded_sample, st->codec->color_table_id);
  886. /* figure out the palette situation */
  887. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  888. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  889. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  890. if ((color_depth == 2) || (color_depth == 4) ||
  891. (color_depth == 8)) {
  892. /* for palette traversal */
  893. unsigned int color_start, color_count, color_end;
  894. unsigned char r, g, b;
  895. st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
  896. if (color_greyscale) {
  897. int color_index, color_dec;
  898. /* compute the greyscale palette */
  899. st->codec->bits_per_coded_sample = color_depth;
  900. color_count = 1 << color_depth;
  901. color_index = 255;
  902. color_dec = 256 / (color_count - 1);
  903. for (j = 0; j < color_count; j++) {
  904. r = g = b = color_index;
  905. st->codec->palctrl->palette[j] =
  906. (r << 16) | (g << 8) | (b);
  907. color_index -= color_dec;
  908. if (color_index < 0)
  909. color_index = 0;
  910. }
  911. } else if (st->codec->color_table_id) {
  912. const uint8_t *color_table;
  913. /* if flag bit 3 is set, use the default palette */
  914. color_count = 1 << color_depth;
  915. if (color_depth == 2)
  916. color_table = ff_qt_default_palette_4;
  917. else if (color_depth == 4)
  918. color_table = ff_qt_default_palette_16;
  919. else
  920. color_table = ff_qt_default_palette_256;
  921. for (j = 0; j < color_count; j++) {
  922. r = color_table[j * 3 + 0];
  923. g = color_table[j * 3 + 1];
  924. b = color_table[j * 3 + 2];
  925. st->codec->palctrl->palette[j] =
  926. (r << 16) | (g << 8) | (b);
  927. }
  928. } else {
  929. /* load the palette from the file */
  930. color_start = avio_rb32(pb);
  931. color_count = avio_rb16(pb);
  932. color_end = avio_rb16(pb);
  933. if ((color_start <= 255) &&
  934. (color_end <= 255)) {
  935. for (j = color_start; j <= color_end; j++) {
  936. /* each R, G, or B component is 16 bits;
  937. * only use the top 8 bits; skip alpha bytes
  938. * up front */
  939. avio_r8(pb);
  940. avio_r8(pb);
  941. r = avio_r8(pb);
  942. avio_r8(pb);
  943. g = avio_r8(pb);
  944. avio_r8(pb);
  945. b = avio_r8(pb);
  946. avio_r8(pb);
  947. st->codec->palctrl->palette[j] =
  948. (r << 16) | (g << 8) | (b);
  949. }
  950. }
  951. }
  952. st->codec->palctrl->palette_changed = 1;
  953. }
  954. } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  955. int bits_per_sample, flags;
  956. uint16_t version = avio_rb16(pb);
  957. st->codec->codec_id = id;
  958. avio_rb16(pb); /* revision level */
  959. avio_rb32(pb); /* vendor */
  960. st->codec->channels = avio_rb16(pb); /* channel count */
  961. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  962. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  963. sc->audio_cid = avio_rb16(pb);
  964. avio_rb16(pb); /* packet size = 0 */
  965. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  966. //Read QT version 1 fields. In version 0 these do not exist.
  967. av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
  968. if(!c->isom) {
  969. if(version==1) {
  970. sc->samples_per_frame = avio_rb32(pb);
  971. avio_rb32(pb); /* bytes per packet */
  972. sc->bytes_per_frame = avio_rb32(pb);
  973. avio_rb32(pb); /* bytes per sample */
  974. } else if(version==2) {
  975. avio_rb32(pb); /* sizeof struct only */
  976. st->codec->sample_rate = av_int2dbl(avio_rb64(pb)); /* float 64 */
  977. st->codec->channels = avio_rb32(pb);
  978. avio_rb32(pb); /* always 0x7F000000 */
  979. st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
  980. flags = avio_rb32(pb); /* lpcm format specific flag */
  981. sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
  982. sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
  983. if (format == MKTAG('l','p','c','m'))
  984. st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  985. }
  986. }
  987. switch (st->codec->codec_id) {
  988. case CODEC_ID_PCM_S8:
  989. case CODEC_ID_PCM_U8:
  990. if (st->codec->bits_per_coded_sample == 16)
  991. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  992. break;
  993. case CODEC_ID_PCM_S16LE:
  994. case CODEC_ID_PCM_S16BE:
  995. if (st->codec->bits_per_coded_sample == 8)
  996. st->codec->codec_id = CODEC_ID_PCM_S8;
  997. else if (st->codec->bits_per_coded_sample == 24)
  998. st->codec->codec_id =
  999. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  1000. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  1001. break;
  1002. /* set values for old format before stsd version 1 appeared */
  1003. case CODEC_ID_MACE3:
  1004. sc->samples_per_frame = 6;
  1005. sc->bytes_per_frame = 2*st->codec->channels;
  1006. break;
  1007. case CODEC_ID_MACE6:
  1008. sc->samples_per_frame = 6;
  1009. sc->bytes_per_frame = 1*st->codec->channels;
  1010. break;
  1011. case CODEC_ID_ADPCM_IMA_QT:
  1012. sc->samples_per_frame = 64;
  1013. sc->bytes_per_frame = 34*st->codec->channels;
  1014. break;
  1015. case CODEC_ID_GSM:
  1016. sc->samples_per_frame = 160;
  1017. sc->bytes_per_frame = 33;
  1018. break;
  1019. default:
  1020. break;
  1021. }
  1022. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1023. if (bits_per_sample) {
  1024. st->codec->bits_per_coded_sample = bits_per_sample;
  1025. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1026. }
  1027. } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1028. // ttxt stsd contains display flags, justification, background
  1029. // color, fonts, and default styles, so fake an atom to read it
  1030. MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
  1031. if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
  1032. mov_read_glbl(c, pb, fake_atom);
  1033. st->codec->codec_id= id;
  1034. st->codec->width = sc->width;
  1035. st->codec->height = sc->height;
  1036. } else {
  1037. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  1038. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  1039. }
  1040. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  1041. a.size = size - (avio_tell(pb) - start_pos);
  1042. if (a.size > 8) {
  1043. if (mov_read_default(c, pb, a) < 0)
  1044. return -1;
  1045. } else if (a.size > 0)
  1046. avio_skip(pb, a.size);
  1047. }
  1048. if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  1049. st->codec->sample_rate= sc->time_scale;
  1050. /* special codec parameters handling */
  1051. switch (st->codec->codec_id) {
  1052. #if CONFIG_DV_DEMUXER
  1053. case CODEC_ID_DVAUDIO:
  1054. c->dv_fctx = avformat_alloc_context();
  1055. c->dv_demux = dv_init_demux(c->dv_fctx);
  1056. if (!c->dv_demux) {
  1057. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1058. return -1;
  1059. }
  1060. sc->dv_audio_container = 1;
  1061. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  1062. break;
  1063. #endif
  1064. /* no ifdef since parameters are always those */
  1065. case CODEC_ID_QCELP:
  1066. // force sample rate for qcelp when not stored in mov
  1067. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1068. st->codec->sample_rate = 8000;
  1069. st->codec->frame_size= 160;
  1070. st->codec->channels= 1; /* really needed */
  1071. break;
  1072. case CODEC_ID_AMR_NB:
  1073. case CODEC_ID_AMR_WB:
  1074. st->codec->frame_size= sc->samples_per_frame;
  1075. st->codec->channels= 1; /* really needed */
  1076. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1077. if (st->codec->codec_id == CODEC_ID_AMR_NB)
  1078. st->codec->sample_rate = 8000;
  1079. else if (st->codec->codec_id == CODEC_ID_AMR_WB)
  1080. st->codec->sample_rate = 16000;
  1081. break;
  1082. case CODEC_ID_MP2:
  1083. case CODEC_ID_MP3:
  1084. st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  1085. st->need_parsing = AVSTREAM_PARSE_FULL;
  1086. break;
  1087. case CODEC_ID_GSM:
  1088. case CODEC_ID_ADPCM_MS:
  1089. case CODEC_ID_ADPCM_IMA_WAV:
  1090. st->codec->frame_size = sc->samples_per_frame;
  1091. st->codec->block_align = sc->bytes_per_frame;
  1092. break;
  1093. case CODEC_ID_ALAC:
  1094. if (st->codec->extradata_size == 36) {
  1095. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  1096. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1097. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1098. }
  1099. break;
  1100. default:
  1101. break;
  1102. }
  1103. return 0;
  1104. }
  1105. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1106. {
  1107. int entries;
  1108. avio_r8(pb); /* version */
  1109. avio_rb24(pb); /* flags */
  1110. entries = avio_rb32(pb);
  1111. return ff_mov_read_stsd_entries(c, pb, entries);
  1112. }
  1113. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1114. {
  1115. AVStream *st;
  1116. MOVStreamContext *sc;
  1117. unsigned int i, entries;
  1118. if (c->fc->nb_streams < 1)
  1119. return 0;
  1120. st = c->fc->streams[c->fc->nb_streams-1];
  1121. sc = st->priv_data;
  1122. avio_r8(pb); /* version */
  1123. avio_rb24(pb); /* flags */
  1124. entries = avio_rb32(pb);
  1125. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1126. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1127. return -1;
  1128. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1129. if (!sc->stsc_data)
  1130. return AVERROR(ENOMEM);
  1131. sc->stsc_count = entries;
  1132. for(i=0; i<entries; i++) {
  1133. sc->stsc_data[i].first = avio_rb32(pb);
  1134. sc->stsc_data[i].count = avio_rb32(pb);
  1135. sc->stsc_data[i].id = avio_rb32(pb);
  1136. }
  1137. return 0;
  1138. }
  1139. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1140. {
  1141. AVStream *st;
  1142. MOVStreamContext *sc;
  1143. unsigned i, entries;
  1144. if (c->fc->nb_streams < 1)
  1145. return 0;
  1146. st = c->fc->streams[c->fc->nb_streams-1];
  1147. sc = st->priv_data;
  1148. avio_rb32(pb); // version + flags
  1149. entries = avio_rb32(pb);
  1150. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1151. return -1;
  1152. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1153. if (!sc->stps_data)
  1154. return AVERROR(ENOMEM);
  1155. sc->stps_count = entries;
  1156. for (i = 0; i < entries; i++) {
  1157. sc->stps_data[i] = avio_rb32(pb);
  1158. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1159. }
  1160. return 0;
  1161. }
  1162. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1163. {
  1164. AVStream *st;
  1165. MOVStreamContext *sc;
  1166. unsigned int i, entries;
  1167. if (c->fc->nb_streams < 1)
  1168. return 0;
  1169. st = c->fc->streams[c->fc->nb_streams-1];
  1170. sc = st->priv_data;
  1171. avio_r8(pb); /* version */
  1172. avio_rb24(pb); /* flags */
  1173. entries = avio_rb32(pb);
  1174. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1175. if(entries >= UINT_MAX / sizeof(int))
  1176. return -1;
  1177. sc->keyframes = av_malloc(entries * sizeof(int));
  1178. if (!sc->keyframes)
  1179. return AVERROR(ENOMEM);
  1180. sc->keyframe_count = entries;
  1181. for(i=0; i<entries; i++) {
  1182. sc->keyframes[i] = avio_rb32(pb);
  1183. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1184. }
  1185. return 0;
  1186. }
  1187. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1188. {
  1189. AVStream *st;
  1190. MOVStreamContext *sc;
  1191. unsigned int i, entries, sample_size, field_size, num_bytes;
  1192. GetBitContext gb;
  1193. unsigned char* buf;
  1194. if (c->fc->nb_streams < 1)
  1195. return 0;
  1196. st = c->fc->streams[c->fc->nb_streams-1];
  1197. sc = st->priv_data;
  1198. avio_r8(pb); /* version */
  1199. avio_rb24(pb); /* flags */
  1200. if (atom.type == MKTAG('s','t','s','z')) {
  1201. sample_size = avio_rb32(pb);
  1202. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1203. sc->sample_size = sample_size;
  1204. field_size = 32;
  1205. } else {
  1206. sample_size = 0;
  1207. avio_rb24(pb); /* reserved */
  1208. field_size = avio_r8(pb);
  1209. }
  1210. entries = avio_rb32(pb);
  1211. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1212. sc->sample_count = entries;
  1213. if (sample_size)
  1214. return 0;
  1215. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1216. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1217. return -1;
  1218. }
  1219. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1220. return -1;
  1221. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1222. if (!sc->sample_sizes)
  1223. return AVERROR(ENOMEM);
  1224. num_bytes = (entries*field_size+4)>>3;
  1225. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1226. if (!buf) {
  1227. av_freep(&sc->sample_sizes);
  1228. return AVERROR(ENOMEM);
  1229. }
  1230. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1231. av_freep(&sc->sample_sizes);
  1232. av_free(buf);
  1233. return -1;
  1234. }
  1235. init_get_bits(&gb, buf, 8*num_bytes);
  1236. for(i=0; i<entries; i++)
  1237. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1238. av_free(buf);
  1239. return 0;
  1240. }
  1241. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1242. {
  1243. AVStream *st;
  1244. MOVStreamContext *sc;
  1245. unsigned int i, entries;
  1246. int64_t duration=0;
  1247. int64_t total_sample_count=0;
  1248. if (c->fc->nb_streams < 1)
  1249. return 0;
  1250. st = c->fc->streams[c->fc->nb_streams-1];
  1251. sc = st->priv_data;
  1252. avio_r8(pb); /* version */
  1253. avio_rb24(pb); /* flags */
  1254. entries = avio_rb32(pb);
  1255. av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1256. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1257. return -1;
  1258. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1259. if (!sc->stts_data)
  1260. return AVERROR(ENOMEM);
  1261. sc->stts_count = entries;
  1262. for(i=0; i<entries; i++) {
  1263. int sample_duration;
  1264. int sample_count;
  1265. sample_count=avio_rb32(pb);
  1266. sample_duration = avio_rb32(pb);
  1267. sc->stts_data[i].count= sample_count;
  1268. sc->stts_data[i].duration= sample_duration;
  1269. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1270. duration+=(int64_t)sample_duration*sample_count;
  1271. total_sample_count+=sample_count;
  1272. }
  1273. st->nb_frames= total_sample_count;
  1274. if(duration)
  1275. st->duration= duration;
  1276. return 0;
  1277. }
  1278. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1279. {
  1280. AVStream *st;
  1281. MOVStreamContext *sc;
  1282. unsigned int i, entries;
  1283. if (c->fc->nb_streams < 1)
  1284. return 0;
  1285. st = c->fc->streams[c->fc->nb_streams-1];
  1286. sc = st->priv_data;
  1287. avio_r8(pb); /* version */
  1288. avio_rb24(pb); /* flags */
  1289. entries = avio_rb32(pb);
  1290. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1291. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1292. return -1;
  1293. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1294. if (!sc->ctts_data)
  1295. return AVERROR(ENOMEM);
  1296. sc->ctts_count = entries;
  1297. for(i=0; i<entries; i++) {
  1298. int count =avio_rb32(pb);
  1299. int duration =avio_rb32(pb);
  1300. sc->ctts_data[i].count = count;
  1301. sc->ctts_data[i].duration= duration;
  1302. if (duration < 0 && i+1<entries)
  1303. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1304. }
  1305. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1306. return 0;
  1307. }
  1308. static void mov_build_index(MOVContext *mov, AVStream *st)
  1309. {
  1310. MOVStreamContext *sc = st->priv_data;
  1311. int64_t current_offset;
  1312. int64_t current_dts = 0;
  1313. unsigned int stts_index = 0;
  1314. unsigned int stsc_index = 0;
  1315. unsigned int stss_index = 0;
  1316. unsigned int stps_index = 0;
  1317. unsigned int i, j;
  1318. uint64_t stream_size = 0;
  1319. /* adjust first dts according to edit list */
  1320. if (sc->time_offset && mov->time_scale > 0) {
  1321. if (sc->time_offset < 0)
  1322. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1323. current_dts = -sc->time_offset;
  1324. if (sc->ctts_data && sc->stts_data &&
  1325. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1326. /* more than 16 frames delay, dts are likely wrong
  1327. this happens with files created by iMovie */
  1328. sc->wrong_dts = 1;
  1329. st->codec->has_b_frames = 1;
  1330. }
  1331. }
  1332. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1333. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1334. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1335. unsigned int current_sample = 0;
  1336. unsigned int stts_sample = 0;
  1337. unsigned int sample_size;
  1338. unsigned int distance = 0;
  1339. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1340. current_dts -= sc->dts_shift;
  1341. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
  1342. return;
  1343. st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
  1344. if (!st->index_entries)
  1345. return;
  1346. st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
  1347. for (i = 0; i < sc->chunk_count; i++) {
  1348. current_offset = sc->chunk_offsets[i];
  1349. while (stsc_index + 1 < sc->stsc_count &&
  1350. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1351. stsc_index++;
  1352. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1353. int keyframe = 0;
  1354. if (current_sample >= sc->sample_count) {
  1355. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1356. return;
  1357. }
  1358. if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
  1359. keyframe = 1;
  1360. if (stss_index + 1 < sc->keyframe_count)
  1361. stss_index++;
  1362. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1363. keyframe = 1;
  1364. if (stps_index + 1 < sc->stps_count)
  1365. stps_index++;
  1366. }
  1367. if (keyframe)
  1368. distance = 0;
  1369. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1370. if(sc->pseudo_stream_id == -1 ||
  1371. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1372. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1373. e->pos = current_offset;
  1374. e->timestamp = current_dts;
  1375. e->size = sample_size;
  1376. e->min_distance = distance;
  1377. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1378. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1379. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1380. current_offset, current_dts, sample_size, distance, keyframe);
  1381. }
  1382. current_offset += sample_size;
  1383. stream_size += sample_size;
  1384. current_dts += sc->stts_data[stts_index].duration;
  1385. distance++;
  1386. stts_sample++;
  1387. current_sample++;
  1388. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1389. stts_sample = 0;
  1390. stts_index++;
  1391. }
  1392. }
  1393. }
  1394. if (st->duration > 0)
  1395. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1396. } else {
  1397. unsigned chunk_samples, total = 0;
  1398. // compute total chunk count
  1399. for (i = 0; i < sc->stsc_count; i++) {
  1400. unsigned count, chunk_count;
  1401. chunk_samples = sc->stsc_data[i].count;
  1402. if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1403. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1404. return;
  1405. }
  1406. if (sc->samples_per_frame >= 160) { // gsm
  1407. count = chunk_samples / sc->samples_per_frame;
  1408. } else if (sc->samples_per_frame > 1) {
  1409. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1410. count = (chunk_samples+samples-1) / samples;
  1411. } else {
  1412. count = (chunk_samples+1023) / 1024;
  1413. }
  1414. if (i < sc->stsc_count - 1)
  1415. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1416. else
  1417. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1418. total += chunk_count * count;
  1419. }
  1420. av_dlog(mov->fc, "chunk count %d\n", total);
  1421. if (total >= UINT_MAX / sizeof(*st->index_entries))
  1422. return;
  1423. st->index_entries = av_malloc(total*sizeof(*st->index_entries));
  1424. if (!st->index_entries)
  1425. return;
  1426. st->index_entries_allocated_size = total*sizeof(*st->index_entries);
  1427. // populate index
  1428. for (i = 0; i < sc->chunk_count; i++) {
  1429. current_offset = sc->chunk_offsets[i];
  1430. if (stsc_index + 1 < sc->stsc_count &&
  1431. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1432. stsc_index++;
  1433. chunk_samples = sc->stsc_data[stsc_index].count;
  1434. while (chunk_samples > 0) {
  1435. AVIndexEntry *e;
  1436. unsigned size, samples;
  1437. if (sc->samples_per_frame >= 160) { // gsm
  1438. samples = sc->samples_per_frame;
  1439. size = sc->bytes_per_frame;
  1440. } else {
  1441. if (sc->samples_per_frame > 1) {
  1442. samples = FFMIN((1024 / sc->samples_per_frame)*
  1443. sc->samples_per_frame, chunk_samples);
  1444. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1445. } else {
  1446. samples = FFMIN(1024, chunk_samples);
  1447. size = samples * sc->sample_size;
  1448. }
  1449. }
  1450. if (st->nb_index_entries >= total) {
  1451. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1452. return;
  1453. }
  1454. e = &st->index_entries[st->nb_index_entries++];
  1455. e->pos = current_offset;
  1456. e->timestamp = current_dts;
  1457. e->size = size;
  1458. e->min_distance = 0;
  1459. e->flags = AVINDEX_KEYFRAME;
  1460. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1461. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1462. size, samples);
  1463. current_offset += size;
  1464. current_dts += samples;
  1465. chunk_samples -= samples;
  1466. }
  1467. }
  1468. }
  1469. }
  1470. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref)
  1471. {
  1472. /* try relative path, we do not try the absolute because it can leak information about our
  1473. system to an attacker */
  1474. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1475. char filename[1024];
  1476. const char *src_path;
  1477. int i, l;
  1478. /* find a source dir */
  1479. src_path = strrchr(src, '/');
  1480. if (src_path)
  1481. src_path++;
  1482. else
  1483. src_path = src;
  1484. /* find a next level down to target */
  1485. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1486. if (ref->path[l] == '/') {
  1487. if (i == ref->nlvl_to - 1)
  1488. break;
  1489. else
  1490. i++;
  1491. }
  1492. /* compose filename if next level down to target was found */
  1493. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1494. memcpy(filename, src, src_path - src);
  1495. filename[src_path - src] = 0;
  1496. for (i = 1; i < ref->nlvl_from; i++)
  1497. av_strlcat(filename, "../", 1024);
  1498. av_strlcat(filename, ref->path + l + 1, 1024);
  1499. if (!avio_open(pb, filename, AVIO_RDONLY))
  1500. return 0;
  1501. }
  1502. }
  1503. return AVERROR(ENOENT);
  1504. }
  1505. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1506. {
  1507. AVStream *st;
  1508. MOVStreamContext *sc;
  1509. int ret;
  1510. st = av_new_stream(c->fc, c->fc->nb_streams);
  1511. if (!st) return AVERROR(ENOMEM);
  1512. sc = av_mallocz(sizeof(MOVStreamContext));
  1513. if (!sc) return AVERROR(ENOMEM);
  1514. st->priv_data = sc;
  1515. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1516. sc->ffindex = st->index;
  1517. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1518. return ret;
  1519. /* sanity checks */
  1520. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1521. (!sc->sample_size && !sc->sample_count))) {
  1522. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1523. st->index);
  1524. return 0;
  1525. }
  1526. if (sc->time_scale <= 0) {
  1527. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1528. sc->time_scale = c->time_scale;
  1529. if (sc->time_scale <= 0)
  1530. sc->time_scale = 1;
  1531. }
  1532. av_set_pts_info(st, 64, 1, sc->time_scale);
  1533. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1534. !st->codec->frame_size && sc->stts_count == 1) {
  1535. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1536. st->codec->sample_rate, sc->time_scale);
  1537. av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
  1538. }
  1539. mov_build_index(c, st);
  1540. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1541. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1542. if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
  1543. av_log(c->fc, AV_LOG_ERROR,
  1544. "stream %d, error opening alias: path='%s', dir='%s', "
  1545. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1546. st->index, dref->path, dref->dir, dref->filename,
  1547. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1548. } else
  1549. sc->pb = c->fc->pb;
  1550. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1551. if (!st->sample_aspect_ratio.num &&
  1552. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1553. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1554. ((double)st->codec->width * sc->height), INT_MAX);
  1555. }
  1556. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1557. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1558. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  1559. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  1560. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  1561. }
  1562. switch (st->codec->codec_id) {
  1563. #if CONFIG_H261_DECODER
  1564. case CODEC_ID_H261:
  1565. #endif
  1566. #if CONFIG_H263_DECODER
  1567. case CODEC_ID_H263:
  1568. #endif
  1569. #if CONFIG_H264_DECODER
  1570. case CODEC_ID_H264:
  1571. #endif
  1572. #if CONFIG_MPEG4_DECODER
  1573. case CODEC_ID_MPEG4:
  1574. #endif
  1575. st->codec->width = 0; /* let decoder init width/height */
  1576. st->codec->height= 0;
  1577. break;
  1578. }
  1579. /* Do not need those anymore. */
  1580. av_freep(&sc->chunk_offsets);
  1581. av_freep(&sc->stsc_data);
  1582. av_freep(&sc->sample_sizes);
  1583. av_freep(&sc->keyframes);
  1584. av_freep(&sc->stts_data);
  1585. av_freep(&sc->stps_data);
  1586. return 0;
  1587. }
  1588. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1589. {
  1590. int ret;
  1591. c->itunes_metadata = 1;
  1592. ret = mov_read_default(c, pb, atom);
  1593. c->itunes_metadata = 0;
  1594. return ret;
  1595. }
  1596. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1597. {
  1598. while (atom.size > 8) {
  1599. uint32_t tag = avio_rl32(pb);
  1600. atom.size -= 4;
  1601. if (tag == MKTAG('h','d','l','r')) {
  1602. avio_seek(pb, -8, SEEK_CUR);
  1603. atom.size += 8;
  1604. return mov_read_default(c, pb, atom);
  1605. }
  1606. }
  1607. return 0;
  1608. }
  1609. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1610. {
  1611. int i;
  1612. int width;
  1613. int height;
  1614. int64_t disp_transform[2];
  1615. int display_matrix[3][2];
  1616. AVStream *st;
  1617. MOVStreamContext *sc;
  1618. int version;
  1619. if (c->fc->nb_streams < 1)
  1620. return 0;
  1621. st = c->fc->streams[c->fc->nb_streams-1];
  1622. sc = st->priv_data;
  1623. version = avio_r8(pb);
  1624. avio_rb24(pb); /* flags */
  1625. /*
  1626. MOV_TRACK_ENABLED 0x0001
  1627. MOV_TRACK_IN_MOVIE 0x0002
  1628. MOV_TRACK_IN_PREVIEW 0x0004
  1629. MOV_TRACK_IN_POSTER 0x0008
  1630. */
  1631. if (version == 1) {
  1632. avio_rb64(pb);
  1633. avio_rb64(pb);
  1634. } else {
  1635. avio_rb32(pb); /* creation time */
  1636. avio_rb32(pb); /* modification time */
  1637. }
  1638. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  1639. avio_rb32(pb); /* reserved */
  1640. /* highlevel (considering edits) duration in movie timebase */
  1641. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  1642. avio_rb32(pb); /* reserved */
  1643. avio_rb32(pb); /* reserved */
  1644. avio_rb16(pb); /* layer */
  1645. avio_rb16(pb); /* alternate group */
  1646. avio_rb16(pb); /* volume */
  1647. avio_rb16(pb); /* reserved */
  1648. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1649. // they're kept in fixed point format through all calculations
  1650. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1651. for (i = 0; i < 3; i++) {
  1652. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1653. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1654. avio_rb32(pb); // 2.30 fixed point (not used)
  1655. }
  1656. width = avio_rb32(pb); // 16.16 fixed point track width
  1657. height = avio_rb32(pb); // 16.16 fixed point track height
  1658. sc->width = width >> 16;
  1659. sc->height = height >> 16;
  1660. if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
  1661. av_dict_set(&st->metadata, "rotate", "180", 0);
  1662. }
  1663. // transform the display width/height according to the matrix
  1664. // skip this if the display matrix is the default identity matrix
  1665. // or if it is rotating the picture, ex iPhone 3GS
  1666. // to keep the same scale, use [width height 1<<16]
  1667. if (width && height &&
  1668. ((display_matrix[0][0] != 65536 ||
  1669. display_matrix[1][1] != 65536) &&
  1670. !display_matrix[0][1] &&
  1671. !display_matrix[1][0] &&
  1672. !display_matrix[2][0] && !display_matrix[2][1])) {
  1673. for (i = 0; i < 2; i++)
  1674. disp_transform[i] =
  1675. (int64_t) width * display_matrix[0][i] +
  1676. (int64_t) height * display_matrix[1][i] +
  1677. ((int64_t) display_matrix[2][i] << 16);
  1678. //sample aspect ratio is new width/height divided by old width/height
  1679. st->sample_aspect_ratio = av_d2q(
  1680. ((double) disp_transform[0] * height) /
  1681. ((double) disp_transform[1] * width), INT_MAX);
  1682. }
  1683. return 0;
  1684. }
  1685. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1686. {
  1687. MOVFragment *frag = &c->fragment;
  1688. MOVTrackExt *trex = NULL;
  1689. int flags, track_id, i;
  1690. avio_r8(pb); /* version */
  1691. flags = avio_rb24(pb);
  1692. track_id = avio_rb32(pb);
  1693. if (!track_id)
  1694. return -1;
  1695. frag->track_id = track_id;
  1696. for (i = 0; i < c->trex_count; i++)
  1697. if (c->trex_data[i].track_id == frag->track_id) {
  1698. trex = &c->trex_data[i];
  1699. break;
  1700. }
  1701. if (!trex) {
  1702. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1703. return -1;
  1704. }
  1705. if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
  1706. else frag->base_data_offset = frag->moof_offset;
  1707. if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
  1708. else frag->stsd_id = trex->stsd_id;
  1709. frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
  1710. frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
  1711. frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
  1712. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  1713. return 0;
  1714. }
  1715. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1716. {
  1717. c->chapter_track = avio_rb32(pb);
  1718. return 0;
  1719. }
  1720. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1721. {
  1722. MOVTrackExt *trex;
  1723. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1724. return -1;
  1725. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1726. if (!trex)
  1727. return AVERROR(ENOMEM);
  1728. c->trex_data = trex;
  1729. trex = &c->trex_data[c->trex_count++];
  1730. avio_r8(pb); /* version */
  1731. avio_rb24(pb); /* flags */
  1732. trex->track_id = avio_rb32(pb);
  1733. trex->stsd_id = avio_rb32(pb);
  1734. trex->duration = avio_rb32(pb);
  1735. trex->size = avio_rb32(pb);
  1736. trex->flags = avio_rb32(pb);
  1737. return 0;
  1738. }
  1739. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1740. {
  1741. MOVFragment *frag = &c->fragment;
  1742. AVStream *st = NULL;
  1743. MOVStreamContext *sc;
  1744. MOVStts *ctts_data;
  1745. uint64_t offset;
  1746. int64_t dts;
  1747. int data_offset = 0;
  1748. unsigned entries, first_sample_flags = frag->flags;
  1749. int flags, distance, i;
  1750. for (i = 0; i < c->fc->nb_streams; i++) {
  1751. if (c->fc->streams[i]->id == frag->track_id) {
  1752. st = c->fc->streams[i];
  1753. break;
  1754. }
  1755. }
  1756. if (!st) {
  1757. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1758. return -1;
  1759. }
  1760. sc = st->priv_data;
  1761. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1762. return 0;
  1763. avio_r8(pb); /* version */
  1764. flags = avio_rb24(pb);
  1765. entries = avio_rb32(pb);
  1766. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1767. /* Always assume the presence of composition time offsets.
  1768. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  1769. * 1) in the initial movie, there are no samples.
  1770. * 2) in the first movie fragment, there is only one sample without composition time offset.
  1771. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  1772. if (!sc->ctts_count && sc->sample_count)
  1773. {
  1774. /* Complement ctts table if moov atom doesn't have ctts atom. */
  1775. ctts_data = av_malloc(sizeof(*sc->ctts_data));
  1776. if (!ctts_data)
  1777. return AVERROR(ENOMEM);
  1778. sc->ctts_data = ctts_data;
  1779. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  1780. sc->ctts_data[sc->ctts_count].duration = 0;
  1781. sc->ctts_count++;
  1782. }
  1783. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1784. return -1;
  1785. ctts_data = av_realloc(sc->ctts_data,
  1786. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1787. if (!ctts_data)
  1788. return AVERROR(ENOMEM);
  1789. sc->ctts_data = ctts_data;
  1790. if (flags & 0x001) data_offset = avio_rb32(pb);
  1791. if (flags & 0x004) first_sample_flags = avio_rb32(pb);
  1792. dts = st->duration - sc->time_offset;
  1793. offset = frag->base_data_offset + data_offset;
  1794. distance = 0;
  1795. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1796. for (i = 0; i < entries; i++) {
  1797. unsigned sample_size = frag->size;
  1798. int sample_flags = i ? frag->flags : first_sample_flags;
  1799. unsigned sample_duration = frag->duration;
  1800. int keyframe;
  1801. if (flags & 0x100) sample_duration = avio_rb32(pb);
  1802. if (flags & 0x200) sample_size = avio_rb32(pb);
  1803. if (flags & 0x400) sample_flags = avio_rb32(pb);
  1804. sc->ctts_data[sc->ctts_count].count = 1;
  1805. sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
  1806. sc->ctts_count++;
  1807. if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
  1808. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1809. distance = 0;
  1810. av_add_index_entry(st, offset, dts, sample_size, distance,
  1811. keyframe ? AVINDEX_KEYFRAME : 0);
  1812. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1813. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1814. offset, dts, sample_size, distance, keyframe);
  1815. distance++;
  1816. dts += sample_duration;
  1817. offset += sample_size;
  1818. }
  1819. frag->moof_offset = offset;
  1820. st->duration = dts + sc->time_offset;
  1821. return 0;
  1822. }
  1823. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1824. /* like the files created with Adobe Premiere 5.0, for samples see */
  1825. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1826. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1827. {
  1828. int err;
  1829. if (atom.size < 8)
  1830. return 0; /* continue */
  1831. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1832. avio_skip(pb, atom.size - 4);
  1833. return 0;
  1834. }
  1835. atom.type = avio_rl32(pb);
  1836. atom.size -= 8;
  1837. if (atom.type != MKTAG('m','d','a','t')) {
  1838. avio_skip(pb, atom.size);
  1839. return 0;
  1840. }
  1841. err = mov_read_mdat(c, pb, atom);
  1842. return err;
  1843. }
  1844. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1845. {
  1846. #if CONFIG_ZLIB
  1847. AVIOContext ctx;
  1848. uint8_t *cmov_data;
  1849. uint8_t *moov_data; /* uncompressed data */
  1850. long cmov_len, moov_len;
  1851. int ret = -1;
  1852. avio_rb32(pb); /* dcom atom */
  1853. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  1854. return -1;
  1855. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  1856. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1857. return -1;
  1858. }
  1859. avio_rb32(pb); /* cmvd atom */
  1860. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  1861. return -1;
  1862. moov_len = avio_rb32(pb); /* uncompressed size */
  1863. cmov_len = atom.size - 6 * 4;
  1864. cmov_data = av_malloc(cmov_len);
  1865. if (!cmov_data)
  1866. return AVERROR(ENOMEM);
  1867. moov_data = av_malloc(moov_len);
  1868. if (!moov_data) {
  1869. av_free(cmov_data);
  1870. return AVERROR(ENOMEM);
  1871. }
  1872. avio_read(pb, cmov_data, cmov_len);
  1873. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1874. goto free_and_return;
  1875. if(ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1876. goto free_and_return;
  1877. atom.type = MKTAG('m','o','o','v');
  1878. atom.size = moov_len;
  1879. ret = mov_read_default(c, &ctx, atom);
  1880. free_and_return:
  1881. av_free(moov_data);
  1882. av_free(cmov_data);
  1883. return ret;
  1884. #else
  1885. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1886. return -1;
  1887. #endif
  1888. }
  1889. /* edit list atom */
  1890. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1891. {
  1892. MOVStreamContext *sc;
  1893. int i, edit_count, version;
  1894. if (c->fc->nb_streams < 1)
  1895. return 0;
  1896. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1897. version = avio_r8(pb); /* version */
  1898. avio_rb24(pb); /* flags */
  1899. edit_count = avio_rb32(pb); /* entries */
  1900. if((uint64_t)edit_count*12+8 > atom.size)
  1901. return -1;
  1902. for(i=0; i<edit_count; i++){
  1903. int64_t time;
  1904. int64_t duration;
  1905. if (version == 1) {
  1906. duration = avio_rb64(pb);
  1907. time = avio_rb64(pb);
  1908. } else {
  1909. duration = avio_rb32(pb); /* segment duration */
  1910. time = (int32_t)avio_rb32(pb); /* media time */
  1911. }
  1912. avio_rb32(pb); /* Media rate */
  1913. if (i == 0 && time >= -1) {
  1914. sc->time_offset = time != -1 ? time : -duration;
  1915. }
  1916. }
  1917. if(edit_count > 1)
  1918. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1919. "a/v desync might occur, patch welcome\n");
  1920. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1921. return 0;
  1922. }
  1923. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1924. {
  1925. if (atom.size < 16)
  1926. return AVERROR_INVALIDDATA;
  1927. avio_skip(pb, 4);
  1928. ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
  1929. return 0;
  1930. }
  1931. static const MOVParseTableEntry mov_default_parse_table[] = {
  1932. { MKTAG('a','v','s','s'), mov_read_extradata },
  1933. { MKTAG('c','h','p','l'), mov_read_chpl },
  1934. { MKTAG('c','o','6','4'), mov_read_stco },
  1935. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1936. { MKTAG('d','i','n','f'), mov_read_default },
  1937. { MKTAG('d','r','e','f'), mov_read_dref },
  1938. { MKTAG('e','d','t','s'), mov_read_default },
  1939. { MKTAG('e','l','s','t'), mov_read_elst },
  1940. { MKTAG('e','n','d','a'), mov_read_enda },
  1941. { MKTAG('f','i','e','l'), mov_read_extradata },
  1942. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1943. { MKTAG('g','l','b','l'), mov_read_glbl },
  1944. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1945. { MKTAG('i','l','s','t'), mov_read_ilst },
  1946. { MKTAG('j','p','2','h'), mov_read_extradata },
  1947. { MKTAG('m','d','a','t'), mov_read_mdat },
  1948. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1949. { MKTAG('m','d','i','a'), mov_read_default },
  1950. { MKTAG('m','e','t','a'), mov_read_meta },
  1951. { MKTAG('m','i','n','f'), mov_read_default },
  1952. { MKTAG('m','o','o','f'), mov_read_moof },
  1953. { MKTAG('m','o','o','v'), mov_read_moov },
  1954. { MKTAG('m','v','e','x'), mov_read_default },
  1955. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1956. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1957. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1958. { MKTAG('a','v','c','C'), mov_read_glbl },
  1959. { MKTAG('p','a','s','p'), mov_read_pasp },
  1960. { MKTAG('s','t','b','l'), mov_read_default },
  1961. { MKTAG('s','t','c','o'), mov_read_stco },
  1962. { MKTAG('s','t','p','s'), mov_read_stps },
  1963. { MKTAG('s','t','r','f'), mov_read_strf },
  1964. { MKTAG('s','t','s','c'), mov_read_stsc },
  1965. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1966. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1967. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1968. { MKTAG('s','t','t','s'), mov_read_stts },
  1969. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  1970. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1971. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1972. { MKTAG('t','r','a','k'), mov_read_trak },
  1973. { MKTAG('t','r','a','f'), mov_read_default },
  1974. { MKTAG('t','r','e','f'), mov_read_default },
  1975. { MKTAG('c','h','a','p'), mov_read_chap },
  1976. { MKTAG('t','r','e','x'), mov_read_trex },
  1977. { MKTAG('t','r','u','n'), mov_read_trun },
  1978. { MKTAG('u','d','t','a'), mov_read_default },
  1979. { MKTAG('w','a','v','e'), mov_read_wave },
  1980. { MKTAG('e','s','d','s'), mov_read_esds },
  1981. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  1982. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1983. { MKTAG('w','f','e','x'), mov_read_wfex },
  1984. { MKTAG('c','m','o','v'), mov_read_cmov },
  1985. { MKTAG('c','h','a','n'), mov_read_chan },
  1986. { 0, NULL }
  1987. };
  1988. static int mov_probe(AVProbeData *p)
  1989. {
  1990. unsigned int offset;
  1991. uint32_t tag;
  1992. int score = 0;
  1993. /* check file header */
  1994. offset = 0;
  1995. for(;;) {
  1996. /* ignore invalid offset */
  1997. if ((offset + 8) > (unsigned int)p->buf_size)
  1998. return score;
  1999. tag = AV_RL32(p->buf + offset + 4);
  2000. switch(tag) {
  2001. /* check for obvious tags */
  2002. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2003. case MKTAG('m','o','o','v'):
  2004. case MKTAG('m','d','a','t'):
  2005. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2006. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2007. case MKTAG('f','t','y','p'):
  2008. return AVPROBE_SCORE_MAX;
  2009. /* those are more common words, so rate then a bit less */
  2010. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2011. case MKTAG('w','i','d','e'):
  2012. case MKTAG('f','r','e','e'):
  2013. case MKTAG('j','u','n','k'):
  2014. case MKTAG('p','i','c','t'):
  2015. return AVPROBE_SCORE_MAX - 5;
  2016. case MKTAG(0x82,0x82,0x7f,0x7d):
  2017. case MKTAG('s','k','i','p'):
  2018. case MKTAG('u','u','i','d'):
  2019. case MKTAG('p','r','f','l'):
  2020. offset = AV_RB32(p->buf+offset) + offset;
  2021. /* if we only find those cause probedata is too small at least rate them */
  2022. score = AVPROBE_SCORE_MAX - 50;
  2023. break;
  2024. default:
  2025. /* unrecognized tag */
  2026. return score;
  2027. }
  2028. }
  2029. return score;
  2030. }
  2031. // must be done after parsing all trak because there's no order requirement
  2032. static void mov_read_chapters(AVFormatContext *s)
  2033. {
  2034. MOVContext *mov = s->priv_data;
  2035. AVStream *st = NULL;
  2036. MOVStreamContext *sc;
  2037. int64_t cur_pos;
  2038. int i;
  2039. for (i = 0; i < s->nb_streams; i++)
  2040. if (s->streams[i]->id == mov->chapter_track) {
  2041. st = s->streams[i];
  2042. break;
  2043. }
  2044. if (!st) {
  2045. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2046. return;
  2047. }
  2048. st->discard = AVDISCARD_ALL;
  2049. sc = st->priv_data;
  2050. cur_pos = avio_tell(sc->pb);
  2051. for (i = 0; i < st->nb_index_entries; i++) {
  2052. AVIndexEntry *sample = &st->index_entries[i];
  2053. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2054. uint8_t *title;
  2055. uint16_t ch;
  2056. int len, title_len;
  2057. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2058. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2059. goto finish;
  2060. }
  2061. // the first two bytes are the length of the title
  2062. len = avio_rb16(sc->pb);
  2063. if (len > sample->size-2)
  2064. continue;
  2065. title_len = 2*len + 1;
  2066. if (!(title = av_mallocz(title_len)))
  2067. goto finish;
  2068. // The samples could theoretically be in any encoding if there's an encd
  2069. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2070. // instead by the presence of a BOM
  2071. ch = avio_rb16(sc->pb);
  2072. if (ch == 0xfeff)
  2073. avio_get_str16be(sc->pb, len, title, title_len);
  2074. else if (ch == 0xfffe)
  2075. avio_get_str16le(sc->pb, len, title, title_len);
  2076. else {
  2077. AV_WB16(title, ch);
  2078. get_strz(sc->pb, title + 2, len - 1);
  2079. }
  2080. ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2081. av_freep(&title);
  2082. }
  2083. finish:
  2084. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2085. }
  2086. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  2087. {
  2088. MOVContext *mov = s->priv_data;
  2089. AVIOContext *pb = s->pb;
  2090. int err;
  2091. MOVAtom atom = { AV_RL32("root") };
  2092. mov->fc = s;
  2093. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2094. if(pb->seekable)
  2095. atom.size = avio_size(pb);
  2096. else
  2097. atom.size = INT64_MAX;
  2098. /* check MOV header */
  2099. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2100. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2101. return err;
  2102. }
  2103. if (!mov->found_moov) {
  2104. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2105. return -1;
  2106. }
  2107. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2108. if (pb->seekable && mov->chapter_track > 0)
  2109. mov_read_chapters(s);
  2110. return 0;
  2111. }
  2112. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2113. {
  2114. AVIndexEntry *sample = NULL;
  2115. int64_t best_dts = INT64_MAX;
  2116. int i;
  2117. for (i = 0; i < s->nb_streams; i++) {
  2118. AVStream *avst = s->streams[i];
  2119. MOVStreamContext *msc = avst->priv_data;
  2120. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2121. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2122. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2123. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2124. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2125. (s->pb->seekable &&
  2126. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2127. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2128. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2129. sample = current_sample;
  2130. best_dts = dts;
  2131. *st = avst;
  2132. }
  2133. }
  2134. }
  2135. return sample;
  2136. }
  2137. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2138. {
  2139. MOVContext *mov = s->priv_data;
  2140. MOVStreamContext *sc;
  2141. AVIndexEntry *sample;
  2142. AVStream *st = NULL;
  2143. int ret;
  2144. retry:
  2145. sample = mov_find_next_sample(s, &st);
  2146. if (!sample) {
  2147. mov->found_mdat = 0;
  2148. if (s->pb->seekable||
  2149. mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2150. url_feof(s->pb))
  2151. return AVERROR_EOF;
  2152. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  2153. goto retry;
  2154. }
  2155. sc = st->priv_data;
  2156. /* must be done just before reading, to avoid infinite loop on sample */
  2157. sc->current_sample++;
  2158. if (st->discard != AVDISCARD_ALL) {
  2159. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2160. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2161. sc->ffindex, sample->pos);
  2162. return -1;
  2163. }
  2164. ret = av_get_packet(sc->pb, pkt, sample->size);
  2165. if (ret < 0)
  2166. return ret;
  2167. #if CONFIG_DV_DEMUXER
  2168. if (mov->dv_demux && sc->dv_audio_container) {
  2169. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  2170. av_free(pkt->data);
  2171. pkt->size = 0;
  2172. ret = dv_get_packet(mov->dv_demux, pkt);
  2173. if (ret < 0)
  2174. return ret;
  2175. }
  2176. #endif
  2177. }
  2178. pkt->stream_index = sc->ffindex;
  2179. pkt->dts = sample->timestamp;
  2180. if (sc->ctts_data) {
  2181. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2182. /* update ctts context */
  2183. sc->ctts_sample++;
  2184. if (sc->ctts_index < sc->ctts_count &&
  2185. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2186. sc->ctts_index++;
  2187. sc->ctts_sample = 0;
  2188. }
  2189. if (sc->wrong_dts)
  2190. pkt->dts = AV_NOPTS_VALUE;
  2191. } else {
  2192. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2193. st->index_entries[sc->current_sample].timestamp : st->duration;
  2194. pkt->duration = next_dts - pkt->dts;
  2195. pkt->pts = pkt->dts;
  2196. }
  2197. if (st->discard == AVDISCARD_ALL)
  2198. goto retry;
  2199. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2200. pkt->pos = sample->pos;
  2201. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2202. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2203. return 0;
  2204. }
  2205. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2206. {
  2207. MOVStreamContext *sc = st->priv_data;
  2208. int sample, time_sample;
  2209. int i;
  2210. sample = av_index_search_timestamp(st, timestamp, flags);
  2211. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2212. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2213. sample = 0;
  2214. if (sample < 0) /* not sure what to do */
  2215. return -1;
  2216. sc->current_sample = sample;
  2217. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2218. /* adjust ctts index */
  2219. if (sc->ctts_data) {
  2220. time_sample = 0;
  2221. for (i = 0; i < sc->ctts_count; i++) {
  2222. int next = time_sample + sc->ctts_data[i].count;
  2223. if (next > sc->current_sample) {
  2224. sc->ctts_index = i;
  2225. sc->ctts_sample = sc->current_sample - time_sample;
  2226. break;
  2227. }
  2228. time_sample = next;
  2229. }
  2230. }
  2231. return sample;
  2232. }
  2233. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2234. {
  2235. AVStream *st;
  2236. int64_t seek_timestamp, timestamp;
  2237. int sample;
  2238. int i;
  2239. if (stream_index >= s->nb_streams)
  2240. return -1;
  2241. if (sample_time < 0)
  2242. sample_time = 0;
  2243. st = s->streams[stream_index];
  2244. sample = mov_seek_stream(s, st, sample_time, flags);
  2245. if (sample < 0)
  2246. return -1;
  2247. /* adjust seek timestamp to found sample timestamp */
  2248. seek_timestamp = st->index_entries[sample].timestamp;
  2249. for (i = 0; i < s->nb_streams; i++) {
  2250. st = s->streams[i];
  2251. if (stream_index == i)
  2252. continue;
  2253. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2254. mov_seek_stream(s, st, timestamp, flags);
  2255. }
  2256. return 0;
  2257. }
  2258. static int mov_read_close(AVFormatContext *s)
  2259. {
  2260. MOVContext *mov = s->priv_data;
  2261. int i, j;
  2262. for (i = 0; i < s->nb_streams; i++) {
  2263. AVStream *st = s->streams[i];
  2264. MOVStreamContext *sc = st->priv_data;
  2265. av_freep(&sc->ctts_data);
  2266. for (j = 0; j < sc->drefs_count; j++) {
  2267. av_freep(&sc->drefs[j].path);
  2268. av_freep(&sc->drefs[j].dir);
  2269. }
  2270. av_freep(&sc->drefs);
  2271. if (sc->pb && sc->pb != s->pb)
  2272. avio_close(sc->pb);
  2273. av_freep(&st->codec->palctrl);
  2274. }
  2275. if (mov->dv_demux) {
  2276. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2277. av_freep(&mov->dv_fctx->streams[i]->codec);
  2278. av_freep(&mov->dv_fctx->streams[i]);
  2279. }
  2280. av_freep(&mov->dv_fctx);
  2281. av_freep(&mov->dv_demux);
  2282. }
  2283. av_freep(&mov->trex_data);
  2284. return 0;
  2285. }
  2286. AVInputFormat ff_mov_demuxer = {
  2287. "mov,mp4,m4a,3gp,3g2,mj2",
  2288. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  2289. sizeof(MOVContext),
  2290. mov_probe,
  2291. mov_read_header,
  2292. mov_read_packet,
  2293. mov_read_close,
  2294. mov_read_seek,
  2295. };