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.

2692 lines
90KB

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