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.

5239 lines
174KB

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