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.

5276 lines
175KB

  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 FFmpeg.
  10. *
  11. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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/internal.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libavutil/intfloat.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/time_internal.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/dict.h"
  37. #include "libavutil/display.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/aes.h"
  40. #include "libavutil/aes_ctr.h"
  41. #include "libavutil/sha.h"
  42. #include "libavutil/timecode.h"
  43. #include "libavcodec/ac3tab.h"
  44. #include "avformat.h"
  45. #include "internal.h"
  46. #include "avio_internal.h"
  47. #include "riff.h"
  48. #include "isom.h"
  49. #include "libavcodec/get_bits.h"
  50. #include "id3v1.h"
  51. #include "mov_chan.h"
  52. #include "replaygain.h"
  53. #if CONFIG_ZLIB
  54. #include <zlib.h>
  55. #endif
  56. #include "qtpalette.h"
  57. /* those functions parse an atom */
  58. /* links atom IDs to parse functions */
  59. typedef struct MOVParseTableEntry {
  60. uint32_t type;
  61. int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom);
  62. } MOVParseTableEntry;
  63. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom);
  64. static int mov_read_mfra(MOVContext *c, AVIOContext *f);
  65. static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb,
  66. unsigned len, const char *key)
  67. {
  68. char buf[16];
  69. short current, total = 0;
  70. avio_rb16(pb); // unknown
  71. current = avio_rb16(pb);
  72. if (len >= 6)
  73. total = avio_rb16(pb);
  74. if (!total)
  75. snprintf(buf, sizeof(buf), "%d", current);
  76. else
  77. snprintf(buf, sizeof(buf), "%d/%d", current, total);
  78. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  79. av_dict_set(&c->fc->metadata, key, buf, 0);
  80. return 0;
  81. }
  82. static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb,
  83. unsigned len, const char *key)
  84. {
  85. /* bypass padding bytes */
  86. avio_r8(pb);
  87. avio_r8(pb);
  88. avio_r8(pb);
  89. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  90. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  91. return 0;
  92. }
  93. static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb,
  94. unsigned len, const char *key)
  95. {
  96. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  97. av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0);
  98. return 0;
  99. }
  100. static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb,
  101. unsigned len, const char *key)
  102. {
  103. short genre;
  104. avio_r8(pb); // unknown
  105. genre = avio_r8(pb);
  106. if (genre < 1 || genre > ID3v1_GENRE_MAX)
  107. return 0;
  108. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  109. av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0);
  110. return 0;
  111. }
  112. static const uint32_t mac_to_unicode[128] = {
  113. 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1,
  114. 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8,
  115. 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3,
  116. 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC,
  117. 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF,
  118. 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8,
  119. 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211,
  120. 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8,
  121. 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB,
  122. 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153,
  123. 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA,
  124. 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02,
  125. 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1,
  126. 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4,
  127. 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC,
  128. 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7,
  129. };
  130. static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,
  131. char *dst, int dstlen)
  132. {
  133. char *p = dst;
  134. char *end = dst+dstlen-1;
  135. int i;
  136. for (i = 0; i < len; i++) {
  137. uint8_t t, c = avio_r8(pb);
  138. if (c < 0x80 && p < end)
  139. *p++ = c;
  140. else if (p < end)
  141. PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);
  142. }
  143. *p = 0;
  144. return p - dst;
  145. }
  146. static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len)
  147. {
  148. AVPacket pkt;
  149. AVStream *st;
  150. MOVStreamContext *sc;
  151. enum AVCodecID id;
  152. int ret;
  153. switch (type) {
  154. case 0xd: id = AV_CODEC_ID_MJPEG; break;
  155. case 0xe: id = AV_CODEC_ID_PNG; break;
  156. case 0x1b: id = AV_CODEC_ID_BMP; break;
  157. default:
  158. av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type);
  159. avio_skip(pb, len);
  160. return 0;
  161. }
  162. st = avformat_new_stream(c->fc, NULL);
  163. if (!st)
  164. return AVERROR(ENOMEM);
  165. sc = av_mallocz(sizeof(*sc));
  166. if (!sc)
  167. return AVERROR(ENOMEM);
  168. st->priv_data = sc;
  169. ret = av_get_packet(pb, &pkt, len);
  170. if (ret < 0)
  171. return ret;
  172. if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) {
  173. if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) {
  174. id = AV_CODEC_ID_PNG;
  175. } else {
  176. id = AV_CODEC_ID_MJPEG;
  177. }
  178. }
  179. st->disposition |= AV_DISPOSITION_ATTACHED_PIC;
  180. st->attached_pic = pkt;
  181. st->attached_pic.stream_index = st->index;
  182. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  183. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  184. st->codec->codec_id = id;
  185. return 0;
  186. }
  187. static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len)
  188. {
  189. char language[4] = { 0 };
  190. char buf[200], place[100];
  191. uint16_t langcode = 0;
  192. double longitude, latitude, altitude;
  193. const char *key = "location";
  194. if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) {
  195. av_log(c->fc, AV_LOG_ERROR, "loci too short\n");
  196. return AVERROR_INVALIDDATA;
  197. }
  198. avio_skip(pb, 4); // version+flags
  199. langcode = avio_rb16(pb);
  200. ff_mov_lang_to_iso639(langcode, language);
  201. len -= 6;
  202. len -= avio_get_str(pb, len, place, sizeof(place));
  203. if (len < 1) {
  204. av_log(c->fc, AV_LOG_ERROR, "place name too long\n");
  205. return AVERROR_INVALIDDATA;
  206. }
  207. avio_skip(pb, 1); // role
  208. len -= 1;
  209. if (len < 12) {
  210. av_log(c->fc, AV_LOG_ERROR, "no space for coordinates left (%d)\n", len);
  211. return AVERROR_INVALIDDATA;
  212. }
  213. longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  214. latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  215. altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16);
  216. // Try to output in the same format as the ?xyz field
  217. snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude);
  218. if (altitude)
  219. av_strlcatf(buf, sizeof(buf), "%+f", altitude);
  220. av_strlcatf(buf, sizeof(buf), "/%s", place);
  221. if (*language && strcmp(language, "und")) {
  222. char key2[16];
  223. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  224. av_dict_set(&c->fc->metadata, key2, buf, 0);
  225. }
  226. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  227. return av_dict_set(&c->fc->metadata, key, buf, 0);
  228. }
  229. static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  230. {
  231. char tmp_key[5];
  232. char key2[32], language[4] = {0};
  233. char *str = NULL;
  234. const char *key = NULL;
  235. uint16_t langcode = 0;
  236. uint32_t data_type = 0, str_size, str_size_alloc;
  237. int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;
  238. int raw = 0;
  239. int num = 0;
  240. switch (atom.type) {
  241. case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break;
  242. case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break;
  243. case MKTAG( 'X','M','P','_'):
  244. if (c->export_xmp) { key = "xmp"; raw = 1; } break;
  245. case MKTAG( 'a','A','R','T'): key = "album_artist"; break;
  246. case MKTAG( 'a','k','I','D'): key = "account_type";
  247. parse = mov_metadata_int8_no_padding; break;
  248. case MKTAG( 'a','p','I','D'): key = "account_id"; break;
  249. case MKTAG( 'c','a','t','g'): key = "category"; break;
  250. case MKTAG( 'c','p','i','l'): key = "compilation";
  251. parse = mov_metadata_int8_no_padding; break;
  252. case MKTAG( 'c','p','r','t'): key = "copyright"; break;
  253. case MKTAG( 'd','e','s','c'): key = "description"; break;
  254. case MKTAG( 'd','i','s','k'): key = "disc";
  255. parse = mov_metadata_track_or_disc_number; break;
  256. case MKTAG( 'e','g','i','d'): key = "episode_uid";
  257. parse = mov_metadata_int8_no_padding; break;
  258. case MKTAG( 'g','n','r','e'): key = "genre";
  259. parse = mov_metadata_gnre; break;
  260. case MKTAG( 'h','d','v','d'): key = "hd_video";
  261. parse = mov_metadata_int8_no_padding; break;
  262. case MKTAG( 'k','e','y','w'): key = "keywords"; break;
  263. case MKTAG( 'l','d','e','s'): key = "synopsis"; break;
  264. case MKTAG( 'l','o','c','i'):
  265. return mov_metadata_loci(c, pb, atom.size);
  266. case MKTAG( 'p','c','s','t'): key = "podcast";
  267. parse = mov_metadata_int8_no_padding; break;
  268. case MKTAG( 'p','g','a','p'): key = "gapless_playback";
  269. parse = mov_metadata_int8_no_padding; break;
  270. case MKTAG( 'p','u','r','d'): key = "purchase_date"; break;
  271. case MKTAG( 'r','t','n','g'): key = "rating";
  272. parse = mov_metadata_int8_no_padding; break;
  273. case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break;
  274. case MKTAG( 's','o','a','l'): key = "sort_album"; break;
  275. case MKTAG( 's','o','a','r'): key = "sort_artist"; break;
  276. case MKTAG( 's','o','c','o'): key = "sort_composer"; break;
  277. case MKTAG( 's','o','n','m'): key = "sort_name"; break;
  278. case MKTAG( 's','o','s','n'): key = "sort_show"; break;
  279. case MKTAG( 's','t','i','k'): key = "media_type";
  280. parse = mov_metadata_int8_no_padding; break;
  281. case MKTAG( 't','r','k','n'): key = "track";
  282. parse = mov_metadata_track_or_disc_number; break;
  283. case MKTAG( 't','v','e','n'): key = "episode_id"; break;
  284. case MKTAG( 't','v','e','s'): key = "episode_sort";
  285. parse = mov_metadata_int8_bypass_padding; break;
  286. case MKTAG( 't','v','n','n'): key = "network"; break;
  287. case MKTAG( 't','v','s','h'): key = "show"; break;
  288. case MKTAG( 't','v','s','n'): key = "season_number";
  289. parse = mov_metadata_int8_bypass_padding; break;
  290. case MKTAG(0xa9,'A','R','T'): key = "artist"; break;
  291. case MKTAG(0xa9,'P','R','D'): key = "producer"; break;
  292. case MKTAG(0xa9,'a','l','b'): key = "album"; break;
  293. case MKTAG(0xa9,'a','u','t'): key = "artist"; break;
  294. case MKTAG(0xa9,'c','h','p'): key = "chapter"; break;
  295. case MKTAG(0xa9,'c','m','t'): key = "comment"; break;
  296. case MKTAG(0xa9,'c','o','m'): key = "composer"; break;
  297. case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;
  298. case MKTAG(0xa9,'d','a','y'): key = "date"; break;
  299. case MKTAG(0xa9,'d','i','r'): key = "director"; break;
  300. case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break;
  301. case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break;
  302. case MKTAG(0xa9,'e','n','c'): key = "encoder"; break;
  303. case MKTAG(0xa9,'f','m','t'): key = "original_format"; break;
  304. case MKTAG(0xa9,'g','e','n'): key = "genre"; break;
  305. case MKTAG(0xa9,'g','r','p'): key = "grouping"; break;
  306. case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break;
  307. case MKTAG(0xa9,'i','n','f'): key = "comment"; break;
  308. case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break;
  309. case MKTAG(0xa9,'m','a','k'): key = "make"; break;
  310. case MKTAG(0xa9,'m','o','d'): key = "model"; break;
  311. case MKTAG(0xa9,'n','a','m'): key = "title"; break;
  312. case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break;
  313. case MKTAG(0xa9,'p','r','d'): key = "producer"; break;
  314. case MKTAG(0xa9,'p','r','f'): key = "performers"; break;
  315. case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break;
  316. case MKTAG(0xa9,'s','r','c'): key = "original_source"; break;
  317. case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break;
  318. case MKTAG(0xa9,'s','w','r'): key = "encoder"; break;
  319. case MKTAG(0xa9,'t','o','o'): key = "encoder"; break;
  320. case MKTAG(0xa9,'t','r','k'): key = "track"; break;
  321. case MKTAG(0xa9,'u','r','l'): key = "URL"; break;
  322. case MKTAG(0xa9,'w','r','n'): key = "warning"; break;
  323. case MKTAG(0xa9,'w','r','t'): key = "composer"; break;
  324. case MKTAG(0xa9,'x','y','z'): key = "location"; break;
  325. }
  326. retry:
  327. if (c->itunes_metadata && atom.size > 8) {
  328. int data_size = avio_rb32(pb);
  329. int tag = avio_rl32(pb);
  330. if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) {
  331. data_type = avio_rb32(pb); // type
  332. avio_rb32(pb); // unknown
  333. str_size = data_size - 16;
  334. atom.size -= 16;
  335. if (atom.type == MKTAG('c', 'o', 'v', 'r')) {
  336. int ret = mov_read_covr(c, pb, data_type, str_size);
  337. if (ret < 0) {
  338. av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");
  339. }
  340. return ret;
  341. } else if (!key && c->found_hdlr_mdta && c->meta_keys) {
  342. uint32_t index = AV_RB32(&atom.type);
  343. if (index < c->meta_keys_count) {
  344. key = c->meta_keys[index];
  345. } else {
  346. av_log(c->fc, AV_LOG_WARNING,
  347. "The index of 'data' is out of range: %d >= %d.\n",
  348. index, c->meta_keys_count);
  349. }
  350. }
  351. } else return 0;
  352. } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) {
  353. str_size = avio_rb16(pb); // string length
  354. if (str_size > atom.size) {
  355. raw = 1;
  356. avio_seek(pb, -2, SEEK_CUR);
  357. av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n");
  358. goto retry;
  359. }
  360. langcode = avio_rb16(pb);
  361. ff_mov_lang_to_iso639(langcode, language);
  362. atom.size -= 4;
  363. } else
  364. str_size = atom.size;
  365. if (c->export_all && !key) {
  366. snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);
  367. key = tmp_key;
  368. }
  369. if (!key)
  370. return 0;
  371. if (atom.size < 0 || str_size >= INT_MAX/2)
  372. return AVERROR_INVALIDDATA;
  373. // Allocates enough space if data_type is a float32 number, otherwise
  374. // worst-case requirement for output string in case of utf8 coded input
  375. num = (data_type == 23);
  376. str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1;
  377. str = av_mallocz(str_size_alloc);
  378. if (!str)
  379. return AVERROR(ENOMEM);
  380. if (parse)
  381. parse(c, pb, str_size, key);
  382. else {
  383. if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded
  384. mov_read_mac_string(c, pb, str_size, str, str_size_alloc);
  385. } else if (data_type == 23 && str_size >= 4) { // BE float32
  386. float val = av_int2float(avio_rb32(pb));
  387. if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) {
  388. av_log(c->fc, AV_LOG_ERROR,
  389. "Failed to store the float32 number (%f) in string.\n", val);
  390. av_free(str);
  391. return AVERROR_INVALIDDATA;
  392. }
  393. } else {
  394. int ret = ffio_read_size(pb, str, str_size);
  395. if (ret < 0) {
  396. av_free(str);
  397. return ret;
  398. }
  399. str[str_size] = 0;
  400. }
  401. c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  402. av_dict_set(&c->fc->metadata, key, str, 0);
  403. if (*language && strcmp(language, "und")) {
  404. snprintf(key2, sizeof(key2), "%s-%s", key, language);
  405. av_dict_set(&c->fc->metadata, key2, str, 0);
  406. }
  407. if (!strcmp(key, "encoder")) {
  408. int major, minor, micro;
  409. if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) {
  410. c->handbrake_version = 1000000*major + 1000*minor + micro;
  411. }
  412. }
  413. }
  414. av_log(c->fc, AV_LOG_TRACE, "lang \"%3s\" ", language);
  415. av_log(c->fc, AV_LOG_TRACE, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",
  416. key, str, (char*)&atom.type, str_size_alloc, atom.size);
  417. av_freep(&str);
  418. return 0;
  419. }
  420. static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  421. {
  422. int64_t start;
  423. int i, nb_chapters, str_len, version;
  424. char str[256+1];
  425. int ret;
  426. if (c->ignore_chapters)
  427. return 0;
  428. if ((atom.size -= 5) < 0)
  429. return 0;
  430. version = avio_r8(pb);
  431. avio_rb24(pb);
  432. if (version)
  433. avio_rb32(pb); // ???
  434. nb_chapters = avio_r8(pb);
  435. for (i = 0; i < nb_chapters; i++) {
  436. if (atom.size < 9)
  437. return 0;
  438. start = avio_rb64(pb);
  439. str_len = avio_r8(pb);
  440. if ((atom.size -= 9+str_len) < 0)
  441. return 0;
  442. ret = ffio_read_size(pb, str, str_len);
  443. if (ret < 0)
  444. return ret;
  445. str[str_len] = 0;
  446. avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str);
  447. }
  448. return 0;
  449. }
  450. #define MIN_DATA_ENTRY_BOX_SIZE 12
  451. static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  452. {
  453. AVStream *st;
  454. MOVStreamContext *sc;
  455. int entries, i, j;
  456. if (c->fc->nb_streams < 1)
  457. return 0;
  458. st = c->fc->streams[c->fc->nb_streams-1];
  459. sc = st->priv_data;
  460. avio_rb32(pb); // version + flags
  461. entries = avio_rb32(pb);
  462. if (entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||
  463. entries >= UINT_MAX / sizeof(*sc->drefs))
  464. return AVERROR_INVALIDDATA;
  465. av_free(sc->drefs);
  466. sc->drefs_count = 0;
  467. sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
  468. if (!sc->drefs)
  469. return AVERROR(ENOMEM);
  470. sc->drefs_count = entries;
  471. for (i = 0; i < entries; i++) {
  472. MOVDref *dref = &sc->drefs[i];
  473. uint32_t size = avio_rb32(pb);
  474. int64_t next = avio_tell(pb) + size - 4;
  475. if (size < 12)
  476. return AVERROR_INVALIDDATA;
  477. dref->type = avio_rl32(pb);
  478. avio_rb32(pb); // version + flags
  479. av_log(c->fc, AV_LOG_TRACE, "type %.4s size %d\n", (char*)&dref->type, size);
  480. if (dref->type == MKTAG('a','l','i','s') && size > 150) {
  481. /* macintosh alias record */
  482. uint16_t volume_len, len;
  483. int16_t type;
  484. int ret;
  485. avio_skip(pb, 10);
  486. volume_len = avio_r8(pb);
  487. volume_len = FFMIN(volume_len, 27);
  488. ret = ffio_read_size(pb, dref->volume, 27);
  489. if (ret < 0)
  490. return ret;
  491. dref->volume[volume_len] = 0;
  492. av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
  493. avio_skip(pb, 12);
  494. len = avio_r8(pb);
  495. len = FFMIN(len, 63);
  496. ret = ffio_read_size(pb, dref->filename, 63);
  497. if (ret < 0)
  498. return ret;
  499. dref->filename[len] = 0;
  500. av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
  501. avio_skip(pb, 16);
  502. /* read next level up_from_alias/down_to_target */
  503. dref->nlvl_from = avio_rb16(pb);
  504. dref->nlvl_to = avio_rb16(pb);
  505. av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
  506. dref->nlvl_from, dref->nlvl_to);
  507. avio_skip(pb, 16);
  508. for (type = 0; type != -1 && avio_tell(pb) < next; ) {
  509. if(avio_feof(pb))
  510. return AVERROR_EOF;
  511. type = avio_rb16(pb);
  512. len = avio_rb16(pb);
  513. av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
  514. if (len&1)
  515. len += 1;
  516. if (type == 2) { // absolute path
  517. av_free(dref->path);
  518. dref->path = av_mallocz(len+1);
  519. if (!dref->path)
  520. return AVERROR(ENOMEM);
  521. ret = ffio_read_size(pb, dref->path, len);
  522. if (ret < 0) {
  523. av_freep(&dref->path);
  524. return ret;
  525. }
  526. if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
  527. len -= volume_len;
  528. memmove(dref->path, dref->path+volume_len, len);
  529. dref->path[len] = 0;
  530. }
  531. for (j = 0; j < len; j++)
  532. if (dref->path[j] == ':' || dref->path[j] == 0)
  533. dref->path[j] = '/';
  534. av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
  535. } else if (type == 0) { // directory name
  536. av_free(dref->dir);
  537. dref->dir = av_malloc(len+1);
  538. if (!dref->dir)
  539. return AVERROR(ENOMEM);
  540. ret = ffio_read_size(pb, dref->dir, len);
  541. if (ret < 0) {
  542. av_freep(&dref->dir);
  543. return ret;
  544. }
  545. dref->dir[len] = 0;
  546. for (j = 0; j < len; j++)
  547. if (dref->dir[j] == ':')
  548. dref->dir[j] = '/';
  549. av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
  550. } else
  551. avio_skip(pb, len);
  552. }
  553. } else {
  554. av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x08%x size %d\n",
  555. dref->type, size);
  556. entries--;
  557. i--;
  558. }
  559. avio_seek(pb, next, SEEK_SET);
  560. }
  561. return 0;
  562. }
  563. static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  564. {
  565. AVStream *st;
  566. uint32_t type;
  567. uint32_t av_unused ctype;
  568. int64_t title_size;
  569. char *title_str;
  570. int ret;
  571. avio_r8(pb); /* version */
  572. avio_rb24(pb); /* flags */
  573. /* component type */
  574. ctype = avio_rl32(pb);
  575. type = avio_rl32(pb); /* component subtype */
  576. av_log(c->fc, AV_LOG_TRACE, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  577. av_log(c->fc, AV_LOG_TRACE, "stype= %.4s\n", (char*)&type);
  578. if (c->trak_index < 0) { // meta not inside a trak
  579. if (type == MKTAG('m','d','t','a')) {
  580. c->found_hdlr_mdta = 1;
  581. }
  582. return 0;
  583. }
  584. st = c->fc->streams[c->fc->nb_streams-1];
  585. if (type == MKTAG('v','i','d','e'))
  586. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  587. else if (type == MKTAG('s','o','u','n'))
  588. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  589. else if (type == MKTAG('m','1','a',' '))
  590. st->codec->codec_id = AV_CODEC_ID_MP2;
  591. else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p')))
  592. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  593. avio_rb32(pb); /* component manufacture */
  594. avio_rb32(pb); /* component flags */
  595. avio_rb32(pb); /* component flags mask */
  596. title_size = atom.size - 24;
  597. if (title_size > 0) {
  598. title_str = av_malloc(title_size + 1); /* Add null terminator */
  599. if (!title_str)
  600. return AVERROR(ENOMEM);
  601. ret = ffio_read_size(pb, title_str, title_size);
  602. if (ret < 0) {
  603. av_freep(&title_str);
  604. return ret;
  605. }
  606. title_str[title_size] = 0;
  607. if (title_str[0]) {
  608. int off = (!c->isom && title_str[0] == title_size - 1);
  609. av_dict_set(&st->metadata, "handler_name", title_str + off, 0);
  610. }
  611. av_freep(&title_str);
  612. }
  613. return 0;
  614. }
  615. int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb)
  616. {
  617. AVStream *st;
  618. int tag;
  619. if (fc->nb_streams < 1)
  620. return 0;
  621. st = fc->streams[fc->nb_streams-1];
  622. avio_rb32(pb); /* version + flags */
  623. ff_mp4_read_descr(fc, pb, &tag);
  624. if (tag == MP4ESDescrTag) {
  625. ff_mp4_parse_es_descr(pb, NULL);
  626. } else
  627. avio_rb16(pb); /* ID */
  628. ff_mp4_read_descr(fc, pb, &tag);
  629. if (tag == MP4DecConfigDescrTag)
  630. ff_mp4_read_dec_config_descr(fc, st, pb);
  631. return 0;
  632. }
  633. static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  634. {
  635. return ff_mov_read_esds(c->fc, pb);
  636. }
  637. static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  638. {
  639. AVStream *st;
  640. enum AVAudioServiceType *ast;
  641. int ac3info, acmod, lfeon, bsmod;
  642. if (c->fc->nb_streams < 1)
  643. return 0;
  644. st = c->fc->streams[c->fc->nb_streams-1];
  645. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  646. sizeof(*ast));
  647. if (!ast)
  648. return AVERROR(ENOMEM);
  649. ac3info = avio_rb24(pb);
  650. bsmod = (ac3info >> 14) & 0x7;
  651. acmod = (ac3info >> 11) & 0x7;
  652. lfeon = (ac3info >> 10) & 0x1;
  653. st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
  654. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  655. if (lfeon)
  656. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  657. *ast = bsmod;
  658. if (st->codec->channels > 1 && bsmod == 0x7)
  659. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  660. st->codec->audio_service_type = *ast;
  661. return 0;
  662. }
  663. static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  664. {
  665. AVStream *st;
  666. enum AVAudioServiceType *ast;
  667. int eac3info, acmod, lfeon, bsmod;
  668. if (c->fc->nb_streams < 1)
  669. return 0;
  670. st = c->fc->streams[c->fc->nb_streams-1];
  671. ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,
  672. sizeof(*ast));
  673. if (!ast)
  674. return AVERROR(ENOMEM);
  675. /* No need to parse fields for additional independent substreams and its
  676. * associated dependent substreams since libavcodec's E-AC-3 decoder
  677. * does not support them yet. */
  678. avio_rb16(pb); /* data_rate and num_ind_sub */
  679. eac3info = avio_rb24(pb);
  680. bsmod = (eac3info >> 12) & 0x1f;
  681. acmod = (eac3info >> 9) & 0x7;
  682. lfeon = (eac3info >> 8) & 0x1;
  683. st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
  684. if (lfeon)
  685. st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
  686. st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
  687. *ast = bsmod;
  688. if (st->codec->channels > 1 && bsmod == 0x7)
  689. *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;
  690. st->codec->audio_service_type = *ast;
  691. return 0;
  692. }
  693. static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  694. {
  695. const uint32_t ddts_size = 20;
  696. AVStream *st = NULL;
  697. uint8_t *buf = NULL;
  698. uint32_t frame_duration_code = 0;
  699. uint32_t channel_layout_code = 0;
  700. GetBitContext gb;
  701. buf = av_malloc(ddts_size + FF_INPUT_BUFFER_PADDING_SIZE);
  702. if (!buf) {
  703. return AVERROR(ENOMEM);
  704. }
  705. if (avio_read(pb, buf, ddts_size) < ddts_size) {
  706. av_free(buf);
  707. return AVERROR_INVALIDDATA;
  708. }
  709. init_get_bits(&gb, buf, 8*ddts_size);
  710. if (c->fc->nb_streams < 1) {
  711. return 0;
  712. }
  713. st = c->fc->streams[c->fc->nb_streams-1];
  714. st->codec->sample_rate = get_bits_long(&gb, 32);
  715. skip_bits_long(&gb, 32); /* max bitrate */
  716. st->codec->bit_rate = get_bits_long(&gb, 32);
  717. st->codec->bits_per_coded_sample = get_bits(&gb, 8);
  718. frame_duration_code = get_bits(&gb, 2);
  719. skip_bits(&gb, 30); /* various fields */
  720. channel_layout_code = get_bits(&gb, 16);
  721. st->codec->frame_size =
  722. (frame_duration_code == 0) ? 512 :
  723. (frame_duration_code == 1) ? 1024 :
  724. (frame_duration_code == 2) ? 2048 :
  725. (frame_duration_code == 3) ? 4096 : 0;
  726. if (channel_layout_code > 0xff) {
  727. av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout");
  728. }
  729. st->codec->channel_layout =
  730. ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) |
  731. ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) |
  732. ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) |
  733. ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) |
  734. ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) |
  735. ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0);
  736. st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);
  737. return 0;
  738. }
  739. static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  740. {
  741. AVStream *st;
  742. if (c->fc->nb_streams < 1)
  743. return 0;
  744. st = c->fc->streams[c->fc->nb_streams-1];
  745. if (atom.size < 16)
  746. return 0;
  747. /* skip version and flags */
  748. avio_skip(pb, 4);
  749. ff_mov_read_chan(c->fc, pb, st, atom.size - 4);
  750. return 0;
  751. }
  752. static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  753. {
  754. AVStream *st;
  755. int ret;
  756. if (c->fc->nb_streams < 1)
  757. return 0;
  758. st = c->fc->streams[c->fc->nb_streams-1];
  759. if ((ret = ff_get_wav_header(c->fc, pb, st->codec, atom.size, 0)) < 0)
  760. av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n");
  761. return ret;
  762. }
  763. static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  764. {
  765. const int num = avio_rb32(pb);
  766. const int den = avio_rb32(pb);
  767. AVStream *st;
  768. if (c->fc->nb_streams < 1)
  769. return 0;
  770. st = c->fc->streams[c->fc->nb_streams-1];
  771. if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default
  772. (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) {
  773. av_log(c->fc, AV_LOG_WARNING,
  774. "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n",
  775. st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
  776. num, den);
  777. } else if (den != 0) {
  778. av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,
  779. num, den, 32767);
  780. }
  781. return 0;
  782. }
  783. /* this atom contains actual media data */
  784. static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  785. {
  786. if (atom.size == 0) /* wrong one (MP4) */
  787. return 0;
  788. c->found_mdat=1;
  789. return 0; /* now go for moov */
  790. }
  791. #define DRM_BLOB_SIZE 56
  792. static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  793. {
  794. uint8_t intermediate_key[20];
  795. uint8_t intermediate_iv[20];
  796. uint8_t input[64];
  797. uint8_t output[64];
  798. uint8_t file_checksum[20];
  799. uint8_t calculated_checksum[20];
  800. struct AVSHA *sha;
  801. int i;
  802. int ret = 0;
  803. uint8_t *activation_bytes = c->activation_bytes;
  804. uint8_t *fixed_key = c->audible_fixed_key;
  805. c->aax_mode = 1;
  806. sha = av_sha_alloc();
  807. if (!sha)
  808. return AVERROR(ENOMEM);
  809. c->aes_decrypt = av_aes_alloc();
  810. if (!c->aes_decrypt) {
  811. ret = AVERROR(ENOMEM);
  812. goto fail;
  813. }
  814. /* drm blob processing */
  815. avio_read(pb, output, 8); // go to offset 8, absolute position 0x251
  816. avio_read(pb, input, DRM_BLOB_SIZE);
  817. avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d
  818. avio_read(pb, file_checksum, 20);
  819. av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools
  820. for (i = 0; i < 20; i++)
  821. av_log(sha, AV_LOG_INFO, "%02x", file_checksum[i]);
  822. av_log(c->fc, AV_LOG_INFO, "\n");
  823. /* verify activation data */
  824. if (!activation_bytes) {
  825. av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n");
  826. ret = 0; /* allow ffprobe to continue working on .aax files */
  827. goto fail;
  828. }
  829. if (c->activation_bytes_size != 4) {
  830. av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n");
  831. ret = AVERROR(EINVAL);
  832. goto fail;
  833. }
  834. /* verify fixed key */
  835. if (c->audible_fixed_key_size != 16) {
  836. av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n");
  837. ret = AVERROR(EINVAL);
  838. goto fail;
  839. }
  840. /* AAX (and AAX+) key derivation */
  841. av_sha_init(sha, 160);
  842. av_sha_update(sha, fixed_key, 16);
  843. av_sha_update(sha, activation_bytes, 4);
  844. av_sha_final(sha, intermediate_key);
  845. av_sha_init(sha, 160);
  846. av_sha_update(sha, fixed_key, 16);
  847. av_sha_update(sha, intermediate_key, 20);
  848. av_sha_update(sha, activation_bytes, 4);
  849. av_sha_final(sha, intermediate_iv);
  850. av_sha_init(sha, 160);
  851. av_sha_update(sha, intermediate_key, 16);
  852. av_sha_update(sha, intermediate_iv, 16);
  853. av_sha_final(sha, calculated_checksum);
  854. if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error
  855. av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n");
  856. ret = AVERROR_INVALIDDATA;
  857. goto fail;
  858. }
  859. av_aes_init(c->aes_decrypt, intermediate_key, 128, 1);
  860. av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1);
  861. for (i = 0; i < 4; i++) {
  862. // file data (in output) is stored in big-endian mode
  863. if (activation_bytes[i] != output[3 - i]) { // critical error
  864. av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n");
  865. ret = AVERROR_INVALIDDATA;
  866. goto fail;
  867. }
  868. }
  869. memcpy(c->file_key, output + 8, 16);
  870. memcpy(input, output + 26, 16);
  871. av_sha_init(sha, 160);
  872. av_sha_update(sha, input, 16);
  873. av_sha_update(sha, c->file_key, 16);
  874. av_sha_update(sha, fixed_key, 16);
  875. av_sha_final(sha, c->file_iv);
  876. fail:
  877. av_free(sha);
  878. return ret;
  879. }
  880. // Audible AAX (and AAX+) bytestream decryption
  881. static int aax_filter(uint8_t *input, int size, MOVContext *c)
  882. {
  883. int blocks = 0;
  884. unsigned char iv[16];
  885. memcpy(iv, c->file_iv, 16); // iv is overwritten
  886. blocks = size >> 4; // trailing bytes are not encrypted!
  887. av_aes_init(c->aes_decrypt, c->file_key, 128, 1);
  888. av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1);
  889. return 0;
  890. }
  891. /* read major brand, minor version and compatible brands and store them as metadata */
  892. static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  893. {
  894. uint32_t minor_ver;
  895. int comp_brand_size;
  896. char* comp_brands_str;
  897. uint8_t type[5] = {0};
  898. int ret = ffio_read_size(pb, type, 4);
  899. if (ret < 0)
  900. return ret;
  901. if (strcmp(type, "qt "))
  902. c->isom = 1;
  903. av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);
  904. av_dict_set(&c->fc->metadata, "major_brand", type, 0);
  905. minor_ver = avio_rb32(pb); /* minor version */
  906. av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0);
  907. comp_brand_size = atom.size - 8;
  908. if (comp_brand_size < 0)
  909. return AVERROR_INVALIDDATA;
  910. comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */
  911. if (!comp_brands_str)
  912. return AVERROR(ENOMEM);
  913. ret = ffio_read_size(pb, comp_brands_str, comp_brand_size);
  914. if (ret < 0) {
  915. av_freep(&comp_brands_str);
  916. return ret;
  917. }
  918. comp_brands_str[comp_brand_size] = 0;
  919. av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);
  920. av_freep(&comp_brands_str);
  921. return 0;
  922. }
  923. /* this atom should contain all header atoms */
  924. static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  925. {
  926. int ret;
  927. if (c->found_moov) {
  928. av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n");
  929. avio_skip(pb, atom.size);
  930. return 0;
  931. }
  932. if ((ret = mov_read_default(c, pb, atom)) < 0)
  933. return ret;
  934. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  935. /* so we don't parse the whole file if over a network */
  936. c->found_moov=1;
  937. return 0; /* now go for mdat */
  938. }
  939. static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  940. {
  941. if (!c->has_looked_for_mfra && c->use_mfra_for > 0) {
  942. c->has_looked_for_mfra = 1;
  943. if (pb->seekable) {
  944. int ret;
  945. av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look "
  946. "for a mfra\n");
  947. if ((ret = mov_read_mfra(c, pb)) < 0) {
  948. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to "
  949. "read the mfra (may be a live ismv)\n");
  950. }
  951. } else {
  952. av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not "
  953. "seekable, can not look for mfra\n");
  954. }
  955. }
  956. c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8;
  957. av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset);
  958. return mov_read_default(c, pb, atom);
  959. }
  960. static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time)
  961. {
  962. char buffer[32];
  963. if (time) {
  964. struct tm *ptm, tmbuf;
  965. time_t timet;
  966. if(time >= 2082844800)
  967. time -= 2082844800; /* seconds between 1904-01-01 and Epoch */
  968. timet = time;
  969. ptm = gmtime_r(&timet, &tmbuf);
  970. if (!ptm) return;
  971. if (strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ptm))
  972. av_dict_set(metadata, "creation_time", buffer, 0);
  973. }
  974. }
  975. static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  976. {
  977. AVStream *st;
  978. MOVStreamContext *sc;
  979. int version;
  980. char language[4] = {0};
  981. unsigned lang;
  982. int64_t creation_time;
  983. if (c->fc->nb_streams < 1)
  984. return 0;
  985. st = c->fc->streams[c->fc->nb_streams-1];
  986. sc = st->priv_data;
  987. if (sc->time_scale) {
  988. av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");
  989. return AVERROR_INVALIDDATA;
  990. }
  991. version = avio_r8(pb);
  992. if (version > 1) {
  993. avpriv_request_sample(c->fc, "Version %d", version);
  994. return AVERROR_PATCHWELCOME;
  995. }
  996. avio_rb24(pb); /* flags */
  997. if (version == 1) {
  998. creation_time = avio_rb64(pb);
  999. avio_rb64(pb);
  1000. } else {
  1001. creation_time = avio_rb32(pb);
  1002. avio_rb32(pb); /* modification time */
  1003. }
  1004. mov_metadata_creation_time(&st->metadata, creation_time);
  1005. sc->time_scale = avio_rb32(pb);
  1006. st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1007. lang = avio_rb16(pb); /* language */
  1008. if (ff_mov_lang_to_iso639(lang, language))
  1009. av_dict_set(&st->metadata, "language", language, 0);
  1010. avio_rb16(pb); /* quality */
  1011. return 0;
  1012. }
  1013. static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1014. {
  1015. int64_t creation_time;
  1016. int version = avio_r8(pb); /* version */
  1017. avio_rb24(pb); /* flags */
  1018. if (version == 1) {
  1019. creation_time = avio_rb64(pb);
  1020. avio_rb64(pb);
  1021. } else {
  1022. creation_time = avio_rb32(pb);
  1023. avio_rb32(pb); /* modification time */
  1024. }
  1025. mov_metadata_creation_time(&c->fc->metadata, creation_time);
  1026. c->time_scale = avio_rb32(pb); /* time scale */
  1027. av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);
  1028. c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */
  1029. // set the AVCodecContext duration because the duration of individual tracks
  1030. // may be inaccurate
  1031. if (c->time_scale > 0 && !c->trex_data)
  1032. c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);
  1033. avio_rb32(pb); /* preferred scale */
  1034. avio_rb16(pb); /* preferred volume */
  1035. avio_skip(pb, 10); /* reserved */
  1036. avio_skip(pb, 36); /* display matrix */
  1037. avio_rb32(pb); /* preview time */
  1038. avio_rb32(pb); /* preview duration */
  1039. avio_rb32(pb); /* poster time */
  1040. avio_rb32(pb); /* selection time */
  1041. avio_rb32(pb); /* selection duration */
  1042. avio_rb32(pb); /* current time */
  1043. avio_rb32(pb); /* next track ID */
  1044. return 0;
  1045. }
  1046. static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1047. {
  1048. AVStream *st;
  1049. int little_endian;
  1050. if (c->fc->nb_streams < 1)
  1051. return 0;
  1052. st = c->fc->streams[c->fc->nb_streams-1];
  1053. little_endian = avio_rb16(pb) & 0xFF;
  1054. av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian);
  1055. if (little_endian == 1) {
  1056. switch (st->codec->codec_id) {
  1057. case AV_CODEC_ID_PCM_S24BE:
  1058. st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
  1059. break;
  1060. case AV_CODEC_ID_PCM_S32BE:
  1061. st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
  1062. break;
  1063. case AV_CODEC_ID_PCM_F32BE:
  1064. st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
  1065. break;
  1066. case AV_CODEC_ID_PCM_F64BE:
  1067. st->codec->codec_id = AV_CODEC_ID_PCM_F64LE;
  1068. break;
  1069. default:
  1070. break;
  1071. }
  1072. }
  1073. return 0;
  1074. }
  1075. static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1076. {
  1077. AVStream *st;
  1078. char color_parameter_type[5] = { 0 };
  1079. uint16_t color_primaries, color_trc, color_matrix;
  1080. int ret;
  1081. if (c->fc->nb_streams < 1)
  1082. return 0;
  1083. st = c->fc->streams[c->fc->nb_streams - 1];
  1084. ret = ffio_read_size(pb, color_parameter_type, 4);
  1085. if (ret < 0)
  1086. return ret;
  1087. if (strncmp(color_parameter_type, "nclx", 4) &&
  1088. strncmp(color_parameter_type, "nclc", 4)) {
  1089. av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",
  1090. color_parameter_type);
  1091. return 0;
  1092. }
  1093. color_primaries = avio_rb16(pb);
  1094. color_trc = avio_rb16(pb);
  1095. color_matrix = avio_rb16(pb);
  1096. av_log(c->fc, AV_LOG_TRACE,
  1097. "%s: pri %d trc %d matrix %d",
  1098. color_parameter_type, color_primaries, color_trc, color_matrix);
  1099. if (!strncmp(color_parameter_type, "nclx", 4)) {
  1100. uint8_t color_range = avio_r8(pb) >> 7;
  1101. av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range);
  1102. if (color_range)
  1103. st->codec->color_range = AVCOL_RANGE_JPEG;
  1104. else
  1105. st->codec->color_range = AVCOL_RANGE_MPEG;
  1106. /* 14496-12 references JPEG XR specs (rather than the more complete
  1107. * 23001-8) so some adjusting is required */
  1108. if (color_primaries >= AVCOL_PRI_FILM)
  1109. color_primaries = AVCOL_PRI_UNSPECIFIED;
  1110. if ((color_trc >= AVCOL_TRC_LINEAR &&
  1111. color_trc <= AVCOL_TRC_LOG_SQRT) ||
  1112. color_trc >= AVCOL_TRC_BT2020_10)
  1113. color_trc = AVCOL_TRC_UNSPECIFIED;
  1114. if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  1115. color_matrix = AVCOL_SPC_UNSPECIFIED;
  1116. st->codec->color_primaries = color_primaries;
  1117. st->codec->color_trc = color_trc;
  1118. st->codec->colorspace = color_matrix;
  1119. } else if (!strncmp(color_parameter_type, "nclc", 4)) {
  1120. /* color primaries, Table 4-4 */
  1121. switch (color_primaries) {
  1122. case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
  1123. case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
  1124. case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
  1125. }
  1126. /* color transfer, Table 4-5 */
  1127. switch (color_trc) {
  1128. case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
  1129. case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
  1130. }
  1131. /* color matrix, Table 4-6 */
  1132. switch (color_matrix) {
  1133. case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
  1134. case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
  1135. case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
  1136. }
  1137. }
  1138. av_log(c->fc, AV_LOG_TRACE, "\n");
  1139. return 0;
  1140. }
  1141. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1142. {
  1143. AVStream *st;
  1144. unsigned mov_field_order;
  1145. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1146. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1147. return 0;
  1148. st = c->fc->streams[c->fc->nb_streams-1];
  1149. if (atom.size < 2)
  1150. return AVERROR_INVALIDDATA;
  1151. mov_field_order = avio_rb16(pb);
  1152. if ((mov_field_order & 0xFF00) == 0x0100)
  1153. decoded_field_order = AV_FIELD_PROGRESSIVE;
  1154. else if ((mov_field_order & 0xFF00) == 0x0200) {
  1155. switch (mov_field_order & 0xFF) {
  1156. case 0x01: decoded_field_order = AV_FIELD_TT;
  1157. break;
  1158. case 0x06: decoded_field_order = AV_FIELD_BB;
  1159. break;
  1160. case 0x09: decoded_field_order = AV_FIELD_TB;
  1161. break;
  1162. case 0x0E: decoded_field_order = AV_FIELD_BT;
  1163. break;
  1164. }
  1165. }
  1166. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1167. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1168. }
  1169. st->codec->field_order = decoded_field_order;
  1170. return 0;
  1171. }
  1172. static int mov_realloc_extradata(AVCodecContext *codec, MOVAtom atom)
  1173. {
  1174. int err = 0;
  1175. uint64_t size = (uint64_t)codec->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1176. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1177. return AVERROR_INVALIDDATA;
  1178. if ((err = av_reallocp(&codec->extradata, size)) < 0) {
  1179. codec->extradata_size = 0;
  1180. return err;
  1181. }
  1182. codec->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1183. return 0;
  1184. }
  1185. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1186. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1187. AVCodecContext *codec, uint8_t *buf)
  1188. {
  1189. int64_t result = atom.size;
  1190. int err;
  1191. AV_WB32(buf , atom.size + 8);
  1192. AV_WL32(buf + 4, atom.type);
  1193. err = ffio_read_size(pb, buf + 8, atom.size);
  1194. if (err < 0) {
  1195. codec->extradata_size -= atom.size;
  1196. return err;
  1197. } else if (err < atom.size) {
  1198. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1199. codec->extradata_size -= atom.size - err;
  1200. result = err;
  1201. }
  1202. memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1203. return result;
  1204. }
  1205. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  1206. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1207. enum AVCodecID codec_id)
  1208. {
  1209. AVStream *st;
  1210. uint64_t original_size;
  1211. int err;
  1212. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1213. return 0;
  1214. st = c->fc->streams[c->fc->nb_streams-1];
  1215. if (st->codec->codec_id != codec_id)
  1216. return 0; /* unexpected codec_id - don't mess with extradata */
  1217. original_size = st->codec->extradata_size;
  1218. err = mov_realloc_extradata(st->codec, atom);
  1219. if (err)
  1220. return err;
  1221. err = mov_read_atom_into_extradata(c, pb, atom, st->codec, st->codec->extradata + original_size);
  1222. if (err < 0)
  1223. return err;
  1224. return 0; // Note: this is the original behavior to ignore truncation.
  1225. }
  1226. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1227. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1228. {
  1229. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1230. }
  1231. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1232. {
  1233. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1234. }
  1235. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1236. {
  1237. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1238. }
  1239. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1240. {
  1241. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1242. }
  1243. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1244. {
  1245. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1246. if(ret == 0)
  1247. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1248. return ret;
  1249. }
  1250. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1251. {
  1252. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1253. if (!ret && c->fc->nb_streams >= 1) {
  1254. AVCodecContext *avctx = c->fc->streams[c->fc->nb_streams-1]->codec;
  1255. if (avctx->extradata_size >= 40) {
  1256. avctx->height = AV_RB16(&avctx->extradata[36]);
  1257. avctx->width = AV_RB16(&avctx->extradata[38]);
  1258. }
  1259. }
  1260. return ret;
  1261. }
  1262. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1263. {
  1264. if (c->fc->nb_streams >= 1) {
  1265. AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  1266. if (codec->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1267. codec->codec_id == AV_CODEC_ID_H264 &&
  1268. atom.size > 11) {
  1269. avio_skip(pb, 10);
  1270. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1271. if (avio_rb16(pb) == 0xd4d)
  1272. codec->width = 1440;
  1273. return 0;
  1274. }
  1275. }
  1276. return mov_read_avid(c, pb, atom);
  1277. }
  1278. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1279. {
  1280. int ret = 0;
  1281. int length = 0;
  1282. uint64_t original_size;
  1283. if (c->fc->nb_streams >= 1) {
  1284. AVCodecContext *codec = c->fc->streams[c->fc->nb_streams-1]->codec;
  1285. if (codec->codec_id == AV_CODEC_ID_H264)
  1286. return 0;
  1287. if (atom.size == 16) {
  1288. original_size = codec->extradata_size;
  1289. ret = mov_realloc_extradata(codec, atom);
  1290. if (!ret) {
  1291. length = mov_read_atom_into_extradata(c, pb, atom, codec, codec->extradata + original_size);
  1292. if (length == atom.size) {
  1293. const uint8_t range_value = codec->extradata[original_size + 19];
  1294. switch (range_value) {
  1295. case 1:
  1296. codec->color_range = AVCOL_RANGE_MPEG;
  1297. break;
  1298. case 2:
  1299. codec->color_range = AVCOL_RANGE_JPEG;
  1300. break;
  1301. default:
  1302. av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1303. break;
  1304. }
  1305. ff_dlog(c, "color_range: %d\n", codec->color_range);
  1306. } else {
  1307. /* For some reason the whole atom was not added to the extradata */
  1308. av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1309. }
  1310. } else {
  1311. av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1312. }
  1313. } else {
  1314. av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1315. }
  1316. }
  1317. return ret;
  1318. }
  1319. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1320. {
  1321. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1322. }
  1323. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1324. {
  1325. AVStream *st;
  1326. int ret;
  1327. if (c->fc->nb_streams < 1)
  1328. return 0;
  1329. st = c->fc->streams[c->fc->nb_streams-1];
  1330. if ((uint64_t)atom.size > (1<<30))
  1331. return AVERROR_INVALIDDATA;
  1332. if (st->codec->codec_id == AV_CODEC_ID_QDM2 ||
  1333. st->codec->codec_id == AV_CODEC_ID_QDMC ||
  1334. st->codec->codec_id == AV_CODEC_ID_SPEEX) {
  1335. // pass all frma atom to codec, needed at least for QDMC and QDM2
  1336. av_freep(&st->codec->extradata);
  1337. ret = ff_get_extradata(st->codec, pb, atom.size);
  1338. if (ret < 0)
  1339. return ret;
  1340. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1341. if (st->codec->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1342. uint64_t buffer;
  1343. ret = ffio_ensure_seekback(pb, 8);
  1344. if (ret < 0)
  1345. return ret;
  1346. buffer = avio_rb64(pb);
  1347. atom.size -= 8;
  1348. if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1349. && buffer >> 32 <= atom.size
  1350. && buffer >> 32 >= 8) {
  1351. avio_skip(pb, -8);
  1352. atom.size += 8;
  1353. } else if (!st->codec->extradata_size) {
  1354. #define ALAC_EXTRADATA_SIZE 36
  1355. st->codec->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1356. if (!st->codec->extradata)
  1357. return AVERROR(ENOMEM);
  1358. st->codec->extradata_size = ALAC_EXTRADATA_SIZE;
  1359. AV_WB32(st->codec->extradata , ALAC_EXTRADATA_SIZE);
  1360. AV_WB32(st->codec->extradata + 4, MKTAG('a','l','a','c'));
  1361. AV_WB64(st->codec->extradata + 12, buffer);
  1362. avio_read(pb, st->codec->extradata + 20, 16);
  1363. avio_skip(pb, atom.size - 24);
  1364. return 0;
  1365. }
  1366. }
  1367. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1368. return ret;
  1369. } else
  1370. avio_skip(pb, atom.size);
  1371. return 0;
  1372. }
  1373. /**
  1374. * This function reads atom content and puts data in extradata without tag
  1375. * nor size unlike mov_read_extradata.
  1376. */
  1377. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1378. {
  1379. AVStream *st;
  1380. int ret;
  1381. if (c->fc->nb_streams < 1)
  1382. return 0;
  1383. st = c->fc->streams[c->fc->nb_streams-1];
  1384. if ((uint64_t)atom.size > (1<<30))
  1385. return AVERROR_INVALIDDATA;
  1386. if (atom.size >= 10) {
  1387. // Broken files created by legacy versions of libavformat will
  1388. // wrap a whole fiel atom inside of a glbl atom.
  1389. unsigned size = avio_rb32(pb);
  1390. unsigned type = avio_rl32(pb);
  1391. avio_seek(pb, -8, SEEK_CUR);
  1392. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1393. return mov_read_default(c, pb, atom);
  1394. }
  1395. if (st->codec->extradata_size > 1 && st->codec->extradata) {
  1396. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1397. return 0;
  1398. }
  1399. av_freep(&st->codec->extradata);
  1400. ret = ff_get_extradata(st->codec, pb, atom.size);
  1401. if (ret < 0)
  1402. return ret;
  1403. return 0;
  1404. }
  1405. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1406. {
  1407. AVStream *st;
  1408. uint8_t profile_level;
  1409. int ret;
  1410. if (c->fc->nb_streams < 1)
  1411. return 0;
  1412. st = c->fc->streams[c->fc->nb_streams-1];
  1413. if (atom.size >= (1<<28) || atom.size < 7)
  1414. return AVERROR_INVALIDDATA;
  1415. profile_level = avio_r8(pb);
  1416. if ((profile_level & 0xf0) != 0xc0)
  1417. return 0;
  1418. avio_seek(pb, 6, SEEK_CUR);
  1419. av_freep(&st->codec->extradata);
  1420. ret = ff_get_extradata(st->codec, pb, atom.size - 7);
  1421. if (ret < 0)
  1422. return ret;
  1423. return 0;
  1424. }
  1425. /**
  1426. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1427. * but can have extradata appended at the end after the 40 bytes belonging
  1428. * to the struct.
  1429. */
  1430. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1431. {
  1432. AVStream *st;
  1433. int ret;
  1434. if (c->fc->nb_streams < 1)
  1435. return 0;
  1436. if (atom.size <= 40)
  1437. return 0;
  1438. st = c->fc->streams[c->fc->nb_streams-1];
  1439. if ((uint64_t)atom.size > (1<<30))
  1440. return AVERROR_INVALIDDATA;
  1441. avio_skip(pb, 40);
  1442. av_freep(&st->codec->extradata);
  1443. ret = ff_get_extradata(st->codec, pb, atom.size - 40);
  1444. if (ret < 0)
  1445. return ret;
  1446. return 0;
  1447. }
  1448. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1449. {
  1450. AVStream *st;
  1451. MOVStreamContext *sc;
  1452. unsigned int i, entries;
  1453. if (c->fc->nb_streams < 1)
  1454. return 0;
  1455. st = c->fc->streams[c->fc->nb_streams-1];
  1456. sc = st->priv_data;
  1457. avio_r8(pb); /* version */
  1458. avio_rb24(pb); /* flags */
  1459. entries = avio_rb32(pb);
  1460. if (!entries)
  1461. return 0;
  1462. if (sc->chunk_offsets)
  1463. av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1464. av_free(sc->chunk_offsets);
  1465. sc->chunk_count = 0;
  1466. sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1467. if (!sc->chunk_offsets)
  1468. return AVERROR(ENOMEM);
  1469. sc->chunk_count = entries;
  1470. if (atom.type == MKTAG('s','t','c','o'))
  1471. for (i = 0; i < entries && !pb->eof_reached; i++)
  1472. sc->chunk_offsets[i] = avio_rb32(pb);
  1473. else if (atom.type == MKTAG('c','o','6','4'))
  1474. for (i = 0; i < entries && !pb->eof_reached; i++)
  1475. sc->chunk_offsets[i] = avio_rb64(pb);
  1476. else
  1477. return AVERROR_INVALIDDATA;
  1478. sc->chunk_count = i;
  1479. if (pb->eof_reached)
  1480. return AVERROR_EOF;
  1481. return 0;
  1482. }
  1483. /**
  1484. * Compute codec id for 'lpcm' tag.
  1485. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1486. */
  1487. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1488. {
  1489. /* lpcm flags:
  1490. * 0x1 = float
  1491. * 0x2 = big-endian
  1492. * 0x4 = signed
  1493. */
  1494. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1495. }
  1496. static int mov_codec_id(AVStream *st, uint32_t format)
  1497. {
  1498. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1499. if (id <= 0 &&
  1500. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1501. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1502. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1503. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1504. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1505. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1506. /* skip old asf mpeg4 tag */
  1507. format && format != MKTAG('m','p','4','s')) {
  1508. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1509. if (id <= 0)
  1510. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1511. if (id > 0)
  1512. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1513. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA ||
  1514. (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1515. st->codec->codec_id == AV_CODEC_ID_NONE)) {
  1516. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1517. if (id > 0)
  1518. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1519. }
  1520. }
  1521. st->codec->codec_tag = format;
  1522. return id;
  1523. }
  1524. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1525. AVStream *st, MOVStreamContext *sc)
  1526. {
  1527. uint8_t codec_name[32];
  1528. int64_t stsd_start;
  1529. unsigned int len;
  1530. /* The first 16 bytes of the video sample description are already
  1531. * read in ff_mov_read_stsd_entries() */
  1532. stsd_start = avio_tell(pb) - 16;
  1533. avio_rb16(pb); /* version */
  1534. avio_rb16(pb); /* revision level */
  1535. avio_rb32(pb); /* vendor */
  1536. avio_rb32(pb); /* temporal quality */
  1537. avio_rb32(pb); /* spatial quality */
  1538. st->codec->width = avio_rb16(pb); /* width */
  1539. st->codec->height = avio_rb16(pb); /* height */
  1540. avio_rb32(pb); /* horiz resolution */
  1541. avio_rb32(pb); /* vert resolution */
  1542. avio_rb32(pb); /* data size, always 0 */
  1543. avio_rb16(pb); /* frames per samples */
  1544. len = avio_r8(pb); /* codec name, pascal string */
  1545. if (len > 31)
  1546. len = 31;
  1547. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1548. if (len < 31)
  1549. avio_skip(pb, 31 - len);
  1550. if (codec_name[0])
  1551. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1552. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1553. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1554. st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1555. st->codec->width &= ~1;
  1556. st->codec->height &= ~1;
  1557. }
  1558. /* Flash Media Server uses tag H263 with Sorenson Spark */
  1559. if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1560. !memcmp(codec_name, "Sorenson H263", 13))
  1561. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1562. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1563. avio_seek(pb, stsd_start, SEEK_SET);
  1564. if (ff_get_qtpalette(st->codec->codec_id, pb, sc->palette)) {
  1565. st->codec->bits_per_coded_sample &= 0x1F;
  1566. sc->has_palette = 1;
  1567. }
  1568. }
  1569. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1570. AVStream *st, MOVStreamContext *sc)
  1571. {
  1572. int bits_per_sample, flags;
  1573. uint16_t version = avio_rb16(pb);
  1574. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1575. avio_rb16(pb); /* revision level */
  1576. avio_rb32(pb); /* vendor */
  1577. st->codec->channels = avio_rb16(pb); /* channel count */
  1578. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1579. av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codec->channels);
  1580. sc->audio_cid = avio_rb16(pb);
  1581. avio_rb16(pb); /* packet size = 0 */
  1582. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1583. // Read QT version 1 fields. In version 0 these do not exist.
  1584. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1585. if (!c->isom ||
  1586. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1587. if (version == 1) {
  1588. sc->samples_per_frame = avio_rb32(pb);
  1589. avio_rb32(pb); /* bytes per packet */
  1590. sc->bytes_per_frame = avio_rb32(pb);
  1591. avio_rb32(pb); /* bytes per sample */
  1592. } else if (version == 2) {
  1593. avio_rb32(pb); /* sizeof struct only */
  1594. st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1595. st->codec->channels = avio_rb32(pb);
  1596. avio_rb32(pb); /* always 0x7F000000 */
  1597. st->codec->bits_per_coded_sample = avio_rb32(pb);
  1598. flags = avio_rb32(pb); /* lpcm format specific flag */
  1599. sc->bytes_per_frame = avio_rb32(pb);
  1600. sc->samples_per_frame = avio_rb32(pb);
  1601. if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1602. st->codec->codec_id =
  1603. ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1604. flags);
  1605. }
  1606. if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1607. /* can't correctly handle variable sized packet as audio unit */
  1608. switch (st->codec->codec_id) {
  1609. case AV_CODEC_ID_MP2:
  1610. case AV_CODEC_ID_MP3:
  1611. st->need_parsing = AVSTREAM_PARSE_FULL;
  1612. break;
  1613. }
  1614. }
  1615. }
  1616. if (sc->format == 0) {
  1617. if (st->codec->bits_per_coded_sample == 8)
  1618. st->codec->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
  1619. else if (st->codec->bits_per_coded_sample == 16)
  1620. st->codec->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
  1621. }
  1622. switch (st->codec->codec_id) {
  1623. case AV_CODEC_ID_PCM_S8:
  1624. case AV_CODEC_ID_PCM_U8:
  1625. if (st->codec->bits_per_coded_sample == 16)
  1626. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1627. break;
  1628. case AV_CODEC_ID_PCM_S16LE:
  1629. case AV_CODEC_ID_PCM_S16BE:
  1630. if (st->codec->bits_per_coded_sample == 8)
  1631. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1632. else if (st->codec->bits_per_coded_sample == 24)
  1633. st->codec->codec_id =
  1634. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1635. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1636. else if (st->codec->bits_per_coded_sample == 32)
  1637. st->codec->codec_id =
  1638. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1639. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1640. break;
  1641. /* set values for old format before stsd version 1 appeared */
  1642. case AV_CODEC_ID_MACE3:
  1643. sc->samples_per_frame = 6;
  1644. sc->bytes_per_frame = 2 * st->codec->channels;
  1645. break;
  1646. case AV_CODEC_ID_MACE6:
  1647. sc->samples_per_frame = 6;
  1648. sc->bytes_per_frame = 1 * st->codec->channels;
  1649. break;
  1650. case AV_CODEC_ID_ADPCM_IMA_QT:
  1651. sc->samples_per_frame = 64;
  1652. sc->bytes_per_frame = 34 * st->codec->channels;
  1653. break;
  1654. case AV_CODEC_ID_GSM:
  1655. sc->samples_per_frame = 160;
  1656. sc->bytes_per_frame = 33;
  1657. break;
  1658. default:
  1659. break;
  1660. }
  1661. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1662. if (bits_per_sample) {
  1663. st->codec->bits_per_coded_sample = bits_per_sample;
  1664. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1665. }
  1666. }
  1667. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1668. AVStream *st, MOVStreamContext *sc,
  1669. int64_t size)
  1670. {
  1671. // ttxt stsd contains display flags, justification, background
  1672. // color, fonts, and default styles, so fake an atom to read it
  1673. MOVAtom fake_atom = { .size = size };
  1674. // mp4s contains a regular esds atom
  1675. if (st->codec->codec_tag != AV_RL32("mp4s"))
  1676. mov_read_glbl(c, pb, fake_atom);
  1677. st->codec->width = sc->width;
  1678. st->codec->height = sc->height;
  1679. }
  1680. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1681. {
  1682. uint8_t r, g, b;
  1683. int y, cb, cr;
  1684. y = (ycbcr >> 16) & 0xFF;
  1685. cr = (ycbcr >> 8) & 0xFF;
  1686. cb = ycbcr & 0xFF;
  1687. b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
  1688. g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
  1689. r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
  1690. return (r << 16) | (g << 8) | b;
  1691. }
  1692. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1693. {
  1694. char buf[256] = {0};
  1695. uint8_t *src = st->codec->extradata;
  1696. int i;
  1697. if (st->codec->extradata_size != 64)
  1698. return 0;
  1699. if (st->codec->width > 0 && st->codec->height > 0)
  1700. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1701. st->codec->width, st->codec->height);
  1702. av_strlcat(buf, "palette: ", sizeof(buf));
  1703. for (i = 0; i < 16; i++) {
  1704. uint32_t yuv = AV_RB32(src + i * 4);
  1705. uint32_t rgba = yuv_to_rgba(yuv);
  1706. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1707. }
  1708. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1709. return 0;
  1710. av_freep(&st->codec->extradata);
  1711. st->codec->extradata_size = 0;
  1712. st->codec->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1713. if (!st->codec->extradata)
  1714. return AVERROR(ENOMEM);
  1715. st->codec->extradata_size = strlen(buf);
  1716. memcpy(st->codec->extradata, buf, st->codec->extradata_size);
  1717. return 0;
  1718. }
  1719. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1720. AVStream *st, MOVStreamContext *sc,
  1721. int64_t size)
  1722. {
  1723. int ret;
  1724. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1725. if ((int)size != size)
  1726. return AVERROR(ENOMEM);
  1727. ret = ff_get_extradata(st->codec, pb, size);
  1728. if (ret < 0)
  1729. return ret;
  1730. if (size > 16) {
  1731. MOVStreamContext *tmcd_ctx = st->priv_data;
  1732. int val;
  1733. val = AV_RB32(st->codec->extradata + 4);
  1734. tmcd_ctx->tmcd_flags = val;
  1735. if (val & 1)
  1736. st->codec->flags2 |= AV_CODEC_FLAG2_DROP_FRAME_TIMECODE;
  1737. st->codec->time_base.den = st->codec->extradata[16]; /* number of frame */
  1738. st->codec->time_base.num = 1;
  1739. /* adjust for per frame dur in counter mode */
  1740. if (tmcd_ctx->tmcd_flags & 0x0008) {
  1741. int timescale = AV_RB32(st->codec->extradata + 8);
  1742. int framedur = AV_RB32(st->codec->extradata + 12);
  1743. st->codec->time_base.den *= timescale;
  1744. st->codec->time_base.num *= framedur;
  1745. }
  1746. if (size > 30) {
  1747. uint32_t len = AV_RB32(st->codec->extradata + 18); /* name atom length */
  1748. uint32_t format = AV_RB32(st->codec->extradata + 22);
  1749. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1750. uint16_t str_size = AV_RB16(st->codec->extradata + 26); /* string length */
  1751. if (str_size > 0 && size >= (int)str_size + 26) {
  1752. char *reel_name = av_malloc(str_size + 1);
  1753. if (!reel_name)
  1754. return AVERROR(ENOMEM);
  1755. memcpy(reel_name, st->codec->extradata + 30, str_size);
  1756. reel_name[str_size] = 0; /* Add null terminator */
  1757. /* don't add reel_name if emtpy string */
  1758. if (*reel_name == 0) {
  1759. av_free(reel_name);
  1760. } else {
  1761. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1762. }
  1763. }
  1764. }
  1765. }
  1766. }
  1767. } else {
  1768. /* other codec type, just skip (rtp, mp4s ...) */
  1769. avio_skip(pb, size);
  1770. }
  1771. return 0;
  1772. }
  1773. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1774. AVStream *st, MOVStreamContext *sc)
  1775. {
  1776. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1777. !st->codec->sample_rate && sc->time_scale > 1)
  1778. st->codec->sample_rate = sc->time_scale;
  1779. /* special codec parameters handling */
  1780. switch (st->codec->codec_id) {
  1781. #if CONFIG_DV_DEMUXER
  1782. case AV_CODEC_ID_DVAUDIO:
  1783. c->dv_fctx = avformat_alloc_context();
  1784. if (!c->dv_fctx) {
  1785. av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  1786. return AVERROR(ENOMEM);
  1787. }
  1788. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1789. if (!c->dv_demux) {
  1790. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1791. return AVERROR(ENOMEM);
  1792. }
  1793. sc->dv_audio_container = 1;
  1794. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1795. break;
  1796. #endif
  1797. /* no ifdef since parameters are always those */
  1798. case AV_CODEC_ID_QCELP:
  1799. st->codec->channels = 1;
  1800. // force sample rate for qcelp when not stored in mov
  1801. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1802. st->codec->sample_rate = 8000;
  1803. // FIXME: Why is the following needed for some files?
  1804. sc->samples_per_frame = 160;
  1805. if (!sc->bytes_per_frame)
  1806. sc->bytes_per_frame = 35;
  1807. break;
  1808. case AV_CODEC_ID_AMR_NB:
  1809. st->codec->channels = 1;
  1810. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1811. st->codec->sample_rate = 8000;
  1812. break;
  1813. case AV_CODEC_ID_AMR_WB:
  1814. st->codec->channels = 1;
  1815. st->codec->sample_rate = 16000;
  1816. break;
  1817. case AV_CODEC_ID_MP2:
  1818. case AV_CODEC_ID_MP3:
  1819. /* force type after stsd for m1a hdlr */
  1820. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1821. break;
  1822. case AV_CODEC_ID_GSM:
  1823. case AV_CODEC_ID_ADPCM_MS:
  1824. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1825. case AV_CODEC_ID_ILBC:
  1826. case AV_CODEC_ID_MACE3:
  1827. case AV_CODEC_ID_MACE6:
  1828. case AV_CODEC_ID_QDM2:
  1829. st->codec->block_align = sc->bytes_per_frame;
  1830. break;
  1831. case AV_CODEC_ID_ALAC:
  1832. if (st->codec->extradata_size == 36) {
  1833. st->codec->channels = AV_RB8 (st->codec->extradata + 21);
  1834. st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  1835. }
  1836. break;
  1837. case AV_CODEC_ID_AC3:
  1838. case AV_CODEC_ID_EAC3:
  1839. case AV_CODEC_ID_MPEG1VIDEO:
  1840. case AV_CODEC_ID_VC1:
  1841. st->need_parsing = AVSTREAM_PARSE_FULL;
  1842. break;
  1843. default:
  1844. break;
  1845. }
  1846. return 0;
  1847. }
  1848. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1849. int codec_tag, int format,
  1850. int64_t size)
  1851. {
  1852. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1853. if (codec_tag &&
  1854. (codec_tag != format &&
  1855. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1856. : codec_tag != MKTAG('j','p','e','g')))) {
  1857. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1858. * export it as a separate AVStream but this needs a few changes
  1859. * in the MOV demuxer, patch welcome. */
  1860. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1861. avio_skip(pb, size);
  1862. return 1;
  1863. }
  1864. if ( codec_tag == AV_RL32("avc1") ||
  1865. codec_tag == AV_RL32("hvc1") ||
  1866. codec_tag == AV_RL32("hev1")
  1867. )
  1868. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1869. return 0;
  1870. }
  1871. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1872. {
  1873. AVStream *st;
  1874. MOVStreamContext *sc;
  1875. int pseudo_stream_id;
  1876. if (c->fc->nb_streams < 1)
  1877. return 0;
  1878. st = c->fc->streams[c->fc->nb_streams-1];
  1879. sc = st->priv_data;
  1880. for (pseudo_stream_id = 0;
  1881. pseudo_stream_id < entries && !pb->eof_reached;
  1882. pseudo_stream_id++) {
  1883. //Parsing Sample description table
  1884. enum AVCodecID id;
  1885. int ret, dref_id = 1;
  1886. MOVAtom a = { AV_RL32("stsd") };
  1887. int64_t start_pos = avio_tell(pb);
  1888. int64_t size = avio_rb32(pb); /* size */
  1889. uint32_t format = avio_rl32(pb); /* data format */
  1890. if (size >= 16) {
  1891. avio_rb32(pb); /* reserved */
  1892. avio_rb16(pb); /* reserved */
  1893. dref_id = avio_rb16(pb);
  1894. } else if (size <= 7) {
  1895. av_log(c->fc, AV_LOG_ERROR,
  1896. "invalid size %"PRId64" in stsd\n", size);
  1897. return AVERROR_INVALIDDATA;
  1898. }
  1899. if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  1900. size - (avio_tell(pb) - start_pos)))
  1901. continue;
  1902. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1903. sc->dref_id= dref_id;
  1904. sc->format = format;
  1905. id = mov_codec_id(st, format);
  1906. av_log(c->fc, AV_LOG_TRACE,
  1907. "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
  1908. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1909. (format >> 24) & 0xff, format, st->codec->codec_type);
  1910. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1911. st->codec->codec_id = id;
  1912. mov_parse_stsd_video(c, pb, st, sc);
  1913. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1914. st->codec->codec_id = id;
  1915. mov_parse_stsd_audio(c, pb, st, sc);
  1916. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1917. st->codec->codec_id = id;
  1918. mov_parse_stsd_subtitle(c, pb, st, sc,
  1919. size - (avio_tell(pb) - start_pos));
  1920. } else {
  1921. ret = mov_parse_stsd_data(c, pb, st, sc,
  1922. size - (avio_tell(pb) - start_pos));
  1923. if (ret < 0)
  1924. return ret;
  1925. }
  1926. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1927. a.size = size - (avio_tell(pb) - start_pos);
  1928. if (a.size > 8) {
  1929. if ((ret = mov_read_default(c, pb, a)) < 0)
  1930. return ret;
  1931. } else if (a.size > 0)
  1932. avio_skip(pb, a.size);
  1933. }
  1934. if (pb->eof_reached)
  1935. return AVERROR_EOF;
  1936. return mov_finalize_stsd_codec(c, pb, st, sc);
  1937. }
  1938. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1939. {
  1940. int entries;
  1941. avio_r8(pb); /* version */
  1942. avio_rb24(pb); /* flags */
  1943. entries = avio_rb32(pb);
  1944. return ff_mov_read_stsd_entries(c, pb, entries);
  1945. }
  1946. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1947. {
  1948. AVStream *st;
  1949. MOVStreamContext *sc;
  1950. unsigned int i, entries;
  1951. if (c->fc->nb_streams < 1)
  1952. return 0;
  1953. st = c->fc->streams[c->fc->nb_streams-1];
  1954. sc = st->priv_data;
  1955. avio_r8(pb); /* version */
  1956. avio_rb24(pb); /* flags */
  1957. entries = avio_rb32(pb);
  1958. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1959. if (!entries)
  1960. return 0;
  1961. if (sc->stsc_data)
  1962. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  1963. av_free(sc->stsc_data);
  1964. sc->stsc_count = 0;
  1965. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  1966. if (!sc->stsc_data)
  1967. return AVERROR(ENOMEM);
  1968. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1969. sc->stsc_data[i].first = avio_rb32(pb);
  1970. sc->stsc_data[i].count = avio_rb32(pb);
  1971. sc->stsc_data[i].id = avio_rb32(pb);
  1972. }
  1973. sc->stsc_count = i;
  1974. if (pb->eof_reached)
  1975. return AVERROR_EOF;
  1976. return 0;
  1977. }
  1978. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1979. {
  1980. AVStream *st;
  1981. MOVStreamContext *sc;
  1982. unsigned i, entries;
  1983. if (c->fc->nb_streams < 1)
  1984. return 0;
  1985. st = c->fc->streams[c->fc->nb_streams-1];
  1986. sc = st->priv_data;
  1987. avio_rb32(pb); // version + flags
  1988. entries = avio_rb32(pb);
  1989. if (sc->stps_data)
  1990. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  1991. av_free(sc->stps_data);
  1992. sc->stps_count = 0;
  1993. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  1994. if (!sc->stps_data)
  1995. return AVERROR(ENOMEM);
  1996. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1997. sc->stps_data[i] = avio_rb32(pb);
  1998. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  1999. }
  2000. sc->stps_count = i;
  2001. if (pb->eof_reached)
  2002. return AVERROR_EOF;
  2003. return 0;
  2004. }
  2005. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2006. {
  2007. AVStream *st;
  2008. MOVStreamContext *sc;
  2009. unsigned int i, entries;
  2010. if (c->fc->nb_streams < 1)
  2011. return 0;
  2012. st = c->fc->streams[c->fc->nb_streams-1];
  2013. sc = st->priv_data;
  2014. avio_r8(pb); /* version */
  2015. avio_rb24(pb); /* flags */
  2016. entries = avio_rb32(pb);
  2017. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2018. if (!entries)
  2019. {
  2020. sc->keyframe_absent = 1;
  2021. if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2022. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2023. return 0;
  2024. }
  2025. if (sc->keyframes)
  2026. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2027. if (entries >= UINT_MAX / sizeof(int))
  2028. return AVERROR_INVALIDDATA;
  2029. av_freep(&sc->keyframes);
  2030. sc->keyframe_count = 0;
  2031. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2032. if (!sc->keyframes)
  2033. return AVERROR(ENOMEM);
  2034. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2035. sc->keyframes[i] = avio_rb32(pb);
  2036. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2037. }
  2038. sc->keyframe_count = i;
  2039. if (pb->eof_reached)
  2040. return AVERROR_EOF;
  2041. return 0;
  2042. }
  2043. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2044. {
  2045. AVStream *st;
  2046. MOVStreamContext *sc;
  2047. unsigned int i, entries, sample_size, field_size, num_bytes;
  2048. GetBitContext gb;
  2049. unsigned char* buf;
  2050. int ret;
  2051. if (c->fc->nb_streams < 1)
  2052. return 0;
  2053. st = c->fc->streams[c->fc->nb_streams-1];
  2054. sc = st->priv_data;
  2055. avio_r8(pb); /* version */
  2056. avio_rb24(pb); /* flags */
  2057. if (atom.type == MKTAG('s','t','s','z')) {
  2058. sample_size = avio_rb32(pb);
  2059. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2060. sc->sample_size = sample_size;
  2061. sc->stsz_sample_size = sample_size;
  2062. field_size = 32;
  2063. } else {
  2064. sample_size = 0;
  2065. avio_rb24(pb); /* reserved */
  2066. field_size = avio_r8(pb);
  2067. }
  2068. entries = avio_rb32(pb);
  2069. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2070. sc->sample_count = entries;
  2071. if (sample_size)
  2072. return 0;
  2073. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2074. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2075. return AVERROR_INVALIDDATA;
  2076. }
  2077. if (!entries)
  2078. return 0;
  2079. if (entries >= (UINT_MAX - 4) / field_size)
  2080. return AVERROR_INVALIDDATA;
  2081. if (sc->sample_sizes)
  2082. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2083. av_free(sc->sample_sizes);
  2084. sc->sample_count = 0;
  2085. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2086. if (!sc->sample_sizes)
  2087. return AVERROR(ENOMEM);
  2088. num_bytes = (entries*field_size+4)>>3;
  2089. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2090. if (!buf) {
  2091. av_freep(&sc->sample_sizes);
  2092. return AVERROR(ENOMEM);
  2093. }
  2094. ret = ffio_read_size(pb, buf, num_bytes);
  2095. if (ret < 0) {
  2096. av_freep(&sc->sample_sizes);
  2097. av_free(buf);
  2098. return ret;
  2099. }
  2100. init_get_bits(&gb, buf, 8*num_bytes);
  2101. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2102. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2103. sc->data_size += sc->sample_sizes[i];
  2104. }
  2105. sc->sample_count = i;
  2106. av_free(buf);
  2107. if (pb->eof_reached)
  2108. return AVERROR_EOF;
  2109. return 0;
  2110. }
  2111. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2112. {
  2113. AVStream *st;
  2114. MOVStreamContext *sc;
  2115. unsigned int i, entries;
  2116. int64_t duration=0;
  2117. int64_t total_sample_count=0;
  2118. if (c->fc->nb_streams < 1)
  2119. return 0;
  2120. st = c->fc->streams[c->fc->nb_streams-1];
  2121. sc = st->priv_data;
  2122. avio_r8(pb); /* version */
  2123. avio_rb24(pb); /* flags */
  2124. entries = avio_rb32(pb);
  2125. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2126. c->fc->nb_streams-1, entries);
  2127. if (sc->stts_data)
  2128. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2129. av_free(sc->stts_data);
  2130. sc->stts_count = 0;
  2131. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2132. if (!sc->stts_data)
  2133. return AVERROR(ENOMEM);
  2134. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2135. int sample_duration;
  2136. int sample_count;
  2137. sample_count=avio_rb32(pb);
  2138. sample_duration = avio_rb32(pb);
  2139. if (sample_count < 0) {
  2140. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2141. return AVERROR_INVALIDDATA;
  2142. }
  2143. sc->stts_data[i].count= sample_count;
  2144. sc->stts_data[i].duration= sample_duration;
  2145. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2146. sample_count, sample_duration);
  2147. if ( i+1 == entries
  2148. && i
  2149. && sample_count == 1
  2150. && total_sample_count > 100
  2151. && sample_duration/10 > duration / total_sample_count)
  2152. sample_duration = duration / total_sample_count;
  2153. duration+=(int64_t)sample_duration*sample_count;
  2154. total_sample_count+=sample_count;
  2155. }
  2156. sc->stts_count = i;
  2157. sc->duration_for_fps += duration;
  2158. sc->nb_frames_for_fps += total_sample_count;
  2159. if (pb->eof_reached)
  2160. return AVERROR_EOF;
  2161. st->nb_frames= total_sample_count;
  2162. if (duration)
  2163. st->duration= duration;
  2164. sc->track_end = duration;
  2165. return 0;
  2166. }
  2167. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2168. {
  2169. if (duration < 0) {
  2170. if (duration == INT_MIN) {
  2171. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2172. duration++;
  2173. }
  2174. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2175. }
  2176. }
  2177. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2178. {
  2179. AVStream *st;
  2180. MOVStreamContext *sc;
  2181. unsigned int i, entries;
  2182. if (c->fc->nb_streams < 1)
  2183. return 0;
  2184. st = c->fc->streams[c->fc->nb_streams-1];
  2185. sc = st->priv_data;
  2186. avio_r8(pb); /* version */
  2187. avio_rb24(pb); /* flags */
  2188. entries = avio_rb32(pb);
  2189. av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2190. if (!entries)
  2191. return 0;
  2192. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2193. return AVERROR_INVALIDDATA;
  2194. av_freep(&sc->ctts_data);
  2195. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2196. if (!sc->ctts_data)
  2197. return AVERROR(ENOMEM);
  2198. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2199. int count =avio_rb32(pb);
  2200. int duration =avio_rb32(pb);
  2201. sc->ctts_data[i].count = count;
  2202. sc->ctts_data[i].duration= duration;
  2203. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2204. count, duration);
  2205. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2206. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2207. av_freep(&sc->ctts_data);
  2208. sc->ctts_count = 0;
  2209. return 0;
  2210. }
  2211. if (i+2<entries)
  2212. mov_update_dts_shift(sc, duration);
  2213. }
  2214. sc->ctts_count = i;
  2215. if (pb->eof_reached)
  2216. return AVERROR_EOF;
  2217. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2218. return 0;
  2219. }
  2220. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2221. {
  2222. AVStream *st;
  2223. MOVStreamContext *sc;
  2224. unsigned int i, entries;
  2225. uint8_t version;
  2226. uint32_t grouping_type;
  2227. if (c->fc->nb_streams < 1)
  2228. return 0;
  2229. st = c->fc->streams[c->fc->nb_streams-1];
  2230. sc = st->priv_data;
  2231. version = avio_r8(pb); /* version */
  2232. avio_rb24(pb); /* flags */
  2233. grouping_type = avio_rl32(pb);
  2234. if (grouping_type != MKTAG( 'r','a','p',' '))
  2235. return 0; /* only support 'rap ' grouping */
  2236. if (version == 1)
  2237. avio_rb32(pb); /* grouping_type_parameter */
  2238. entries = avio_rb32(pb);
  2239. if (!entries)
  2240. return 0;
  2241. if (sc->rap_group)
  2242. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2243. av_free(sc->rap_group);
  2244. sc->rap_group_count = 0;
  2245. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2246. if (!sc->rap_group)
  2247. return AVERROR(ENOMEM);
  2248. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2249. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2250. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2251. }
  2252. sc->rap_group_count = i;
  2253. return pb->eof_reached ? AVERROR_EOF : 0;
  2254. }
  2255. static void mov_build_index(MOVContext *mov, AVStream *st)
  2256. {
  2257. MOVStreamContext *sc = st->priv_data;
  2258. int64_t current_offset;
  2259. int64_t current_dts = 0;
  2260. unsigned int stts_index = 0;
  2261. unsigned int stsc_index = 0;
  2262. unsigned int stss_index = 0;
  2263. unsigned int stps_index = 0;
  2264. unsigned int i, j;
  2265. uint64_t stream_size = 0;
  2266. if (sc->elst_count) {
  2267. int i, edit_start_index = 0, unsupported = 0;
  2268. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2269. int64_t start_time = 0; // start time of the media
  2270. for (i = 0; i < sc->elst_count; i++) {
  2271. const MOVElst *e = &sc->elst_data[i];
  2272. if (i == 0 && e->time == -1) {
  2273. /* if empty, the first entry is the start time of the stream
  2274. * relative to the presentation itself */
  2275. empty_duration = e->duration;
  2276. edit_start_index = 1;
  2277. } else if (i == edit_start_index && e->time >= 0) {
  2278. start_time = e->time;
  2279. } else
  2280. unsupported = 1;
  2281. }
  2282. if (unsupported)
  2283. av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2284. "a/v desync might occur, patch welcome\n");
  2285. /* adjust first dts according to edit list */
  2286. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2287. if (empty_duration)
  2288. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2289. sc->time_offset = start_time - empty_duration;
  2290. current_dts = -sc->time_offset;
  2291. if (sc->ctts_count>0 && sc->stts_count>0 &&
  2292. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  2293. /* more than 16 frames delay, dts are likely wrong
  2294. this happens with files created by iMovie */
  2295. sc->wrong_dts = 1;
  2296. st->codec->has_b_frames = 1;
  2297. }
  2298. }
  2299. }
  2300. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2301. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  2302. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2303. unsigned int current_sample = 0;
  2304. unsigned int stts_sample = 0;
  2305. unsigned int sample_size;
  2306. unsigned int distance = 0;
  2307. unsigned int rap_group_index = 0;
  2308. unsigned int rap_group_sample = 0;
  2309. int64_t last_dts = 0;
  2310. int64_t dts_correction = 0;
  2311. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2312. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2313. current_dts -= sc->dts_shift;
  2314. last_dts = current_dts;
  2315. if (!sc->sample_count || st->nb_index_entries)
  2316. return;
  2317. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2318. return;
  2319. if (av_reallocp_array(&st->index_entries,
  2320. st->nb_index_entries + sc->sample_count,
  2321. sizeof(*st->index_entries)) < 0) {
  2322. st->nb_index_entries = 0;
  2323. return;
  2324. }
  2325. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2326. for (i = 0; i < sc->chunk_count; i++) {
  2327. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2328. current_offset = sc->chunk_offsets[i];
  2329. while (stsc_index + 1 < sc->stsc_count &&
  2330. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2331. stsc_index++;
  2332. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2333. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2334. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2335. sc->stsz_sample_size = sc->sample_size;
  2336. }
  2337. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2338. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2339. sc->stsz_sample_size = sc->sample_size;
  2340. }
  2341. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2342. int keyframe = 0;
  2343. if (current_sample >= sc->sample_count) {
  2344. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2345. return;
  2346. }
  2347. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2348. keyframe = 1;
  2349. if (stss_index + 1 < sc->keyframe_count)
  2350. stss_index++;
  2351. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2352. keyframe = 1;
  2353. if (stps_index + 1 < sc->stps_count)
  2354. stps_index++;
  2355. }
  2356. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2357. if (sc->rap_group[rap_group_index].index > 0)
  2358. keyframe = 1;
  2359. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2360. rap_group_sample = 0;
  2361. rap_group_index++;
  2362. }
  2363. }
  2364. if (sc->keyframe_absent
  2365. && !sc->stps_count
  2366. && !rap_group_present
  2367. && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2368. keyframe = 1;
  2369. if (keyframe)
  2370. distance = 0;
  2371. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2372. if (sc->pseudo_stream_id == -1 ||
  2373. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2374. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  2375. e->pos = current_offset;
  2376. e->timestamp = current_dts;
  2377. e->size = sample_size;
  2378. e->min_distance = distance;
  2379. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2380. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2381. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2382. current_offset, current_dts, sample_size, distance, keyframe);
  2383. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2384. ff_rfps_add_frame(mov->fc, st, current_dts);
  2385. }
  2386. current_offset += sample_size;
  2387. stream_size += sample_size;
  2388. /* A negative sample duration is invalid based on the spec,
  2389. * but some samples need it to correct the DTS. */
  2390. if (sc->stts_data[stts_index].duration < 0) {
  2391. av_log(mov->fc, AV_LOG_WARNING,
  2392. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2393. sc->stts_data[stts_index].duration, stts_index,
  2394. st->index);
  2395. dts_correction += sc->stts_data[stts_index].duration - 1;
  2396. sc->stts_data[stts_index].duration = 1;
  2397. }
  2398. current_dts += sc->stts_data[stts_index].duration;
  2399. if (!dts_correction || current_dts + dts_correction > last_dts) {
  2400. current_dts += dts_correction;
  2401. dts_correction = 0;
  2402. } else {
  2403. /* Avoid creating non-monotonous DTS */
  2404. dts_correction += current_dts - last_dts - 1;
  2405. current_dts = last_dts + 1;
  2406. }
  2407. last_dts = current_dts;
  2408. distance++;
  2409. stts_sample++;
  2410. current_sample++;
  2411. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2412. stts_sample = 0;
  2413. stts_index++;
  2414. }
  2415. }
  2416. }
  2417. if (st->duration > 0)
  2418. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2419. } else {
  2420. unsigned chunk_samples, total = 0;
  2421. // compute total chunk count
  2422. for (i = 0; i < sc->stsc_count; i++) {
  2423. unsigned count, chunk_count;
  2424. chunk_samples = sc->stsc_data[i].count;
  2425. if (i != sc->stsc_count - 1 &&
  2426. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2427. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2428. return;
  2429. }
  2430. if (sc->samples_per_frame >= 160) { // gsm
  2431. count = chunk_samples / sc->samples_per_frame;
  2432. } else if (sc->samples_per_frame > 1) {
  2433. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2434. count = (chunk_samples+samples-1) / samples;
  2435. } else {
  2436. count = (chunk_samples+1023) / 1024;
  2437. }
  2438. if (i < sc->stsc_count - 1)
  2439. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2440. else
  2441. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2442. total += chunk_count * count;
  2443. }
  2444. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2445. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2446. return;
  2447. if (av_reallocp_array(&st->index_entries,
  2448. st->nb_index_entries + total,
  2449. sizeof(*st->index_entries)) < 0) {
  2450. st->nb_index_entries = 0;
  2451. return;
  2452. }
  2453. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2454. // populate index
  2455. for (i = 0; i < sc->chunk_count; i++) {
  2456. current_offset = sc->chunk_offsets[i];
  2457. if (stsc_index + 1 < sc->stsc_count &&
  2458. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2459. stsc_index++;
  2460. chunk_samples = sc->stsc_data[stsc_index].count;
  2461. while (chunk_samples > 0) {
  2462. AVIndexEntry *e;
  2463. unsigned size, samples;
  2464. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2465. avpriv_request_sample(mov->fc,
  2466. "Zero bytes per frame, but %d samples per frame",
  2467. sc->samples_per_frame);
  2468. return;
  2469. }
  2470. if (sc->samples_per_frame >= 160) { // gsm
  2471. samples = sc->samples_per_frame;
  2472. size = sc->bytes_per_frame;
  2473. } else {
  2474. if (sc->samples_per_frame > 1) {
  2475. samples = FFMIN((1024 / sc->samples_per_frame)*
  2476. sc->samples_per_frame, chunk_samples);
  2477. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2478. } else {
  2479. samples = FFMIN(1024, chunk_samples);
  2480. size = samples * sc->sample_size;
  2481. }
  2482. }
  2483. if (st->nb_index_entries >= total) {
  2484. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2485. return;
  2486. }
  2487. e = &st->index_entries[st->nb_index_entries++];
  2488. e->pos = current_offset;
  2489. e->timestamp = current_dts;
  2490. e->size = size;
  2491. e->min_distance = 0;
  2492. e->flags = AVINDEX_KEYFRAME;
  2493. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2494. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2495. size, samples);
  2496. current_offset += size;
  2497. current_dts += samples;
  2498. chunk_samples -= samples;
  2499. }
  2500. }
  2501. }
  2502. }
  2503. static int test_same_origin(const char *src, const char *ref) {
  2504. char src_proto[64];
  2505. char ref_proto[64];
  2506. char src_auth[256];
  2507. char ref_auth[256];
  2508. char src_host[256];
  2509. char ref_host[256];
  2510. int src_port=-1;
  2511. int ref_port=-1;
  2512. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  2513. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  2514. if (strlen(src) == 0) {
  2515. return -1;
  2516. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  2517. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  2518. strlen(src_host) + 1 >= sizeof(src_host) ||
  2519. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  2520. return 0;
  2521. } else if (strcmp(src_proto, ref_proto) ||
  2522. strcmp(src_auth, ref_auth) ||
  2523. strcmp(src_host, ref_host) ||
  2524. src_port != ref_port) {
  2525. return 0;
  2526. } else
  2527. return 1;
  2528. }
  2529. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  2530. {
  2531. /* try relative path, we do not try the absolute because it can leak information about our
  2532. system to an attacker */
  2533. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2534. char filename[1025];
  2535. const char *src_path;
  2536. int i, l;
  2537. /* find a source dir */
  2538. src_path = strrchr(src, '/');
  2539. if (src_path)
  2540. src_path++;
  2541. else
  2542. src_path = src;
  2543. /* find a next level down to target */
  2544. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2545. if (ref->path[l] == '/') {
  2546. if (i == ref->nlvl_to - 1)
  2547. break;
  2548. else
  2549. i++;
  2550. }
  2551. /* compose filename if next level down to target was found */
  2552. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2553. memcpy(filename, src, src_path - src);
  2554. filename[src_path - src] = 0;
  2555. for (i = 1; i < ref->nlvl_from; i++)
  2556. av_strlcat(filename, "../", sizeof(filename));
  2557. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  2558. if (!c->use_absolute_path) {
  2559. int same_origin = test_same_origin(src, filename);
  2560. if (!same_origin) {
  2561. av_log(c->fc, AV_LOG_ERROR,
  2562. "Reference with mismatching origin, %s not tried for security reasons, "
  2563. "set demuxer option use_absolute_path to allow it anyway\n",
  2564. ref->path);
  2565. return AVERROR(ENOENT);
  2566. }
  2567. if(strstr(ref->path + l + 1, "..") ||
  2568. strstr(ref->path + l + 1, ":") ||
  2569. (ref->nlvl_from > 1 && same_origin < 0) ||
  2570. (filename[0] == '/' && src_path == src))
  2571. return AVERROR(ENOENT);
  2572. }
  2573. if (strlen(filename) + 1 == sizeof(filename))
  2574. return AVERROR(ENOENT);
  2575. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  2576. return 0;
  2577. }
  2578. } else if (c->use_absolute_path) {
  2579. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2580. "this is a possible security issue\n");
  2581. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  2582. return 0;
  2583. } else {
  2584. av_log(c->fc, AV_LOG_ERROR,
  2585. "Absolute path %s not tried for security reasons, "
  2586. "set demuxer option use_absolute_path to allow absolute paths\n",
  2587. ref->path);
  2588. }
  2589. return AVERROR(ENOENT);
  2590. }
  2591. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2592. {
  2593. if (sc->time_scale <= 0) {
  2594. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2595. sc->time_scale = c->time_scale;
  2596. if (sc->time_scale <= 0)
  2597. sc->time_scale = 1;
  2598. }
  2599. }
  2600. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2601. {
  2602. AVStream *st;
  2603. MOVStreamContext *sc;
  2604. int ret;
  2605. st = avformat_new_stream(c->fc, NULL);
  2606. if (!st) return AVERROR(ENOMEM);
  2607. st->id = c->fc->nb_streams;
  2608. sc = av_mallocz(sizeof(MOVStreamContext));
  2609. if (!sc) return AVERROR(ENOMEM);
  2610. st->priv_data = sc;
  2611. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2612. sc->ffindex = st->index;
  2613. c->trak_index = st->index;
  2614. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2615. return ret;
  2616. c->trak_index = -1;
  2617. /* sanity checks */
  2618. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2619. (!sc->sample_size && !sc->sample_count))) {
  2620. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2621. st->index);
  2622. return 0;
  2623. }
  2624. fix_timescale(c, sc);
  2625. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2626. mov_build_index(c, st);
  2627. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2628. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2629. if (c->enable_drefs) {
  2630. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  2631. av_log(c->fc, AV_LOG_ERROR,
  2632. "stream %d, error opening alias: path='%s', dir='%s', "
  2633. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2634. st->index, dref->path, dref->dir, dref->filename,
  2635. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2636. } else {
  2637. av_log(c->fc, AV_LOG_WARNING,
  2638. "Skipped opening external track: "
  2639. "stream %d, alias: path='%s', dir='%s', "
  2640. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  2641. "Set enable_drefs to allow this.\n",
  2642. st->index, dref->path, dref->dir, dref->filename,
  2643. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2644. }
  2645. } else {
  2646. sc->pb = c->fc->pb;
  2647. sc->pb_is_copied = 1;
  2648. }
  2649. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2650. if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
  2651. sc->height && sc->width &&
  2652. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  2653. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  2654. ((double)st->codec->width * sc->height), INT_MAX);
  2655. }
  2656. #if FF_API_R_FRAME_RATE
  2657. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2658. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2659. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2660. #endif
  2661. }
  2662. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2663. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  2664. TAG_IS_AVCI(st->codec->codec_tag)) {
  2665. ret = ff_generate_avci_extradata(st);
  2666. if (ret < 0)
  2667. return ret;
  2668. }
  2669. switch (st->codec->codec_id) {
  2670. #if CONFIG_H261_DECODER
  2671. case AV_CODEC_ID_H261:
  2672. #endif
  2673. #if CONFIG_H263_DECODER
  2674. case AV_CODEC_ID_H263:
  2675. #endif
  2676. #if CONFIG_MPEG4_DECODER
  2677. case AV_CODEC_ID_MPEG4:
  2678. #endif
  2679. st->codec->width = 0; /* let decoder init width/height */
  2680. st->codec->height= 0;
  2681. break;
  2682. }
  2683. // If the duration of the mp3 packets is not constant, then they could need a parser
  2684. if (st->codec->codec_id == AV_CODEC_ID_MP3
  2685. && sc->stts_count > 3
  2686. && sc->stts_count*10 > st->nb_frames
  2687. && sc->time_scale == st->codec->sample_rate) {
  2688. st->need_parsing = AVSTREAM_PARSE_FULL;
  2689. }
  2690. /* Do not need those anymore. */
  2691. av_freep(&sc->chunk_offsets);
  2692. av_freep(&sc->stsc_data);
  2693. av_freep(&sc->sample_sizes);
  2694. av_freep(&sc->keyframes);
  2695. av_freep(&sc->stts_data);
  2696. av_freep(&sc->stps_data);
  2697. av_freep(&sc->elst_data);
  2698. av_freep(&sc->rap_group);
  2699. return 0;
  2700. }
  2701. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2702. {
  2703. int ret;
  2704. c->itunes_metadata = 1;
  2705. ret = mov_read_default(c, pb, atom);
  2706. c->itunes_metadata = 0;
  2707. return ret;
  2708. }
  2709. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2710. {
  2711. uint32_t count;
  2712. uint32_t i;
  2713. if (atom.size < 8)
  2714. return 0;
  2715. avio_skip(pb, 4);
  2716. count = avio_rb32(pb);
  2717. if (count > UINT_MAX / sizeof(*c->meta_keys)) {
  2718. av_log(c->fc, AV_LOG_ERROR,
  2719. "The 'keys' atom with the invalid key count: %d\n", count);
  2720. return AVERROR_INVALIDDATA;
  2721. }
  2722. c->meta_keys_count = count + 1;
  2723. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  2724. if (!c->meta_keys)
  2725. return AVERROR(ENOMEM);
  2726. for (i = 1; i <= count; ++i) {
  2727. uint32_t key_size = avio_rb32(pb);
  2728. uint32_t type = avio_rl32(pb);
  2729. if (key_size < 8) {
  2730. av_log(c->fc, AV_LOG_ERROR,
  2731. "The key# %d in meta has invalid size: %d\n", i, key_size);
  2732. return AVERROR_INVALIDDATA;
  2733. }
  2734. key_size -= 8;
  2735. if (type != MKTAG('m','d','t','a')) {
  2736. avio_skip(pb, key_size);
  2737. }
  2738. c->meta_keys[i] = av_mallocz(key_size + 1);
  2739. if (!c->meta_keys[i])
  2740. return AVERROR(ENOMEM);
  2741. avio_read(pb, c->meta_keys[i], key_size);
  2742. }
  2743. return 0;
  2744. }
  2745. static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int64_t size)
  2746. {
  2747. int64_t end = avio_tell(pb) + size;
  2748. uint8_t *key = NULL, *val = NULL;
  2749. int i;
  2750. AVStream *st;
  2751. MOVStreamContext *sc;
  2752. if (c->fc->nb_streams < 1)
  2753. return 0;
  2754. st = c->fc->streams[c->fc->nb_streams-1];
  2755. sc = st->priv_data;
  2756. for (i = 0; i < 2; i++) {
  2757. uint8_t **p;
  2758. uint32_t len, tag;
  2759. int ret;
  2760. if (end - avio_tell(pb) <= 12)
  2761. break;
  2762. len = avio_rb32(pb);
  2763. tag = avio_rl32(pb);
  2764. avio_skip(pb, 4); // flags
  2765. if (len < 12 || len - 12 > end - avio_tell(pb))
  2766. break;
  2767. len -= 12;
  2768. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2769. p = &key;
  2770. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2771. avio_skip(pb, 4);
  2772. len -= 4;
  2773. p = &val;
  2774. } else
  2775. break;
  2776. *p = av_malloc(len + 1);
  2777. if (!*p)
  2778. break;
  2779. ret = ffio_read_size(pb, *p, len);
  2780. if (ret < 0) {
  2781. av_freep(p);
  2782. return ret;
  2783. }
  2784. (*p)[len] = 0;
  2785. }
  2786. if (key && val) {
  2787. if (strcmp(key, "iTunSMPB") == 0) {
  2788. int priming, remainder, samples;
  2789. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  2790. if(priming>0 && priming<16384)
  2791. sc->start_pad = priming;
  2792. }
  2793. }
  2794. if (strcmp(key, "cdec") != 0) {
  2795. av_dict_set(&c->fc->metadata, key, val,
  2796. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2797. key = val = NULL;
  2798. }
  2799. }
  2800. avio_seek(pb, end, SEEK_SET);
  2801. av_freep(&key);
  2802. av_freep(&val);
  2803. return 0;
  2804. }
  2805. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2806. {
  2807. int64_t end = avio_tell(pb) + atom.size;
  2808. uint32_t tag, len;
  2809. if (atom.size < 8)
  2810. goto fail;
  2811. len = avio_rb32(pb);
  2812. tag = avio_rl32(pb);
  2813. if (len > atom.size)
  2814. goto fail;
  2815. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2816. uint8_t domain[128];
  2817. int domain_len;
  2818. avio_skip(pb, 4); // flags
  2819. len -= 12;
  2820. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2821. avio_skip(pb, len - domain_len);
  2822. return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
  2823. }
  2824. fail:
  2825. av_log(c->fc, AV_LOG_VERBOSE,
  2826. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2827. return 0;
  2828. }
  2829. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2830. {
  2831. while (atom.size > 8) {
  2832. uint32_t tag = avio_rl32(pb);
  2833. atom.size -= 4;
  2834. if (tag == MKTAG('h','d','l','r')) {
  2835. avio_seek(pb, -8, SEEK_CUR);
  2836. atom.size += 8;
  2837. return mov_read_default(c, pb, atom);
  2838. }
  2839. }
  2840. return 0;
  2841. }
  2842. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2843. {
  2844. int i;
  2845. int width;
  2846. int height;
  2847. int display_matrix[3][3];
  2848. AVStream *st;
  2849. MOVStreamContext *sc;
  2850. int version;
  2851. int flags;
  2852. if (c->fc->nb_streams < 1)
  2853. return 0;
  2854. st = c->fc->streams[c->fc->nb_streams-1];
  2855. sc = st->priv_data;
  2856. version = avio_r8(pb);
  2857. flags = avio_rb24(pb);
  2858. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2859. if (version == 1) {
  2860. avio_rb64(pb);
  2861. avio_rb64(pb);
  2862. } else {
  2863. avio_rb32(pb); /* creation time */
  2864. avio_rb32(pb); /* modification time */
  2865. }
  2866. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2867. avio_rb32(pb); /* reserved */
  2868. /* highlevel (considering edits) duration in movie timebase */
  2869. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2870. avio_rb32(pb); /* reserved */
  2871. avio_rb32(pb); /* reserved */
  2872. avio_rb16(pb); /* layer */
  2873. avio_rb16(pb); /* alternate group */
  2874. avio_rb16(pb); /* volume */
  2875. avio_rb16(pb); /* reserved */
  2876. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2877. // they're kept in fixed point format through all calculations
  2878. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2879. // side data, but the scale factor is not needed to calculate aspect ratio
  2880. for (i = 0; i < 3; i++) {
  2881. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2882. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2883. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2884. }
  2885. width = avio_rb32(pb); // 16.16 fixed point track width
  2886. height = avio_rb32(pb); // 16.16 fixed point track height
  2887. sc->width = width >> 16;
  2888. sc->height = height >> 16;
  2889. // save the matrix and add rotate metadata when it is not the default
  2890. // identity
  2891. if (display_matrix[0][0] != (1 << 16) ||
  2892. display_matrix[1][1] != (1 << 16) ||
  2893. display_matrix[2][2] != (1 << 30) ||
  2894. display_matrix[0][1] || display_matrix[0][2] ||
  2895. display_matrix[1][0] || display_matrix[1][2] ||
  2896. display_matrix[2][0] || display_matrix[2][1]) {
  2897. int i, j;
  2898. double rotate;
  2899. av_freep(&sc->display_matrix);
  2900. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2901. if (!sc->display_matrix)
  2902. return AVERROR(ENOMEM);
  2903. for (i = 0; i < 3; i++)
  2904. for (j = 0; j < 3; j++)
  2905. sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  2906. rotate = av_display_rotation_get(sc->display_matrix);
  2907. if (!isnan(rotate)) {
  2908. char rotate_buf[64];
  2909. rotate = -rotate;
  2910. if (rotate < 0) // for backward compatibility
  2911. rotate += 360;
  2912. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  2913. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  2914. }
  2915. }
  2916. // transform the display width/height according to the matrix
  2917. // to keep the same scale, use [width height 1<<16]
  2918. if (width && height && sc->display_matrix) {
  2919. double disp_transform[2];
  2920. for (i = 0; i < 2; i++)
  2921. disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
  2922. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  2923. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  2924. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  2925. st->sample_aspect_ratio = av_d2q(
  2926. disp_transform[0] / disp_transform[1],
  2927. INT_MAX);
  2928. }
  2929. return 0;
  2930. }
  2931. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2932. {
  2933. MOVFragment *frag = &c->fragment;
  2934. MOVTrackExt *trex = NULL;
  2935. MOVFragmentIndex* index = NULL;
  2936. int flags, track_id, i, found = 0;
  2937. avio_r8(pb); /* version */
  2938. flags = avio_rb24(pb);
  2939. track_id = avio_rb32(pb);
  2940. if (!track_id)
  2941. return AVERROR_INVALIDDATA;
  2942. frag->track_id = track_id;
  2943. for (i = 0; i < c->trex_count; i++)
  2944. if (c->trex_data[i].track_id == frag->track_id) {
  2945. trex = &c->trex_data[i];
  2946. break;
  2947. }
  2948. if (!trex) {
  2949. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2950. return AVERROR_INVALIDDATA;
  2951. }
  2952. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2953. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2954. frag->moof_offset : frag->implicit_offset;
  2955. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2956. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2957. avio_rb32(pb) : trex->duration;
  2958. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2959. avio_rb32(pb) : trex->size;
  2960. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2961. avio_rb32(pb) : trex->flags;
  2962. frag->time = AV_NOPTS_VALUE;
  2963. for (i = 0; i < c->fragment_index_count; i++) {
  2964. int j;
  2965. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  2966. if (candidate->track_id == frag->track_id) {
  2967. av_log(c->fc, AV_LOG_DEBUG,
  2968. "found fragment index for track %u\n", frag->track_id);
  2969. index = candidate;
  2970. for (j = index->current_item; j < index->item_count; j++) {
  2971. if (frag->implicit_offset == index->items[j].moof_offset) {
  2972. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  2973. "for track %u and moof_offset %"PRId64"\n",
  2974. frag->track_id, index->items[j].moof_offset);
  2975. frag->time = index->items[j].time;
  2976. index->current_item = j + 1;
  2977. found = 1;
  2978. break;
  2979. }
  2980. }
  2981. if (found)
  2982. break;
  2983. }
  2984. }
  2985. if (index && !found) {
  2986. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  2987. "it doesn't have an (in-order) entry for moof_offset "
  2988. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  2989. }
  2990. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  2991. return 0;
  2992. }
  2993. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2994. {
  2995. c->chapter_track = avio_rb32(pb);
  2996. return 0;
  2997. }
  2998. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2999. {
  3000. MOVTrackExt *trex;
  3001. int err;
  3002. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3003. return AVERROR_INVALIDDATA;
  3004. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3005. sizeof(*c->trex_data))) < 0) {
  3006. c->trex_count = 0;
  3007. return err;
  3008. }
  3009. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3010. trex = &c->trex_data[c->trex_count++];
  3011. avio_r8(pb); /* version */
  3012. avio_rb24(pb); /* flags */
  3013. trex->track_id = avio_rb32(pb);
  3014. trex->stsd_id = avio_rb32(pb);
  3015. trex->duration = avio_rb32(pb);
  3016. trex->size = avio_rb32(pb);
  3017. trex->flags = avio_rb32(pb);
  3018. return 0;
  3019. }
  3020. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3021. {
  3022. MOVFragment *frag = &c->fragment;
  3023. AVStream *st = NULL;
  3024. MOVStreamContext *sc;
  3025. int version, i;
  3026. for (i = 0; i < c->fc->nb_streams; i++) {
  3027. if (c->fc->streams[i]->id == frag->track_id) {
  3028. st = c->fc->streams[i];
  3029. break;
  3030. }
  3031. }
  3032. if (!st) {
  3033. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3034. return AVERROR_INVALIDDATA;
  3035. }
  3036. sc = st->priv_data;
  3037. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3038. return 0;
  3039. version = avio_r8(pb);
  3040. avio_rb24(pb); /* flags */
  3041. if (version) {
  3042. sc->track_end = avio_rb64(pb);
  3043. } else {
  3044. sc->track_end = avio_rb32(pb);
  3045. }
  3046. return 0;
  3047. }
  3048. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3049. {
  3050. MOVFragment *frag = &c->fragment;
  3051. AVStream *st = NULL;
  3052. MOVStreamContext *sc;
  3053. MOVStts *ctts_data;
  3054. uint64_t offset;
  3055. int64_t dts;
  3056. int data_offset = 0;
  3057. unsigned entries, first_sample_flags = frag->flags;
  3058. int flags, distance, i, err;
  3059. for (i = 0; i < c->fc->nb_streams; i++) {
  3060. if (c->fc->streams[i]->id == frag->track_id) {
  3061. st = c->fc->streams[i];
  3062. break;
  3063. }
  3064. }
  3065. if (!st) {
  3066. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3067. return AVERROR_INVALIDDATA;
  3068. }
  3069. sc = st->priv_data;
  3070. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3071. return 0;
  3072. avio_r8(pb); /* version */
  3073. flags = avio_rb24(pb);
  3074. entries = avio_rb32(pb);
  3075. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3076. /* Always assume the presence of composition time offsets.
  3077. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3078. * 1) in the initial movie, there are no samples.
  3079. * 2) in the first movie fragment, there is only one sample without composition time offset.
  3080. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  3081. if (!sc->ctts_count && sc->sample_count)
  3082. {
  3083. /* Complement ctts table if moov atom doesn't have ctts atom. */
  3084. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3085. if (!ctts_data)
  3086. return AVERROR(ENOMEM);
  3087. sc->ctts_data = ctts_data;
  3088. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3089. sc->ctts_data[sc->ctts_count].duration = 0;
  3090. sc->ctts_count++;
  3091. }
  3092. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3093. return AVERROR_INVALIDDATA;
  3094. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3095. sizeof(*sc->ctts_data))) < 0) {
  3096. sc->ctts_count = 0;
  3097. return err;
  3098. }
  3099. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3100. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3101. dts = sc->track_end - sc->time_offset;
  3102. offset = frag->base_data_offset + data_offset;
  3103. distance = 0;
  3104. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3105. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3106. unsigned sample_size = frag->size;
  3107. int sample_flags = i ? frag->flags : first_sample_flags;
  3108. unsigned sample_duration = frag->duration;
  3109. int keyframe = 0;
  3110. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3111. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3112. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3113. sc->ctts_data[sc->ctts_count].count = 1;
  3114. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3115. avio_rb32(pb) : 0;
  3116. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3117. if (frag->time != AV_NOPTS_VALUE) {
  3118. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3119. int64_t pts = frag->time;
  3120. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3121. " sc->dts_shift %d ctts.duration %d"
  3122. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3123. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3124. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3125. dts = pts - sc->dts_shift;
  3126. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3127. dts -= sc->ctts_data[sc->ctts_count].duration;
  3128. } else {
  3129. dts -= sc->time_offset;
  3130. }
  3131. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3132. } else {
  3133. dts = frag->time;
  3134. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3135. ", using it for dts\n", dts);
  3136. }
  3137. frag->time = AV_NOPTS_VALUE;
  3138. }
  3139. sc->ctts_count++;
  3140. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3141. keyframe = 1;
  3142. else
  3143. keyframe =
  3144. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3145. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3146. if (keyframe)
  3147. distance = 0;
  3148. err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3149. keyframe ? AVINDEX_KEYFRAME : 0);
  3150. if (err < 0) {
  3151. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3152. }
  3153. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3154. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3155. offset, dts, sample_size, distance, keyframe);
  3156. distance++;
  3157. dts += sample_duration;
  3158. offset += sample_size;
  3159. sc->data_size += sample_size;
  3160. sc->duration_for_fps += sample_duration;
  3161. sc->nb_frames_for_fps ++;
  3162. }
  3163. if (pb->eof_reached)
  3164. return AVERROR_EOF;
  3165. frag->implicit_offset = offset;
  3166. sc->track_end = dts + sc->time_offset;
  3167. if (st->duration < sc->track_end)
  3168. st->duration = sc->track_end;
  3169. return 0;
  3170. }
  3171. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3172. {
  3173. int64_t offset = avio_tell(pb) + atom.size, pts;
  3174. uint8_t version;
  3175. unsigned i, track_id;
  3176. AVStream *st = NULL;
  3177. MOVStreamContext *sc;
  3178. MOVFragmentIndex *index = NULL;
  3179. MOVFragmentIndex **tmp;
  3180. AVRational timescale;
  3181. version = avio_r8(pb);
  3182. if (version > 1) {
  3183. avpriv_request_sample(c->fc, "sidx version %u", version);
  3184. return AVERROR_PATCHWELCOME;
  3185. }
  3186. avio_rb24(pb); // flags
  3187. track_id = avio_rb32(pb); // Reference ID
  3188. for (i = 0; i < c->fc->nb_streams; i++) {
  3189. if (c->fc->streams[i]->id == track_id) {
  3190. st = c->fc->streams[i];
  3191. break;
  3192. }
  3193. }
  3194. if (!st) {
  3195. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", track_id);
  3196. return AVERROR_INVALIDDATA;
  3197. }
  3198. sc = st->priv_data;
  3199. timescale = av_make_q(1, avio_rb32(pb));
  3200. if (version == 0) {
  3201. pts = avio_rb32(pb);
  3202. offset += avio_rb32(pb);
  3203. } else {
  3204. pts = avio_rb64(pb);
  3205. offset += avio_rb64(pb);
  3206. }
  3207. avio_rb16(pb); // reserved
  3208. index = av_mallocz(sizeof(MOVFragmentIndex));
  3209. if (!index)
  3210. return AVERROR(ENOMEM);
  3211. index->track_id = track_id;
  3212. index->item_count = avio_rb16(pb);
  3213. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3214. if (!index->items) {
  3215. av_freep(&index);
  3216. return AVERROR(ENOMEM);
  3217. }
  3218. for (i = 0; i < index->item_count; i++) {
  3219. uint32_t size = avio_rb32(pb);
  3220. uint32_t duration = avio_rb32(pb);
  3221. if (size & 0x80000000) {
  3222. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3223. av_freep(&index->items);
  3224. av_freep(&index);
  3225. return AVERROR_PATCHWELCOME;
  3226. }
  3227. avio_rb32(pb); // sap_flags
  3228. index->items[i].moof_offset = offset;
  3229. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3230. offset += size;
  3231. pts += duration;
  3232. }
  3233. st->duration = sc->track_end = pts;
  3234. tmp = av_realloc_array(c->fragment_index_data,
  3235. c->fragment_index_count + 1,
  3236. sizeof(MOVFragmentIndex*));
  3237. if (!tmp) {
  3238. av_freep(&index->items);
  3239. av_freep(&index);
  3240. return AVERROR(ENOMEM);
  3241. }
  3242. c->fragment_index_data = tmp;
  3243. c->fragment_index_data[c->fragment_index_count++] = index;
  3244. if (offset == avio_size(pb))
  3245. c->fragment_index_complete = 1;
  3246. return 0;
  3247. }
  3248. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3249. /* like the files created with Adobe Premiere 5.0, for samples see */
  3250. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3251. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3252. {
  3253. int err;
  3254. if (atom.size < 8)
  3255. return 0; /* continue */
  3256. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3257. avio_skip(pb, atom.size - 4);
  3258. return 0;
  3259. }
  3260. atom.type = avio_rl32(pb);
  3261. atom.size -= 8;
  3262. if (atom.type != MKTAG('m','d','a','t')) {
  3263. avio_skip(pb, atom.size);
  3264. return 0;
  3265. }
  3266. err = mov_read_mdat(c, pb, atom);
  3267. return err;
  3268. }
  3269. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3270. {
  3271. #if CONFIG_ZLIB
  3272. AVIOContext ctx;
  3273. uint8_t *cmov_data;
  3274. uint8_t *moov_data; /* uncompressed data */
  3275. long cmov_len, moov_len;
  3276. int ret = -1;
  3277. avio_rb32(pb); /* dcom atom */
  3278. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3279. return AVERROR_INVALIDDATA;
  3280. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3281. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3282. return AVERROR_INVALIDDATA;
  3283. }
  3284. avio_rb32(pb); /* cmvd atom */
  3285. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3286. return AVERROR_INVALIDDATA;
  3287. moov_len = avio_rb32(pb); /* uncompressed size */
  3288. cmov_len = atom.size - 6 * 4;
  3289. cmov_data = av_malloc(cmov_len);
  3290. if (!cmov_data)
  3291. return AVERROR(ENOMEM);
  3292. moov_data = av_malloc(moov_len);
  3293. if (!moov_data) {
  3294. av_free(cmov_data);
  3295. return AVERROR(ENOMEM);
  3296. }
  3297. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3298. if (ret < 0)
  3299. goto free_and_return;
  3300. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3301. goto free_and_return;
  3302. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3303. goto free_and_return;
  3304. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3305. atom.type = MKTAG('m','o','o','v');
  3306. atom.size = moov_len;
  3307. ret = mov_read_default(c, &ctx, atom);
  3308. free_and_return:
  3309. av_free(moov_data);
  3310. av_free(cmov_data);
  3311. return ret;
  3312. #else
  3313. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3314. return AVERROR(ENOSYS);
  3315. #endif
  3316. }
  3317. /* edit list atom */
  3318. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3319. {
  3320. MOVStreamContext *sc;
  3321. int i, edit_count, version;
  3322. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3323. return 0;
  3324. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3325. version = avio_r8(pb); /* version */
  3326. avio_rb24(pb); /* flags */
  3327. edit_count = avio_rb32(pb); /* entries */
  3328. if (!edit_count)
  3329. return 0;
  3330. if (sc->elst_data)
  3331. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3332. av_free(sc->elst_data);
  3333. sc->elst_count = 0;
  3334. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3335. if (!sc->elst_data)
  3336. return AVERROR(ENOMEM);
  3337. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3338. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3339. MOVElst *e = &sc->elst_data[i];
  3340. if (version == 1) {
  3341. e->duration = avio_rb64(pb);
  3342. e->time = avio_rb64(pb);
  3343. } else {
  3344. e->duration = avio_rb32(pb); /* segment duration */
  3345. e->time = (int32_t)avio_rb32(pb); /* media time */
  3346. }
  3347. e->rate = avio_rb32(pb) / 65536.0;
  3348. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3349. e->duration, e->time, e->rate);
  3350. }
  3351. sc->elst_count = i;
  3352. return 0;
  3353. }
  3354. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3355. {
  3356. MOVStreamContext *sc;
  3357. if (c->fc->nb_streams < 1)
  3358. return AVERROR_INVALIDDATA;
  3359. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3360. sc->timecode_track = avio_rb32(pb);
  3361. return 0;
  3362. }
  3363. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3364. {
  3365. int ret;
  3366. uint8_t uuid[16];
  3367. static const uint8_t uuid_isml_manifest[] = {
  3368. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3369. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3370. };
  3371. static const uint8_t uuid_xmp[] = {
  3372. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  3373. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  3374. };
  3375. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  3376. return AVERROR_INVALIDDATA;
  3377. ret = avio_read(pb, uuid, sizeof(uuid));
  3378. if (ret < 0) {
  3379. return ret;
  3380. } else if (ret != sizeof(uuid)) {
  3381. return AVERROR_INVALIDDATA;
  3382. }
  3383. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  3384. uint8_t *buffer, *ptr;
  3385. char *endptr;
  3386. size_t len = atom.size - sizeof(uuid);
  3387. if (len < 4) {
  3388. return AVERROR_INVALIDDATA;
  3389. }
  3390. ret = avio_skip(pb, 4); // zeroes
  3391. len -= 4;
  3392. buffer = av_mallocz(len + 1);
  3393. if (!buffer) {
  3394. return AVERROR(ENOMEM);
  3395. }
  3396. ret = avio_read(pb, buffer, len);
  3397. if (ret < 0) {
  3398. av_free(buffer);
  3399. return ret;
  3400. } else if (ret != len) {
  3401. av_free(buffer);
  3402. return AVERROR_INVALIDDATA;
  3403. }
  3404. ptr = buffer;
  3405. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  3406. ptr += sizeof("systemBitrate=\"") - 1;
  3407. c->bitrates_count++;
  3408. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  3409. if (!c->bitrates) {
  3410. c->bitrates_count = 0;
  3411. av_free(buffer);
  3412. return AVERROR(ENOMEM);
  3413. }
  3414. errno = 0;
  3415. ret = strtol(ptr, &endptr, 10);
  3416. if (ret < 0 || errno || *endptr != '"') {
  3417. c->bitrates[c->bitrates_count - 1] = 0;
  3418. } else {
  3419. c->bitrates[c->bitrates_count - 1] = ret;
  3420. }
  3421. }
  3422. av_free(buffer);
  3423. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  3424. uint8_t *buffer;
  3425. size_t len = atom.size - sizeof(uuid);
  3426. buffer = av_mallocz(len + 1);
  3427. if (!buffer) {
  3428. return AVERROR(ENOMEM);
  3429. }
  3430. ret = avio_read(pb, buffer, len);
  3431. if (ret < 0) {
  3432. av_free(buffer);
  3433. return ret;
  3434. } else if (ret != len) {
  3435. av_free(buffer);
  3436. return AVERROR_INVALIDDATA;
  3437. }
  3438. if (c->export_xmp) {
  3439. buffer[len] = '\0';
  3440. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  3441. }
  3442. av_free(buffer);
  3443. }
  3444. return 0;
  3445. }
  3446. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3447. {
  3448. int ret;
  3449. uint8_t content[16];
  3450. if (atom.size < 8)
  3451. return 0;
  3452. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  3453. if (ret < 0)
  3454. return ret;
  3455. if ( !c->found_moov
  3456. && !c->found_mdat
  3457. && !memcmp(content, "Anevia\x1A\x1A", 8)
  3458. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  3459. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  3460. }
  3461. return 0;
  3462. }
  3463. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3464. {
  3465. uint32_t format = avio_rl32(pb);
  3466. MOVStreamContext *sc;
  3467. enum AVCodecID id;
  3468. AVStream *st;
  3469. if (c->fc->nb_streams < 1)
  3470. return 0;
  3471. st = c->fc->streams[c->fc->nb_streams - 1];
  3472. sc = st->priv_data;
  3473. switch (sc->format)
  3474. {
  3475. case MKTAG('e','n','c','v'): // encrypted video
  3476. case MKTAG('e','n','c','a'): // encrypted audio
  3477. id = mov_codec_id(st, format);
  3478. if (st->codec->codec_id != AV_CODEC_ID_NONE &&
  3479. st->codec->codec_id != id) {
  3480. av_log(c->fc, AV_LOG_WARNING,
  3481. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  3482. (char*)&format, st->codec->codec_id);
  3483. break;
  3484. }
  3485. st->codec->codec_id = id;
  3486. sc->format = format;
  3487. break;
  3488. default:
  3489. if (format != sc->format) {
  3490. av_log(c->fc, AV_LOG_WARNING,
  3491. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  3492. (char*)&format, (char*)&sc->format);
  3493. }
  3494. break;
  3495. }
  3496. return 0;
  3497. }
  3498. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3499. {
  3500. AVStream *st;
  3501. MOVStreamContext *sc;
  3502. size_t auxiliary_info_size;
  3503. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  3504. return 0;
  3505. st = c->fc->streams[c->fc->nb_streams - 1];
  3506. sc = st->priv_data;
  3507. if (sc->cenc.aes_ctr) {
  3508. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  3509. return AVERROR_INVALIDDATA;
  3510. }
  3511. avio_r8(pb); /* version */
  3512. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  3513. avio_rb32(pb); /* entries */
  3514. if (atom.size < 8) {
  3515. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
  3516. return AVERROR_INVALIDDATA;
  3517. }
  3518. /* save the auxiliary info as is */
  3519. auxiliary_info_size = atom.size - 8;
  3520. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  3521. if (!sc->cenc.auxiliary_info) {
  3522. return AVERROR(ENOMEM);
  3523. }
  3524. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  3525. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  3526. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  3527. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  3528. return AVERROR_INVALIDDATA;
  3529. }
  3530. /* initialize the cipher */
  3531. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  3532. if (!sc->cenc.aes_ctr) {
  3533. return AVERROR(ENOMEM);
  3534. }
  3535. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  3536. }
  3537. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
  3538. {
  3539. uint32_t encrypted_bytes;
  3540. uint16_t subsample_count;
  3541. uint16_t clear_bytes;
  3542. uint8_t* input_end = input + size;
  3543. /* read the iv */
  3544. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3545. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  3546. return AVERROR_INVALIDDATA;
  3547. }
  3548. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  3549. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  3550. if (!sc->cenc.use_subsamples)
  3551. {
  3552. /* decrypt the whole packet */
  3553. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  3554. return 0;
  3555. }
  3556. /* read the subsample count */
  3557. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3558. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  3559. return AVERROR_INVALIDDATA;
  3560. }
  3561. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  3562. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3563. for (; subsample_count > 0; subsample_count--)
  3564. {
  3565. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3566. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  3567. return AVERROR_INVALIDDATA;
  3568. }
  3569. /* read the number of clear / encrypted bytes */
  3570. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  3571. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3572. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  3573. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  3574. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  3575. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  3576. return AVERROR_INVALIDDATA;
  3577. }
  3578. /* skip the clear bytes */
  3579. input += clear_bytes;
  3580. /* decrypt the encrypted bytes */
  3581. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  3582. input += encrypted_bytes;
  3583. }
  3584. if (input < input_end) {
  3585. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  3586. return AVERROR_INVALIDDATA;
  3587. }
  3588. return 0;
  3589. }
  3590. static const MOVParseTableEntry mov_default_parse_table[] = {
  3591. { MKTAG('A','C','L','R'), mov_read_aclr },
  3592. { MKTAG('A','P','R','G'), mov_read_avid },
  3593. { MKTAG('A','A','L','P'), mov_read_avid },
  3594. { MKTAG('A','R','E','S'), mov_read_ares },
  3595. { MKTAG('a','v','s','s'), mov_read_avss },
  3596. { MKTAG('c','h','p','l'), mov_read_chpl },
  3597. { MKTAG('c','o','6','4'), mov_read_stco },
  3598. { MKTAG('c','o','l','r'), mov_read_colr },
  3599. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  3600. { MKTAG('d','i','n','f'), mov_read_default },
  3601. { MKTAG('D','p','x','E'), mov_read_dpxe },
  3602. { MKTAG('d','r','e','f'), mov_read_dref },
  3603. { MKTAG('e','d','t','s'), mov_read_default },
  3604. { MKTAG('e','l','s','t'), mov_read_elst },
  3605. { MKTAG('e','n','d','a'), mov_read_enda },
  3606. { MKTAG('f','i','e','l'), mov_read_fiel },
  3607. { MKTAG('a','d','r','m'), mov_read_adrm },
  3608. { MKTAG('f','t','y','p'), mov_read_ftyp },
  3609. { MKTAG('g','l','b','l'), mov_read_glbl },
  3610. { MKTAG('h','d','l','r'), mov_read_hdlr },
  3611. { MKTAG('i','l','s','t'), mov_read_ilst },
  3612. { MKTAG('j','p','2','h'), mov_read_jp2h },
  3613. { MKTAG('m','d','a','t'), mov_read_mdat },
  3614. { MKTAG('m','d','h','d'), mov_read_mdhd },
  3615. { MKTAG('m','d','i','a'), mov_read_default },
  3616. { MKTAG('m','e','t','a'), mov_read_meta },
  3617. { MKTAG('m','i','n','f'), mov_read_default },
  3618. { MKTAG('m','o','o','f'), mov_read_moof },
  3619. { MKTAG('m','o','o','v'), mov_read_moov },
  3620. { MKTAG('m','v','e','x'), mov_read_default },
  3621. { MKTAG('m','v','h','d'), mov_read_mvhd },
  3622. { MKTAG('S','M','I',' '), mov_read_svq3 },
  3623. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  3624. { MKTAG('a','v','c','C'), mov_read_glbl },
  3625. { MKTAG('p','a','s','p'), mov_read_pasp },
  3626. { MKTAG('s','i','d','x'), mov_read_sidx },
  3627. { MKTAG('s','t','b','l'), mov_read_default },
  3628. { MKTAG('s','t','c','o'), mov_read_stco },
  3629. { MKTAG('s','t','p','s'), mov_read_stps },
  3630. { MKTAG('s','t','r','f'), mov_read_strf },
  3631. { MKTAG('s','t','s','c'), mov_read_stsc },
  3632. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  3633. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  3634. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  3635. { MKTAG('s','t','t','s'), mov_read_stts },
  3636. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  3637. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  3638. { MKTAG('t','f','d','t'), mov_read_tfdt },
  3639. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  3640. { MKTAG('t','r','a','k'), mov_read_trak },
  3641. { MKTAG('t','r','a','f'), mov_read_default },
  3642. { MKTAG('t','r','e','f'), mov_read_default },
  3643. { MKTAG('t','m','c','d'), mov_read_tmcd },
  3644. { MKTAG('c','h','a','p'), mov_read_chap },
  3645. { MKTAG('t','r','e','x'), mov_read_trex },
  3646. { MKTAG('t','r','u','n'), mov_read_trun },
  3647. { MKTAG('u','d','t','a'), mov_read_default },
  3648. { MKTAG('w','a','v','e'), mov_read_wave },
  3649. { MKTAG('e','s','d','s'), mov_read_esds },
  3650. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  3651. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  3652. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  3653. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  3654. { MKTAG('w','f','e','x'), mov_read_wfex },
  3655. { MKTAG('c','m','o','v'), mov_read_cmov },
  3656. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  3657. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  3658. { MKTAG('s','b','g','p'), mov_read_sbgp },
  3659. { MKTAG('h','v','c','C'), mov_read_glbl },
  3660. { MKTAG('u','u','i','d'), mov_read_uuid },
  3661. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  3662. { MKTAG('f','r','e','e'), mov_read_free },
  3663. { MKTAG('-','-','-','-'), mov_read_custom },
  3664. { MKTAG('s','i','n','f'), mov_read_default },
  3665. { MKTAG('f','r','m','a'), mov_read_frma },
  3666. { MKTAG('s','e','n','c'), mov_read_senc },
  3667. { 0, NULL }
  3668. };
  3669. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3670. {
  3671. int64_t total_size = 0;
  3672. MOVAtom a;
  3673. int i;
  3674. if (c->atom_depth > 10) {
  3675. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  3676. return AVERROR_INVALIDDATA;
  3677. }
  3678. c->atom_depth ++;
  3679. if (atom.size < 0)
  3680. atom.size = INT64_MAX;
  3681. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  3682. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  3683. a.size = atom.size;
  3684. a.type=0;
  3685. if (atom.size >= 8) {
  3686. a.size = avio_rb32(pb);
  3687. a.type = avio_rl32(pb);
  3688. if (a.type == MKTAG('f','r','e','e') &&
  3689. a.size >= 8 &&
  3690. c->moov_retry) {
  3691. uint8_t buf[8];
  3692. uint32_t *type = (uint32_t *)buf + 1;
  3693. if (avio_read(pb, buf, 8) != 8)
  3694. return AVERROR_INVALIDDATA;
  3695. avio_seek(pb, -8, SEEK_CUR);
  3696. if (*type == MKTAG('m','v','h','d') ||
  3697. *type == MKTAG('c','m','o','v')) {
  3698. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  3699. a.type = MKTAG('m','o','o','v');
  3700. }
  3701. }
  3702. if (atom.type != MKTAG('r','o','o','t') &&
  3703. atom.type != MKTAG('m','o','o','v'))
  3704. {
  3705. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  3706. {
  3707. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  3708. avio_skip(pb, -8);
  3709. c->atom_depth --;
  3710. return 0;
  3711. }
  3712. }
  3713. total_size += 8;
  3714. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  3715. a.size = avio_rb64(pb) - 8;
  3716. total_size += 8;
  3717. }
  3718. }
  3719. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  3720. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  3721. if (a.size == 0) {
  3722. a.size = atom.size - total_size + 8;
  3723. }
  3724. a.size -= 8;
  3725. if (a.size < 0)
  3726. break;
  3727. a.size = FFMIN(a.size, atom.size - total_size);
  3728. for (i = 0; mov_default_parse_table[i].type; i++)
  3729. if (mov_default_parse_table[i].type == a.type) {
  3730. parse = mov_default_parse_table[i].parse;
  3731. break;
  3732. }
  3733. // container is user data
  3734. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  3735. atom.type == MKTAG('i','l','s','t')))
  3736. parse = mov_read_udta_string;
  3737. // Supports parsing the QuickTime Metadata Keys.
  3738. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  3739. if (!parse && c->found_hdlr_mdta &&
  3740. atom.type == MKTAG('m','e','t','a') &&
  3741. a.type == MKTAG('k','e','y','s')) {
  3742. parse = mov_read_keys;
  3743. }
  3744. if (!parse) { /* skip leaf atoms data */
  3745. avio_skip(pb, a.size);
  3746. } else {
  3747. int64_t start_pos = avio_tell(pb);
  3748. int64_t left;
  3749. int err = parse(c, pb, a);
  3750. if (err < 0) {
  3751. c->atom_depth --;
  3752. return err;
  3753. }
  3754. if (c->found_moov && c->found_mdat &&
  3755. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  3756. start_pos + a.size == avio_size(pb))) {
  3757. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  3758. c->next_root_atom = start_pos + a.size;
  3759. c->atom_depth --;
  3760. return 0;
  3761. }
  3762. left = a.size - avio_tell(pb) + start_pos;
  3763. if (left > 0) /* skip garbage at atom end */
  3764. avio_skip(pb, left);
  3765. else if (left < 0) {
  3766. av_log(c->fc, AV_LOG_WARNING,
  3767. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  3768. (char*)&a.type, -left);
  3769. avio_seek(pb, left, SEEK_CUR);
  3770. }
  3771. }
  3772. total_size += a.size;
  3773. }
  3774. if (total_size < atom.size && atom.size < 0x7ffff)
  3775. avio_skip(pb, atom.size - total_size);
  3776. c->atom_depth --;
  3777. return 0;
  3778. }
  3779. static int mov_probe(AVProbeData *p)
  3780. {
  3781. int64_t offset;
  3782. uint32_t tag;
  3783. int score = 0;
  3784. int moov_offset = -1;
  3785. /* check file header */
  3786. offset = 0;
  3787. for (;;) {
  3788. /* ignore invalid offset */
  3789. if ((offset + 8) > (unsigned int)p->buf_size)
  3790. break;
  3791. tag = AV_RL32(p->buf + offset + 4);
  3792. switch(tag) {
  3793. /* check for obvious tags */
  3794. case MKTAG('m','o','o','v'):
  3795. moov_offset = offset + 4;
  3796. case MKTAG('m','d','a','t'):
  3797. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3798. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3799. case MKTAG('f','t','y','p'):
  3800. if (AV_RB32(p->buf+offset) < 8 &&
  3801. (AV_RB32(p->buf+offset) != 1 ||
  3802. offset + 12 > (unsigned int)p->buf_size ||
  3803. AV_RB64(p->buf+offset + 8) == 0)) {
  3804. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3805. } else if (tag == MKTAG('f','t','y','p') &&
  3806. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  3807. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  3808. )) {
  3809. score = FFMAX(score, 5);
  3810. } else {
  3811. score = AVPROBE_SCORE_MAX;
  3812. }
  3813. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3814. break;
  3815. /* those are more common words, so rate then a bit less */
  3816. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3817. case MKTAG('w','i','d','e'):
  3818. case MKTAG('f','r','e','e'):
  3819. case MKTAG('j','u','n','k'):
  3820. case MKTAG('p','i','c','t'):
  3821. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  3822. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3823. break;
  3824. case MKTAG(0x82,0x82,0x7f,0x7d):
  3825. case MKTAG('s','k','i','p'):
  3826. case MKTAG('u','u','i','d'):
  3827. case MKTAG('p','r','f','l'):
  3828. /* if we only find those cause probedata is too small at least rate them */
  3829. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3830. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3831. break;
  3832. default:
  3833. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3834. }
  3835. }
  3836. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  3837. /* moov atom in the header - we should make sure that this is not a
  3838. * MOV-packed MPEG-PS */
  3839. offset = moov_offset;
  3840. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  3841. /* We found an actual hdlr atom */
  3842. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  3843. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  3844. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  3845. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  3846. /* We found a media handler reference atom describing an
  3847. * MPEG-PS-in-MOV, return a
  3848. * low score to force expanding the probe window until
  3849. * mpegps_probe finds what it needs */
  3850. return 5;
  3851. }else
  3852. /* Keep looking */
  3853. offset+=2;
  3854. }
  3855. }
  3856. return score;
  3857. }
  3858. // must be done after parsing all trak because there's no order requirement
  3859. static void mov_read_chapters(AVFormatContext *s)
  3860. {
  3861. MOVContext *mov = s->priv_data;
  3862. AVStream *st = NULL;
  3863. MOVStreamContext *sc;
  3864. int64_t cur_pos;
  3865. int i;
  3866. for (i = 0; i < s->nb_streams; i++)
  3867. if (s->streams[i]->id == mov->chapter_track) {
  3868. st = s->streams[i];
  3869. break;
  3870. }
  3871. if (!st) {
  3872. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  3873. return;
  3874. }
  3875. st->discard = AVDISCARD_ALL;
  3876. sc = st->priv_data;
  3877. cur_pos = avio_tell(sc->pb);
  3878. for (i = 0; i < st->nb_index_entries; i++) {
  3879. AVIndexEntry *sample = &st->index_entries[i];
  3880. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  3881. uint8_t *title;
  3882. uint16_t ch;
  3883. int len, title_len;
  3884. if (end < sample->timestamp) {
  3885. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  3886. end = AV_NOPTS_VALUE;
  3887. }
  3888. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3889. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  3890. goto finish;
  3891. }
  3892. // the first two bytes are the length of the title
  3893. len = avio_rb16(sc->pb);
  3894. if (len > sample->size-2)
  3895. continue;
  3896. title_len = 2*len + 1;
  3897. if (!(title = av_mallocz(title_len)))
  3898. goto finish;
  3899. // The samples could theoretically be in any encoding if there's an encd
  3900. // atom following, but in practice are only utf-8 or utf-16, distinguished
  3901. // instead by the presence of a BOM
  3902. if (!len) {
  3903. title[0] = 0;
  3904. } else {
  3905. ch = avio_rb16(sc->pb);
  3906. if (ch == 0xfeff)
  3907. avio_get_str16be(sc->pb, len, title, title_len);
  3908. else if (ch == 0xfffe)
  3909. avio_get_str16le(sc->pb, len, title, title_len);
  3910. else {
  3911. AV_WB16(title, ch);
  3912. if (len == 1 || len == 2)
  3913. title[len] = 0;
  3914. else
  3915. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  3916. }
  3917. }
  3918. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  3919. av_freep(&title);
  3920. }
  3921. finish:
  3922. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3923. }
  3924. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  3925. uint32_t value, int flags)
  3926. {
  3927. AVTimecode tc;
  3928. char buf[AV_TIMECODE_STR_SIZE];
  3929. AVRational rate = {st->codec->time_base.den,
  3930. st->codec->time_base.num};
  3931. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  3932. if (ret < 0)
  3933. return ret;
  3934. av_dict_set(&st->metadata, "timecode",
  3935. av_timecode_make_string(&tc, buf, value), 0);
  3936. return 0;
  3937. }
  3938. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  3939. {
  3940. MOVStreamContext *sc = st->priv_data;
  3941. int flags = 0;
  3942. int64_t cur_pos = avio_tell(sc->pb);
  3943. uint32_t value;
  3944. if (!st->nb_index_entries)
  3945. return -1;
  3946. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  3947. value = avio_rb32(s->pb);
  3948. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  3949. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  3950. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  3951. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  3952. * not the case) and thus assume "frame number format" instead of QT one.
  3953. * No sample with tmcd track can be found with a QT timecode at the moment,
  3954. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  3955. * format). */
  3956. parse_timecode_in_framenum_format(s, st, value, flags);
  3957. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3958. return 0;
  3959. }
  3960. static int mov_read_close(AVFormatContext *s)
  3961. {
  3962. MOVContext *mov = s->priv_data;
  3963. int i, j;
  3964. for (i = 0; i < s->nb_streams; i++) {
  3965. AVStream *st = s->streams[i];
  3966. MOVStreamContext *sc = st->priv_data;
  3967. if (!sc)
  3968. continue;
  3969. av_freep(&sc->ctts_data);
  3970. for (j = 0; j < sc->drefs_count; j++) {
  3971. av_freep(&sc->drefs[j].path);
  3972. av_freep(&sc->drefs[j].dir);
  3973. }
  3974. av_freep(&sc->drefs);
  3975. sc->drefs_count = 0;
  3976. if (!sc->pb_is_copied)
  3977. ff_format_io_close(s, &sc->pb);
  3978. sc->pb = NULL;
  3979. av_freep(&sc->chunk_offsets);
  3980. av_freep(&sc->stsc_data);
  3981. av_freep(&sc->sample_sizes);
  3982. av_freep(&sc->keyframes);
  3983. av_freep(&sc->stts_data);
  3984. av_freep(&sc->stps_data);
  3985. av_freep(&sc->elst_data);
  3986. av_freep(&sc->rap_group);
  3987. av_freep(&sc->display_matrix);
  3988. av_freep(&sc->cenc.auxiliary_info);
  3989. av_aes_ctr_free(sc->cenc.aes_ctr);
  3990. }
  3991. if (mov->dv_demux) {
  3992. avformat_free_context(mov->dv_fctx);
  3993. mov->dv_fctx = NULL;
  3994. }
  3995. if (mov->meta_keys) {
  3996. for (i = 1; i < mov->meta_keys_count; i++) {
  3997. av_freep(&mov->meta_keys[i]);
  3998. }
  3999. av_freep(&mov->meta_keys);
  4000. }
  4001. av_freep(&mov->trex_data);
  4002. av_freep(&mov->bitrates);
  4003. for (i = 0; i < mov->fragment_index_count; i++) {
  4004. MOVFragmentIndex* index = mov->fragment_index_data[i];
  4005. av_freep(&index->items);
  4006. av_freep(&mov->fragment_index_data[i]);
  4007. }
  4008. av_freep(&mov->fragment_index_data);
  4009. av_freep(&mov->aes_decrypt);
  4010. return 0;
  4011. }
  4012. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  4013. {
  4014. int i;
  4015. for (i = 0; i < s->nb_streams; i++) {
  4016. AVStream *st = s->streams[i];
  4017. MOVStreamContext *sc = st->priv_data;
  4018. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  4019. sc->timecode_track == tmcd_id)
  4020. return 1;
  4021. }
  4022. return 0;
  4023. }
  4024. /* look for a tmcd track not referenced by any video track, and export it globally */
  4025. static void export_orphan_timecode(AVFormatContext *s)
  4026. {
  4027. int i;
  4028. for (i = 0; i < s->nb_streams; i++) {
  4029. AVStream *st = s->streams[i];
  4030. if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
  4031. !tmcd_is_referenced(s, i + 1)) {
  4032. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  4033. if (tcr) {
  4034. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  4035. break;
  4036. }
  4037. }
  4038. }
  4039. }
  4040. static int read_tfra(MOVContext *mov, AVIOContext *f)
  4041. {
  4042. MOVFragmentIndex* index = NULL;
  4043. int version, fieldlength, i, j;
  4044. int64_t pos = avio_tell(f);
  4045. uint32_t size = avio_rb32(f);
  4046. void *tmp;
  4047. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  4048. return 1;
  4049. }
  4050. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  4051. index = av_mallocz(sizeof(MOVFragmentIndex));
  4052. if (!index) {
  4053. return AVERROR(ENOMEM);
  4054. }
  4055. tmp = av_realloc_array(mov->fragment_index_data,
  4056. mov->fragment_index_count + 1,
  4057. sizeof(MOVFragmentIndex*));
  4058. if (!tmp) {
  4059. av_freep(&index);
  4060. return AVERROR(ENOMEM);
  4061. }
  4062. mov->fragment_index_data = tmp;
  4063. mov->fragment_index_data[mov->fragment_index_count++] = index;
  4064. version = avio_r8(f);
  4065. avio_rb24(f);
  4066. index->track_id = avio_rb32(f);
  4067. fieldlength = avio_rb32(f);
  4068. index->item_count = avio_rb32(f);
  4069. index->items = av_mallocz_array(
  4070. index->item_count, sizeof(MOVFragmentIndexItem));
  4071. if (!index->items) {
  4072. index->item_count = 0;
  4073. return AVERROR(ENOMEM);
  4074. }
  4075. for (i = 0; i < index->item_count; i++) {
  4076. int64_t time, offset;
  4077. if (version == 1) {
  4078. time = avio_rb64(f);
  4079. offset = avio_rb64(f);
  4080. } else {
  4081. time = avio_rb32(f);
  4082. offset = avio_rb32(f);
  4083. }
  4084. index->items[i].time = time;
  4085. index->items[i].moof_offset = offset;
  4086. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  4087. avio_r8(f);
  4088. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  4089. avio_r8(f);
  4090. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  4091. avio_r8(f);
  4092. }
  4093. avio_seek(f, pos + size, SEEK_SET);
  4094. return 0;
  4095. }
  4096. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  4097. {
  4098. int64_t stream_size = avio_size(f);
  4099. int64_t original_pos = avio_tell(f);
  4100. int64_t seek_ret;
  4101. int32_t mfra_size;
  4102. int ret = -1;
  4103. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  4104. ret = seek_ret;
  4105. goto fail;
  4106. }
  4107. mfra_size = avio_rb32(f);
  4108. if (mfra_size < 0 || mfra_size > stream_size) {
  4109. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  4110. goto fail;
  4111. }
  4112. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  4113. ret = seek_ret;
  4114. goto fail;
  4115. }
  4116. if (avio_rb32(f) != mfra_size) {
  4117. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  4118. goto fail;
  4119. }
  4120. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  4121. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  4122. goto fail;
  4123. }
  4124. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  4125. do {
  4126. ret = read_tfra(c, f);
  4127. if (ret < 0)
  4128. goto fail;
  4129. } while (!ret);
  4130. ret = 0;
  4131. fail:
  4132. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  4133. if (seek_ret < 0) {
  4134. av_log(c->fc, AV_LOG_ERROR,
  4135. "failed to seek back after looking for mfra\n");
  4136. ret = seek_ret;
  4137. }
  4138. return ret;
  4139. }
  4140. static int mov_read_header(AVFormatContext *s)
  4141. {
  4142. MOVContext *mov = s->priv_data;
  4143. AVIOContext *pb = s->pb;
  4144. int j, err;
  4145. MOVAtom atom = { AV_RL32("root") };
  4146. int i;
  4147. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  4148. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  4149. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  4150. return AVERROR(EINVAL);
  4151. }
  4152. mov->fc = s;
  4153. mov->trak_index = -1;
  4154. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  4155. if (pb->seekable)
  4156. atom.size = avio_size(pb);
  4157. else
  4158. atom.size = INT64_MAX;
  4159. /* check MOV header */
  4160. do {
  4161. if (mov->moov_retry)
  4162. avio_seek(pb, 0, SEEK_SET);
  4163. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  4164. av_log(s, AV_LOG_ERROR, "error reading header\n");
  4165. mov_read_close(s);
  4166. return err;
  4167. }
  4168. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  4169. if (!mov->found_moov) {
  4170. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  4171. mov_read_close(s);
  4172. return AVERROR_INVALIDDATA;
  4173. }
  4174. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  4175. if (pb->seekable) {
  4176. if (mov->chapter_track > 0 && !mov->ignore_chapters)
  4177. mov_read_chapters(s);
  4178. for (i = 0; i < s->nb_streams; i++)
  4179. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  4180. mov_read_timecode_track(s, s->streams[i]);
  4181. }
  4182. /* copy timecode metadata from tmcd tracks to the related video streams */
  4183. for (i = 0; i < s->nb_streams; i++) {
  4184. AVStream *st = s->streams[i];
  4185. MOVStreamContext *sc = st->priv_data;
  4186. if (sc->timecode_track > 0) {
  4187. AVDictionaryEntry *tcr;
  4188. int tmcd_st_id = -1;
  4189. for (j = 0; j < s->nb_streams; j++)
  4190. if (s->streams[j]->id == sc->timecode_track)
  4191. tmcd_st_id = j;
  4192. if (tmcd_st_id < 0 || tmcd_st_id == i)
  4193. continue;
  4194. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  4195. if (tcr)
  4196. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  4197. }
  4198. }
  4199. export_orphan_timecode(s);
  4200. for (i = 0; i < s->nb_streams; i++) {
  4201. AVStream *st = s->streams[i];
  4202. MOVStreamContext *sc = st->priv_data;
  4203. fix_timescale(mov, sc);
  4204. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  4205. st->skip_samples = sc->start_pad;
  4206. }
  4207. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  4208. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  4209. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  4210. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4211. if (st->codec->width <= 0 || st->codec->height <= 0) {
  4212. st->codec->width = sc->width;
  4213. st->codec->height = sc->height;
  4214. }
  4215. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  4216. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  4217. return err;
  4218. }
  4219. }
  4220. if (mov->handbrake_version &&
  4221. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  4222. st->codec->codec_id == AV_CODEC_ID_MP3
  4223. ) {
  4224. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  4225. st->need_parsing = AVSTREAM_PARSE_FULL;
  4226. }
  4227. }
  4228. if (mov->trex_data) {
  4229. for (i = 0; i < s->nb_streams; i++) {
  4230. AVStream *st = s->streams[i];
  4231. MOVStreamContext *sc = st->priv_data;
  4232. if (st->duration > 0)
  4233. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  4234. }
  4235. }
  4236. if (mov->use_mfra_for > 0) {
  4237. for (i = 0; i < s->nb_streams; i++) {
  4238. AVStream *st = s->streams[i];
  4239. MOVStreamContext *sc = st->priv_data;
  4240. if (sc->duration_for_fps > 0) {
  4241. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
  4242. sc->duration_for_fps;
  4243. }
  4244. }
  4245. }
  4246. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  4247. if (mov->bitrates[i]) {
  4248. s->streams[i]->codec->bit_rate = mov->bitrates[i];
  4249. }
  4250. }
  4251. ff_rfps_calculate(s);
  4252. for (i = 0; i < s->nb_streams; i++) {
  4253. AVStream *st = s->streams[i];
  4254. MOVStreamContext *sc = st->priv_data;
  4255. switch (st->codec->codec_type) {
  4256. case AVMEDIA_TYPE_AUDIO:
  4257. err = ff_replaygain_export(st, s->metadata);
  4258. if (err < 0) {
  4259. mov_read_close(s);
  4260. return err;
  4261. }
  4262. break;
  4263. case AVMEDIA_TYPE_VIDEO:
  4264. if (sc->display_matrix) {
  4265. AVPacketSideData *sd, *tmp;
  4266. tmp = av_realloc_array(st->side_data,
  4267. st->nb_side_data + 1, sizeof(*tmp));
  4268. if (!tmp)
  4269. return AVERROR(ENOMEM);
  4270. st->side_data = tmp;
  4271. st->nb_side_data++;
  4272. sd = &st->side_data[st->nb_side_data - 1];
  4273. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  4274. sd->size = sizeof(int32_t) * 9;
  4275. sd->data = (uint8_t*)sc->display_matrix;
  4276. sc->display_matrix = NULL;
  4277. }
  4278. break;
  4279. }
  4280. }
  4281. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  4282. return 0;
  4283. }
  4284. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  4285. {
  4286. AVIndexEntry *sample = NULL;
  4287. int64_t best_dts = INT64_MAX;
  4288. int i;
  4289. for (i = 0; i < s->nb_streams; i++) {
  4290. AVStream *avst = s->streams[i];
  4291. MOVStreamContext *msc = avst->priv_data;
  4292. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  4293. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  4294. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  4295. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  4296. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  4297. (s->pb->seekable &&
  4298. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  4299. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  4300. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  4301. sample = current_sample;
  4302. best_dts = dts;
  4303. *st = avst;
  4304. }
  4305. }
  4306. }
  4307. return sample;
  4308. }
  4309. static int should_retry(AVIOContext *pb, int error_code) {
  4310. if (error_code == AVERROR_EOF || avio_feof(pb))
  4311. return 0;
  4312. return 1;
  4313. }
  4314. static int mov_switch_root(AVFormatContext *s, int64_t target)
  4315. {
  4316. MOVContext *mov = s->priv_data;
  4317. int i, j;
  4318. int already_read = 0;
  4319. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  4320. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  4321. return AVERROR_INVALIDDATA;
  4322. }
  4323. mov->next_root_atom = 0;
  4324. for (i = 0; i < mov->fragment_index_count; i++) {
  4325. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4326. int found = 0;
  4327. for (j = 0; j < index->item_count; j++) {
  4328. MOVFragmentIndexItem *item = &index->items[j];
  4329. if (found) {
  4330. mov->next_root_atom = item->moof_offset;
  4331. break; // Advance to next index in outer loop
  4332. } else if (item->moof_offset == target) {
  4333. index->current_item = FFMIN(j, index->current_item);
  4334. if (item->headers_read)
  4335. already_read = 1;
  4336. item->headers_read = 1;
  4337. found = 1;
  4338. }
  4339. }
  4340. if (!found)
  4341. index->current_item = 0;
  4342. }
  4343. if (already_read)
  4344. return 0;
  4345. mov->found_mdat = 0;
  4346. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  4347. avio_feof(s->pb))
  4348. return AVERROR_EOF;
  4349. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  4350. return 1;
  4351. }
  4352. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  4353. {
  4354. MOVContext *mov = s->priv_data;
  4355. MOVStreamContext *sc;
  4356. AVIndexEntry *sample;
  4357. AVStream *st = NULL;
  4358. int ret;
  4359. mov->fc = s;
  4360. retry:
  4361. sample = mov_find_next_sample(s, &st);
  4362. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  4363. if (!mov->next_root_atom)
  4364. return AVERROR_EOF;
  4365. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  4366. return ret;
  4367. goto retry;
  4368. }
  4369. sc = st->priv_data;
  4370. /* must be done just before reading, to avoid infinite loop on sample */
  4371. sc->current_sample++;
  4372. if (mov->next_root_atom) {
  4373. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  4374. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  4375. }
  4376. if (st->discard != AVDISCARD_ALL) {
  4377. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  4378. if (ret64 != sample->pos) {
  4379. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  4380. sc->ffindex, sample->pos);
  4381. sc->current_sample -= should_retry(sc->pb, ret64);
  4382. return AVERROR_INVALIDDATA;
  4383. }
  4384. ret = av_get_packet(sc->pb, pkt, sample->size);
  4385. if (ret < 0) {
  4386. sc->current_sample -= should_retry(sc->pb, ret);
  4387. return ret;
  4388. }
  4389. if (sc->has_palette) {
  4390. uint8_t *pal;
  4391. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  4392. if (!pal) {
  4393. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  4394. } else {
  4395. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  4396. sc->has_palette = 0;
  4397. }
  4398. }
  4399. #if CONFIG_DV_DEMUXER
  4400. if (mov->dv_demux && sc->dv_audio_container) {
  4401. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  4402. av_freep(&pkt->data);
  4403. pkt->size = 0;
  4404. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  4405. if (ret < 0)
  4406. return ret;
  4407. }
  4408. #endif
  4409. }
  4410. pkt->stream_index = sc->ffindex;
  4411. pkt->dts = sample->timestamp;
  4412. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  4413. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  4414. /* update ctts context */
  4415. sc->ctts_sample++;
  4416. if (sc->ctts_index < sc->ctts_count &&
  4417. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  4418. sc->ctts_index++;
  4419. sc->ctts_sample = 0;
  4420. }
  4421. if (sc->wrong_dts)
  4422. pkt->dts = AV_NOPTS_VALUE;
  4423. } else {
  4424. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  4425. st->index_entries[sc->current_sample].timestamp : st->duration;
  4426. pkt->duration = next_dts - pkt->dts;
  4427. pkt->pts = pkt->dts;
  4428. }
  4429. if (st->discard == AVDISCARD_ALL)
  4430. goto retry;
  4431. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  4432. pkt->pos = sample->pos;
  4433. if (mov->aax_mode)
  4434. aax_filter(pkt->data, pkt->size, mov);
  4435. if (sc->cenc.aes_ctr) {
  4436. ret = cenc_filter(mov, sc, pkt->data, pkt->size);
  4437. if (ret) {
  4438. return ret;
  4439. }
  4440. }
  4441. return 0;
  4442. }
  4443. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  4444. {
  4445. MOVContext *mov = s->priv_data;
  4446. int i, j;
  4447. if (!mov->fragment_index_complete)
  4448. return 0;
  4449. for (i = 0; i < mov->fragment_index_count; i++) {
  4450. if (mov->fragment_index_data[i]->track_id == st->id) {
  4451. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4452. for (j = index->item_count - 1; j >= 0; j--) {
  4453. if (index->items[j].time <= timestamp) {
  4454. if (index->items[j].headers_read)
  4455. return 0;
  4456. return mov_switch_root(s, index->items[j].moof_offset);
  4457. }
  4458. }
  4459. }
  4460. }
  4461. return 0;
  4462. }
  4463. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  4464. {
  4465. MOVStreamContext *sc = st->priv_data;
  4466. int sample, time_sample;
  4467. int i;
  4468. int ret = mov_seek_fragment(s, st, timestamp);
  4469. if (ret < 0)
  4470. return ret;
  4471. sample = av_index_search_timestamp(st, timestamp, flags);
  4472. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  4473. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  4474. sample = 0;
  4475. if (sample < 0) /* not sure what to do */
  4476. return AVERROR_INVALIDDATA;
  4477. sc->current_sample = sample;
  4478. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  4479. /* adjust ctts index */
  4480. if (sc->ctts_data) {
  4481. time_sample = 0;
  4482. for (i = 0; i < sc->ctts_count; i++) {
  4483. int next = time_sample + sc->ctts_data[i].count;
  4484. if (next > sc->current_sample) {
  4485. sc->ctts_index = i;
  4486. sc->ctts_sample = sc->current_sample - time_sample;
  4487. break;
  4488. }
  4489. time_sample = next;
  4490. }
  4491. }
  4492. return sample;
  4493. }
  4494. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  4495. {
  4496. MOVContext *mc = s->priv_data;
  4497. AVStream *st;
  4498. int sample;
  4499. int i;
  4500. if (stream_index >= s->nb_streams)
  4501. return AVERROR_INVALIDDATA;
  4502. st = s->streams[stream_index];
  4503. sample = mov_seek_stream(s, st, sample_time, flags);
  4504. if (sample < 0)
  4505. return sample;
  4506. if (mc->seek_individually) {
  4507. /* adjust seek timestamp to found sample timestamp */
  4508. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  4509. for (i = 0; i < s->nb_streams; i++) {
  4510. int64_t timestamp;
  4511. MOVStreamContext *sc = s->streams[i]->priv_data;
  4512. st = s->streams[i];
  4513. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  4514. if (stream_index == i)
  4515. continue;
  4516. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  4517. mov_seek_stream(s, st, timestamp, flags);
  4518. }
  4519. } else {
  4520. for (i = 0; i < s->nb_streams; i++) {
  4521. MOVStreamContext *sc;
  4522. st = s->streams[i];
  4523. sc = st->priv_data;
  4524. sc->current_sample = 0;
  4525. }
  4526. while (1) {
  4527. MOVStreamContext *sc;
  4528. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  4529. if (!entry)
  4530. return AVERROR_INVALIDDATA;
  4531. sc = st->priv_data;
  4532. if (sc->ffindex == stream_index && sc->current_sample == sample)
  4533. break;
  4534. sc->current_sample++;
  4535. }
  4536. }
  4537. return 0;
  4538. }
  4539. #define OFFSET(x) offsetof(MOVContext, x)
  4540. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  4541. static const AVOption mov_options[] = {
  4542. {"use_absolute_path",
  4543. "allow using absolute path when opening alias, this is a possible security issue",
  4544. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4545. 0, 1, FLAGS},
  4546. {"seek_streams_individually",
  4547. "Seek each stream individually to the to the closest point",
  4548. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  4549. 0, 1, FLAGS},
  4550. {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4551. 0, 1, FLAGS},
  4552. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4553. 0, 1, FLAGS},
  4554. {"use_mfra_for",
  4555. "use mfra for fragment timestamps",
  4556. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  4557. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  4558. "use_mfra_for"},
  4559. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  4560. FLAGS, "use_mfra_for" },
  4561. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  4562. FLAGS, "use_mfra_for" },
  4563. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  4564. FLAGS, "use_mfra_for" },
  4565. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  4566. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4567. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  4568. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4569. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  4570. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4571. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  4572. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  4573. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  4574. .flags = AV_OPT_FLAG_DECODING_PARAM },
  4575. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4576. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  4577. {.i64 = 0}, 0, 1, FLAGS },
  4578. { NULL },
  4579. };
  4580. static const AVClass mov_class = {
  4581. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  4582. .item_name = av_default_item_name,
  4583. .option = mov_options,
  4584. .version = LIBAVUTIL_VERSION_INT,
  4585. };
  4586. AVInputFormat ff_mov_demuxer = {
  4587. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  4588. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  4589. .priv_class = &mov_class,
  4590. .priv_data_size = sizeof(MOVContext),
  4591. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  4592. .read_probe = mov_probe,
  4593. .read_header = mov_read_header,
  4594. .read_packet = mov_read_packet,
  4595. .read_close = mov_read_close,
  4596. .read_seek = mov_read_seek,
  4597. .flags = AVFMT_NO_BYTE_SEEK,
  4598. };