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.

4346 lines
145KB

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