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.

3061 lines
100KB

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