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.

6669 lines
226KB

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