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.

6832 lines
232KB

  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. av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
  2117. if (!entries)
  2118. return 0;
  2119. if (sc->stsc_data)
  2120. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2121. av_free(sc->stsc_data);
  2122. sc->stsc_count = 0;
  2123. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2124. if (!sc->stsc_data)
  2125. return AVERROR(ENOMEM);
  2126. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2127. sc->stsc_data[i].first = avio_rb32(pb);
  2128. sc->stsc_data[i].count = avio_rb32(pb);
  2129. sc->stsc_data[i].id = avio_rb32(pb);
  2130. }
  2131. sc->stsc_count = i;
  2132. if (pb->eof_reached)
  2133. return AVERROR_EOF;
  2134. return 0;
  2135. }
  2136. static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
  2137. {
  2138. return index < count - 1;
  2139. }
  2140. /* Compute the samples value for the stsc entry at the given index. */
  2141. static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
  2142. {
  2143. int chunk_count;
  2144. if (mov_stsc_index_valid(index, sc->stsc_count))
  2145. chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
  2146. else
  2147. chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
  2148. return sc->stsc_data[index].count * chunk_count;
  2149. }
  2150. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2151. {
  2152. AVStream *st;
  2153. MOVStreamContext *sc;
  2154. unsigned i, entries;
  2155. if (c->fc->nb_streams < 1)
  2156. return 0;
  2157. st = c->fc->streams[c->fc->nb_streams-1];
  2158. sc = st->priv_data;
  2159. avio_rb32(pb); // version + flags
  2160. entries = avio_rb32(pb);
  2161. if (sc->stps_data)
  2162. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2163. av_free(sc->stps_data);
  2164. sc->stps_count = 0;
  2165. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2166. if (!sc->stps_data)
  2167. return AVERROR(ENOMEM);
  2168. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2169. sc->stps_data[i] = avio_rb32(pb);
  2170. }
  2171. sc->stps_count = i;
  2172. if (pb->eof_reached)
  2173. return AVERROR_EOF;
  2174. return 0;
  2175. }
  2176. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2177. {
  2178. AVStream *st;
  2179. MOVStreamContext *sc;
  2180. unsigned int i, entries;
  2181. if (c->fc->nb_streams < 1)
  2182. return 0;
  2183. st = c->fc->streams[c->fc->nb_streams-1];
  2184. sc = st->priv_data;
  2185. avio_r8(pb); /* version */
  2186. avio_rb24(pb); /* flags */
  2187. entries = avio_rb32(pb);
  2188. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
  2189. if (!entries)
  2190. {
  2191. sc->keyframe_absent = 1;
  2192. if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2193. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2194. return 0;
  2195. }
  2196. if (sc->keyframes)
  2197. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2198. if (entries >= UINT_MAX / sizeof(int))
  2199. return AVERROR_INVALIDDATA;
  2200. av_freep(&sc->keyframes);
  2201. sc->keyframe_count = 0;
  2202. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2203. if (!sc->keyframes)
  2204. return AVERROR(ENOMEM);
  2205. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2206. sc->keyframes[i] = avio_rb32(pb);
  2207. }
  2208. sc->keyframe_count = i;
  2209. if (pb->eof_reached)
  2210. return AVERROR_EOF;
  2211. return 0;
  2212. }
  2213. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2214. {
  2215. AVStream *st;
  2216. MOVStreamContext *sc;
  2217. unsigned int i, entries, sample_size, field_size, num_bytes;
  2218. GetBitContext gb;
  2219. unsigned char* buf;
  2220. int ret;
  2221. if (c->fc->nb_streams < 1)
  2222. return 0;
  2223. st = c->fc->streams[c->fc->nb_streams-1];
  2224. sc = st->priv_data;
  2225. avio_r8(pb); /* version */
  2226. avio_rb24(pb); /* flags */
  2227. if (atom.type == MKTAG('s','t','s','z')) {
  2228. sample_size = avio_rb32(pb);
  2229. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2230. sc->sample_size = sample_size;
  2231. sc->stsz_sample_size = sample_size;
  2232. field_size = 32;
  2233. } else {
  2234. sample_size = 0;
  2235. avio_rb24(pb); /* reserved */
  2236. field_size = avio_r8(pb);
  2237. }
  2238. entries = avio_rb32(pb);
  2239. av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
  2240. sc->sample_count = entries;
  2241. if (sample_size)
  2242. return 0;
  2243. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2244. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
  2245. return AVERROR_INVALIDDATA;
  2246. }
  2247. if (!entries)
  2248. return 0;
  2249. if (entries >= (UINT_MAX - 4) / field_size)
  2250. return AVERROR_INVALIDDATA;
  2251. if (sc->sample_sizes)
  2252. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2253. av_free(sc->sample_sizes);
  2254. sc->sample_count = 0;
  2255. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2256. if (!sc->sample_sizes)
  2257. return AVERROR(ENOMEM);
  2258. num_bytes = (entries*field_size+4)>>3;
  2259. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2260. if (!buf) {
  2261. av_freep(&sc->sample_sizes);
  2262. return AVERROR(ENOMEM);
  2263. }
  2264. ret = ffio_read_size(pb, buf, num_bytes);
  2265. if (ret < 0) {
  2266. av_freep(&sc->sample_sizes);
  2267. av_free(buf);
  2268. return ret;
  2269. }
  2270. init_get_bits(&gb, buf, 8*num_bytes);
  2271. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2272. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2273. sc->data_size += sc->sample_sizes[i];
  2274. }
  2275. sc->sample_count = i;
  2276. av_free(buf);
  2277. if (pb->eof_reached)
  2278. return AVERROR_EOF;
  2279. return 0;
  2280. }
  2281. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2282. {
  2283. AVStream *st;
  2284. MOVStreamContext *sc;
  2285. unsigned int i, entries;
  2286. int64_t duration=0;
  2287. int64_t total_sample_count=0;
  2288. if (c->fc->nb_streams < 1)
  2289. return 0;
  2290. st = c->fc->streams[c->fc->nb_streams-1];
  2291. sc = st->priv_data;
  2292. avio_r8(pb); /* version */
  2293. avio_rb24(pb); /* flags */
  2294. entries = avio_rb32(pb);
  2295. av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
  2296. c->fc->nb_streams-1, entries);
  2297. if (sc->stts_data)
  2298. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2299. av_free(sc->stts_data);
  2300. sc->stts_count = 0;
  2301. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2302. if (!sc->stts_data)
  2303. return AVERROR(ENOMEM);
  2304. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2305. int sample_duration;
  2306. unsigned int sample_count;
  2307. sample_count=avio_rb32(pb);
  2308. sample_duration = avio_rb32(pb);
  2309. sc->stts_data[i].count= sample_count;
  2310. sc->stts_data[i].duration= sample_duration;
  2311. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2312. sample_count, sample_duration);
  2313. if ( i+1 == entries
  2314. && i
  2315. && sample_count == 1
  2316. && total_sample_count > 100
  2317. && sample_duration/10 > duration / total_sample_count)
  2318. sample_duration = duration / total_sample_count;
  2319. duration+=(int64_t)sample_duration*sample_count;
  2320. total_sample_count+=sample_count;
  2321. }
  2322. sc->stts_count = i;
  2323. sc->duration_for_fps += duration;
  2324. sc->nb_frames_for_fps += total_sample_count;
  2325. if (pb->eof_reached)
  2326. return AVERROR_EOF;
  2327. st->nb_frames= total_sample_count;
  2328. if (duration)
  2329. st->duration= duration;
  2330. sc->track_end = duration;
  2331. return 0;
  2332. }
  2333. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2334. {
  2335. if (duration < 0) {
  2336. if (duration == INT_MIN) {
  2337. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2338. duration++;
  2339. }
  2340. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2341. }
  2342. }
  2343. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2344. {
  2345. AVStream *st;
  2346. MOVStreamContext *sc;
  2347. unsigned int i, j, entries, ctts_count = 0;
  2348. if (c->fc->nb_streams < 1)
  2349. return 0;
  2350. st = c->fc->streams[c->fc->nb_streams-1];
  2351. sc = st->priv_data;
  2352. avio_r8(pb); /* version */
  2353. avio_rb24(pb); /* flags */
  2354. entries = avio_rb32(pb);
  2355. av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
  2356. if (!entries)
  2357. return 0;
  2358. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2359. return AVERROR_INVALIDDATA;
  2360. av_freep(&sc->ctts_data);
  2361. sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data));
  2362. if (!sc->ctts_data)
  2363. return AVERROR(ENOMEM);
  2364. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2365. int count =avio_rb32(pb);
  2366. int duration =avio_rb32(pb);
  2367. if (count <= 0) {
  2368. av_log(c->fc, AV_LOG_TRACE,
  2369. "ignoring CTTS entry with count=%d duration=%d\n",
  2370. count, duration);
  2371. continue;
  2372. }
  2373. /* Expand entries such that we have a 1-1 mapping with samples. */
  2374. for (j = 0; j < count; j++)
  2375. add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size, 1, duration);
  2376. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2377. count, duration);
  2378. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2379. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2380. av_freep(&sc->ctts_data);
  2381. sc->ctts_count = 0;
  2382. return 0;
  2383. }
  2384. if (i+2<entries)
  2385. mov_update_dts_shift(sc, duration);
  2386. }
  2387. sc->ctts_count = ctts_count;
  2388. if (pb->eof_reached)
  2389. return AVERROR_EOF;
  2390. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2391. return 0;
  2392. }
  2393. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2394. {
  2395. AVStream *st;
  2396. MOVStreamContext *sc;
  2397. unsigned int i, entries;
  2398. uint8_t version;
  2399. uint32_t grouping_type;
  2400. if (c->fc->nb_streams < 1)
  2401. return 0;
  2402. st = c->fc->streams[c->fc->nb_streams-1];
  2403. sc = st->priv_data;
  2404. version = avio_r8(pb); /* version */
  2405. avio_rb24(pb); /* flags */
  2406. grouping_type = avio_rl32(pb);
  2407. if (grouping_type != MKTAG( 'r','a','p',' '))
  2408. return 0; /* only support 'rap ' grouping */
  2409. if (version == 1)
  2410. avio_rb32(pb); /* grouping_type_parameter */
  2411. entries = avio_rb32(pb);
  2412. if (!entries)
  2413. return 0;
  2414. if (sc->rap_group)
  2415. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2416. av_free(sc->rap_group);
  2417. sc->rap_group_count = 0;
  2418. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2419. if (!sc->rap_group)
  2420. return AVERROR(ENOMEM);
  2421. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2422. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2423. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2424. }
  2425. sc->rap_group_count = i;
  2426. return pb->eof_reached ? AVERROR_EOF : 0;
  2427. }
  2428. /**
  2429. * Get ith edit list entry (media time, duration).
  2430. */
  2431. static int get_edit_list_entry(MOVContext *mov,
  2432. const MOVStreamContext *msc,
  2433. unsigned int edit_list_index,
  2434. int64_t *edit_list_media_time,
  2435. int64_t *edit_list_duration,
  2436. int64_t global_timescale)
  2437. {
  2438. if (edit_list_index == msc->elst_count) {
  2439. return 0;
  2440. }
  2441. *edit_list_media_time = msc->elst_data[edit_list_index].time;
  2442. *edit_list_duration = msc->elst_data[edit_list_index].duration;
  2443. /* duration is in global timescale units;convert to msc timescale */
  2444. if (global_timescale == 0) {
  2445. avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists");
  2446. return 0;
  2447. }
  2448. *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale,
  2449. global_timescale);
  2450. return 1;
  2451. }
  2452. /**
  2453. * Find the closest previous frame to the timestamp, in e_old index
  2454. * entries. Searching for just any frame / just key frames can be controlled by
  2455. * last argument 'flag'.
  2456. * Returns the index of the entry in st->index_entries if successful,
  2457. * else returns -1.
  2458. */
  2459. static int64_t find_prev_closest_index(AVStream *st,
  2460. AVIndexEntry *e_old,
  2461. int nb_old,
  2462. int64_t timestamp,
  2463. int flag)
  2464. {
  2465. AVIndexEntry *e_keep = st->index_entries;
  2466. int nb_keep = st->nb_index_entries;
  2467. int64_t found = -1;
  2468. int64_t i = 0;
  2469. st->index_entries = e_old;
  2470. st->nb_index_entries = nb_old;
  2471. found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD);
  2472. // Keep going backwards in the index entries until the timestamp is the same.
  2473. if (found >= 0) {
  2474. for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp;
  2475. i--) {
  2476. if ((flag & AVSEEK_FLAG_ANY) ||
  2477. (e_old[i - 1].flags & AVINDEX_KEYFRAME)) {
  2478. found = i - 1;
  2479. }
  2480. }
  2481. }
  2482. /* restore AVStream state*/
  2483. st->index_entries = e_keep;
  2484. st->nb_index_entries = nb_keep;
  2485. return found;
  2486. }
  2487. /**
  2488. * Add index entry with the given values, to the end of st->index_entries.
  2489. * Returns the new size st->index_entries if successful, else returns -1.
  2490. *
  2491. * This function is similar to ff_add_index_entry in libavformat/utils.c
  2492. * except that here we are always unconditionally adding an index entry to
  2493. * the end, instead of searching the entries list and skipping the add if
  2494. * there is an existing entry with the same timestamp.
  2495. * This is needed because the mov_fix_index calls this func with the same
  2496. * unincremented timestamp for successive discarded frames.
  2497. */
  2498. static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp,
  2499. int size, int distance, int flags)
  2500. {
  2501. AVIndexEntry *entries, *ie;
  2502. int64_t index = -1;
  2503. const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry);
  2504. // Double the allocation each time, to lower memory fragmentation.
  2505. // Another difference from ff_add_index_entry function.
  2506. const size_t requested_size =
  2507. min_size_needed > st->index_entries_allocated_size ?
  2508. FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) :
  2509. min_size_needed;
  2510. if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
  2511. return -1;
  2512. entries = av_fast_realloc(st->index_entries,
  2513. &st->index_entries_allocated_size,
  2514. requested_size);
  2515. if(!entries)
  2516. return -1;
  2517. st->index_entries= entries;
  2518. index= st->nb_index_entries++;
  2519. ie= &entries[index];
  2520. ie->pos = pos;
  2521. ie->timestamp = timestamp;
  2522. ie->min_distance= distance;
  2523. ie->size= size;
  2524. ie->flags = flags;
  2525. return index;
  2526. }
  2527. /**
  2528. * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index)
  2529. * by subtracting end_ts successively by the amounts given in frame_duration_buffer.
  2530. */
  2531. static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts,
  2532. int64_t* frame_duration_buffer,
  2533. int frame_duration_buffer_size) {
  2534. int i = 0;
  2535. av_assert0(end_index >= 0 && end_index <= st->nb_index_entries);
  2536. for (i = 0; i < frame_duration_buffer_size; i++) {
  2537. end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i];
  2538. st->index_entries[end_index - 1 - i].timestamp = end_ts;
  2539. }
  2540. }
  2541. /**
  2542. * Append a new ctts entry to ctts_data.
  2543. * Returns the new ctts_count if successful, else returns -1.
  2544. */
  2545. static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size,
  2546. int count, int duration)
  2547. {
  2548. MOVStts *ctts_buf_new;
  2549. const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts);
  2550. const size_t requested_size =
  2551. min_size_needed > *allocated_size ?
  2552. FFMAX(min_size_needed, 2 * (*allocated_size)) :
  2553. min_size_needed;
  2554. if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts))
  2555. return -1;
  2556. ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size);
  2557. if(!ctts_buf_new)
  2558. return -1;
  2559. *ctts_data = ctts_buf_new;
  2560. ctts_buf_new[*ctts_count].count = count;
  2561. ctts_buf_new[*ctts_count].duration = duration;
  2562. *ctts_count = (*ctts_count) + 1;
  2563. return *ctts_count;
  2564. }
  2565. static void mov_current_sample_inc(MOVStreamContext *sc)
  2566. {
  2567. sc->current_sample++;
  2568. sc->current_index++;
  2569. if (sc->index_ranges &&
  2570. sc->current_index >= sc->current_index_range->end &&
  2571. sc->current_index_range->end) {
  2572. sc->current_index_range++;
  2573. sc->current_index = sc->current_index_range->start;
  2574. }
  2575. }
  2576. static void mov_current_sample_dec(MOVStreamContext *sc)
  2577. {
  2578. sc->current_sample--;
  2579. sc->current_index--;
  2580. if (sc->index_ranges &&
  2581. sc->current_index < sc->current_index_range->start &&
  2582. sc->current_index_range > sc->index_ranges) {
  2583. sc->current_index_range--;
  2584. sc->current_index = sc->current_index_range->end - 1;
  2585. }
  2586. }
  2587. static void mov_current_sample_set(MOVStreamContext *sc, int current_sample)
  2588. {
  2589. int64_t range_size;
  2590. sc->current_sample = current_sample;
  2591. sc->current_index = current_sample;
  2592. if (!sc->index_ranges) {
  2593. return;
  2594. }
  2595. for (sc->current_index_range = sc->index_ranges;
  2596. sc->current_index_range->end;
  2597. sc->current_index_range++) {
  2598. range_size = sc->current_index_range->end - sc->current_index_range->start;
  2599. if (range_size > current_sample) {
  2600. sc->current_index = sc->current_index_range->start + current_sample;
  2601. break;
  2602. }
  2603. current_sample -= range_size;
  2604. }
  2605. }
  2606. /**
  2607. * Fix st->index_entries, so that it contains only the entries (and the entries
  2608. * which are needed to decode them) that fall in the edit list time ranges.
  2609. * Also fixes the timestamps of the index entries to match the timeline
  2610. * specified the edit lists.
  2611. */
  2612. static void mov_fix_index(MOVContext *mov, AVStream *st)
  2613. {
  2614. MOVStreamContext *msc = st->priv_data;
  2615. AVIndexEntry *e_old = st->index_entries;
  2616. int nb_old = st->nb_index_entries;
  2617. const AVIndexEntry *e_old_end = e_old + nb_old;
  2618. const AVIndexEntry *current = NULL;
  2619. MOVStts *ctts_data_old = msc->ctts_data;
  2620. int64_t ctts_index_old = 0;
  2621. int64_t ctts_sample_old = 0;
  2622. int64_t ctts_count_old = msc->ctts_count;
  2623. int64_t edit_list_media_time = 0;
  2624. int64_t edit_list_duration = 0;
  2625. int64_t frame_duration = 0;
  2626. int64_t edit_list_dts_counter = 0;
  2627. int64_t edit_list_dts_entry_end = 0;
  2628. int64_t edit_list_start_ctts_sample = 0;
  2629. int64_t curr_cts;
  2630. int64_t curr_ctts = 0;
  2631. int64_t min_corrected_pts = -1;
  2632. int64_t empty_edits_sum_duration = 0;
  2633. int64_t edit_list_index = 0;
  2634. int64_t index;
  2635. int64_t index_ctts_count;
  2636. int flags;
  2637. int64_t start_dts = 0;
  2638. int64_t edit_list_media_time_dts = 0;
  2639. int64_t edit_list_start_encountered = 0;
  2640. int64_t search_timestamp = 0;
  2641. int64_t* frame_duration_buffer = NULL;
  2642. int num_discarded_begin = 0;
  2643. int first_non_zero_audio_edit = -1;
  2644. int packet_skip_samples = 0;
  2645. MOVIndexRange *current_index_range;
  2646. int i;
  2647. if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {
  2648. return;
  2649. }
  2650. // allocate the index ranges array
  2651. msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));
  2652. if (!msc->index_ranges) {
  2653. av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");
  2654. return;
  2655. }
  2656. msc->current_index_range = msc->index_ranges;
  2657. current_index_range = msc->index_ranges - 1;
  2658. // Clean AVStream from traces of old index
  2659. st->index_entries = NULL;
  2660. st->index_entries_allocated_size = 0;
  2661. st->nb_index_entries = 0;
  2662. // Clean ctts fields of MOVStreamContext
  2663. msc->ctts_data = NULL;
  2664. msc->ctts_count = 0;
  2665. msc->ctts_index = 0;
  2666. msc->ctts_sample = 0;
  2667. msc->ctts_allocated_size = 0;
  2668. // If the dts_shift is positive (in case of negative ctts values in mov),
  2669. // then negate the DTS by dts_shift
  2670. if (msc->dts_shift > 0) {
  2671. edit_list_dts_entry_end -= msc->dts_shift;
  2672. av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift);
  2673. }
  2674. start_dts = edit_list_dts_entry_end;
  2675. while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,
  2676. &edit_list_duration, mov->time_scale)) {
  2677. av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",
  2678. st->index, edit_list_index, edit_list_media_time, edit_list_duration);
  2679. edit_list_index++;
  2680. edit_list_dts_counter = edit_list_dts_entry_end;
  2681. edit_list_dts_entry_end += edit_list_duration;
  2682. num_discarded_begin = 0;
  2683. if (edit_list_media_time == -1) {
  2684. empty_edits_sum_duration += edit_list_duration;
  2685. continue;
  2686. }
  2687. // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them
  2688. // according to the edit list below.
  2689. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2690. if (first_non_zero_audio_edit < 0) {
  2691. first_non_zero_audio_edit = 1;
  2692. } else {
  2693. first_non_zero_audio_edit = 0;
  2694. }
  2695. if (first_non_zero_audio_edit > 0)
  2696. st->skip_samples = msc->start_pad = 0;
  2697. }
  2698. //find closest previous key frame
  2699. edit_list_media_time_dts = edit_list_media_time;
  2700. if (msc->dts_shift > 0) {
  2701. edit_list_media_time_dts -= msc->dts_shift;
  2702. }
  2703. // While reordering frame index according to edit list we must handle properly
  2704. // the scenario when edit list entry starts from none key frame.
  2705. // We find closest previous key frame and preserve it and consequent frames in index.
  2706. // All frames which are outside edit list entry time boundaries will be dropped after decoding.
  2707. search_timestamp = edit_list_media_time_dts;
  2708. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  2709. // Audio decoders like AAC need need a decoder delay samples previous to the current sample,
  2710. // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the
  2711. // edit_list_media_time to cover the decoder delay.
  2712. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);
  2713. }
  2714. index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);
  2715. if (index == -1) {
  2716. av_log(mov->fc, AV_LOG_WARNING,
  2717. "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",
  2718. st->index, edit_list_index, search_timestamp);
  2719. index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);
  2720. if (index == -1) {
  2721. av_log(mov->fc, AV_LOG_WARNING,
  2722. "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"
  2723. "Rounding edit list media time to zero.\n",
  2724. st->index, edit_list_index, search_timestamp);
  2725. index = 0;
  2726. edit_list_media_time = 0;
  2727. }
  2728. }
  2729. current = e_old + index;
  2730. ctts_index_old = 0;
  2731. ctts_sample_old = 0;
  2732. // set ctts_index properly for the found key frame
  2733. for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {
  2734. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2735. ctts_sample_old++;
  2736. if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {
  2737. ctts_index_old++;
  2738. ctts_sample_old = 0;
  2739. }
  2740. }
  2741. }
  2742. edit_list_start_ctts_sample = ctts_sample_old;
  2743. // Iterate over index and arrange it according to edit list
  2744. edit_list_start_encountered = 0;
  2745. for (; current < e_old_end; current++, index++) {
  2746. // check if frame outside edit list mark it for discard
  2747. frame_duration = (current + 1 < e_old_end) ?
  2748. ((current + 1)->timestamp - current->timestamp) : edit_list_duration;
  2749. flags = current->flags;
  2750. // frames (pts) before or after edit list
  2751. curr_cts = current->timestamp + msc->dts_shift;
  2752. curr_ctts = 0;
  2753. if (ctts_data_old && ctts_index_old < ctts_count_old) {
  2754. curr_ctts = ctts_data_old[ctts_index_old].duration;
  2755. av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n",
  2756. curr_cts, curr_ctts, ctts_index_old, ctts_count_old);
  2757. curr_cts += curr_ctts;
  2758. ctts_sample_old++;
  2759. if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {
  2760. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2761. &msc->ctts_allocated_size,
  2762. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2763. ctts_data_old[ctts_index_old].duration) == -1) {
  2764. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2765. ctts_index_old,
  2766. ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,
  2767. ctts_data_old[ctts_index_old].duration);
  2768. break;
  2769. }
  2770. ctts_index_old++;
  2771. ctts_sample_old = 0;
  2772. edit_list_start_ctts_sample = 0;
  2773. }
  2774. }
  2775. if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {
  2776. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
  2777. curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&
  2778. first_non_zero_audio_edit > 0) {
  2779. packet_skip_samples = edit_list_media_time - curr_cts;
  2780. st->skip_samples += packet_skip_samples;
  2781. // Shift the index entry timestamp by packet_skip_samples to be correct.
  2782. edit_list_dts_counter -= packet_skip_samples;
  2783. if (edit_list_start_encountered == 0) {
  2784. edit_list_start_encountered = 1;
  2785. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2786. // discarded packets.
  2787. if (frame_duration_buffer) {
  2788. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2789. frame_duration_buffer, num_discarded_begin);
  2790. av_freep(&frame_duration_buffer);
  2791. }
  2792. }
  2793. av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);
  2794. } else {
  2795. flags |= AVINDEX_DISCARD_FRAME;
  2796. av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);
  2797. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {
  2798. num_discarded_begin++;
  2799. frame_duration_buffer = av_realloc(frame_duration_buffer,
  2800. num_discarded_begin * sizeof(int64_t));
  2801. if (!frame_duration_buffer) {
  2802. av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");
  2803. break;
  2804. }
  2805. frame_duration_buffer[num_discarded_begin - 1] = frame_duration;
  2806. // Increment skip_samples for the first non-zero audio edit list
  2807. if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {
  2808. st->skip_samples += frame_duration;
  2809. }
  2810. }
  2811. }
  2812. } else {
  2813. if (min_corrected_pts < 0) {
  2814. min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift;
  2815. } else {
  2816. min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift);
  2817. }
  2818. if (edit_list_start_encountered == 0) {
  2819. edit_list_start_encountered = 1;
  2820. // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for
  2821. // discarded packets.
  2822. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {
  2823. fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,
  2824. frame_duration_buffer, num_discarded_begin);
  2825. av_freep(&frame_duration_buffer);
  2826. }
  2827. }
  2828. }
  2829. if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,
  2830. current->min_distance, flags) == -1) {
  2831. av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");
  2832. break;
  2833. }
  2834. // Update the index ranges array
  2835. if (current_index_range < msc->index_ranges || index != current_index_range->end) {
  2836. current_index_range++;
  2837. current_index_range->start = index;
  2838. }
  2839. current_index_range->end = index + 1;
  2840. // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.
  2841. if (edit_list_start_encountered > 0) {
  2842. edit_list_dts_counter = edit_list_dts_counter + frame_duration;
  2843. }
  2844. // Break when found first key frame after edit entry completion
  2845. if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&
  2846. ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {
  2847. if (ctts_data_old && ctts_sample_old != 0) {
  2848. if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,
  2849. &msc->ctts_allocated_size,
  2850. ctts_sample_old - edit_list_start_ctts_sample,
  2851. ctts_data_old[ctts_index_old].duration) == -1) {
  2852. av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",
  2853. ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,
  2854. ctts_data_old[ctts_index_old].duration);
  2855. break;
  2856. }
  2857. }
  2858. break;
  2859. }
  2860. }
  2861. }
  2862. // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the
  2863. // sum duration of emtpy edits here.
  2864. min_corrected_pts -= empty_edits_sum_duration;
  2865. // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the
  2866. // dts by that amount to make the first pts zero.
  2867. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) {
  2868. av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts);
  2869. for (i = 0; i < st->nb_index_entries; ++i) {
  2870. st->index_entries[i].timestamp -= min_corrected_pts;
  2871. }
  2872. }
  2873. // Update av stream length
  2874. st->duration = edit_list_dts_entry_end - start_dts;
  2875. msc->start_pad = st->skip_samples;
  2876. // Free the old index and the old CTTS structures
  2877. av_free(e_old);
  2878. av_free(ctts_data_old);
  2879. // Null terminate the index ranges array
  2880. current_index_range++;
  2881. current_index_range->start = 0;
  2882. current_index_range->end = 0;
  2883. msc->current_index = msc->index_ranges[0].start;
  2884. }
  2885. static void mov_build_index(MOVContext *mov, AVStream *st)
  2886. {
  2887. MOVStreamContext *sc = st->priv_data;
  2888. int64_t current_offset;
  2889. int64_t current_dts = 0;
  2890. unsigned int stts_index = 0;
  2891. unsigned int stsc_index = 0;
  2892. unsigned int stss_index = 0;
  2893. unsigned int stps_index = 0;
  2894. unsigned int i, j;
  2895. uint64_t stream_size = 0;
  2896. if (sc->elst_count) {
  2897. int i, edit_start_index = 0, multiple_edits = 0;
  2898. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2899. int64_t start_time = 0; // start time of the media
  2900. for (i = 0; i < sc->elst_count; i++) {
  2901. const MOVElst *e = &sc->elst_data[i];
  2902. if (i == 0 && e->time == -1) {
  2903. /* if empty, the first entry is the start time of the stream
  2904. * relative to the presentation itself */
  2905. empty_duration = e->duration;
  2906. edit_start_index = 1;
  2907. } else if (i == edit_start_index && e->time >= 0) {
  2908. start_time = e->time;
  2909. } else {
  2910. multiple_edits = 1;
  2911. }
  2912. }
  2913. if (multiple_edits && !mov->advanced_editlist)
  2914. av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2915. "Use -advanced_editlist to correctly decode otherwise "
  2916. "a/v desync might occur\n");
  2917. /* adjust first dts according to edit list */
  2918. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2919. if (empty_duration)
  2920. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2921. sc->time_offset = start_time - empty_duration;
  2922. if (!mov->advanced_editlist)
  2923. current_dts = -sc->time_offset;
  2924. }
  2925. if (!multiple_edits && !mov->advanced_editlist &&
  2926. st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
  2927. sc->start_pad = start_time;
  2928. }
  2929. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2930. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  2931. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2932. unsigned int current_sample = 0;
  2933. unsigned int stts_sample = 0;
  2934. unsigned int sample_size;
  2935. unsigned int distance = 0;
  2936. unsigned int rap_group_index = 0;
  2937. unsigned int rap_group_sample = 0;
  2938. int64_t last_dts = 0;
  2939. int64_t dts_correction = 0;
  2940. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2941. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2942. current_dts -= sc->dts_shift;
  2943. last_dts = current_dts;
  2944. if (!sc->sample_count || st->nb_index_entries)
  2945. return;
  2946. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2947. return;
  2948. if (av_reallocp_array(&st->index_entries,
  2949. st->nb_index_entries + sc->sample_count,
  2950. sizeof(*st->index_entries)) < 0) {
  2951. st->nb_index_entries = 0;
  2952. return;
  2953. }
  2954. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2955. for (i = 0; i < sc->chunk_count; i++) {
  2956. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2957. current_offset = sc->chunk_offsets[i];
  2958. while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  2959. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2960. stsc_index++;
  2961. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2962. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2963. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2964. sc->stsz_sample_size = sc->sample_size;
  2965. }
  2966. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2967. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2968. sc->stsz_sample_size = sc->sample_size;
  2969. }
  2970. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2971. int keyframe = 0;
  2972. if (current_sample >= sc->sample_count) {
  2973. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2974. return;
  2975. }
  2976. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2977. keyframe = 1;
  2978. if (stss_index + 1 < sc->keyframe_count)
  2979. stss_index++;
  2980. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2981. keyframe = 1;
  2982. if (stps_index + 1 < sc->stps_count)
  2983. stps_index++;
  2984. }
  2985. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2986. if (sc->rap_group[rap_group_index].index > 0)
  2987. keyframe = 1;
  2988. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2989. rap_group_sample = 0;
  2990. rap_group_index++;
  2991. }
  2992. }
  2993. if (sc->keyframe_absent
  2994. && !sc->stps_count
  2995. && !rap_group_present
  2996. && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2997. keyframe = 1;
  2998. if (keyframe)
  2999. distance = 0;
  3000. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  3001. if (sc->pseudo_stream_id == -1 ||
  3002. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  3003. AVIndexEntry *e;
  3004. if (sample_size > 0x3FFFFFFF) {
  3005. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  3006. return;
  3007. }
  3008. e = &st->index_entries[st->nb_index_entries++];
  3009. e->pos = current_offset;
  3010. e->timestamp = current_dts;
  3011. e->size = sample_size;
  3012. e->min_distance = distance;
  3013. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  3014. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
  3015. "size %u, distance %u, keyframe %d\n", st->index, current_sample,
  3016. current_offset, current_dts, sample_size, distance, keyframe);
  3017. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  3018. ff_rfps_add_frame(mov->fc, st, current_dts);
  3019. }
  3020. current_offset += sample_size;
  3021. stream_size += sample_size;
  3022. /* A negative sample duration is invalid based on the spec,
  3023. * but some samples need it to correct the DTS. */
  3024. if (sc->stts_data[stts_index].duration < 0) {
  3025. av_log(mov->fc, AV_LOG_WARNING,
  3026. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  3027. sc->stts_data[stts_index].duration, stts_index,
  3028. st->index);
  3029. dts_correction += sc->stts_data[stts_index].duration - 1;
  3030. sc->stts_data[stts_index].duration = 1;
  3031. }
  3032. current_dts += sc->stts_data[stts_index].duration;
  3033. if (!dts_correction || current_dts + dts_correction > last_dts) {
  3034. current_dts += dts_correction;
  3035. dts_correction = 0;
  3036. } else {
  3037. /* Avoid creating non-monotonous DTS */
  3038. dts_correction += current_dts - last_dts - 1;
  3039. current_dts = last_dts + 1;
  3040. }
  3041. last_dts = current_dts;
  3042. distance++;
  3043. stts_sample++;
  3044. current_sample++;
  3045. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  3046. stts_sample = 0;
  3047. stts_index++;
  3048. }
  3049. }
  3050. }
  3051. if (st->duration > 0)
  3052. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  3053. } else {
  3054. unsigned chunk_samples, total = 0;
  3055. // compute total chunk count
  3056. for (i = 0; i < sc->stsc_count; i++) {
  3057. unsigned count, chunk_count;
  3058. chunk_samples = sc->stsc_data[i].count;
  3059. if (i != sc->stsc_count - 1 &&
  3060. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  3061. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  3062. return;
  3063. }
  3064. if (sc->samples_per_frame >= 160) { // gsm
  3065. count = chunk_samples / sc->samples_per_frame;
  3066. } else if (sc->samples_per_frame > 1) {
  3067. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  3068. count = (chunk_samples+samples-1) / samples;
  3069. } else {
  3070. count = (chunk_samples+1023) / 1024;
  3071. }
  3072. if (mov_stsc_index_valid(i, sc->stsc_count))
  3073. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  3074. else
  3075. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  3076. total += chunk_count * count;
  3077. }
  3078. av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
  3079. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  3080. return;
  3081. if (av_reallocp_array(&st->index_entries,
  3082. st->nb_index_entries + total,
  3083. sizeof(*st->index_entries)) < 0) {
  3084. st->nb_index_entries = 0;
  3085. return;
  3086. }
  3087. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  3088. // populate index
  3089. for (i = 0; i < sc->chunk_count; i++) {
  3090. current_offset = sc->chunk_offsets[i];
  3091. if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  3092. i + 1 == sc->stsc_data[stsc_index + 1].first)
  3093. stsc_index++;
  3094. chunk_samples = sc->stsc_data[stsc_index].count;
  3095. while (chunk_samples > 0) {
  3096. AVIndexEntry *e;
  3097. unsigned size, samples;
  3098. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  3099. avpriv_request_sample(mov->fc,
  3100. "Zero bytes per frame, but %d samples per frame",
  3101. sc->samples_per_frame);
  3102. return;
  3103. }
  3104. if (sc->samples_per_frame >= 160) { // gsm
  3105. samples = sc->samples_per_frame;
  3106. size = sc->bytes_per_frame;
  3107. } else {
  3108. if (sc->samples_per_frame > 1) {
  3109. samples = FFMIN((1024 / sc->samples_per_frame)*
  3110. sc->samples_per_frame, chunk_samples);
  3111. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  3112. } else {
  3113. samples = FFMIN(1024, chunk_samples);
  3114. size = samples * sc->sample_size;
  3115. }
  3116. }
  3117. if (st->nb_index_entries >= total) {
  3118. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
  3119. return;
  3120. }
  3121. if (size > 0x3FFFFFFF) {
  3122. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  3123. return;
  3124. }
  3125. e = &st->index_entries[st->nb_index_entries++];
  3126. e->pos = current_offset;
  3127. e->timestamp = current_dts;
  3128. e->size = size;
  3129. e->min_distance = 0;
  3130. e->flags = AVINDEX_KEYFRAME;
  3131. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
  3132. "size %u, duration %u\n", st->index, i, current_offset, current_dts,
  3133. size, samples);
  3134. current_offset += size;
  3135. current_dts += samples;
  3136. chunk_samples -= samples;
  3137. }
  3138. }
  3139. }
  3140. if (!mov->ignore_editlist && mov->advanced_editlist) {
  3141. // Fix index according to edit lists.
  3142. mov_fix_index(mov, st);
  3143. }
  3144. }
  3145. static int test_same_origin(const char *src, const char *ref) {
  3146. char src_proto[64];
  3147. char ref_proto[64];
  3148. char src_auth[256];
  3149. char ref_auth[256];
  3150. char src_host[256];
  3151. char ref_host[256];
  3152. int src_port=-1;
  3153. int ref_port=-1;
  3154. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  3155. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  3156. if (strlen(src) == 0) {
  3157. return -1;
  3158. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  3159. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  3160. strlen(src_host) + 1 >= sizeof(src_host) ||
  3161. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  3162. return 0;
  3163. } else if (strcmp(src_proto, ref_proto) ||
  3164. strcmp(src_auth, ref_auth) ||
  3165. strcmp(src_host, ref_host) ||
  3166. src_port != ref_port) {
  3167. return 0;
  3168. } else
  3169. return 1;
  3170. }
  3171. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  3172. {
  3173. /* try relative path, we do not try the absolute because it can leak information about our
  3174. system to an attacker */
  3175. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  3176. char filename[1025];
  3177. const char *src_path;
  3178. int i, l;
  3179. /* find a source dir */
  3180. src_path = strrchr(src, '/');
  3181. if (src_path)
  3182. src_path++;
  3183. else
  3184. src_path = src;
  3185. /* find a next level down to target */
  3186. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  3187. if (ref->path[l] == '/') {
  3188. if (i == ref->nlvl_to - 1)
  3189. break;
  3190. else
  3191. i++;
  3192. }
  3193. /* compose filename if next level down to target was found */
  3194. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  3195. memcpy(filename, src, src_path - src);
  3196. filename[src_path - src] = 0;
  3197. for (i = 1; i < ref->nlvl_from; i++)
  3198. av_strlcat(filename, "../", sizeof(filename));
  3199. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  3200. if (!c->use_absolute_path) {
  3201. int same_origin = test_same_origin(src, filename);
  3202. if (!same_origin) {
  3203. av_log(c->fc, AV_LOG_ERROR,
  3204. "Reference with mismatching origin, %s not tried for security reasons, "
  3205. "set demuxer option use_absolute_path to allow it anyway\n",
  3206. ref->path);
  3207. return AVERROR(ENOENT);
  3208. }
  3209. if(strstr(ref->path + l + 1, "..") ||
  3210. strstr(ref->path + l + 1, ":") ||
  3211. (ref->nlvl_from > 1 && same_origin < 0) ||
  3212. (filename[0] == '/' && src_path == src))
  3213. return AVERROR(ENOENT);
  3214. }
  3215. if (strlen(filename) + 1 == sizeof(filename))
  3216. return AVERROR(ENOENT);
  3217. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  3218. return 0;
  3219. }
  3220. } else if (c->use_absolute_path) {
  3221. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  3222. "this is a possible security issue\n");
  3223. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  3224. return 0;
  3225. } else {
  3226. av_log(c->fc, AV_LOG_ERROR,
  3227. "Absolute path %s not tried for security reasons, "
  3228. "set demuxer option use_absolute_path to allow absolute paths\n",
  3229. ref->path);
  3230. }
  3231. return AVERROR(ENOENT);
  3232. }
  3233. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  3234. {
  3235. if (sc->time_scale <= 0) {
  3236. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  3237. sc->time_scale = c->time_scale;
  3238. if (sc->time_scale <= 0)
  3239. sc->time_scale = 1;
  3240. }
  3241. }
  3242. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3243. {
  3244. AVStream *st;
  3245. MOVStreamContext *sc;
  3246. int ret;
  3247. st = avformat_new_stream(c->fc, NULL);
  3248. if (!st) return AVERROR(ENOMEM);
  3249. st->id = c->fc->nb_streams;
  3250. sc = av_mallocz(sizeof(MOVStreamContext));
  3251. if (!sc) return AVERROR(ENOMEM);
  3252. st->priv_data = sc;
  3253. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  3254. sc->ffindex = st->index;
  3255. c->trak_index = st->index;
  3256. if ((ret = mov_read_default(c, pb, atom)) < 0)
  3257. return ret;
  3258. c->trak_index = -1;
  3259. /* sanity checks */
  3260. if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  3261. (!sc->sample_size && !sc->sample_count))) ||
  3262. (!sc->chunk_count && sc->sample_count)) {
  3263. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  3264. st->index);
  3265. return 0;
  3266. }
  3267. fix_timescale(c, sc);
  3268. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  3269. mov_build_index(c, st);
  3270. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  3271. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  3272. if (c->enable_drefs) {
  3273. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  3274. av_log(c->fc, AV_LOG_ERROR,
  3275. "stream %d, error opening alias: path='%s', dir='%s', "
  3276. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  3277. st->index, dref->path, dref->dir, dref->filename,
  3278. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3279. } else {
  3280. av_log(c->fc, AV_LOG_WARNING,
  3281. "Skipped opening external track: "
  3282. "stream %d, alias: path='%s', dir='%s', "
  3283. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  3284. "Set enable_drefs to allow this.\n",
  3285. st->index, dref->path, dref->dir, dref->filename,
  3286. dref->volume, dref->nlvl_from, dref->nlvl_to);
  3287. }
  3288. } else {
  3289. sc->pb = c->fc->pb;
  3290. sc->pb_is_copied = 1;
  3291. }
  3292. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3293. if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
  3294. sc->height && sc->width &&
  3295. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  3296. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  3297. ((double)st->codecpar->width * sc->height), INT_MAX);
  3298. }
  3299. #if FF_API_R_FRAME_RATE
  3300. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  3301. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  3302. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  3303. #endif
  3304. }
  3305. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  3306. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  3307. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  3308. ret = ff_generate_avci_extradata(st);
  3309. if (ret < 0)
  3310. return ret;
  3311. }
  3312. switch (st->codecpar->codec_id) {
  3313. #if CONFIG_H261_DECODER
  3314. case AV_CODEC_ID_H261:
  3315. #endif
  3316. #if CONFIG_H263_DECODER
  3317. case AV_CODEC_ID_H263:
  3318. #endif
  3319. #if CONFIG_MPEG4_DECODER
  3320. case AV_CODEC_ID_MPEG4:
  3321. #endif
  3322. st->codecpar->width = 0; /* let decoder init width/height */
  3323. st->codecpar->height= 0;
  3324. break;
  3325. }
  3326. // If the duration of the mp3 packets is not constant, then they could need a parser
  3327. if (st->codecpar->codec_id == AV_CODEC_ID_MP3
  3328. && sc->stts_count > 3
  3329. && sc->stts_count*10 > st->nb_frames
  3330. && sc->time_scale == st->codecpar->sample_rate) {
  3331. st->need_parsing = AVSTREAM_PARSE_FULL;
  3332. }
  3333. /* Do not need those anymore. */
  3334. av_freep(&sc->chunk_offsets);
  3335. av_freep(&sc->sample_sizes);
  3336. av_freep(&sc->keyframes);
  3337. av_freep(&sc->stts_data);
  3338. av_freep(&sc->stps_data);
  3339. av_freep(&sc->elst_data);
  3340. av_freep(&sc->rap_group);
  3341. return 0;
  3342. }
  3343. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3344. {
  3345. int ret;
  3346. c->itunes_metadata = 1;
  3347. ret = mov_read_default(c, pb, atom);
  3348. c->itunes_metadata = 0;
  3349. return ret;
  3350. }
  3351. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3352. {
  3353. uint32_t count;
  3354. uint32_t i;
  3355. if (atom.size < 8)
  3356. return 0;
  3357. avio_skip(pb, 4);
  3358. count = avio_rb32(pb);
  3359. if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) {
  3360. av_log(c->fc, AV_LOG_ERROR,
  3361. "The 'keys' atom with the invalid key count: %"PRIu32"\n", count);
  3362. return AVERROR_INVALIDDATA;
  3363. }
  3364. c->meta_keys_count = count + 1;
  3365. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  3366. if (!c->meta_keys)
  3367. return AVERROR(ENOMEM);
  3368. for (i = 1; i <= count; ++i) {
  3369. uint32_t key_size = avio_rb32(pb);
  3370. uint32_t type = avio_rl32(pb);
  3371. if (key_size < 8) {
  3372. av_log(c->fc, AV_LOG_ERROR,
  3373. "The key# %"PRIu32" in meta has invalid size:"
  3374. "%"PRIu32"\n", i, key_size);
  3375. return AVERROR_INVALIDDATA;
  3376. }
  3377. key_size -= 8;
  3378. if (type != MKTAG('m','d','t','a')) {
  3379. avio_skip(pb, key_size);
  3380. }
  3381. c->meta_keys[i] = av_mallocz(key_size + 1);
  3382. if (!c->meta_keys[i])
  3383. return AVERROR(ENOMEM);
  3384. avio_read(pb, c->meta_keys[i], key_size);
  3385. }
  3386. return 0;
  3387. }
  3388. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3389. {
  3390. int64_t end = avio_tell(pb) + atom.size;
  3391. uint8_t *key = NULL, *val = NULL, *mean = NULL;
  3392. int i;
  3393. int ret = 0;
  3394. AVStream *st;
  3395. MOVStreamContext *sc;
  3396. if (c->fc->nb_streams < 1)
  3397. return 0;
  3398. st = c->fc->streams[c->fc->nb_streams-1];
  3399. sc = st->priv_data;
  3400. for (i = 0; i < 3; i++) {
  3401. uint8_t **p;
  3402. uint32_t len, tag;
  3403. if (end - avio_tell(pb) <= 12)
  3404. break;
  3405. len = avio_rb32(pb);
  3406. tag = avio_rl32(pb);
  3407. avio_skip(pb, 4); // flags
  3408. if (len < 12 || len - 12 > end - avio_tell(pb))
  3409. break;
  3410. len -= 12;
  3411. if (tag == MKTAG('m', 'e', 'a', 'n'))
  3412. p = &mean;
  3413. else if (tag == MKTAG('n', 'a', 'm', 'e'))
  3414. p = &key;
  3415. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  3416. avio_skip(pb, 4);
  3417. len -= 4;
  3418. p = &val;
  3419. } else
  3420. break;
  3421. *p = av_malloc(len + 1);
  3422. if (!*p)
  3423. break;
  3424. ret = ffio_read_size(pb, *p, len);
  3425. if (ret < 0) {
  3426. av_freep(p);
  3427. break;
  3428. }
  3429. (*p)[len] = 0;
  3430. }
  3431. if (mean && key && val) {
  3432. if (strcmp(key, "iTunSMPB") == 0) {
  3433. int priming, remainder, samples;
  3434. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  3435. if(priming>0 && priming<16384)
  3436. sc->start_pad = priming;
  3437. }
  3438. }
  3439. if (strcmp(key, "cdec") != 0) {
  3440. av_dict_set(&c->fc->metadata, key, val,
  3441. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  3442. key = val = NULL;
  3443. }
  3444. } else {
  3445. av_log(c->fc, AV_LOG_VERBOSE,
  3446. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  3447. }
  3448. avio_seek(pb, end, SEEK_SET);
  3449. av_freep(&key);
  3450. av_freep(&val);
  3451. av_freep(&mean);
  3452. return ret;
  3453. }
  3454. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3455. {
  3456. while (atom.size > 8) {
  3457. uint32_t tag = avio_rl32(pb);
  3458. atom.size -= 4;
  3459. if (tag == MKTAG('h','d','l','r')) {
  3460. avio_seek(pb, -8, SEEK_CUR);
  3461. atom.size += 8;
  3462. return mov_read_default(c, pb, atom);
  3463. }
  3464. }
  3465. return 0;
  3466. }
  3467. // return 1 when matrix is identity, 0 otherwise
  3468. #define IS_MATRIX_IDENT(matrix) \
  3469. ( (matrix)[0][0] == (1 << 16) && \
  3470. (matrix)[1][1] == (1 << 16) && \
  3471. (matrix)[2][2] == (1 << 30) && \
  3472. !(matrix)[0][1] && !(matrix)[0][2] && \
  3473. !(matrix)[1][0] && !(matrix)[1][2] && \
  3474. !(matrix)[2][0] && !(matrix)[2][1])
  3475. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3476. {
  3477. int i, j, e;
  3478. int width;
  3479. int height;
  3480. int display_matrix[3][3];
  3481. int res_display_matrix[3][3] = { { 0 } };
  3482. AVStream *st;
  3483. MOVStreamContext *sc;
  3484. int version;
  3485. int flags;
  3486. if (c->fc->nb_streams < 1)
  3487. return 0;
  3488. st = c->fc->streams[c->fc->nb_streams-1];
  3489. sc = st->priv_data;
  3490. version = avio_r8(pb);
  3491. flags = avio_rb24(pb);
  3492. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  3493. if (version == 1) {
  3494. avio_rb64(pb);
  3495. avio_rb64(pb);
  3496. } else {
  3497. avio_rb32(pb); /* creation time */
  3498. avio_rb32(pb); /* modification time */
  3499. }
  3500. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  3501. avio_rb32(pb); /* reserved */
  3502. /* highlevel (considering edits) duration in movie timebase */
  3503. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  3504. avio_rb32(pb); /* reserved */
  3505. avio_rb32(pb); /* reserved */
  3506. avio_rb16(pb); /* layer */
  3507. avio_rb16(pb); /* alternate group */
  3508. avio_rb16(pb); /* volume */
  3509. avio_rb16(pb); /* reserved */
  3510. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  3511. // they're kept in fixed point format through all calculations
  3512. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  3513. // side data, but the scale factor is not needed to calculate aspect ratio
  3514. for (i = 0; i < 3; i++) {
  3515. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  3516. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  3517. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  3518. }
  3519. width = avio_rb32(pb); // 16.16 fixed point track width
  3520. height = avio_rb32(pb); // 16.16 fixed point track height
  3521. sc->width = width >> 16;
  3522. sc->height = height >> 16;
  3523. // apply the moov display matrix (after the tkhd one)
  3524. for (i = 0; i < 3; i++) {
  3525. const int sh[3] = { 16, 16, 30 };
  3526. for (j = 0; j < 3; j++) {
  3527. for (e = 0; e < 3; e++) {
  3528. res_display_matrix[i][j] +=
  3529. ((int64_t) display_matrix[i][e] *
  3530. c->movie_display_matrix[e][j]) >> sh[e];
  3531. }
  3532. }
  3533. }
  3534. // save the matrix when it is not the default identity
  3535. if (!IS_MATRIX_IDENT(res_display_matrix)) {
  3536. double rotate;
  3537. av_freep(&sc->display_matrix);
  3538. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  3539. if (!sc->display_matrix)
  3540. return AVERROR(ENOMEM);
  3541. for (i = 0; i < 3; i++)
  3542. for (j = 0; j < 3; j++)
  3543. sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
  3544. #if FF_API_OLD_ROTATE_API
  3545. rotate = av_display_rotation_get(sc->display_matrix);
  3546. if (!isnan(rotate)) {
  3547. char rotate_buf[64];
  3548. rotate = -rotate;
  3549. if (rotate < 0) // for backward compatibility
  3550. rotate += 360;
  3551. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  3552. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  3553. }
  3554. #endif
  3555. }
  3556. // transform the display width/height according to the matrix
  3557. // to keep the same scale, use [width height 1<<16]
  3558. if (width && height && sc->display_matrix) {
  3559. double disp_transform[2];
  3560. for (i = 0; i < 2; i++)
  3561. disp_transform[i] = hypot(sc->display_matrix[0 + i],
  3562. sc->display_matrix[3 + i]);
  3563. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  3564. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3565. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3566. st->sample_aspect_ratio = av_d2q(
  3567. disp_transform[0] / disp_transform[1],
  3568. INT_MAX);
  3569. }
  3570. return 0;
  3571. }
  3572. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3573. {
  3574. MOVFragment *frag = &c->fragment;
  3575. MOVTrackExt *trex = NULL;
  3576. MOVFragmentIndex* index = NULL;
  3577. int flags, track_id, i, found = 0;
  3578. avio_r8(pb); /* version */
  3579. flags = avio_rb24(pb);
  3580. track_id = avio_rb32(pb);
  3581. if (!track_id)
  3582. return AVERROR_INVALIDDATA;
  3583. frag->track_id = track_id;
  3584. for (i = 0; i < c->trex_count; i++)
  3585. if (c->trex_data[i].track_id == frag->track_id) {
  3586. trex = &c->trex_data[i];
  3587. break;
  3588. }
  3589. if (!trex) {
  3590. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3591. return AVERROR_INVALIDDATA;
  3592. }
  3593. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3594. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3595. frag->moof_offset : frag->implicit_offset;
  3596. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3597. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3598. avio_rb32(pb) : trex->duration;
  3599. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  3600. avio_rb32(pb) : trex->size;
  3601. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3602. avio_rb32(pb) : trex->flags;
  3603. frag->time = AV_NOPTS_VALUE;
  3604. for (i = 0; i < c->fragment_index_count; i++) {
  3605. int j;
  3606. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3607. if (candidate->track_id == frag->track_id) {
  3608. av_log(c->fc, AV_LOG_DEBUG,
  3609. "found fragment index for track %u\n", frag->track_id);
  3610. index = candidate;
  3611. for (j = index->current_item; j < index->item_count; j++) {
  3612. if (frag->implicit_offset == index->items[j].moof_offset) {
  3613. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3614. "for track %u and moof_offset %"PRId64"\n",
  3615. frag->track_id, index->items[j].moof_offset);
  3616. frag->time = index->items[j].time;
  3617. index->current_item = j + 1;
  3618. found = 1;
  3619. break;
  3620. }
  3621. }
  3622. if (found)
  3623. break;
  3624. }
  3625. }
  3626. if (index && !found) {
  3627. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3628. "it doesn't have an (in-order) entry for moof_offset "
  3629. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3630. }
  3631. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3632. return 0;
  3633. }
  3634. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3635. {
  3636. unsigned i, num;
  3637. void *new_tracks;
  3638. num = atom.size / 4;
  3639. if (!(new_tracks = av_malloc_array(num, sizeof(int))))
  3640. return AVERROR(ENOMEM);
  3641. av_free(c->chapter_tracks);
  3642. c->chapter_tracks = new_tracks;
  3643. c->nb_chapter_tracks = num;
  3644. for (i = 0; i < num && !pb->eof_reached; i++)
  3645. c->chapter_tracks[i] = avio_rb32(pb);
  3646. return 0;
  3647. }
  3648. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3649. {
  3650. MOVTrackExt *trex;
  3651. int err;
  3652. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3653. return AVERROR_INVALIDDATA;
  3654. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3655. sizeof(*c->trex_data))) < 0) {
  3656. c->trex_count = 0;
  3657. return err;
  3658. }
  3659. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3660. trex = &c->trex_data[c->trex_count++];
  3661. avio_r8(pb); /* version */
  3662. avio_rb24(pb); /* flags */
  3663. trex->track_id = avio_rb32(pb);
  3664. trex->stsd_id = avio_rb32(pb);
  3665. trex->duration = avio_rb32(pb);
  3666. trex->size = avio_rb32(pb);
  3667. trex->flags = avio_rb32(pb);
  3668. return 0;
  3669. }
  3670. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3671. {
  3672. MOVFragment *frag = &c->fragment;
  3673. AVStream *st = NULL;
  3674. MOVStreamContext *sc;
  3675. int version, i;
  3676. for (i = 0; i < c->fc->nb_streams; i++) {
  3677. if (c->fc->streams[i]->id == frag->track_id) {
  3678. st = c->fc->streams[i];
  3679. break;
  3680. }
  3681. }
  3682. if (!st) {
  3683. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  3684. return AVERROR_INVALIDDATA;
  3685. }
  3686. sc = st->priv_data;
  3687. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3688. return 0;
  3689. version = avio_r8(pb);
  3690. avio_rb24(pb); /* flags */
  3691. if (version) {
  3692. sc->track_end = avio_rb64(pb);
  3693. } else {
  3694. sc->track_end = avio_rb32(pb);
  3695. }
  3696. return 0;
  3697. }
  3698. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3699. {
  3700. MOVFragment *frag = &c->fragment;
  3701. AVStream *st = NULL;
  3702. MOVStreamContext *sc;
  3703. MOVStts *ctts_data;
  3704. uint64_t offset;
  3705. int64_t dts;
  3706. int data_offset = 0;
  3707. unsigned entries, first_sample_flags = frag->flags;
  3708. int flags, distance, i;
  3709. for (i = 0; i < c->fc->nb_streams; i++) {
  3710. if (c->fc->streams[i]->id == frag->track_id) {
  3711. st = c->fc->streams[i];
  3712. break;
  3713. }
  3714. }
  3715. if (!st) {
  3716. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  3717. return AVERROR_INVALIDDATA;
  3718. }
  3719. sc = st->priv_data;
  3720. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3721. return 0;
  3722. avio_r8(pb); /* version */
  3723. flags = avio_rb24(pb);
  3724. entries = avio_rb32(pb);
  3725. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
  3726. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3727. return AVERROR_INVALIDDATA;
  3728. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3729. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3730. dts = sc->track_end - sc->time_offset;
  3731. offset = frag->base_data_offset + data_offset;
  3732. distance = 0;
  3733. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3734. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3735. unsigned sample_size = frag->size;
  3736. int sample_flags = i ? frag->flags : first_sample_flags;
  3737. unsigned sample_duration = frag->duration;
  3738. unsigned ctts_duration = 0;
  3739. int keyframe = 0;
  3740. int ctts_index = 0;
  3741. int old_nb_index_entries = st->nb_index_entries;
  3742. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3743. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3744. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3745. if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb);
  3746. mov_update_dts_shift(sc, ctts_duration);
  3747. if (frag->time != AV_NOPTS_VALUE) {
  3748. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3749. int64_t pts = frag->time;
  3750. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3751. " sc->dts_shift %d ctts.duration %d"
  3752. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3753. sc->dts_shift, ctts_duration,
  3754. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3755. dts = pts - sc->dts_shift;
  3756. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3757. dts -= ctts_duration;
  3758. } else {
  3759. dts -= sc->time_offset;
  3760. }
  3761. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3762. } else {
  3763. dts = frag->time - sc->time_offset;
  3764. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3765. ", using it for dts\n", dts);
  3766. }
  3767. frag->time = AV_NOPTS_VALUE;
  3768. }
  3769. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  3770. keyframe = 1;
  3771. else
  3772. keyframe =
  3773. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3774. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3775. if (keyframe)
  3776. distance = 0;
  3777. ctts_index = av_add_index_entry(st, offset, dts, sample_size, distance,
  3778. keyframe ? AVINDEX_KEYFRAME : 0);
  3779. if (ctts_index >= 0 && old_nb_index_entries < st->nb_index_entries) {
  3780. unsigned int size_needed = st->nb_index_entries * sizeof(*sc->ctts_data);
  3781. unsigned int request_size = size_needed > sc->ctts_allocated_size ?
  3782. FFMAX(size_needed, 2 * sc->ctts_allocated_size) : size_needed;
  3783. unsigned int old_ctts_size = sc->ctts_allocated_size;
  3784. ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, request_size);
  3785. if (!ctts_data) {
  3786. av_freep(&sc->ctts_data);
  3787. return AVERROR(ENOMEM);
  3788. }
  3789. sc->ctts_data = ctts_data;
  3790. // In case there were samples without ctts entries, ensure they get
  3791. // zero valued entries. This ensures clips which mix boxes with and
  3792. // without ctts entries don't pickup uninitialized data.
  3793. memset((uint8_t*)(sc->ctts_data) + old_ctts_size, 0, sc->ctts_allocated_size - old_ctts_size);
  3794. if (ctts_index != old_nb_index_entries) {
  3795. memmove(sc->ctts_data + ctts_index + 1, sc->ctts_data + ctts_index,
  3796. sizeof(*sc->ctts_data) * (sc->ctts_count - ctts_index));
  3797. if (ctts_index <= sc->current_sample) {
  3798. // if we inserted a new item before the current sample, move the
  3799. // counter ahead so it is still pointing to the same sample.
  3800. sc->current_sample++;
  3801. }
  3802. }
  3803. sc->ctts_data[ctts_index].count = 1;
  3804. sc->ctts_data[ctts_index].duration = ctts_duration;
  3805. sc->ctts_count++;
  3806. } else {
  3807. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3808. }
  3809. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3810. "size %u, distance %d, keyframe %d\n", st->index, ctts_index,
  3811. offset, dts, sample_size, distance, keyframe);
  3812. distance++;
  3813. dts += sample_duration;
  3814. offset += sample_size;
  3815. sc->data_size += sample_size;
  3816. sc->duration_for_fps += sample_duration;
  3817. sc->nb_frames_for_fps ++;
  3818. }
  3819. if (pb->eof_reached)
  3820. return AVERROR_EOF;
  3821. frag->implicit_offset = offset;
  3822. sc->track_end = dts + sc->time_offset;
  3823. if (st->duration < sc->track_end)
  3824. st->duration = sc->track_end;
  3825. return 0;
  3826. }
  3827. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3828. {
  3829. int64_t offset = avio_tell(pb) + atom.size, pts;
  3830. uint8_t version;
  3831. unsigned i, track_id;
  3832. AVStream *st = NULL;
  3833. AVStream *ref_st = NULL;
  3834. MOVStreamContext *sc, *ref_sc = NULL;
  3835. MOVFragmentIndex *index = NULL;
  3836. MOVFragmentIndex **tmp;
  3837. AVRational timescale;
  3838. version = avio_r8(pb);
  3839. if (version > 1) {
  3840. avpriv_request_sample(c->fc, "sidx version %u", version);
  3841. return 0;
  3842. }
  3843. avio_rb24(pb); // flags
  3844. track_id = avio_rb32(pb); // Reference ID
  3845. for (i = 0; i < c->fc->nb_streams; i++) {
  3846. if (c->fc->streams[i]->id == track_id) {
  3847. st = c->fc->streams[i];
  3848. break;
  3849. }
  3850. }
  3851. if (!st) {
  3852. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  3853. return 0;
  3854. }
  3855. sc = st->priv_data;
  3856. timescale = av_make_q(1, avio_rb32(pb));
  3857. if (timescale.den <= 0) {
  3858. av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den);
  3859. return AVERROR_INVALIDDATA;
  3860. }
  3861. if (version == 0) {
  3862. pts = avio_rb32(pb);
  3863. offset += avio_rb32(pb);
  3864. } else {
  3865. pts = avio_rb64(pb);
  3866. offset += avio_rb64(pb);
  3867. }
  3868. avio_rb16(pb); // reserved
  3869. index = av_mallocz(sizeof(MOVFragmentIndex));
  3870. if (!index)
  3871. return AVERROR(ENOMEM);
  3872. index->track_id = track_id;
  3873. index->item_count = avio_rb16(pb);
  3874. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3875. if (!index->items) {
  3876. av_freep(&index);
  3877. return AVERROR(ENOMEM);
  3878. }
  3879. for (i = 0; i < index->item_count; i++) {
  3880. uint32_t size = avio_rb32(pb);
  3881. uint32_t duration = avio_rb32(pb);
  3882. if (size & 0x80000000) {
  3883. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3884. av_freep(&index->items);
  3885. av_freep(&index);
  3886. return AVERROR_PATCHWELCOME;
  3887. }
  3888. avio_rb32(pb); // sap_flags
  3889. index->items[i].moof_offset = offset;
  3890. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3891. offset += size;
  3892. pts += duration;
  3893. }
  3894. st->duration = sc->track_end = pts;
  3895. tmp = av_realloc_array(c->fragment_index_data,
  3896. c->fragment_index_count + 1,
  3897. sizeof(MOVFragmentIndex*));
  3898. if (!tmp) {
  3899. av_freep(&index->items);
  3900. av_freep(&index);
  3901. return AVERROR(ENOMEM);
  3902. }
  3903. c->fragment_index_data = tmp;
  3904. c->fragment_index_data[c->fragment_index_count++] = index;
  3905. sc->has_sidx = 1;
  3906. if (offset == avio_size(pb)) {
  3907. for (i = 0; i < c->fc->nb_streams; i++) {
  3908. if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) {
  3909. ref_st = c->fc->streams[i];
  3910. ref_sc = ref_st->priv_data;
  3911. break;
  3912. }
  3913. }
  3914. for (i = 0; i < c->fc->nb_streams; i++) {
  3915. st = c->fc->streams[i];
  3916. sc = st->priv_data;
  3917. if (!sc->has_sidx) {
  3918. st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale);
  3919. }
  3920. }
  3921. c->fragment_index_complete = 1;
  3922. }
  3923. return 0;
  3924. }
  3925. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3926. /* like the files created with Adobe Premiere 5.0, for samples see */
  3927. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3928. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3929. {
  3930. int err;
  3931. if (atom.size < 8)
  3932. return 0; /* continue */
  3933. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3934. avio_skip(pb, atom.size - 4);
  3935. return 0;
  3936. }
  3937. atom.type = avio_rl32(pb);
  3938. atom.size -= 8;
  3939. if (atom.type != MKTAG('m','d','a','t')) {
  3940. avio_skip(pb, atom.size);
  3941. return 0;
  3942. }
  3943. err = mov_read_mdat(c, pb, atom);
  3944. return err;
  3945. }
  3946. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3947. {
  3948. #if CONFIG_ZLIB
  3949. AVIOContext ctx;
  3950. uint8_t *cmov_data;
  3951. uint8_t *moov_data; /* uncompressed data */
  3952. long cmov_len, moov_len;
  3953. int ret = -1;
  3954. avio_rb32(pb); /* dcom atom */
  3955. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3956. return AVERROR_INVALIDDATA;
  3957. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3958. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3959. return AVERROR_INVALIDDATA;
  3960. }
  3961. avio_rb32(pb); /* cmvd atom */
  3962. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3963. return AVERROR_INVALIDDATA;
  3964. moov_len = avio_rb32(pb); /* uncompressed size */
  3965. cmov_len = atom.size - 6 * 4;
  3966. cmov_data = av_malloc(cmov_len);
  3967. if (!cmov_data)
  3968. return AVERROR(ENOMEM);
  3969. moov_data = av_malloc(moov_len);
  3970. if (!moov_data) {
  3971. av_free(cmov_data);
  3972. return AVERROR(ENOMEM);
  3973. }
  3974. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3975. if (ret < 0)
  3976. goto free_and_return;
  3977. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3978. goto free_and_return;
  3979. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3980. goto free_and_return;
  3981. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3982. atom.type = MKTAG('m','o','o','v');
  3983. atom.size = moov_len;
  3984. ret = mov_read_default(c, &ctx, atom);
  3985. free_and_return:
  3986. av_free(moov_data);
  3987. av_free(cmov_data);
  3988. return ret;
  3989. #else
  3990. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3991. return AVERROR(ENOSYS);
  3992. #endif
  3993. }
  3994. /* edit list atom */
  3995. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3996. {
  3997. MOVStreamContext *sc;
  3998. int i, edit_count, version;
  3999. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  4000. return 0;
  4001. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  4002. version = avio_r8(pb); /* version */
  4003. avio_rb24(pb); /* flags */
  4004. edit_count = avio_rb32(pb); /* entries */
  4005. if (!edit_count)
  4006. return 0;
  4007. if (sc->elst_data)
  4008. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  4009. av_free(sc->elst_data);
  4010. sc->elst_count = 0;
  4011. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  4012. if (!sc->elst_data)
  4013. return AVERROR(ENOMEM);
  4014. av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
  4015. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  4016. MOVElst *e = &sc->elst_data[i];
  4017. if (version == 1) {
  4018. e->duration = avio_rb64(pb);
  4019. e->time = avio_rb64(pb);
  4020. } else {
  4021. e->duration = avio_rb32(pb); /* segment duration */
  4022. e->time = (int32_t)avio_rb32(pb); /* media time */
  4023. }
  4024. e->rate = avio_rb32(pb) / 65536.0;
  4025. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  4026. e->duration, e->time, e->rate);
  4027. if (e->time < 0 && e->time != -1 &&
  4028. c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
  4029. av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n",
  4030. c->fc->nb_streams-1, i, e->time);
  4031. return AVERROR_INVALIDDATA;
  4032. }
  4033. }
  4034. sc->elst_count = i;
  4035. return 0;
  4036. }
  4037. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4038. {
  4039. MOVStreamContext *sc;
  4040. if (c->fc->nb_streams < 1)
  4041. return AVERROR_INVALIDDATA;
  4042. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4043. sc->timecode_track = avio_rb32(pb);
  4044. return 0;
  4045. }
  4046. static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4047. {
  4048. AVStream *st;
  4049. int version, color_range, color_primaries, color_trc, color_space;
  4050. if (c->fc->nb_streams < 1)
  4051. return 0;
  4052. st = c->fc->streams[c->fc->nb_streams - 1];
  4053. if (atom.size < 5) {
  4054. av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n");
  4055. return AVERROR_INVALIDDATA;
  4056. }
  4057. version = avio_r8(pb);
  4058. if (version != 1) {
  4059. av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version);
  4060. return 0;
  4061. }
  4062. avio_skip(pb, 3); /* flags */
  4063. avio_skip(pb, 2); /* profile + level */
  4064. color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */
  4065. color_primaries = avio_r8(pb);
  4066. color_trc = avio_r8(pb);
  4067. color_space = avio_r8(pb);
  4068. if (avio_rb16(pb)) /* codecIntializationDataSize */
  4069. return AVERROR_INVALIDDATA;
  4070. if (!av_color_primaries_name(color_primaries))
  4071. color_primaries = AVCOL_PRI_UNSPECIFIED;
  4072. if (!av_color_transfer_name(color_trc))
  4073. color_trc = AVCOL_TRC_UNSPECIFIED;
  4074. if (!av_color_space_name(color_space))
  4075. color_space = AVCOL_SPC_UNSPECIFIED;
  4076. st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  4077. st->codecpar->color_primaries = color_primaries;
  4078. st->codecpar->color_trc = color_trc;
  4079. st->codecpar->color_space = color_space;
  4080. return 0;
  4081. }
  4082. static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4083. {
  4084. MOVStreamContext *sc;
  4085. const int chroma_den = 50000;
  4086. const int luma_den = 10000;
  4087. int i, j, version;
  4088. if (c->fc->nb_streams < 1)
  4089. return AVERROR_INVALIDDATA;
  4090. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4091. if (atom.size < 5) {
  4092. av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n");
  4093. return AVERROR_INVALIDDATA;
  4094. }
  4095. version = avio_r8(pb);
  4096. if (version) {
  4097. av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version);
  4098. return 0;
  4099. }
  4100. avio_skip(pb, 3); /* flags */
  4101. sc->mastering = av_mastering_display_metadata_alloc();
  4102. if (!sc->mastering)
  4103. return AVERROR(ENOMEM);
  4104. for (i = 0; i < 3; i++)
  4105. for (j = 0; j < 2; j++)
  4106. sc->mastering->display_primaries[i][j] =
  4107. av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
  4108. for (i = 0; i < 2; i++)
  4109. sc->mastering->white_point[i] =
  4110. av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den);
  4111. sc->mastering->max_luminance =
  4112. av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den);
  4113. sc->mastering->min_luminance =
  4114. av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den);
  4115. sc->mastering->has_primaries = 1;
  4116. sc->mastering->has_luminance = 1;
  4117. return 0;
  4118. }
  4119. static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4120. {
  4121. MOVStreamContext *sc;
  4122. int version;
  4123. if (c->fc->nb_streams < 1)
  4124. return AVERROR_INVALIDDATA;
  4125. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  4126. if (atom.size < 5) {
  4127. av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n");
  4128. return AVERROR_INVALIDDATA;
  4129. }
  4130. version = avio_r8(pb);
  4131. if (version) {
  4132. av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version);
  4133. return 0;
  4134. }
  4135. avio_skip(pb, 3); /* flags */
  4136. sc->coll = av_content_light_metadata_alloc(&sc->coll_size);
  4137. if (!sc->coll)
  4138. return AVERROR(ENOMEM);
  4139. sc->coll->MaxCLL = avio_rb16(pb);
  4140. sc->coll->MaxFALL = avio_rb16(pb);
  4141. return 0;
  4142. }
  4143. static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4144. {
  4145. AVStream *st;
  4146. MOVStreamContext *sc;
  4147. enum AVStereo3DType type;
  4148. int mode;
  4149. if (c->fc->nb_streams < 1)
  4150. return 0;
  4151. st = c->fc->streams[c->fc->nb_streams - 1];
  4152. sc = st->priv_data;
  4153. if (atom.size < 5) {
  4154. av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
  4155. return AVERROR_INVALIDDATA;
  4156. }
  4157. avio_skip(pb, 4); /* version + flags */
  4158. mode = avio_r8(pb);
  4159. switch (mode) {
  4160. case 0:
  4161. type = AV_STEREO3D_2D;
  4162. break;
  4163. case 1:
  4164. type = AV_STEREO3D_TOPBOTTOM;
  4165. break;
  4166. case 2:
  4167. type = AV_STEREO3D_SIDEBYSIDE;
  4168. break;
  4169. default:
  4170. av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
  4171. return 0;
  4172. }
  4173. sc->stereo3d = av_stereo3d_alloc();
  4174. if (!sc->stereo3d)
  4175. return AVERROR(ENOMEM);
  4176. sc->stereo3d->type = type;
  4177. return 0;
  4178. }
  4179. static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4180. {
  4181. AVStream *st;
  4182. MOVStreamContext *sc;
  4183. int size, version, layout;
  4184. int32_t yaw, pitch, roll;
  4185. uint32_t l = 0, t = 0, r = 0, b = 0;
  4186. uint32_t tag, padding = 0;
  4187. enum AVSphericalProjection projection;
  4188. if (c->fc->nb_streams < 1)
  4189. return 0;
  4190. st = c->fc->streams[c->fc->nb_streams - 1];
  4191. sc = st->priv_data;
  4192. if (atom.size < 8) {
  4193. av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
  4194. return AVERROR_INVALIDDATA;
  4195. }
  4196. size = avio_rb32(pb);
  4197. if (size <= 12 || size > atom.size)
  4198. return AVERROR_INVALIDDATA;
  4199. tag = avio_rl32(pb);
  4200. if (tag != MKTAG('s','v','h','d')) {
  4201. av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
  4202. return 0;
  4203. }
  4204. version = avio_r8(pb);
  4205. if (version != 0) {
  4206. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4207. version);
  4208. return 0;
  4209. }
  4210. avio_skip(pb, 3); /* flags */
  4211. avio_skip(pb, size - 12); /* metadata_source */
  4212. size = avio_rb32(pb);
  4213. if (size > atom.size)
  4214. return AVERROR_INVALIDDATA;
  4215. tag = avio_rl32(pb);
  4216. if (tag != MKTAG('p','r','o','j')) {
  4217. av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
  4218. return 0;
  4219. }
  4220. size = avio_rb32(pb);
  4221. if (size > atom.size)
  4222. return AVERROR_INVALIDDATA;
  4223. tag = avio_rl32(pb);
  4224. if (tag != MKTAG('p','r','h','d')) {
  4225. av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
  4226. return 0;
  4227. }
  4228. version = avio_r8(pb);
  4229. if (version != 0) {
  4230. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4231. version);
  4232. return 0;
  4233. }
  4234. avio_skip(pb, 3); /* flags */
  4235. /* 16.16 fixed point */
  4236. yaw = avio_rb32(pb);
  4237. pitch = avio_rb32(pb);
  4238. roll = avio_rb32(pb);
  4239. size = avio_rb32(pb);
  4240. if (size > atom.size)
  4241. return AVERROR_INVALIDDATA;
  4242. tag = avio_rl32(pb);
  4243. version = avio_r8(pb);
  4244. if (version != 0) {
  4245. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  4246. version);
  4247. return 0;
  4248. }
  4249. avio_skip(pb, 3); /* flags */
  4250. switch (tag) {
  4251. case MKTAG('c','b','m','p'):
  4252. layout = avio_rb32(pb);
  4253. if (layout) {
  4254. av_log(c->fc, AV_LOG_WARNING,
  4255. "Unsupported cubemap layout %d\n", layout);
  4256. return 0;
  4257. }
  4258. projection = AV_SPHERICAL_CUBEMAP;
  4259. padding = avio_rb32(pb);
  4260. break;
  4261. case MKTAG('e','q','u','i'):
  4262. t = avio_rb32(pb);
  4263. b = avio_rb32(pb);
  4264. l = avio_rb32(pb);
  4265. r = avio_rb32(pb);
  4266. if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
  4267. av_log(c->fc, AV_LOG_ERROR,
  4268. "Invalid bounding rectangle coordinates "
  4269. "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
  4270. return AVERROR_INVALIDDATA;
  4271. }
  4272. if (l || t || r || b)
  4273. projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
  4274. else
  4275. projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4276. break;
  4277. default:
  4278. av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
  4279. return 0;
  4280. }
  4281. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4282. if (!sc->spherical)
  4283. return AVERROR(ENOMEM);
  4284. sc->spherical->projection = projection;
  4285. sc->spherical->yaw = yaw;
  4286. sc->spherical->pitch = pitch;
  4287. sc->spherical->roll = roll;
  4288. sc->spherical->padding = padding;
  4289. sc->spherical->bound_left = l;
  4290. sc->spherical->bound_top = t;
  4291. sc->spherical->bound_right = r;
  4292. sc->spherical->bound_bottom = b;
  4293. return 0;
  4294. }
  4295. static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
  4296. {
  4297. int ret = 0;
  4298. uint8_t *buffer = av_malloc(len + 1);
  4299. const char *val;
  4300. if (!buffer)
  4301. return AVERROR(ENOMEM);
  4302. buffer[len] = '\0';
  4303. ret = ffio_read_size(pb, buffer, len);
  4304. if (ret < 0)
  4305. goto out;
  4306. /* Check for mandatory keys and values, try to support XML as best-effort */
  4307. if (!sc->spherical &&
  4308. av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
  4309. (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
  4310. av_stristr(val, "true") &&
  4311. (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
  4312. av_stristr(val, "true") &&
  4313. (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
  4314. av_stristr(val, "equirectangular")) {
  4315. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  4316. if (!sc->spherical)
  4317. goto out;
  4318. sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
  4319. if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
  4320. enum AVStereo3DType mode;
  4321. if (av_stristr(buffer, "left-right"))
  4322. mode = AV_STEREO3D_SIDEBYSIDE;
  4323. else if (av_stristr(buffer, "top-bottom"))
  4324. mode = AV_STEREO3D_TOPBOTTOM;
  4325. else
  4326. mode = AV_STEREO3D_2D;
  4327. sc->stereo3d = av_stereo3d_alloc();
  4328. if (!sc->stereo3d)
  4329. goto out;
  4330. sc->stereo3d->type = mode;
  4331. }
  4332. /* orientation */
  4333. val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
  4334. if (val)
  4335. sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
  4336. val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
  4337. if (val)
  4338. sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
  4339. val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
  4340. if (val)
  4341. sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
  4342. }
  4343. out:
  4344. av_free(buffer);
  4345. return ret;
  4346. }
  4347. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4348. {
  4349. AVStream *st;
  4350. MOVStreamContext *sc;
  4351. int64_t ret;
  4352. uint8_t uuid[16];
  4353. static const uint8_t uuid_isml_manifest[] = {
  4354. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  4355. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  4356. };
  4357. static const uint8_t uuid_xmp[] = {
  4358. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  4359. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  4360. };
  4361. static const uint8_t uuid_spherical[] = {
  4362. 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
  4363. 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
  4364. };
  4365. if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX))
  4366. return AVERROR_INVALIDDATA;
  4367. if (c->fc->nb_streams < 1)
  4368. return 0;
  4369. st = c->fc->streams[c->fc->nb_streams - 1];
  4370. sc = st->priv_data;
  4371. ret = avio_read(pb, uuid, sizeof(uuid));
  4372. if (ret < 0) {
  4373. return ret;
  4374. } else if (ret != sizeof(uuid)) {
  4375. return AVERROR_INVALIDDATA;
  4376. }
  4377. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  4378. uint8_t *buffer, *ptr;
  4379. char *endptr;
  4380. size_t len = atom.size - sizeof(uuid);
  4381. if (len < 4) {
  4382. return AVERROR_INVALIDDATA;
  4383. }
  4384. ret = avio_skip(pb, 4); // zeroes
  4385. len -= 4;
  4386. buffer = av_mallocz(len + 1);
  4387. if (!buffer) {
  4388. return AVERROR(ENOMEM);
  4389. }
  4390. ret = avio_read(pb, buffer, len);
  4391. if (ret < 0) {
  4392. av_free(buffer);
  4393. return ret;
  4394. } else if (ret != len) {
  4395. av_free(buffer);
  4396. return AVERROR_INVALIDDATA;
  4397. }
  4398. ptr = buffer;
  4399. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  4400. ptr += sizeof("systemBitrate=\"") - 1;
  4401. c->bitrates_count++;
  4402. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  4403. if (!c->bitrates) {
  4404. c->bitrates_count = 0;
  4405. av_free(buffer);
  4406. return AVERROR(ENOMEM);
  4407. }
  4408. errno = 0;
  4409. ret = strtol(ptr, &endptr, 10);
  4410. if (ret < 0 || errno || *endptr != '"') {
  4411. c->bitrates[c->bitrates_count - 1] = 0;
  4412. } else {
  4413. c->bitrates[c->bitrates_count - 1] = ret;
  4414. }
  4415. }
  4416. av_free(buffer);
  4417. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  4418. uint8_t *buffer;
  4419. size_t len = atom.size - sizeof(uuid);
  4420. if (c->export_xmp) {
  4421. buffer = av_mallocz(len + 1);
  4422. if (!buffer) {
  4423. return AVERROR(ENOMEM);
  4424. }
  4425. ret = avio_read(pb, buffer, len);
  4426. if (ret < 0) {
  4427. av_free(buffer);
  4428. return ret;
  4429. } else if (ret != len) {
  4430. av_free(buffer);
  4431. return AVERROR_INVALIDDATA;
  4432. }
  4433. buffer[len] = '\0';
  4434. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  4435. av_free(buffer);
  4436. } else {
  4437. // skip all uuid atom, which makes it fast for long uuid-xmp file
  4438. ret = avio_skip(pb, len);
  4439. if (ret < 0)
  4440. return ret;
  4441. }
  4442. } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) {
  4443. size_t len = atom.size - sizeof(uuid);
  4444. ret = mov_parse_uuid_spherical(sc, pb, len);
  4445. if (ret < 0)
  4446. return ret;
  4447. if (!sc->spherical)
  4448. av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); }
  4449. return 0;
  4450. }
  4451. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4452. {
  4453. int ret;
  4454. uint8_t content[16];
  4455. if (atom.size < 8)
  4456. return 0;
  4457. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  4458. if (ret < 0)
  4459. return ret;
  4460. if ( !c->found_moov
  4461. && !c->found_mdat
  4462. && !memcmp(content, "Anevia\x1A\x1A", 8)
  4463. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  4464. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  4465. }
  4466. return 0;
  4467. }
  4468. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4469. {
  4470. uint32_t format = avio_rl32(pb);
  4471. MOVStreamContext *sc;
  4472. enum AVCodecID id;
  4473. AVStream *st;
  4474. if (c->fc->nb_streams < 1)
  4475. return 0;
  4476. st = c->fc->streams[c->fc->nb_streams - 1];
  4477. sc = st->priv_data;
  4478. switch (sc->format)
  4479. {
  4480. case MKTAG('e','n','c','v'): // encrypted video
  4481. case MKTAG('e','n','c','a'): // encrypted audio
  4482. id = mov_codec_id(st, format);
  4483. if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
  4484. st->codecpar->codec_id != id) {
  4485. av_log(c->fc, AV_LOG_WARNING,
  4486. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  4487. (char*)&format, st->codecpar->codec_id);
  4488. break;
  4489. }
  4490. st->codecpar->codec_id = id;
  4491. sc->format = format;
  4492. break;
  4493. default:
  4494. if (format != sc->format) {
  4495. av_log(c->fc, AV_LOG_WARNING,
  4496. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  4497. (char*)&format, (char*)&sc->format);
  4498. }
  4499. break;
  4500. }
  4501. return 0;
  4502. }
  4503. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4504. {
  4505. AVStream *st;
  4506. MOVStreamContext *sc;
  4507. size_t auxiliary_info_size;
  4508. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4509. return 0;
  4510. st = c->fc->streams[c->fc->nb_streams - 1];
  4511. sc = st->priv_data;
  4512. if (sc->cenc.aes_ctr) {
  4513. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  4514. return AVERROR_INVALIDDATA;
  4515. }
  4516. avio_r8(pb); /* version */
  4517. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  4518. avio_rb32(pb); /* entries */
  4519. if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
  4520. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size);
  4521. return AVERROR_INVALIDDATA;
  4522. }
  4523. /* save the auxiliary info as is */
  4524. auxiliary_info_size = atom.size - 8;
  4525. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  4526. if (!sc->cenc.auxiliary_info) {
  4527. return AVERROR(ENOMEM);
  4528. }
  4529. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  4530. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  4531. sc->cenc.auxiliary_info_index = 0;
  4532. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  4533. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  4534. return AVERROR_INVALIDDATA;
  4535. }
  4536. /* initialize the cipher */
  4537. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  4538. if (!sc->cenc.aes_ctr) {
  4539. return AVERROR(ENOMEM);
  4540. }
  4541. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  4542. }
  4543. static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4544. {
  4545. AVStream *st;
  4546. MOVStreamContext *sc;
  4547. size_t data_size;
  4548. int atom_header_size;
  4549. int flags;
  4550. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  4551. return 0;
  4552. st = c->fc->streams[c->fc->nb_streams - 1];
  4553. sc = st->priv_data;
  4554. if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
  4555. av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
  4556. return AVERROR_INVALIDDATA;
  4557. }
  4558. atom_header_size = 9;
  4559. avio_r8(pb); /* version */
  4560. flags = avio_rb24(pb);
  4561. if ((flags & 0x01) != 0) {
  4562. atom_header_size += 8;
  4563. avio_rb32(pb); /* info type */
  4564. avio_rb32(pb); /* info type param */
  4565. }
  4566. sc->cenc.auxiliary_info_default_size = avio_r8(pb);
  4567. avio_rb32(pb); /* entries */
  4568. if (atom.size <= atom_header_size) {
  4569. return 0;
  4570. }
  4571. if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) {
  4572. av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size);
  4573. return AVERROR_INVALIDDATA;
  4574. }
  4575. /* save the auxiliary info sizes as is */
  4576. data_size = atom.size - atom_header_size;
  4577. sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
  4578. if (!sc->cenc.auxiliary_info_sizes) {
  4579. return AVERROR(ENOMEM);
  4580. }
  4581. sc->cenc.auxiliary_info_sizes_count = data_size;
  4582. if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
  4583. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
  4584. return AVERROR_INVALIDDATA;
  4585. }
  4586. return 0;
  4587. }
  4588. static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4589. {
  4590. AVStream *st;
  4591. int last, type, size, ret;
  4592. uint8_t buf[4];
  4593. if (c->fc->nb_streams < 1)
  4594. return 0;
  4595. st = c->fc->streams[c->fc->nb_streams-1];
  4596. if ((uint64_t)atom.size > (1<<30) || atom.size < 42)
  4597. return AVERROR_INVALIDDATA;
  4598. /* Check FlacSpecificBox version. */
  4599. if (avio_r8(pb) != 0)
  4600. return AVERROR_INVALIDDATA;
  4601. avio_rb24(pb); /* Flags */
  4602. avio_read(pb, buf, sizeof(buf));
  4603. flac_parse_block_header(buf, &last, &type, &size);
  4604. if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) {
  4605. av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
  4606. return AVERROR_INVALIDDATA;
  4607. }
  4608. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  4609. if (ret < 0)
  4610. return ret;
  4611. if (!last)
  4612. av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
  4613. return 0;
  4614. }
  4615. static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index)
  4616. {
  4617. size_t auxiliary_info_seek_offset = 0;
  4618. int i;
  4619. if (sc->cenc.auxiliary_info_default_size) {
  4620. auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index;
  4621. } else if (sc->cenc.auxiliary_info_sizes) {
  4622. if (index > sc->cenc.auxiliary_info_sizes_count) {
  4623. av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
  4624. index, sc->cenc.auxiliary_info_sizes_count);
  4625. return AVERROR_INVALIDDATA;
  4626. }
  4627. for (i = 0; i < index; i++) {
  4628. auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
  4629. }
  4630. }
  4631. if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
  4632. av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
  4633. auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
  4634. return AVERROR_INVALIDDATA;
  4635. }
  4636. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
  4637. sc->cenc.auxiliary_info_index = index;
  4638. return 0;
  4639. }
  4640. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size)
  4641. {
  4642. uint32_t encrypted_bytes;
  4643. uint16_t subsample_count;
  4644. uint16_t clear_bytes;
  4645. uint8_t* input_end = input + size;
  4646. int ret;
  4647. if (index != sc->cenc.auxiliary_info_index) {
  4648. ret = mov_seek_auxiliary_info(c, sc, index);
  4649. if (ret < 0) {
  4650. return ret;
  4651. }
  4652. }
  4653. /* read the iv */
  4654. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4655. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  4656. return AVERROR_INVALIDDATA;
  4657. }
  4658. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  4659. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  4660. if (!sc->cenc.use_subsamples)
  4661. {
  4662. /* decrypt the whole packet */
  4663. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  4664. return 0;
  4665. }
  4666. /* read the subsample count */
  4667. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4668. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  4669. return AVERROR_INVALIDDATA;
  4670. }
  4671. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  4672. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4673. for (; subsample_count > 0; subsample_count--)
  4674. {
  4675. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  4676. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  4677. return AVERROR_INVALIDDATA;
  4678. }
  4679. /* read the number of clear / encrypted bytes */
  4680. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  4681. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  4682. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  4683. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  4684. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  4685. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  4686. return AVERROR_INVALIDDATA;
  4687. }
  4688. /* skip the clear bytes */
  4689. input += clear_bytes;
  4690. /* decrypt the encrypted bytes */
  4691. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  4692. input += encrypted_bytes;
  4693. }
  4694. if (input < input_end) {
  4695. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  4696. return AVERROR_INVALIDDATA;
  4697. }
  4698. sc->cenc.auxiliary_info_index++;
  4699. return 0;
  4700. }
  4701. static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4702. {
  4703. const int OPUS_SEEK_PREROLL_MS = 80;
  4704. AVStream *st;
  4705. size_t size;
  4706. int16_t pre_skip;
  4707. if (c->fc->nb_streams < 1)
  4708. return 0;
  4709. st = c->fc->streams[c->fc->nb_streams-1];
  4710. if ((uint64_t)atom.size > (1<<30) || atom.size < 11)
  4711. return AVERROR_INVALIDDATA;
  4712. /* Check OpusSpecificBox version. */
  4713. if (avio_r8(pb) != 0) {
  4714. av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n");
  4715. return AVERROR_INVALIDDATA;
  4716. }
  4717. /* OpusSpecificBox size plus magic for Ogg OpusHead header. */
  4718. size = atom.size + 8;
  4719. if (ff_alloc_extradata(st->codecpar, size))
  4720. return AVERROR(ENOMEM);
  4721. AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s'));
  4722. AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d'));
  4723. AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */
  4724. avio_read(pb, st->codecpar->extradata + 9, size - 9);
  4725. /* OpusSpecificBox is stored in big-endian, but OpusHead is
  4726. little-endian; aside from the preceeding magic and version they're
  4727. otherwise currently identical. Data after output gain at offset 16
  4728. doesn't need to be bytewapped. */
  4729. pre_skip = AV_RB16(st->codecpar->extradata + 10);
  4730. AV_WL16(st->codecpar->extradata + 10, pre_skip);
  4731. AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12));
  4732. AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16));
  4733. st->codecpar->initial_padding = pre_skip;
  4734. st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS,
  4735. (AVRational){1, 1000},
  4736. (AVRational){1, 48000});
  4737. return 0;
  4738. }
  4739. static const MOVParseTableEntry mov_default_parse_table[] = {
  4740. { MKTAG('A','C','L','R'), mov_read_aclr },
  4741. { MKTAG('A','P','R','G'), mov_read_avid },
  4742. { MKTAG('A','A','L','P'), mov_read_avid },
  4743. { MKTAG('A','R','E','S'), mov_read_ares },
  4744. { MKTAG('a','v','s','s'), mov_read_avss },
  4745. { MKTAG('c','h','p','l'), mov_read_chpl },
  4746. { MKTAG('c','o','6','4'), mov_read_stco },
  4747. { MKTAG('c','o','l','r'), mov_read_colr },
  4748. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  4749. { MKTAG('d','i','n','f'), mov_read_default },
  4750. { MKTAG('D','p','x','E'), mov_read_dpxe },
  4751. { MKTAG('d','r','e','f'), mov_read_dref },
  4752. { MKTAG('e','d','t','s'), mov_read_default },
  4753. { MKTAG('e','l','s','t'), mov_read_elst },
  4754. { MKTAG('e','n','d','a'), mov_read_enda },
  4755. { MKTAG('f','i','e','l'), mov_read_fiel },
  4756. { MKTAG('a','d','r','m'), mov_read_adrm },
  4757. { MKTAG('f','t','y','p'), mov_read_ftyp },
  4758. { MKTAG('g','l','b','l'), mov_read_glbl },
  4759. { MKTAG('h','d','l','r'), mov_read_hdlr },
  4760. { MKTAG('i','l','s','t'), mov_read_ilst },
  4761. { MKTAG('j','p','2','h'), mov_read_jp2h },
  4762. { MKTAG('m','d','a','t'), mov_read_mdat },
  4763. { MKTAG('m','d','h','d'), mov_read_mdhd },
  4764. { MKTAG('m','d','i','a'), mov_read_default },
  4765. { MKTAG('m','e','t','a'), mov_read_meta },
  4766. { MKTAG('m','i','n','f'), mov_read_default },
  4767. { MKTAG('m','o','o','f'), mov_read_moof },
  4768. { MKTAG('m','o','o','v'), mov_read_moov },
  4769. { MKTAG('m','v','e','x'), mov_read_default },
  4770. { MKTAG('m','v','h','d'), mov_read_mvhd },
  4771. { MKTAG('S','M','I',' '), mov_read_svq3 },
  4772. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  4773. { MKTAG('a','v','c','C'), mov_read_glbl },
  4774. { MKTAG('p','a','s','p'), mov_read_pasp },
  4775. { MKTAG('s','i','d','x'), mov_read_sidx },
  4776. { MKTAG('s','t','b','l'), mov_read_default },
  4777. { MKTAG('s','t','c','o'), mov_read_stco },
  4778. { MKTAG('s','t','p','s'), mov_read_stps },
  4779. { MKTAG('s','t','r','f'), mov_read_strf },
  4780. { MKTAG('s','t','s','c'), mov_read_stsc },
  4781. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  4782. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  4783. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  4784. { MKTAG('s','t','t','s'), mov_read_stts },
  4785. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  4786. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  4787. { MKTAG('t','f','d','t'), mov_read_tfdt },
  4788. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  4789. { MKTAG('t','r','a','k'), mov_read_trak },
  4790. { MKTAG('t','r','a','f'), mov_read_default },
  4791. { MKTAG('t','r','e','f'), mov_read_default },
  4792. { MKTAG('t','m','c','d'), mov_read_tmcd },
  4793. { MKTAG('c','h','a','p'), mov_read_chap },
  4794. { MKTAG('t','r','e','x'), mov_read_trex },
  4795. { MKTAG('t','r','u','n'), mov_read_trun },
  4796. { MKTAG('u','d','t','a'), mov_read_default },
  4797. { MKTAG('w','a','v','e'), mov_read_wave },
  4798. { MKTAG('e','s','d','s'), mov_read_esds },
  4799. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  4800. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  4801. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  4802. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  4803. { MKTAG('w','f','e','x'), mov_read_wfex },
  4804. { MKTAG('c','m','o','v'), mov_read_cmov },
  4805. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  4806. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  4807. { MKTAG('s','b','g','p'), mov_read_sbgp },
  4808. { MKTAG('h','v','c','C'), mov_read_glbl },
  4809. { MKTAG('u','u','i','d'), mov_read_uuid },
  4810. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  4811. { MKTAG('f','r','e','e'), mov_read_free },
  4812. { MKTAG('-','-','-','-'), mov_read_custom },
  4813. { MKTAG('s','i','n','f'), mov_read_default },
  4814. { MKTAG('f','r','m','a'), mov_read_frma },
  4815. { MKTAG('s','e','n','c'), mov_read_senc },
  4816. { MKTAG('s','a','i','z'), mov_read_saiz },
  4817. { MKTAG('d','f','L','a'), mov_read_dfla },
  4818. { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
  4819. { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
  4820. { MKTAG('d','O','p','s'), mov_read_dops },
  4821. { MKTAG('S','m','D','m'), mov_read_smdm },
  4822. { MKTAG('C','o','L','L'), mov_read_coll },
  4823. { MKTAG('v','p','c','C'), mov_read_vpcc },
  4824. { 0, NULL }
  4825. };
  4826. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  4827. {
  4828. int64_t total_size = 0;
  4829. MOVAtom a;
  4830. int i;
  4831. if (c->atom_depth > 10) {
  4832. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  4833. return AVERROR_INVALIDDATA;
  4834. }
  4835. c->atom_depth ++;
  4836. if (atom.size < 0)
  4837. atom.size = INT64_MAX;
  4838. while (total_size <= atom.size - 8 && !avio_feof(pb)) {
  4839. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  4840. a.size = atom.size;
  4841. a.type=0;
  4842. if (atom.size >= 8) {
  4843. a.size = avio_rb32(pb);
  4844. a.type = avio_rl32(pb);
  4845. if (a.type == MKTAG('f','r','e','e') &&
  4846. a.size >= 8 &&
  4847. c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT &&
  4848. c->moov_retry) {
  4849. uint8_t buf[8];
  4850. uint32_t *type = (uint32_t *)buf + 1;
  4851. if (avio_read(pb, buf, 8) != 8)
  4852. return AVERROR_INVALIDDATA;
  4853. avio_seek(pb, -8, SEEK_CUR);
  4854. if (*type == MKTAG('m','v','h','d') ||
  4855. *type == MKTAG('c','m','o','v')) {
  4856. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  4857. a.type = MKTAG('m','o','o','v');
  4858. }
  4859. }
  4860. if (atom.type != MKTAG('r','o','o','t') &&
  4861. atom.type != MKTAG('m','o','o','v'))
  4862. {
  4863. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  4864. {
  4865. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  4866. avio_skip(pb, -8);
  4867. c->atom_depth --;
  4868. return 0;
  4869. }
  4870. }
  4871. total_size += 8;
  4872. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  4873. a.size = avio_rb64(pb) - 8;
  4874. total_size += 8;
  4875. }
  4876. }
  4877. av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  4878. av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size);
  4879. if (a.size == 0) {
  4880. a.size = atom.size - total_size + 8;
  4881. }
  4882. a.size -= 8;
  4883. if (a.size < 0)
  4884. break;
  4885. a.size = FFMIN(a.size, atom.size - total_size);
  4886. for (i = 0; mov_default_parse_table[i].type; i++)
  4887. if (mov_default_parse_table[i].type == a.type) {
  4888. parse = mov_default_parse_table[i].parse;
  4889. break;
  4890. }
  4891. // container is user data
  4892. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  4893. atom.type == MKTAG('i','l','s','t')))
  4894. parse = mov_read_udta_string;
  4895. // Supports parsing the QuickTime Metadata Keys.
  4896. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  4897. if (!parse && c->found_hdlr_mdta &&
  4898. atom.type == MKTAG('m','e','t','a') &&
  4899. a.type == MKTAG('k','e','y','s')) {
  4900. parse = mov_read_keys;
  4901. }
  4902. if (!parse) { /* skip leaf atoms data */
  4903. avio_skip(pb, a.size);
  4904. } else {
  4905. int64_t start_pos = avio_tell(pb);
  4906. int64_t left;
  4907. int err = parse(c, pb, a);
  4908. if (err < 0) {
  4909. c->atom_depth --;
  4910. return err;
  4911. }
  4912. if (c->found_moov && c->found_mdat &&
  4913. ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  4914. start_pos + a.size == avio_size(pb))) {
  4915. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  4916. c->next_root_atom = start_pos + a.size;
  4917. c->atom_depth --;
  4918. return 0;
  4919. }
  4920. left = a.size - avio_tell(pb) + start_pos;
  4921. if (left > 0) /* skip garbage at atom end */
  4922. avio_skip(pb, left);
  4923. else if (left < 0) {
  4924. av_log(c->fc, AV_LOG_WARNING,
  4925. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  4926. (char*)&a.type, -left);
  4927. avio_seek(pb, left, SEEK_CUR);
  4928. }
  4929. }
  4930. total_size += a.size;
  4931. }
  4932. if (total_size < atom.size && atom.size < 0x7ffff)
  4933. avio_skip(pb, atom.size - total_size);
  4934. c->atom_depth --;
  4935. return 0;
  4936. }
  4937. static int mov_probe(AVProbeData *p)
  4938. {
  4939. int64_t offset;
  4940. uint32_t tag;
  4941. int score = 0;
  4942. int moov_offset = -1;
  4943. /* check file header */
  4944. offset = 0;
  4945. for (;;) {
  4946. /* ignore invalid offset */
  4947. if ((offset + 8) > (unsigned int)p->buf_size)
  4948. break;
  4949. tag = AV_RL32(p->buf + offset + 4);
  4950. switch(tag) {
  4951. /* check for obvious tags */
  4952. case MKTAG('m','o','o','v'):
  4953. moov_offset = offset + 4;
  4954. case MKTAG('m','d','a','t'):
  4955. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  4956. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  4957. case MKTAG('f','t','y','p'):
  4958. if (AV_RB32(p->buf+offset) < 8 &&
  4959. (AV_RB32(p->buf+offset) != 1 ||
  4960. offset + 12 > (unsigned int)p->buf_size ||
  4961. AV_RB64(p->buf+offset + 8) == 0)) {
  4962. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4963. } else if (tag == MKTAG('f','t','y','p') &&
  4964. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  4965. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  4966. )) {
  4967. score = FFMAX(score, 5);
  4968. } else {
  4969. score = AVPROBE_SCORE_MAX;
  4970. }
  4971. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4972. break;
  4973. /* those are more common words, so rate then a bit less */
  4974. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  4975. case MKTAG('w','i','d','e'):
  4976. case MKTAG('f','r','e','e'):
  4977. case MKTAG('j','u','n','k'):
  4978. case MKTAG('p','i','c','t'):
  4979. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  4980. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4981. break;
  4982. case MKTAG(0x82,0x82,0x7f,0x7d):
  4983. case MKTAG('s','k','i','p'):
  4984. case MKTAG('u','u','i','d'):
  4985. case MKTAG('p','r','f','l'):
  4986. /* if we only find those cause probedata is too small at least rate them */
  4987. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  4988. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4989. break;
  4990. default:
  4991. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  4992. }
  4993. }
  4994. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  4995. /* moov atom in the header - we should make sure that this is not a
  4996. * MOV-packed MPEG-PS */
  4997. offset = moov_offset;
  4998. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  4999. /* We found an actual hdlr atom */
  5000. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  5001. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  5002. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  5003. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  5004. /* We found a media handler reference atom describing an
  5005. * MPEG-PS-in-MOV, return a
  5006. * low score to force expanding the probe window until
  5007. * mpegps_probe finds what it needs */
  5008. return 5;
  5009. }else
  5010. /* Keep looking */
  5011. offset+=2;
  5012. }
  5013. }
  5014. return score;
  5015. }
  5016. // must be done after parsing all trak because there's no order requirement
  5017. static void mov_read_chapters(AVFormatContext *s)
  5018. {
  5019. MOVContext *mov = s->priv_data;
  5020. AVStream *st;
  5021. MOVStreamContext *sc;
  5022. int64_t cur_pos;
  5023. int i, j;
  5024. int chapter_track;
  5025. for (j = 0; j < mov->nb_chapter_tracks; j++) {
  5026. chapter_track = mov->chapter_tracks[j];
  5027. st = NULL;
  5028. for (i = 0; i < s->nb_streams; i++)
  5029. if (s->streams[i]->id == chapter_track) {
  5030. st = s->streams[i];
  5031. break;
  5032. }
  5033. if (!st) {
  5034. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  5035. continue;
  5036. }
  5037. sc = st->priv_data;
  5038. cur_pos = avio_tell(sc->pb);
  5039. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  5040. st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS;
  5041. if (st->nb_index_entries) {
  5042. // Retrieve the first frame, if possible
  5043. AVPacket pkt;
  5044. AVIndexEntry *sample = &st->index_entries[0];
  5045. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  5046. av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n");
  5047. goto finish;
  5048. }
  5049. if (av_get_packet(sc->pb, &pkt, sample->size) < 0)
  5050. goto finish;
  5051. st->attached_pic = pkt;
  5052. st->attached_pic.stream_index = st->index;
  5053. st->attached_pic.flags |= AV_PKT_FLAG_KEY;
  5054. }
  5055. } else {
  5056. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  5057. st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA;
  5058. st->discard = AVDISCARD_ALL;
  5059. for (i = 0; i < st->nb_index_entries; i++) {
  5060. AVIndexEntry *sample = &st->index_entries[i];
  5061. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  5062. uint8_t *title;
  5063. uint16_t ch;
  5064. int len, title_len;
  5065. if (end < sample->timestamp) {
  5066. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  5067. end = AV_NOPTS_VALUE;
  5068. }
  5069. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  5070. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  5071. goto finish;
  5072. }
  5073. // the first two bytes are the length of the title
  5074. len = avio_rb16(sc->pb);
  5075. if (len > sample->size-2)
  5076. continue;
  5077. title_len = 2*len + 1;
  5078. if (!(title = av_mallocz(title_len)))
  5079. goto finish;
  5080. // The samples could theoretically be in any encoding if there's an encd
  5081. // atom following, but in practice are only utf-8 or utf-16, distinguished
  5082. // instead by the presence of a BOM
  5083. if (!len) {
  5084. title[0] = 0;
  5085. } else {
  5086. ch = avio_rb16(sc->pb);
  5087. if (ch == 0xfeff)
  5088. avio_get_str16be(sc->pb, len, title, title_len);
  5089. else if (ch == 0xfffe)
  5090. avio_get_str16le(sc->pb, len, title, title_len);
  5091. else {
  5092. AV_WB16(title, ch);
  5093. if (len == 1 || len == 2)
  5094. title[len] = 0;
  5095. else
  5096. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  5097. }
  5098. }
  5099. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  5100. av_freep(&title);
  5101. }
  5102. }
  5103. finish:
  5104. avio_seek(sc->pb, cur_pos, SEEK_SET);
  5105. }
  5106. }
  5107. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  5108. uint32_t value, int flags)
  5109. {
  5110. AVTimecode tc;
  5111. char buf[AV_TIMECODE_STR_SIZE];
  5112. AVRational rate = st->avg_frame_rate;
  5113. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  5114. if (ret < 0)
  5115. return ret;
  5116. av_dict_set(&st->metadata, "timecode",
  5117. av_timecode_make_string(&tc, buf, value), 0);
  5118. return 0;
  5119. }
  5120. static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st)
  5121. {
  5122. MOVStreamContext *sc = st->priv_data;
  5123. char buf[AV_TIMECODE_STR_SIZE];
  5124. int64_t cur_pos = avio_tell(sc->pb);
  5125. int hh, mm, ss, ff, drop;
  5126. if (!st->nb_index_entries)
  5127. return -1;
  5128. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  5129. avio_skip(s->pb, 13);
  5130. hh = avio_r8(s->pb);
  5131. mm = avio_r8(s->pb);
  5132. ss = avio_r8(s->pb);
  5133. drop = avio_r8(s->pb);
  5134. ff = avio_r8(s->pb);
  5135. snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d",
  5136. hh, mm, ss, drop ? ';' : ':', ff);
  5137. av_dict_set(&st->metadata, "timecode", buf, 0);
  5138. avio_seek(sc->pb, cur_pos, SEEK_SET);
  5139. return 0;
  5140. }
  5141. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  5142. {
  5143. MOVStreamContext *sc = st->priv_data;
  5144. int flags = 0;
  5145. int64_t cur_pos = avio_tell(sc->pb);
  5146. uint32_t value;
  5147. if (!st->nb_index_entries)
  5148. return -1;
  5149. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  5150. value = avio_rb32(s->pb);
  5151. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  5152. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  5153. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  5154. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  5155. * not the case) and thus assume "frame number format" instead of QT one.
  5156. * No sample with tmcd track can be found with a QT timecode at the moment,
  5157. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  5158. * format). */
  5159. parse_timecode_in_framenum_format(s, st, value, flags);
  5160. avio_seek(sc->pb, cur_pos, SEEK_SET);
  5161. return 0;
  5162. }
  5163. static int mov_read_close(AVFormatContext *s)
  5164. {
  5165. MOVContext *mov = s->priv_data;
  5166. int i, j;
  5167. for (i = 0; i < s->nb_streams; i++) {
  5168. AVStream *st = s->streams[i];
  5169. MOVStreamContext *sc = st->priv_data;
  5170. if (!sc)
  5171. continue;
  5172. av_freep(&sc->ctts_data);
  5173. for (j = 0; j < sc->drefs_count; j++) {
  5174. av_freep(&sc->drefs[j].path);
  5175. av_freep(&sc->drefs[j].dir);
  5176. }
  5177. av_freep(&sc->drefs);
  5178. sc->drefs_count = 0;
  5179. if (!sc->pb_is_copied)
  5180. ff_format_io_close(s, &sc->pb);
  5181. sc->pb = NULL;
  5182. av_freep(&sc->chunk_offsets);
  5183. av_freep(&sc->stsc_data);
  5184. av_freep(&sc->sample_sizes);
  5185. av_freep(&sc->keyframes);
  5186. av_freep(&sc->stts_data);
  5187. av_freep(&sc->stps_data);
  5188. av_freep(&sc->elst_data);
  5189. av_freep(&sc->rap_group);
  5190. av_freep(&sc->display_matrix);
  5191. av_freep(&sc->index_ranges);
  5192. if (sc->extradata)
  5193. for (j = 0; j < sc->stsd_count; j++)
  5194. av_free(sc->extradata[j]);
  5195. av_freep(&sc->extradata);
  5196. av_freep(&sc->extradata_size);
  5197. av_freep(&sc->cenc.auxiliary_info);
  5198. av_freep(&sc->cenc.auxiliary_info_sizes);
  5199. av_aes_ctr_free(sc->cenc.aes_ctr);
  5200. av_freep(&sc->stereo3d);
  5201. av_freep(&sc->spherical);
  5202. av_freep(&sc->mastering);
  5203. av_freep(&sc->coll);
  5204. }
  5205. if (mov->dv_demux) {
  5206. avformat_free_context(mov->dv_fctx);
  5207. mov->dv_fctx = NULL;
  5208. }
  5209. if (mov->meta_keys) {
  5210. for (i = 1; i < mov->meta_keys_count; i++) {
  5211. av_freep(&mov->meta_keys[i]);
  5212. }
  5213. av_freep(&mov->meta_keys);
  5214. }
  5215. av_freep(&mov->trex_data);
  5216. av_freep(&mov->bitrates);
  5217. for (i = 0; i < mov->fragment_index_count; i++) {
  5218. MOVFragmentIndex* index = mov->fragment_index_data[i];
  5219. av_freep(&index->items);
  5220. av_freep(&mov->fragment_index_data[i]);
  5221. }
  5222. av_freep(&mov->fragment_index_data);
  5223. av_freep(&mov->aes_decrypt);
  5224. av_freep(&mov->chapter_tracks);
  5225. return 0;
  5226. }
  5227. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  5228. {
  5229. int i;
  5230. for (i = 0; i < s->nb_streams; i++) {
  5231. AVStream *st = s->streams[i];
  5232. MOVStreamContext *sc = st->priv_data;
  5233. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  5234. sc->timecode_track == tmcd_id)
  5235. return 1;
  5236. }
  5237. return 0;
  5238. }
  5239. /* look for a tmcd track not referenced by any video track, and export it globally */
  5240. static void export_orphan_timecode(AVFormatContext *s)
  5241. {
  5242. int i;
  5243. for (i = 0; i < s->nb_streams; i++) {
  5244. AVStream *st = s->streams[i];
  5245. if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
  5246. !tmcd_is_referenced(s, i + 1)) {
  5247. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  5248. if (tcr) {
  5249. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  5250. break;
  5251. }
  5252. }
  5253. }
  5254. }
  5255. static int read_tfra(MOVContext *mov, AVIOContext *f)
  5256. {
  5257. MOVFragmentIndex* index = NULL;
  5258. int version, fieldlength, i, j;
  5259. int64_t pos = avio_tell(f);
  5260. uint32_t size = avio_rb32(f);
  5261. void *tmp;
  5262. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  5263. return 1;
  5264. }
  5265. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  5266. index = av_mallocz(sizeof(MOVFragmentIndex));
  5267. if (!index) {
  5268. return AVERROR(ENOMEM);
  5269. }
  5270. tmp = av_realloc_array(mov->fragment_index_data,
  5271. mov->fragment_index_count + 1,
  5272. sizeof(MOVFragmentIndex*));
  5273. if (!tmp) {
  5274. av_freep(&index);
  5275. return AVERROR(ENOMEM);
  5276. }
  5277. mov->fragment_index_data = tmp;
  5278. mov->fragment_index_data[mov->fragment_index_count++] = index;
  5279. version = avio_r8(f);
  5280. avio_rb24(f);
  5281. index->track_id = avio_rb32(f);
  5282. fieldlength = avio_rb32(f);
  5283. index->item_count = avio_rb32(f);
  5284. index->items = av_mallocz_array(
  5285. index->item_count, sizeof(MOVFragmentIndexItem));
  5286. if (!index->items) {
  5287. index->item_count = 0;
  5288. return AVERROR(ENOMEM);
  5289. }
  5290. for (i = 0; i < index->item_count; i++) {
  5291. int64_t time, offset;
  5292. if (avio_feof(f)) {
  5293. index->item_count = 0;
  5294. av_freep(&index->items);
  5295. return AVERROR_INVALIDDATA;
  5296. }
  5297. if (version == 1) {
  5298. time = avio_rb64(f);
  5299. offset = avio_rb64(f);
  5300. } else {
  5301. time = avio_rb32(f);
  5302. offset = avio_rb32(f);
  5303. }
  5304. index->items[i].time = time;
  5305. index->items[i].moof_offset = offset;
  5306. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  5307. avio_r8(f);
  5308. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  5309. avio_r8(f);
  5310. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  5311. avio_r8(f);
  5312. }
  5313. avio_seek(f, pos + size, SEEK_SET);
  5314. return 0;
  5315. }
  5316. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  5317. {
  5318. int64_t stream_size = avio_size(f);
  5319. int64_t original_pos = avio_tell(f);
  5320. int64_t seek_ret;
  5321. int32_t mfra_size;
  5322. int ret = -1;
  5323. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  5324. ret = seek_ret;
  5325. goto fail;
  5326. }
  5327. mfra_size = avio_rb32(f);
  5328. if (mfra_size < 0 || mfra_size > stream_size) {
  5329. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  5330. goto fail;
  5331. }
  5332. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  5333. ret = seek_ret;
  5334. goto fail;
  5335. }
  5336. if (avio_rb32(f) != mfra_size) {
  5337. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  5338. goto fail;
  5339. }
  5340. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  5341. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  5342. goto fail;
  5343. }
  5344. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  5345. do {
  5346. ret = read_tfra(c, f);
  5347. if (ret < 0)
  5348. goto fail;
  5349. } while (!ret);
  5350. ret = 0;
  5351. fail:
  5352. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  5353. if (seek_ret < 0) {
  5354. av_log(c->fc, AV_LOG_ERROR,
  5355. "failed to seek back after looking for mfra\n");
  5356. ret = seek_ret;
  5357. }
  5358. return ret;
  5359. }
  5360. static int mov_read_header(AVFormatContext *s)
  5361. {
  5362. MOVContext *mov = s->priv_data;
  5363. AVIOContext *pb = s->pb;
  5364. int j, err;
  5365. MOVAtom atom = { AV_RL32("root") };
  5366. int i;
  5367. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  5368. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  5369. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  5370. return AVERROR(EINVAL);
  5371. }
  5372. mov->fc = s;
  5373. mov->trak_index = -1;
  5374. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  5375. if (pb->seekable & AVIO_SEEKABLE_NORMAL)
  5376. atom.size = avio_size(pb);
  5377. else
  5378. atom.size = INT64_MAX;
  5379. /* check MOV header */
  5380. do {
  5381. if (mov->moov_retry)
  5382. avio_seek(pb, 0, SEEK_SET);
  5383. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  5384. av_log(s, AV_LOG_ERROR, "error reading header\n");
  5385. mov_read_close(s);
  5386. return err;
  5387. }
  5388. } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++);
  5389. if (!mov->found_moov) {
  5390. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  5391. mov_read_close(s);
  5392. return AVERROR_INVALIDDATA;
  5393. }
  5394. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  5395. if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
  5396. if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters)
  5397. mov_read_chapters(s);
  5398. for (i = 0; i < s->nb_streams; i++)
  5399. if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) {
  5400. mov_read_timecode_track(s, s->streams[i]);
  5401. } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) {
  5402. mov_read_rtmd_track(s, s->streams[i]);
  5403. }
  5404. }
  5405. /* copy timecode metadata from tmcd tracks to the related video streams */
  5406. for (i = 0; i < s->nb_streams; i++) {
  5407. AVStream *st = s->streams[i];
  5408. MOVStreamContext *sc = st->priv_data;
  5409. if (sc->timecode_track > 0) {
  5410. AVDictionaryEntry *tcr;
  5411. int tmcd_st_id = -1;
  5412. for (j = 0; j < s->nb_streams; j++)
  5413. if (s->streams[j]->id == sc->timecode_track)
  5414. tmcd_st_id = j;
  5415. if (tmcd_st_id < 0 || tmcd_st_id == i)
  5416. continue;
  5417. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  5418. if (tcr)
  5419. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  5420. }
  5421. }
  5422. export_orphan_timecode(s);
  5423. for (i = 0; i < s->nb_streams; i++) {
  5424. AVStream *st = s->streams[i];
  5425. MOVStreamContext *sc = st->priv_data;
  5426. fix_timescale(mov, sc);
  5427. if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  5428. st->skip_samples = sc->start_pad;
  5429. }
  5430. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  5431. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  5432. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  5433. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  5434. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  5435. st->codecpar->width = sc->width;
  5436. st->codecpar->height = sc->height;
  5437. }
  5438. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  5439. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  5440. return err;
  5441. }
  5442. }
  5443. if (mov->handbrake_version &&
  5444. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  5445. st->codecpar->codec_id == AV_CODEC_ID_MP3
  5446. ) {
  5447. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  5448. st->need_parsing = AVSTREAM_PARSE_FULL;
  5449. }
  5450. }
  5451. if (mov->trex_data) {
  5452. for (i = 0; i < s->nb_streams; i++) {
  5453. AVStream *st = s->streams[i];
  5454. MOVStreamContext *sc = st->priv_data;
  5455. if (st->duration > 0) {
  5456. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  5457. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  5458. sc->data_size, sc->time_scale);
  5459. mov_read_close(s);
  5460. return AVERROR_INVALIDDATA;
  5461. }
  5462. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  5463. }
  5464. }
  5465. }
  5466. if (mov->use_mfra_for > 0) {
  5467. for (i = 0; i < s->nb_streams; i++) {
  5468. AVStream *st = s->streams[i];
  5469. MOVStreamContext *sc = st->priv_data;
  5470. if (sc->duration_for_fps > 0) {
  5471. if (sc->data_size > INT64_MAX / sc->time_scale / 8) {
  5472. av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n",
  5473. sc->data_size, sc->time_scale);
  5474. mov_read_close(s);
  5475. return AVERROR_INVALIDDATA;
  5476. }
  5477. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
  5478. sc->duration_for_fps;
  5479. }
  5480. }
  5481. }
  5482. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  5483. if (mov->bitrates[i]) {
  5484. s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
  5485. }
  5486. }
  5487. ff_rfps_calculate(s);
  5488. for (i = 0; i < s->nb_streams; i++) {
  5489. AVStream *st = s->streams[i];
  5490. MOVStreamContext *sc = st->priv_data;
  5491. switch (st->codecpar->codec_type) {
  5492. case AVMEDIA_TYPE_AUDIO:
  5493. err = ff_replaygain_export(st, s->metadata);
  5494. if (err < 0) {
  5495. mov_read_close(s);
  5496. return err;
  5497. }
  5498. break;
  5499. case AVMEDIA_TYPE_VIDEO:
  5500. if (sc->display_matrix) {
  5501. err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix,
  5502. sizeof(int32_t) * 9);
  5503. if (err < 0)
  5504. return err;
  5505. sc->display_matrix = NULL;
  5506. }
  5507. if (sc->stereo3d) {
  5508. err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
  5509. (uint8_t *)sc->stereo3d,
  5510. sizeof(*sc->stereo3d));
  5511. if (err < 0)
  5512. return err;
  5513. sc->stereo3d = NULL;
  5514. }
  5515. if (sc->spherical) {
  5516. err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
  5517. (uint8_t *)sc->spherical,
  5518. sc->spherical_size);
  5519. if (err < 0)
  5520. return err;
  5521. sc->spherical = NULL;
  5522. }
  5523. if (sc->mastering) {
  5524. err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  5525. (uint8_t *)sc->mastering,
  5526. sizeof(*sc->mastering));
  5527. if (err < 0)
  5528. return err;
  5529. sc->mastering = NULL;
  5530. }
  5531. if (sc->coll) {
  5532. err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
  5533. (uint8_t *)sc->coll,
  5534. sc->coll_size);
  5535. if (err < 0)
  5536. return err;
  5537. sc->coll = NULL;
  5538. }
  5539. break;
  5540. }
  5541. }
  5542. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  5543. for (i = 0; i < mov->fragment_index_count; i++) {
  5544. MOVFragmentIndex *idx = mov->fragment_index_data[i];
  5545. for (j = 0; j < idx->item_count; j++)
  5546. if (idx->items[j].moof_offset <= mov->fragment.moof_offset)
  5547. idx->items[j].headers_read = 1;
  5548. }
  5549. return 0;
  5550. }
  5551. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  5552. {
  5553. AVIndexEntry *sample = NULL;
  5554. int64_t best_dts = INT64_MAX;
  5555. int i;
  5556. for (i = 0; i < s->nb_streams; i++) {
  5557. AVStream *avst = s->streams[i];
  5558. MOVStreamContext *msc = avst->priv_data;
  5559. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  5560. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  5561. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  5562. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  5563. if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
  5564. ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  5565. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  5566. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  5567. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  5568. sample = current_sample;
  5569. best_dts = dts;
  5570. *st = avst;
  5571. }
  5572. }
  5573. }
  5574. return sample;
  5575. }
  5576. static int should_retry(AVIOContext *pb, int error_code) {
  5577. if (error_code == AVERROR_EOF || avio_feof(pb))
  5578. return 0;
  5579. return 1;
  5580. }
  5581. static int mov_switch_root(AVFormatContext *s, int64_t target)
  5582. {
  5583. MOVContext *mov = s->priv_data;
  5584. int i, j;
  5585. int already_read = 0;
  5586. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  5587. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  5588. return AVERROR_INVALIDDATA;
  5589. }
  5590. mov->next_root_atom = 0;
  5591. for (i = 0; i < mov->fragment_index_count; i++) {
  5592. MOVFragmentIndex *index = mov->fragment_index_data[i];
  5593. int found = 0;
  5594. for (j = 0; j < index->item_count; j++) {
  5595. MOVFragmentIndexItem *item = &index->items[j];
  5596. if (found) {
  5597. mov->next_root_atom = item->moof_offset;
  5598. break; // Advance to next index in outer loop
  5599. } else if (item->moof_offset == target) {
  5600. index->current_item = FFMIN(j, index->current_item);
  5601. if (item->headers_read)
  5602. already_read = 1;
  5603. item->headers_read = 1;
  5604. found = 1;
  5605. }
  5606. }
  5607. if (!found)
  5608. index->current_item = 0;
  5609. }
  5610. if (already_read)
  5611. return 0;
  5612. mov->found_mdat = 0;
  5613. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  5614. avio_feof(s->pb))
  5615. return AVERROR_EOF;
  5616. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  5617. return 1;
  5618. }
  5619. static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
  5620. {
  5621. uint8_t *side, *extradata;
  5622. int extradata_size;
  5623. /* Save the current index. */
  5624. sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
  5625. /* Notify the decoder that extradata changed. */
  5626. extradata_size = sc->extradata_size[sc->last_stsd_index];
  5627. extradata = sc->extradata[sc->last_stsd_index];
  5628. if (extradata_size > 0 && extradata) {
  5629. side = av_packet_new_side_data(pkt,
  5630. AV_PKT_DATA_NEW_EXTRADATA,
  5631. extradata_size);
  5632. if (!side)
  5633. return AVERROR(ENOMEM);
  5634. memcpy(side, extradata, extradata_size);
  5635. }
  5636. return 0;
  5637. }
  5638. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  5639. {
  5640. MOVContext *mov = s->priv_data;
  5641. MOVStreamContext *sc;
  5642. AVIndexEntry *sample;
  5643. AVStream *st = NULL;
  5644. int64_t current_index;
  5645. int ret;
  5646. mov->fc = s;
  5647. retry:
  5648. sample = mov_find_next_sample(s, &st);
  5649. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  5650. if (!mov->next_root_atom)
  5651. return AVERROR_EOF;
  5652. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  5653. return ret;
  5654. goto retry;
  5655. }
  5656. sc = st->priv_data;
  5657. /* must be done just before reading, to avoid infinite loop on sample */
  5658. current_index = sc->current_index;
  5659. mov_current_sample_inc(sc);
  5660. if (mov->next_root_atom) {
  5661. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  5662. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  5663. }
  5664. if (st->discard != AVDISCARD_ALL) {
  5665. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  5666. if (ret64 != sample->pos) {
  5667. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  5668. sc->ffindex, sample->pos);
  5669. if (should_retry(sc->pb, ret64)) {
  5670. mov_current_sample_dec(sc);
  5671. }
  5672. return AVERROR_INVALIDDATA;
  5673. }
  5674. if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) {
  5675. av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex);
  5676. goto retry;
  5677. }
  5678. ret = av_get_packet(sc->pb, pkt, sample->size);
  5679. if (ret < 0) {
  5680. if (should_retry(sc->pb, ret)) {
  5681. mov_current_sample_dec(sc);
  5682. }
  5683. return ret;
  5684. }
  5685. if (sc->has_palette) {
  5686. uint8_t *pal;
  5687. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  5688. if (!pal) {
  5689. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  5690. } else {
  5691. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  5692. sc->has_palette = 0;
  5693. }
  5694. }
  5695. #if CONFIG_DV_DEMUXER
  5696. if (mov->dv_demux && sc->dv_audio_container) {
  5697. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  5698. av_freep(&pkt->data);
  5699. pkt->size = 0;
  5700. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  5701. if (ret < 0)
  5702. return ret;
  5703. }
  5704. #endif
  5705. if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
  5706. if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
  5707. st->need_parsing = AVSTREAM_PARSE_FULL;
  5708. }
  5709. }
  5710. pkt->stream_index = sc->ffindex;
  5711. pkt->dts = sample->timestamp;
  5712. if (sample->flags & AVINDEX_DISCARD_FRAME) {
  5713. pkt->flags |= AV_PKT_FLAG_DISCARD;
  5714. }
  5715. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  5716. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  5717. /* update ctts context */
  5718. sc->ctts_sample++;
  5719. if (sc->ctts_index < sc->ctts_count &&
  5720. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  5721. sc->ctts_index++;
  5722. sc->ctts_sample = 0;
  5723. }
  5724. } else {
  5725. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  5726. st->index_entries[sc->current_sample].timestamp : st->duration;
  5727. pkt->duration = next_dts - pkt->dts;
  5728. pkt->pts = pkt->dts;
  5729. }
  5730. if (st->discard == AVDISCARD_ALL)
  5731. goto retry;
  5732. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  5733. pkt->pos = sample->pos;
  5734. /* Multiple stsd handling. */
  5735. if (sc->stsc_data) {
  5736. /* Keep track of the stsc index for the given sample, then check
  5737. * if the stsd index is different from the last used one. */
  5738. sc->stsc_sample++;
  5739. if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
  5740. mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
  5741. sc->stsc_index++;
  5742. sc->stsc_sample = 0;
  5743. /* Do not check indexes after a switch. */
  5744. } else if (sc->stsc_data[sc->stsc_index].id > 0 &&
  5745. sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count &&
  5746. sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
  5747. ret = mov_change_extradata(sc, pkt);
  5748. if (ret < 0)
  5749. return ret;
  5750. }
  5751. }
  5752. if (mov->aax_mode)
  5753. aax_filter(pkt->data, pkt->size, mov);
  5754. if (sc->cenc.aes_ctr) {
  5755. ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size);
  5756. if (ret) {
  5757. return ret;
  5758. }
  5759. }
  5760. return 0;
  5761. }
  5762. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  5763. {
  5764. MOVContext *mov = s->priv_data;
  5765. MOVStreamContext *sc = st->priv_data;
  5766. int i, j;
  5767. if (!mov->fragment_index_complete)
  5768. return 0;
  5769. for (i = 0; i < mov->fragment_index_count; i++) {
  5770. if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) {
  5771. MOVFragmentIndex *index = mov->fragment_index_data[i];
  5772. for (j = index->item_count - 1; j >= 0; j--) {
  5773. if (index->items[j].time <= timestamp) {
  5774. if (index->items[j].headers_read)
  5775. return 0;
  5776. return mov_switch_root(s, index->items[j].moof_offset);
  5777. }
  5778. }
  5779. }
  5780. }
  5781. return 0;
  5782. }
  5783. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  5784. {
  5785. MOVStreamContext *sc = st->priv_data;
  5786. int sample, time_sample;
  5787. unsigned int i;
  5788. int ret = mov_seek_fragment(s, st, timestamp);
  5789. if (ret < 0)
  5790. return ret;
  5791. sample = av_index_search_timestamp(st, timestamp, flags);
  5792. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  5793. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  5794. sample = 0;
  5795. if (sample < 0) /* not sure what to do */
  5796. return AVERROR_INVALIDDATA;
  5797. mov_current_sample_set(sc, sample);
  5798. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  5799. /* adjust ctts index */
  5800. if (sc->ctts_data) {
  5801. time_sample = 0;
  5802. for (i = 0; i < sc->ctts_count; i++) {
  5803. int next = time_sample + sc->ctts_data[i].count;
  5804. if (next > sc->current_sample) {
  5805. sc->ctts_index = i;
  5806. sc->ctts_sample = sc->current_sample - time_sample;
  5807. break;
  5808. }
  5809. time_sample = next;
  5810. }
  5811. }
  5812. /* adjust stsd index */
  5813. time_sample = 0;
  5814. for (i = 0; i < sc->stsc_count; i++) {
  5815. int next = time_sample + mov_get_stsc_samples(sc, i);
  5816. if (next > sc->current_sample) {
  5817. sc->stsc_index = i;
  5818. sc->stsc_sample = sc->current_sample - time_sample;
  5819. break;
  5820. }
  5821. time_sample = next;
  5822. }
  5823. return sample;
  5824. }
  5825. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  5826. {
  5827. MOVContext *mc = s->priv_data;
  5828. AVStream *st;
  5829. int sample;
  5830. int i;
  5831. if (stream_index >= s->nb_streams)
  5832. return AVERROR_INVALIDDATA;
  5833. st = s->streams[stream_index];
  5834. sample = mov_seek_stream(s, st, sample_time, flags);
  5835. if (sample < 0)
  5836. return sample;
  5837. if (mc->seek_individually) {
  5838. /* adjust seek timestamp to found sample timestamp */
  5839. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  5840. for (i = 0; i < s->nb_streams; i++) {
  5841. int64_t timestamp;
  5842. MOVStreamContext *sc = s->streams[i]->priv_data;
  5843. st = s->streams[i];
  5844. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  5845. if (stream_index == i)
  5846. continue;
  5847. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  5848. mov_seek_stream(s, st, timestamp, flags);
  5849. }
  5850. } else {
  5851. for (i = 0; i < s->nb_streams; i++) {
  5852. MOVStreamContext *sc;
  5853. st = s->streams[i];
  5854. sc = st->priv_data;
  5855. mov_current_sample_set(sc, 0);
  5856. }
  5857. while (1) {
  5858. MOVStreamContext *sc;
  5859. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  5860. if (!entry)
  5861. return AVERROR_INVALIDDATA;
  5862. sc = st->priv_data;
  5863. if (sc->ffindex == stream_index && sc->current_sample == sample)
  5864. break;
  5865. mov_current_sample_inc(sc);
  5866. }
  5867. }
  5868. return 0;
  5869. }
  5870. #define OFFSET(x) offsetof(MOVContext, x)
  5871. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  5872. static const AVOption mov_options[] = {
  5873. {"use_absolute_path",
  5874. "allow using absolute path when opening alias, this is a possible security issue",
  5875. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5876. 0, 1, FLAGS},
  5877. {"seek_streams_individually",
  5878. "Seek each stream individually to the to the closest point",
  5879. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  5880. 0, 1, FLAGS},
  5881. {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5882. 0, 1, FLAGS},
  5883. {"advanced_editlist",
  5884. "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.",
  5885. OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1},
  5886. 0, 1, FLAGS},
  5887. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  5888. 0, 1, FLAGS},
  5889. {"use_mfra_for",
  5890. "use mfra for fragment timestamps",
  5891. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  5892. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  5893. "use_mfra_for"},
  5894. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  5895. FLAGS, "use_mfra_for" },
  5896. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  5897. FLAGS, "use_mfra_for" },
  5898. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  5899. FLAGS, "use_mfra_for" },
  5900. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  5901. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5902. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  5903. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  5904. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  5905. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5906. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  5907. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  5908. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  5909. .flags = AV_OPT_FLAG_DECODING_PARAM },
  5910. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  5911. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  5912. {.i64 = 0}, 0, 1, FLAGS },
  5913. { NULL },
  5914. };
  5915. static const AVClass mov_class = {
  5916. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  5917. .item_name = av_default_item_name,
  5918. .option = mov_options,
  5919. .version = LIBAVUTIL_VERSION_INT,
  5920. };
  5921. AVInputFormat ff_mov_demuxer = {
  5922. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  5923. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  5924. .priv_class = &mov_class,
  5925. .priv_data_size = sizeof(MOVContext),
  5926. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  5927. .read_probe = mov_probe,
  5928. .read_header = mov_read_header,
  5929. .read_packet = mov_read_packet,
  5930. .read_close = mov_read_close,
  5931. .read_seek = mov_read_seek,
  5932. .flags = AVFMT_NO_BYTE_SEEK,
  5933. };