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.

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