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.

2641 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. if (color_greyscale) {
  896. int color_index, color_dec;
  897. /* compute the greyscale palette */
  898. st->codec->bits_per_coded_sample = color_depth;
  899. color_count = 1 << color_depth;
  900. color_index = 255;
  901. color_dec = 256 / (color_count - 1);
  902. for (j = 0; j < color_count; j++) {
  903. r = g = b = color_index;
  904. sc->palette[j] =
  905. (r << 16) | (g << 8) | (b);
  906. color_index -= color_dec;
  907. if (color_index < 0)
  908. color_index = 0;
  909. }
  910. } else if (st->codec->color_table_id) {
  911. const uint8_t *color_table;
  912. /* if flag bit 3 is set, use the default palette */
  913. color_count = 1 << color_depth;
  914. if (color_depth == 2)
  915. color_table = ff_qt_default_palette_4;
  916. else if (color_depth == 4)
  917. color_table = ff_qt_default_palette_16;
  918. else
  919. color_table = ff_qt_default_palette_256;
  920. for (j = 0; j < color_count; j++) {
  921. r = color_table[j * 3 + 0];
  922. g = color_table[j * 3 + 1];
  923. b = color_table[j * 3 + 2];
  924. sc->palette[j] =
  925. (r << 16) | (g << 8) | (b);
  926. }
  927. } else {
  928. /* load the palette from the file */
  929. color_start = avio_rb32(pb);
  930. color_count = avio_rb16(pb);
  931. color_end = avio_rb16(pb);
  932. if ((color_start <= 255) &&
  933. (color_end <= 255)) {
  934. for (j = color_start; j <= color_end; j++) {
  935. /* each R, G, or B component is 16 bits;
  936. * only use the top 8 bits; skip alpha bytes
  937. * up front */
  938. avio_r8(pb);
  939. avio_r8(pb);
  940. r = avio_r8(pb);
  941. avio_r8(pb);
  942. g = avio_r8(pb);
  943. avio_r8(pb);
  944. b = avio_r8(pb);
  945. avio_r8(pb);
  946. sc->palette[j] =
  947. (r << 16) | (g << 8) | (b);
  948. }
  949. }
  950. }
  951. sc->has_palette = 1;
  952. }
  953. } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  954. int bits_per_sample, flags;
  955. uint16_t version = avio_rb16(pb);
  956. st->codec->codec_id = id;
  957. avio_rb16(pb); /* revision level */
  958. avio_rb32(pb); /* vendor */
  959. st->codec->channels = avio_rb16(pb); /* channel count */
  960. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  961. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  962. sc->audio_cid = avio_rb16(pb);
  963. avio_rb16(pb); /* packet size = 0 */
  964. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  965. //Read QT version 1 fields. In version 0 these do not exist.
  966. av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
  967. if(!c->isom) {
  968. if(version==1) {
  969. sc->samples_per_frame = avio_rb32(pb);
  970. avio_rb32(pb); /* bytes per packet */
  971. sc->bytes_per_frame = avio_rb32(pb);
  972. avio_rb32(pb); /* bytes per sample */
  973. } else if(version==2) {
  974. avio_rb32(pb); /* sizeof struct only */
  975. st->codec->sample_rate = av_int2dbl(avio_rb64(pb)); /* float 64 */
  976. st->codec->channels = avio_rb32(pb);
  977. avio_rb32(pb); /* always 0x7F000000 */
  978. st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
  979. flags = avio_rb32(pb); /* lpcm format specific flag */
  980. sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
  981. sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
  982. if (format == MKTAG('l','p','c','m'))
  983. st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  984. }
  985. }
  986. switch (st->codec->codec_id) {
  987. case CODEC_ID_PCM_S8:
  988. case CODEC_ID_PCM_U8:
  989. if (st->codec->bits_per_coded_sample == 16)
  990. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  991. break;
  992. case CODEC_ID_PCM_S16LE:
  993. case CODEC_ID_PCM_S16BE:
  994. if (st->codec->bits_per_coded_sample == 8)
  995. st->codec->codec_id = CODEC_ID_PCM_S8;
  996. else if (st->codec->bits_per_coded_sample == 24)
  997. st->codec->codec_id =
  998. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  999. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  1000. break;
  1001. /* set values for old format before stsd version 1 appeared */
  1002. case CODEC_ID_MACE3:
  1003. sc->samples_per_frame = 6;
  1004. sc->bytes_per_frame = 2*st->codec->channels;
  1005. break;
  1006. case CODEC_ID_MACE6:
  1007. sc->samples_per_frame = 6;
  1008. sc->bytes_per_frame = 1*st->codec->channels;
  1009. break;
  1010. case CODEC_ID_ADPCM_IMA_QT:
  1011. sc->samples_per_frame = 64;
  1012. sc->bytes_per_frame = 34*st->codec->channels;
  1013. break;
  1014. case CODEC_ID_GSM:
  1015. sc->samples_per_frame = 160;
  1016. sc->bytes_per_frame = 33;
  1017. break;
  1018. default:
  1019. break;
  1020. }
  1021. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1022. if (bits_per_sample) {
  1023. st->codec->bits_per_coded_sample = bits_per_sample;
  1024. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1025. }
  1026. } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1027. // ttxt stsd contains display flags, justification, background
  1028. // color, fonts, and default styles, so fake an atom to read it
  1029. MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
  1030. if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
  1031. mov_read_glbl(c, pb, fake_atom);
  1032. st->codec->codec_id= id;
  1033. st->codec->width = sc->width;
  1034. st->codec->height = sc->height;
  1035. } else {
  1036. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  1037. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  1038. }
  1039. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  1040. a.size = size - (avio_tell(pb) - start_pos);
  1041. if (a.size > 8) {
  1042. if (mov_read_default(c, pb, a) < 0)
  1043. return -1;
  1044. } else if (a.size > 0)
  1045. avio_skip(pb, a.size);
  1046. }
  1047. if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  1048. st->codec->sample_rate= sc->time_scale;
  1049. /* special codec parameters handling */
  1050. switch (st->codec->codec_id) {
  1051. #if CONFIG_DV_DEMUXER
  1052. case CODEC_ID_DVAUDIO:
  1053. c->dv_fctx = avformat_alloc_context();
  1054. c->dv_demux = dv_init_demux(c->dv_fctx);
  1055. if (!c->dv_demux) {
  1056. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1057. return -1;
  1058. }
  1059. sc->dv_audio_container = 1;
  1060. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  1061. break;
  1062. #endif
  1063. /* no ifdef since parameters are always those */
  1064. case CODEC_ID_QCELP:
  1065. // force sample rate for qcelp when not stored in mov
  1066. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1067. st->codec->sample_rate = 8000;
  1068. st->codec->frame_size= 160;
  1069. st->codec->channels= 1; /* really needed */
  1070. break;
  1071. case CODEC_ID_AMR_NB:
  1072. case CODEC_ID_AMR_WB:
  1073. st->codec->frame_size= sc->samples_per_frame;
  1074. st->codec->channels= 1; /* really needed */
  1075. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1076. if (st->codec->codec_id == CODEC_ID_AMR_NB)
  1077. st->codec->sample_rate = 8000;
  1078. else if (st->codec->codec_id == CODEC_ID_AMR_WB)
  1079. st->codec->sample_rate = 16000;
  1080. break;
  1081. case CODEC_ID_MP2:
  1082. case CODEC_ID_MP3:
  1083. st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  1084. st->need_parsing = AVSTREAM_PARSE_FULL;
  1085. break;
  1086. case CODEC_ID_GSM:
  1087. case CODEC_ID_ADPCM_MS:
  1088. case CODEC_ID_ADPCM_IMA_WAV:
  1089. st->codec->frame_size = sc->samples_per_frame;
  1090. st->codec->block_align = sc->bytes_per_frame;
  1091. break;
  1092. case CODEC_ID_ALAC:
  1093. if (st->codec->extradata_size == 36) {
  1094. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  1095. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1096. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1097. }
  1098. break;
  1099. default:
  1100. break;
  1101. }
  1102. return 0;
  1103. }
  1104. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1105. {
  1106. int entries;
  1107. avio_r8(pb); /* version */
  1108. avio_rb24(pb); /* flags */
  1109. entries = avio_rb32(pb);
  1110. return ff_mov_read_stsd_entries(c, pb, entries);
  1111. }
  1112. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1113. {
  1114. AVStream *st;
  1115. MOVStreamContext *sc;
  1116. unsigned int i, entries;
  1117. if (c->fc->nb_streams < 1)
  1118. return 0;
  1119. st = c->fc->streams[c->fc->nb_streams-1];
  1120. sc = st->priv_data;
  1121. avio_r8(pb); /* version */
  1122. avio_rb24(pb); /* flags */
  1123. entries = avio_rb32(pb);
  1124. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1125. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1126. return -1;
  1127. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1128. if (!sc->stsc_data)
  1129. return AVERROR(ENOMEM);
  1130. sc->stsc_count = entries;
  1131. for(i=0; i<entries; i++) {
  1132. sc->stsc_data[i].first = avio_rb32(pb);
  1133. sc->stsc_data[i].count = avio_rb32(pb);
  1134. sc->stsc_data[i].id = avio_rb32(pb);
  1135. }
  1136. return 0;
  1137. }
  1138. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1139. {
  1140. AVStream *st;
  1141. MOVStreamContext *sc;
  1142. unsigned i, entries;
  1143. if (c->fc->nb_streams < 1)
  1144. return 0;
  1145. st = c->fc->streams[c->fc->nb_streams-1];
  1146. sc = st->priv_data;
  1147. avio_rb32(pb); // version + flags
  1148. entries = avio_rb32(pb);
  1149. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1150. return -1;
  1151. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1152. if (!sc->stps_data)
  1153. return AVERROR(ENOMEM);
  1154. sc->stps_count = entries;
  1155. for (i = 0; i < entries; i++) {
  1156. sc->stps_data[i] = avio_rb32(pb);
  1157. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1158. }
  1159. return 0;
  1160. }
  1161. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1162. {
  1163. AVStream *st;
  1164. MOVStreamContext *sc;
  1165. unsigned int i, entries;
  1166. if (c->fc->nb_streams < 1)
  1167. return 0;
  1168. st = c->fc->streams[c->fc->nb_streams-1];
  1169. sc = st->priv_data;
  1170. avio_r8(pb); /* version */
  1171. avio_rb24(pb); /* flags */
  1172. entries = avio_rb32(pb);
  1173. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1174. if(entries >= UINT_MAX / sizeof(int))
  1175. return -1;
  1176. sc->keyframes = av_malloc(entries * sizeof(int));
  1177. if (!sc->keyframes)
  1178. return AVERROR(ENOMEM);
  1179. sc->keyframe_count = entries;
  1180. for(i=0; i<entries; i++) {
  1181. sc->keyframes[i] = avio_rb32(pb);
  1182. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1183. }
  1184. return 0;
  1185. }
  1186. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1187. {
  1188. AVStream *st;
  1189. MOVStreamContext *sc;
  1190. unsigned int i, entries, sample_size, field_size, num_bytes;
  1191. GetBitContext gb;
  1192. unsigned char* buf;
  1193. if (c->fc->nb_streams < 1)
  1194. return 0;
  1195. st = c->fc->streams[c->fc->nb_streams-1];
  1196. sc = st->priv_data;
  1197. avio_r8(pb); /* version */
  1198. avio_rb24(pb); /* flags */
  1199. if (atom.type == MKTAG('s','t','s','z')) {
  1200. sample_size = avio_rb32(pb);
  1201. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1202. sc->sample_size = sample_size;
  1203. field_size = 32;
  1204. } else {
  1205. sample_size = 0;
  1206. avio_rb24(pb); /* reserved */
  1207. field_size = avio_r8(pb);
  1208. }
  1209. entries = avio_rb32(pb);
  1210. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1211. sc->sample_count = entries;
  1212. if (sample_size)
  1213. return 0;
  1214. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1215. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1216. return -1;
  1217. }
  1218. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1219. return -1;
  1220. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1221. if (!sc->sample_sizes)
  1222. return AVERROR(ENOMEM);
  1223. num_bytes = (entries*field_size+4)>>3;
  1224. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1225. if (!buf) {
  1226. av_freep(&sc->sample_sizes);
  1227. return AVERROR(ENOMEM);
  1228. }
  1229. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1230. av_freep(&sc->sample_sizes);
  1231. av_free(buf);
  1232. return -1;
  1233. }
  1234. init_get_bits(&gb, buf, 8*num_bytes);
  1235. for(i=0; i<entries; i++)
  1236. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1237. av_free(buf);
  1238. return 0;
  1239. }
  1240. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1241. {
  1242. AVStream *st;
  1243. MOVStreamContext *sc;
  1244. unsigned int i, entries;
  1245. int64_t duration=0;
  1246. int64_t total_sample_count=0;
  1247. if (c->fc->nb_streams < 1)
  1248. return 0;
  1249. st = c->fc->streams[c->fc->nb_streams-1];
  1250. sc = st->priv_data;
  1251. avio_r8(pb); /* version */
  1252. avio_rb24(pb); /* flags */
  1253. entries = avio_rb32(pb);
  1254. av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1255. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1256. return -1;
  1257. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1258. if (!sc->stts_data)
  1259. return AVERROR(ENOMEM);
  1260. sc->stts_count = entries;
  1261. for(i=0; i<entries; i++) {
  1262. int sample_duration;
  1263. int sample_count;
  1264. sample_count=avio_rb32(pb);
  1265. sample_duration = avio_rb32(pb);
  1266. sc->stts_data[i].count= sample_count;
  1267. sc->stts_data[i].duration= sample_duration;
  1268. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1269. duration+=(int64_t)sample_duration*sample_count;
  1270. total_sample_count+=sample_count;
  1271. }
  1272. st->nb_frames= total_sample_count;
  1273. if(duration)
  1274. st->duration= duration;
  1275. return 0;
  1276. }
  1277. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1278. {
  1279. AVStream *st;
  1280. MOVStreamContext *sc;
  1281. unsigned int i, entries;
  1282. if (c->fc->nb_streams < 1)
  1283. return 0;
  1284. st = c->fc->streams[c->fc->nb_streams-1];
  1285. sc = st->priv_data;
  1286. avio_r8(pb); /* version */
  1287. avio_rb24(pb); /* flags */
  1288. entries = avio_rb32(pb);
  1289. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1290. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1291. return -1;
  1292. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1293. if (!sc->ctts_data)
  1294. return AVERROR(ENOMEM);
  1295. sc->ctts_count = entries;
  1296. for(i=0; i<entries; i++) {
  1297. int count =avio_rb32(pb);
  1298. int duration =avio_rb32(pb);
  1299. sc->ctts_data[i].count = count;
  1300. sc->ctts_data[i].duration= duration;
  1301. if (duration < 0 && i+1<entries)
  1302. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1303. }
  1304. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1305. return 0;
  1306. }
  1307. static void mov_build_index(MOVContext *mov, AVStream *st)
  1308. {
  1309. MOVStreamContext *sc = st->priv_data;
  1310. int64_t current_offset;
  1311. int64_t current_dts = 0;
  1312. unsigned int stts_index = 0;
  1313. unsigned int stsc_index = 0;
  1314. unsigned int stss_index = 0;
  1315. unsigned int stps_index = 0;
  1316. unsigned int i, j;
  1317. uint64_t stream_size = 0;
  1318. /* adjust first dts according to edit list */
  1319. if (sc->time_offset && mov->time_scale > 0) {
  1320. if (sc->time_offset < 0)
  1321. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1322. current_dts = -sc->time_offset;
  1323. if (sc->ctts_data && sc->stts_data &&
  1324. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  1325. /* more than 16 frames delay, dts are likely wrong
  1326. this happens with files created by iMovie */
  1327. sc->wrong_dts = 1;
  1328. st->codec->has_b_frames = 1;
  1329. }
  1330. }
  1331. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1332. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1333. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1334. unsigned int current_sample = 0;
  1335. unsigned int stts_sample = 0;
  1336. unsigned int sample_size;
  1337. unsigned int distance = 0;
  1338. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1339. current_dts -= sc->dts_shift;
  1340. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
  1341. return;
  1342. st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
  1343. if (!st->index_entries)
  1344. return;
  1345. st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
  1346. for (i = 0; i < sc->chunk_count; i++) {
  1347. current_offset = sc->chunk_offsets[i];
  1348. while (stsc_index + 1 < sc->stsc_count &&
  1349. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1350. stsc_index++;
  1351. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1352. int keyframe = 0;
  1353. if (current_sample >= sc->sample_count) {
  1354. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1355. return;
  1356. }
  1357. if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
  1358. keyframe = 1;
  1359. if (stss_index + 1 < sc->keyframe_count)
  1360. stss_index++;
  1361. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1362. keyframe = 1;
  1363. if (stps_index + 1 < sc->stps_count)
  1364. stps_index++;
  1365. }
  1366. if (keyframe)
  1367. distance = 0;
  1368. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1369. if(sc->pseudo_stream_id == -1 ||
  1370. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1371. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1372. e->pos = current_offset;
  1373. e->timestamp = current_dts;
  1374. e->size = sample_size;
  1375. e->min_distance = distance;
  1376. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1377. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1378. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1379. current_offset, current_dts, sample_size, distance, keyframe);
  1380. }
  1381. current_offset += sample_size;
  1382. stream_size += sample_size;
  1383. current_dts += sc->stts_data[stts_index].duration;
  1384. distance++;
  1385. stts_sample++;
  1386. current_sample++;
  1387. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1388. stts_sample = 0;
  1389. stts_index++;
  1390. }
  1391. }
  1392. }
  1393. if (st->duration > 0)
  1394. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1395. } else {
  1396. unsigned chunk_samples, total = 0;
  1397. // compute total chunk count
  1398. for (i = 0; i < sc->stsc_count; i++) {
  1399. unsigned count, chunk_count;
  1400. chunk_samples = sc->stsc_data[i].count;
  1401. if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1402. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1403. return;
  1404. }
  1405. if (sc->samples_per_frame >= 160) { // gsm
  1406. count = chunk_samples / sc->samples_per_frame;
  1407. } else if (sc->samples_per_frame > 1) {
  1408. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1409. count = (chunk_samples+samples-1) / samples;
  1410. } else {
  1411. count = (chunk_samples+1023) / 1024;
  1412. }
  1413. if (i < sc->stsc_count - 1)
  1414. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1415. else
  1416. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1417. total += chunk_count * count;
  1418. }
  1419. av_dlog(mov->fc, "chunk count %d\n", total);
  1420. if (total >= UINT_MAX / sizeof(*st->index_entries))
  1421. return;
  1422. st->index_entries = av_malloc(total*sizeof(*st->index_entries));
  1423. if (!st->index_entries)
  1424. return;
  1425. st->index_entries_allocated_size = total*sizeof(*st->index_entries);
  1426. // populate index
  1427. for (i = 0; i < sc->chunk_count; i++) {
  1428. current_offset = sc->chunk_offsets[i];
  1429. if (stsc_index + 1 < sc->stsc_count &&
  1430. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1431. stsc_index++;
  1432. chunk_samples = sc->stsc_data[stsc_index].count;
  1433. while (chunk_samples > 0) {
  1434. AVIndexEntry *e;
  1435. unsigned size, samples;
  1436. if (sc->samples_per_frame >= 160) { // gsm
  1437. samples = sc->samples_per_frame;
  1438. size = sc->bytes_per_frame;
  1439. } else {
  1440. if (sc->samples_per_frame > 1) {
  1441. samples = FFMIN((1024 / sc->samples_per_frame)*
  1442. sc->samples_per_frame, chunk_samples);
  1443. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1444. } else {
  1445. samples = FFMIN(1024, chunk_samples);
  1446. size = samples * sc->sample_size;
  1447. }
  1448. }
  1449. if (st->nb_index_entries >= total) {
  1450. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1451. return;
  1452. }
  1453. e = &st->index_entries[st->nb_index_entries++];
  1454. e->pos = current_offset;
  1455. e->timestamp = current_dts;
  1456. e->size = size;
  1457. e->min_distance = 0;
  1458. e->flags = AVINDEX_KEYFRAME;
  1459. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1460. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1461. size, samples);
  1462. current_offset += size;
  1463. current_dts += samples;
  1464. chunk_samples -= samples;
  1465. }
  1466. }
  1467. }
  1468. }
  1469. static int mov_open_dref(AVIOContext **pb, const char *src, MOVDref *ref)
  1470. {
  1471. /* try relative path, we do not try the absolute because it can leak information about our
  1472. system to an attacker */
  1473. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1474. char filename[1024];
  1475. const char *src_path;
  1476. int i, l;
  1477. /* find a source dir */
  1478. src_path = strrchr(src, '/');
  1479. if (src_path)
  1480. src_path++;
  1481. else
  1482. src_path = src;
  1483. /* find a next level down to target */
  1484. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1485. if (ref->path[l] == '/') {
  1486. if (i == ref->nlvl_to - 1)
  1487. break;
  1488. else
  1489. i++;
  1490. }
  1491. /* compose filename if next level down to target was found */
  1492. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1493. memcpy(filename, src, src_path - src);
  1494. filename[src_path - src] = 0;
  1495. for (i = 1; i < ref->nlvl_from; i++)
  1496. av_strlcat(filename, "../", 1024);
  1497. av_strlcat(filename, ref->path + l + 1, 1024);
  1498. if (!avio_open(pb, filename, AVIO_FLAG_READ))
  1499. return 0;
  1500. }
  1501. }
  1502. return AVERROR(ENOENT);
  1503. }
  1504. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1505. {
  1506. AVStream *st;
  1507. MOVStreamContext *sc;
  1508. int ret;
  1509. st = av_new_stream(c->fc, c->fc->nb_streams);
  1510. if (!st) return AVERROR(ENOMEM);
  1511. sc = av_mallocz(sizeof(MOVStreamContext));
  1512. if (!sc) return AVERROR(ENOMEM);
  1513. st->priv_data = sc;
  1514. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1515. sc->ffindex = st->index;
  1516. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1517. return ret;
  1518. /* sanity checks */
  1519. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1520. (!sc->sample_size && !sc->sample_count))) {
  1521. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1522. st->index);
  1523. return 0;
  1524. }
  1525. if (sc->time_scale <= 0) {
  1526. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1527. sc->time_scale = c->time_scale;
  1528. if (sc->time_scale <= 0)
  1529. sc->time_scale = 1;
  1530. }
  1531. av_set_pts_info(st, 64, 1, sc->time_scale);
  1532. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1533. !st->codec->frame_size && sc->stts_count == 1) {
  1534. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1535. st->codec->sample_rate, sc->time_scale);
  1536. av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
  1537. }
  1538. mov_build_index(c, st);
  1539. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1540. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1541. if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
  1542. av_log(c->fc, AV_LOG_ERROR,
  1543. "stream %d, error opening alias: path='%s', dir='%s', "
  1544. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1545. st->index, dref->path, dref->dir, dref->filename,
  1546. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1547. } else
  1548. sc->pb = c->fc->pb;
  1549. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1550. if (!st->sample_aspect_ratio.num &&
  1551. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1552. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1553. ((double)st->codec->width * sc->height), INT_MAX);
  1554. }
  1555. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1556. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1557. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  1558. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  1559. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  1560. }
  1561. switch (st->codec->codec_id) {
  1562. #if CONFIG_H261_DECODER
  1563. case CODEC_ID_H261:
  1564. #endif
  1565. #if CONFIG_H263_DECODER
  1566. case CODEC_ID_H263:
  1567. #endif
  1568. #if CONFIG_H264_DECODER
  1569. case CODEC_ID_H264:
  1570. #endif
  1571. #if CONFIG_MPEG4_DECODER
  1572. case CODEC_ID_MPEG4:
  1573. #endif
  1574. st->codec->width = 0; /* let decoder init width/height */
  1575. st->codec->height= 0;
  1576. break;
  1577. }
  1578. /* Do not need those anymore. */
  1579. av_freep(&sc->chunk_offsets);
  1580. av_freep(&sc->stsc_data);
  1581. av_freep(&sc->sample_sizes);
  1582. av_freep(&sc->keyframes);
  1583. av_freep(&sc->stts_data);
  1584. av_freep(&sc->stps_data);
  1585. return 0;
  1586. }
  1587. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1588. {
  1589. int ret;
  1590. c->itunes_metadata = 1;
  1591. ret = mov_read_default(c, pb, atom);
  1592. c->itunes_metadata = 0;
  1593. return ret;
  1594. }
  1595. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1596. {
  1597. while (atom.size > 8) {
  1598. uint32_t tag = avio_rl32(pb);
  1599. atom.size -= 4;
  1600. if (tag == MKTAG('h','d','l','r')) {
  1601. avio_seek(pb, -8, SEEK_CUR);
  1602. atom.size += 8;
  1603. return mov_read_default(c, pb, atom);
  1604. }
  1605. }
  1606. return 0;
  1607. }
  1608. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1609. {
  1610. int i;
  1611. int width;
  1612. int height;
  1613. int64_t disp_transform[2];
  1614. int display_matrix[3][2];
  1615. AVStream *st;
  1616. MOVStreamContext *sc;
  1617. int version;
  1618. if (c->fc->nb_streams < 1)
  1619. return 0;
  1620. st = c->fc->streams[c->fc->nb_streams-1];
  1621. sc = st->priv_data;
  1622. version = avio_r8(pb);
  1623. avio_rb24(pb); /* flags */
  1624. /*
  1625. MOV_TRACK_ENABLED 0x0001
  1626. MOV_TRACK_IN_MOVIE 0x0002
  1627. MOV_TRACK_IN_PREVIEW 0x0004
  1628. MOV_TRACK_IN_POSTER 0x0008
  1629. */
  1630. if (version == 1) {
  1631. avio_rb64(pb);
  1632. avio_rb64(pb);
  1633. } else {
  1634. avio_rb32(pb); /* creation time */
  1635. avio_rb32(pb); /* modification time */
  1636. }
  1637. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  1638. avio_rb32(pb); /* reserved */
  1639. /* highlevel (considering edits) duration in movie timebase */
  1640. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  1641. avio_rb32(pb); /* reserved */
  1642. avio_rb32(pb); /* reserved */
  1643. avio_rb16(pb); /* layer */
  1644. avio_rb16(pb); /* alternate group */
  1645. avio_rb16(pb); /* volume */
  1646. avio_rb16(pb); /* reserved */
  1647. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1648. // they're kept in fixed point format through all calculations
  1649. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1650. for (i = 0; i < 3; i++) {
  1651. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1652. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1653. avio_rb32(pb); // 2.30 fixed point (not used)
  1654. }
  1655. width = avio_rb32(pb); // 16.16 fixed point track width
  1656. height = avio_rb32(pb); // 16.16 fixed point track height
  1657. sc->width = width >> 16;
  1658. sc->height = height >> 16;
  1659. if (display_matrix[0][0] == -65536 && display_matrix[1][1] == -65536) {
  1660. av_dict_set(&st->metadata, "rotate", "180", 0);
  1661. }
  1662. // transform the display width/height according to the matrix
  1663. // skip this if the display matrix is the default identity matrix
  1664. // or if it is rotating the picture, ex iPhone 3GS
  1665. // to keep the same scale, use [width height 1<<16]
  1666. if (width && height &&
  1667. ((display_matrix[0][0] != 65536 ||
  1668. display_matrix[1][1] != 65536) &&
  1669. !display_matrix[0][1] &&
  1670. !display_matrix[1][0] &&
  1671. !display_matrix[2][0] && !display_matrix[2][1])) {
  1672. for (i = 0; i < 2; i++)
  1673. disp_transform[i] =
  1674. (int64_t) width * display_matrix[0][i] +
  1675. (int64_t) height * display_matrix[1][i] +
  1676. ((int64_t) display_matrix[2][i] << 16);
  1677. //sample aspect ratio is new width/height divided by old width/height
  1678. st->sample_aspect_ratio = av_d2q(
  1679. ((double) disp_transform[0] * height) /
  1680. ((double) disp_transform[1] * width), INT_MAX);
  1681. }
  1682. return 0;
  1683. }
  1684. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1685. {
  1686. MOVFragment *frag = &c->fragment;
  1687. MOVTrackExt *trex = NULL;
  1688. int flags, track_id, i;
  1689. avio_r8(pb); /* version */
  1690. flags = avio_rb24(pb);
  1691. track_id = avio_rb32(pb);
  1692. if (!track_id)
  1693. return -1;
  1694. frag->track_id = track_id;
  1695. for (i = 0; i < c->trex_count; i++)
  1696. if (c->trex_data[i].track_id == frag->track_id) {
  1697. trex = &c->trex_data[i];
  1698. break;
  1699. }
  1700. if (!trex) {
  1701. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1702. return -1;
  1703. }
  1704. if (flags & 0x01) frag->base_data_offset = avio_rb64(pb);
  1705. else frag->base_data_offset = frag->moof_offset;
  1706. if (flags & 0x02) frag->stsd_id = avio_rb32(pb);
  1707. else frag->stsd_id = trex->stsd_id;
  1708. frag->duration = flags & 0x08 ? avio_rb32(pb) : trex->duration;
  1709. frag->size = flags & 0x10 ? avio_rb32(pb) : trex->size;
  1710. frag->flags = flags & 0x20 ? avio_rb32(pb) : trex->flags;
  1711. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  1712. return 0;
  1713. }
  1714. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1715. {
  1716. c->chapter_track = avio_rb32(pb);
  1717. return 0;
  1718. }
  1719. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1720. {
  1721. MOVTrackExt *trex;
  1722. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1723. return -1;
  1724. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1725. if (!trex)
  1726. return AVERROR(ENOMEM);
  1727. c->trex_data = trex;
  1728. trex = &c->trex_data[c->trex_count++];
  1729. avio_r8(pb); /* version */
  1730. avio_rb24(pb); /* flags */
  1731. trex->track_id = avio_rb32(pb);
  1732. trex->stsd_id = avio_rb32(pb);
  1733. trex->duration = avio_rb32(pb);
  1734. trex->size = avio_rb32(pb);
  1735. trex->flags = avio_rb32(pb);
  1736. return 0;
  1737. }
  1738. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1739. {
  1740. MOVFragment *frag = &c->fragment;
  1741. AVStream *st = NULL;
  1742. MOVStreamContext *sc;
  1743. MOVStts *ctts_data;
  1744. uint64_t offset;
  1745. int64_t dts;
  1746. int data_offset = 0;
  1747. unsigned entries, first_sample_flags = frag->flags;
  1748. int flags, distance, i;
  1749. for (i = 0; i < c->fc->nb_streams; i++) {
  1750. if (c->fc->streams[i]->id == frag->track_id) {
  1751. st = c->fc->streams[i];
  1752. break;
  1753. }
  1754. }
  1755. if (!st) {
  1756. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1757. return -1;
  1758. }
  1759. sc = st->priv_data;
  1760. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1761. return 0;
  1762. avio_r8(pb); /* version */
  1763. flags = avio_rb24(pb);
  1764. entries = avio_rb32(pb);
  1765. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1766. /* Always assume the presence of composition time offsets.
  1767. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  1768. * 1) in the initial movie, there are no samples.
  1769. * 2) in the first movie fragment, there is only one sample without composition time offset.
  1770. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  1771. if (!sc->ctts_count && sc->sample_count)
  1772. {
  1773. /* Complement ctts table if moov atom doesn't have ctts atom. */
  1774. ctts_data = av_malloc(sizeof(*sc->ctts_data));
  1775. if (!ctts_data)
  1776. return AVERROR(ENOMEM);
  1777. sc->ctts_data = ctts_data;
  1778. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  1779. sc->ctts_data[sc->ctts_count].duration = 0;
  1780. sc->ctts_count++;
  1781. }
  1782. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1783. return -1;
  1784. ctts_data = av_realloc(sc->ctts_data,
  1785. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1786. if (!ctts_data)
  1787. return AVERROR(ENOMEM);
  1788. sc->ctts_data = ctts_data;
  1789. if (flags & 0x001) data_offset = avio_rb32(pb);
  1790. if (flags & 0x004) first_sample_flags = avio_rb32(pb);
  1791. dts = st->duration - sc->time_offset;
  1792. offset = frag->base_data_offset + data_offset;
  1793. distance = 0;
  1794. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1795. for (i = 0; i < entries; i++) {
  1796. unsigned sample_size = frag->size;
  1797. int sample_flags = i ? frag->flags : first_sample_flags;
  1798. unsigned sample_duration = frag->duration;
  1799. int keyframe;
  1800. if (flags & 0x100) sample_duration = avio_rb32(pb);
  1801. if (flags & 0x200) sample_size = avio_rb32(pb);
  1802. if (flags & 0x400) sample_flags = avio_rb32(pb);
  1803. sc->ctts_data[sc->ctts_count].count = 1;
  1804. sc->ctts_data[sc->ctts_count].duration = (flags & 0x800) ? avio_rb32(pb) : 0;
  1805. sc->ctts_count++;
  1806. if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
  1807. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1808. distance = 0;
  1809. av_add_index_entry(st, offset, dts, sample_size, distance,
  1810. keyframe ? AVINDEX_KEYFRAME : 0);
  1811. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1812. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1813. offset, dts, sample_size, distance, keyframe);
  1814. distance++;
  1815. dts += sample_duration;
  1816. offset += sample_size;
  1817. }
  1818. frag->moof_offset = offset;
  1819. st->duration = dts + sc->time_offset;
  1820. return 0;
  1821. }
  1822. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1823. /* like the files created with Adobe Premiere 5.0, for samples see */
  1824. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1825. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1826. {
  1827. int err;
  1828. if (atom.size < 8)
  1829. return 0; /* continue */
  1830. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1831. avio_skip(pb, atom.size - 4);
  1832. return 0;
  1833. }
  1834. atom.type = avio_rl32(pb);
  1835. atom.size -= 8;
  1836. if (atom.type != MKTAG('m','d','a','t')) {
  1837. avio_skip(pb, atom.size);
  1838. return 0;
  1839. }
  1840. err = mov_read_mdat(c, pb, atom);
  1841. return err;
  1842. }
  1843. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1844. {
  1845. #if CONFIG_ZLIB
  1846. AVIOContext ctx;
  1847. uint8_t *cmov_data;
  1848. uint8_t *moov_data; /* uncompressed data */
  1849. long cmov_len, moov_len;
  1850. int ret = -1;
  1851. avio_rb32(pb); /* dcom atom */
  1852. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  1853. return -1;
  1854. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  1855. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1856. return -1;
  1857. }
  1858. avio_rb32(pb); /* cmvd atom */
  1859. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  1860. return -1;
  1861. moov_len = avio_rb32(pb); /* uncompressed size */
  1862. cmov_len = atom.size - 6 * 4;
  1863. cmov_data = av_malloc(cmov_len);
  1864. if (!cmov_data)
  1865. return AVERROR(ENOMEM);
  1866. moov_data = av_malloc(moov_len);
  1867. if (!moov_data) {
  1868. av_free(cmov_data);
  1869. return AVERROR(ENOMEM);
  1870. }
  1871. avio_read(pb, cmov_data, cmov_len);
  1872. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1873. goto free_and_return;
  1874. if(ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1875. goto free_and_return;
  1876. atom.type = MKTAG('m','o','o','v');
  1877. atom.size = moov_len;
  1878. ret = mov_read_default(c, &ctx, atom);
  1879. free_and_return:
  1880. av_free(moov_data);
  1881. av_free(cmov_data);
  1882. return ret;
  1883. #else
  1884. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1885. return -1;
  1886. #endif
  1887. }
  1888. /* edit list atom */
  1889. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1890. {
  1891. MOVStreamContext *sc;
  1892. int i, edit_count, version;
  1893. if (c->fc->nb_streams < 1)
  1894. return 0;
  1895. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1896. version = avio_r8(pb); /* version */
  1897. avio_rb24(pb); /* flags */
  1898. edit_count = avio_rb32(pb); /* entries */
  1899. if((uint64_t)edit_count*12+8 > atom.size)
  1900. return -1;
  1901. for(i=0; i<edit_count; i++){
  1902. int64_t time;
  1903. int64_t duration;
  1904. if (version == 1) {
  1905. duration = avio_rb64(pb);
  1906. time = avio_rb64(pb);
  1907. } else {
  1908. duration = avio_rb32(pb); /* segment duration */
  1909. time = avio_rb32(pb); /* media time */
  1910. }
  1911. avio_rb32(pb); /* Media rate */
  1912. if (i == 0 && time >= -1) {
  1913. sc->time_offset = time != -1 ? time : -duration;
  1914. }
  1915. }
  1916. if(edit_count > 1)
  1917. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1918. "a/v desync might occur, patch welcome\n");
  1919. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1920. return 0;
  1921. }
  1922. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1923. {
  1924. if (atom.size < 16)
  1925. return AVERROR_INVALIDDATA;
  1926. avio_skip(pb, 4);
  1927. ff_mov_read_chan(c->fc, atom.size - 4, c->fc->streams[0]->codec);
  1928. return 0;
  1929. }
  1930. static const MOVParseTableEntry mov_default_parse_table[] = {
  1931. { MKTAG('a','v','s','s'), mov_read_extradata },
  1932. { MKTAG('c','h','p','l'), mov_read_chpl },
  1933. { MKTAG('c','o','6','4'), mov_read_stco },
  1934. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1935. { MKTAG('d','i','n','f'), mov_read_default },
  1936. { MKTAG('d','r','e','f'), mov_read_dref },
  1937. { MKTAG('e','d','t','s'), mov_read_default },
  1938. { MKTAG('e','l','s','t'), mov_read_elst },
  1939. { MKTAG('e','n','d','a'), mov_read_enda },
  1940. { MKTAG('f','i','e','l'), mov_read_extradata },
  1941. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1942. { MKTAG('g','l','b','l'), mov_read_glbl },
  1943. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1944. { MKTAG('i','l','s','t'), mov_read_ilst },
  1945. { MKTAG('j','p','2','h'), mov_read_extradata },
  1946. { MKTAG('m','d','a','t'), mov_read_mdat },
  1947. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1948. { MKTAG('m','d','i','a'), mov_read_default },
  1949. { MKTAG('m','e','t','a'), mov_read_meta },
  1950. { MKTAG('m','i','n','f'), mov_read_default },
  1951. { MKTAG('m','o','o','f'), mov_read_moof },
  1952. { MKTAG('m','o','o','v'), mov_read_moov },
  1953. { MKTAG('m','v','e','x'), mov_read_default },
  1954. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1955. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1956. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1957. { MKTAG('a','v','c','C'), mov_read_glbl },
  1958. { MKTAG('p','a','s','p'), mov_read_pasp },
  1959. { MKTAG('s','t','b','l'), mov_read_default },
  1960. { MKTAG('s','t','c','o'), mov_read_stco },
  1961. { MKTAG('s','t','p','s'), mov_read_stps },
  1962. { MKTAG('s','t','r','f'), mov_read_strf },
  1963. { MKTAG('s','t','s','c'), mov_read_stsc },
  1964. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1965. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1966. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1967. { MKTAG('s','t','t','s'), mov_read_stts },
  1968. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  1969. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1970. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1971. { MKTAG('t','r','a','k'), mov_read_trak },
  1972. { MKTAG('t','r','a','f'), mov_read_default },
  1973. { MKTAG('t','r','e','f'), mov_read_default },
  1974. { MKTAG('c','h','a','p'), mov_read_chap },
  1975. { MKTAG('t','r','e','x'), mov_read_trex },
  1976. { MKTAG('t','r','u','n'), mov_read_trun },
  1977. { MKTAG('u','d','t','a'), mov_read_default },
  1978. { MKTAG('w','a','v','e'), mov_read_wave },
  1979. { MKTAG('e','s','d','s'), mov_read_esds },
  1980. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  1981. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1982. { MKTAG('w','f','e','x'), mov_read_wfex },
  1983. { MKTAG('c','m','o','v'), mov_read_cmov },
  1984. { MKTAG('c','h','a','n'), mov_read_chan },
  1985. { 0, NULL }
  1986. };
  1987. static int mov_probe(AVProbeData *p)
  1988. {
  1989. unsigned int offset;
  1990. uint32_t tag;
  1991. int score = 0;
  1992. /* check file header */
  1993. offset = 0;
  1994. for(;;) {
  1995. /* ignore invalid offset */
  1996. if ((offset + 8) > (unsigned int)p->buf_size)
  1997. return score;
  1998. tag = AV_RL32(p->buf + offset + 4);
  1999. switch(tag) {
  2000. /* check for obvious tags */
  2001. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2002. case MKTAG('m','o','o','v'):
  2003. case MKTAG('m','d','a','t'):
  2004. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2005. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2006. case MKTAG('f','t','y','p'):
  2007. return AVPROBE_SCORE_MAX;
  2008. /* those are more common words, so rate then a bit less */
  2009. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2010. case MKTAG('w','i','d','e'):
  2011. case MKTAG('f','r','e','e'):
  2012. case MKTAG('j','u','n','k'):
  2013. case MKTAG('p','i','c','t'):
  2014. return AVPROBE_SCORE_MAX - 5;
  2015. case MKTAG(0x82,0x82,0x7f,0x7d):
  2016. case MKTAG('s','k','i','p'):
  2017. case MKTAG('u','u','i','d'):
  2018. case MKTAG('p','r','f','l'):
  2019. offset = AV_RB32(p->buf+offset) + offset;
  2020. /* if we only find those cause probedata is too small at least rate them */
  2021. score = AVPROBE_SCORE_MAX - 50;
  2022. break;
  2023. default:
  2024. /* unrecognized tag */
  2025. return score;
  2026. }
  2027. }
  2028. return score;
  2029. }
  2030. // must be done after parsing all trak because there's no order requirement
  2031. static void mov_read_chapters(AVFormatContext *s)
  2032. {
  2033. MOVContext *mov = s->priv_data;
  2034. AVStream *st = NULL;
  2035. MOVStreamContext *sc;
  2036. int64_t cur_pos;
  2037. int i;
  2038. for (i = 0; i < s->nb_streams; i++)
  2039. if (s->streams[i]->id == mov->chapter_track) {
  2040. st = s->streams[i];
  2041. break;
  2042. }
  2043. if (!st) {
  2044. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2045. return;
  2046. }
  2047. st->discard = AVDISCARD_ALL;
  2048. sc = st->priv_data;
  2049. cur_pos = avio_tell(sc->pb);
  2050. for (i = 0; i < st->nb_index_entries; i++) {
  2051. AVIndexEntry *sample = &st->index_entries[i];
  2052. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2053. uint8_t *title;
  2054. uint16_t ch;
  2055. int len, title_len;
  2056. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2057. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2058. goto finish;
  2059. }
  2060. // the first two bytes are the length of the title
  2061. len = avio_rb16(sc->pb);
  2062. if (len > sample->size-2)
  2063. continue;
  2064. title_len = 2*len + 1;
  2065. if (!(title = av_mallocz(title_len)))
  2066. goto finish;
  2067. // The samples could theoretically be in any encoding if there's an encd
  2068. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2069. // instead by the presence of a BOM
  2070. ch = avio_rb16(sc->pb);
  2071. if (ch == 0xfeff)
  2072. avio_get_str16be(sc->pb, len, title, title_len);
  2073. else if (ch == 0xfffe)
  2074. avio_get_str16le(sc->pb, len, title, title_len);
  2075. else {
  2076. AV_WB16(title, ch);
  2077. get_strz(sc->pb, title + 2, len - 1);
  2078. }
  2079. ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2080. av_freep(&title);
  2081. }
  2082. finish:
  2083. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2084. }
  2085. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  2086. {
  2087. MOVContext *mov = s->priv_data;
  2088. AVIOContext *pb = s->pb;
  2089. int err;
  2090. MOVAtom atom = { AV_RL32("root") };
  2091. mov->fc = s;
  2092. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2093. if(pb->seekable)
  2094. atom.size = avio_size(pb);
  2095. else
  2096. atom.size = INT64_MAX;
  2097. /* check MOV header */
  2098. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2099. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2100. return err;
  2101. }
  2102. if (!mov->found_moov) {
  2103. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2104. return -1;
  2105. }
  2106. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2107. if (pb->seekable && mov->chapter_track > 0)
  2108. mov_read_chapters(s);
  2109. return 0;
  2110. }
  2111. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2112. {
  2113. AVIndexEntry *sample = NULL;
  2114. int64_t best_dts = INT64_MAX;
  2115. int i;
  2116. for (i = 0; i < s->nb_streams; i++) {
  2117. AVStream *avst = s->streams[i];
  2118. MOVStreamContext *msc = avst->priv_data;
  2119. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2120. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2121. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2122. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2123. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2124. (s->pb->seekable &&
  2125. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2126. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2127. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2128. sample = current_sample;
  2129. best_dts = dts;
  2130. *st = avst;
  2131. }
  2132. }
  2133. }
  2134. return sample;
  2135. }
  2136. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2137. {
  2138. MOVContext *mov = s->priv_data;
  2139. MOVStreamContext *sc;
  2140. AVIndexEntry *sample;
  2141. AVStream *st = NULL;
  2142. int ret;
  2143. retry:
  2144. sample = mov_find_next_sample(s, &st);
  2145. if (!sample) {
  2146. mov->found_mdat = 0;
  2147. if (s->pb->seekable||
  2148. mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2149. url_feof(s->pb))
  2150. return AVERROR_EOF;
  2151. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  2152. goto retry;
  2153. }
  2154. sc = st->priv_data;
  2155. /* must be done just before reading, to avoid infinite loop on sample */
  2156. sc->current_sample++;
  2157. if (st->discard != AVDISCARD_ALL) {
  2158. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2159. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2160. sc->ffindex, sample->pos);
  2161. return -1;
  2162. }
  2163. ret = av_get_packet(sc->pb, pkt, sample->size);
  2164. if (ret < 0)
  2165. return ret;
  2166. if (sc->has_palette) {
  2167. uint8_t *pal;
  2168. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  2169. if (!pal) {
  2170. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  2171. } else {
  2172. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  2173. sc->has_palette = 0;
  2174. }
  2175. }
  2176. #if CONFIG_DV_DEMUXER
  2177. if (mov->dv_demux && sc->dv_audio_container) {
  2178. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  2179. av_free(pkt->data);
  2180. pkt->size = 0;
  2181. ret = dv_get_packet(mov->dv_demux, pkt);
  2182. if (ret < 0)
  2183. return ret;
  2184. }
  2185. #endif
  2186. }
  2187. pkt->stream_index = sc->ffindex;
  2188. pkt->dts = sample->timestamp;
  2189. if (sc->ctts_data) {
  2190. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2191. /* update ctts context */
  2192. sc->ctts_sample++;
  2193. if (sc->ctts_index < sc->ctts_count &&
  2194. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2195. sc->ctts_index++;
  2196. sc->ctts_sample = 0;
  2197. }
  2198. if (sc->wrong_dts)
  2199. pkt->dts = AV_NOPTS_VALUE;
  2200. } else {
  2201. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2202. st->index_entries[sc->current_sample].timestamp : st->duration;
  2203. pkt->duration = next_dts - pkt->dts;
  2204. pkt->pts = pkt->dts;
  2205. }
  2206. if (st->discard == AVDISCARD_ALL)
  2207. goto retry;
  2208. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2209. pkt->pos = sample->pos;
  2210. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2211. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2212. return 0;
  2213. }
  2214. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2215. {
  2216. MOVStreamContext *sc = st->priv_data;
  2217. int sample, time_sample;
  2218. int i;
  2219. sample = av_index_search_timestamp(st, timestamp, flags);
  2220. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2221. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2222. sample = 0;
  2223. if (sample < 0) /* not sure what to do */
  2224. return -1;
  2225. sc->current_sample = sample;
  2226. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2227. /* adjust ctts index */
  2228. if (sc->ctts_data) {
  2229. time_sample = 0;
  2230. for (i = 0; i < sc->ctts_count; i++) {
  2231. int next = time_sample + sc->ctts_data[i].count;
  2232. if (next > sc->current_sample) {
  2233. sc->ctts_index = i;
  2234. sc->ctts_sample = sc->current_sample - time_sample;
  2235. break;
  2236. }
  2237. time_sample = next;
  2238. }
  2239. }
  2240. return sample;
  2241. }
  2242. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2243. {
  2244. AVStream *st;
  2245. int64_t seek_timestamp, timestamp;
  2246. int sample;
  2247. int i;
  2248. if (stream_index >= s->nb_streams)
  2249. return -1;
  2250. if (sample_time < 0)
  2251. sample_time = 0;
  2252. st = s->streams[stream_index];
  2253. sample = mov_seek_stream(s, st, sample_time, flags);
  2254. if (sample < 0)
  2255. return -1;
  2256. /* adjust seek timestamp to found sample timestamp */
  2257. seek_timestamp = st->index_entries[sample].timestamp;
  2258. for (i = 0; i < s->nb_streams; i++) {
  2259. st = s->streams[i];
  2260. if (stream_index == i)
  2261. continue;
  2262. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2263. mov_seek_stream(s, st, timestamp, flags);
  2264. }
  2265. return 0;
  2266. }
  2267. static int mov_read_close(AVFormatContext *s)
  2268. {
  2269. MOVContext *mov = s->priv_data;
  2270. int i, j;
  2271. for (i = 0; i < s->nb_streams; i++) {
  2272. AVStream *st = s->streams[i];
  2273. MOVStreamContext *sc = st->priv_data;
  2274. av_freep(&sc->ctts_data);
  2275. for (j = 0; j < sc->drefs_count; j++) {
  2276. av_freep(&sc->drefs[j].path);
  2277. av_freep(&sc->drefs[j].dir);
  2278. }
  2279. av_freep(&sc->drefs);
  2280. if (sc->pb && sc->pb != s->pb)
  2281. avio_close(sc->pb);
  2282. av_freep(&st->codec->palctrl);
  2283. }
  2284. if (mov->dv_demux) {
  2285. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2286. av_freep(&mov->dv_fctx->streams[i]->codec);
  2287. av_freep(&mov->dv_fctx->streams[i]);
  2288. }
  2289. av_freep(&mov->dv_fctx);
  2290. av_freep(&mov->dv_demux);
  2291. }
  2292. av_freep(&mov->trex_data);
  2293. return 0;
  2294. }
  2295. AVInputFormat ff_mov_demuxer = {
  2296. "mov,mp4,m4a,3gp,3g2,mj2",
  2297. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  2298. sizeof(MOVContext),
  2299. mov_probe,
  2300. mov_read_header,
  2301. mov_read_packet,
  2302. mov_read_close,
  2303. mov_read_seek,
  2304. };