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.

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