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.

3529 lines
116KB

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