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.

3034 lines
102KB

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