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.

5401 lines
180KB

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