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.

4771 lines
160KB

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