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.

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