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.

2983 lines
99KB

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