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.

2938 lines
98KB

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