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.

3073 lines
100KB

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