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.

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