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.

3032 lines
102KB

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