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.

3079 lines
100KB

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