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.

5449 lines
182KB

  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. /* 14496-12 references JPEG XR specs (rather than the more complete
  1159. * 23001-8) so some adjusting is required */
  1160. if (color_primaries >= AVCOL_PRI_FILM)
  1161. color_primaries = AVCOL_PRI_UNSPECIFIED;
  1162. if ((color_trc >= AVCOL_TRC_LINEAR &&
  1163. color_trc <= AVCOL_TRC_LOG_SQRT) ||
  1164. color_trc >= AVCOL_TRC_BT2020_10)
  1165. color_trc = AVCOL_TRC_UNSPECIFIED;
  1166. if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  1167. color_matrix = AVCOL_SPC_UNSPECIFIED;
  1168. st->codecpar->color_primaries = color_primaries;
  1169. st->codecpar->color_trc = color_trc;
  1170. st->codecpar->color_space = color_matrix;
  1171. } else if (!strncmp(color_parameter_type, "nclc", 4)) {
  1172. /* color primaries, Table 4-4 */
  1173. switch (color_primaries) {
  1174. case 1: st->codecpar->color_primaries = AVCOL_PRI_BT709; break;
  1175. case 5: st->codecpar->color_primaries = AVCOL_PRI_SMPTE170M; break;
  1176. case 6: st->codecpar->color_primaries = AVCOL_PRI_SMPTE240M; break;
  1177. }
  1178. /* color transfer, Table 4-5 */
  1179. switch (color_trc) {
  1180. case 1: st->codecpar->color_trc = AVCOL_TRC_BT709; break;
  1181. case 7: st->codecpar->color_trc = AVCOL_TRC_SMPTE240M; break;
  1182. }
  1183. /* color matrix, Table 4-6 */
  1184. switch (color_matrix) {
  1185. case 1: st->codecpar->color_space = AVCOL_SPC_BT709; break;
  1186. case 6: st->codecpar->color_space = AVCOL_SPC_BT470BG; break;
  1187. case 7: st->codecpar->color_space = AVCOL_SPC_SMPTE240M; break;
  1188. }
  1189. }
  1190. av_log(c->fc, AV_LOG_TRACE, "\n");
  1191. return 0;
  1192. }
  1193. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1194. {
  1195. AVStream *st;
  1196. unsigned mov_field_order;
  1197. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  1198. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1199. return 0;
  1200. st = c->fc->streams[c->fc->nb_streams-1];
  1201. if (atom.size < 2)
  1202. return AVERROR_INVALIDDATA;
  1203. mov_field_order = avio_rb16(pb);
  1204. if ((mov_field_order & 0xFF00) == 0x0100)
  1205. decoded_field_order = AV_FIELD_PROGRESSIVE;
  1206. else if ((mov_field_order & 0xFF00) == 0x0200) {
  1207. switch (mov_field_order & 0xFF) {
  1208. case 0x01: decoded_field_order = AV_FIELD_TT;
  1209. break;
  1210. case 0x06: decoded_field_order = AV_FIELD_BB;
  1211. break;
  1212. case 0x09: decoded_field_order = AV_FIELD_TB;
  1213. break;
  1214. case 0x0E: decoded_field_order = AV_FIELD_BT;
  1215. break;
  1216. }
  1217. }
  1218. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  1219. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  1220. }
  1221. st->codecpar->field_order = decoded_field_order;
  1222. return 0;
  1223. }
  1224. static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom)
  1225. {
  1226. int err = 0;
  1227. uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE;
  1228. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  1229. return AVERROR_INVALIDDATA;
  1230. if ((err = av_reallocp(&par->extradata, size)) < 0) {
  1231. par->extradata_size = 0;
  1232. return err;
  1233. }
  1234. par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE;
  1235. return 0;
  1236. }
  1237. /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */
  1238. static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1239. AVCodecParameters *par, uint8_t *buf)
  1240. {
  1241. int64_t result = atom.size;
  1242. int err;
  1243. AV_WB32(buf , atom.size + 8);
  1244. AV_WL32(buf + 4, atom.type);
  1245. err = ffio_read_size(pb, buf + 8, atom.size);
  1246. if (err < 0) {
  1247. par->extradata_size -= atom.size;
  1248. return err;
  1249. } else if (err < atom.size) {
  1250. av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n");
  1251. par->extradata_size -= atom.size - err;
  1252. result = err;
  1253. }
  1254. memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  1255. return result;
  1256. }
  1257. /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */
  1258. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom,
  1259. enum AVCodecID codec_id)
  1260. {
  1261. AVStream *st;
  1262. uint64_t original_size;
  1263. int err;
  1264. if (c->fc->nb_streams < 1) // will happen with jp2 files
  1265. return 0;
  1266. st = c->fc->streams[c->fc->nb_streams-1];
  1267. if (st->codecpar->codec_id != codec_id)
  1268. return 0; /* unexpected codec_id - don't mess with extradata */
  1269. original_size = st->codecpar->extradata_size;
  1270. err = mov_realloc_extradata(st->codecpar, atom);
  1271. if (err)
  1272. return err;
  1273. err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size);
  1274. if (err < 0)
  1275. return err;
  1276. return 0; // Note: this is the original behavior to ignore truncation.
  1277. }
  1278. /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */
  1279. static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1280. {
  1281. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC);
  1282. }
  1283. static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1284. {
  1285. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS);
  1286. }
  1287. static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1288. {
  1289. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000);
  1290. }
  1291. static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1292. {
  1293. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K);
  1294. }
  1295. static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1296. {
  1297. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI);
  1298. if(ret == 0)
  1299. ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD);
  1300. return ret;
  1301. }
  1302. static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1303. {
  1304. int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216);
  1305. if (!ret && c->fc->nb_streams >= 1) {
  1306. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1307. if (par->extradata_size >= 40) {
  1308. par->height = AV_RB16(&par->extradata[36]);
  1309. par->width = AV_RB16(&par->extradata[38]);
  1310. }
  1311. }
  1312. return ret;
  1313. }
  1314. static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1315. {
  1316. if (c->fc->nb_streams >= 1) {
  1317. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1318. if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') &&
  1319. par->codec_id == AV_CODEC_ID_H264 &&
  1320. atom.size > 11) {
  1321. int cid;
  1322. avio_skip(pb, 10);
  1323. cid = avio_rb16(pb);
  1324. /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */
  1325. if (cid == 0xd4d || cid == 0xd4e)
  1326. par->width = 1440;
  1327. return 0;
  1328. } else if (par->codec_tag == MKTAG('A', 'V', 'd', '1') &&
  1329. atom.size >= 24) {
  1330. int num, den;
  1331. avio_skip(pb, 12);
  1332. num = avio_rb32(pb);
  1333. den = avio_rb32(pb);
  1334. if (num <= 0 || den <= 0)
  1335. return 0;
  1336. switch (avio_rb32(pb)) {
  1337. case 2:
  1338. if (den >= INT_MAX / 2)
  1339. return 0;
  1340. den *= 2;
  1341. case 1:
  1342. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num;
  1343. c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den;
  1344. default:
  1345. return 0;
  1346. }
  1347. }
  1348. }
  1349. return mov_read_avid(c, pb, atom);
  1350. }
  1351. static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1352. {
  1353. int ret = 0;
  1354. int length = 0;
  1355. uint64_t original_size;
  1356. if (c->fc->nb_streams >= 1) {
  1357. AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar;
  1358. if (par->codec_id == AV_CODEC_ID_H264)
  1359. return 0;
  1360. if (atom.size == 16) {
  1361. original_size = par->extradata_size;
  1362. ret = mov_realloc_extradata(par, atom);
  1363. if (!ret) {
  1364. length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size);
  1365. if (length == atom.size) {
  1366. const uint8_t range_value = par->extradata[original_size + 19];
  1367. switch (range_value) {
  1368. case 1:
  1369. par->color_range = AVCOL_RANGE_MPEG;
  1370. break;
  1371. case 2:
  1372. par->color_range = AVCOL_RANGE_JPEG;
  1373. break;
  1374. default:
  1375. av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value);
  1376. break;
  1377. }
  1378. ff_dlog(c, "color_range: %d\n", par->color_range);
  1379. } else {
  1380. /* For some reason the whole atom was not added to the extradata */
  1381. av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n");
  1382. }
  1383. } else {
  1384. av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n");
  1385. }
  1386. } else {
  1387. av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size);
  1388. }
  1389. }
  1390. return ret;
  1391. }
  1392. static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1393. {
  1394. return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3);
  1395. }
  1396. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1397. {
  1398. AVStream *st;
  1399. int ret;
  1400. if (c->fc->nb_streams < 1)
  1401. return 0;
  1402. st = c->fc->streams[c->fc->nb_streams-1];
  1403. if ((uint64_t)atom.size > (1<<30))
  1404. return AVERROR_INVALIDDATA;
  1405. if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 ||
  1406. st->codecpar->codec_id == AV_CODEC_ID_QDMC ||
  1407. st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
  1408. // pass all frma atom to codec, needed at least for QDMC and QDM2
  1409. av_freep(&st->codecpar->extradata);
  1410. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1411. if (ret < 0)
  1412. return ret;
  1413. } else if (atom.size > 8) { /* to read frma, esds atoms */
  1414. if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) {
  1415. uint64_t buffer;
  1416. ret = ffio_ensure_seekback(pb, 8);
  1417. if (ret < 0)
  1418. return ret;
  1419. buffer = avio_rb64(pb);
  1420. atom.size -= 8;
  1421. if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a')
  1422. && buffer >> 32 <= atom.size
  1423. && buffer >> 32 >= 8) {
  1424. avio_skip(pb, -8);
  1425. atom.size += 8;
  1426. } else if (!st->codecpar->extradata_size) {
  1427. #define ALAC_EXTRADATA_SIZE 36
  1428. st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  1429. if (!st->codecpar->extradata)
  1430. return AVERROR(ENOMEM);
  1431. st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE;
  1432. AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE);
  1433. AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c'));
  1434. AV_WB64(st->codecpar->extradata + 12, buffer);
  1435. avio_read(pb, st->codecpar->extradata + 20, 16);
  1436. avio_skip(pb, atom.size - 24);
  1437. return 0;
  1438. }
  1439. }
  1440. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1441. return ret;
  1442. } else
  1443. avio_skip(pb, atom.size);
  1444. return 0;
  1445. }
  1446. /**
  1447. * This function reads atom content and puts data in extradata without tag
  1448. * nor size unlike mov_read_extradata.
  1449. */
  1450. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1451. {
  1452. AVStream *st;
  1453. int ret;
  1454. if (c->fc->nb_streams < 1)
  1455. return 0;
  1456. st = c->fc->streams[c->fc->nb_streams-1];
  1457. if ((uint64_t)atom.size > (1<<30))
  1458. return AVERROR_INVALIDDATA;
  1459. if (atom.size >= 10) {
  1460. // Broken files created by legacy versions of libavformat will
  1461. // wrap a whole fiel atom inside of a glbl atom.
  1462. unsigned size = avio_rb32(pb);
  1463. unsigned type = avio_rl32(pb);
  1464. avio_seek(pb, -8, SEEK_CUR);
  1465. if (type == MKTAG('f','i','e','l') && size == atom.size)
  1466. return mov_read_default(c, pb, atom);
  1467. }
  1468. if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) {
  1469. av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n");
  1470. return 0;
  1471. }
  1472. av_freep(&st->codecpar->extradata);
  1473. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size);
  1474. if (ret < 0)
  1475. return ret;
  1476. return 0;
  1477. }
  1478. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1479. {
  1480. AVStream *st;
  1481. uint8_t profile_level;
  1482. int ret;
  1483. if (c->fc->nb_streams < 1)
  1484. return 0;
  1485. st = c->fc->streams[c->fc->nb_streams-1];
  1486. if (atom.size >= (1<<28) || atom.size < 7)
  1487. return AVERROR_INVALIDDATA;
  1488. profile_level = avio_r8(pb);
  1489. if ((profile_level & 0xf0) != 0xc0)
  1490. return 0;
  1491. avio_seek(pb, 6, SEEK_CUR);
  1492. av_freep(&st->codecpar->extradata);
  1493. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7);
  1494. if (ret < 0)
  1495. return ret;
  1496. return 0;
  1497. }
  1498. /**
  1499. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  1500. * but can have extradata appended at the end after the 40 bytes belonging
  1501. * to the struct.
  1502. */
  1503. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1504. {
  1505. AVStream *st;
  1506. int ret;
  1507. if (c->fc->nb_streams < 1)
  1508. return 0;
  1509. if (atom.size <= 40)
  1510. return 0;
  1511. st = c->fc->streams[c->fc->nb_streams-1];
  1512. if ((uint64_t)atom.size > (1<<30))
  1513. return AVERROR_INVALIDDATA;
  1514. avio_skip(pb, 40);
  1515. av_freep(&st->codecpar->extradata);
  1516. ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40);
  1517. if (ret < 0)
  1518. return ret;
  1519. return 0;
  1520. }
  1521. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1522. {
  1523. AVStream *st;
  1524. MOVStreamContext *sc;
  1525. unsigned int i, entries;
  1526. if (c->fc->nb_streams < 1)
  1527. return 0;
  1528. st = c->fc->streams[c->fc->nb_streams-1];
  1529. sc = st->priv_data;
  1530. avio_r8(pb); /* version */
  1531. avio_rb24(pb); /* flags */
  1532. entries = avio_rb32(pb);
  1533. if (!entries)
  1534. return 0;
  1535. if (sc->chunk_offsets)
  1536. av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n");
  1537. av_free(sc->chunk_offsets);
  1538. sc->chunk_count = 0;
  1539. sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
  1540. if (!sc->chunk_offsets)
  1541. return AVERROR(ENOMEM);
  1542. sc->chunk_count = entries;
  1543. if (atom.type == MKTAG('s','t','c','o'))
  1544. for (i = 0; i < entries && !pb->eof_reached; i++)
  1545. sc->chunk_offsets[i] = avio_rb32(pb);
  1546. else if (atom.type == MKTAG('c','o','6','4'))
  1547. for (i = 0; i < entries && !pb->eof_reached; i++)
  1548. sc->chunk_offsets[i] = avio_rb64(pb);
  1549. else
  1550. return AVERROR_INVALIDDATA;
  1551. sc->chunk_count = i;
  1552. if (pb->eof_reached)
  1553. return AVERROR_EOF;
  1554. return 0;
  1555. }
  1556. /**
  1557. * Compute codec id for 'lpcm' tag.
  1558. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1559. */
  1560. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1561. {
  1562. /* lpcm flags:
  1563. * 0x1 = float
  1564. * 0x2 = big-endian
  1565. * 0x4 = signed
  1566. */
  1567. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1568. }
  1569. static int mov_codec_id(AVStream *st, uint32_t format)
  1570. {
  1571. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1572. if (id <= 0 &&
  1573. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1574. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1575. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1576. if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1577. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1578. } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
  1579. /* skip old ASF MPEG-4 tag */
  1580. format && format != MKTAG('m','p','4','s')) {
  1581. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1582. if (id <= 0)
  1583. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1584. if (id > 0)
  1585. st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  1586. else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA ||
  1587. (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE &&
  1588. st->codecpar->codec_id == AV_CODEC_ID_NONE)) {
  1589. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1590. if (id > 0)
  1591. st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1592. }
  1593. }
  1594. st->codecpar->codec_tag = format;
  1595. return id;
  1596. }
  1597. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1598. AVStream *st, MOVStreamContext *sc)
  1599. {
  1600. uint8_t codec_name[32];
  1601. int64_t stsd_start;
  1602. unsigned int len;
  1603. /* The first 16 bytes of the video sample description are already
  1604. * read in ff_mov_read_stsd_entries() */
  1605. stsd_start = avio_tell(pb) - 16;
  1606. avio_rb16(pb); /* version */
  1607. avio_rb16(pb); /* revision level */
  1608. avio_rb32(pb); /* vendor */
  1609. avio_rb32(pb); /* temporal quality */
  1610. avio_rb32(pb); /* spatial quality */
  1611. st->codecpar->width = avio_rb16(pb); /* width */
  1612. st->codecpar->height = avio_rb16(pb); /* height */
  1613. avio_rb32(pb); /* horiz resolution */
  1614. avio_rb32(pb); /* vert resolution */
  1615. avio_rb32(pb); /* data size, always 0 */
  1616. avio_rb16(pb); /* frames per samples */
  1617. len = avio_r8(pb); /* codec name, pascal string */
  1618. if (len > 31)
  1619. len = 31;
  1620. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1621. if (len < 31)
  1622. avio_skip(pb, 31 - len);
  1623. if (codec_name[0])
  1624. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1625. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1626. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {
  1627. st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');
  1628. st->codecpar->width &= ~1;
  1629. st->codecpar->height &= ~1;
  1630. }
  1631. /* Flash Media Server uses tag H.263 with Sorenson Spark */
  1632. if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&
  1633. !memcmp(codec_name, "Sorenson H263", 13))
  1634. st->codecpar->codec_id = AV_CODEC_ID_FLV1;
  1635. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1636. avio_seek(pb, stsd_start, SEEK_SET);
  1637. if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {
  1638. st->codecpar->bits_per_coded_sample &= 0x1F;
  1639. sc->has_palette = 1;
  1640. }
  1641. }
  1642. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1643. AVStream *st, MOVStreamContext *sc)
  1644. {
  1645. int bits_per_sample, flags;
  1646. uint16_t version = avio_rb16(pb);
  1647. AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE);
  1648. avio_rb16(pb); /* revision level */
  1649. avio_rb32(pb); /* vendor */
  1650. st->codecpar->channels = avio_rb16(pb); /* channel count */
  1651. st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1652. av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels);
  1653. sc->audio_cid = avio_rb16(pb);
  1654. avio_rb16(pb); /* packet size = 0 */
  1655. st->codecpar->sample_rate = ((avio_rb32(pb) >> 16));
  1656. // Read QT version 1 fields. In version 0 these do not exist.
  1657. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom);
  1658. if (!c->isom ||
  1659. (compatible_brands && strstr(compatible_brands->value, "qt "))) {
  1660. if (version == 1) {
  1661. sc->samples_per_frame = avio_rb32(pb);
  1662. avio_rb32(pb); /* bytes per packet */
  1663. sc->bytes_per_frame = avio_rb32(pb);
  1664. avio_rb32(pb); /* bytes per sample */
  1665. } else if (version == 2) {
  1666. avio_rb32(pb); /* sizeof struct only */
  1667. st->codecpar->sample_rate = av_int2double(avio_rb64(pb));
  1668. st->codecpar->channels = avio_rb32(pb);
  1669. avio_rb32(pb); /* always 0x7F000000 */
  1670. st->codecpar->bits_per_coded_sample = avio_rb32(pb);
  1671. flags = avio_rb32(pb); /* lpcm format specific flag */
  1672. sc->bytes_per_frame = avio_rb32(pb);
  1673. sc->samples_per_frame = avio_rb32(pb);
  1674. if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
  1675. st->codecpar->codec_id =
  1676. ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample,
  1677. flags);
  1678. }
  1679. if (version == 0 || (version == 1 && sc->audio_cid != -2)) {
  1680. /* can't correctly handle variable sized packet as audio unit */
  1681. switch (st->codecpar->codec_id) {
  1682. case AV_CODEC_ID_MP2:
  1683. case AV_CODEC_ID_MP3:
  1684. st->need_parsing = AVSTREAM_PARSE_FULL;
  1685. break;
  1686. }
  1687. }
  1688. }
  1689. if (sc->format == 0) {
  1690. if (st->codecpar->bits_per_coded_sample == 8)
  1691. st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' '));
  1692. else if (st->codecpar->bits_per_coded_sample == 16)
  1693. st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s'));
  1694. }
  1695. switch (st->codecpar->codec_id) {
  1696. case AV_CODEC_ID_PCM_S8:
  1697. case AV_CODEC_ID_PCM_U8:
  1698. if (st->codecpar->bits_per_coded_sample == 16)
  1699. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
  1700. break;
  1701. case AV_CODEC_ID_PCM_S16LE:
  1702. case AV_CODEC_ID_PCM_S16BE:
  1703. if (st->codecpar->bits_per_coded_sample == 8)
  1704. st->codecpar->codec_id = AV_CODEC_ID_PCM_S8;
  1705. else if (st->codecpar->bits_per_coded_sample == 24)
  1706. st->codecpar->codec_id =
  1707. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1708. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1709. else if (st->codecpar->bits_per_coded_sample == 32)
  1710. st->codecpar->codec_id =
  1711. st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1712. AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
  1713. break;
  1714. /* set values for old format before stsd version 1 appeared */
  1715. case AV_CODEC_ID_MACE3:
  1716. sc->samples_per_frame = 6;
  1717. sc->bytes_per_frame = 2 * st->codecpar->channels;
  1718. break;
  1719. case AV_CODEC_ID_MACE6:
  1720. sc->samples_per_frame = 6;
  1721. sc->bytes_per_frame = 1 * st->codecpar->channels;
  1722. break;
  1723. case AV_CODEC_ID_ADPCM_IMA_QT:
  1724. sc->samples_per_frame = 64;
  1725. sc->bytes_per_frame = 34 * st->codecpar->channels;
  1726. break;
  1727. case AV_CODEC_ID_GSM:
  1728. sc->samples_per_frame = 160;
  1729. sc->bytes_per_frame = 33;
  1730. break;
  1731. default:
  1732. break;
  1733. }
  1734. bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id);
  1735. if (bits_per_sample) {
  1736. st->codecpar->bits_per_coded_sample = bits_per_sample;
  1737. sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels;
  1738. }
  1739. }
  1740. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1741. AVStream *st, MOVStreamContext *sc,
  1742. int64_t size)
  1743. {
  1744. // ttxt stsd contains display flags, justification, background
  1745. // color, fonts, and default styles, so fake an atom to read it
  1746. MOVAtom fake_atom = { .size = size };
  1747. // mp4s contains a regular esds atom
  1748. if (st->codecpar->codec_tag != AV_RL32("mp4s"))
  1749. mov_read_glbl(c, pb, fake_atom);
  1750. st->codecpar->width = sc->width;
  1751. st->codecpar->height = sc->height;
  1752. }
  1753. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1754. {
  1755. uint8_t r, g, b;
  1756. int y, cb, cr;
  1757. y = (ycbcr >> 16) & 0xFF;
  1758. cr = (ycbcr >> 8) & 0xFF;
  1759. cb = ycbcr & 0xFF;
  1760. b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000);
  1761. g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000);
  1762. r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000);
  1763. return (r << 16) | (g << 8) | b;
  1764. }
  1765. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1766. {
  1767. char buf[256] = {0};
  1768. uint8_t *src = st->codecpar->extradata;
  1769. int i;
  1770. if (st->codecpar->extradata_size != 64)
  1771. return 0;
  1772. if (st->codecpar->width > 0 && st->codecpar->height > 0)
  1773. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1774. st->codecpar->width, st->codecpar->height);
  1775. av_strlcat(buf, "palette: ", sizeof(buf));
  1776. for (i = 0; i < 16; i++) {
  1777. uint32_t yuv = AV_RB32(src + i * 4);
  1778. uint32_t rgba = yuv_to_rgba(yuv);
  1779. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1780. }
  1781. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1782. return 0;
  1783. av_freep(&st->codecpar->extradata);
  1784. st->codecpar->extradata_size = 0;
  1785. st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE);
  1786. if (!st->codecpar->extradata)
  1787. return AVERROR(ENOMEM);
  1788. st->codecpar->extradata_size = strlen(buf);
  1789. memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size);
  1790. return 0;
  1791. }
  1792. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1793. AVStream *st, MOVStreamContext *sc,
  1794. int64_t size)
  1795. {
  1796. int ret;
  1797. if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
  1798. if ((int)size != size)
  1799. return AVERROR(ENOMEM);
  1800. ret = ff_get_extradata(c->fc, st->codecpar, pb, size);
  1801. if (ret < 0)
  1802. return ret;
  1803. if (size > 16) {
  1804. MOVStreamContext *tmcd_ctx = st->priv_data;
  1805. int val;
  1806. val = AV_RB32(st->codecpar->extradata + 4);
  1807. tmcd_ctx->tmcd_flags = val;
  1808. st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */
  1809. st->avg_frame_rate.den = 1;
  1810. #if FF_API_LAVF_AVCTX
  1811. FF_DISABLE_DEPRECATION_WARNINGS
  1812. st->codec->time_base = av_inv_q(st->avg_frame_rate);
  1813. FF_ENABLE_DEPRECATION_WARNINGS
  1814. #endif
  1815. /* adjust for per frame dur in counter mode */
  1816. if (tmcd_ctx->tmcd_flags & 0x0008) {
  1817. int timescale = AV_RB32(st->codecpar->extradata + 8);
  1818. int framedur = AV_RB32(st->codecpar->extradata + 12);
  1819. st->avg_frame_rate.num *= timescale;
  1820. st->avg_frame_rate.den *= framedur;
  1821. #if FF_API_LAVF_AVCTX
  1822. FF_DISABLE_DEPRECATION_WARNINGS
  1823. st->codec->time_base.den *= timescale;
  1824. st->codec->time_base.num *= framedur;
  1825. FF_ENABLE_DEPRECATION_WARNINGS
  1826. #endif
  1827. }
  1828. if (size > 30) {
  1829. uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */
  1830. uint32_t format = AV_RB32(st->codecpar->extradata + 22);
  1831. if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) {
  1832. uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */
  1833. if (str_size > 0 && size >= (int)str_size + 26) {
  1834. char *reel_name = av_malloc(str_size + 1);
  1835. if (!reel_name)
  1836. return AVERROR(ENOMEM);
  1837. memcpy(reel_name, st->codecpar->extradata + 30, str_size);
  1838. reel_name[str_size] = 0; /* Add null terminator */
  1839. /* don't add reel_name if emtpy string */
  1840. if (*reel_name == 0) {
  1841. av_free(reel_name);
  1842. } else {
  1843. av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL);
  1844. }
  1845. }
  1846. }
  1847. }
  1848. }
  1849. } else {
  1850. /* other codec type, just skip (rtp, mp4s ...) */
  1851. avio_skip(pb, size);
  1852. }
  1853. return 0;
  1854. }
  1855. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1856. AVStream *st, MOVStreamContext *sc)
  1857. {
  1858. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1859. !st->codecpar->sample_rate && sc->time_scale > 1)
  1860. st->codecpar->sample_rate = sc->time_scale;
  1861. /* special codec parameters handling */
  1862. switch (st->codecpar->codec_id) {
  1863. #if CONFIG_DV_DEMUXER
  1864. case AV_CODEC_ID_DVAUDIO:
  1865. c->dv_fctx = avformat_alloc_context();
  1866. if (!c->dv_fctx) {
  1867. av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");
  1868. return AVERROR(ENOMEM);
  1869. }
  1870. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1871. if (!c->dv_demux) {
  1872. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1873. return AVERROR(ENOMEM);
  1874. }
  1875. sc->dv_audio_container = 1;
  1876. st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
  1877. break;
  1878. #endif
  1879. /* no ifdef since parameters are always those */
  1880. case AV_CODEC_ID_QCELP:
  1881. st->codecpar->channels = 1;
  1882. // force sample rate for qcelp when not stored in mov
  1883. if (st->codecpar->codec_tag != MKTAG('Q','c','l','p'))
  1884. st->codecpar->sample_rate = 8000;
  1885. // FIXME: Why is the following needed for some files?
  1886. sc->samples_per_frame = 160;
  1887. if (!sc->bytes_per_frame)
  1888. sc->bytes_per_frame = 35;
  1889. break;
  1890. case AV_CODEC_ID_AMR_NB:
  1891. st->codecpar->channels = 1;
  1892. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1893. st->codecpar->sample_rate = 8000;
  1894. break;
  1895. case AV_CODEC_ID_AMR_WB:
  1896. st->codecpar->channels = 1;
  1897. st->codecpar->sample_rate = 16000;
  1898. break;
  1899. case AV_CODEC_ID_MP2:
  1900. case AV_CODEC_ID_MP3:
  1901. /* force type after stsd for m1a hdlr */
  1902. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  1903. break;
  1904. case AV_CODEC_ID_GSM:
  1905. case AV_CODEC_ID_ADPCM_MS:
  1906. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1907. case AV_CODEC_ID_ILBC:
  1908. case AV_CODEC_ID_MACE3:
  1909. case AV_CODEC_ID_MACE6:
  1910. case AV_CODEC_ID_QDM2:
  1911. st->codecpar->block_align = sc->bytes_per_frame;
  1912. break;
  1913. case AV_CODEC_ID_ALAC:
  1914. if (st->codecpar->extradata_size == 36) {
  1915. st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21);
  1916. st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32);
  1917. }
  1918. break;
  1919. case AV_CODEC_ID_AC3:
  1920. case AV_CODEC_ID_EAC3:
  1921. case AV_CODEC_ID_MPEG1VIDEO:
  1922. case AV_CODEC_ID_VC1:
  1923. st->need_parsing = AVSTREAM_PARSE_FULL;
  1924. break;
  1925. default:
  1926. break;
  1927. }
  1928. return 0;
  1929. }
  1930. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1931. int codec_tag, int format,
  1932. int64_t size)
  1933. {
  1934. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1935. if (codec_tag &&
  1936. (codec_tag != format &&
  1937. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1938. : codec_tag != MKTAG('j','p','e','g')))) {
  1939. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1940. * export it as a separate AVStream but this needs a few changes
  1941. * in the MOV demuxer, patch welcome. */
  1942. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1943. avio_skip(pb, size);
  1944. return 1;
  1945. }
  1946. if ( codec_tag == AV_RL32("avc1") ||
  1947. codec_tag == AV_RL32("hvc1") ||
  1948. codec_tag == AV_RL32("hev1")
  1949. )
  1950. av_log(c->fc, AV_LOG_WARNING, "Concatenated H.264 or H.265 might not play correctly.\n");
  1951. return 0;
  1952. }
  1953. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1954. {
  1955. AVStream *st;
  1956. MOVStreamContext *sc;
  1957. int pseudo_stream_id;
  1958. if (c->fc->nb_streams < 1)
  1959. return 0;
  1960. st = c->fc->streams[c->fc->nb_streams-1];
  1961. sc = st->priv_data;
  1962. for (pseudo_stream_id = 0;
  1963. pseudo_stream_id < entries && !pb->eof_reached;
  1964. pseudo_stream_id++) {
  1965. //Parsing Sample description table
  1966. enum AVCodecID id;
  1967. int ret, dref_id = 1;
  1968. MOVAtom a = { AV_RL32("stsd") };
  1969. int64_t start_pos = avio_tell(pb);
  1970. int64_t size = avio_rb32(pb); /* size */
  1971. uint32_t format = avio_rl32(pb); /* data format */
  1972. if (size >= 16) {
  1973. avio_rb32(pb); /* reserved */
  1974. avio_rb16(pb); /* reserved */
  1975. dref_id = avio_rb16(pb);
  1976. } else if (size <= 7) {
  1977. av_log(c->fc, AV_LOG_ERROR,
  1978. "invalid size %"PRId64" in stsd\n", size);
  1979. return AVERROR_INVALIDDATA;
  1980. }
  1981. if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
  1982. size - (avio_tell(pb) - start_pos)))
  1983. continue;
  1984. sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
  1985. sc->dref_id= dref_id;
  1986. sc->format = format;
  1987. id = mov_codec_id(st, format);
  1988. av_log(c->fc, AV_LOG_TRACE,
  1989. "size=%"PRId64" 4CC= %c%c%c%c/0x%08x codec_type=%d\n", size,
  1990. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1991. (format >> 24) & 0xff, format, st->codecpar->codec_type);
  1992. if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
  1993. st->codecpar->codec_id = id;
  1994. mov_parse_stsd_video(c, pb, st, sc);
  1995. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
  1996. st->codecpar->codec_id = id;
  1997. mov_parse_stsd_audio(c, pb, st, sc);
  1998. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1999. st->codecpar->codec_id = id;
  2000. mov_parse_stsd_subtitle(c, pb, st, sc,
  2001. size - (avio_tell(pb) - start_pos));
  2002. } else {
  2003. ret = mov_parse_stsd_data(c, pb, st, sc,
  2004. size - (avio_tell(pb) - start_pos));
  2005. if (ret < 0)
  2006. return ret;
  2007. }
  2008. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  2009. a.size = size - (avio_tell(pb) - start_pos);
  2010. if (a.size > 8) {
  2011. if ((ret = mov_read_default(c, pb, a)) < 0)
  2012. return ret;
  2013. } else if (a.size > 0)
  2014. avio_skip(pb, a.size);
  2015. }
  2016. if (pb->eof_reached)
  2017. return AVERROR_EOF;
  2018. return mov_finalize_stsd_codec(c, pb, st, sc);
  2019. }
  2020. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2021. {
  2022. int entries;
  2023. avio_r8(pb); /* version */
  2024. avio_rb24(pb); /* flags */
  2025. entries = avio_rb32(pb);
  2026. return ff_mov_read_stsd_entries(c, pb, entries);
  2027. }
  2028. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2029. {
  2030. AVStream *st;
  2031. MOVStreamContext *sc;
  2032. unsigned int i, entries;
  2033. if (c->fc->nb_streams < 1)
  2034. return 0;
  2035. st = c->fc->streams[c->fc->nb_streams-1];
  2036. sc = st->priv_data;
  2037. avio_r8(pb); /* version */
  2038. avio_rb24(pb); /* flags */
  2039. entries = avio_rb32(pb);
  2040. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  2041. if (!entries)
  2042. return 0;
  2043. if (sc->stsc_data)
  2044. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n");
  2045. av_free(sc->stsc_data);
  2046. sc->stsc_count = 0;
  2047. sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data));
  2048. if (!sc->stsc_data)
  2049. return AVERROR(ENOMEM);
  2050. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2051. sc->stsc_data[i].first = avio_rb32(pb);
  2052. sc->stsc_data[i].count = avio_rb32(pb);
  2053. sc->stsc_data[i].id = avio_rb32(pb);
  2054. }
  2055. sc->stsc_count = i;
  2056. if (pb->eof_reached)
  2057. return AVERROR_EOF;
  2058. return 0;
  2059. }
  2060. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2061. {
  2062. AVStream *st;
  2063. MOVStreamContext *sc;
  2064. unsigned i, entries;
  2065. if (c->fc->nb_streams < 1)
  2066. return 0;
  2067. st = c->fc->streams[c->fc->nb_streams-1];
  2068. sc = st->priv_data;
  2069. avio_rb32(pb); // version + flags
  2070. entries = avio_rb32(pb);
  2071. if (sc->stps_data)
  2072. av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n");
  2073. av_free(sc->stps_data);
  2074. sc->stps_count = 0;
  2075. sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data));
  2076. if (!sc->stps_data)
  2077. return AVERROR(ENOMEM);
  2078. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2079. sc->stps_data[i] = avio_rb32(pb);
  2080. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  2081. }
  2082. sc->stps_count = i;
  2083. if (pb->eof_reached)
  2084. return AVERROR_EOF;
  2085. return 0;
  2086. }
  2087. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2088. {
  2089. AVStream *st;
  2090. MOVStreamContext *sc;
  2091. unsigned int i, entries;
  2092. if (c->fc->nb_streams < 1)
  2093. return 0;
  2094. st = c->fc->streams[c->fc->nb_streams-1];
  2095. sc = st->priv_data;
  2096. avio_r8(pb); /* version */
  2097. avio_rb24(pb); /* flags */
  2098. entries = avio_rb32(pb);
  2099. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  2100. if (!entries)
  2101. {
  2102. sc->keyframe_absent = 1;
  2103. if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  2104. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  2105. return 0;
  2106. }
  2107. if (sc->keyframes)
  2108. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n");
  2109. if (entries >= UINT_MAX / sizeof(int))
  2110. return AVERROR_INVALIDDATA;
  2111. av_freep(&sc->keyframes);
  2112. sc->keyframe_count = 0;
  2113. sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes));
  2114. if (!sc->keyframes)
  2115. return AVERROR(ENOMEM);
  2116. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2117. sc->keyframes[i] = avio_rb32(pb);
  2118. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  2119. }
  2120. sc->keyframe_count = i;
  2121. if (pb->eof_reached)
  2122. return AVERROR_EOF;
  2123. return 0;
  2124. }
  2125. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2126. {
  2127. AVStream *st;
  2128. MOVStreamContext *sc;
  2129. unsigned int i, entries, sample_size, field_size, num_bytes;
  2130. GetBitContext gb;
  2131. unsigned char* buf;
  2132. int ret;
  2133. if (c->fc->nb_streams < 1)
  2134. return 0;
  2135. st = c->fc->streams[c->fc->nb_streams-1];
  2136. sc = st->priv_data;
  2137. avio_r8(pb); /* version */
  2138. avio_rb24(pb); /* flags */
  2139. if (atom.type == MKTAG('s','t','s','z')) {
  2140. sample_size = avio_rb32(pb);
  2141. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  2142. sc->sample_size = sample_size;
  2143. sc->stsz_sample_size = sample_size;
  2144. field_size = 32;
  2145. } else {
  2146. sample_size = 0;
  2147. avio_rb24(pb); /* reserved */
  2148. field_size = avio_r8(pb);
  2149. }
  2150. entries = avio_rb32(pb);
  2151. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  2152. sc->sample_count = entries;
  2153. if (sample_size)
  2154. return 0;
  2155. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  2156. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  2157. return AVERROR_INVALIDDATA;
  2158. }
  2159. if (!entries)
  2160. return 0;
  2161. if (entries >= (UINT_MAX - 4) / field_size)
  2162. return AVERROR_INVALIDDATA;
  2163. if (sc->sample_sizes)
  2164. av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n");
  2165. av_free(sc->sample_sizes);
  2166. sc->sample_count = 0;
  2167. sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes));
  2168. if (!sc->sample_sizes)
  2169. return AVERROR(ENOMEM);
  2170. num_bytes = (entries*field_size+4)>>3;
  2171. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  2172. if (!buf) {
  2173. av_freep(&sc->sample_sizes);
  2174. return AVERROR(ENOMEM);
  2175. }
  2176. ret = ffio_read_size(pb, buf, num_bytes);
  2177. if (ret < 0) {
  2178. av_freep(&sc->sample_sizes);
  2179. av_free(buf);
  2180. return ret;
  2181. }
  2182. init_get_bits(&gb, buf, 8*num_bytes);
  2183. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2184. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  2185. sc->data_size += sc->sample_sizes[i];
  2186. }
  2187. sc->sample_count = i;
  2188. av_free(buf);
  2189. if (pb->eof_reached)
  2190. return AVERROR_EOF;
  2191. return 0;
  2192. }
  2193. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2194. {
  2195. AVStream *st;
  2196. MOVStreamContext *sc;
  2197. unsigned int i, entries;
  2198. int64_t duration=0;
  2199. int64_t total_sample_count=0;
  2200. if (c->fc->nb_streams < 1)
  2201. return 0;
  2202. st = c->fc->streams[c->fc->nb_streams-1];
  2203. sc = st->priv_data;
  2204. avio_r8(pb); /* version */
  2205. avio_rb24(pb); /* flags */
  2206. entries = avio_rb32(pb);
  2207. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  2208. c->fc->nb_streams-1, entries);
  2209. if (sc->stts_data)
  2210. av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n");
  2211. av_free(sc->stts_data);
  2212. sc->stts_count = 0;
  2213. sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data));
  2214. if (!sc->stts_data)
  2215. return AVERROR(ENOMEM);
  2216. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2217. int sample_duration;
  2218. int sample_count;
  2219. sample_count=avio_rb32(pb);
  2220. sample_duration = avio_rb32(pb);
  2221. if (sample_count < 0) {
  2222. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  2223. return AVERROR_INVALIDDATA;
  2224. }
  2225. sc->stts_data[i].count= sample_count;
  2226. sc->stts_data[i].duration= sample_duration;
  2227. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  2228. sample_count, sample_duration);
  2229. if ( i+1 == entries
  2230. && i
  2231. && sample_count == 1
  2232. && total_sample_count > 100
  2233. && sample_duration/10 > duration / total_sample_count)
  2234. sample_duration = duration / total_sample_count;
  2235. duration+=(int64_t)sample_duration*sample_count;
  2236. total_sample_count+=sample_count;
  2237. }
  2238. sc->stts_count = i;
  2239. sc->duration_for_fps += duration;
  2240. sc->nb_frames_for_fps += total_sample_count;
  2241. if (pb->eof_reached)
  2242. return AVERROR_EOF;
  2243. st->nb_frames= total_sample_count;
  2244. if (duration)
  2245. st->duration= duration;
  2246. sc->track_end = duration;
  2247. return 0;
  2248. }
  2249. static void mov_update_dts_shift(MOVStreamContext *sc, int duration)
  2250. {
  2251. if (duration < 0) {
  2252. if (duration == INT_MIN) {
  2253. av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX);
  2254. duration++;
  2255. }
  2256. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  2257. }
  2258. }
  2259. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2260. {
  2261. AVStream *st;
  2262. MOVStreamContext *sc;
  2263. unsigned int i, entries, ctts_count = 0;
  2264. if (c->fc->nb_streams < 1)
  2265. return 0;
  2266. st = c->fc->streams[c->fc->nb_streams-1];
  2267. sc = st->priv_data;
  2268. avio_r8(pb); /* version */
  2269. avio_rb24(pb); /* flags */
  2270. entries = avio_rb32(pb);
  2271. av_log(c->fc, AV_LOG_TRACE, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  2272. if (!entries)
  2273. return 0;
  2274. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  2275. return AVERROR_INVALIDDATA;
  2276. av_freep(&sc->ctts_data);
  2277. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  2278. if (!sc->ctts_data)
  2279. return AVERROR(ENOMEM);
  2280. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2281. int count =avio_rb32(pb);
  2282. int duration =avio_rb32(pb);
  2283. if (count <= 0) {
  2284. av_log(c->fc, AV_LOG_TRACE,
  2285. "ignoring CTTS entry with count=%d duration=%d\n",
  2286. count, duration);
  2287. continue;
  2288. }
  2289. sc->ctts_data[ctts_count].count = count;
  2290. sc->ctts_data[ctts_count].duration = duration;
  2291. ctts_count++;
  2292. av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n",
  2293. count, duration);
  2294. if (FFNABS(duration) < -(1<<28) && i+2<entries) {
  2295. av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n");
  2296. av_freep(&sc->ctts_data);
  2297. sc->ctts_count = 0;
  2298. return 0;
  2299. }
  2300. if (i+2<entries)
  2301. mov_update_dts_shift(sc, duration);
  2302. }
  2303. sc->ctts_count = ctts_count;
  2304. if (pb->eof_reached)
  2305. return AVERROR_EOF;
  2306. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  2307. return 0;
  2308. }
  2309. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2310. {
  2311. AVStream *st;
  2312. MOVStreamContext *sc;
  2313. unsigned int i, entries;
  2314. uint8_t version;
  2315. uint32_t grouping_type;
  2316. if (c->fc->nb_streams < 1)
  2317. return 0;
  2318. st = c->fc->streams[c->fc->nb_streams-1];
  2319. sc = st->priv_data;
  2320. version = avio_r8(pb); /* version */
  2321. avio_rb24(pb); /* flags */
  2322. grouping_type = avio_rl32(pb);
  2323. if (grouping_type != MKTAG( 'r','a','p',' '))
  2324. return 0; /* only support 'rap ' grouping */
  2325. if (version == 1)
  2326. avio_rb32(pb); /* grouping_type_parameter */
  2327. entries = avio_rb32(pb);
  2328. if (!entries)
  2329. return 0;
  2330. if (sc->rap_group)
  2331. av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n");
  2332. av_free(sc->rap_group);
  2333. sc->rap_group_count = 0;
  2334. sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group));
  2335. if (!sc->rap_group)
  2336. return AVERROR(ENOMEM);
  2337. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2338. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  2339. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  2340. }
  2341. sc->rap_group_count = i;
  2342. return pb->eof_reached ? AVERROR_EOF : 0;
  2343. }
  2344. static void mov_build_index(MOVContext *mov, AVStream *st)
  2345. {
  2346. MOVStreamContext *sc = st->priv_data;
  2347. int64_t current_offset;
  2348. int64_t current_dts = 0;
  2349. unsigned int stts_index = 0;
  2350. unsigned int stsc_index = 0;
  2351. unsigned int stss_index = 0;
  2352. unsigned int stps_index = 0;
  2353. unsigned int i, j;
  2354. uint64_t stream_size = 0;
  2355. if (sc->elst_count) {
  2356. int i, edit_start_index = 0, unsupported = 0;
  2357. int64_t empty_duration = 0; // empty duration of the first edit list entry
  2358. int64_t start_time = 0; // start time of the media
  2359. for (i = 0; i < sc->elst_count; i++) {
  2360. const MOVElst *e = &sc->elst_data[i];
  2361. if (i == 0 && e->time == -1) {
  2362. /* if empty, the first entry is the start time of the stream
  2363. * relative to the presentation itself */
  2364. empty_duration = e->duration;
  2365. edit_start_index = 1;
  2366. } else if (i == edit_start_index && e->time >= 0) {
  2367. start_time = e->time;
  2368. } else
  2369. unsupported = 1;
  2370. }
  2371. if (unsupported)
  2372. av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2373. "a/v desync might occur, patch welcome\n");
  2374. /* adjust first dts according to edit list */
  2375. if ((empty_duration || start_time) && mov->time_scale > 0) {
  2376. if (empty_duration)
  2377. empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale);
  2378. sc->time_offset = start_time - empty_duration;
  2379. current_dts = -sc->time_offset;
  2380. if (sc->ctts_count>0 && sc->stts_count>0 &&
  2381. sc->ctts_data[0].duration / FFMAX(sc->stts_data[0].duration, 1) > 16) {
  2382. /* more than 16 frames delay, dts are likely wrong
  2383. this happens with files created by iMovie */
  2384. sc->wrong_dts = 1;
  2385. st->codecpar->video_delay = 1;
  2386. }
  2387. }
  2388. if (!unsupported && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0)
  2389. sc->start_pad = start_time;
  2390. }
  2391. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  2392. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  2393. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  2394. unsigned int current_sample = 0;
  2395. unsigned int stts_sample = 0;
  2396. unsigned int sample_size;
  2397. unsigned int distance = 0;
  2398. unsigned int rap_group_index = 0;
  2399. unsigned int rap_group_sample = 0;
  2400. int64_t last_dts = 0;
  2401. int64_t dts_correction = 0;
  2402. int rap_group_present = sc->rap_group_count && sc->rap_group;
  2403. int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0);
  2404. current_dts -= sc->dts_shift;
  2405. last_dts = current_dts;
  2406. if (!sc->sample_count || st->nb_index_entries)
  2407. return;
  2408. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2409. return;
  2410. if (av_reallocp_array(&st->index_entries,
  2411. st->nb_index_entries + sc->sample_count,
  2412. sizeof(*st->index_entries)) < 0) {
  2413. st->nb_index_entries = 0;
  2414. return;
  2415. }
  2416. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  2417. for (i = 0; i < sc->chunk_count; i++) {
  2418. int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX;
  2419. current_offset = sc->chunk_offsets[i];
  2420. while (stsc_index + 1 < sc->stsc_count &&
  2421. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2422. stsc_index++;
  2423. if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size &&
  2424. sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) {
  2425. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size);
  2426. sc->stsz_sample_size = sc->sample_size;
  2427. }
  2428. if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) {
  2429. av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size);
  2430. sc->stsz_sample_size = sc->sample_size;
  2431. }
  2432. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  2433. int keyframe = 0;
  2434. if (current_sample >= sc->sample_count) {
  2435. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  2436. return;
  2437. }
  2438. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  2439. keyframe = 1;
  2440. if (stss_index + 1 < sc->keyframe_count)
  2441. stss_index++;
  2442. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  2443. keyframe = 1;
  2444. if (stps_index + 1 < sc->stps_count)
  2445. stps_index++;
  2446. }
  2447. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2448. if (sc->rap_group[rap_group_index].index > 0)
  2449. keyframe = 1;
  2450. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2451. rap_group_sample = 0;
  2452. rap_group_index++;
  2453. }
  2454. }
  2455. if (sc->keyframe_absent
  2456. && !sc->stps_count
  2457. && !rap_group_present
  2458. && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0)))
  2459. keyframe = 1;
  2460. if (keyframe)
  2461. distance = 0;
  2462. sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample];
  2463. if (sc->pseudo_stream_id == -1 ||
  2464. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2465. AVIndexEntry *e;
  2466. if (sample_size > 0x3FFFFFFF) {
  2467. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size);
  2468. return;
  2469. }
  2470. e = &st->index_entries[st->nb_index_entries++];
  2471. e->pos = current_offset;
  2472. e->timestamp = current_dts;
  2473. e->size = sample_size;
  2474. e->min_distance = distance;
  2475. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2476. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2477. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  2478. current_offset, current_dts, sample_size, distance, keyframe);
  2479. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100)
  2480. ff_rfps_add_frame(mov->fc, st, current_dts);
  2481. }
  2482. current_offset += sample_size;
  2483. stream_size += sample_size;
  2484. /* A negative sample duration is invalid based on the spec,
  2485. * but some samples need it to correct the DTS. */
  2486. if (sc->stts_data[stts_index].duration < 0) {
  2487. av_log(mov->fc, AV_LOG_WARNING,
  2488. "Invalid SampleDelta %d in STTS, at %d st:%d\n",
  2489. sc->stts_data[stts_index].duration, stts_index,
  2490. st->index);
  2491. dts_correction += sc->stts_data[stts_index].duration - 1;
  2492. sc->stts_data[stts_index].duration = 1;
  2493. }
  2494. current_dts += sc->stts_data[stts_index].duration;
  2495. if (!dts_correction || current_dts + dts_correction > last_dts) {
  2496. current_dts += dts_correction;
  2497. dts_correction = 0;
  2498. } else {
  2499. /* Avoid creating non-monotonous DTS */
  2500. dts_correction += current_dts - last_dts - 1;
  2501. current_dts = last_dts + 1;
  2502. }
  2503. last_dts = current_dts;
  2504. distance++;
  2505. stts_sample++;
  2506. current_sample++;
  2507. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2508. stts_sample = 0;
  2509. stts_index++;
  2510. }
  2511. }
  2512. }
  2513. if (st->duration > 0)
  2514. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2515. } else {
  2516. unsigned chunk_samples, total = 0;
  2517. // compute total chunk count
  2518. for (i = 0; i < sc->stsc_count; i++) {
  2519. unsigned count, chunk_count;
  2520. chunk_samples = sc->stsc_data[i].count;
  2521. if (i != sc->stsc_count - 1 &&
  2522. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2523. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2524. return;
  2525. }
  2526. if (sc->samples_per_frame >= 160) { // gsm
  2527. count = chunk_samples / sc->samples_per_frame;
  2528. } else if (sc->samples_per_frame > 1) {
  2529. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2530. count = (chunk_samples+samples-1) / samples;
  2531. } else {
  2532. count = (chunk_samples+1023) / 1024;
  2533. }
  2534. if (i < sc->stsc_count - 1)
  2535. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2536. else
  2537. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2538. total += chunk_count * count;
  2539. }
  2540. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2541. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2542. return;
  2543. if (av_reallocp_array(&st->index_entries,
  2544. st->nb_index_entries + total,
  2545. sizeof(*st->index_entries)) < 0) {
  2546. st->nb_index_entries = 0;
  2547. return;
  2548. }
  2549. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2550. // populate index
  2551. for (i = 0; i < sc->chunk_count; i++) {
  2552. current_offset = sc->chunk_offsets[i];
  2553. if (stsc_index + 1 < sc->stsc_count &&
  2554. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2555. stsc_index++;
  2556. chunk_samples = sc->stsc_data[stsc_index].count;
  2557. while (chunk_samples > 0) {
  2558. AVIndexEntry *e;
  2559. unsigned size, samples;
  2560. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2561. avpriv_request_sample(mov->fc,
  2562. "Zero bytes per frame, but %d samples per frame",
  2563. sc->samples_per_frame);
  2564. return;
  2565. }
  2566. if (sc->samples_per_frame >= 160) { // gsm
  2567. samples = sc->samples_per_frame;
  2568. size = sc->bytes_per_frame;
  2569. } else {
  2570. if (sc->samples_per_frame > 1) {
  2571. samples = FFMIN((1024 / sc->samples_per_frame)*
  2572. sc->samples_per_frame, chunk_samples);
  2573. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2574. } else {
  2575. samples = FFMIN(1024, chunk_samples);
  2576. size = samples * sc->sample_size;
  2577. }
  2578. }
  2579. if (st->nb_index_entries >= total) {
  2580. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2581. return;
  2582. }
  2583. if (size > 0x3FFFFFFF) {
  2584. av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size);
  2585. return;
  2586. }
  2587. e = &st->index_entries[st->nb_index_entries++];
  2588. e->pos = current_offset;
  2589. e->timestamp = current_dts;
  2590. e->size = size;
  2591. e->min_distance = 0;
  2592. e->flags = AVINDEX_KEYFRAME;
  2593. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2594. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2595. size, samples);
  2596. current_offset += size;
  2597. current_dts += samples;
  2598. chunk_samples -= samples;
  2599. }
  2600. }
  2601. }
  2602. }
  2603. static int test_same_origin(const char *src, const char *ref) {
  2604. char src_proto[64];
  2605. char ref_proto[64];
  2606. char src_auth[256];
  2607. char ref_auth[256];
  2608. char src_host[256];
  2609. char ref_host[256];
  2610. int src_port=-1;
  2611. int ref_port=-1;
  2612. av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src);
  2613. av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref);
  2614. if (strlen(src) == 0) {
  2615. return -1;
  2616. } else if (strlen(src_auth) + 1 >= sizeof(src_auth) ||
  2617. strlen(ref_auth) + 1 >= sizeof(ref_auth) ||
  2618. strlen(src_host) + 1 >= sizeof(src_host) ||
  2619. strlen(ref_host) + 1 >= sizeof(ref_host)) {
  2620. return 0;
  2621. } else if (strcmp(src_proto, ref_proto) ||
  2622. strcmp(src_auth, ref_auth) ||
  2623. strcmp(src_host, ref_host) ||
  2624. src_port != ref_port) {
  2625. return 0;
  2626. } else
  2627. return 1;
  2628. }
  2629. static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
  2630. {
  2631. /* try relative path, we do not try the absolute because it can leak information about our
  2632. system to an attacker */
  2633. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2634. char filename[1025];
  2635. const char *src_path;
  2636. int i, l;
  2637. /* find a source dir */
  2638. src_path = strrchr(src, '/');
  2639. if (src_path)
  2640. src_path++;
  2641. else
  2642. src_path = src;
  2643. /* find a next level down to target */
  2644. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2645. if (ref->path[l] == '/') {
  2646. if (i == ref->nlvl_to - 1)
  2647. break;
  2648. else
  2649. i++;
  2650. }
  2651. /* compose filename if next level down to target was found */
  2652. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2653. memcpy(filename, src, src_path - src);
  2654. filename[src_path - src] = 0;
  2655. for (i = 1; i < ref->nlvl_from; i++)
  2656. av_strlcat(filename, "../", sizeof(filename));
  2657. av_strlcat(filename, ref->path + l + 1, sizeof(filename));
  2658. if (!c->use_absolute_path) {
  2659. int same_origin = test_same_origin(src, filename);
  2660. if (!same_origin) {
  2661. av_log(c->fc, AV_LOG_ERROR,
  2662. "Reference with mismatching origin, %s not tried for security reasons, "
  2663. "set demuxer option use_absolute_path to allow it anyway\n",
  2664. ref->path);
  2665. return AVERROR(ENOENT);
  2666. }
  2667. if(strstr(ref->path + l + 1, "..") ||
  2668. strstr(ref->path + l + 1, ":") ||
  2669. (ref->nlvl_from > 1 && same_origin < 0) ||
  2670. (filename[0] == '/' && src_path == src))
  2671. return AVERROR(ENOENT);
  2672. }
  2673. if (strlen(filename) + 1 == sizeof(filename))
  2674. return AVERROR(ENOENT);
  2675. if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
  2676. return 0;
  2677. }
  2678. } else if (c->use_absolute_path) {
  2679. av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
  2680. "this is a possible security issue\n");
  2681. if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
  2682. return 0;
  2683. } else {
  2684. av_log(c->fc, AV_LOG_ERROR,
  2685. "Absolute path %s not tried for security reasons, "
  2686. "set demuxer option use_absolute_path to allow absolute paths\n",
  2687. ref->path);
  2688. }
  2689. return AVERROR(ENOENT);
  2690. }
  2691. static void fix_timescale(MOVContext *c, MOVStreamContext *sc)
  2692. {
  2693. if (sc->time_scale <= 0) {
  2694. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex);
  2695. sc->time_scale = c->time_scale;
  2696. if (sc->time_scale <= 0)
  2697. sc->time_scale = 1;
  2698. }
  2699. }
  2700. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2701. {
  2702. AVStream *st;
  2703. MOVStreamContext *sc;
  2704. int ret;
  2705. st = avformat_new_stream(c->fc, NULL);
  2706. if (!st) return AVERROR(ENOMEM);
  2707. st->id = c->fc->nb_streams;
  2708. sc = av_mallocz(sizeof(MOVStreamContext));
  2709. if (!sc) return AVERROR(ENOMEM);
  2710. st->priv_data = sc;
  2711. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2712. sc->ffindex = st->index;
  2713. c->trak_index = st->index;
  2714. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2715. return ret;
  2716. c->trak_index = -1;
  2717. /* sanity checks */
  2718. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2719. (!sc->sample_size && !sc->sample_count))) {
  2720. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2721. st->index);
  2722. return 0;
  2723. }
  2724. fix_timescale(c, sc);
  2725. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2726. mov_build_index(c, st);
  2727. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2728. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2729. if (c->enable_drefs) {
  2730. if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0)
  2731. av_log(c->fc, AV_LOG_ERROR,
  2732. "stream %d, error opening alias: path='%s', dir='%s', "
  2733. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2734. st->index, dref->path, dref->dir, dref->filename,
  2735. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2736. } else {
  2737. av_log(c->fc, AV_LOG_WARNING,
  2738. "Skipped opening external track: "
  2739. "stream %d, alias: path='%s', dir='%s', "
  2740. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  2741. "Set enable_drefs to allow this.\n",
  2742. st->index, dref->path, dref->dir, dref->filename,
  2743. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2744. }
  2745. } else {
  2746. sc->pb = c->fc->pb;
  2747. sc->pb_is_copied = 1;
  2748. }
  2749. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  2750. if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height &&
  2751. sc->height && sc->width &&
  2752. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  2753. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  2754. ((double)st->codecpar->width * sc->height), INT_MAX);
  2755. }
  2756. #if FF_API_R_FRAME_RATE
  2757. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  2758. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  2759. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  2760. #endif
  2761. }
  2762. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2763. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  2764. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  2765. ret = ff_generate_avci_extradata(st);
  2766. if (ret < 0)
  2767. return ret;
  2768. }
  2769. switch (st->codecpar->codec_id) {
  2770. #if CONFIG_H261_DECODER
  2771. case AV_CODEC_ID_H261:
  2772. #endif
  2773. #if CONFIG_H263_DECODER
  2774. case AV_CODEC_ID_H263:
  2775. #endif
  2776. #if CONFIG_MPEG4_DECODER
  2777. case AV_CODEC_ID_MPEG4:
  2778. #endif
  2779. st->codecpar->width = 0; /* let decoder init width/height */
  2780. st->codecpar->height= 0;
  2781. break;
  2782. }
  2783. // If the duration of the mp3 packets is not constant, then they could need a parser
  2784. if (st->codecpar->codec_id == AV_CODEC_ID_MP3
  2785. && sc->stts_count > 3
  2786. && sc->stts_count*10 > st->nb_frames
  2787. && sc->time_scale == st->codecpar->sample_rate) {
  2788. st->need_parsing = AVSTREAM_PARSE_FULL;
  2789. }
  2790. /* Do not need those anymore. */
  2791. av_freep(&sc->chunk_offsets);
  2792. av_freep(&sc->stsc_data);
  2793. av_freep(&sc->sample_sizes);
  2794. av_freep(&sc->keyframes);
  2795. av_freep(&sc->stts_data);
  2796. av_freep(&sc->stps_data);
  2797. av_freep(&sc->elst_data);
  2798. av_freep(&sc->rap_group);
  2799. return 0;
  2800. }
  2801. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2802. {
  2803. int ret;
  2804. c->itunes_metadata = 1;
  2805. ret = mov_read_default(c, pb, atom);
  2806. c->itunes_metadata = 0;
  2807. return ret;
  2808. }
  2809. static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2810. {
  2811. uint32_t count;
  2812. uint32_t i;
  2813. if (atom.size < 8)
  2814. return 0;
  2815. avio_skip(pb, 4);
  2816. count = avio_rb32(pb);
  2817. if (count > UINT_MAX / sizeof(*c->meta_keys)) {
  2818. av_log(c->fc, AV_LOG_ERROR,
  2819. "The 'keys' atom with the invalid key count: %d\n", count);
  2820. return AVERROR_INVALIDDATA;
  2821. }
  2822. c->meta_keys_count = count + 1;
  2823. c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys));
  2824. if (!c->meta_keys)
  2825. return AVERROR(ENOMEM);
  2826. for (i = 1; i <= count; ++i) {
  2827. uint32_t key_size = avio_rb32(pb);
  2828. uint32_t type = avio_rl32(pb);
  2829. if (key_size < 8) {
  2830. av_log(c->fc, AV_LOG_ERROR,
  2831. "The key# %d in meta has invalid size: %d\n", i, key_size);
  2832. return AVERROR_INVALIDDATA;
  2833. }
  2834. key_size -= 8;
  2835. if (type != MKTAG('m','d','t','a')) {
  2836. avio_skip(pb, key_size);
  2837. }
  2838. c->meta_keys[i] = av_mallocz(key_size + 1);
  2839. if (!c->meta_keys[i])
  2840. return AVERROR(ENOMEM);
  2841. avio_read(pb, c->meta_keys[i], key_size);
  2842. }
  2843. return 0;
  2844. }
  2845. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2846. {
  2847. int64_t end = avio_tell(pb) + atom.size;
  2848. uint8_t *key = NULL, *val = NULL, *mean = NULL;
  2849. int i;
  2850. int ret = 0;
  2851. AVStream *st;
  2852. MOVStreamContext *sc;
  2853. if (c->fc->nb_streams < 1)
  2854. return 0;
  2855. st = c->fc->streams[c->fc->nb_streams-1];
  2856. sc = st->priv_data;
  2857. for (i = 0; i < 3; i++) {
  2858. uint8_t **p;
  2859. uint32_t len, tag;
  2860. if (end - avio_tell(pb) <= 12)
  2861. break;
  2862. len = avio_rb32(pb);
  2863. tag = avio_rl32(pb);
  2864. avio_skip(pb, 4); // flags
  2865. if (len < 12 || len - 12 > end - avio_tell(pb))
  2866. break;
  2867. len -= 12;
  2868. if (tag == MKTAG('m', 'e', 'a', 'n'))
  2869. p = &mean;
  2870. else if (tag == MKTAG('n', 'a', 'm', 'e'))
  2871. p = &key;
  2872. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2873. avio_skip(pb, 4);
  2874. len -= 4;
  2875. p = &val;
  2876. } else
  2877. break;
  2878. *p = av_malloc(len + 1);
  2879. if (!*p)
  2880. break;
  2881. ret = ffio_read_size(pb, *p, len);
  2882. if (ret < 0) {
  2883. av_freep(p);
  2884. break;
  2885. }
  2886. (*p)[len] = 0;
  2887. }
  2888. if (mean && key && val) {
  2889. if (strcmp(key, "iTunSMPB") == 0) {
  2890. int priming, remainder, samples;
  2891. if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){
  2892. if(priming>0 && priming<16384)
  2893. sc->start_pad = priming;
  2894. }
  2895. }
  2896. if (strcmp(key, "cdec") != 0) {
  2897. av_dict_set(&c->fc->metadata, key, val,
  2898. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2899. key = val = NULL;
  2900. }
  2901. } else {
  2902. av_log(c->fc, AV_LOG_VERBOSE,
  2903. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2904. }
  2905. avio_seek(pb, end, SEEK_SET);
  2906. av_freep(&key);
  2907. av_freep(&val);
  2908. av_freep(&mean);
  2909. return ret;
  2910. }
  2911. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2912. {
  2913. while (atom.size > 8) {
  2914. uint32_t tag = avio_rl32(pb);
  2915. atom.size -= 4;
  2916. if (tag == MKTAG('h','d','l','r')) {
  2917. avio_seek(pb, -8, SEEK_CUR);
  2918. atom.size += 8;
  2919. return mov_read_default(c, pb, atom);
  2920. }
  2921. }
  2922. return 0;
  2923. }
  2924. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2925. {
  2926. int i;
  2927. int width;
  2928. int height;
  2929. int display_matrix[3][3];
  2930. AVStream *st;
  2931. MOVStreamContext *sc;
  2932. int version;
  2933. int flags;
  2934. if (c->fc->nb_streams < 1)
  2935. return 0;
  2936. st = c->fc->streams[c->fc->nb_streams-1];
  2937. sc = st->priv_data;
  2938. version = avio_r8(pb);
  2939. flags = avio_rb24(pb);
  2940. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2941. if (version == 1) {
  2942. avio_rb64(pb);
  2943. avio_rb64(pb);
  2944. } else {
  2945. avio_rb32(pb); /* creation time */
  2946. avio_rb32(pb); /* modification time */
  2947. }
  2948. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2949. avio_rb32(pb); /* reserved */
  2950. /* highlevel (considering edits) duration in movie timebase */
  2951. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2952. avio_rb32(pb); /* reserved */
  2953. avio_rb32(pb); /* reserved */
  2954. avio_rb16(pb); /* layer */
  2955. avio_rb16(pb); /* alternate group */
  2956. avio_rb16(pb); /* volume */
  2957. avio_rb16(pb); /* reserved */
  2958. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2959. // they're kept in fixed point format through all calculations
  2960. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2961. // side data, but the scale factor is not needed to calculate aspect ratio
  2962. for (i = 0; i < 3; i++) {
  2963. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2964. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2965. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2966. }
  2967. width = avio_rb32(pb); // 16.16 fixed point track width
  2968. height = avio_rb32(pb); // 16.16 fixed point track height
  2969. sc->width = width >> 16;
  2970. sc->height = height >> 16;
  2971. // save the matrix and add rotate metadata when it is not the default
  2972. // identity
  2973. if (display_matrix[0][0] != (1 << 16) ||
  2974. display_matrix[1][1] != (1 << 16) ||
  2975. display_matrix[2][2] != (1 << 30) ||
  2976. display_matrix[0][1] || display_matrix[0][2] ||
  2977. display_matrix[1][0] || display_matrix[1][2] ||
  2978. display_matrix[2][0] || display_matrix[2][1]) {
  2979. int i, j;
  2980. double rotate;
  2981. av_freep(&sc->display_matrix);
  2982. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2983. if (!sc->display_matrix)
  2984. return AVERROR(ENOMEM);
  2985. for (i = 0; i < 3; i++)
  2986. for (j = 0; j < 3; j++)
  2987. sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  2988. rotate = av_display_rotation_get(sc->display_matrix);
  2989. if (!isnan(rotate)) {
  2990. char rotate_buf[64];
  2991. rotate = -rotate;
  2992. if (rotate < 0) // for backward compatibility
  2993. rotate += 360;
  2994. snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);
  2995. av_dict_set(&st->metadata, "rotate", rotate_buf, 0);
  2996. }
  2997. }
  2998. // transform the display width/height according to the matrix
  2999. // to keep the same scale, use [width height 1<<16]
  3000. if (width && height && sc->display_matrix) {
  3001. double disp_transform[2];
  3002. for (i = 0; i < 2; i++)
  3003. disp_transform[i] = hypot(display_matrix[i][0], display_matrix[i][1]);
  3004. if (disp_transform[0] > 0 && disp_transform[1] > 0 &&
  3005. disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) &&
  3006. fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)
  3007. st->sample_aspect_ratio = av_d2q(
  3008. disp_transform[0] / disp_transform[1],
  3009. INT_MAX);
  3010. }
  3011. return 0;
  3012. }
  3013. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3014. {
  3015. MOVFragment *frag = &c->fragment;
  3016. MOVTrackExt *trex = NULL;
  3017. MOVFragmentIndex* index = NULL;
  3018. int flags, track_id, i, found = 0;
  3019. avio_r8(pb); /* version */
  3020. flags = avio_rb24(pb);
  3021. track_id = avio_rb32(pb);
  3022. if (!track_id)
  3023. return AVERROR_INVALIDDATA;
  3024. frag->track_id = track_id;
  3025. for (i = 0; i < c->trex_count; i++)
  3026. if (c->trex_data[i].track_id == frag->track_id) {
  3027. trex = &c->trex_data[i];
  3028. break;
  3029. }
  3030. if (!trex) {
  3031. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  3032. return AVERROR_INVALIDDATA;
  3033. }
  3034. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  3035. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  3036. frag->moof_offset : frag->implicit_offset;
  3037. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  3038. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  3039. avio_rb32(pb) : trex->duration;
  3040. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  3041. avio_rb32(pb) : trex->size;
  3042. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  3043. avio_rb32(pb) : trex->flags;
  3044. frag->time = AV_NOPTS_VALUE;
  3045. for (i = 0; i < c->fragment_index_count; i++) {
  3046. int j;
  3047. MOVFragmentIndex* candidate = c->fragment_index_data[i];
  3048. if (candidate->track_id == frag->track_id) {
  3049. av_log(c->fc, AV_LOG_DEBUG,
  3050. "found fragment index for track %u\n", frag->track_id);
  3051. index = candidate;
  3052. for (j = index->current_item; j < index->item_count; j++) {
  3053. if (frag->implicit_offset == index->items[j].moof_offset) {
  3054. av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry "
  3055. "for track %u and moof_offset %"PRId64"\n",
  3056. frag->track_id, index->items[j].moof_offset);
  3057. frag->time = index->items[j].time;
  3058. index->current_item = j + 1;
  3059. found = 1;
  3060. break;
  3061. }
  3062. }
  3063. if (found)
  3064. break;
  3065. }
  3066. }
  3067. if (index && !found) {
  3068. av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but "
  3069. "it doesn't have an (in-order) entry for moof_offset "
  3070. "%"PRId64"\n", frag->track_id, frag->implicit_offset);
  3071. }
  3072. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  3073. return 0;
  3074. }
  3075. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3076. {
  3077. c->chapter_track = avio_rb32(pb);
  3078. return 0;
  3079. }
  3080. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3081. {
  3082. MOVTrackExt *trex;
  3083. int err;
  3084. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  3085. return AVERROR_INVALIDDATA;
  3086. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  3087. sizeof(*c->trex_data))) < 0) {
  3088. c->trex_count = 0;
  3089. return err;
  3090. }
  3091. c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used.
  3092. trex = &c->trex_data[c->trex_count++];
  3093. avio_r8(pb); /* version */
  3094. avio_rb24(pb); /* flags */
  3095. trex->track_id = avio_rb32(pb);
  3096. trex->stsd_id = avio_rb32(pb);
  3097. trex->duration = avio_rb32(pb);
  3098. trex->size = avio_rb32(pb);
  3099. trex->flags = avio_rb32(pb);
  3100. return 0;
  3101. }
  3102. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3103. {
  3104. MOVFragment *frag = &c->fragment;
  3105. AVStream *st = NULL;
  3106. MOVStreamContext *sc;
  3107. int version, i;
  3108. for (i = 0; i < c->fc->nb_streams; i++) {
  3109. if (c->fc->streams[i]->id == frag->track_id) {
  3110. st = c->fc->streams[i];
  3111. break;
  3112. }
  3113. }
  3114. if (!st) {
  3115. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3116. return AVERROR_INVALIDDATA;
  3117. }
  3118. sc = st->priv_data;
  3119. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  3120. return 0;
  3121. version = avio_r8(pb);
  3122. avio_rb24(pb); /* flags */
  3123. if (version) {
  3124. sc->track_end = avio_rb64(pb);
  3125. } else {
  3126. sc->track_end = avio_rb32(pb);
  3127. }
  3128. return 0;
  3129. }
  3130. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3131. {
  3132. MOVFragment *frag = &c->fragment;
  3133. AVStream *st = NULL;
  3134. MOVStreamContext *sc;
  3135. MOVStts *ctts_data;
  3136. uint64_t offset;
  3137. int64_t dts;
  3138. int data_offset = 0;
  3139. unsigned entries, first_sample_flags = frag->flags;
  3140. int flags, distance, i, err;
  3141. for (i = 0; i < c->fc->nb_streams; i++) {
  3142. if (c->fc->streams[i]->id == frag->track_id) {
  3143. st = c->fc->streams[i];
  3144. break;
  3145. }
  3146. }
  3147. if (!st) {
  3148. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  3149. return AVERROR_INVALIDDATA;
  3150. }
  3151. sc = st->priv_data;
  3152. if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)
  3153. return 0;
  3154. avio_r8(pb); /* version */
  3155. flags = avio_rb24(pb);
  3156. entries = avio_rb32(pb);
  3157. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  3158. /* Always assume the presence of composition time offsets.
  3159. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  3160. * 1) in the initial movie, there are no samples.
  3161. * 2) in the first movie fragment, there is only one sample without composition time offset.
  3162. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  3163. if (!sc->ctts_count && sc->sample_count)
  3164. {
  3165. /* Complement ctts table if moov atom doesn't have ctts atom. */
  3166. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  3167. if (!ctts_data)
  3168. return AVERROR(ENOMEM);
  3169. sc->ctts_data = ctts_data;
  3170. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  3171. sc->ctts_data[sc->ctts_count].duration = 0;
  3172. sc->ctts_count++;
  3173. }
  3174. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  3175. return AVERROR_INVALIDDATA;
  3176. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  3177. sizeof(*sc->ctts_data))) < 0) {
  3178. sc->ctts_count = 0;
  3179. return err;
  3180. }
  3181. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  3182. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  3183. dts = sc->track_end - sc->time_offset;
  3184. offset = frag->base_data_offset + data_offset;
  3185. distance = 0;
  3186. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  3187. for (i = 0; i < entries && !pb->eof_reached; i++) {
  3188. unsigned sample_size = frag->size;
  3189. int sample_flags = i ? frag->flags : first_sample_flags;
  3190. unsigned sample_duration = frag->duration;
  3191. int keyframe = 0;
  3192. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  3193. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  3194. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  3195. sc->ctts_data[sc->ctts_count].count = 1;
  3196. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  3197. avio_rb32(pb) : 0;
  3198. mov_update_dts_shift(sc, sc->ctts_data[sc->ctts_count].duration);
  3199. if (frag->time != AV_NOPTS_VALUE) {
  3200. if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {
  3201. int64_t pts = frag->time;
  3202. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3203. " sc->dts_shift %d ctts.duration %d"
  3204. " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,
  3205. sc->dts_shift, sc->ctts_data[sc->ctts_count].duration,
  3206. sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);
  3207. dts = pts - sc->dts_shift;
  3208. if (flags & MOV_TRUN_SAMPLE_CTS) {
  3209. dts -= sc->ctts_data[sc->ctts_count].duration;
  3210. } else {
  3211. dts -= sc->time_offset;
  3212. }
  3213. av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);
  3214. } else {
  3215. dts = frag->time - sc->time_offset;
  3216. av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64
  3217. ", using it for dts\n", dts);
  3218. }
  3219. frag->time = AV_NOPTS_VALUE;
  3220. }
  3221. sc->ctts_count++;
  3222. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  3223. keyframe = 1;
  3224. else
  3225. keyframe =
  3226. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  3227. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  3228. if (keyframe)
  3229. distance = 0;
  3230. err = av_add_index_entry(st, offset, dts, sample_size, distance,
  3231. keyframe ? AVINDEX_KEYFRAME : 0);
  3232. if (err < 0) {
  3233. av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");
  3234. }
  3235. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  3236. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  3237. offset, dts, sample_size, distance, keyframe);
  3238. distance++;
  3239. dts += sample_duration;
  3240. offset += sample_size;
  3241. sc->data_size += sample_size;
  3242. sc->duration_for_fps += sample_duration;
  3243. sc->nb_frames_for_fps ++;
  3244. }
  3245. if (pb->eof_reached)
  3246. return AVERROR_EOF;
  3247. frag->implicit_offset = offset;
  3248. sc->track_end = dts + sc->time_offset;
  3249. if (st->duration < sc->track_end)
  3250. st->duration = sc->track_end;
  3251. return 0;
  3252. }
  3253. static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3254. {
  3255. int64_t offset = avio_tell(pb) + atom.size, pts;
  3256. uint8_t version;
  3257. unsigned i, track_id;
  3258. AVStream *st = NULL;
  3259. MOVStreamContext *sc;
  3260. MOVFragmentIndex *index = NULL;
  3261. MOVFragmentIndex **tmp;
  3262. AVRational timescale;
  3263. version = avio_r8(pb);
  3264. if (version > 1) {
  3265. avpriv_request_sample(c->fc, "sidx version %u", version);
  3266. return 0;
  3267. }
  3268. avio_rb24(pb); // flags
  3269. track_id = avio_rb32(pb); // Reference ID
  3270. for (i = 0; i < c->fc->nb_streams; i++) {
  3271. if (c->fc->streams[i]->id == track_id) {
  3272. st = c->fc->streams[i];
  3273. break;
  3274. }
  3275. }
  3276. if (!st) {
  3277. av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id);
  3278. return 0;
  3279. }
  3280. sc = st->priv_data;
  3281. timescale = av_make_q(1, avio_rb32(pb));
  3282. if (version == 0) {
  3283. pts = avio_rb32(pb);
  3284. offset += avio_rb32(pb);
  3285. } else {
  3286. pts = avio_rb64(pb);
  3287. offset += avio_rb64(pb);
  3288. }
  3289. avio_rb16(pb); // reserved
  3290. index = av_mallocz(sizeof(MOVFragmentIndex));
  3291. if (!index)
  3292. return AVERROR(ENOMEM);
  3293. index->track_id = track_id;
  3294. index->item_count = avio_rb16(pb);
  3295. index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem));
  3296. if (!index->items) {
  3297. av_freep(&index);
  3298. return AVERROR(ENOMEM);
  3299. }
  3300. for (i = 0; i < index->item_count; i++) {
  3301. uint32_t size = avio_rb32(pb);
  3302. uint32_t duration = avio_rb32(pb);
  3303. if (size & 0x80000000) {
  3304. avpriv_request_sample(c->fc, "sidx reference_type 1");
  3305. av_freep(&index->items);
  3306. av_freep(&index);
  3307. return AVERROR_PATCHWELCOME;
  3308. }
  3309. avio_rb32(pb); // sap_flags
  3310. index->items[i].moof_offset = offset;
  3311. index->items[i].time = av_rescale_q(pts, st->time_base, timescale);
  3312. offset += size;
  3313. pts += duration;
  3314. }
  3315. st->duration = sc->track_end = pts;
  3316. tmp = av_realloc_array(c->fragment_index_data,
  3317. c->fragment_index_count + 1,
  3318. sizeof(MOVFragmentIndex*));
  3319. if (!tmp) {
  3320. av_freep(&index->items);
  3321. av_freep(&index);
  3322. return AVERROR(ENOMEM);
  3323. }
  3324. c->fragment_index_data = tmp;
  3325. c->fragment_index_data[c->fragment_index_count++] = index;
  3326. if (offset == avio_size(pb))
  3327. c->fragment_index_complete = 1;
  3328. return 0;
  3329. }
  3330. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  3331. /* like the files created with Adobe Premiere 5.0, for samples see */
  3332. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  3333. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3334. {
  3335. int err;
  3336. if (atom.size < 8)
  3337. return 0; /* continue */
  3338. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  3339. avio_skip(pb, atom.size - 4);
  3340. return 0;
  3341. }
  3342. atom.type = avio_rl32(pb);
  3343. atom.size -= 8;
  3344. if (atom.type != MKTAG('m','d','a','t')) {
  3345. avio_skip(pb, atom.size);
  3346. return 0;
  3347. }
  3348. err = mov_read_mdat(c, pb, atom);
  3349. return err;
  3350. }
  3351. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3352. {
  3353. #if CONFIG_ZLIB
  3354. AVIOContext ctx;
  3355. uint8_t *cmov_data;
  3356. uint8_t *moov_data; /* uncompressed data */
  3357. long cmov_len, moov_len;
  3358. int ret = -1;
  3359. avio_rb32(pb); /* dcom atom */
  3360. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  3361. return AVERROR_INVALIDDATA;
  3362. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  3363. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n");
  3364. return AVERROR_INVALIDDATA;
  3365. }
  3366. avio_rb32(pb); /* cmvd atom */
  3367. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  3368. return AVERROR_INVALIDDATA;
  3369. moov_len = avio_rb32(pb); /* uncompressed size */
  3370. cmov_len = atom.size - 6 * 4;
  3371. cmov_data = av_malloc(cmov_len);
  3372. if (!cmov_data)
  3373. return AVERROR(ENOMEM);
  3374. moov_data = av_malloc(moov_len);
  3375. if (!moov_data) {
  3376. av_free(cmov_data);
  3377. return AVERROR(ENOMEM);
  3378. }
  3379. ret = ffio_read_size(pb, cmov_data, cmov_len);
  3380. if (ret < 0)
  3381. goto free_and_return;
  3382. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  3383. goto free_and_return;
  3384. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  3385. goto free_and_return;
  3386. ctx.seekable = AVIO_SEEKABLE_NORMAL;
  3387. atom.type = MKTAG('m','o','o','v');
  3388. atom.size = moov_len;
  3389. ret = mov_read_default(c, &ctx, atom);
  3390. free_and_return:
  3391. av_free(moov_data);
  3392. av_free(cmov_data);
  3393. return ret;
  3394. #else
  3395. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  3396. return AVERROR(ENOSYS);
  3397. #endif
  3398. }
  3399. /* edit list atom */
  3400. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3401. {
  3402. MOVStreamContext *sc;
  3403. int i, edit_count, version;
  3404. if (c->fc->nb_streams < 1 || c->ignore_editlist)
  3405. return 0;
  3406. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  3407. version = avio_r8(pb); /* version */
  3408. avio_rb24(pb); /* flags */
  3409. edit_count = avio_rb32(pb); /* entries */
  3410. if (!edit_count)
  3411. return 0;
  3412. if (sc->elst_data)
  3413. av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n");
  3414. av_free(sc->elst_data);
  3415. sc->elst_count = 0;
  3416. sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data));
  3417. if (!sc->elst_data)
  3418. return AVERROR(ENOMEM);
  3419. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  3420. for (i = 0; i < edit_count && !pb->eof_reached; i++) {
  3421. MOVElst *e = &sc->elst_data[i];
  3422. if (version == 1) {
  3423. e->duration = avio_rb64(pb);
  3424. e->time = avio_rb64(pb);
  3425. } else {
  3426. e->duration = avio_rb32(pb); /* segment duration */
  3427. e->time = (int32_t)avio_rb32(pb); /* media time */
  3428. }
  3429. e->rate = avio_rb32(pb) / 65536.0;
  3430. av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n",
  3431. e->duration, e->time, e->rate);
  3432. }
  3433. sc->elst_count = i;
  3434. return 0;
  3435. }
  3436. static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3437. {
  3438. MOVStreamContext *sc;
  3439. if (c->fc->nb_streams < 1)
  3440. return AVERROR_INVALIDDATA;
  3441. sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data;
  3442. sc->timecode_track = avio_rb32(pb);
  3443. return 0;
  3444. }
  3445. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3446. {
  3447. int ret;
  3448. uint8_t uuid[16];
  3449. static const uint8_t uuid_isml_manifest[] = {
  3450. 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
  3451. 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
  3452. };
  3453. static const uint8_t uuid_xmp[] = {
  3454. 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8,
  3455. 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac
  3456. };
  3457. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  3458. return AVERROR_INVALIDDATA;
  3459. ret = avio_read(pb, uuid, sizeof(uuid));
  3460. if (ret < 0) {
  3461. return ret;
  3462. } else if (ret != sizeof(uuid)) {
  3463. return AVERROR_INVALIDDATA;
  3464. }
  3465. if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) {
  3466. uint8_t *buffer, *ptr;
  3467. char *endptr;
  3468. size_t len = atom.size - sizeof(uuid);
  3469. if (len < 4) {
  3470. return AVERROR_INVALIDDATA;
  3471. }
  3472. ret = avio_skip(pb, 4); // zeroes
  3473. len -= 4;
  3474. buffer = av_mallocz(len + 1);
  3475. if (!buffer) {
  3476. return AVERROR(ENOMEM);
  3477. }
  3478. ret = avio_read(pb, buffer, len);
  3479. if (ret < 0) {
  3480. av_free(buffer);
  3481. return ret;
  3482. } else if (ret != len) {
  3483. av_free(buffer);
  3484. return AVERROR_INVALIDDATA;
  3485. }
  3486. ptr = buffer;
  3487. while ((ptr = av_stristr(ptr, "systemBitrate=\""))) {
  3488. ptr += sizeof("systemBitrate=\"") - 1;
  3489. c->bitrates_count++;
  3490. c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates));
  3491. if (!c->bitrates) {
  3492. c->bitrates_count = 0;
  3493. av_free(buffer);
  3494. return AVERROR(ENOMEM);
  3495. }
  3496. errno = 0;
  3497. ret = strtol(ptr, &endptr, 10);
  3498. if (ret < 0 || errno || *endptr != '"') {
  3499. c->bitrates[c->bitrates_count - 1] = 0;
  3500. } else {
  3501. c->bitrates[c->bitrates_count - 1] = ret;
  3502. }
  3503. }
  3504. av_free(buffer);
  3505. } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) {
  3506. uint8_t *buffer;
  3507. size_t len = atom.size - sizeof(uuid);
  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. if (c->export_xmp) {
  3521. buffer[len] = '\0';
  3522. av_dict_set(&c->fc->metadata, "xmp", buffer, 0);
  3523. }
  3524. av_free(buffer);
  3525. }
  3526. return 0;
  3527. }
  3528. static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3529. {
  3530. int ret;
  3531. uint8_t content[16];
  3532. if (atom.size < 8)
  3533. return 0;
  3534. ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size));
  3535. if (ret < 0)
  3536. return ret;
  3537. if ( !c->found_moov
  3538. && !c->found_mdat
  3539. && !memcmp(content, "Anevia\x1A\x1A", 8)
  3540. && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) {
  3541. c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS;
  3542. }
  3543. return 0;
  3544. }
  3545. static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3546. {
  3547. uint32_t format = avio_rl32(pb);
  3548. MOVStreamContext *sc;
  3549. enum AVCodecID id;
  3550. AVStream *st;
  3551. if (c->fc->nb_streams < 1)
  3552. return 0;
  3553. st = c->fc->streams[c->fc->nb_streams - 1];
  3554. sc = st->priv_data;
  3555. switch (sc->format)
  3556. {
  3557. case MKTAG('e','n','c','v'): // encrypted video
  3558. case MKTAG('e','n','c','a'): // encrypted audio
  3559. id = mov_codec_id(st, format);
  3560. if (st->codecpar->codec_id != AV_CODEC_ID_NONE &&
  3561. st->codecpar->codec_id != id) {
  3562. av_log(c->fc, AV_LOG_WARNING,
  3563. "ignoring 'frma' atom of '%.4s', stream has codec id %d\n",
  3564. (char*)&format, st->codecpar->codec_id);
  3565. break;
  3566. }
  3567. st->codecpar->codec_id = id;
  3568. sc->format = format;
  3569. break;
  3570. default:
  3571. if (format != sc->format) {
  3572. av_log(c->fc, AV_LOG_WARNING,
  3573. "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n",
  3574. (char*)&format, (char*)&sc->format);
  3575. }
  3576. break;
  3577. }
  3578. return 0;
  3579. }
  3580. static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3581. {
  3582. AVStream *st;
  3583. MOVStreamContext *sc;
  3584. size_t auxiliary_info_size;
  3585. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  3586. return 0;
  3587. st = c->fc->streams[c->fc->nb_streams - 1];
  3588. sc = st->priv_data;
  3589. if (sc->cenc.aes_ctr) {
  3590. av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n");
  3591. return AVERROR_INVALIDDATA;
  3592. }
  3593. avio_r8(pb); /* version */
  3594. sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */
  3595. avio_rb32(pb); /* entries */
  3596. if (atom.size < 8) {
  3597. av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" too small\n", atom.size);
  3598. return AVERROR_INVALIDDATA;
  3599. }
  3600. /* save the auxiliary info as is */
  3601. auxiliary_info_size = atom.size - 8;
  3602. sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size);
  3603. if (!sc->cenc.auxiliary_info) {
  3604. return AVERROR(ENOMEM);
  3605. }
  3606. sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size;
  3607. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info;
  3608. if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) {
  3609. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info");
  3610. return AVERROR_INVALIDDATA;
  3611. }
  3612. /* initialize the cipher */
  3613. sc->cenc.aes_ctr = av_aes_ctr_alloc();
  3614. if (!sc->cenc.aes_ctr) {
  3615. return AVERROR(ENOMEM);
  3616. }
  3617. return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key);
  3618. }
  3619. static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3620. {
  3621. AVStream *st;
  3622. MOVStreamContext *sc;
  3623. size_t data_size;
  3624. int atom_header_size;
  3625. int flags;
  3626. if (c->decryption_key_len == 0 || c->fc->nb_streams < 1)
  3627. return 0;
  3628. st = c->fc->streams[c->fc->nb_streams - 1];
  3629. sc = st->priv_data;
  3630. if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) {
  3631. av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n");
  3632. return AVERROR_INVALIDDATA;
  3633. }
  3634. atom_header_size = 9;
  3635. avio_r8(pb); /* version */
  3636. flags = avio_rb24(pb);
  3637. if ((flags & 0x01) != 0) {
  3638. atom_header_size += 8;
  3639. avio_rb32(pb); /* info type */
  3640. avio_rb32(pb); /* info type param */
  3641. }
  3642. sc->cenc.auxiliary_info_default_size = avio_r8(pb);
  3643. avio_rb32(pb); /* entries */
  3644. if (atom.size <= atom_header_size) {
  3645. return 0;
  3646. }
  3647. /* save the auxiliary info sizes as is */
  3648. data_size = atom.size - atom_header_size;
  3649. sc->cenc.auxiliary_info_sizes = av_malloc(data_size);
  3650. if (!sc->cenc.auxiliary_info_sizes) {
  3651. return AVERROR(ENOMEM);
  3652. }
  3653. sc->cenc.auxiliary_info_sizes_count = data_size;
  3654. if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) {
  3655. av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes");
  3656. return AVERROR_INVALIDDATA;
  3657. }
  3658. return 0;
  3659. }
  3660. static int cenc_filter(MOVContext *c, MOVStreamContext *sc, uint8_t *input, int size)
  3661. {
  3662. uint32_t encrypted_bytes;
  3663. uint16_t subsample_count;
  3664. uint16_t clear_bytes;
  3665. uint8_t* input_end = input + size;
  3666. /* read the iv */
  3667. if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3668. av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n");
  3669. return AVERROR_INVALIDDATA;
  3670. }
  3671. av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos);
  3672. sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE;
  3673. if (!sc->cenc.use_subsamples)
  3674. {
  3675. /* decrypt the whole packet */
  3676. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size);
  3677. return 0;
  3678. }
  3679. /* read the subsample count */
  3680. if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3681. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n");
  3682. return AVERROR_INVALIDDATA;
  3683. }
  3684. subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos);
  3685. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3686. for (; subsample_count > 0; subsample_count--)
  3687. {
  3688. if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) {
  3689. av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n");
  3690. return AVERROR_INVALIDDATA;
  3691. }
  3692. /* read the number of clear / encrypted bytes */
  3693. clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos);
  3694. sc->cenc.auxiliary_info_pos += sizeof(uint16_t);
  3695. encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos);
  3696. sc->cenc.auxiliary_info_pos += sizeof(uint32_t);
  3697. if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) {
  3698. av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n");
  3699. return AVERROR_INVALIDDATA;
  3700. }
  3701. /* skip the clear bytes */
  3702. input += clear_bytes;
  3703. /* decrypt the encrypted bytes */
  3704. av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes);
  3705. input += encrypted_bytes;
  3706. }
  3707. if (input < input_end) {
  3708. av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n");
  3709. return AVERROR_INVALIDDATA;
  3710. }
  3711. return 0;
  3712. }
  3713. static int mov_seek_auxiliary_info(AVFormatContext *s, MOVStreamContext *sc)
  3714. {
  3715. size_t auxiliary_info_seek_offset = 0;
  3716. int i;
  3717. if (sc->cenc.auxiliary_info_default_size) {
  3718. auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * sc->current_sample;
  3719. } else if (sc->cenc.auxiliary_info_sizes) {
  3720. if (sc->current_sample > sc->cenc.auxiliary_info_sizes_count) {
  3721. av_log(s, AV_LOG_ERROR, "current sample %d greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n",
  3722. sc->current_sample, sc->cenc.auxiliary_info_sizes_count);
  3723. return AVERROR_INVALIDDATA;
  3724. }
  3725. for (i = 0; i < sc->current_sample; i++) {
  3726. auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i];
  3727. }
  3728. }
  3729. if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) {
  3730. av_log(s, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n",
  3731. auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info));
  3732. return AVERROR_INVALIDDATA;
  3733. }
  3734. sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset;
  3735. return 0;
  3736. }
  3737. static const MOVParseTableEntry mov_default_parse_table[] = {
  3738. { MKTAG('A','C','L','R'), mov_read_aclr },
  3739. { MKTAG('A','P','R','G'), mov_read_avid },
  3740. { MKTAG('A','A','L','P'), mov_read_avid },
  3741. { MKTAG('A','R','E','S'), mov_read_ares },
  3742. { MKTAG('a','v','s','s'), mov_read_avss },
  3743. { MKTAG('c','h','p','l'), mov_read_chpl },
  3744. { MKTAG('c','o','6','4'), mov_read_stco },
  3745. { MKTAG('c','o','l','r'), mov_read_colr },
  3746. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  3747. { MKTAG('d','i','n','f'), mov_read_default },
  3748. { MKTAG('D','p','x','E'), mov_read_dpxe },
  3749. { MKTAG('d','r','e','f'), mov_read_dref },
  3750. { MKTAG('e','d','t','s'), mov_read_default },
  3751. { MKTAG('e','l','s','t'), mov_read_elst },
  3752. { MKTAG('e','n','d','a'), mov_read_enda },
  3753. { MKTAG('f','i','e','l'), mov_read_fiel },
  3754. { MKTAG('a','d','r','m'), mov_read_adrm },
  3755. { MKTAG('f','t','y','p'), mov_read_ftyp },
  3756. { MKTAG('g','l','b','l'), mov_read_glbl },
  3757. { MKTAG('h','d','l','r'), mov_read_hdlr },
  3758. { MKTAG('i','l','s','t'), mov_read_ilst },
  3759. { MKTAG('j','p','2','h'), mov_read_jp2h },
  3760. { MKTAG('m','d','a','t'), mov_read_mdat },
  3761. { MKTAG('m','d','h','d'), mov_read_mdhd },
  3762. { MKTAG('m','d','i','a'), mov_read_default },
  3763. { MKTAG('m','e','t','a'), mov_read_meta },
  3764. { MKTAG('m','i','n','f'), mov_read_default },
  3765. { MKTAG('m','o','o','f'), mov_read_moof },
  3766. { MKTAG('m','o','o','v'), mov_read_moov },
  3767. { MKTAG('m','v','e','x'), mov_read_default },
  3768. { MKTAG('m','v','h','d'), mov_read_mvhd },
  3769. { MKTAG('S','M','I',' '), mov_read_svq3 },
  3770. { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */
  3771. { MKTAG('a','v','c','C'), mov_read_glbl },
  3772. { MKTAG('p','a','s','p'), mov_read_pasp },
  3773. { MKTAG('s','i','d','x'), mov_read_sidx },
  3774. { MKTAG('s','t','b','l'), mov_read_default },
  3775. { MKTAG('s','t','c','o'), mov_read_stco },
  3776. { MKTAG('s','t','p','s'), mov_read_stps },
  3777. { MKTAG('s','t','r','f'), mov_read_strf },
  3778. { MKTAG('s','t','s','c'), mov_read_stsc },
  3779. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  3780. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  3781. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  3782. { MKTAG('s','t','t','s'), mov_read_stts },
  3783. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  3784. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  3785. { MKTAG('t','f','d','t'), mov_read_tfdt },
  3786. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  3787. { MKTAG('t','r','a','k'), mov_read_trak },
  3788. { MKTAG('t','r','a','f'), mov_read_default },
  3789. { MKTAG('t','r','e','f'), mov_read_default },
  3790. { MKTAG('t','m','c','d'), mov_read_tmcd },
  3791. { MKTAG('c','h','a','p'), mov_read_chap },
  3792. { MKTAG('t','r','e','x'), mov_read_trex },
  3793. { MKTAG('t','r','u','n'), mov_read_trun },
  3794. { MKTAG('u','d','t','a'), mov_read_default },
  3795. { MKTAG('w','a','v','e'), mov_read_wave },
  3796. { MKTAG('e','s','d','s'), mov_read_esds },
  3797. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  3798. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  3799. { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */
  3800. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  3801. { MKTAG('w','f','e','x'), mov_read_wfex },
  3802. { MKTAG('c','m','o','v'), mov_read_cmov },
  3803. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  3804. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  3805. { MKTAG('s','b','g','p'), mov_read_sbgp },
  3806. { MKTAG('h','v','c','C'), mov_read_glbl },
  3807. { MKTAG('u','u','i','d'), mov_read_uuid },
  3808. { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 },
  3809. { MKTAG('f','r','e','e'), mov_read_free },
  3810. { MKTAG('-','-','-','-'), mov_read_custom },
  3811. { MKTAG('s','i','n','f'), mov_read_default },
  3812. { MKTAG('f','r','m','a'), mov_read_frma },
  3813. { MKTAG('s','e','n','c'), mov_read_senc },
  3814. { MKTAG('s','a','i','z'), mov_read_saiz },
  3815. { 0, NULL }
  3816. };
  3817. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3818. {
  3819. int64_t total_size = 0;
  3820. MOVAtom a;
  3821. int i;
  3822. if (c->atom_depth > 10) {
  3823. av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n");
  3824. return AVERROR_INVALIDDATA;
  3825. }
  3826. c->atom_depth ++;
  3827. if (atom.size < 0)
  3828. atom.size = INT64_MAX;
  3829. while (total_size + 8 <= atom.size && !avio_feof(pb)) {
  3830. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  3831. a.size = atom.size;
  3832. a.type=0;
  3833. if (atom.size >= 8) {
  3834. a.size = avio_rb32(pb);
  3835. a.type = avio_rl32(pb);
  3836. if (a.type == MKTAG('f','r','e','e') &&
  3837. a.size >= 8 &&
  3838. c->moov_retry) {
  3839. uint8_t buf[8];
  3840. uint32_t *type = (uint32_t *)buf + 1;
  3841. if (avio_read(pb, buf, 8) != 8)
  3842. return AVERROR_INVALIDDATA;
  3843. avio_seek(pb, -8, SEEK_CUR);
  3844. if (*type == MKTAG('m','v','h','d') ||
  3845. *type == MKTAG('c','m','o','v')) {
  3846. av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n");
  3847. a.type = MKTAG('m','o','o','v');
  3848. }
  3849. }
  3850. if (atom.type != MKTAG('r','o','o','t') &&
  3851. atom.type != MKTAG('m','o','o','v'))
  3852. {
  3853. if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t'))
  3854. {
  3855. av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n");
  3856. avio_skip(pb, -8);
  3857. c->atom_depth --;
  3858. return 0;
  3859. }
  3860. }
  3861. total_size += 8;
  3862. if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */
  3863. a.size = avio_rb64(pb) - 8;
  3864. total_size += 8;
  3865. }
  3866. }
  3867. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  3868. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  3869. if (a.size == 0) {
  3870. a.size = atom.size - total_size + 8;
  3871. }
  3872. a.size -= 8;
  3873. if (a.size < 0)
  3874. break;
  3875. a.size = FFMIN(a.size, atom.size - total_size);
  3876. for (i = 0; mov_default_parse_table[i].type; i++)
  3877. if (mov_default_parse_table[i].type == a.type) {
  3878. parse = mov_default_parse_table[i].parse;
  3879. break;
  3880. }
  3881. // container is user data
  3882. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  3883. atom.type == MKTAG('i','l','s','t')))
  3884. parse = mov_read_udta_string;
  3885. // Supports parsing the QuickTime Metadata Keys.
  3886. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
  3887. if (!parse && c->found_hdlr_mdta &&
  3888. atom.type == MKTAG('m','e','t','a') &&
  3889. a.type == MKTAG('k','e','y','s')) {
  3890. parse = mov_read_keys;
  3891. }
  3892. if (!parse) { /* skip leaf atoms data */
  3893. avio_skip(pb, a.size);
  3894. } else {
  3895. int64_t start_pos = avio_tell(pb);
  3896. int64_t left;
  3897. int err = parse(c, pb, a);
  3898. if (err < 0) {
  3899. c->atom_depth --;
  3900. return err;
  3901. }
  3902. if (c->found_moov && c->found_mdat &&
  3903. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) ||
  3904. start_pos + a.size == avio_size(pb))) {
  3905. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete)
  3906. c->next_root_atom = start_pos + a.size;
  3907. c->atom_depth --;
  3908. return 0;
  3909. }
  3910. left = a.size - avio_tell(pb) + start_pos;
  3911. if (left > 0) /* skip garbage at atom end */
  3912. avio_skip(pb, left);
  3913. else if (left < 0) {
  3914. av_log(c->fc, AV_LOG_WARNING,
  3915. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  3916. (char*)&a.type, -left);
  3917. avio_seek(pb, left, SEEK_CUR);
  3918. }
  3919. }
  3920. total_size += a.size;
  3921. }
  3922. if (total_size < atom.size && atom.size < 0x7ffff)
  3923. avio_skip(pb, atom.size - total_size);
  3924. c->atom_depth --;
  3925. return 0;
  3926. }
  3927. static int mov_probe(AVProbeData *p)
  3928. {
  3929. int64_t offset;
  3930. uint32_t tag;
  3931. int score = 0;
  3932. int moov_offset = -1;
  3933. /* check file header */
  3934. offset = 0;
  3935. for (;;) {
  3936. /* ignore invalid offset */
  3937. if ((offset + 8) > (unsigned int)p->buf_size)
  3938. break;
  3939. tag = AV_RL32(p->buf + offset + 4);
  3940. switch(tag) {
  3941. /* check for obvious tags */
  3942. case MKTAG('m','o','o','v'):
  3943. moov_offset = offset + 4;
  3944. case MKTAG('m','d','a','t'):
  3945. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3946. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3947. case MKTAG('f','t','y','p'):
  3948. if (AV_RB32(p->buf+offset) < 8 &&
  3949. (AV_RB32(p->buf+offset) != 1 ||
  3950. offset + 12 > (unsigned int)p->buf_size ||
  3951. AV_RB64(p->buf+offset + 8) == 0)) {
  3952. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3953. } else if (tag == MKTAG('f','t','y','p') &&
  3954. ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ')
  3955. || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ')
  3956. )) {
  3957. score = FFMAX(score, 5);
  3958. } else {
  3959. score = AVPROBE_SCORE_MAX;
  3960. }
  3961. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3962. break;
  3963. /* those are more common words, so rate then a bit less */
  3964. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3965. case MKTAG('w','i','d','e'):
  3966. case MKTAG('f','r','e','e'):
  3967. case MKTAG('j','u','n','k'):
  3968. case MKTAG('p','i','c','t'):
  3969. score = FFMAX(score, AVPROBE_SCORE_MAX - 5);
  3970. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3971. break;
  3972. case MKTAG(0x82,0x82,0x7f,0x7d):
  3973. case MKTAG('s','k','i','p'):
  3974. case MKTAG('u','u','i','d'):
  3975. case MKTAG('p','r','f','l'):
  3976. /* if we only find those cause probedata is too small at least rate them */
  3977. score = FFMAX(score, AVPROBE_SCORE_EXTENSION);
  3978. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3979. break;
  3980. default:
  3981. offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset;
  3982. }
  3983. }
  3984. if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) {
  3985. /* moov atom in the header - we should make sure that this is not a
  3986. * MOV-packed MPEG-PS */
  3987. offset = moov_offset;
  3988. while(offset < (p->buf_size - 16)){ /* Sufficient space */
  3989. /* We found an actual hdlr atom */
  3990. if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') &&
  3991. AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') &&
  3992. AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){
  3993. av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n");
  3994. /* We found a media handler reference atom describing an
  3995. * MPEG-PS-in-MOV, return a
  3996. * low score to force expanding the probe window until
  3997. * mpegps_probe finds what it needs */
  3998. return 5;
  3999. }else
  4000. /* Keep looking */
  4001. offset+=2;
  4002. }
  4003. }
  4004. return score;
  4005. }
  4006. // must be done after parsing all trak because there's no order requirement
  4007. static void mov_read_chapters(AVFormatContext *s)
  4008. {
  4009. MOVContext *mov = s->priv_data;
  4010. AVStream *st = NULL;
  4011. MOVStreamContext *sc;
  4012. int64_t cur_pos;
  4013. int i;
  4014. for (i = 0; i < s->nb_streams; i++)
  4015. if (s->streams[i]->id == mov->chapter_track) {
  4016. st = s->streams[i];
  4017. break;
  4018. }
  4019. if (!st) {
  4020. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  4021. return;
  4022. }
  4023. st->discard = AVDISCARD_ALL;
  4024. sc = st->priv_data;
  4025. cur_pos = avio_tell(sc->pb);
  4026. for (i = 0; i < st->nb_index_entries; i++) {
  4027. AVIndexEntry *sample = &st->index_entries[i];
  4028. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  4029. uint8_t *title;
  4030. uint16_t ch;
  4031. int len, title_len;
  4032. if (end < sample->timestamp) {
  4033. av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");
  4034. end = AV_NOPTS_VALUE;
  4035. }
  4036. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  4037. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  4038. goto finish;
  4039. }
  4040. // the first two bytes are the length of the title
  4041. len = avio_rb16(sc->pb);
  4042. if (len > sample->size-2)
  4043. continue;
  4044. title_len = 2*len + 1;
  4045. if (!(title = av_mallocz(title_len)))
  4046. goto finish;
  4047. // The samples could theoretically be in any encoding if there's an encd
  4048. // atom following, but in practice are only utf-8 or utf-16, distinguished
  4049. // instead by the presence of a BOM
  4050. if (!len) {
  4051. title[0] = 0;
  4052. } else {
  4053. ch = avio_rb16(sc->pb);
  4054. if (ch == 0xfeff)
  4055. avio_get_str16be(sc->pb, len, title, title_len);
  4056. else if (ch == 0xfffe)
  4057. avio_get_str16le(sc->pb, len, title, title_len);
  4058. else {
  4059. AV_WB16(title, ch);
  4060. if (len == 1 || len == 2)
  4061. title[len] = 0;
  4062. else
  4063. avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);
  4064. }
  4065. }
  4066. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  4067. av_freep(&title);
  4068. }
  4069. finish:
  4070. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4071. }
  4072. static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st,
  4073. uint32_t value, int flags)
  4074. {
  4075. AVTimecode tc;
  4076. char buf[AV_TIMECODE_STR_SIZE];
  4077. AVRational rate = st->avg_frame_rate;
  4078. int ret = av_timecode_init(&tc, rate, flags, 0, s);
  4079. if (ret < 0)
  4080. return ret;
  4081. av_dict_set(&st->metadata, "timecode",
  4082. av_timecode_make_string(&tc, buf, value), 0);
  4083. return 0;
  4084. }
  4085. static int mov_read_timecode_track(AVFormatContext *s, AVStream *st)
  4086. {
  4087. MOVStreamContext *sc = st->priv_data;
  4088. int flags = 0;
  4089. int64_t cur_pos = avio_tell(sc->pb);
  4090. uint32_t value;
  4091. if (!st->nb_index_entries)
  4092. return -1;
  4093. avio_seek(sc->pb, st->index_entries->pos, SEEK_SET);
  4094. value = avio_rb32(s->pb);
  4095. if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME;
  4096. if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  4097. if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE;
  4098. /* Assume Counter flag is set to 1 in tmcd track (even though it is likely
  4099. * not the case) and thus assume "frame number format" instead of QT one.
  4100. * No sample with tmcd track can be found with a QT timecode at the moment,
  4101. * despite what the tmcd track "suggests" (Counter flag set to 0 means QT
  4102. * format). */
  4103. parse_timecode_in_framenum_format(s, st, value, flags);
  4104. avio_seek(sc->pb, cur_pos, SEEK_SET);
  4105. return 0;
  4106. }
  4107. static int mov_read_close(AVFormatContext *s)
  4108. {
  4109. MOVContext *mov = s->priv_data;
  4110. int i, j;
  4111. for (i = 0; i < s->nb_streams; i++) {
  4112. AVStream *st = s->streams[i];
  4113. MOVStreamContext *sc = st->priv_data;
  4114. if (!sc)
  4115. continue;
  4116. av_freep(&sc->ctts_data);
  4117. for (j = 0; j < sc->drefs_count; j++) {
  4118. av_freep(&sc->drefs[j].path);
  4119. av_freep(&sc->drefs[j].dir);
  4120. }
  4121. av_freep(&sc->drefs);
  4122. sc->drefs_count = 0;
  4123. if (!sc->pb_is_copied)
  4124. ff_format_io_close(s, &sc->pb);
  4125. sc->pb = NULL;
  4126. av_freep(&sc->chunk_offsets);
  4127. av_freep(&sc->stsc_data);
  4128. av_freep(&sc->sample_sizes);
  4129. av_freep(&sc->keyframes);
  4130. av_freep(&sc->stts_data);
  4131. av_freep(&sc->stps_data);
  4132. av_freep(&sc->elst_data);
  4133. av_freep(&sc->rap_group);
  4134. av_freep(&sc->display_matrix);
  4135. av_freep(&sc->cenc.auxiliary_info);
  4136. av_freep(&sc->cenc.auxiliary_info_sizes);
  4137. av_aes_ctr_free(sc->cenc.aes_ctr);
  4138. }
  4139. if (mov->dv_demux) {
  4140. avformat_free_context(mov->dv_fctx);
  4141. mov->dv_fctx = NULL;
  4142. }
  4143. if (mov->meta_keys) {
  4144. for (i = 1; i < mov->meta_keys_count; i++) {
  4145. av_freep(&mov->meta_keys[i]);
  4146. }
  4147. av_freep(&mov->meta_keys);
  4148. }
  4149. av_freep(&mov->trex_data);
  4150. av_freep(&mov->bitrates);
  4151. for (i = 0; i < mov->fragment_index_count; i++) {
  4152. MOVFragmentIndex* index = mov->fragment_index_data[i];
  4153. av_freep(&index->items);
  4154. av_freep(&mov->fragment_index_data[i]);
  4155. }
  4156. av_freep(&mov->fragment_index_data);
  4157. av_freep(&mov->aes_decrypt);
  4158. return 0;
  4159. }
  4160. static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id)
  4161. {
  4162. int i;
  4163. for (i = 0; i < s->nb_streams; i++) {
  4164. AVStream *st = s->streams[i];
  4165. MOVStreamContext *sc = st->priv_data;
  4166. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  4167. sc->timecode_track == tmcd_id)
  4168. return 1;
  4169. }
  4170. return 0;
  4171. }
  4172. /* look for a tmcd track not referenced by any video track, and export it globally */
  4173. static void export_orphan_timecode(AVFormatContext *s)
  4174. {
  4175. int i;
  4176. for (i = 0; i < s->nb_streams; i++) {
  4177. AVStream *st = s->streams[i];
  4178. if (st->codecpar->codec_tag == MKTAG('t','m','c','d') &&
  4179. !tmcd_is_referenced(s, i + 1)) {
  4180. AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0);
  4181. if (tcr) {
  4182. av_dict_set(&s->metadata, "timecode", tcr->value, 0);
  4183. break;
  4184. }
  4185. }
  4186. }
  4187. }
  4188. static int read_tfra(MOVContext *mov, AVIOContext *f)
  4189. {
  4190. MOVFragmentIndex* index = NULL;
  4191. int version, fieldlength, i, j;
  4192. int64_t pos = avio_tell(f);
  4193. uint32_t size = avio_rb32(f);
  4194. void *tmp;
  4195. if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
  4196. return 1;
  4197. }
  4198. av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
  4199. index = av_mallocz(sizeof(MOVFragmentIndex));
  4200. if (!index) {
  4201. return AVERROR(ENOMEM);
  4202. }
  4203. tmp = av_realloc_array(mov->fragment_index_data,
  4204. mov->fragment_index_count + 1,
  4205. sizeof(MOVFragmentIndex*));
  4206. if (!tmp) {
  4207. av_freep(&index);
  4208. return AVERROR(ENOMEM);
  4209. }
  4210. mov->fragment_index_data = tmp;
  4211. mov->fragment_index_data[mov->fragment_index_count++] = index;
  4212. version = avio_r8(f);
  4213. avio_rb24(f);
  4214. index->track_id = avio_rb32(f);
  4215. fieldlength = avio_rb32(f);
  4216. index->item_count = avio_rb32(f);
  4217. index->items = av_mallocz_array(
  4218. index->item_count, sizeof(MOVFragmentIndexItem));
  4219. if (!index->items) {
  4220. index->item_count = 0;
  4221. return AVERROR(ENOMEM);
  4222. }
  4223. for (i = 0; i < index->item_count; i++) {
  4224. int64_t time, offset;
  4225. if (version == 1) {
  4226. time = avio_rb64(f);
  4227. offset = avio_rb64(f);
  4228. } else {
  4229. time = avio_rb32(f);
  4230. offset = avio_rb32(f);
  4231. }
  4232. index->items[i].time = time;
  4233. index->items[i].moof_offset = offset;
  4234. for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
  4235. avio_r8(f);
  4236. for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
  4237. avio_r8(f);
  4238. for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
  4239. avio_r8(f);
  4240. }
  4241. avio_seek(f, pos + size, SEEK_SET);
  4242. return 0;
  4243. }
  4244. static int mov_read_mfra(MOVContext *c, AVIOContext *f)
  4245. {
  4246. int64_t stream_size = avio_size(f);
  4247. int64_t original_pos = avio_tell(f);
  4248. int64_t seek_ret;
  4249. int32_t mfra_size;
  4250. int ret = -1;
  4251. if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {
  4252. ret = seek_ret;
  4253. goto fail;
  4254. }
  4255. mfra_size = avio_rb32(f);
  4256. if (mfra_size < 0 || mfra_size > stream_size) {
  4257. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");
  4258. goto fail;
  4259. }
  4260. if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {
  4261. ret = seek_ret;
  4262. goto fail;
  4263. }
  4264. if (avio_rb32(f) != mfra_size) {
  4265. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");
  4266. goto fail;
  4267. }
  4268. if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {
  4269. av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");
  4270. goto fail;
  4271. }
  4272. av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");
  4273. do {
  4274. ret = read_tfra(c, f);
  4275. if (ret < 0)
  4276. goto fail;
  4277. } while (!ret);
  4278. ret = 0;
  4279. fail:
  4280. seek_ret = avio_seek(f, original_pos, SEEK_SET);
  4281. if (seek_ret < 0) {
  4282. av_log(c->fc, AV_LOG_ERROR,
  4283. "failed to seek back after looking for mfra\n");
  4284. ret = seek_ret;
  4285. }
  4286. return ret;
  4287. }
  4288. static int mov_read_header(AVFormatContext *s)
  4289. {
  4290. MOVContext *mov = s->priv_data;
  4291. AVIOContext *pb = s->pb;
  4292. int j, err;
  4293. MOVAtom atom = { AV_RL32("root") };
  4294. int i;
  4295. if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) {
  4296. av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n",
  4297. mov->decryption_key_len, AES_CTR_KEY_SIZE);
  4298. return AVERROR(EINVAL);
  4299. }
  4300. mov->fc = s;
  4301. mov->trak_index = -1;
  4302. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  4303. if (pb->seekable)
  4304. atom.size = avio_size(pb);
  4305. else
  4306. atom.size = INT64_MAX;
  4307. /* check MOV header */
  4308. do {
  4309. if (mov->moov_retry)
  4310. avio_seek(pb, 0, SEEK_SET);
  4311. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  4312. av_log(s, AV_LOG_ERROR, "error reading header\n");
  4313. mov_read_close(s);
  4314. return err;
  4315. }
  4316. } while (pb->seekable && !mov->found_moov && !mov->moov_retry++);
  4317. if (!mov->found_moov) {
  4318. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  4319. mov_read_close(s);
  4320. return AVERROR_INVALIDDATA;
  4321. }
  4322. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  4323. if (pb->seekable) {
  4324. if (mov->chapter_track > 0 && !mov->ignore_chapters)
  4325. mov_read_chapters(s);
  4326. for (i = 0; i < s->nb_streams; i++)
  4327. if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd"))
  4328. mov_read_timecode_track(s, s->streams[i]);
  4329. }
  4330. /* copy timecode metadata from tmcd tracks to the related video streams */
  4331. for (i = 0; i < s->nb_streams; i++) {
  4332. AVStream *st = s->streams[i];
  4333. MOVStreamContext *sc = st->priv_data;
  4334. if (sc->timecode_track > 0) {
  4335. AVDictionaryEntry *tcr;
  4336. int tmcd_st_id = -1;
  4337. for (j = 0; j < s->nb_streams; j++)
  4338. if (s->streams[j]->id == sc->timecode_track)
  4339. tmcd_st_id = j;
  4340. if (tmcd_st_id < 0 || tmcd_st_id == i)
  4341. continue;
  4342. tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0);
  4343. if (tcr)
  4344. av_dict_set(&st->metadata, "timecode", tcr->value, 0);
  4345. }
  4346. }
  4347. export_orphan_timecode(s);
  4348. for (i = 0; i < s->nb_streams; i++) {
  4349. AVStream *st = s->streams[i];
  4350. MOVStreamContext *sc = st->priv_data;
  4351. fix_timescale(mov, sc);
  4352. if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) {
  4353. st->skip_samples = sc->start_pad;
  4354. }
  4355. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0)
  4356. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  4357. sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX);
  4358. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  4359. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  4360. st->codecpar->width = sc->width;
  4361. st->codecpar->height = sc->height;
  4362. }
  4363. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  4364. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  4365. return err;
  4366. }
  4367. }
  4368. if (mov->handbrake_version &&
  4369. mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2
  4370. st->codecpar->codec_id == AV_CODEC_ID_MP3
  4371. ) {
  4372. av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n");
  4373. st->need_parsing = AVSTREAM_PARSE_FULL;
  4374. }
  4375. }
  4376. if (mov->trex_data) {
  4377. for (i = 0; i < s->nb_streams; i++) {
  4378. AVStream *st = s->streams[i];
  4379. MOVStreamContext *sc = st->priv_data;
  4380. if (st->duration > 0)
  4381. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  4382. }
  4383. }
  4384. if (mov->use_mfra_for > 0) {
  4385. for (i = 0; i < s->nb_streams; i++) {
  4386. AVStream *st = s->streams[i];
  4387. MOVStreamContext *sc = st->priv_data;
  4388. if (sc->duration_for_fps > 0) {
  4389. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale /
  4390. sc->duration_for_fps;
  4391. }
  4392. }
  4393. }
  4394. for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) {
  4395. if (mov->bitrates[i]) {
  4396. s->streams[i]->codecpar->bit_rate = mov->bitrates[i];
  4397. }
  4398. }
  4399. ff_rfps_calculate(s);
  4400. for (i = 0; i < s->nb_streams; i++) {
  4401. AVStream *st = s->streams[i];
  4402. MOVStreamContext *sc = st->priv_data;
  4403. switch (st->codecpar->codec_type) {
  4404. case AVMEDIA_TYPE_AUDIO:
  4405. err = ff_replaygain_export(st, s->metadata);
  4406. if (err < 0) {
  4407. mov_read_close(s);
  4408. return err;
  4409. }
  4410. break;
  4411. case AVMEDIA_TYPE_VIDEO:
  4412. if (sc->display_matrix) {
  4413. AVPacketSideData *sd, *tmp;
  4414. tmp = av_realloc_array(st->side_data,
  4415. st->nb_side_data + 1, sizeof(*tmp));
  4416. if (!tmp)
  4417. return AVERROR(ENOMEM);
  4418. st->side_data = tmp;
  4419. st->nb_side_data++;
  4420. sd = &st->side_data[st->nb_side_data - 1];
  4421. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  4422. sd->size = sizeof(int32_t) * 9;
  4423. sd->data = (uint8_t*)sc->display_matrix;
  4424. sc->display_matrix = NULL;
  4425. }
  4426. break;
  4427. }
  4428. }
  4429. ff_configure_buffers_for_index(s, AV_TIME_BASE);
  4430. return 0;
  4431. }
  4432. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  4433. {
  4434. AVIndexEntry *sample = NULL;
  4435. int64_t best_dts = INT64_MAX;
  4436. int i;
  4437. for (i = 0; i < s->nb_streams; i++) {
  4438. AVStream *avst = s->streams[i];
  4439. MOVStreamContext *msc = avst->priv_data;
  4440. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  4441. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  4442. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  4443. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  4444. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  4445. (s->pb->seekable &&
  4446. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  4447. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  4448. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  4449. sample = current_sample;
  4450. best_dts = dts;
  4451. *st = avst;
  4452. }
  4453. }
  4454. }
  4455. return sample;
  4456. }
  4457. static int should_retry(AVIOContext *pb, int error_code) {
  4458. if (error_code == AVERROR_EOF || avio_feof(pb))
  4459. return 0;
  4460. return 1;
  4461. }
  4462. static int mov_switch_root(AVFormatContext *s, int64_t target)
  4463. {
  4464. MOVContext *mov = s->priv_data;
  4465. int i, j;
  4466. int already_read = 0;
  4467. if (avio_seek(s->pb, target, SEEK_SET) != target) {
  4468. av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target);
  4469. return AVERROR_INVALIDDATA;
  4470. }
  4471. mov->next_root_atom = 0;
  4472. for (i = 0; i < mov->fragment_index_count; i++) {
  4473. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4474. int found = 0;
  4475. for (j = 0; j < index->item_count; j++) {
  4476. MOVFragmentIndexItem *item = &index->items[j];
  4477. if (found) {
  4478. mov->next_root_atom = item->moof_offset;
  4479. break; // Advance to next index in outer loop
  4480. } else if (item->moof_offset == target) {
  4481. index->current_item = FFMIN(j, index->current_item);
  4482. if (item->headers_read)
  4483. already_read = 1;
  4484. item->headers_read = 1;
  4485. found = 1;
  4486. }
  4487. }
  4488. if (!found)
  4489. index->current_item = 0;
  4490. }
  4491. if (already_read)
  4492. return 0;
  4493. mov->found_mdat = 0;
  4494. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  4495. avio_feof(s->pb))
  4496. return AVERROR_EOF;
  4497. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  4498. return 1;
  4499. }
  4500. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  4501. {
  4502. MOVContext *mov = s->priv_data;
  4503. MOVStreamContext *sc;
  4504. AVIndexEntry *sample;
  4505. AVStream *st = NULL;
  4506. int ret;
  4507. mov->fc = s;
  4508. retry:
  4509. sample = mov_find_next_sample(s, &st);
  4510. if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) {
  4511. if (!mov->next_root_atom)
  4512. return AVERROR_EOF;
  4513. if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0)
  4514. return ret;
  4515. goto retry;
  4516. }
  4517. sc = st->priv_data;
  4518. /* must be done just before reading, to avoid infinite loop on sample */
  4519. sc->current_sample++;
  4520. if (mov->next_root_atom) {
  4521. sample->pos = FFMIN(sample->pos, mov->next_root_atom);
  4522. sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));
  4523. }
  4524. if (st->discard != AVDISCARD_ALL) {
  4525. int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET);
  4526. if (ret64 != sample->pos) {
  4527. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  4528. sc->ffindex, sample->pos);
  4529. sc->current_sample -= should_retry(sc->pb, ret64);
  4530. return AVERROR_INVALIDDATA;
  4531. }
  4532. ret = av_get_packet(sc->pb, pkt, sample->size);
  4533. if (ret < 0) {
  4534. sc->current_sample -= should_retry(sc->pb, ret);
  4535. return ret;
  4536. }
  4537. if (sc->has_palette) {
  4538. uint8_t *pal;
  4539. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  4540. if (!pal) {
  4541. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  4542. } else {
  4543. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  4544. sc->has_palette = 0;
  4545. }
  4546. }
  4547. #if CONFIG_DV_DEMUXER
  4548. if (mov->dv_demux && sc->dv_audio_container) {
  4549. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
  4550. av_freep(&pkt->data);
  4551. pkt->size = 0;
  4552. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  4553. if (ret < 0)
  4554. return ret;
  4555. }
  4556. #endif
  4557. if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) {
  4558. if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0)
  4559. st->need_parsing = AVSTREAM_PARSE_FULL;
  4560. }
  4561. }
  4562. pkt->stream_index = sc->ffindex;
  4563. pkt->dts = sample->timestamp;
  4564. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  4565. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  4566. /* update ctts context */
  4567. sc->ctts_sample++;
  4568. if (sc->ctts_index < sc->ctts_count &&
  4569. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  4570. sc->ctts_index++;
  4571. sc->ctts_sample = 0;
  4572. }
  4573. if (sc->wrong_dts)
  4574. pkt->dts = AV_NOPTS_VALUE;
  4575. } else {
  4576. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  4577. st->index_entries[sc->current_sample].timestamp : st->duration;
  4578. pkt->duration = next_dts - pkt->dts;
  4579. pkt->pts = pkt->dts;
  4580. }
  4581. if (st->discard == AVDISCARD_ALL)
  4582. goto retry;
  4583. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  4584. pkt->pos = sample->pos;
  4585. if (mov->aax_mode)
  4586. aax_filter(pkt->data, pkt->size, mov);
  4587. if (sc->cenc.aes_ctr) {
  4588. ret = cenc_filter(mov, sc, pkt->data, pkt->size);
  4589. if (ret) {
  4590. return ret;
  4591. }
  4592. }
  4593. return 0;
  4594. }
  4595. static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp)
  4596. {
  4597. MOVContext *mov = s->priv_data;
  4598. int i, j;
  4599. if (!mov->fragment_index_complete)
  4600. return 0;
  4601. for (i = 0; i < mov->fragment_index_count; i++) {
  4602. if (mov->fragment_index_data[i]->track_id == st->id) {
  4603. MOVFragmentIndex *index = mov->fragment_index_data[i];
  4604. for (j = index->item_count - 1; j >= 0; j--) {
  4605. if (index->items[j].time <= timestamp) {
  4606. if (index->items[j].headers_read)
  4607. return 0;
  4608. return mov_switch_root(s, index->items[j].moof_offset);
  4609. }
  4610. }
  4611. }
  4612. }
  4613. return 0;
  4614. }
  4615. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  4616. {
  4617. MOVStreamContext *sc = st->priv_data;
  4618. int sample, time_sample;
  4619. int i;
  4620. int ret = mov_seek_fragment(s, st, timestamp);
  4621. if (ret < 0)
  4622. return ret;
  4623. sample = av_index_search_timestamp(st, timestamp, flags);
  4624. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  4625. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  4626. sample = 0;
  4627. if (sample < 0) /* not sure what to do */
  4628. return AVERROR_INVALIDDATA;
  4629. sc->current_sample = sample;
  4630. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  4631. /* adjust ctts index */
  4632. if (sc->ctts_data) {
  4633. time_sample = 0;
  4634. for (i = 0; i < sc->ctts_count; i++) {
  4635. int next = time_sample + sc->ctts_data[i].count;
  4636. if (next > sc->current_sample) {
  4637. sc->ctts_index = i;
  4638. sc->ctts_sample = sc->current_sample - time_sample;
  4639. break;
  4640. }
  4641. time_sample = next;
  4642. }
  4643. }
  4644. ret = mov_seek_auxiliary_info(s, sc);
  4645. if (ret < 0) {
  4646. return ret;
  4647. }
  4648. return sample;
  4649. }
  4650. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  4651. {
  4652. MOVContext *mc = s->priv_data;
  4653. AVStream *st;
  4654. int sample;
  4655. int i;
  4656. if (stream_index >= s->nb_streams)
  4657. return AVERROR_INVALIDDATA;
  4658. st = s->streams[stream_index];
  4659. sample = mov_seek_stream(s, st, sample_time, flags);
  4660. if (sample < 0)
  4661. return sample;
  4662. if (mc->seek_individually) {
  4663. /* adjust seek timestamp to found sample timestamp */
  4664. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  4665. for (i = 0; i < s->nb_streams; i++) {
  4666. int64_t timestamp;
  4667. MOVStreamContext *sc = s->streams[i]->priv_data;
  4668. st = s->streams[i];
  4669. st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0;
  4670. if (stream_index == i)
  4671. continue;
  4672. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  4673. mov_seek_stream(s, st, timestamp, flags);
  4674. }
  4675. } else {
  4676. for (i = 0; i < s->nb_streams; i++) {
  4677. MOVStreamContext *sc;
  4678. st = s->streams[i];
  4679. sc = st->priv_data;
  4680. sc->current_sample = 0;
  4681. }
  4682. while (1) {
  4683. MOVStreamContext *sc;
  4684. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  4685. if (!entry)
  4686. return AVERROR_INVALIDDATA;
  4687. sc = st->priv_data;
  4688. if (sc->ffindex == stream_index && sc->current_sample == sample)
  4689. break;
  4690. sc->current_sample++;
  4691. }
  4692. }
  4693. return 0;
  4694. }
  4695. #define OFFSET(x) offsetof(MOVContext, x)
  4696. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  4697. static const AVOption mov_options[] = {
  4698. {"use_absolute_path",
  4699. "allow using absolute path when opening alias, this is a possible security issue",
  4700. OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4701. 0, 1, FLAGS},
  4702. {"seek_streams_individually",
  4703. "Seek each stream individually to the to the closest point",
  4704. OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 },
  4705. 0, 1, FLAGS},
  4706. {"ignore_editlist", "", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4707. 0, 1, FLAGS},
  4708. {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0},
  4709. 0, 1, FLAGS},
  4710. {"use_mfra_for",
  4711. "use mfra for fragment timestamps",
  4712. OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO},
  4713. -1, FF_MOV_FLAG_MFRA_PTS, FLAGS,
  4714. "use_mfra_for"},
  4715. {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0,
  4716. FLAGS, "use_mfra_for" },
  4717. {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0,
  4718. FLAGS, "use_mfra_for" },
  4719. {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0,
  4720. FLAGS, "use_mfra_for" },
  4721. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  4722. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4723. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  4724. AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  4725. { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes),
  4726. AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4727. { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  4728. "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key),
  4729. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"},
  4730. .flags = AV_OPT_FLAG_DECODING_PARAM },
  4731. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM },
  4732. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL,
  4733. {.i64 = 0}, 0, 1, FLAGS },
  4734. { NULL },
  4735. };
  4736. static const AVClass mov_class = {
  4737. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  4738. .item_name = av_default_item_name,
  4739. .option = mov_options,
  4740. .version = LIBAVUTIL_VERSION_INT,
  4741. };
  4742. AVInputFormat ff_mov_demuxer = {
  4743. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  4744. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  4745. .priv_class = &mov_class,
  4746. .priv_data_size = sizeof(MOVContext),
  4747. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  4748. .read_probe = mov_probe,
  4749. .read_header = mov_read_header,
  4750. .read_packet = mov_read_packet,
  4751. .read_close = mov_read_close,
  4752. .read_seek = mov_read_seek,
  4753. .flags = AVFMT_NO_BYTE_SEEK,
  4754. };