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.

5328 lines
178KB

  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. if ((uint64_t)entries * 12 + 4 > atom.size)
  1960. return AVERROR_INVALIDDATA;
  1961. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1962. if (!entries)
  1963. return 0;
  1964. if (sc->stsc_data)
  1965. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  1966. av_free(sc->stsc_data);
  1967. sc->stsc_count = 0;
  1968. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  1969. if (!sc->stsc_data)
  1970. return AVERROR(ENOMEM);
  1971. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1972. sc->stsc_data[i].first = avio_rb32(pb);
  1973. sc->stsc_data[i].count = avio_rb32(pb);
  1974. sc->stsc_data[i].id = avio_rb32(pb);
  1975. }
  1976. sc->stsc_count = i;
  1977. for (i = sc->stsc_count - 1; i < UINT_MAX; i--) {
  1978. if ((i+1 < sc->stsc_count && sc->stsc_data[i].first >= sc->stsc_data[i+1].first) ||
  1979. (i > 0 && sc->stsc_data[i].first <= sc->stsc_data[i-1].first) ||
  1980. sc->stsc_data[i].first < 1 ||
  1981. sc->stsc_data[i].count < 1 ||
  1982. sc->stsc_data[i].id < 1) {
  1983. av_log(c->fc, AV_LOG_WARNING, "STSC entry %d is invalid (first=%d count=%d id=%d)\n", i, sc->stsc_data[i].first, sc->stsc_data[i].count, sc->stsc_data[i].id);
  1984. if (i+1 >= sc->stsc_count || sc->stsc_data[i+1].first < 2)
  1985. return AVERROR_INVALIDDATA;
  1986. // We replace this entry by the next valid
  1987. sc->stsc_data[i].first = sc->stsc_data[i+1].first - 1;
  1988. sc->stsc_data[i].count = sc->stsc_data[i+1].count;
  1989. sc->stsc_data[i].id = sc->stsc_data[i+1].id;
  1990. }
  1991. }
  1992. if (pb->eof_reached)
  1993. return AVERROR_EOF;
  1994. return 0;
  1995. }
  1996. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1997. {
  1998. AVStream *st;
  1999. MOVStreamContext *sc;
  2000. unsigned i, entries;
  2001. if (c->fc->nb_streams < 1)
  2002. return 0;
  2003. st = c->fc->streams[c->fc->nb_streams-1];
  2004. sc = st->priv_data;
  2005. avio_rb32(pb); // version + flags
  2006. entries = avio_rb32(pb);
  2007. if (sc->stps_data)
  2008. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2009. av_free(sc->stps_data);
  2010. sc->stps_count = 0;
  2011. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2012. if (!sc->stps_data)
  2013. return AVERROR(ENOMEM);
  2014. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2015. sc->stps_data[i] = avio_rb32(pb);
  2016. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  2017. }
  2018. sc->stps_count = i;
  2019. if (pb->eof_reached)
  2020. return AVERROR_EOF;
  2021. return 0;
  2022. }
  2023. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2024. {
  2025. AVStream *st;
  2026. MOVStreamContext *sc;
  2027. unsigned int i, entries;
  2028. if (c->fc->nb_streams < 1)
  2029. return 0;
  2030. st = c->fc->streams[c->fc->nb_streams-1];
  2031. sc = st->priv_data;
  2032. avio_r8(pb); /* version */
  2033. avio_rb24(pb); /* flags */
  2034. entries = avio_rb32(pb);
  2035. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2036. if (!entries)
  2037. {
  2038. sc->keyframe_absent = 1;
  2039. if (!st->need_parsing && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  2040. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2041. return 0;
  2042. }
  2043. if (sc->keyframes)
  2044. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2045. if (entries >= UINT_MAX / sizeof(int))
  2046. return AVERROR_INVALIDDATA;
  2047. av_freep(&sc->keyframes);
  2048. sc->keyframe_count = 0;
  2049. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2050. if (!sc->keyframes)
  2051. return AVERROR(ENOMEM);
  2052. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2053. sc->keyframes[i] = avio_rb32(pb);
  2054. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2055. }
  2056. sc->keyframe_count = i;
  2057. if (pb->eof_reached)
  2058. return AVERROR_EOF;
  2059. return 0;
  2060. }
  2061. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2062. {
  2063. AVStream *st;
  2064. MOVStreamContext *sc;
  2065. unsigned int i, entries, sample_size, field_size, num_bytes;
  2066. GetBitContext gb;
  2067. unsigned char* buf;
  2068. int ret;
  2069. if (c->fc->nb_streams < 1)
  2070. return 0;
  2071. st = c->fc->streams[c->fc->nb_streams-1];
  2072. sc = st->priv_data;
  2073. avio_r8(pb); /* version */
  2074. avio_rb24(pb); /* flags */
  2075. if (atom.type == MKTAG('s','t','s','z')) {
  2076. sample_size = avio_rb32(pb);
  2077. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2078. sc->sample_size = sample_size;
  2079. sc->stsz_sample_size = sample_size;
  2080. field_size = 32;
  2081. } else {
  2082. sample_size = 0;
  2083. avio_rb24(pb); /* reserved */
  2084. field_size = avio_r8(pb);
  2085. }
  2086. entries = avio_rb32(pb);
  2087. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2088. sc->sample_count = entries;
  2089. if (sample_size)
  2090. return 0;
  2091. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2092. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2093. return AVERROR_INVALIDDATA;
  2094. }
  2095. if (!entries)
  2096. return 0;
  2097. if (entries >= (UINT_MAX - 4) / field_size)
  2098. return AVERROR_INVALIDDATA;
  2099. if (sc->sample_sizes)
  2100. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2101. av_free(sc->sample_sizes);
  2102. sc->sample_count = 0;
  2103. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2104. if (!sc->sample_sizes)
  2105. return AVERROR(ENOMEM);
  2106. num_bytes = (entries*field_size+4)>>3;
  2107. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2108. if (!buf) {
  2109. av_freep(&sc->sample_sizes);
  2110. return AVERROR(ENOMEM);
  2111. }
  2112. ret = ffio_read_size(pb, buf, num_bytes);
  2113. if (ret < 0) {
  2114. av_freep(&sc->sample_sizes);
  2115. av_free(buf);
  2116. return ret;
  2117. }
  2118. init_get_bits(&gb, buf, 8*num_bytes);
  2119. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2120. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2121. sc->data_size += sc->sample_sizes[i];
  2122. }
  2123. sc->sample_count = i;
  2124. av_free(buf);
  2125. if (pb->eof_reached)
  2126. return AVERROR_EOF;
  2127. return 0;
  2128. }
  2129. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2130. {
  2131. AVStream *st;
  2132. MOVStreamContext *sc;
  2133. unsigned int i, entries;
  2134. int64_t duration=0;
  2135. int64_t total_sample_count=0;
  2136. if (c->fc->nb_streams < 1)
  2137. return 0;
  2138. st = c->fc->streams[c->fc->nb_streams-1];
  2139. sc = st->priv_data;
  2140. avio_r8(pb); /* version */
  2141. avio_rb24(pb); /* flags */
  2142. entries = avio_rb32(pb);
  2143. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2144. c->fc->nb_streams-1, entries);
  2145. if (sc->stts_data)
  2146. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2147. av_free(sc->stts_data);
  2148. sc->stts_count = 0;
  2149. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2150. if (!sc->stts_data)
  2151. return AVERROR(ENOMEM);
  2152. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2153. int sample_duration;
  2154. int sample_count;
  2155. sample_count=avio_rb32(pb);
  2156. sample_duration = avio_rb32(pb);
  2157. if (sample_count < 0) {
  2158. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2159. return AVERROR_INVALIDDATA;
  2160. }
  2161. sc->stts_data[i].count= sample_count;
  2162. sc->stts_data[i].duration= sample_duration;
  2163. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2164. sample_count, sample_duration);
  2165. if ( i+1 == entries
  2166. && i
  2167. && sample_count == 1
  2168. && total_sample_count > 100
  2169. && sample_duration/10 > duration / total_sample_count)
  2170. sample_duration = duration / total_sample_count;
  2171. duration+=(int64_t)sample_duration*(uint64_t)sample_count;
  2172. total_sample_count+=sample_count;
  2173. }
  2174. sc->stts_count = i;
  2175. if (duration > 0 &&
  2176. duration <= INT64_MAX - sc->duration_for_fps &&
  2177. total_sample_count <= INT64_MAX - sc->nb_frames_for_fps
  2178. ) {
  2179. sc->duration_for_fps += duration;
  2180. sc->nb_frames_for_fps += total_sample_count;
  2181. }
  2182. if (pb->eof_reached)
  2183. return AVERROR_EOF;
  2184. st->nb_frames= total_sample_count;
  2185. if (duration)
  2186. st->duration= duration;
  2187. sc->track_end = duration;
  2188. return 0;
  2189. }
  2190. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2191. {
  2192. if (duration < 0) {
  2193. if (duration == INT_MIN) {
  2194. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2195. duration++;
  2196. }
  2197. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2198. }
  2199. }
  2200. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2201. {
  2202. AVStream *st;
  2203. MOVStreamContext *sc;
  2204. unsigned int i, entries;
  2205. if (c->fc->nb_streams < 1)
  2206. return 0;
  2207. st = c->fc->streams[c->fc->nb_streams-1];
  2208. sc = st->priv_data;
  2209. avio_r8(pb); /* version */
  2210. avio_rb24(pb); /* flags */
  2211. entries = avio_rb32(pb);
  2212. av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2213. if (!entries)
  2214. return 0;
  2215. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2216. return AVERROR_INVALIDDATA;
  2217. av_freep(&sc->ctts_data);
  2218. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2219. if (!sc->ctts_data)
  2220. return AVERROR(ENOMEM);
  2221. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2222. int count =avio_rb32(pb);
  2223. int duration =avio_rb32(pb);
  2224. sc->ctts_data[i].count = count;
  2225. sc->ctts_data[i].duration= duration;
  2226. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2227. count, duration);
  2228. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2229. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2230. av_freep(&sc->ctts_data);
  2231. sc->ctts_count = 0;
  2232. return 0;
  2233. }
  2234. if (i+2<entries)
  2235. mov_update_dts_shift(sc, duration);
  2236. }
  2237. sc->ctts_count = i;
  2238. if (pb->eof_reached)
  2239. return AVERROR_EOF;
  2240. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2241. return 0;
  2242. }
  2243. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2244. {
  2245. AVStream *st;
  2246. MOVStreamContext *sc;
  2247. unsigned int i, entries;
  2248. uint8_t version;
  2249. uint32_t grouping_type;
  2250. if (c->fc->nb_streams < 1)
  2251. return 0;
  2252. st = c->fc->streams[c->fc->nb_streams-1];
  2253. sc = st->priv_data;
  2254. version = avio_r8(pb); /* version */
  2255. avio_rb24(pb); /* flags */
  2256. grouping_type = avio_rl32(pb);
  2257. if (grouping_type != MKTAG( 'r','a','p',' '))
  2258. return 0; /* only support 'rap ' grouping */
  2259. if (version == 1)
  2260. avio_rb32(pb); /* grouping_type_parameter */
  2261. entries = avio_rb32(pb);
  2262. if (!entries)
  2263. return 0;
  2264. if (sc->rap_group)
  2265. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2266. av_free(sc->rap_group);
  2267. sc->rap_group_count = 0;
  2268. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2269. if (!sc->rap_group)
  2270. return AVERROR(ENOMEM);
  2271. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2272. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2273. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2274. }
  2275. sc->rap_group_count = i;
  2276. return pb->eof_reached ? AVERROR_EOF : 0;
  2277. }
  2278. static void mov_build_index(MOVContext *mov, AVStream *st)
  2279. {
  2280. MOVStreamContext *sc = st->priv_data;
  2281. int64_t current_offset;
  2282. int64_t current_dts = 0;
  2283. unsigned int stts_index = 0;
  2284. unsigned int stsc_index = 0;
  2285. unsigned int stss_index = 0;
  2286. unsigned int stps_index = 0;
  2287. unsigned int i, j;
  2288. uint64_t stream_size = 0;
  2289. if (sc->elst_count) {
  2290. int i, edit_start_index = 0, unsupported = 0;
  2291. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2292. int64_t start_time = 0; // start time of the media
  2293. for (i = 0; i < sc->elst_count; i++) {
  2294. const MOVElst *e = &sc->elst_data[i];
  2295. if (i == 0 && e->time == -1) {
  2296. /* if empty, the first entry is the start time of the stream
  2297. * relative to the presentation itself */
  2298. empty_duration = e->duration;
  2299. edit_start_index = 1;
  2300. } else if (i == edit_start_index && e->time >= 0) {
  2301. start_time = e->time;
  2302. } else
  2303. unsupported = 1;
  2304. }
  2305. if (unsupported)
  2306. av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2307. "a/v desync might occur, patch welcome\n");
  2308. /* adjust first dts according to edit list */
  2309. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2310. if (empty_duration)
  2311. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2312. sc->time_offset = start_time - empty_duration;
  2313. current_dts = -sc->time_offset;
  2314. if (sc->ctts_count>0 && sc->stts_count>0 &&
  2315. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  2316. /* more than 16 frames delay, dts are likely wrong
  2317. this happens with files created by iMovie */
  2318. sc->wrong_dts = 1;
  2319. st->codec->has_b_frames = 1;
  2320. }
  2321. }
  2322. }
  2323. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2324. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  2325. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2326. unsigned int current_sample = 0;
  2327. unsigned int stts_sample = 0;
  2328. unsigned int sample_size;
  2329. unsigned int distance = 0;
  2330. unsigned int rap_group_index = 0;
  2331. unsigned int rap_group_sample = 0;
  2332. int64_t last_dts = 0;
  2333. int64_t dts_correction = 0;
  2334. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2335. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2336. current_dts -= sc->dts_shift;
  2337. last_dts = current_dts;
  2338. if (!sc->sample_count || st->nb_index_entries)
  2339. return;
  2340. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2341. return;
  2342. if (av_reallocp_array(&st->index_entries,
  2343. st->nb_index_entries + sc->sample_count,
  2344. sizeof(*st->index_entries)) < 0) {
  2345. st->nb_index_entries = 0;
  2346. return;
  2347. }
  2348. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2349. for (i = 0; i < sc->chunk_count; i++) {
  2350. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2351. current_offset = sc->chunk_offsets[i];
  2352. while (stsc_index + 1 < sc->stsc_count &&
  2353. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2354. stsc_index++;
  2355. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2356. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2357. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2358. sc->stsz_sample_size = sc->sample_size;
  2359. }
  2360. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2361. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2362. sc->stsz_sample_size = sc->sample_size;
  2363. }
  2364. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2365. int keyframe = 0;
  2366. if (current_sample >= sc->sample_count) {
  2367. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2368. return;
  2369. }
  2370. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2371. keyframe = 1;
  2372. if (stss_index + 1 < sc->keyframe_count)
  2373. stss_index++;
  2374. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2375. keyframe = 1;
  2376. if (stps_index + 1 < sc->stps_count)
  2377. stps_index++;
  2378. }
  2379. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2380. if (sc->rap_group[rap_group_index].index > 0)
  2381. keyframe = 1;
  2382. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2383. rap_group_sample = 0;
  2384. rap_group_index++;
  2385. }
  2386. }
  2387. if (sc->keyframe_absent
  2388. && !sc->stps_count
  2389. && !rap_group_present
  2390. && (st->codec->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2391. keyframe = 1;
  2392. if (keyframe)
  2393. distance = 0;
  2394. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2395. if (sc->pseudo_stream_id == -1 ||
  2396. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2397. AVIndexEntry *e;
  2398. if (sample_size > 0x3FFFFFFF) {
  2399. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  2400. return;
  2401. }
  2402. e = &st->index_entries[st->nb_index_entries++];
  2403. e->pos = current_offset;
  2404. e->timestamp = current_dts;
  2405. e->size = sample_size;
  2406. e->min_distance = distance;
  2407. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2408. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2409. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2410. current_offset, current_dts, sample_size, distance, keyframe);
  2411. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2412. ff_rfps_add_frame(mov->fc, st, current_dts);
  2413. }
  2414. current_offset += sample_size;
  2415. stream_size += sample_size;
  2416. /* A negative sample duration is invalid based on the spec,
  2417. * but some samples need it to correct the DTS. */
  2418. if (sc->stts_data[stts_index].duration < 0) {
  2419. av_log(mov->fc, AV_LOG_WARNING,
  2420. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2421. sc->stts_data[stts_index].duration, stts_index,
  2422. st->index);
  2423. dts_correction += sc->stts_data[stts_index].duration - 1;
  2424. sc->stts_data[stts_index].duration = 1;
  2425. }
  2426. current_dts += sc->stts_data[stts_index].duration;
  2427. if (!dts_correction || current_dts + dts_correction > last_dts) {
  2428. current_dts += dts_correction;
  2429. dts_correction = 0;
  2430. } else {
  2431. /* Avoid creating non-monotonous DTS */
  2432. dts_correction += current_dts - last_dts - 1;
  2433. current_dts = last_dts + 1;
  2434. }
  2435. last_dts = current_dts;
  2436. distance++;
  2437. stts_sample++;
  2438. current_sample++;
  2439. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2440. stts_sample = 0;
  2441. stts_index++;
  2442. }
  2443. }
  2444. }
  2445. if (st->duration > 0)
  2446. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2447. } else {
  2448. unsigned chunk_samples, total = 0;
  2449. // compute total chunk count
  2450. for (i = 0; i < sc->stsc_count; i++) {
  2451. unsigned count, chunk_count;
  2452. chunk_samples = sc->stsc_data[i].count;
  2453. if (i != sc->stsc_count - 1 &&
  2454. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2455. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2456. return;
  2457. }
  2458. if (sc->samples_per_frame >= 160) { // gsm
  2459. count = chunk_samples / sc->samples_per_frame;
  2460. } else if (sc->samples_per_frame > 1) {
  2461. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2462. count = (chunk_samples+samples-1) / samples;
  2463. } else {
  2464. count = (chunk_samples+1023) / 1024;
  2465. }
  2466. if (i < sc->stsc_count - 1)
  2467. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2468. else
  2469. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2470. total += chunk_count * count;
  2471. }
  2472. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2473. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2474. return;
  2475. if (av_reallocp_array(&st->index_entries,
  2476. st->nb_index_entries + total,
  2477. sizeof(*st->index_entries)) < 0) {
  2478. st->nb_index_entries = 0;
  2479. return;
  2480. }
  2481. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2482. // populate index
  2483. for (i = 0; i < sc->chunk_count; i++) {
  2484. current_offset = sc->chunk_offsets[i];
  2485. if (stsc_index + 1 < sc->stsc_count &&
  2486. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2487. stsc_index++;
  2488. chunk_samples = sc->stsc_data[stsc_index].count;
  2489. while (chunk_samples > 0) {
  2490. AVIndexEntry *e;
  2491. unsigned size, samples;
  2492. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2493. avpriv_request_sample(mov->fc,
  2494. "Zero bytes per frame, but %d samples per frame",
  2495. sc->samples_per_frame);
  2496. return;
  2497. }
  2498. if (sc->samples_per_frame >= 160) { // gsm
  2499. samples = sc->samples_per_frame;
  2500. size = sc->bytes_per_frame;
  2501. } else {
  2502. if (sc->samples_per_frame > 1) {
  2503. samples = FFMIN((1024 / sc->samples_per_frame)*
  2504. sc->samples_per_frame, chunk_samples);
  2505. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2506. } else {
  2507. samples = FFMIN(1024, chunk_samples);
  2508. size = samples * sc->sample_size;
  2509. }
  2510. }
  2511. if (st->nb_index_entries >= total) {
  2512. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2513. return;
  2514. }
  2515. if (size > 0x3FFFFFFF) {
  2516. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  2517. return;
  2518. }
  2519. e = &st->index_entries[st->nb_index_entries++];
  2520. e->pos = current_offset;
  2521. e->timestamp = current_dts;
  2522. e->size = size;
  2523. e->min_distance = 0;
  2524. e->flags = AVINDEX_KEYFRAME;
  2525. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2526. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2527. size, samples);
  2528. current_offset += size;
  2529. current_dts += samples;
  2530. chunk_samples -= samples;
  2531. }
  2532. }
  2533. }
  2534. }
  2535. static int test_same_origin(const char *src, const char *ref) {
  2536. char src_proto[64];
  2537. char ref_proto[64];
  2538. char src_auth[256];
  2539. char ref_auth[256];
  2540. char src_host[256];
  2541. char ref_host[256];
  2542. int src_port=-1;
  2543. int ref_port=-1;
  2544. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  2545. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  2546. if (strlen(src) == 0) {
  2547. return -1;
  2548. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  2549. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  2550. strlen(src_host) + 1 >= sizeof(src_host) ||
  2551. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  2552. return 0;
  2553. } else if (strcmp(src_proto, ref_proto) ||
  2554. strcmp(src_auth, ref_auth) ||
  2555. strcmp(src_host, ref_host) ||
  2556. src_port != ref_port) {
  2557. return 0;
  2558. } else
  2559. return 1;
  2560. }
  2561. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  2562. {
  2563. /* try relative path, we do not try the absolute because it can leak information about our
  2564. system to an attacker */
  2565. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2566. char filename[1025];
  2567. const char *src_path;
  2568. int i, l;
  2569. /* find a source dir */
  2570. src_path = strrchr(src, '/');
  2571. if (src_path)
  2572. src_path++;
  2573. else
  2574. src_path = src;
  2575. /* find a next level down to target */
  2576. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2577. if (ref->path[l] == '/') {
  2578. if (i == ref->nlvl_to - 1)
  2579. break;
  2580. else
  2581. i++;
  2582. }
  2583. /* compose filename if next level down to target was found */
  2584. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2585. memcpy(filename, src, src_path - src);
  2586. filename[src_path - src] = 0;
  2587. for (i = 1; i < ref->nlvl_from; i++)
  2588. av_strlcat(filename, "../", sizeof(filename));
  2589. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  2590. if (!c->use_absolute_path) {
  2591. int same_origin = test_same_origin(src, filename);
  2592. if (!same_origin) {
  2593. av_log(c->fc, AV_LOG_ERROR,
  2594. "Reference with mismatching origin, %s not tried for security reasons, "
  2595. "set demuxer option use_absolute_path to allow it anyway\n",
  2596. ref->path);
  2597. return AVERROR(ENOENT);
  2598. }
  2599. if(strstr(ref->path + l + 1, "..") ||
  2600. strstr(ref->path + l + 1, ":") ||
  2601. (ref->nlvl_from > 1 && same_origin < 0) ||
  2602. (filename[0] == '/' && src_path == src))
  2603. return AVERROR(ENOENT);
  2604. }
  2605. if (strlen(filename) + 1 == sizeof(filename))
  2606. return AVERROR(ENOENT);
  2607. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  2608. return 0;
  2609. }
  2610. } else if (c->use_absolute_path) {
  2611. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2612. "this is a possible security issue\n");
  2613. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  2614. return 0;
  2615. } else {
  2616. av_log(c->fc, AV_LOG_ERROR,
  2617. "Absolute path %s not tried for security reasons, "
  2618. "set demuxer option use_absolute_path to allow absolute paths\n",
  2619. ref->path);
  2620. }
  2621. return AVERROR(ENOENT);
  2622. }
  2623. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2624. {
  2625. if (sc->time_scale <= 0) {
  2626. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2627. sc->time_scale = c->time_scale;
  2628. if (sc->time_scale <= 0)
  2629. sc->time_scale = 1;
  2630. }
  2631. }
  2632. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2633. {
  2634. AVStream *st;
  2635. MOVStreamContext *sc;
  2636. int ret;
  2637. st = avformat_new_stream(c->fc, NULL);
  2638. if (!st) return AVERROR(ENOMEM);
  2639. st->id = c->fc->nb_streams;
  2640. sc = av_mallocz(sizeof(MOVStreamContext));
  2641. if (!sc) return AVERROR(ENOMEM);
  2642. st->priv_data = sc;
  2643. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  2644. sc->ffindex = st->index;
  2645. c->trak_index = st->index;
  2646. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2647. return ret;
  2648. c->trak_index = -1;
  2649. /* sanity checks */
  2650. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2651. (!sc->sample_size && !sc->sample_count))) {
  2652. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2653. st->index);
  2654. return 0;
  2655. }
  2656. if (sc->chunk_count && sc->stsc_count && sc->stsc_data[ sc->stsc_count - 1 ].first > sc->chunk_count) {
  2657. av_log(c->fc, AV_LOG_ERROR, "stream %d, contradictionary STSC and STCO\n",
  2658. st->index);
  2659. return AVERROR_INVALIDDATA;
  2660. }
  2661. fix_timescale(c, sc);
  2662. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2663. mov_build_index(c, st);
  2664. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2665. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2666. if (c->enable_drefs) {
  2667. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  2668. av_log(c->fc, AV_LOG_ERROR,
  2669. "stream %d, error opening alias: path='%s', dir='%s', "
  2670. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2671. st->index, dref->path, dref->dir, dref->filename,
  2672. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2673. } else {
  2674. av_log(c->fc, AV_LOG_WARNING,
  2675. "Skipped opening external track: "
  2676. "stream %d, alias: path='%s', dir='%s', "
  2677. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  2678. "Set enable_drefs to allow this.\n",
  2679. st->index, dref->path, dref->dir, dref->filename,
  2680. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2681. }
  2682. } else {
  2683. sc->pb = c->fc->pb;
  2684. sc->pb_is_copied = 1;
  2685. }
  2686. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  2687. if (!st->sample_aspect_ratio.num && st->codec->width && st->codec->height &&
  2688. sc->height && sc->width &&
  2689. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  2690. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  2691. ((double)st->codec->width * sc->height), INT_MAX);
  2692. }
  2693. #if FF_API_R_FRAME_RATE
  2694. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2695. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2696. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2697. #endif
  2698. }
  2699. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2700. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  2701. TAG_IS_AVCI(st->codec->codec_tag)) {
  2702. ret = ff_generate_avci_extradata(st);
  2703. if (ret < 0)
  2704. return ret;
  2705. }
  2706. switch (st->codec->codec_id) {
  2707. #if CONFIG_H261_DECODER
  2708. case AV_CODEC_ID_H261:
  2709. #endif
  2710. #if CONFIG_H263_DECODER
  2711. case AV_CODEC_ID_H263:
  2712. #endif
  2713. #if CONFIG_MPEG4_DECODER
  2714. case AV_CODEC_ID_MPEG4:
  2715. #endif
  2716. st->codec->width = 0; /* let decoder init width/height */
  2717. st->codec->height= 0;
  2718. break;
  2719. }
  2720. // If the duration of the mp3 packets is not constant, then they could need a parser
  2721. if (st->codec->codec_id == AV_CODEC_ID_MP3
  2722. && sc->stts_count > 3
  2723. && sc->stts_count*10 > st->nb_frames
  2724. && sc->time_scale == st->codec->sample_rate) {
  2725. st->need_parsing = AVSTREAM_PARSE_FULL;
  2726. }
  2727. /* Do not need those anymore. */
  2728. av_freep(&sc->chunk_offsets);
  2729. av_freep(&sc->stsc_data);
  2730. av_freep(&sc->sample_sizes);
  2731. av_freep(&sc->keyframes);
  2732. av_freep(&sc->stts_data);
  2733. av_freep(&sc->stps_data);
  2734. av_freep(&sc->elst_data);
  2735. av_freep(&sc->rap_group);
  2736. return 0;
  2737. }
  2738. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2739. {
  2740. int ret;
  2741. c->itunes_metadata = 1;
  2742. ret = mov_read_default(c, pb, atom);
  2743. c->itunes_metadata = 0;
  2744. return ret;
  2745. }
  2746. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2747. {
  2748. uint32_t count;
  2749. uint32_t i;
  2750. if (atom.size < 8)
  2751. return 0;
  2752. avio_skip(pb, 4);
  2753. count = avio_rb32(pb);
  2754. if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
  2755. av_log(c->fc, AV_LOG_ERROR,
  2756. "The 'keys' atom with the invalid key count: %d\n", count);
  2757. return AVERROR_INVALIDDATA;
  2758. }
  2759. c->meta_keys_count = count + 1;
  2760. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  2761. if (!c->meta_keys)
  2762. return AVERROR(ENOMEM);
  2763. for (i = 1; i <= count; ++i) {
  2764. uint32_t key_size = avio_rb32(pb);
  2765. uint32_t type = avio_rl32(pb);
  2766. if (key_size < 8) {
  2767. av_log(c->fc, AV_LOG_ERROR,
  2768. "The key# %d in meta has invalid size: %d\n", i, key_size);
  2769. return AVERROR_INVALIDDATA;
  2770. }
  2771. key_size -= 8;
  2772. if (type != MKTAG('m','d','t','a')) {
  2773. avio_skip(pb, key_size);
  2774. }
  2775. c->meta_keys[i] = av_mallocz(key_size + 1);
  2776. if (!c->meta_keys[i])
  2777. return AVERROR(ENOMEM);
  2778. avio_read(pb, c->meta_keys[i], key_size);
  2779. }
  2780. return 0;
  2781. }
  2782. static int mov_read_custom_2plus(MOVContext *c, AVIOContext *pb, int size)
  2783. {
  2784. int64_t end = avio_tell(pb) + size;
  2785. uint8_t *key = NULL, *val = NULL;
  2786. int i;
  2787. AVStream *st;
  2788. MOVStreamContext *sc;
  2789. if (c->fc->nb_streams < 1)
  2790. return 0;
  2791. st = c->fc->streams[c->fc->nb_streams-1];
  2792. sc = st->priv_data;
  2793. for (i = 0; i < 2; i++) {
  2794. uint8_t **p;
  2795. uint32_t len, tag;
  2796. int ret;
  2797. if (end - avio_tell(pb) <= 12)
  2798. break;
  2799. len = avio_rb32(pb);
  2800. tag = avio_rl32(pb);
  2801. avio_skip(pb, 4); // flags
  2802. if (len < 12 || len - 12 > end - avio_tell(pb))
  2803. break;
  2804. len -= 12;
  2805. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2806. p = &key;
  2807. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2808. avio_skip(pb, 4);
  2809. len -= 4;
  2810. p = &val;
  2811. } else
  2812. break;
  2813. *p = av_malloc(len + 1);
  2814. if (!*p)
  2815. break;
  2816. ret = ffio_read_size(pb, *p, len);
  2817. if (ret < 0) {
  2818. av_freep(p);
  2819. return ret;
  2820. }
  2821. (*p)[len] = 0;
  2822. }
  2823. if (key && val) {
  2824. if (strcmp(key, "iTunSMPB") == 0) {
  2825. int priming, remainder, samples;
  2826. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  2827. if(priming>0 && priming<16384)
  2828. sc->start_pad = priming;
  2829. }
  2830. }
  2831. if (strcmp(key, "cdec") != 0) {
  2832. av_dict_set(&c->fc->metadata, key, val,
  2833. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2834. key = val = NULL;
  2835. }
  2836. }
  2837. avio_seek(pb, end, SEEK_SET);
  2838. av_freep(&key);
  2839. av_freep(&val);
  2840. return 0;
  2841. }
  2842. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2843. {
  2844. int64_t end = avio_tell(pb) + atom.size;
  2845. uint32_t tag, len;
  2846. if (atom.size < 8)
  2847. goto fail;
  2848. len = avio_rb32(pb);
  2849. tag = avio_rl32(pb);
  2850. if (len > atom.size)
  2851. goto fail;
  2852. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2853. uint8_t domain[128];
  2854. int domain_len;
  2855. avio_skip(pb, 4); // flags
  2856. len -= 12;
  2857. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2858. avio_skip(pb, len - domain_len);
  2859. return mov_read_custom_2plus(c, pb, end - avio_tell(pb));
  2860. }
  2861. fail:
  2862. av_log(c->fc, AV_LOG_VERBOSE,
  2863. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2864. return 0;
  2865. }
  2866. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2867. {
  2868. while (atom.size > 8) {
  2869. uint32_t tag = avio_rl32(pb);
  2870. atom.size -= 4;
  2871. if (tag == MKTAG('h','d','l','r')) {
  2872. avio_seek(pb, -8, SEEK_CUR);
  2873. atom.size += 8;
  2874. return mov_read_default(c, pb, atom);
  2875. }
  2876. }
  2877. return 0;
  2878. }
  2879. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2880. {
  2881. int i;
  2882. int width;
  2883. int height;
  2884. int display_matrix[3][3];
  2885. AVStream *st;
  2886. MOVStreamContext *sc;
  2887. int version;
  2888. int flags;
  2889. if (c->fc->nb_streams < 1)
  2890. return 0;
  2891. st = c->fc->streams[c->fc->nb_streams-1];
  2892. sc = st->priv_data;
  2893. version = avio_r8(pb);
  2894. flags = avio_rb24(pb);
  2895. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2896. if (version == 1) {
  2897. avio_rb64(pb);
  2898. avio_rb64(pb);
  2899. } else {
  2900. avio_rb32(pb); /* creation time */
  2901. avio_rb32(pb); /* modification time */
  2902. }
  2903. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2904. avio_rb32(pb); /* reserved */
  2905. /* highlevel (considering edits) duration in movie timebase */
  2906. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2907. avio_rb32(pb); /* reserved */
  2908. avio_rb32(pb); /* reserved */
  2909. avio_rb16(pb); /* layer */
  2910. avio_rb16(pb); /* alternate group */
  2911. avio_rb16(pb); /* volume */
  2912. avio_rb16(pb); /* reserved */
  2913. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2914. // they're kept in fixed point format through all calculations
  2915. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2916. // side data, but the scale factor is not needed to calculate aspect ratio
  2917. for (i = 0; i < 3; i++) {
  2918. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2919. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2920. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2921. }
  2922. width = avio_rb32(pb); // 16.16 fixed point track width
  2923. height = avio_rb32(pb); // 16.16 fixed point track height
  2924. sc->width = width >> 16;
  2925. sc->height = height >> 16;
  2926. // save the matrix and add rotate metadata when it is not the default
  2927. // identity
  2928. if (display_matrix[0][0] != (1 << 16) ||
  2929. display_matrix[1][1] != (1 << 16) ||
  2930. display_matrix[2][2] != (1 << 30) ||
  2931. display_matrix[0][1] || display_matrix[0][2] ||
  2932. display_matrix[1][0] || display_matrix[1][2] ||
  2933. display_matrix[2][0] || display_matrix[2][1]) {
  2934. int i, j;
  2935. double rotate;
  2936. av_freep(&sc->display_matrix);
  2937. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2938. if (!sc->display_matrix)
  2939. return AVERROR(ENOMEM);
  2940. for (i = 0; i < 3; i++)
  2941. for (j = 0; j < 3; j++)
  2942. sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  2943. rotate = av_display_rotation_get(sc->display_matrix);
  2944. if (!isnan(rotate)) {
  2945. char rotate_buf[64];
  2946. rotate = -rotate;
  2947. if (rotate < 0) // for backward compatibility
  2948. rotate += 360;
  2949. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  2950. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  2951. }
  2952. }
  2953. // transform the display width/height according to the matrix
  2954. // to keep the same scale, use [width height 1<<16]
  2955. if (width && height && sc->display_matrix) {
  2956. double disp_transform[2];
  2957. for (i = 0; i < 2; i++)
  2958. disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
  2959. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  2960. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  2961. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  2962. st->sample_aspect_ratio = av_d2q(
  2963. disp_transform[0] / disp_transform[1],
  2964. INT_MAX);
  2965. }
  2966. return 0;
  2967. }
  2968. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2969. {
  2970. MOVFragment *frag = &c->fragment;
  2971. MOVTrackExt *trex = NULL;
  2972. MOVFragmentIndex* index = NULL;
  2973. int flags, track_id, i, found = 0;
  2974. avio_r8(pb); /* version */
  2975. flags = avio_rb24(pb);
  2976. track_id = avio_rb32(pb);
  2977. if (!track_id)
  2978. return AVERROR_INVALIDDATA;
  2979. frag->track_id = track_id;
  2980. for (i = 0; i < c->trex_count; i++)
  2981. if (c->trex_data[i].track_id == frag->track_id) {
  2982. trex = &c->trex_data[i];
  2983. break;
  2984. }
  2985. if (!trex) {
  2986. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2987. return AVERROR_INVALIDDATA;
  2988. }
  2989. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2990. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2991. frag->moof_offset : frag->implicit_offset;
  2992. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2993. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2994. avio_rb32(pb) : trex->duration;
  2995. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2996. avio_rb32(pb) : trex->size;
  2997. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2998. avio_rb32(pb) : trex->flags;
  2999. frag->time = AV_NOPTS_VALUE;
  3000. for (i = 0; i < c->fragment_index_count; i++) {
  3001. int j;
  3002. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3003. if (candidate->track_id == frag->track_id) {
  3004. av_log(c->fc, AV_LOG_DEBUG,
  3005. "found fragment index for track %u\n", frag->track_id);
  3006. index = candidate;
  3007. for (j = index->current_item; j < index->item_count; j++) {
  3008. if (frag->implicit_offset == index->items[j].moof_offset) {
  3009. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3010. "for track %u and moof_offset %"PRId64"\n",
  3011. frag->track_id, index->items[j].moof_offset);
  3012. frag->time = index->items[j].time;
  3013. index->current_item = j + 1;
  3014. found = 1;
  3015. break;
  3016. }
  3017. }
  3018. if (found)
  3019. break;
  3020. }
  3021. }
  3022. if (index && !found) {
  3023. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3024. "it doesn't have an (in-order) entry for moof_offset "
  3025. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3026. }
  3027. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3028. return 0;
  3029. }
  3030. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3031. {
  3032. c->chapter_track = avio_rb32(pb);
  3033. return 0;
  3034. }
  3035. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3036. {
  3037. MOVTrackExt *trex;
  3038. int err;
  3039. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3040. return AVERROR_INVALIDDATA;
  3041. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3042. sizeof(*c->trex_data))) < 0) {
  3043. c->trex_count = 0;
  3044. return err;
  3045. }
  3046. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3047. trex = &c->trex_data[c->trex_count++];
  3048. avio_r8(pb); /* version */
  3049. avio_rb24(pb); /* flags */
  3050. trex->track_id = avio_rb32(pb);
  3051. trex->stsd_id = avio_rb32(pb);
  3052. trex->duration = avio_rb32(pb);
  3053. trex->size = avio_rb32(pb);
  3054. trex->flags = avio_rb32(pb);
  3055. return 0;
  3056. }
  3057. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3058. {
  3059. MOVFragment *frag = &c->fragment;
  3060. AVStream *st = NULL;
  3061. MOVStreamContext *sc;
  3062. int version, i;
  3063. for (i = 0; i < c->fc->nb_streams; i++) {
  3064. if (c->fc->streams[i]->id == frag->track_id) {
  3065. st = c->fc->streams[i];
  3066. break;
  3067. }
  3068. }
  3069. if (!st) {
  3070. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3071. return AVERROR_INVALIDDATA;
  3072. }
  3073. sc = st->priv_data;
  3074. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3075. return 0;
  3076. version = avio_r8(pb);
  3077. avio_rb24(pb); /* flags */
  3078. if (version) {
  3079. sc->track_end = avio_rb64(pb);
  3080. } else {
  3081. sc->track_end = avio_rb32(pb);
  3082. }
  3083. return 0;
  3084. }
  3085. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3086. {
  3087. MOVFragment *frag = &c->fragment;
  3088. AVStream *st = NULL;
  3089. MOVStreamContext *sc;
  3090. MOVStts *ctts_data;
  3091. uint64_t offset;
  3092. int64_t dts;
  3093. int data_offset = 0;
  3094. unsigned entries, first_sample_flags = frag->flags;
  3095. int flags, distance, i, err;
  3096. for (i = 0; i < c->fc->nb_streams; i++) {
  3097. if (c->fc->streams[i]->id == frag->track_id) {
  3098. st = c->fc->streams[i];
  3099. break;
  3100. }
  3101. }
  3102. if (!st) {
  3103. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3104. return AVERROR_INVALIDDATA;
  3105. }
  3106. sc = st->priv_data;
  3107. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3108. return 0;
  3109. avio_r8(pb); /* version */
  3110. flags = avio_rb24(pb);
  3111. entries = avio_rb32(pb);
  3112. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3113. /* Always assume the presence of composition time offsets.
  3114. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3115. * 1) in the initial movie, there are no samples.
  3116. * 2) in the first movie fragment, there is only one sample without composition time offset.
  3117. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  3118. if (!sc->ctts_count && sc->sample_count)
  3119. {
  3120. /* Complement ctts table if moov atom doesn't have ctts atom. */
  3121. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3122. if (!ctts_data)
  3123. return AVERROR(ENOMEM);
  3124. sc->ctts_data = ctts_data;
  3125. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3126. sc->ctts_data[sc->ctts_count].duration = 0;
  3127. sc->ctts_count++;
  3128. }
  3129. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3130. return AVERROR_INVALIDDATA;
  3131. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3132. sizeof(*sc->ctts_data))) < 0) {
  3133. sc->ctts_count = 0;
  3134. return err;
  3135. }
  3136. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3137. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3138. dts = sc->track_end - sc->time_offset;
  3139. offset = frag->base_data_offset + data_offset;
  3140. distance = 0;
  3141. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3142. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3143. unsigned sample_size = frag->size;
  3144. int sample_flags = i ? frag->flags : first_sample_flags;
  3145. unsigned sample_duration = frag->duration;
  3146. int keyframe = 0;
  3147. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3148. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3149. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3150. sc->ctts_data[sc->ctts_count].count = 1;
  3151. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3152. avio_rb32(pb) : 0;
  3153. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3154. if (frag->time != AV_NOPTS_VALUE) {
  3155. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3156. int64_t pts = frag->time;
  3157. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3158. " sc->dts_shift %d ctts.duration %d"
  3159. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3160. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3161. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3162. dts = pts - sc->dts_shift;
  3163. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3164. dts -= sc->ctts_data[sc->ctts_count].duration;
  3165. } else {
  3166. dts -= sc->time_offset;
  3167. }
  3168. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3169. } else {
  3170. dts = frag->time - sc->time_offset;
  3171. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3172. ", using it for dts\n", dts);
  3173. }
  3174. frag->time = AV_NOPTS_VALUE;
  3175. }
  3176. sc->ctts_count++;
  3177. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  3178. keyframe = 1;
  3179. else
  3180. keyframe =
  3181. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3182. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3183. if (keyframe)
  3184. distance = 0;
  3185. err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3186. keyframe ? AVINDEX_KEYFRAME : 0);
  3187. if (err < 0) {
  3188. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3189. }
  3190. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3191. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3192. offset, dts, sample_size, distance, keyframe);
  3193. distance++;
  3194. dts += sample_duration;
  3195. offset += sample_size;
  3196. sc->data_size += sample_size;
  3197. if (sample_duration <= INT64_MAX - sc->duration_for_fps &&
  3198. 1 <= INT64_MAX - sc->nb_frames_for_fps
  3199. ) {
  3200. sc->duration_for_fps += sample_duration;
  3201. sc->nb_frames_for_fps ++;
  3202. }
  3203. }
  3204. if (pb->eof_reached)
  3205. return AVERROR_EOF;
  3206. frag->implicit_offset = offset;
  3207. sc->track_end = dts + sc->time_offset;
  3208. if (st->duration < sc->track_end)
  3209. st->duration = sc->track_end;
  3210. return 0;
  3211. }
  3212. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3213. {
  3214. int64_t offset = avio_tell(pb) + atom.size, pts;
  3215. uint8_t version;
  3216. unsigned i, track_id;
  3217. AVStream *st = NULL;
  3218. MOVStreamContext *sc;
  3219. MOVFragmentIndex *index = NULL;
  3220. MOVFragmentIndex **tmp;
  3221. AVRational timescale;
  3222. version = avio_r8(pb);
  3223. if (version > 1) {
  3224. avpriv_request_sample(c->fc, "sidx version %u", version);
  3225. return 0;
  3226. }
  3227. avio_rb24(pb); // flags
  3228. track_id = avio_rb32(pb); // Reference ID
  3229. for (i = 0; i < c->fc->nb_streams; i++) {
  3230. if (c->fc->streams[i]->id == track_id) {
  3231. st = c->fc->streams[i];
  3232. break;
  3233. }
  3234. }
  3235. if (!st) {
  3236. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  3237. return 0;
  3238. }
  3239. sc = st->priv_data;
  3240. timescale = av_make_q(1, avio_rb32(pb));
  3241. if (version == 0) {
  3242. pts = avio_rb32(pb);
  3243. offset += avio_rb32(pb);
  3244. } else {
  3245. pts = avio_rb64(pb);
  3246. offset += avio_rb64(pb);
  3247. }
  3248. avio_rb16(pb); // reserved
  3249. index = av_mallocz(sizeof(MOVFragmentIndex));
  3250. if (!index)
  3251. return AVERROR(ENOMEM);
  3252. index->track_id = track_id;
  3253. index->item_count = avio_rb16(pb);
  3254. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3255. if (!index->items) {
  3256. av_freep(&index);
  3257. return AVERROR(ENOMEM);
  3258. }
  3259. for (i = 0; i < index->item_count; i++) {
  3260. uint32_t size = avio_rb32(pb);
  3261. uint32_t duration = avio_rb32(pb);
  3262. if (size & 0x80000000) {
  3263. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3264. av_freep(&index->items);
  3265. av_freep(&index);
  3266. return AVERROR_PATCHWELCOME;
  3267. }
  3268. avio_rb32(pb); // sap_flags
  3269. index->items[i].moof_offset = offset;
  3270. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3271. offset += size;
  3272. pts += duration;
  3273. }
  3274. st->duration = sc->track_end = pts;
  3275. tmp = av_realloc_array(c->fragment_index_data,
  3276. c->fragment_index_count + 1,
  3277. sizeof(MOVFragmentIndex*));
  3278. if (!tmp) {
  3279. av_freep(&index->items);
  3280. av_freep(&index);
  3281. return AVERROR(ENOMEM);
  3282. }
  3283. c->fragment_index_data = tmp;
  3284. c->fragment_index_data[c->fragment_index_count++] = index;
  3285. if (offset == avio_size(pb))
  3286. c->fragment_index_complete = 1;
  3287. return 0;
  3288. }
  3289. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3290. /* like the files created with Adobe Premiere 5.0, for samples see */
  3291. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3292. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3293. {
  3294. int err;
  3295. if (atom.size < 8)
  3296. return 0; /* continue */
  3297. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3298. avio_skip(pb, atom.size - 4);
  3299. return 0;
  3300. }
  3301. atom.type = avio_rl32(pb);
  3302. atom.size -= 8;
  3303. if (atom.type != MKTAG('m','d','a','t')) {
  3304. avio_skip(pb, atom.size);
  3305. return 0;
  3306. }
  3307. err = mov_read_mdat(c, pb, atom);
  3308. return err;
  3309. }
  3310. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3311. {
  3312. #if CONFIG_ZLIB
  3313. AVIOContext ctx;
  3314. uint8_t *cmov_data;
  3315. uint8_t *moov_data; /* uncompressed data */
  3316. long cmov_len, moov_len;
  3317. int ret = -1;
  3318. avio_rb32(pb); /* dcom atom */
  3319. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3320. return AVERROR_INVALIDDATA;
  3321. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3322. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3323. return AVERROR_INVALIDDATA;
  3324. }
  3325. avio_rb32(pb); /* cmvd atom */
  3326. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3327. return AVERROR_INVALIDDATA;
  3328. moov_len = avio_rb32(pb); /* uncompressed size */
  3329. cmov_len = atom.size - 6 * 4;
  3330. cmov_data = av_malloc(cmov_len);
  3331. if (!cmov_data)
  3332. return AVERROR(ENOMEM);
  3333. moov_data = av_malloc(moov_len);
  3334. if (!moov_data) {
  3335. av_free(cmov_data);
  3336. return AVERROR(ENOMEM);
  3337. }
  3338. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3339. if (ret < 0)
  3340. goto free_and_return;
  3341. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3342. goto free_and_return;
  3343. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3344. goto free_and_return;
  3345. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3346. atom.type = MKTAG('m','o','o','v');
  3347. atom.size = moov_len;
  3348. ret = mov_read_default(c, &ctx, atom);
  3349. free_and_return:
  3350. av_free(moov_data);
  3351. av_free(cmov_data);
  3352. return ret;
  3353. #else
  3354. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3355. return AVERROR(ENOSYS);
  3356. #endif
  3357. }
  3358. /* edit list atom */
  3359. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3360. {
  3361. MOVStreamContext *sc;
  3362. int i, edit_count, version;
  3363. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3364. return 0;
  3365. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3366. version = avio_r8(pb); /* version */
  3367. avio_rb24(pb); /* flags */
  3368. edit_count = avio_rb32(pb); /* entries */
  3369. if (!edit_count)
  3370. return 0;
  3371. if (sc->elst_data)
  3372. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3373. av_free(sc->elst_data);
  3374. sc->elst_count = 0;
  3375. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3376. if (!sc->elst_data)
  3377. return AVERROR(ENOMEM);
  3378. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3379. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3380. MOVElst *e = &sc->elst_data[i];
  3381. if (version == 1) {
  3382. e->duration = avio_rb64(pb);
  3383. e->time = avio_rb64(pb);
  3384. } else {
  3385. e->duration = avio_rb32(pb); /* segment duration */
  3386. e->time = (int32_t)avio_rb32(pb); /* media time */
  3387. }
  3388. e->rate = avio_rb32(pb) / 65536.0;
  3389. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3390. e->duration, e->time, e->rate);
  3391. }
  3392. sc->elst_count = i;
  3393. return 0;
  3394. }
  3395. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3396. {
  3397. MOVStreamContext *sc;
  3398. if (c->fc->nb_streams < 1)
  3399. return AVERROR_INVALIDDATA;
  3400. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3401. sc->timecode_track = avio_rb32(pb);
  3402. return 0;
  3403. }
  3404. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3405. {
  3406. int ret;
  3407. uint8_t uuid[16];
  3408. static const uint8_t uuid_isml_manifest[] = {
  3409. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3410. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3411. };
  3412. static const uint8_t uuid_xmp[] = {
  3413. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  3414. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  3415. };
  3416. if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
  3417. return AVERROR_INVALIDDATA;
  3418. ret = avio_read(pb, uuid, sizeof(uuid));
  3419. if (ret < 0) {
  3420. return ret;
  3421. } else if (ret != sizeof(uuid)) {
  3422. return AVERROR_INVALIDDATA;
  3423. }
  3424. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  3425. uint8_t *buffer, *ptr;
  3426. char *endptr;
  3427. size_t len = atom.size - sizeof(uuid);
  3428. if (len < 4) {
  3429. return AVERROR_INVALIDDATA;
  3430. }
  3431. ret = avio_skip(pb, 4); // zeroes
  3432. len -= 4;
  3433. buffer = av_mallocz(len + 1);
  3434. if (!buffer) {
  3435. return AVERROR(ENOMEM);
  3436. }
  3437. ret = avio_read(pb, buffer, len);
  3438. if (ret < 0) {
  3439. av_free(buffer);
  3440. return ret;
  3441. } else if (ret != len) {
  3442. av_free(buffer);
  3443. return AVERROR_INVALIDDATA;
  3444. }
  3445. ptr = buffer;
  3446. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  3447. ptr += sizeof("systemBitrate=\"") - 1;
  3448. c->bitrates_count++;
  3449. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  3450. if (!c->bitrates) {
  3451. c->bitrates_count = 0;
  3452. av_free(buffer);
  3453. return AVERROR(ENOMEM);
  3454. }
  3455. errno = 0;
  3456. ret = strtol(ptr, &endptr, 10);
  3457. if (ret < 0 || errno || *endptr != '"') {
  3458. c->bitrates[c->bitrates_count - 1] = 0;
  3459. } else {
  3460. c->bitrates[c->bitrates_count - 1] = ret;
  3461. }
  3462. }
  3463. av_free(buffer);
  3464. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  3465. uint8_t *buffer;
  3466. size_t len = atom.size - sizeof(uuid);
  3467. buffer = av_mallocz(len + 1);
  3468. if (!buffer) {
  3469. return AVERROR(ENOMEM);
  3470. }
  3471. ret = avio_read(pb, buffer, len);
  3472. if (ret < 0) {
  3473. av_free(buffer);
  3474. return ret;
  3475. } else if (ret != len) {
  3476. av_free(buffer);
  3477. return AVERROR_INVALIDDATA;
  3478. }
  3479. if (c->export_xmp) {
  3480. buffer[len] = '\0';
  3481. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  3482. }
  3483. av_free(buffer);
  3484. }
  3485. return 0;
  3486. }
  3487. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3488. {
  3489. int ret;
  3490. uint8_t content[16];
  3491. if (atom.size < 8)
  3492. return 0;
  3493. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  3494. if (ret < 0)
  3495. return ret;
  3496. if ( !c->found_moov
  3497. && !c->found_mdat
  3498. && !memcmp(content, "Anevia\x1A\x1A", 8)
  3499. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  3500. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  3501. }
  3502. return 0;
  3503. }
  3504. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3505. {
  3506. uint32_t format = avio_rl32(pb);
  3507. MOVStreamContext *sc;
  3508. enum AVCodecID id;
  3509. AVStream *st;
  3510. if (c->fc->nb_streams < 1)
  3511. return 0;
  3512. st = c->fc->streams[c->fc->nb_streams - 1];
  3513. sc = st->priv_data;
  3514. switch (sc->format)
  3515. {
  3516. case MKTAG('e','n','c','v'): // encrypted video
  3517. case MKTAG('e','n','c','a'): // encrypted audio
  3518. id = mov_codec_id(st, format);
  3519. if (st->codec->codec_id != AV_CODEC_ID_NONE &&
  3520. st->codec->codec_id != id) {
  3521. av_log(c->fc, AV_LOG_WARNING,
  3522. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  3523. (char*)&format, st->codec->codec_id);
  3524. break;
  3525. }
  3526. st->codec->codec_id = id;
  3527. sc->format = format;
  3528. break;
  3529. default:
  3530. if (format != sc->format) {
  3531. av_log(c->fc, AV_LOG_WARNING,
  3532. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  3533. (char*)&format, (char*)&sc->format);
  3534. }
  3535. break;
  3536. }
  3537. return 0;
  3538. }
  3539. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3540. {
  3541. AVStream *st;
  3542. MOVStreamContext *sc;
  3543. size_t auxiliary_info_size;
  3544. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  3545. return 0;
  3546. st = c->fc->streams[c->fc->nb_streams - 1];
  3547. sc = st->priv_data;
  3548. if (sc->cenc.aes_ctr) {
  3549. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  3550. return AVERROR_INVALIDDATA;
  3551. }
  3552. avio_r8(pb); /* version */
  3553. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  3554. avio_rb32(pb); /* entries */
  3555. if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
  3556. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
  3557. return AVERROR_INVALIDDATA;
  3558. }
  3559. /* save the auxiliary info as is */
  3560. auxiliary_info_size = atom.size - 8;
  3561. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  3562. if (!sc->cenc.auxiliary_info) {
  3563. return AVERROR(ENOMEM);
  3564. }
  3565. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  3566. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  3567. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  3568. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  3569. return AVERROR_INVALIDDATA;
  3570. }
  3571. /* initialize the cipher */
  3572. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  3573. if (!sc->cenc.aes_ctr) {
  3574. return AVERROR(ENOMEM);
  3575. }
  3576. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  3577. }
  3578. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
  3579. {
  3580. uint32_t encrypted_bytes;
  3581. uint16_t subsample_count;
  3582. uint16_t clear_bytes;
  3583. uint8_t* input_end = input + size;
  3584. /* read the iv */
  3585. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3586. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  3587. return AVERROR_INVALIDDATA;
  3588. }
  3589. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  3590. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  3591. if (!sc->cenc.use_subsamples)
  3592. {
  3593. /* decrypt the whole packet */
  3594. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  3595. return 0;
  3596. }
  3597. /* read the subsample count */
  3598. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3599. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  3600. return AVERROR_INVALIDDATA;
  3601. }
  3602. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  3603. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3604. for (; subsample_count > 0; subsample_count--)
  3605. {
  3606. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3607. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  3608. return AVERROR_INVALIDDATA;
  3609. }
  3610. /* read the number of clear / encrypted bytes */
  3611. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  3612. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3613. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  3614. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  3615. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  3616. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  3617. return AVERROR_INVALIDDATA;
  3618. }
  3619. /* skip the clear bytes */
  3620. input += clear_bytes;
  3621. /* decrypt the encrypted bytes */
  3622. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  3623. input += encrypted_bytes;
  3624. }
  3625. if (input < input_end) {
  3626. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  3627. return AVERROR_INVALIDDATA;
  3628. }
  3629. return 0;
  3630. }
  3631. static const MOVParseTableEntry mov_default_parse_table[] = {
  3632. { MKTAG('A','C','L','R'), mov_read_aclr },
  3633. { MKTAG('A','P','R','G'), mov_read_avid },
  3634. { MKTAG('A','A','L','P'), mov_read_avid },
  3635. { MKTAG('A','R','E','S'), mov_read_ares },
  3636. { MKTAG('a','v','s','s'), mov_read_avss },
  3637. { MKTAG('c','h','p','l'), mov_read_chpl },
  3638. { MKTAG('c','o','6','4'), mov_read_stco },
  3639. { MKTAG('c','o','l','r'), mov_read_colr },
  3640. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  3641. { MKTAG('d','i','n','f'), mov_read_default },
  3642. { MKTAG('D','p','x','E'), mov_read_dpxe },
  3643. { MKTAG('d','r','e','f'), mov_read_dref },
  3644. { MKTAG('e','d','t','s'), mov_read_default },
  3645. { MKTAG('e','l','s','t'), mov_read_elst },
  3646. { MKTAG('e','n','d','a'), mov_read_enda },
  3647. { MKTAG('f','i','e','l'), mov_read_fiel },
  3648. { MKTAG('a','d','r','m'), mov_read_adrm },
  3649. { MKTAG('f','t','y','p'), mov_read_ftyp },
  3650. { MKTAG('g','l','b','l'), mov_read_glbl },
  3651. { MKTAG('h','d','l','r'), mov_read_hdlr },
  3652. { MKTAG('i','l','s','t'), mov_read_ilst },
  3653. { MKTAG('j','p','2','h'), mov_read_jp2h },
  3654. { MKTAG('m','d','a','t'), mov_read_mdat },
  3655. { MKTAG('m','d','h','d'), mov_read_mdhd },
  3656. { MKTAG('m','d','i','a'), mov_read_default },
  3657. { MKTAG('m','e','t','a'), mov_read_meta },
  3658. { MKTAG('m','i','n','f'), mov_read_default },
  3659. { MKTAG('m','o','o','f'), mov_read_moof },
  3660. { MKTAG('m','o','o','v'), mov_read_moov },
  3661. { MKTAG('m','v','e','x'), mov_read_default },
  3662. { MKTAG('m','v','h','d'), mov_read_mvhd },
  3663. { MKTAG('S','M','I',' '), mov_read_svq3 },
  3664. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  3665. { MKTAG('a','v','c','C'), mov_read_glbl },
  3666. { MKTAG('p','a','s','p'), mov_read_pasp },
  3667. { MKTAG('s','i','d','x'), mov_read_sidx },
  3668. { MKTAG('s','t','b','l'), mov_read_default },
  3669. { MKTAG('s','t','c','o'), mov_read_stco },
  3670. { MKTAG('s','t','p','s'), mov_read_stps },
  3671. { MKTAG('s','t','r','f'), mov_read_strf },
  3672. { MKTAG('s','t','s','c'), mov_read_stsc },
  3673. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  3674. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  3675. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  3676. { MKTAG('s','t','t','s'), mov_read_stts },
  3677. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  3678. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  3679. { MKTAG('t','f','d','t'), mov_read_tfdt },
  3680. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  3681. { MKTAG('t','r','a','k'), mov_read_trak },
  3682. { MKTAG('t','r','a','f'), mov_read_default },
  3683. { MKTAG('t','r','e','f'), mov_read_default },
  3684. { MKTAG('t','m','c','d'), mov_read_tmcd },
  3685. { MKTAG('c','h','a','p'), mov_read_chap },
  3686. { MKTAG('t','r','e','x'), mov_read_trex },
  3687. { MKTAG('t','r','u','n'), mov_read_trun },
  3688. { MKTAG('u','d','t','a'), mov_read_default },
  3689. { MKTAG('w','a','v','e'), mov_read_wave },
  3690. { MKTAG('e','s','d','s'), mov_read_esds },
  3691. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  3692. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  3693. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  3694. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  3695. { MKTAG('w','f','e','x'), mov_read_wfex },
  3696. { MKTAG('c','m','o','v'), mov_read_cmov },
  3697. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  3698. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  3699. { MKTAG('s','b','g','p'), mov_read_sbgp },
  3700. { MKTAG('h','v','c','C'), mov_read_glbl },
  3701. { MKTAG('u','u','i','d'), mov_read_uuid },
  3702. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  3703. { MKTAG('f','r','e','e'), mov_read_free },
  3704. { MKTAG('-','-','-','-'), mov_read_custom },
  3705. { MKTAG('s','i','n','f'), mov_read_default },
  3706. { MKTAG('f','r','m','a'), mov_read_frma },
  3707. { MKTAG('s','e','n','c'), mov_read_senc },
  3708. { 0, NULL }
  3709. };
  3710. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3711. {
  3712. int64_t total_size = 0;
  3713. MOVAtom a;
  3714. int i;
  3715. if (c->atom_depth > 10) {
  3716. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  3717. return AVERROR_INVALIDDATA;
  3718. }
  3719. c->atom_depth ++;
  3720. if (atom.size < 0)
  3721. atom.size = INT64_MAX;
  3722. while (total_size <= atom.size - 8 && !avio_feof(pb)) {
  3723. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  3724. a.size = atom.size;
  3725. a.type=0;
  3726. if (atom.size >= 8) {
  3727. a.size = avio_rb32(pb);
  3728. a.type = avio_rl32(pb);
  3729. if (a.type == MKTAG('f','r','e','e') &&
  3730. a.size >= 8 &&
  3731. c->moov_retry) {
  3732. uint8_t buf[8];
  3733. uint32_t *type = (uint32_t *)buf + 1;
  3734. if (avio_read(pb, buf, 8) != 8)
  3735. return AVERROR_INVALIDDATA;
  3736. avio_seek(pb, -8, SEEK_CUR);
  3737. if (*type == MKTAG('m','v','h','d') ||
  3738. *type == MKTAG('c','m','o','v')) {
  3739. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  3740. a.type = MKTAG('m','o','o','v');
  3741. }
  3742. }
  3743. if (atom.type != MKTAG('r','o','o','t') &&
  3744. atom.type != MKTAG('m','o','o','v'))
  3745. {
  3746. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  3747. {
  3748. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  3749. avio_skip(pb, -8);
  3750. c->atom_depth --;
  3751. return 0;
  3752. }
  3753. }
  3754. total_size += 8;
  3755. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  3756. a.size = avio_rb64(pb) - 8;
  3757. total_size += 8;
  3758. }
  3759. }
  3760. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  3761. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  3762. if (a.size == 0) {
  3763. a.size = atom.size - total_size + 8;
  3764. }
  3765. a.size -= 8;
  3766. if (a.size < 0)
  3767. break;
  3768. a.size = FFMIN(a.size, atom.size - total_size);
  3769. for (i = 0; mov_default_parse_table[i].type; i++)
  3770. if (mov_default_parse_table[i].type == a.type) {
  3771. parse = mov_default_parse_table[i].parse;
  3772. break;
  3773. }
  3774. // container is user data
  3775. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  3776. atom.type == MKTAG('i','l','s','t')))
  3777. parse = mov_read_udta_string;
  3778. // Supports parsing the QuickTime Metadata Keys.
  3779. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  3780. if (!parse && c->found_hdlr_mdta &&
  3781. atom.type == MKTAG('m','e','t','a') &&
  3782. a.type == MKTAG('k','e','y','s')) {
  3783. parse = mov_read_keys;
  3784. }
  3785. if (!parse) { /* skip leaf atoms data */
  3786. avio_skip(pb, a.size);
  3787. } else {
  3788. int64_t start_pos = avio_tell(pb);
  3789. int64_t left;
  3790. int err = parse(c, pb, a);
  3791. if (err < 0) {
  3792. c->atom_depth --;
  3793. return err;
  3794. }
  3795. if (c->found_moov && c->found_mdat &&
  3796. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  3797. start_pos + a.size == avio_size(pb))) {
  3798. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  3799. c->next_root_atom = start_pos + a.size;
  3800. c->atom_depth --;
  3801. return 0;
  3802. }
  3803. left = a.size - avio_tell(pb) + start_pos;
  3804. if (left > 0) /* skip garbage at atom end */
  3805. avio_skip(pb, left);
  3806. else if (left < 0) {
  3807. av_log(c->fc, AV_LOG_WARNING,
  3808. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  3809. (char*)&a.type, -left);
  3810. avio_seek(pb, left, SEEK_CUR);
  3811. }
  3812. }
  3813. total_size += a.size;
  3814. }
  3815. if (total_size < atom.size && atom.size < 0x7ffff)
  3816. avio_skip(pb, atom.size - total_size);
  3817. c->atom_depth --;
  3818. return 0;
  3819. }
  3820. static int mov_probe(AVProbeData *p)
  3821. {
  3822. int64_t offset;
  3823. uint32_t tag;
  3824. int score = 0;
  3825. int moov_offset = -1;
  3826. /* check file header */
  3827. offset = 0;
  3828. for (;;) {
  3829. /* ignore invalid offset */
  3830. if ((offset + 8) > (unsigned int)p->buf_size)
  3831. break;
  3832. tag = AV_RL32(p->buf + offset + 4);
  3833. switch(tag) {
  3834. /* check for obvious tags */
  3835. case MKTAG('m','o','o','v'):
  3836. moov_offset = offset + 4;
  3837. case MKTAG('m','d','a','t'):
  3838. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3839. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3840. case MKTAG('f','t','y','p'):
  3841. if (AV_RB32(p->buf+offset) < 8 &&
  3842. (AV_RB32(p->buf+offset) != 1 ||
  3843. offset + 12 > (unsigned int)p->buf_size ||
  3844. AV_RB64(p->buf+offset + 8) == 0)) {
  3845. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3846. } else if (tag == MKTAG('f','t','y','p') &&
  3847. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  3848. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  3849. )) {
  3850. score = FFMAX(score, 5);
  3851. } else {
  3852. score = AVPROBE_SCORE_MAX;
  3853. }
  3854. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3855. break;
  3856. /* those are more common words, so rate then a bit less */
  3857. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3858. case MKTAG('w','i','d','e'):
  3859. case MKTAG('f','r','e','e'):
  3860. case MKTAG('j','u','n','k'):
  3861. case MKTAG('p','i','c','t'):
  3862. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  3863. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3864. break;
  3865. case MKTAG(0x82,0x82,0x7f,0x7d):
  3866. case MKTAG('s','k','i','p'):
  3867. case MKTAG('u','u','i','d'):
  3868. case MKTAG('p','r','f','l'):
  3869. /* if we only find those cause probedata is too small at least rate them */
  3870. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3871. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3872. break;
  3873. default:
  3874. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3875. }
  3876. }
  3877. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  3878. /* moov atom in the header - we should make sure that this is not a
  3879. * MOV-packed MPEG-PS */
  3880. offset = moov_offset;
  3881. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  3882. /* We found an actual hdlr atom */
  3883. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  3884. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  3885. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  3886. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  3887. /* We found a media handler reference atom describing an
  3888. * MPEG-PS-in-MOV, return a
  3889. * low score to force expanding the probe window until
  3890. * mpegps_probe finds what it needs */
  3891. return 5;
  3892. }else
  3893. /* Keep looking */
  3894. offset+=2;
  3895. }
  3896. }
  3897. return score;
  3898. }
  3899. // must be done after parsing all trak because there's no order requirement
  3900. static void mov_read_chapters(AVFormatContext *s)
  3901. {
  3902. MOVContext *mov = s->priv_data;
  3903. AVStream *st = NULL;
  3904. MOVStreamContext *sc;
  3905. int64_t cur_pos;
  3906. int i;
  3907. for (i = 0; i < s->nb_streams; i++)
  3908. if (s->streams[i]->id == mov->chapter_track) {
  3909. st = s->streams[i];
  3910. break;
  3911. }
  3912. if (!st) {
  3913. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  3914. return;
  3915. }
  3916. st->discard = AVDISCARD_ALL;
  3917. sc = st->priv_data;
  3918. cur_pos = avio_tell(sc->pb);
  3919. for (i = 0; i < st->nb_index_entries; i++) {
  3920. AVIndexEntry *sample = &st->index_entries[i];
  3921. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  3922. uint8_t *title;
  3923. uint16_t ch;
  3924. int len, title_len;
  3925. if (end < sample->timestamp) {
  3926. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  3927. end = AV_NOPTS_VALUE;
  3928. }
  3929. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3930. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  3931. goto finish;
  3932. }
  3933. // the first two bytes are the length of the title
  3934. len = avio_rb16(sc->pb);
  3935. if (len > sample->size-2)
  3936. continue;
  3937. title_len = 2*len + 1;
  3938. if (!(title = av_mallocz(title_len)))
  3939. goto finish;
  3940. // The samples could theoretically be in any encoding if there's an encd
  3941. // atom following, but in practice are only utf-8 or utf-16, distinguished
  3942. // instead by the presence of a BOM
  3943. if (!len) {
  3944. title[0] = 0;
  3945. } else {
  3946. ch = avio_rb16(sc->pb);
  3947. if (ch == 0xfeff)
  3948. avio_get_str16be(sc->pb, len, title, title_len);
  3949. else if (ch == 0xfffe)
  3950. avio_get_str16le(sc->pb, len, title, title_len);
  3951. else {
  3952. AV_WB16(title, ch);
  3953. if (len == 1 || len == 2)
  3954. title[len] = 0;
  3955. else
  3956. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  3957. }
  3958. }
  3959. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  3960. av_freep(&title);
  3961. }
  3962. finish:
  3963. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3964. }
  3965. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  3966. uint32_t value, int flags)
  3967. {
  3968. AVTimecode tc;
  3969. char buf[AV_TIMECODE_STR_SIZE];
  3970. AVRational rate = {st->codec->time_base.den,
  3971. st->codec->time_base.num};
  3972. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  3973. if (ret < 0)
  3974. return ret;
  3975. av_dict_set(&st->metadata, "timecode",
  3976. av_timecode_make_string(&tc, buf, value), 0);
  3977. return 0;
  3978. }
  3979. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  3980. {
  3981. MOVStreamContext *sc = st->priv_data;
  3982. int flags = 0;
  3983. int64_t cur_pos = avio_tell(sc->pb);
  3984. uint32_t value;
  3985. if (!st->nb_index_entries)
  3986. return -1;
  3987. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  3988. value = avio_rb32(s->pb);
  3989. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  3990. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  3991. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  3992. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  3993. * not the case) and thus assume "frame number format" instead of QT one.
  3994. * No sample with tmcd track can be found with a QT timecode at the moment,
  3995. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  3996. * format). */
  3997. parse_timecode_in_framenum_format(s, st, value, flags);
  3998. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3999. return 0;
  4000. }
  4001. static int mov_read_close(AVFormatContext *s)
  4002. {
  4003. MOVContext *mov = s->priv_data;
  4004. int i, j;
  4005. for (i = 0; i < s->nb_streams; i++) {
  4006. AVStream *st = s->streams[i];
  4007. MOVStreamContext *sc = st->priv_data;
  4008. if (!sc)
  4009. continue;
  4010. av_freep(&sc->ctts_data);
  4011. for (j = 0; j < sc->drefs_count; j++) {
  4012. av_freep(&sc->drefs[j].path);
  4013. av_freep(&sc->drefs[j].dir);
  4014. }
  4015. av_freep(&sc->drefs);
  4016. sc->drefs_count = 0;
  4017. if (!sc->pb_is_copied)
  4018. ff_format_io_close(s, &sc->pb);
  4019. sc->pb = NULL;
  4020. av_freep(&sc->chunk_offsets);
  4021. av_freep(&sc->stsc_data);
  4022. av_freep(&sc->sample_sizes);
  4023. av_freep(&sc->keyframes);
  4024. av_freep(&sc->stts_data);
  4025. av_freep(&sc->stps_data);
  4026. av_freep(&sc->elst_data);
  4027. av_freep(&sc->rap_group);
  4028. av_freep(&sc->display_matrix);
  4029. av_freep(&sc->cenc.auxiliary_info);
  4030. av_aes_ctr_free(sc->cenc.aes_ctr);
  4031. }
  4032. if (mov->dv_demux) {
  4033. avformat_free_context(mov->dv_fctx);
  4034. mov->dv_fctx = NULL;
  4035. }
  4036. if (mov->meta_keys) {
  4037. for (i = 1; i < mov->meta_keys_count; i++) {
  4038. av_freep(&mov->meta_keys[i]);
  4039. }
  4040. av_freep(&mov->meta_keys);
  4041. }
  4042. av_freep(&mov->trex_data);
  4043. av_freep(&mov->bitrates);
  4044. for (i = 0; i < mov->fragment_index_count; i++) {
  4045. MOVFragmentIndex* index = mov->fragment_index_data[i];
  4046. av_freep(&index->items);
  4047. av_freep(&mov->fragment_index_data[i]);
  4048. }
  4049. av_freep(&mov->fragment_index_data);
  4050. av_freep(&mov->aes_decrypt);
  4051. return 0;
  4052. }
  4053. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  4054. {
  4055. int i;
  4056. for (i = 0; i < s->nb_streams; i++) {
  4057. AVStream *st = s->streams[i];
  4058. MOVStreamContext *sc = st->priv_data;
  4059. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  4060. sc->timecode_track == tmcd_id)
  4061. return 1;
  4062. }
  4063. return 0;
  4064. }
  4065. /* look for a tmcd track not referenced by any video track, and export it globally */
  4066. static void export_orphan_timecode(AVFormatContext *s)
  4067. {
  4068. int i;
  4069. for (i = 0; i < s->nb_streams; i++) {
  4070. AVStream *st = s->streams[i];
  4071. if (st->codec->codec_tag == MKTAG('t','m','c','d') &&
  4072. !tmcd_is_referenced(s, i + 1)) {
  4073. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  4074. if (tcr) {
  4075. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  4076. break;
  4077. }
  4078. }
  4079. }
  4080. }
  4081. static int read_tfra(MOVContext *mov, AVIOContext *f)
  4082. {
  4083. MOVFragmentIndex* index = NULL;
  4084. int version, fieldlength, i, j;
  4085. int64_t pos = avio_tell(f);
  4086. uint32_t size = avio_rb32(f);
  4087. void *tmp;
  4088. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  4089. return 1;
  4090. }
  4091. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  4092. index = av_mallocz(sizeof(MOVFragmentIndex));
  4093. if (!index) {
  4094. return AVERROR(ENOMEM);
  4095. }
  4096. tmp = av_realloc_array(mov->fragment_index_data,
  4097. mov->fragment_index_count + 1,
  4098. sizeof(MOVFragmentIndex*));
  4099. if (!tmp) {
  4100. av_freep(&index);
  4101. return AVERROR(ENOMEM);
  4102. }
  4103. mov->fragment_index_data = tmp;
  4104. mov->fragment_index_data[mov->fragment_index_count++] = index;
  4105. version = avio_r8(f);
  4106. avio_rb24(f);
  4107. index->track_id = avio_rb32(f);
  4108. fieldlength = avio_rb32(f);
  4109. index->item_count = avio_rb32(f);
  4110. index->items = av_mallocz_array(
  4111. index->item_count, sizeof(MOVFragmentIndexItem));
  4112. if (!index->items) {
  4113. index->item_count = 0;
  4114. return AVERROR(ENOMEM);
  4115. }
  4116. for (i = 0; i < index->item_count; i++) {
  4117. int64_t time, offset;
  4118. if (avio_feof(f)) {
  4119. index->item_count = 0;
  4120. av_freep(&index->items);
  4121. return AVERROR_INVALIDDATA;
  4122. }
  4123. if (version == 1) {
  4124. time = avio_rb64(f);
  4125. offset = avio_rb64(f);
  4126. } else {
  4127. time = avio_rb32(f);
  4128. offset = avio_rb32(f);
  4129. }
  4130. index->items[i].time = time;
  4131. index->items[i].moof_offset = offset;
  4132. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  4133. avio_r8(f);
  4134. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  4135. avio_r8(f);
  4136. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  4137. avio_r8(f);
  4138. }
  4139. avio_seek(f, pos + size, SEEK_SET);
  4140. return 0;
  4141. }
  4142. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  4143. {
  4144. int64_t stream_size = avio_size(f);
  4145. int64_t original_pos = avio_tell(f);
  4146. int64_t seek_ret;
  4147. int32_t mfra_size;
  4148. int ret = -1;
  4149. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  4150. ret = seek_ret;
  4151. goto fail;
  4152. }
  4153. mfra_size = avio_rb32(f);
  4154. if (mfra_size < 0 || mfra_size > stream_size) {
  4155. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  4156. goto fail;
  4157. }
  4158. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  4159. ret = seek_ret;
  4160. goto fail;
  4161. }
  4162. if (avio_rb32(f) != mfra_size) {
  4163. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  4164. goto fail;
  4165. }
  4166. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  4167. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  4168. goto fail;
  4169. }
  4170. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  4171. do {
  4172. ret = read_tfra(c, f);
  4173. if (ret < 0)
  4174. goto fail;
  4175. } while (!ret);
  4176. ret = 0;
  4177. fail:
  4178. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  4179. if (seek_ret < 0) {
  4180. av_log(c->fc, AV_LOG_ERROR,
  4181. "failed to seek back after looking for mfra\n");
  4182. ret = seek_ret;
  4183. }
  4184. return ret;
  4185. }
  4186. static int mov_read_header(AVFormatContext *s)
  4187. {
  4188. MOVContext *mov = s->priv_data;
  4189. AVIOContext *pb = s->pb;
  4190. int j, err;
  4191. MOVAtom atom = { AV_RL32("root") };
  4192. int i;
  4193. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  4194. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  4195. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  4196. return AVERROR(EINVAL);
  4197. }
  4198. mov->fc = s;
  4199. mov->trak_index = -1;
  4200. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  4201. if (pb->seekable)
  4202. atom.size = avio_size(pb);
  4203. else
  4204. atom.size = INT64_MAX;
  4205. /* check MOV header */
  4206. do {
  4207. if (mov->moov_retry)
  4208. avio_seek(pb, 0, SEEK_SET);
  4209. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  4210. av_log(s, AV_LOG_ERROR, "error reading header\n");
  4211. mov_read_close(s);
  4212. return err;
  4213. }
  4214. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  4215. if (!mov->found_moov) {
  4216. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  4217. mov_read_close(s);
  4218. return AVERROR_INVALIDDATA;
  4219. }
  4220. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  4221. if (pb->seekable) {
  4222. if (mov->chapter_track > 0 && !mov->ignore_chapters)
  4223. mov_read_chapters(s);
  4224. for (i = 0; i < s->nb_streams; i++)
  4225. if (s->streams[i]->codec->codec_tag == AV_RL32("tmcd"))
  4226. mov_read_timecode_track(s, s->streams[i]);
  4227. }
  4228. /* copy timecode metadata from tmcd tracks to the related video streams */
  4229. for (i = 0; i < s->nb_streams; i++) {
  4230. AVStream *st = s->streams[i];
  4231. MOVStreamContext *sc = st->priv_data;
  4232. if (sc->timecode_track > 0) {
  4233. AVDictionaryEntry *tcr;
  4234. int tmcd_st_id = -1;
  4235. for (j = 0; j < s->nb_streams; j++)
  4236. if (s->streams[j]->id == sc->timecode_track)
  4237. tmcd_st_id = j;
  4238. if (tmcd_st_id < 0 || tmcd_st_id == i)
  4239. continue;
  4240. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  4241. if (tcr)
  4242. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  4243. }
  4244. }
  4245. export_orphan_timecode(s);
  4246. for (i = 0; i < s->nb_streams; i++) {
  4247. AVStream *st = s->streams[i];
  4248. MOVStreamContext *sc = st->priv_data;
  4249. fix_timescale(mov, sc);
  4250. if(st->codec->codec_type == AVMEDIA_TYPE_AUDIO && st->codec->codec_id == AV_CODEC_ID_AAC) {
  4251. st->skip_samples = sc->start_pad;
  4252. }
  4253. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  4254. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  4255. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  4256. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4257. if (st->codec->width <= 0 || st->codec->height <= 0) {
  4258. st->codec->width = sc->width;
  4259. st->codec->height = sc->height;
  4260. }
  4261. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  4262. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  4263. return err;
  4264. }
  4265. }
  4266. if (mov->handbrake_version &&
  4267. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  4268. st->codec->codec_id == AV_CODEC_ID_MP3
  4269. ) {
  4270. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  4271. st->need_parsing = AVSTREAM_PARSE_FULL;
  4272. }
  4273. }
  4274. if (mov->trex_data) {
  4275. for (i = 0; i < s->nb_streams; i++) {
  4276. AVStream *st = s->streams[i];
  4277. MOVStreamContext *sc = st->priv_data;
  4278. if (st->duration > 0)
  4279. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  4280. }
  4281. }
  4282. if (mov->use_mfra_for > 0) {
  4283. for (i = 0; i < s->nb_streams; i++) {
  4284. AVStream *st = s->streams[i];
  4285. MOVStreamContext *sc = st->priv_data;
  4286. if (sc->duration_for_fps > 0) {
  4287. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale /
  4288. sc->duration_for_fps;
  4289. }
  4290. }
  4291. }
  4292. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  4293. if (mov->bitrates[i]) {
  4294. s->streams[i]->codec->bit_rate = mov->bitrates[i];
  4295. }
  4296. }
  4297. ff_rfps_calculate(s);
  4298. for (i = 0; i < s->nb_streams; i++) {
  4299. AVStream *st = s->streams[i];
  4300. MOVStreamContext *sc = st->priv_data;
  4301. switch (st->codec->codec_type) {
  4302. case AVMEDIA_TYPE_AUDIO:
  4303. err = ff_replaygain_export(st, s->metadata);
  4304. if (err < 0) {
  4305. mov_read_close(s);
  4306. return err;
  4307. }
  4308. break;
  4309. case AVMEDIA_TYPE_VIDEO:
  4310. if (sc->display_matrix) {
  4311. AVPacketSideData *sd, *tmp;
  4312. tmp = av_realloc_array(st->side_data,
  4313. st->nb_side_data + 1, sizeof(*tmp));
  4314. if (!tmp)
  4315. return AVERROR(ENOMEM);
  4316. st->side_data = tmp;
  4317. st->nb_side_data++;
  4318. sd = &st->side_data[st->nb_side_data - 1];
  4319. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  4320. sd->size = sizeof(int32_t) * 9;
  4321. sd->data = (uint8_t*)sc->display_matrix;
  4322. sc->display_matrix = NULL;
  4323. }
  4324. break;
  4325. }
  4326. }
  4327. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  4328. return 0;
  4329. }
  4330. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  4331. {
  4332. AVIndexEntry *sample = NULL;
  4333. int64_t best_dts = INT64_MAX;
  4334. int i;
  4335. for (i = 0; i < s->nb_streams; i++) {
  4336. AVStream *avst = s->streams[i];
  4337. MOVStreamContext *msc = avst->priv_data;
  4338. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  4339. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  4340. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  4341. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  4342. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  4343. (s->pb->seekable &&
  4344. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  4345. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  4346. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  4347. sample = current_sample;
  4348. best_dts = dts;
  4349. *st = avst;
  4350. }
  4351. }
  4352. }
  4353. return sample;
  4354. }
  4355. static int should_retry(AVIOContext *pb, int error_code) {
  4356. if (error_code == AVERROR_EOF || avio_feof(pb))
  4357. return 0;
  4358. return 1;
  4359. }
  4360. static int mov_switch_root(AVFormatContext *s, int64_t target)
  4361. {
  4362. int ret;
  4363. MOVContext *mov = s->priv_data;
  4364. int i, j;
  4365. int already_read = 0;
  4366. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  4367. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  4368. return AVERROR_INVALIDDATA;
  4369. }
  4370. mov->next_root_atom = 0;
  4371. for (i = 0; i < mov->fragment_index_count; i++) {
  4372. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4373. int found = 0;
  4374. for (j = 0; j < index->item_count; j++) {
  4375. MOVFragmentIndexItem *item = &index->items[j];
  4376. if (found) {
  4377. mov->next_root_atom = item->moof_offset;
  4378. break; // Advance to next index in outer loop
  4379. } else if (item->moof_offset == target) {
  4380. index->current_item = FFMIN(j, index->current_item);
  4381. if (item->headers_read)
  4382. already_read = 1;
  4383. item->headers_read = 1;
  4384. found = 1;
  4385. }
  4386. }
  4387. if (!found)
  4388. index->current_item = 0;
  4389. }
  4390. if (already_read)
  4391. return 0;
  4392. mov->found_mdat = 0;
  4393. ret = mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX });
  4394. if (ret < 0)
  4395. return ret;
  4396. if (avio_feof(s->pb))
  4397. return AVERROR_EOF;
  4398. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  4399. return 1;
  4400. }
  4401. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  4402. {
  4403. MOVContext *mov = s->priv_data;
  4404. MOVStreamContext *sc;
  4405. AVIndexEntry *sample;
  4406. AVStream *st = NULL;
  4407. int ret;
  4408. mov->fc = s;
  4409. retry:
  4410. sample = mov_find_next_sample(s, &st);
  4411. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  4412. if (!mov->next_root_atom)
  4413. return AVERROR_EOF;
  4414. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  4415. return ret;
  4416. goto retry;
  4417. }
  4418. sc = st->priv_data;
  4419. /* must be done just before reading, to avoid infinite loop on sample */
  4420. sc->current_sample++;
  4421. if (mov->next_root_atom) {
  4422. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  4423. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  4424. }
  4425. if (st->discard != AVDISCARD_ALL) {
  4426. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  4427. if (ret64 != sample->pos) {
  4428. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  4429. sc->ffindex, sample->pos);
  4430. sc->current_sample -= should_retry(sc->pb, ret64);
  4431. return AVERROR_INVALIDDATA;
  4432. }
  4433. ret = av_get_packet(sc->pb, pkt, sample->size);
  4434. if (ret < 0) {
  4435. sc->current_sample -= should_retry(sc->pb, ret);
  4436. return ret;
  4437. }
  4438. if (sc->has_palette) {
  4439. uint8_t *pal;
  4440. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  4441. if (!pal) {
  4442. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  4443. } else {
  4444. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  4445. sc->has_palette = 0;
  4446. }
  4447. }
  4448. #if CONFIG_DV_DEMUXER
  4449. if (mov->dv_demux && sc->dv_audio_container) {
  4450. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  4451. av_freep(&pkt->data);
  4452. pkt->size = 0;
  4453. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  4454. if (ret < 0)
  4455. return ret;
  4456. }
  4457. #endif
  4458. }
  4459. pkt->stream_index = sc->ffindex;
  4460. pkt->dts = sample->timestamp;
  4461. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  4462. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  4463. /* update ctts context */
  4464. sc->ctts_sample++;
  4465. if (sc->ctts_index < sc->ctts_count &&
  4466. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  4467. sc->ctts_index++;
  4468. sc->ctts_sample = 0;
  4469. }
  4470. if (sc->wrong_dts)
  4471. pkt->dts = AV_NOPTS_VALUE;
  4472. } else {
  4473. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  4474. st->index_entries[sc->current_sample].timestamp : st->duration;
  4475. pkt->duration = next_dts - pkt->dts;
  4476. pkt->pts = pkt->dts;
  4477. }
  4478. if (st->discard == AVDISCARD_ALL)
  4479. goto retry;
  4480. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  4481. pkt->pos = sample->pos;
  4482. if (mov->aax_mode)
  4483. aax_filter(pkt->data, pkt->size, mov);
  4484. if (sc->cenc.aes_ctr) {
  4485. ret = cenc_filter(mov, sc, pkt->data, pkt->size);
  4486. if (ret) {
  4487. return ret;
  4488. }
  4489. }
  4490. return 0;
  4491. }
  4492. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  4493. {
  4494. MOVContext *mov = s->priv_data;
  4495. int i, j;
  4496. if (!mov->fragment_index_complete)
  4497. return 0;
  4498. for (i = 0; i < mov->fragment_index_count; i++) {
  4499. if (mov->fragment_index_data[i]->track_id == st->id) {
  4500. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4501. for (j = index->item_count - 1; j >= 0; j--) {
  4502. if (index->items[j].time <= timestamp) {
  4503. if (index->items[j].headers_read)
  4504. return 0;
  4505. return mov_switch_root(s, index->items[j].moof_offset);
  4506. }
  4507. }
  4508. }
  4509. }
  4510. return 0;
  4511. }
  4512. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  4513. {
  4514. MOVStreamContext *sc = st->priv_data;
  4515. int sample, time_sample;
  4516. int i;
  4517. int ret = mov_seek_fragment(s, st, timestamp);
  4518. if (ret < 0)
  4519. return ret;
  4520. sample = av_index_search_timestamp(st, timestamp, flags);
  4521. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  4522. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  4523. sample = 0;
  4524. if (sample < 0) /* not sure what to do */
  4525. return AVERROR_INVALIDDATA;
  4526. sc->current_sample = sample;
  4527. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  4528. /* adjust ctts index */
  4529. if (sc->ctts_data) {
  4530. time_sample = 0;
  4531. for (i = 0; i < sc->ctts_count; i++) {
  4532. int next = time_sample + sc->ctts_data[i].count;
  4533. if (next > sc->current_sample) {
  4534. sc->ctts_index = i;
  4535. sc->ctts_sample = sc->current_sample - time_sample;
  4536. break;
  4537. }
  4538. time_sample = next;
  4539. }
  4540. }
  4541. return sample;
  4542. }
  4543. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  4544. {
  4545. MOVContext *mc = s->priv_data;
  4546. AVStream *st;
  4547. int sample;
  4548. int i;
  4549. if (stream_index >= s->nb_streams)
  4550. return AVERROR_INVALIDDATA;
  4551. st = s->streams[stream_index];
  4552. sample = mov_seek_stream(s, st, sample_time, flags);
  4553. if (sample < 0)
  4554. return sample;
  4555. if (mc->seek_individually) {
  4556. /* adjust seek timestamp to found sample timestamp */
  4557. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  4558. for (i = 0; i < s->nb_streams; i++) {
  4559. int64_t timestamp;
  4560. MOVStreamContext *sc = s->streams[i]->priv_data;
  4561. st = s->streams[i];
  4562. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  4563. if (stream_index == i)
  4564. continue;
  4565. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  4566. mov_seek_stream(s, st, timestamp, flags);
  4567. }
  4568. } else {
  4569. for (i = 0; i < s->nb_streams; i++) {
  4570. MOVStreamContext *sc;
  4571. st = s->streams[i];
  4572. sc = st->priv_data;
  4573. sc->current_sample = 0;
  4574. }
  4575. while (1) {
  4576. MOVStreamContext *sc;
  4577. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  4578. if (!entry)
  4579. return AVERROR_INVALIDDATA;
  4580. sc = st->priv_data;
  4581. if (sc->ffindex == stream_index && sc->current_sample == sample)
  4582. break;
  4583. sc->current_sample++;
  4584. }
  4585. }
  4586. return 0;
  4587. }
  4588. #define OFFSET(x) offsetof(MOVContext, x)
  4589. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  4590. static const AVOption mov_options[] = {
  4591. {"use_absolute_path",
  4592. "allow using absolute path when opening alias, this is a possible security issue",
  4593. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4594. 0, 1, FLAGS},
  4595. {"seek_streams_individually",
  4596. "Seek each stream individually to the to the closest point",
  4597. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  4598. 0, 1, FLAGS},
  4599. {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4600. 0, 1, FLAGS},
  4601. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4602. 0, 1, FLAGS},
  4603. {"use_mfra_for",
  4604. "use mfra for fragment timestamps",
  4605. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  4606. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  4607. "use_mfra_for"},
  4608. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  4609. FLAGS, "use_mfra_for" },
  4610. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  4611. FLAGS, "use_mfra_for" },
  4612. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  4613. FLAGS, "use_mfra_for" },
  4614. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  4615. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4616. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  4617. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4618. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  4619. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4620. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  4621. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  4622. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  4623. .flags = AV_OPT_FLAG_DECODING_PARAM },
  4624. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4625. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  4626. {.i64 = 0}, 0, 1, FLAGS },
  4627. { NULL },
  4628. };
  4629. static const AVClass mov_class = {
  4630. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  4631. .item_name = av_default_item_name,
  4632. .option = mov_options,
  4633. .version = LIBAVUTIL_VERSION_INT,
  4634. };
  4635. AVInputFormat ff_mov_demuxer = {
  4636. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  4637. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  4638. .priv_class = &mov_class,
  4639. .priv_data_size = sizeof(MOVContext),
  4640. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  4641. .read_probe = mov_probe,
  4642. .read_header = mov_read_header,
  4643. .read_packet = mov_read_packet,
  4644. .read_close = mov_read_close,
  4645. .read_seek = mov_read_seek,
  4646. .flags = AVFMT_NO_BYTE_SEEK,
  4647. };