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.

6558 lines
223KB

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