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.

2989 lines
99KB

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