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.

3001 lines
101KB

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