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.

5586 lines
187KB

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