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.

5577 lines
186KB

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