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.

3556 lines
117KB

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