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.

4994 lines
167KB

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