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.

6842 lines
233KB

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