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.

4433 lines
149KB

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