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.

3657 lines
119KB

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