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.

2981 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->fc, "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. /* Flash Media Server uses tag H263 with Sorenson Spark */
  998. if (format == MKTAG('H','2','6','3') &&
  999. !memcmp(st->codec->codec_name, "Sorenson H263", 13))
  1000. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1001. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1002. color_table_id = avio_rb16(pb); /* colortable id */
  1003. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1004. st->codec->bits_per_coded_sample, color_table_id);
  1005. /* figure out the palette situation */
  1006. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1007. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1008. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1009. if ((color_depth == 2) || (color_depth == 4) ||
  1010. (color_depth == 8)) {
  1011. /* for palette traversal */
  1012. unsigned int color_start, color_count, color_end;
  1013. unsigned char r, g, b;
  1014. if (color_greyscale) {
  1015. int color_index, color_dec;
  1016. /* compute the greyscale palette */
  1017. st->codec->bits_per_coded_sample = color_depth;
  1018. color_count = 1 << color_depth;
  1019. color_index = 255;
  1020. color_dec = 256 / (color_count - 1);
  1021. for (j = 0; j < color_count; j++) {
  1022. r = g = b = color_index;
  1023. sc->palette[j] =
  1024. (r << 16) | (g << 8) | (b);
  1025. color_index -= color_dec;
  1026. if (color_index < 0)
  1027. color_index = 0;
  1028. }
  1029. } else if (color_table_id) {
  1030. const uint8_t *color_table;
  1031. /* if flag bit 3 is set, use the default palette */
  1032. color_count = 1 << color_depth;
  1033. if (color_depth == 2)
  1034. color_table = ff_qt_default_palette_4;
  1035. else if (color_depth == 4)
  1036. color_table = ff_qt_default_palette_16;
  1037. else
  1038. color_table = ff_qt_default_palette_256;
  1039. for (j = 0; j < color_count; j++) {
  1040. r = color_table[j * 3 + 0];
  1041. g = color_table[j * 3 + 1];
  1042. b = color_table[j * 3 + 2];
  1043. sc->palette[j] =
  1044. (r << 16) | (g << 8) | (b);
  1045. }
  1046. } else {
  1047. /* load the palette from the file */
  1048. color_start = avio_rb32(pb);
  1049. color_count = avio_rb16(pb);
  1050. color_end = avio_rb16(pb);
  1051. if ((color_start <= 255) &&
  1052. (color_end <= 255)) {
  1053. for (j = color_start; j <= color_end; j++) {
  1054. /* each R, G, or B component is 16 bits;
  1055. * only use the top 8 bits; skip alpha bytes
  1056. * up front */
  1057. avio_r8(pb);
  1058. avio_r8(pb);
  1059. r = avio_r8(pb);
  1060. avio_r8(pb);
  1061. g = avio_r8(pb);
  1062. avio_r8(pb);
  1063. b = avio_r8(pb);
  1064. avio_r8(pb);
  1065. sc->palette[j] =
  1066. (r << 16) | (g << 8) | (b);
  1067. }
  1068. }
  1069. }
  1070. sc->has_palette = 1;
  1071. }
  1072. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1073. int bits_per_sample, flags;
  1074. uint16_t version = avio_rb16(pb);
  1075. st->codec->codec_id = id;
  1076. avio_rb16(pb); /* revision level */
  1077. avio_rb32(pb); /* vendor */
  1078. st->codec->channels = avio_rb16(pb); /* channel count */
  1079. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1080. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1081. sc->audio_cid = avio_rb16(pb);
  1082. avio_rb16(pb); /* packet size = 0 */
  1083. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1084. //Read QT version 1 fields. In version 0 these do not exist.
  1085. av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);
  1086. if (!c->isom) {
  1087. if (version==1) {
  1088. sc->samples_per_frame = avio_rb32(pb);
  1089. avio_rb32(pb); /* bytes per packet */
  1090. sc->bytes_per_frame = avio_rb32(pb);
  1091. avio_rb32(pb); /* bytes per sample */
  1092. } else if (version==2) {
  1093. avio_rb32(pb); /* sizeof struct only */
  1094. st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */
  1095. st->codec->channels = avio_rb32(pb);
  1096. avio_rb32(pb); /* always 0x7F000000 */
  1097. st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */
  1098. flags = avio_rb32(pb); /* lpcm format specific flag */
  1099. sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */
  1100. sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */
  1101. if (format == MKTAG('l','p','c','m'))
  1102. st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  1103. }
  1104. }
  1105. switch (st->codec->codec_id) {
  1106. case AV_CODEC_ID_PCM_S8:
  1107. case AV_CODEC_ID_PCM_U8:
  1108. if (st->codec->bits_per_coded_sample == 16)
  1109. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1110. break;
  1111. case AV_CODEC_ID_PCM_S16LE:
  1112. case AV_CODEC_ID_PCM_S16BE:
  1113. if (st->codec->bits_per_coded_sample == 8)
  1114. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1115. else if (st->codec->bits_per_coded_sample == 24)
  1116. st->codec->codec_id =
  1117. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1118. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1119. break;
  1120. /* set values for old format before stsd version 1 appeared */
  1121. case AV_CODEC_ID_MACE3:
  1122. sc->samples_per_frame = 6;
  1123. sc->bytes_per_frame = 2*st->codec->channels;
  1124. break;
  1125. case AV_CODEC_ID_MACE6:
  1126. sc->samples_per_frame = 6;
  1127. sc->bytes_per_frame = 1*st->codec->channels;
  1128. break;
  1129. case AV_CODEC_ID_ADPCM_IMA_QT:
  1130. sc->samples_per_frame = 64;
  1131. sc->bytes_per_frame = 34*st->codec->channels;
  1132. break;
  1133. case AV_CODEC_ID_GSM:
  1134. sc->samples_per_frame = 160;
  1135. sc->bytes_per_frame = 33;
  1136. break;
  1137. default:
  1138. break;
  1139. }
  1140. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1141. if (bits_per_sample) {
  1142. st->codec->bits_per_coded_sample = bits_per_sample;
  1143. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1144. }
  1145. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1146. // ttxt stsd contains display flags, justification, background
  1147. // color, fonts, and default styles, so fake an atom to read it
  1148. MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };
  1149. if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
  1150. mov_read_glbl(c, pb, fake_atom);
  1151. st->codec->codec_id= id;
  1152. st->codec->width = sc->width;
  1153. st->codec->height = sc->height;
  1154. } else {
  1155. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  1156. avio_skip(pb, size - (avio_tell(pb) - start_pos));
  1157. }
  1158. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  1159. a.size = size - (avio_tell(pb) - start_pos);
  1160. if (a.size > 8) {
  1161. int ret;
  1162. if ((ret = mov_read_default(c, pb, a)) < 0)
  1163. return ret;
  1164. } else if (a.size > 0)
  1165. avio_skip(pb, a.size);
  1166. }
  1167. if (pb->eof_reached)
  1168. return AVERROR_EOF;
  1169. if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  1170. st->codec->sample_rate= sc->time_scale;
  1171. /* special codec parameters handling */
  1172. switch (st->codec->codec_id) {
  1173. #if CONFIG_DV_DEMUXER
  1174. case AV_CODEC_ID_DVAUDIO:
  1175. c->dv_fctx = avformat_alloc_context();
  1176. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1177. if (!c->dv_demux) {
  1178. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1179. return AVERROR(ENOMEM);
  1180. }
  1181. sc->dv_audio_container = 1;
  1182. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1183. break;
  1184. #endif
  1185. /* no ifdef since parameters are always those */
  1186. case AV_CODEC_ID_QCELP:
  1187. // force sample rate for qcelp when not stored in mov
  1188. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1189. st->codec->sample_rate = 8000;
  1190. st->codec->channels= 1; /* really needed */
  1191. break;
  1192. case AV_CODEC_ID_AMR_NB:
  1193. st->codec->channels= 1; /* really needed */
  1194. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1195. st->codec->sample_rate = 8000;
  1196. break;
  1197. case AV_CODEC_ID_AMR_WB:
  1198. st->codec->channels = 1;
  1199. st->codec->sample_rate = 16000;
  1200. break;
  1201. case AV_CODEC_ID_MP2:
  1202. case AV_CODEC_ID_MP3:
  1203. st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  1204. st->need_parsing = AVSTREAM_PARSE_FULL;
  1205. break;
  1206. case AV_CODEC_ID_GSM:
  1207. case AV_CODEC_ID_ADPCM_MS:
  1208. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1209. case AV_CODEC_ID_ILBC:
  1210. st->codec->block_align = sc->bytes_per_frame;
  1211. break;
  1212. case AV_CODEC_ID_ALAC:
  1213. if (st->codec->extradata_size == 36) {
  1214. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1215. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1216. }
  1217. break;
  1218. case AV_CODEC_ID_VC1:
  1219. st->need_parsing = AVSTREAM_PARSE_FULL;
  1220. break;
  1221. default:
  1222. break;
  1223. }
  1224. return 0;
  1225. }
  1226. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1227. {
  1228. int entries;
  1229. avio_r8(pb); /* version */
  1230. avio_rb24(pb); /* flags */
  1231. entries = avio_rb32(pb);
  1232. return ff_mov_read_stsd_entries(c, pb, entries);
  1233. }
  1234. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1235. {
  1236. AVStream *st;
  1237. MOVStreamContext *sc;
  1238. unsigned int i, entries;
  1239. if (c->fc->nb_streams < 1)
  1240. return 0;
  1241. st = c->fc->streams[c->fc->nb_streams-1];
  1242. sc = st->priv_data;
  1243. avio_r8(pb); /* version */
  1244. avio_rb24(pb); /* flags */
  1245. entries = avio_rb32(pb);
  1246. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1247. if (!entries)
  1248. return 0;
  1249. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1250. return AVERROR_INVALIDDATA;
  1251. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1252. if (!sc->stsc_data)
  1253. return AVERROR(ENOMEM);
  1254. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1255. sc->stsc_data[i].first = avio_rb32(pb);
  1256. sc->stsc_data[i].count = avio_rb32(pb);
  1257. sc->stsc_data[i].id = avio_rb32(pb);
  1258. }
  1259. sc->stsc_count = i;
  1260. if (pb->eof_reached)
  1261. return AVERROR_EOF;
  1262. return 0;
  1263. }
  1264. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1265. {
  1266. AVStream *st;
  1267. MOVStreamContext *sc;
  1268. unsigned i, entries;
  1269. if (c->fc->nb_streams < 1)
  1270. return 0;
  1271. st = c->fc->streams[c->fc->nb_streams-1];
  1272. sc = st->priv_data;
  1273. avio_rb32(pb); // version + flags
  1274. entries = avio_rb32(pb);
  1275. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1276. return AVERROR_INVALIDDATA;
  1277. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1278. if (!sc->stps_data)
  1279. return AVERROR(ENOMEM);
  1280. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1281. sc->stps_data[i] = avio_rb32(pb);
  1282. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1283. }
  1284. sc->stps_count = i;
  1285. if (pb->eof_reached)
  1286. return AVERROR_EOF;
  1287. return 0;
  1288. }
  1289. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1290. {
  1291. AVStream *st;
  1292. MOVStreamContext *sc;
  1293. unsigned int i, entries;
  1294. if (c->fc->nb_streams < 1)
  1295. return 0;
  1296. st = c->fc->streams[c->fc->nb_streams-1];
  1297. sc = st->priv_data;
  1298. avio_r8(pb); /* version */
  1299. avio_rb24(pb); /* flags */
  1300. entries = avio_rb32(pb);
  1301. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1302. if (!entries)
  1303. {
  1304. sc->keyframe_absent = 1;
  1305. return 0;
  1306. }
  1307. if (entries >= UINT_MAX / sizeof(int))
  1308. return AVERROR_INVALIDDATA;
  1309. sc->keyframes = av_malloc(entries * sizeof(int));
  1310. if (!sc->keyframes)
  1311. return AVERROR(ENOMEM);
  1312. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1313. sc->keyframes[i] = avio_rb32(pb);
  1314. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1315. }
  1316. sc->keyframe_count = i;
  1317. if (pb->eof_reached)
  1318. return AVERROR_EOF;
  1319. return 0;
  1320. }
  1321. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1322. {
  1323. AVStream *st;
  1324. MOVStreamContext *sc;
  1325. unsigned int i, entries, sample_size, field_size, num_bytes;
  1326. GetBitContext gb;
  1327. unsigned char* buf;
  1328. if (c->fc->nb_streams < 1)
  1329. return 0;
  1330. st = c->fc->streams[c->fc->nb_streams-1];
  1331. sc = st->priv_data;
  1332. avio_r8(pb); /* version */
  1333. avio_rb24(pb); /* flags */
  1334. if (atom.type == MKTAG('s','t','s','z')) {
  1335. sample_size = avio_rb32(pb);
  1336. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1337. sc->sample_size = sample_size;
  1338. field_size = 32;
  1339. } else {
  1340. sample_size = 0;
  1341. avio_rb24(pb); /* reserved */
  1342. field_size = avio_r8(pb);
  1343. }
  1344. entries = avio_rb32(pb);
  1345. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1346. sc->sample_count = entries;
  1347. if (sample_size)
  1348. return 0;
  1349. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1350. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1351. return AVERROR_INVALIDDATA;
  1352. }
  1353. if (!entries)
  1354. return 0;
  1355. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1356. return AVERROR_INVALIDDATA;
  1357. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1358. if (!sc->sample_sizes)
  1359. return AVERROR(ENOMEM);
  1360. num_bytes = (entries*field_size+4)>>3;
  1361. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1362. if (!buf) {
  1363. av_freep(&sc->sample_sizes);
  1364. return AVERROR(ENOMEM);
  1365. }
  1366. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1367. av_freep(&sc->sample_sizes);
  1368. av_free(buf);
  1369. return AVERROR_INVALIDDATA;
  1370. }
  1371. init_get_bits(&gb, buf, 8*num_bytes);
  1372. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1373. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1374. sc->data_size += sc->sample_sizes[i];
  1375. }
  1376. sc->sample_count = i;
  1377. if (pb->eof_reached)
  1378. return AVERROR_EOF;
  1379. av_free(buf);
  1380. return 0;
  1381. }
  1382. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1383. {
  1384. AVStream *st;
  1385. MOVStreamContext *sc;
  1386. unsigned int i, entries;
  1387. int64_t duration=0;
  1388. int64_t total_sample_count=0;
  1389. if (c->fc->nb_streams < 1)
  1390. return 0;
  1391. st = c->fc->streams[c->fc->nb_streams-1];
  1392. sc = st->priv_data;
  1393. avio_r8(pb); /* version */
  1394. avio_rb24(pb); /* flags */
  1395. entries = avio_rb32(pb);
  1396. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1397. c->fc->nb_streams-1, entries);
  1398. if (!entries)
  1399. return 0;
  1400. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1401. return AVERROR(EINVAL);
  1402. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1403. if (!sc->stts_data)
  1404. return AVERROR(ENOMEM);
  1405. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1406. int sample_duration;
  1407. int sample_count;
  1408. sample_count=avio_rb32(pb);
  1409. sample_duration = avio_rb32(pb);
  1410. sc->stts_data[i].count= sample_count;
  1411. sc->stts_data[i].duration= sample_duration;
  1412. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1413. sample_count, sample_duration);
  1414. duration+=(int64_t)sample_duration*sample_count;
  1415. total_sample_count+=sample_count;
  1416. }
  1417. sc->stts_count = i;
  1418. if (pb->eof_reached)
  1419. return AVERROR_EOF;
  1420. st->nb_frames= total_sample_count;
  1421. if (duration)
  1422. st->duration= duration;
  1423. sc->track_end = duration;
  1424. return 0;
  1425. }
  1426. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1427. {
  1428. AVStream *st;
  1429. MOVStreamContext *sc;
  1430. unsigned int i, entries;
  1431. if (c->fc->nb_streams < 1)
  1432. return 0;
  1433. st = c->fc->streams[c->fc->nb_streams-1];
  1434. sc = st->priv_data;
  1435. avio_r8(pb); /* version */
  1436. avio_rb24(pb); /* flags */
  1437. entries = avio_rb32(pb);
  1438. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1439. if (!entries)
  1440. return 0;
  1441. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1442. return AVERROR_INVALIDDATA;
  1443. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1444. if (!sc->ctts_data)
  1445. return AVERROR(ENOMEM);
  1446. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1447. int count =avio_rb32(pb);
  1448. int duration =avio_rb32(pb);
  1449. sc->ctts_data[i].count = count;
  1450. sc->ctts_data[i].duration= duration;
  1451. if (duration < 0)
  1452. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1453. }
  1454. sc->ctts_count = i;
  1455. if (pb->eof_reached)
  1456. return AVERROR_EOF;
  1457. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1458. return 0;
  1459. }
  1460. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1461. {
  1462. AVStream *st;
  1463. MOVStreamContext *sc;
  1464. unsigned int i, entries;
  1465. uint8_t version;
  1466. uint32_t grouping_type;
  1467. if (c->fc->nb_streams < 1)
  1468. return 0;
  1469. st = c->fc->streams[c->fc->nb_streams-1];
  1470. sc = st->priv_data;
  1471. version = avio_r8(pb); /* version */
  1472. avio_rb24(pb); /* flags */
  1473. grouping_type = avio_rl32(pb);
  1474. if (grouping_type != MKTAG( 'r','a','p',' '))
  1475. return 0; /* only support 'rap ' grouping */
  1476. if (version == 1)
  1477. avio_rb32(pb); /* grouping_type_parameter */
  1478. entries = avio_rb32(pb);
  1479. if (!entries)
  1480. return 0;
  1481. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1482. return AVERROR_INVALIDDATA;
  1483. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1484. if (!sc->rap_group)
  1485. return AVERROR(ENOMEM);
  1486. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1487. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1488. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1489. }
  1490. sc->rap_group_count = i;
  1491. return pb->eof_reached ? AVERROR_EOF : 0;
  1492. }
  1493. static void mov_build_index(MOVContext *mov, AVStream *st)
  1494. {
  1495. MOVStreamContext *sc = st->priv_data;
  1496. int64_t current_offset;
  1497. int64_t current_dts = 0;
  1498. unsigned int stts_index = 0;
  1499. unsigned int stsc_index = 0;
  1500. unsigned int stss_index = 0;
  1501. unsigned int stps_index = 0;
  1502. unsigned int i, j;
  1503. uint64_t stream_size = 0;
  1504. AVIndexEntry *mem;
  1505. /* adjust first dts according to edit list */
  1506. if (sc->time_offset && mov->time_scale > 0) {
  1507. if (sc->time_offset < 0)
  1508. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1509. current_dts = -sc->time_offset;
  1510. if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
  1511. sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1512. /* more than 16 frames delay, dts are likely wrong
  1513. this happens with files created by iMovie */
  1514. sc->wrong_dts = 1;
  1515. st->codec->has_b_frames = 1;
  1516. }
  1517. }
  1518. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1519. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1520. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1521. unsigned int current_sample = 0;
  1522. unsigned int stts_sample = 0;
  1523. unsigned int sample_size;
  1524. unsigned int distance = 0;
  1525. unsigned int rap_group_index = 0;
  1526. unsigned int rap_group_sample = 0;
  1527. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1528. int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
  1529. current_dts -= sc->dts_shift;
  1530. if (!sc->sample_count)
  1531. return;
  1532. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1533. return;
  1534. mem = av_realloc(st->index_entries, (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries));
  1535. if (!mem)
  1536. return;
  1537. st->index_entries = mem;
  1538. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1539. for (i = 0; i < sc->chunk_count; i++) {
  1540. current_offset = sc->chunk_offsets[i];
  1541. while (stsc_index + 1 < sc->stsc_count &&
  1542. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1543. stsc_index++;
  1544. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1545. int keyframe = 0;
  1546. if (current_sample >= sc->sample_count) {
  1547. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1548. return;
  1549. }
  1550. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1551. keyframe = 1;
  1552. if (stss_index + 1 < sc->keyframe_count)
  1553. stss_index++;
  1554. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1555. keyframe = 1;
  1556. if (stps_index + 1 < sc->stps_count)
  1557. stps_index++;
  1558. }
  1559. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1560. if (sc->rap_group[rap_group_index].index > 0)
  1561. keyframe = 1;
  1562. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1563. rap_group_sample = 0;
  1564. rap_group_index++;
  1565. }
  1566. }
  1567. if (keyframe)
  1568. distance = 0;
  1569. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1570. if (sc->pseudo_stream_id == -1 ||
  1571. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1572. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1573. e->pos = current_offset;
  1574. e->timestamp = current_dts;
  1575. e->size = sample_size;
  1576. e->min_distance = distance;
  1577. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1578. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1579. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1580. current_offset, current_dts, sample_size, distance, keyframe);
  1581. }
  1582. current_offset += sample_size;
  1583. stream_size += sample_size;
  1584. current_dts += sc->stts_data[stts_index].duration;
  1585. distance++;
  1586. stts_sample++;
  1587. current_sample++;
  1588. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1589. stts_sample = 0;
  1590. stts_index++;
  1591. }
  1592. }
  1593. }
  1594. if (st->duration > 0)
  1595. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1596. } else {
  1597. unsigned chunk_samples, total = 0;
  1598. // compute total chunk count
  1599. for (i = 0; i < sc->stsc_count; i++) {
  1600. unsigned count, chunk_count;
  1601. chunk_samples = sc->stsc_data[i].count;
  1602. if (i != sc->stsc_count - 1 &&
  1603. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1604. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1605. return;
  1606. }
  1607. if (sc->samples_per_frame >= 160) { // gsm
  1608. count = chunk_samples / sc->samples_per_frame;
  1609. } else if (sc->samples_per_frame > 1) {
  1610. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1611. count = (chunk_samples+samples-1) / samples;
  1612. } else {
  1613. count = (chunk_samples+1023) / 1024;
  1614. }
  1615. if (i < sc->stsc_count - 1)
  1616. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1617. else
  1618. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1619. total += chunk_count * count;
  1620. }
  1621. av_dlog(mov->fc, "chunk count %d\n", total);
  1622. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1623. return;
  1624. mem = av_realloc(st->index_entries, (st->nb_index_entries + total) * sizeof(*st->index_entries));
  1625. if (!mem)
  1626. return;
  1627. st->index_entries = mem;
  1628. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  1629. // populate index
  1630. for (i = 0; i < sc->chunk_count; i++) {
  1631. current_offset = sc->chunk_offsets[i];
  1632. if (stsc_index + 1 < sc->stsc_count &&
  1633. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1634. stsc_index++;
  1635. chunk_samples = sc->stsc_data[stsc_index].count;
  1636. while (chunk_samples > 0) {
  1637. AVIndexEntry *e;
  1638. unsigned size, samples;
  1639. if (sc->samples_per_frame >= 160) { // gsm
  1640. samples = sc->samples_per_frame;
  1641. size = sc->bytes_per_frame;
  1642. } else {
  1643. if (sc->samples_per_frame > 1) {
  1644. samples = FFMIN((1024 / sc->samples_per_frame)*
  1645. sc->samples_per_frame, chunk_samples);
  1646. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1647. } else {
  1648. samples = FFMIN(1024, chunk_samples);
  1649. size = samples * sc->sample_size;
  1650. }
  1651. }
  1652. if (st->nb_index_entries >= total) {
  1653. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1654. return;
  1655. }
  1656. e = &st->index_entries[st->nb_index_entries++];
  1657. e->pos = current_offset;
  1658. e->timestamp = current_dts;
  1659. e->size = size;
  1660. e->min_distance = 0;
  1661. e->flags = AVINDEX_KEYFRAME;
  1662. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1663. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1664. size, samples);
  1665. current_offset += size;
  1666. current_dts += samples;
  1667. chunk_samples -= samples;
  1668. }
  1669. }
  1670. }
  1671. }
  1672. static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
  1673. AVIOInterruptCB *int_cb)
  1674. {
  1675. /* try relative path, we do not try the absolute because it can leak information about our
  1676. system to an attacker */
  1677. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1678. char filename[1024];
  1679. char *src_path;
  1680. int i, l;
  1681. /* find a source dir */
  1682. src_path = strrchr(src, '/');
  1683. if (src_path)
  1684. src_path++;
  1685. else
  1686. src_path = src;
  1687. /* find a next level down to target */
  1688. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1689. if (ref->path[l] == '/') {
  1690. if (i == ref->nlvl_to - 1)
  1691. break;
  1692. else
  1693. i++;
  1694. }
  1695. /* compose filename if next level down to target was found */
  1696. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1697. memcpy(filename, src, src_path - src);
  1698. filename[src_path - src] = 0;
  1699. for (i = 1; i < ref->nlvl_from; i++)
  1700. av_strlcat(filename, "../", 1024);
  1701. av_strlcat(filename, ref->path + l + 1, 1024);
  1702. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  1703. return 0;
  1704. }
  1705. }
  1706. return AVERROR(ENOENT);
  1707. }
  1708. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1709. {
  1710. AVStream *st;
  1711. MOVStreamContext *sc;
  1712. int ret;
  1713. st = avformat_new_stream(c->fc, NULL);
  1714. if (!st) return AVERROR(ENOMEM);
  1715. st->id = c->fc->nb_streams;
  1716. sc = av_mallocz(sizeof(MOVStreamContext));
  1717. if (!sc) return AVERROR(ENOMEM);
  1718. st->priv_data = sc;
  1719. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1720. sc->ffindex = st->index;
  1721. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1722. return ret;
  1723. /* sanity checks */
  1724. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1725. (!sc->sample_size && !sc->sample_count))) {
  1726. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1727. st->index);
  1728. return 0;
  1729. }
  1730. if (sc->time_scale <= 0) {
  1731. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1732. sc->time_scale = c->time_scale;
  1733. if (sc->time_scale <= 0)
  1734. sc->time_scale = 1;
  1735. }
  1736. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  1737. mov_build_index(c, st);
  1738. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1739. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1740. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
  1741. av_log(c->fc, AV_LOG_ERROR,
  1742. "stream %d, error opening alias: path='%s', dir='%s', "
  1743. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1744. st->index, dref->path, dref->dir, dref->filename,
  1745. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1746. } else
  1747. sc->pb = c->fc->pb;
  1748. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1749. if (!st->sample_aspect_ratio.num &&
  1750. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1751. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1752. ((double)st->codec->width * sc->height), INT_MAX);
  1753. }
  1754. if (st->duration != AV_NOPTS_VALUE)
  1755. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1756. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1757. }
  1758. switch (st->codec->codec_id) {
  1759. #if CONFIG_H261_DECODER
  1760. case AV_CODEC_ID_H261:
  1761. #endif
  1762. #if CONFIG_H263_DECODER
  1763. case AV_CODEC_ID_H263:
  1764. #endif
  1765. #if CONFIG_MPEG4_DECODER
  1766. case AV_CODEC_ID_MPEG4:
  1767. #endif
  1768. st->codec->width = 0; /* let decoder init width/height */
  1769. st->codec->height= 0;
  1770. break;
  1771. }
  1772. /* Do not need those anymore. */
  1773. av_freep(&sc->chunk_offsets);
  1774. av_freep(&sc->stsc_data);
  1775. av_freep(&sc->sample_sizes);
  1776. av_freep(&sc->keyframes);
  1777. av_freep(&sc->stts_data);
  1778. av_freep(&sc->stps_data);
  1779. av_freep(&sc->rap_group);
  1780. return 0;
  1781. }
  1782. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1783. {
  1784. int ret;
  1785. c->itunes_metadata = 1;
  1786. ret = mov_read_default(c, pb, atom);
  1787. c->itunes_metadata = 0;
  1788. return ret;
  1789. }
  1790. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1791. {
  1792. while (atom.size > 8) {
  1793. uint32_t tag = avio_rl32(pb);
  1794. atom.size -= 4;
  1795. if (tag == MKTAG('h','d','l','r')) {
  1796. avio_seek(pb, -8, SEEK_CUR);
  1797. atom.size += 8;
  1798. return mov_read_default(c, pb, atom);
  1799. }
  1800. }
  1801. return 0;
  1802. }
  1803. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1804. {
  1805. int i;
  1806. int width;
  1807. int height;
  1808. int64_t disp_transform[2];
  1809. int display_matrix[3][2];
  1810. AVStream *st;
  1811. MOVStreamContext *sc;
  1812. int version;
  1813. if (c->fc->nb_streams < 1)
  1814. return 0;
  1815. st = c->fc->streams[c->fc->nb_streams-1];
  1816. sc = st->priv_data;
  1817. version = avio_r8(pb);
  1818. avio_rb24(pb); /* flags */
  1819. /*
  1820. MOV_TRACK_ENABLED 0x0001
  1821. MOV_TRACK_IN_MOVIE 0x0002
  1822. MOV_TRACK_IN_PREVIEW 0x0004
  1823. MOV_TRACK_IN_POSTER 0x0008
  1824. */
  1825. if (version == 1) {
  1826. avio_rb64(pb);
  1827. avio_rb64(pb);
  1828. } else {
  1829. avio_rb32(pb); /* creation time */
  1830. avio_rb32(pb); /* modification time */
  1831. }
  1832. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  1833. avio_rb32(pb); /* reserved */
  1834. /* highlevel (considering edits) duration in movie timebase */
  1835. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  1836. avio_rb32(pb); /* reserved */
  1837. avio_rb32(pb); /* reserved */
  1838. avio_rb16(pb); /* layer */
  1839. avio_rb16(pb); /* alternate group */
  1840. avio_rb16(pb); /* volume */
  1841. avio_rb16(pb); /* reserved */
  1842. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1843. // they're kept in fixed point format through all calculations
  1844. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1845. for (i = 0; i < 3; i++) {
  1846. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  1847. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  1848. avio_rb32(pb); // 2.30 fixed point (not used)
  1849. }
  1850. width = avio_rb32(pb); // 16.16 fixed point track width
  1851. height = avio_rb32(pb); // 16.16 fixed point track height
  1852. sc->width = width >> 16;
  1853. sc->height = height >> 16;
  1854. // transform the display width/height according to the matrix
  1855. // skip this if the display matrix is the default identity matrix
  1856. // or if it is rotating the picture, ex iPhone 3GS
  1857. // to keep the same scale, use [width height 1<<16]
  1858. if (width && height &&
  1859. ((display_matrix[0][0] != 65536 ||
  1860. display_matrix[1][1] != 65536) &&
  1861. !display_matrix[0][1] &&
  1862. !display_matrix[1][0] &&
  1863. !display_matrix[2][0] && !display_matrix[2][1])) {
  1864. for (i = 0; i < 2; i++)
  1865. disp_transform[i] =
  1866. (int64_t) width * display_matrix[0][i] +
  1867. (int64_t) height * display_matrix[1][i] +
  1868. ((int64_t) display_matrix[2][i] << 16);
  1869. //sample aspect ratio is new width/height divided by old width/height
  1870. st->sample_aspect_ratio = av_d2q(
  1871. ((double) disp_transform[0] * height) /
  1872. ((double) disp_transform[1] * width), INT_MAX);
  1873. }
  1874. return 0;
  1875. }
  1876. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1877. {
  1878. MOVFragment *frag = &c->fragment;
  1879. MOVTrackExt *trex = NULL;
  1880. int flags, track_id, i;
  1881. avio_r8(pb); /* version */
  1882. flags = avio_rb24(pb);
  1883. track_id = avio_rb32(pb);
  1884. if (!track_id)
  1885. return AVERROR_INVALIDDATA;
  1886. frag->track_id = track_id;
  1887. for (i = 0; i < c->trex_count; i++)
  1888. if (c->trex_data[i].track_id == frag->track_id) {
  1889. trex = &c->trex_data[i];
  1890. break;
  1891. }
  1892. if (!trex) {
  1893. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1894. return AVERROR_INVALIDDATA;
  1895. }
  1896. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  1897. avio_rb64(pb) : frag->moof_offset;
  1898. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  1899. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  1900. avio_rb32(pb) : trex->duration;
  1901. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  1902. avio_rb32(pb) : trex->size;
  1903. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  1904. avio_rb32(pb) : trex->flags;
  1905. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  1906. return 0;
  1907. }
  1908. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1909. {
  1910. c->chapter_track = avio_rb32(pb);
  1911. return 0;
  1912. }
  1913. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1914. {
  1915. MOVTrackExt *trex;
  1916. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1917. return AVERROR_INVALIDDATA;
  1918. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1919. if (!trex)
  1920. return AVERROR(ENOMEM);
  1921. c->trex_data = trex;
  1922. trex = &c->trex_data[c->trex_count++];
  1923. avio_r8(pb); /* version */
  1924. avio_rb24(pb); /* flags */
  1925. trex->track_id = avio_rb32(pb);
  1926. trex->stsd_id = avio_rb32(pb);
  1927. trex->duration = avio_rb32(pb);
  1928. trex->size = avio_rb32(pb);
  1929. trex->flags = avio_rb32(pb);
  1930. return 0;
  1931. }
  1932. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1933. {
  1934. MOVFragment *frag = &c->fragment;
  1935. AVStream *st = NULL;
  1936. MOVStreamContext *sc;
  1937. MOVStts *ctts_data;
  1938. uint64_t offset;
  1939. int64_t dts;
  1940. int data_offset = 0;
  1941. unsigned entries, first_sample_flags = frag->flags;
  1942. int flags, distance, i, found_keyframe = 0;
  1943. for (i = 0; i < c->fc->nb_streams; i++) {
  1944. if (c->fc->streams[i]->id == frag->track_id) {
  1945. st = c->fc->streams[i];
  1946. break;
  1947. }
  1948. }
  1949. if (!st) {
  1950. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1951. return AVERROR_INVALIDDATA;
  1952. }
  1953. sc = st->priv_data;
  1954. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1955. return 0;
  1956. avio_r8(pb); /* version */
  1957. flags = avio_rb24(pb);
  1958. entries = avio_rb32(pb);
  1959. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1960. /* Always assume the presence of composition time offsets.
  1961. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  1962. * 1) in the initial movie, there are no samples.
  1963. * 2) in the first movie fragment, there is only one sample without composition time offset.
  1964. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  1965. if (!sc->ctts_count && sc->sample_count)
  1966. {
  1967. /* Complement ctts table if moov atom doesn't have ctts atom. */
  1968. ctts_data = av_malloc(sizeof(*sc->ctts_data));
  1969. if (!ctts_data)
  1970. return AVERROR(ENOMEM);
  1971. sc->ctts_data = ctts_data;
  1972. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  1973. sc->ctts_data[sc->ctts_count].duration = 0;
  1974. sc->ctts_count++;
  1975. }
  1976. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1977. return AVERROR_INVALIDDATA;
  1978. ctts_data = av_realloc(sc->ctts_data,
  1979. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1980. if (!ctts_data)
  1981. return AVERROR(ENOMEM);
  1982. sc->ctts_data = ctts_data;
  1983. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  1984. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  1985. dts = sc->track_end - sc->time_offset;
  1986. offset = frag->base_data_offset + data_offset;
  1987. distance = 0;
  1988. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1989. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1990. unsigned sample_size = frag->size;
  1991. int sample_flags = i ? frag->flags : first_sample_flags;
  1992. unsigned sample_duration = frag->duration;
  1993. int keyframe = 0;
  1994. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  1995. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  1996. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  1997. sc->ctts_data[sc->ctts_count].count = 1;
  1998. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  1999. avio_rb32(pb) : 0;
  2000. sc->ctts_count++;
  2001. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2002. keyframe = 1;
  2003. else if (!found_keyframe)
  2004. keyframe = found_keyframe =
  2005. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2006. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2007. if (keyframe)
  2008. distance = 0;
  2009. av_add_index_entry(st, offset, dts, sample_size, distance,
  2010. keyframe ? AVINDEX_KEYFRAME : 0);
  2011. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2012. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2013. offset, dts, sample_size, distance, keyframe);
  2014. distance++;
  2015. dts += sample_duration;
  2016. offset += sample_size;
  2017. sc->data_size += sample_size;
  2018. }
  2019. if (pb->eof_reached)
  2020. return AVERROR_EOF;
  2021. frag->moof_offset = offset;
  2022. st->duration = sc->track_end = dts + sc->time_offset;
  2023. return 0;
  2024. }
  2025. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2026. /* like the files created with Adobe Premiere 5.0, for samples see */
  2027. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2028. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2029. {
  2030. int err;
  2031. if (atom.size < 8)
  2032. return 0; /* continue */
  2033. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2034. avio_skip(pb, atom.size - 4);
  2035. return 0;
  2036. }
  2037. atom.type = avio_rl32(pb);
  2038. atom.size -= 8;
  2039. if (atom.type != MKTAG('m','d','a','t')) {
  2040. avio_skip(pb, atom.size);
  2041. return 0;
  2042. }
  2043. err = mov_read_mdat(c, pb, atom);
  2044. return err;
  2045. }
  2046. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2047. {
  2048. #if CONFIG_ZLIB
  2049. AVIOContext ctx;
  2050. uint8_t *cmov_data;
  2051. uint8_t *moov_data; /* uncompressed data */
  2052. long cmov_len, moov_len;
  2053. int ret = -1;
  2054. avio_rb32(pb); /* dcom atom */
  2055. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2056. return AVERROR_INVALIDDATA;
  2057. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2058. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  2059. return AVERROR_INVALIDDATA;
  2060. }
  2061. avio_rb32(pb); /* cmvd atom */
  2062. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2063. return AVERROR_INVALIDDATA;
  2064. moov_len = avio_rb32(pb); /* uncompressed size */
  2065. cmov_len = atom.size - 6 * 4;
  2066. cmov_data = av_malloc(cmov_len);
  2067. if (!cmov_data)
  2068. return AVERROR(ENOMEM);
  2069. moov_data = av_malloc(moov_len);
  2070. if (!moov_data) {
  2071. av_free(cmov_data);
  2072. return AVERROR(ENOMEM);
  2073. }
  2074. avio_read(pb, cmov_data, cmov_len);
  2075. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2076. goto free_and_return;
  2077. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2078. goto free_and_return;
  2079. atom.type = MKTAG('m','o','o','v');
  2080. atom.size = moov_len;
  2081. ret = mov_read_default(c, &ctx, atom);
  2082. free_and_return:
  2083. av_free(moov_data);
  2084. av_free(cmov_data);
  2085. return ret;
  2086. #else
  2087. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2088. return AVERROR(ENOSYS);
  2089. #endif
  2090. }
  2091. /* edit list atom */
  2092. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2093. {
  2094. MOVStreamContext *sc;
  2095. int i, edit_count, version;
  2096. if (c->fc->nb_streams < 1)
  2097. return 0;
  2098. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2099. version = avio_r8(pb); /* version */
  2100. avio_rb24(pb); /* flags */
  2101. edit_count = avio_rb32(pb); /* entries */
  2102. if ((uint64_t)edit_count*12+8 > atom.size)
  2103. return AVERROR_INVALIDDATA;
  2104. for (i=0; i<edit_count; i++){
  2105. int64_t time;
  2106. int64_t duration;
  2107. if (version == 1) {
  2108. duration = avio_rb64(pb);
  2109. time = avio_rb64(pb);
  2110. } else {
  2111. duration = avio_rb32(pb); /* segment duration */
  2112. time = (int32_t)avio_rb32(pb); /* media time */
  2113. }
  2114. avio_rb32(pb); /* Media rate */
  2115. if (i == 0 && time >= -1) {
  2116. sc->time_offset = time != -1 ? time : -duration;
  2117. }
  2118. }
  2119. if (edit_count > 1)
  2120. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2121. "a/v desync might occur, patch welcome\n");
  2122. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2123. return 0;
  2124. }
  2125. static const MOVParseTableEntry mov_default_parse_table[] = {
  2126. { MKTAG('a','v','s','s'), mov_read_extradata },
  2127. { MKTAG('c','h','p','l'), mov_read_chpl },
  2128. { MKTAG('c','o','6','4'), mov_read_stco },
  2129. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2130. { MKTAG('d','i','n','f'), mov_read_default },
  2131. { MKTAG('d','r','e','f'), mov_read_dref },
  2132. { MKTAG('e','d','t','s'), mov_read_default },
  2133. { MKTAG('e','l','s','t'), mov_read_elst },
  2134. { MKTAG('e','n','d','a'), mov_read_enda },
  2135. { MKTAG('f','i','e','l'), mov_read_fiel },
  2136. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2137. { MKTAG('g','l','b','l'), mov_read_glbl },
  2138. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2139. { MKTAG('i','l','s','t'), mov_read_ilst },
  2140. { MKTAG('j','p','2','h'), mov_read_extradata },
  2141. { MKTAG('m','d','a','t'), mov_read_mdat },
  2142. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2143. { MKTAG('m','d','i','a'), mov_read_default },
  2144. { MKTAG('m','e','t','a'), mov_read_meta },
  2145. { MKTAG('m','i','n','f'), mov_read_default },
  2146. { MKTAG('m','o','o','f'), mov_read_moof },
  2147. { MKTAG('m','o','o','v'), mov_read_moov },
  2148. { MKTAG('m','v','e','x'), mov_read_default },
  2149. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2150. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  2151. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  2152. { MKTAG('a','v','c','C'), mov_read_glbl },
  2153. { MKTAG('p','a','s','p'), mov_read_pasp },
  2154. { MKTAG('s','t','b','l'), mov_read_default },
  2155. { MKTAG('s','t','c','o'), mov_read_stco },
  2156. { MKTAG('s','t','p','s'), mov_read_stps },
  2157. { MKTAG('s','t','r','f'), mov_read_strf },
  2158. { MKTAG('s','t','s','c'), mov_read_stsc },
  2159. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2160. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2161. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2162. { MKTAG('s','t','t','s'), mov_read_stts },
  2163. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2164. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2165. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2166. { MKTAG('t','r','a','k'), mov_read_trak },
  2167. { MKTAG('t','r','a','f'), mov_read_default },
  2168. { MKTAG('t','r','e','f'), mov_read_default },
  2169. { MKTAG('c','h','a','p'), mov_read_chap },
  2170. { MKTAG('t','r','e','x'), mov_read_trex },
  2171. { MKTAG('t','r','u','n'), mov_read_trun },
  2172. { MKTAG('u','d','t','a'), mov_read_default },
  2173. { MKTAG('w','a','v','e'), mov_read_wave },
  2174. { MKTAG('e','s','d','s'), mov_read_esds },
  2175. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2176. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2177. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2178. { MKTAG('w','f','e','x'), mov_read_wfex },
  2179. { MKTAG('c','m','o','v'), mov_read_cmov },
  2180. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2181. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2182. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2183. { 0, NULL }
  2184. };
  2185. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2186. {
  2187. int64_t total_size = 0;
  2188. MOVAtom a;
  2189. int i;
  2190. if (atom.size < 0)
  2191. atom.size = INT64_MAX;
  2192. while (total_size + 8 < atom.size && !pb->eof_reached) {
  2193. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2194. a.size = atom.size;
  2195. a.type=0;
  2196. if (atom.size >= 8) {
  2197. a.size = avio_rb32(pb);
  2198. a.type = avio_rl32(pb);
  2199. }
  2200. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2201. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2202. total_size += 8;
  2203. if (a.size == 1) { /* 64 bit extended size */
  2204. a.size = avio_rb64(pb) - 8;
  2205. total_size += 8;
  2206. }
  2207. if (a.size == 0) {
  2208. a.size = atom.size - total_size;
  2209. if (a.size <= 8)
  2210. break;
  2211. }
  2212. a.size -= 8;
  2213. if (a.size < 0)
  2214. break;
  2215. a.size = FFMIN(a.size, atom.size - total_size);
  2216. for (i = 0; mov_default_parse_table[i].type; i++)
  2217. if (mov_default_parse_table[i].type == a.type) {
  2218. parse = mov_default_parse_table[i].parse;
  2219. break;
  2220. }
  2221. // container is user data
  2222. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2223. atom.type == MKTAG('i','l','s','t')))
  2224. parse = mov_read_udta_string;
  2225. if (!parse) { /* skip leaf atoms data */
  2226. avio_skip(pb, a.size);
  2227. } else {
  2228. int64_t start_pos = avio_tell(pb);
  2229. int64_t left;
  2230. int err = parse(c, pb, a);
  2231. if (err < 0)
  2232. return err;
  2233. if (c->found_moov && c->found_mdat &&
  2234. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2235. start_pos + a.size == avio_size(pb))) {
  2236. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2237. c->next_root_atom = start_pos + a.size;
  2238. return 0;
  2239. }
  2240. left = a.size - avio_tell(pb) + start_pos;
  2241. if (left > 0) /* skip garbage at atom end */
  2242. avio_skip(pb, left);
  2243. }
  2244. total_size += a.size;
  2245. }
  2246. if (total_size < atom.size && atom.size < 0x7ffff)
  2247. avio_skip(pb, atom.size - total_size);
  2248. return 0;
  2249. }
  2250. static int mov_probe(AVProbeData *p)
  2251. {
  2252. unsigned int offset;
  2253. uint32_t tag;
  2254. int score = 0;
  2255. /* check file header */
  2256. offset = 0;
  2257. for (;;) {
  2258. /* ignore invalid offset */
  2259. if ((offset + 8) > (unsigned int)p->buf_size)
  2260. return score;
  2261. tag = AV_RL32(p->buf + offset + 4);
  2262. switch(tag) {
  2263. /* check for obvious tags */
  2264. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2265. case MKTAG('m','o','o','v'):
  2266. case MKTAG('m','d','a','t'):
  2267. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2268. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2269. case MKTAG('f','t','y','p'):
  2270. return AVPROBE_SCORE_MAX;
  2271. /* those are more common words, so rate then a bit less */
  2272. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2273. case MKTAG('w','i','d','e'):
  2274. case MKTAG('f','r','e','e'):
  2275. case MKTAG('j','u','n','k'):
  2276. case MKTAG('p','i','c','t'):
  2277. return AVPROBE_SCORE_MAX - 5;
  2278. case MKTAG(0x82,0x82,0x7f,0x7d):
  2279. case MKTAG('s','k','i','p'):
  2280. case MKTAG('u','u','i','d'):
  2281. case MKTAG('p','r','f','l'):
  2282. offset = AV_RB32(p->buf+offset) + offset;
  2283. /* if we only find those cause probedata is too small at least rate them */
  2284. score = AVPROBE_SCORE_MAX - 50;
  2285. break;
  2286. default:
  2287. /* unrecognized tag */
  2288. return score;
  2289. }
  2290. }
  2291. }
  2292. // must be done after parsing all trak because there's no order requirement
  2293. static void mov_read_chapters(AVFormatContext *s)
  2294. {
  2295. MOVContext *mov = s->priv_data;
  2296. AVStream *st = NULL;
  2297. MOVStreamContext *sc;
  2298. int64_t cur_pos;
  2299. int i;
  2300. for (i = 0; i < s->nb_streams; i++)
  2301. if (s->streams[i]->id == mov->chapter_track) {
  2302. st = s->streams[i];
  2303. break;
  2304. }
  2305. if (!st) {
  2306. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2307. return;
  2308. }
  2309. st->discard = AVDISCARD_ALL;
  2310. sc = st->priv_data;
  2311. cur_pos = avio_tell(sc->pb);
  2312. for (i = 0; i < st->nb_index_entries; i++) {
  2313. AVIndexEntry *sample = &st->index_entries[i];
  2314. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2315. uint8_t *title;
  2316. uint16_t ch;
  2317. int len, title_len;
  2318. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2319. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2320. goto finish;
  2321. }
  2322. // the first two bytes are the length of the title
  2323. len = avio_rb16(sc->pb);
  2324. if (len > sample->size-2)
  2325. continue;
  2326. title_len = 2*len + 1;
  2327. if (!(title = av_mallocz(title_len)))
  2328. goto finish;
  2329. // The samples could theoretically be in any encoding if there's an encd
  2330. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2331. // instead by the presence of a BOM
  2332. if (!len) {
  2333. title[0] = 0;
  2334. } else {
  2335. ch = avio_rb16(sc->pb);
  2336. if (ch == 0xfeff)
  2337. avio_get_str16be(sc->pb, len, title, title_len);
  2338. else if (ch == 0xfffe)
  2339. avio_get_str16le(sc->pb, len, title, title_len);
  2340. else {
  2341. AV_WB16(title, ch);
  2342. if (len == 1 || len == 2)
  2343. title[len] = 0;
  2344. else
  2345. avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
  2346. }
  2347. }
  2348. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2349. av_freep(&title);
  2350. }
  2351. finish:
  2352. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2353. }
  2354. static int mov_read_close(AVFormatContext *s)
  2355. {
  2356. MOVContext *mov = s->priv_data;
  2357. int i, j;
  2358. for (i = 0; i < s->nb_streams; i++) {
  2359. AVStream *st = s->streams[i];
  2360. MOVStreamContext *sc = st->priv_data;
  2361. av_freep(&sc->ctts_data);
  2362. for (j = 0; j < sc->drefs_count; j++) {
  2363. av_freep(&sc->drefs[j].path);
  2364. av_freep(&sc->drefs[j].dir);
  2365. }
  2366. av_freep(&sc->drefs);
  2367. if (sc->pb && sc->pb != s->pb)
  2368. avio_close(sc->pb);
  2369. }
  2370. if (mov->dv_demux) {
  2371. for (i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2372. av_freep(&mov->dv_fctx->streams[i]->codec);
  2373. av_freep(&mov->dv_fctx->streams[i]);
  2374. }
  2375. av_freep(&mov->dv_fctx);
  2376. av_freep(&mov->dv_demux);
  2377. }
  2378. av_freep(&mov->trex_data);
  2379. return 0;
  2380. }
  2381. static int mov_read_header(AVFormatContext *s)
  2382. {
  2383. MOVContext *mov = s->priv_data;
  2384. AVIOContext *pb = s->pb;
  2385. int err;
  2386. MOVAtom atom = { AV_RL32("root") };
  2387. mov->fc = s;
  2388. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2389. if (pb->seekable)
  2390. atom.size = avio_size(pb);
  2391. else
  2392. atom.size = INT64_MAX;
  2393. /* check MOV header */
  2394. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2395. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2396. mov_read_close(s);
  2397. return err;
  2398. }
  2399. if (!mov->found_moov) {
  2400. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2401. mov_read_close(s);
  2402. return AVERROR_INVALIDDATA;
  2403. }
  2404. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2405. if (pb->seekable && mov->chapter_track > 0)
  2406. mov_read_chapters(s);
  2407. if (mov->trex_data) {
  2408. int i;
  2409. for (i = 0; i < s->nb_streams; i++) {
  2410. AVStream *st = s->streams[i];
  2411. MOVStreamContext *sc = st->priv_data;
  2412. if (st->duration)
  2413. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  2414. }
  2415. }
  2416. return 0;
  2417. }
  2418. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2419. {
  2420. AVIndexEntry *sample = NULL;
  2421. int64_t best_dts = INT64_MAX;
  2422. int i;
  2423. for (i = 0; i < s->nb_streams; i++) {
  2424. AVStream *avst = s->streams[i];
  2425. MOVStreamContext *msc = avst->priv_data;
  2426. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2427. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2428. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2429. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2430. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2431. (s->pb->seekable &&
  2432. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2433. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2434. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2435. sample = current_sample;
  2436. best_dts = dts;
  2437. *st = avst;
  2438. }
  2439. }
  2440. }
  2441. return sample;
  2442. }
  2443. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2444. {
  2445. MOVContext *mov = s->priv_data;
  2446. MOVStreamContext *sc;
  2447. AVIndexEntry *sample;
  2448. AVStream *st = NULL;
  2449. int ret;
  2450. retry:
  2451. sample = mov_find_next_sample(s, &st);
  2452. if (!sample) {
  2453. mov->found_mdat = 0;
  2454. if (!mov->next_root_atom)
  2455. return AVERROR_EOF;
  2456. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  2457. mov->next_root_atom = 0;
  2458. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2459. s->pb->eof_reached)
  2460. return AVERROR_EOF;
  2461. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  2462. goto retry;
  2463. }
  2464. sc = st->priv_data;
  2465. /* must be done just before reading, to avoid infinite loop on sample */
  2466. sc->current_sample++;
  2467. if (st->discard != AVDISCARD_ALL) {
  2468. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2469. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2470. sc->ffindex, sample->pos);
  2471. return AVERROR_INVALIDDATA;
  2472. }
  2473. ret = av_get_packet(sc->pb, pkt, sample->size);
  2474. if (ret < 0)
  2475. return ret;
  2476. if (sc->has_palette) {
  2477. uint8_t *pal;
  2478. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  2479. if (!pal) {
  2480. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  2481. } else {
  2482. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  2483. sc->has_palette = 0;
  2484. }
  2485. }
  2486. #if CONFIG_DV_DEMUXER
  2487. if (mov->dv_demux && sc->dv_audio_container) {
  2488. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  2489. av_free(pkt->data);
  2490. pkt->size = 0;
  2491. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  2492. if (ret < 0)
  2493. return ret;
  2494. }
  2495. #endif
  2496. }
  2497. pkt->stream_index = sc->ffindex;
  2498. pkt->dts = sample->timestamp;
  2499. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  2500. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2501. /* update ctts context */
  2502. sc->ctts_sample++;
  2503. if (sc->ctts_index < sc->ctts_count &&
  2504. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2505. sc->ctts_index++;
  2506. sc->ctts_sample = 0;
  2507. }
  2508. if (sc->wrong_dts)
  2509. pkt->dts = AV_NOPTS_VALUE;
  2510. } else {
  2511. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2512. st->index_entries[sc->current_sample].timestamp : st->duration;
  2513. pkt->duration = next_dts - pkt->dts;
  2514. pkt->pts = pkt->dts;
  2515. }
  2516. if (st->discard == AVDISCARD_ALL)
  2517. goto retry;
  2518. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2519. pkt->pos = sample->pos;
  2520. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2521. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2522. return 0;
  2523. }
  2524. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2525. {
  2526. MOVStreamContext *sc = st->priv_data;
  2527. int sample, time_sample;
  2528. int i;
  2529. sample = av_index_search_timestamp(st, timestamp, flags);
  2530. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2531. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2532. sample = 0;
  2533. if (sample < 0) /* not sure what to do */
  2534. return AVERROR_INVALIDDATA;
  2535. sc->current_sample = sample;
  2536. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2537. /* adjust ctts index */
  2538. if (sc->ctts_data) {
  2539. time_sample = 0;
  2540. for (i = 0; i < sc->ctts_count; i++) {
  2541. int next = time_sample + sc->ctts_data[i].count;
  2542. if (next > sc->current_sample) {
  2543. sc->ctts_index = i;
  2544. sc->ctts_sample = sc->current_sample - time_sample;
  2545. break;
  2546. }
  2547. time_sample = next;
  2548. }
  2549. }
  2550. return sample;
  2551. }
  2552. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2553. {
  2554. AVStream *st;
  2555. int64_t seek_timestamp, timestamp;
  2556. int sample;
  2557. int i;
  2558. if (stream_index >= s->nb_streams)
  2559. return AVERROR_INVALIDDATA;
  2560. if (sample_time < 0)
  2561. sample_time = 0;
  2562. st = s->streams[stream_index];
  2563. sample = mov_seek_stream(s, st, sample_time, flags);
  2564. if (sample < 0)
  2565. return sample;
  2566. /* adjust seek timestamp to found sample timestamp */
  2567. seek_timestamp = st->index_entries[sample].timestamp;
  2568. for (i = 0; i < s->nb_streams; i++) {
  2569. st = s->streams[i];
  2570. if (stream_index == i)
  2571. continue;
  2572. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2573. mov_seek_stream(s, st, timestamp, flags);
  2574. }
  2575. return 0;
  2576. }
  2577. AVInputFormat ff_mov_demuxer = {
  2578. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  2579. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  2580. .priv_data_size = sizeof(MOVContext),
  2581. .read_probe = mov_probe,
  2582. .read_header = mov_read_header,
  2583. .read_packet = mov_read_packet,
  2584. .read_close = mov_read_close,
  2585. .read_seek = mov_read_seek,
  2586. };