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.

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