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.

5293 lines
176KB

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