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.

2819 lines
94KB

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