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.

5456 lines
183KB

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