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.

2657 lines
89KB

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