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.

3049 lines
103KB

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