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.

3826 lines
126KB

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