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.

4279 lines
143KB

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