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.

4963 lines
166KB

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