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.

6619 lines
225KB

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