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.

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