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.

4411 lines
148KB

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