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.

3052 lines
99KB

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