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.

3711 lines
122KB

  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("avc1") ||
  1534. codec_tag == AV_RL32("hvc1") ||
  1535. codec_tag == AV_RL32("hev1") ||
  1536. (codec_tag != format &&
  1537. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1538. : codec_tag != MKTAG('j','p','e','g'))))) {
  1539. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1540. * export it as a separate AVStream but this needs a few changes
  1541. * in the MOV demuxer, patch welcome. */
  1542. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1543. avio_skip(pb, size);
  1544. return 1;
  1545. }
  1546. return 0;
  1547. }
  1548. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1549. {
  1550. AVStream *st;
  1551. MOVStreamContext *sc;
  1552. int pseudo_stream_id;
  1553. if (c->fc->nb_streams < 1)
  1554. return 0;
  1555. st = c->fc->streams[c->fc->nb_streams-1];
  1556. sc = st->priv_data;
  1557. for (pseudo_stream_id = 0;
  1558. pseudo_stream_id < entries && !pb->eof_reached;
  1559. pseudo_stream_id++) {
  1560. //Parsing Sample description table
  1561. enum AVCodecID id;
  1562. int ret, dref_id = 1;
  1563. MOVAtom a = { AV_RL32("stsd") };
  1564. int64_t start_pos = avio_tell(pb);
  1565. int64_t size = avio_rb32(pb); /* size */
  1566. uint32_t format = avio_rl32(pb); /* data format */
  1567. if (size >= 16) {
  1568. avio_rb32(pb); /* reserved */
  1569. avio_rb16(pb); /* reserved */
  1570. dref_id = avio_rb16(pb);
  1571. } else {
  1572. av_log(c->fc, AV_LOG_ERROR,
  1573. "invalid size %"PRId64" in stsd\n", size);
  1574. return AVERROR_INVALIDDATA;
  1575. }
  1576. if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format,
  1577. size - (avio_tell(pb) - start_pos)))
  1578. continue;
  1579. sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id;
  1580. sc->dref_id= dref_id;
  1581. id = mov_codec_id(st, format);
  1582. av_log(c->fc, AV_LOG_TRACE,
  1583. "size=%"PRId64" format=0x%08x codec_type=%d\n",
  1584. size, format, st->codecpar->codec_type);
  1585. if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) {
  1586. st->codecpar->codec_id = id;
  1587. mov_parse_stsd_video(c, pb, st, sc);
  1588. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) {
  1589. st->codecpar->codec_id = id;
  1590. mov_parse_stsd_audio(c, pb, st, sc);
  1591. } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1592. st->codecpar->codec_id = id;
  1593. mov_parse_stsd_subtitle(c, pb, st, sc,
  1594. size - (avio_tell(pb) - start_pos));
  1595. } else {
  1596. ret = mov_parse_stsd_data(c, pb, st, sc,
  1597. size - (avio_tell(pb) - start_pos));
  1598. if (ret < 0)
  1599. return ret;
  1600. }
  1601. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1602. a.size = size - (avio_tell(pb) - start_pos);
  1603. if (a.size > 8) {
  1604. if ((ret = mov_read_default(c, pb, a)) < 0)
  1605. return ret;
  1606. } else if (a.size > 0)
  1607. avio_skip(pb, a.size);
  1608. }
  1609. if (pb->eof_reached)
  1610. return AVERROR_EOF;
  1611. return mov_finalize_stsd_codec(c, pb, st, sc);
  1612. }
  1613. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1614. {
  1615. int entries;
  1616. avio_r8(pb); /* version */
  1617. avio_rb24(pb); /* flags */
  1618. entries = avio_rb32(pb);
  1619. return ff_mov_read_stsd_entries(c, pb, entries);
  1620. }
  1621. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1622. {
  1623. AVStream *st;
  1624. MOVStreamContext *sc;
  1625. unsigned int i, entries;
  1626. if (c->fc->nb_streams < 1)
  1627. return 0;
  1628. st = c->fc->streams[c->fc->nb_streams-1];
  1629. sc = st->priv_data;
  1630. avio_r8(pb); /* version */
  1631. avio_rb24(pb); /* flags */
  1632. entries = avio_rb32(pb);
  1633. av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1634. if (!entries)
  1635. return 0;
  1636. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1637. return AVERROR_INVALIDDATA;
  1638. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1639. if (!sc->stsc_data)
  1640. return AVERROR(ENOMEM);
  1641. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1642. sc->stsc_data[i].first = avio_rb32(pb);
  1643. sc->stsc_data[i].count = avio_rb32(pb);
  1644. sc->stsc_data[i].id = avio_rb32(pb);
  1645. }
  1646. sc->stsc_count = i;
  1647. if (pb->eof_reached)
  1648. return AVERROR_EOF;
  1649. return 0;
  1650. }
  1651. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1652. {
  1653. AVStream *st;
  1654. MOVStreamContext *sc;
  1655. unsigned i, entries;
  1656. if (c->fc->nb_streams < 1)
  1657. return 0;
  1658. st = c->fc->streams[c->fc->nb_streams-1];
  1659. sc = st->priv_data;
  1660. avio_rb32(pb); // version + flags
  1661. entries = avio_rb32(pb);
  1662. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1663. return AVERROR_INVALIDDATA;
  1664. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1665. if (!sc->stps_data)
  1666. return AVERROR(ENOMEM);
  1667. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1668. sc->stps_data[i] = avio_rb32(pb);
  1669. //av_log(c->fc, AV_LOG_TRACE, "stps %d\n", sc->stps_data[i]);
  1670. }
  1671. sc->stps_count = i;
  1672. if (pb->eof_reached)
  1673. return AVERROR_EOF;
  1674. return 0;
  1675. }
  1676. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1677. {
  1678. AVStream *st;
  1679. MOVStreamContext *sc;
  1680. unsigned int i, entries;
  1681. if (c->fc->nb_streams < 1)
  1682. return 0;
  1683. st = c->fc->streams[c->fc->nb_streams-1];
  1684. sc = st->priv_data;
  1685. avio_r8(pb); /* version */
  1686. avio_rb24(pb); /* flags */
  1687. entries = avio_rb32(pb);
  1688. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %d\n", entries);
  1689. if (!entries)
  1690. {
  1691. sc->keyframe_absent = 1;
  1692. return 0;
  1693. }
  1694. if (entries >= UINT_MAX / sizeof(int))
  1695. return AVERROR_INVALIDDATA;
  1696. av_freep(&sc->keyframes);
  1697. sc->keyframes = av_malloc(entries * sizeof(int));
  1698. if (!sc->keyframes)
  1699. return AVERROR(ENOMEM);
  1700. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1701. sc->keyframes[i] = avio_rb32(pb);
  1702. //av_log(c->fc, AV_LOG_TRACE, "keyframes[]=%d\n", sc->keyframes[i]);
  1703. }
  1704. sc->keyframe_count = i;
  1705. if (pb->eof_reached)
  1706. return AVERROR_EOF;
  1707. return 0;
  1708. }
  1709. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1710. {
  1711. AVStream *st;
  1712. MOVStreamContext *sc;
  1713. unsigned int i, entries, sample_size, field_size, num_bytes;
  1714. GetBitContext gb;
  1715. unsigned char* buf;
  1716. int ret;
  1717. if (c->fc->nb_streams < 1)
  1718. return 0;
  1719. st = c->fc->streams[c->fc->nb_streams-1];
  1720. sc = st->priv_data;
  1721. avio_r8(pb); /* version */
  1722. avio_rb24(pb); /* flags */
  1723. if (atom.type == MKTAG('s','t','s','z')) {
  1724. sample_size = avio_rb32(pb);
  1725. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1726. sc->sample_size = sample_size;
  1727. field_size = 32;
  1728. } else {
  1729. sample_size = 0;
  1730. avio_rb24(pb); /* reserved */
  1731. field_size = avio_r8(pb);
  1732. }
  1733. entries = avio_rb32(pb);
  1734. av_log(c->fc, AV_LOG_TRACE, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1735. sc->sample_count = entries;
  1736. if (sample_size)
  1737. return 0;
  1738. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1739. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1740. return AVERROR_INVALIDDATA;
  1741. }
  1742. if (!entries)
  1743. return 0;
  1744. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1745. return AVERROR_INVALIDDATA;
  1746. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1747. if (!sc->sample_sizes)
  1748. return AVERROR(ENOMEM);
  1749. num_bytes = (entries*field_size+4)>>3;
  1750. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  1751. if (!buf) {
  1752. av_freep(&sc->sample_sizes);
  1753. return AVERROR(ENOMEM);
  1754. }
  1755. ret = ffio_read_size(pb, buf, num_bytes);
  1756. if (ret < 0) {
  1757. av_freep(&sc->sample_sizes);
  1758. av_free(buf);
  1759. return ret;
  1760. }
  1761. init_get_bits(&gb, buf, 8*num_bytes);
  1762. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1763. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1764. sc->data_size += sc->sample_sizes[i];
  1765. }
  1766. sc->sample_count = i;
  1767. av_free(buf);
  1768. if (pb->eof_reached)
  1769. return AVERROR_EOF;
  1770. return 0;
  1771. }
  1772. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1773. {
  1774. AVStream *st;
  1775. MOVStreamContext *sc;
  1776. unsigned int i, entries;
  1777. int64_t duration=0;
  1778. int64_t total_sample_count=0;
  1779. if (c->fc->nb_streams < 1)
  1780. return 0;
  1781. st = c->fc->streams[c->fc->nb_streams-1];
  1782. sc = st->priv_data;
  1783. avio_r8(pb); /* version */
  1784. avio_rb24(pb); /* flags */
  1785. entries = avio_rb32(pb);
  1786. av_log(c->fc, AV_LOG_TRACE, "track[%i].stts.entries = %i\n",
  1787. c->fc->nb_streams-1, entries);
  1788. if (!entries)
  1789. return 0;
  1790. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1791. return AVERROR(EINVAL);
  1792. av_free(sc->stts_data);
  1793. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1794. if (!sc->stts_data)
  1795. return AVERROR(ENOMEM);
  1796. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1797. int sample_duration;
  1798. int sample_count;
  1799. sample_count=avio_rb32(pb);
  1800. sample_duration = avio_rb32(pb);
  1801. if (sample_count < 0) {
  1802. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1803. return AVERROR_INVALIDDATA;
  1804. }
  1805. sc->stts_data[i].count= sample_count;
  1806. sc->stts_data[i].duration= sample_duration;
  1807. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  1808. sample_count, sample_duration);
  1809. duration+=(int64_t)sample_duration*sample_count;
  1810. total_sample_count+=sample_count;
  1811. }
  1812. sc->stts_count = i;
  1813. if (pb->eof_reached)
  1814. return AVERROR_EOF;
  1815. st->nb_frames= total_sample_count;
  1816. if (duration)
  1817. st->duration= duration;
  1818. sc->track_end = duration;
  1819. return 0;
  1820. }
  1821. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1822. {
  1823. AVStream *st;
  1824. MOVStreamContext *sc;
  1825. unsigned int i, entries;
  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].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1834. av_freep(&sc->ctts_data);
  1835. if (!entries)
  1836. return 0;
  1837. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1838. return AVERROR_INVALIDDATA;
  1839. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  1840. if (!sc->ctts_data)
  1841. return AVERROR(ENOMEM);
  1842. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1843. int count =avio_rb32(pb);
  1844. int duration =avio_rb32(pb);
  1845. sc->ctts_data[i].count = count;
  1846. sc->ctts_data[i].duration= duration;
  1847. if (duration < 0)
  1848. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1849. }
  1850. sc->ctts_count = i;
  1851. if (pb->eof_reached)
  1852. return AVERROR_EOF;
  1853. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  1854. return 0;
  1855. }
  1856. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1857. {
  1858. AVStream *st;
  1859. MOVStreamContext *sc;
  1860. unsigned int i, entries;
  1861. uint8_t version;
  1862. uint32_t grouping_type;
  1863. if (c->fc->nb_streams < 1)
  1864. return 0;
  1865. st = c->fc->streams[c->fc->nb_streams-1];
  1866. sc = st->priv_data;
  1867. version = avio_r8(pb); /* version */
  1868. avio_rb24(pb); /* flags */
  1869. grouping_type = avio_rl32(pb);
  1870. if (grouping_type != MKTAG( 'r','a','p',' '))
  1871. return 0; /* only support 'rap ' grouping */
  1872. if (version == 1)
  1873. avio_rb32(pb); /* grouping_type_parameter */
  1874. entries = avio_rb32(pb);
  1875. if (!entries)
  1876. return 0;
  1877. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1878. return AVERROR_INVALIDDATA;
  1879. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1880. if (!sc->rap_group)
  1881. return AVERROR(ENOMEM);
  1882. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1883. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1884. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1885. }
  1886. sc->rap_group_count = i;
  1887. return pb->eof_reached ? AVERROR_EOF : 0;
  1888. }
  1889. static void mov_build_index(MOVContext *mov, AVStream *st)
  1890. {
  1891. MOVStreamContext *sc = st->priv_data;
  1892. int64_t current_offset;
  1893. int64_t current_dts = 0;
  1894. unsigned int stts_index = 0;
  1895. unsigned int stsc_index = 0;
  1896. unsigned int stss_index = 0;
  1897. unsigned int stps_index = 0;
  1898. unsigned int i, j;
  1899. uint64_t stream_size = 0;
  1900. /* adjust first dts according to edit list */
  1901. if (sc->time_offset && mov->time_scale > 0) {
  1902. if (sc->time_offset < 0)
  1903. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1904. current_dts = -sc->time_offset;
  1905. if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
  1906. sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1907. /* more than 16 frames delay, dts are likely wrong
  1908. this happens with files created by iMovie */
  1909. sc->wrong_dts = 1;
  1910. st->internal->avctx->has_b_frames = 1;
  1911. }
  1912. }
  1913. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1914. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1915. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1916. unsigned int current_sample = 0;
  1917. unsigned int stts_sample = 0;
  1918. unsigned int sample_size;
  1919. unsigned int distance = 0;
  1920. unsigned int rap_group_index = 0;
  1921. unsigned int rap_group_sample = 0;
  1922. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1923. int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
  1924. current_dts -= sc->dts_shift;
  1925. if (!sc->sample_count)
  1926. return;
  1927. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1928. return;
  1929. if (av_reallocp_array(&st->index_entries,
  1930. st->nb_index_entries + sc->sample_count,
  1931. sizeof(*st->index_entries)) < 0) {
  1932. st->nb_index_entries = 0;
  1933. return;
  1934. }
  1935. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1936. for (i = 0; i < sc->chunk_count; i++) {
  1937. current_offset = sc->chunk_offsets[i];
  1938. while (stsc_index + 1 < sc->stsc_count &&
  1939. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1940. stsc_index++;
  1941. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1942. int keyframe = 0;
  1943. if (current_sample >= sc->sample_count) {
  1944. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1945. return;
  1946. }
  1947. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1948. keyframe = 1;
  1949. if (stss_index + 1 < sc->keyframe_count)
  1950. stss_index++;
  1951. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1952. keyframe = 1;
  1953. if (stps_index + 1 < sc->stps_count)
  1954. stps_index++;
  1955. }
  1956. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1957. if (sc->rap_group[rap_group_index].index > 0)
  1958. keyframe = 1;
  1959. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1960. rap_group_sample = 0;
  1961. rap_group_index++;
  1962. }
  1963. }
  1964. if (keyframe)
  1965. distance = 0;
  1966. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1967. if (sc->pseudo_stream_id == -1 ||
  1968. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1969. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1970. e->pos = current_offset;
  1971. e->timestamp = current_dts;
  1972. e->size = sample_size;
  1973. e->min_distance = distance;
  1974. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1975. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1976. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1977. current_offset, current_dts, sample_size, distance, keyframe);
  1978. }
  1979. current_offset += sample_size;
  1980. stream_size += sample_size;
  1981. current_dts += sc->stts_data[stts_index].duration;
  1982. distance++;
  1983. stts_sample++;
  1984. current_sample++;
  1985. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1986. stts_sample = 0;
  1987. stts_index++;
  1988. }
  1989. }
  1990. }
  1991. if (st->duration > 0)
  1992. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1993. } else {
  1994. unsigned chunk_samples, total = 0;
  1995. // compute total chunk count
  1996. for (i = 0; i < sc->stsc_count; i++) {
  1997. unsigned count, chunk_count;
  1998. chunk_samples = sc->stsc_data[i].count;
  1999. if (i != sc->stsc_count - 1 &&
  2000. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2001. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2002. return;
  2003. }
  2004. if (sc->samples_per_frame >= 160) { // gsm
  2005. count = chunk_samples / sc->samples_per_frame;
  2006. } else if (sc->samples_per_frame > 1) {
  2007. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2008. count = (chunk_samples+samples-1) / samples;
  2009. } else {
  2010. count = (chunk_samples+1023) / 1024;
  2011. }
  2012. if (i < sc->stsc_count - 1)
  2013. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2014. else
  2015. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2016. total += chunk_count * count;
  2017. }
  2018. av_log(mov->fc, AV_LOG_TRACE, "chunk count %d\n", total);
  2019. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2020. return;
  2021. if (av_reallocp_array(&st->index_entries,
  2022. st->nb_index_entries + total,
  2023. sizeof(*st->index_entries)) < 0) {
  2024. st->nb_index_entries = 0;
  2025. return;
  2026. }
  2027. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2028. // populate index
  2029. for (i = 0; i < sc->chunk_count; i++) {
  2030. current_offset = sc->chunk_offsets[i];
  2031. if (stsc_index + 1 < sc->stsc_count &&
  2032. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2033. stsc_index++;
  2034. chunk_samples = sc->stsc_data[stsc_index].count;
  2035. while (chunk_samples > 0) {
  2036. AVIndexEntry *e;
  2037. unsigned size, samples;
  2038. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2039. avpriv_request_sample(mov->fc,
  2040. "Zero bytes per frame, but %d samples per frame",
  2041. sc->samples_per_frame);
  2042. return;
  2043. }
  2044. if (sc->samples_per_frame >= 160) { // gsm
  2045. samples = sc->samples_per_frame;
  2046. size = sc->bytes_per_frame;
  2047. } else {
  2048. if (sc->samples_per_frame > 1) {
  2049. samples = FFMIN((1024 / sc->samples_per_frame)*
  2050. sc->samples_per_frame, chunk_samples);
  2051. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2052. } else {
  2053. samples = FFMIN(1024, chunk_samples);
  2054. size = samples * sc->sample_size;
  2055. }
  2056. }
  2057. if (st->nb_index_entries >= total) {
  2058. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  2059. return;
  2060. }
  2061. e = &st->index_entries[st->nb_index_entries++];
  2062. e->pos = current_offset;
  2063. e->timestamp = current_dts;
  2064. e->size = size;
  2065. e->min_distance = 0;
  2066. e->flags = AVINDEX_KEYFRAME;
  2067. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  2068. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  2069. size, samples);
  2070. current_offset += size;
  2071. current_dts += samples;
  2072. chunk_samples -= samples;
  2073. }
  2074. }
  2075. }
  2076. }
  2077. static int mov_open_dref(AVFormatContext *s, AVIOContext **pb, char *src,
  2078. MOVDref *ref)
  2079. {
  2080. /* try relative path, we do not try the absolute because it can leak information about our
  2081. system to an attacker */
  2082. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2083. char filename[1024];
  2084. char *src_path;
  2085. int i, l;
  2086. /* find a source dir */
  2087. src_path = strrchr(src, '/');
  2088. if (src_path)
  2089. src_path++;
  2090. else
  2091. src_path = src;
  2092. /* find a next level down to target */
  2093. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2094. if (ref->path[l] == '/') {
  2095. if (i == ref->nlvl_to - 1)
  2096. break;
  2097. else
  2098. i++;
  2099. }
  2100. /* compose filename if next level down to target was found */
  2101. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2102. memcpy(filename, src, src_path - src);
  2103. filename[src_path - src] = 0;
  2104. for (i = 1; i < ref->nlvl_from; i++)
  2105. av_strlcat(filename, "../", 1024);
  2106. av_strlcat(filename, ref->path + l + 1, 1024);
  2107. if (!s->io_open(s, pb, filename, AVIO_FLAG_READ, NULL))
  2108. return 0;
  2109. }
  2110. }
  2111. return AVERROR(ENOENT);
  2112. }
  2113. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2114. {
  2115. AVStream *st;
  2116. MOVStreamContext *sc;
  2117. int ret;
  2118. st = avformat_new_stream(c->fc, NULL);
  2119. if (!st) return AVERROR(ENOMEM);
  2120. st->id = c->fc->nb_streams;
  2121. sc = av_mallocz(sizeof(MOVStreamContext));
  2122. if (!sc) return AVERROR(ENOMEM);
  2123. st->priv_data = sc;
  2124. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2125. sc->ffindex = st->index;
  2126. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2127. return ret;
  2128. /* sanity checks */
  2129. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2130. (!sc->sample_size && !sc->sample_count))) {
  2131. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2132. st->index);
  2133. return 0;
  2134. }
  2135. if (sc->time_scale <= 0) {
  2136. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  2137. sc->time_scale = c->time_scale;
  2138. if (sc->time_scale <= 0)
  2139. sc->time_scale = 1;
  2140. }
  2141. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2142. mov_build_index(c, st);
  2143. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2144. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2145. if (c->enable_drefs) {
  2146. if (mov_open_dref(c->fc, &sc->pb, c->fc->filename, dref) < 0)
  2147. av_log(c->fc, AV_LOG_ERROR,
  2148. "stream %d, error opening alias: path='%s', dir='%s', "
  2149. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  2150. st->index, dref->path, dref->dir, dref->filename,
  2151. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2152. } else {
  2153. av_log(c->fc, AV_LOG_WARNING,
  2154. "Skipped opening external track: "
  2155. "stream %d, alias: path='%s', dir='%s', "
  2156. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d."
  2157. "Set enable_drefs to allow this.\n",
  2158. st->index, dref->path, dref->dir, dref->filename,
  2159. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2160. }
  2161. } else
  2162. sc->pb = c->fc->pb;
  2163. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  2164. if (!st->sample_aspect_ratio.num &&
  2165. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  2166. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  2167. ((double)st->codecpar->width * sc->height), INT_MAX);
  2168. }
  2169. }
  2170. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2171. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  2172. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  2173. ret = ff_generate_avci_extradata(st);
  2174. if (ret < 0)
  2175. return ret;
  2176. }
  2177. switch (st->codecpar->codec_id) {
  2178. #if CONFIG_H261_DECODER
  2179. case AV_CODEC_ID_H261:
  2180. #endif
  2181. #if CONFIG_H263_DECODER
  2182. case AV_CODEC_ID_H263:
  2183. #endif
  2184. #if CONFIG_MPEG4_DECODER
  2185. case AV_CODEC_ID_MPEG4:
  2186. #endif
  2187. st->codecpar->width = 0; /* let decoder init width/height */
  2188. st->codecpar->height= 0;
  2189. break;
  2190. case AV_CODEC_ID_MP3:
  2191. st->need_parsing = AVSTREAM_PARSE_FULL;
  2192. break;
  2193. }
  2194. /* Do not need those anymore. */
  2195. av_freep(&sc->chunk_offsets);
  2196. av_freep(&sc->stsc_data);
  2197. av_freep(&sc->sample_sizes);
  2198. av_freep(&sc->keyframes);
  2199. av_freep(&sc->stts_data);
  2200. av_freep(&sc->stps_data);
  2201. av_freep(&sc->rap_group);
  2202. return 0;
  2203. }
  2204. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2205. {
  2206. int ret;
  2207. c->itunes_metadata = 1;
  2208. ret = mov_read_default(c, pb, atom);
  2209. c->itunes_metadata = 0;
  2210. return ret;
  2211. }
  2212. static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int64_t size)
  2213. {
  2214. int64_t end = avio_tell(pb) + size;
  2215. uint8_t *key = NULL, *val = NULL;
  2216. int i;
  2217. for (i = 0; i < 2; i++) {
  2218. uint8_t **p;
  2219. uint32_t len, tag;
  2220. int ret;
  2221. if (end - avio_tell(pb) <= 12)
  2222. break;
  2223. len = avio_rb32(pb);
  2224. tag = avio_rl32(pb);
  2225. avio_skip(pb, 4); // flags
  2226. if (len < 12 || len - 12 > end - avio_tell(pb))
  2227. break;
  2228. len -= 12;
  2229. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2230. p = &key;
  2231. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2232. avio_skip(pb, 4);
  2233. len -= 4;
  2234. p = &val;
  2235. } else
  2236. break;
  2237. *p = av_malloc(len + 1);
  2238. if (!*p)
  2239. break;
  2240. ret = ffio_read_size(pb, *p, len);
  2241. if (ret < 0) {
  2242. av_freep(p);
  2243. return ret;
  2244. }
  2245. (*p)[len] = 0;
  2246. }
  2247. if (key && val) {
  2248. av_dict_set(&c->fc->metadata, key, val,
  2249. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2250. key = val = NULL;
  2251. }
  2252. avio_seek(pb, end, SEEK_SET);
  2253. av_freep(&key);
  2254. av_freep(&val);
  2255. return 0;
  2256. }
  2257. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2258. {
  2259. int64_t end = avio_tell(pb) + atom.size;
  2260. uint32_t tag, len;
  2261. if (atom.size < 8)
  2262. goto fail;
  2263. len = avio_rb32(pb);
  2264. tag = avio_rl32(pb);
  2265. if (len > atom.size)
  2266. goto fail;
  2267. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2268. uint8_t domain[128];
  2269. int domain_len;
  2270. avio_skip(pb, 4); // flags
  2271. len -= 12;
  2272. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2273. avio_skip(pb, len - domain_len);
  2274. if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
  2275. return mov_read_replaygain(c, pb, end - avio_tell(pb));
  2276. }
  2277. fail:
  2278. av_log(c->fc, AV_LOG_VERBOSE,
  2279. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2280. return 0;
  2281. }
  2282. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2283. {
  2284. while (atom.size > 8) {
  2285. uint32_t tag = avio_rl32(pb);
  2286. atom.size -= 4;
  2287. if (tag == MKTAG('h','d','l','r')) {
  2288. avio_seek(pb, -8, SEEK_CUR);
  2289. atom.size += 8;
  2290. return mov_read_default(c, pb, atom);
  2291. }
  2292. }
  2293. return 0;
  2294. }
  2295. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2296. {
  2297. int i;
  2298. int width;
  2299. int height;
  2300. int64_t disp_transform[2];
  2301. int display_matrix[3][3];
  2302. AVStream *st;
  2303. MOVStreamContext *sc;
  2304. int version;
  2305. int flags;
  2306. if (c->fc->nb_streams < 1)
  2307. return 0;
  2308. st = c->fc->streams[c->fc->nb_streams-1];
  2309. sc = st->priv_data;
  2310. version = avio_r8(pb);
  2311. flags = avio_rb24(pb);
  2312. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2313. if (version == 1) {
  2314. avio_rb64(pb);
  2315. avio_rb64(pb);
  2316. } else {
  2317. avio_rb32(pb); /* creation time */
  2318. avio_rb32(pb); /* modification time */
  2319. }
  2320. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2321. avio_rb32(pb); /* reserved */
  2322. /* highlevel (considering edits) duration in movie timebase */
  2323. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2324. avio_rb32(pb); /* reserved */
  2325. avio_rb32(pb); /* reserved */
  2326. avio_rb16(pb); /* layer */
  2327. avio_rb16(pb); /* alternate group */
  2328. avio_rb16(pb); /* volume */
  2329. avio_rb16(pb); /* reserved */
  2330. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2331. // they're kept in fixed point format through all calculations
  2332. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2333. // side data, but the scale factor is not needed to calculate aspect ratio
  2334. for (i = 0; i < 3; i++) {
  2335. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2336. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2337. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2338. }
  2339. width = avio_rb32(pb); // 16.16 fixed point track width
  2340. height = avio_rb32(pb); // 16.16 fixed point track height
  2341. sc->width = width >> 16;
  2342. sc->height = height >> 16;
  2343. // save the matrix when it is not the default identity
  2344. if (display_matrix[0][0] != (1 << 16) ||
  2345. display_matrix[1][1] != (1 << 16) ||
  2346. display_matrix[2][2] != (1 << 30) ||
  2347. display_matrix[0][1] || display_matrix[0][2] ||
  2348. display_matrix[1][0] || display_matrix[1][2] ||
  2349. display_matrix[2][0] || display_matrix[2][1]) {
  2350. int i, j;
  2351. av_freep(&sc->display_matrix);
  2352. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2353. if (!sc->display_matrix)
  2354. return AVERROR(ENOMEM);
  2355. for (i = 0; i < 3; i++)
  2356. for (j = 0; j < 3; j++)
  2357. sc->display_matrix[i * 3 + j] = display_matrix[i][j];
  2358. }
  2359. // transform the display width/height according to the matrix
  2360. // skip this when the display matrix is the identity one
  2361. // to keep the same scale, use [width height 1<<16]
  2362. if (width && height && sc->display_matrix) {
  2363. for (i = 0; i < 2; i++)
  2364. disp_transform[i] =
  2365. (int64_t) width * display_matrix[0][i] +
  2366. (int64_t) height * display_matrix[1][i] +
  2367. ((int64_t) display_matrix[2][i] << 16);
  2368. //sample aspect ratio is new width/height divided by old width/height
  2369. if (disp_transform[0] > 0 && disp_transform[1] > 0)
  2370. st->sample_aspect_ratio = av_d2q(
  2371. ((double) disp_transform[0] * height) /
  2372. ((double) disp_transform[1] * width), INT_MAX);
  2373. }
  2374. return 0;
  2375. }
  2376. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2377. {
  2378. MOVFragment *frag = &c->fragment;
  2379. MOVTrackExt *trex = NULL;
  2380. int flags, track_id, i;
  2381. avio_r8(pb); /* version */
  2382. flags = avio_rb24(pb);
  2383. track_id = avio_rb32(pb);
  2384. if (!track_id)
  2385. return AVERROR_INVALIDDATA;
  2386. frag->track_id = track_id;
  2387. for (i = 0; i < c->trex_count; i++)
  2388. if (c->trex_data[i].track_id == frag->track_id) {
  2389. trex = &c->trex_data[i];
  2390. break;
  2391. }
  2392. if (!trex) {
  2393. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2394. return AVERROR_INVALIDDATA;
  2395. }
  2396. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2397. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2398. frag->moof_offset : frag->implicit_offset;
  2399. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2400. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2401. avio_rb32(pb) : trex->duration;
  2402. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2403. avio_rb32(pb) : trex->size;
  2404. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2405. avio_rb32(pb) : trex->flags;
  2406. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  2407. return 0;
  2408. }
  2409. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2410. {
  2411. c->chapter_track = avio_rb32(pb);
  2412. return 0;
  2413. }
  2414. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2415. {
  2416. MOVTrackExt *trex;
  2417. int err;
  2418. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2419. return AVERROR_INVALIDDATA;
  2420. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2421. sizeof(*c->trex_data))) < 0) {
  2422. c->trex_count = 0;
  2423. return err;
  2424. }
  2425. trex = &c->trex_data[c->trex_count++];
  2426. avio_r8(pb); /* version */
  2427. avio_rb24(pb); /* flags */
  2428. trex->track_id = avio_rb32(pb);
  2429. trex->stsd_id = avio_rb32(pb);
  2430. trex->duration = avio_rb32(pb);
  2431. trex->size = avio_rb32(pb);
  2432. trex->flags = avio_rb32(pb);
  2433. return 0;
  2434. }
  2435. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2436. {
  2437. MOVFragment *frag = &c->fragment;
  2438. AVStream *st = NULL;
  2439. MOVStreamContext *sc;
  2440. int version, i;
  2441. for (i = 0; i < c->fc->nb_streams; i++) {
  2442. if (c->fc->streams[i]->id == frag->track_id) {
  2443. st = c->fc->streams[i];
  2444. break;
  2445. }
  2446. }
  2447. if (!st) {
  2448. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2449. return AVERROR_INVALIDDATA;
  2450. }
  2451. sc = st->priv_data;
  2452. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  2453. return 0;
  2454. version = avio_r8(pb);
  2455. avio_rb24(pb); /* flags */
  2456. if (version) {
  2457. sc->track_end = avio_rb64(pb);
  2458. } else {
  2459. sc->track_end = avio_rb32(pb);
  2460. }
  2461. return 0;
  2462. }
  2463. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2464. {
  2465. MOVFragment *frag = &c->fragment;
  2466. AVStream *st = NULL;
  2467. MOVStreamContext *sc;
  2468. MOVStts *ctts_data;
  2469. uint64_t offset;
  2470. int64_t dts;
  2471. int data_offset = 0;
  2472. unsigned entries, first_sample_flags = frag->flags;
  2473. int flags, distance, i, err;
  2474. for (i = 0; i < c->fc->nb_streams; i++) {
  2475. if (c->fc->streams[i]->id == frag->track_id) {
  2476. st = c->fc->streams[i];
  2477. break;
  2478. }
  2479. }
  2480. if (!st) {
  2481. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2482. return AVERROR_INVALIDDATA;
  2483. }
  2484. sc = st->priv_data;
  2485. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  2486. return 0;
  2487. avio_r8(pb); /* version */
  2488. flags = avio_rb24(pb);
  2489. entries = avio_rb32(pb);
  2490. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %d\n", flags, entries);
  2491. /* Always assume the presence of composition time offsets.
  2492. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2493. * 1) in the initial movie, there are no samples.
  2494. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2495. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2496. if (!sc->ctts_count && sc->sample_count)
  2497. {
  2498. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2499. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2500. if (!ctts_data)
  2501. return AVERROR(ENOMEM);
  2502. sc->ctts_data = ctts_data;
  2503. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2504. sc->ctts_data[sc->ctts_count].duration = 0;
  2505. sc->ctts_count++;
  2506. }
  2507. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2508. return AVERROR_INVALIDDATA;
  2509. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2510. sizeof(*sc->ctts_data))) < 0) {
  2511. sc->ctts_count = 0;
  2512. return err;
  2513. }
  2514. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2515. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2516. dts = sc->track_end - sc->time_offset;
  2517. offset = frag->base_data_offset + data_offset;
  2518. distance = 0;
  2519. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  2520. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2521. unsigned sample_size = frag->size;
  2522. int sample_flags = i ? frag->flags : first_sample_flags;
  2523. unsigned sample_duration = frag->duration;
  2524. int keyframe = 0;
  2525. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2526. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2527. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2528. sc->ctts_data[sc->ctts_count].count = 1;
  2529. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2530. avio_rb32(pb) : 0;
  2531. sc->ctts_count++;
  2532. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  2533. keyframe = 1;
  2534. else
  2535. keyframe =
  2536. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2537. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2538. if (keyframe)
  2539. distance = 0;
  2540. av_add_index_entry(st, offset, dts, sample_size, distance,
  2541. keyframe ? AVINDEX_KEYFRAME : 0);
  2542. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2543. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2544. offset, dts, sample_size, distance, keyframe);
  2545. distance++;
  2546. dts += sample_duration;
  2547. offset += sample_size;
  2548. sc->data_size += sample_size;
  2549. }
  2550. if (pb->eof_reached)
  2551. return AVERROR_EOF;
  2552. frag->implicit_offset = offset;
  2553. st->duration = sc->track_end = dts + sc->time_offset;
  2554. return 0;
  2555. }
  2556. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2557. /* like the files created with Adobe Premiere 5.0, for samples see */
  2558. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2559. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2560. {
  2561. int err;
  2562. if (atom.size < 8)
  2563. return 0; /* continue */
  2564. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2565. avio_skip(pb, atom.size - 4);
  2566. return 0;
  2567. }
  2568. atom.type = avio_rl32(pb);
  2569. atom.size -= 8;
  2570. if (atom.type != MKTAG('m','d','a','t')) {
  2571. avio_skip(pb, atom.size);
  2572. return 0;
  2573. }
  2574. err = mov_read_mdat(c, pb, atom);
  2575. return err;
  2576. }
  2577. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2578. {
  2579. #if CONFIG_ZLIB
  2580. AVIOContext ctx;
  2581. uint8_t *cmov_data;
  2582. uint8_t *moov_data; /* uncompressed data */
  2583. long cmov_len, moov_len;
  2584. int ret = -1;
  2585. avio_rb32(pb); /* dcom atom */
  2586. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2587. return AVERROR_INVALIDDATA;
  2588. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2589. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  2590. return AVERROR_INVALIDDATA;
  2591. }
  2592. avio_rb32(pb); /* cmvd atom */
  2593. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2594. return AVERROR_INVALIDDATA;
  2595. moov_len = avio_rb32(pb); /* uncompressed size */
  2596. cmov_len = atom.size - 6 * 4;
  2597. cmov_data = av_malloc(cmov_len);
  2598. if (!cmov_data)
  2599. return AVERROR(ENOMEM);
  2600. moov_data = av_malloc(moov_len);
  2601. if (!moov_data) {
  2602. av_free(cmov_data);
  2603. return AVERROR(ENOMEM);
  2604. }
  2605. ret = ffio_read_size(pb, cmov_data, cmov_len);
  2606. if (ret < 0)
  2607. goto free_and_return;
  2608. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2609. goto free_and_return;
  2610. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2611. goto free_and_return;
  2612. atom.type = MKTAG('m','o','o','v');
  2613. atom.size = moov_len;
  2614. ret = mov_read_default(c, &ctx, atom);
  2615. free_and_return:
  2616. av_free(moov_data);
  2617. av_free(cmov_data);
  2618. return ret;
  2619. #else
  2620. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2621. return AVERROR(ENOSYS);
  2622. #endif
  2623. }
  2624. /* edit list atom */
  2625. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2626. {
  2627. MOVStreamContext *sc;
  2628. int i, edit_count, version;
  2629. if (c->fc->nb_streams < 1)
  2630. return 0;
  2631. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2632. version = avio_r8(pb); /* version */
  2633. avio_rb24(pb); /* flags */
  2634. edit_count = avio_rb32(pb); /* entries */
  2635. if ((uint64_t)edit_count*12+8 > atom.size)
  2636. return AVERROR_INVALIDDATA;
  2637. for (i=0; i<edit_count; i++){
  2638. int64_t time;
  2639. int64_t duration;
  2640. if (version == 1) {
  2641. duration = avio_rb64(pb);
  2642. time = avio_rb64(pb);
  2643. } else {
  2644. duration = avio_rb32(pb); /* segment duration */
  2645. time = (int32_t)avio_rb32(pb); /* media time */
  2646. }
  2647. avio_rb32(pb); /* Media rate */
  2648. if (i == 0 && time >= -1) {
  2649. sc->time_offset = time != -1 ? time : -duration;
  2650. }
  2651. }
  2652. if (edit_count > 1)
  2653. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2654. "a/v desync might occur, patch welcome\n");
  2655. av_log(c->fc, AV_LOG_TRACE, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2656. return 0;
  2657. }
  2658. static const MOVParseTableEntry mov_default_parse_table[] = {
  2659. { MKTAG('a','v','s','s'), mov_read_extradata },
  2660. { MKTAG('c','h','p','l'), mov_read_chpl },
  2661. { MKTAG('c','o','6','4'), mov_read_stco },
  2662. { MKTAG('c','o','l','r'), mov_read_colr },
  2663. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2664. { MKTAG('d','i','n','f'), mov_read_default },
  2665. { MKTAG('d','r','e','f'), mov_read_dref },
  2666. { MKTAG('e','d','t','s'), mov_read_default },
  2667. { MKTAG('e','l','s','t'), mov_read_elst },
  2668. { MKTAG('e','n','d','a'), mov_read_enda },
  2669. { MKTAG('f','i','e','l'), mov_read_fiel },
  2670. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2671. { MKTAG('g','l','b','l'), mov_read_glbl },
  2672. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2673. { MKTAG('i','l','s','t'), mov_read_ilst },
  2674. { MKTAG('j','p','2','h'), mov_read_extradata },
  2675. { MKTAG('m','d','a','t'), mov_read_mdat },
  2676. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2677. { MKTAG('m','d','i','a'), mov_read_default },
  2678. { MKTAG('m','e','t','a'), mov_read_meta },
  2679. { MKTAG('m','i','n','f'), mov_read_default },
  2680. { MKTAG('m','o','o','f'), mov_read_moof },
  2681. { MKTAG('m','o','o','v'), mov_read_moov },
  2682. { MKTAG('m','v','e','x'), mov_read_default },
  2683. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2684. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  2685. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  2686. { MKTAG('a','v','c','C'), mov_read_glbl },
  2687. { MKTAG('p','a','s','p'), mov_read_pasp },
  2688. { MKTAG('s','t','b','l'), mov_read_default },
  2689. { MKTAG('s','t','c','o'), mov_read_stco },
  2690. { MKTAG('s','t','p','s'), mov_read_stps },
  2691. { MKTAG('s','t','r','f'), mov_read_strf },
  2692. { MKTAG('s','t','s','c'), mov_read_stsc },
  2693. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2694. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2695. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2696. { MKTAG('s','t','t','s'), mov_read_stts },
  2697. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2698. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2699. { MKTAG('t','f','d','t'), mov_read_tfdt },
  2700. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2701. { MKTAG('t','r','a','k'), mov_read_trak },
  2702. { MKTAG('t','r','a','f'), mov_read_default },
  2703. { MKTAG('t','r','e','f'), mov_read_default },
  2704. { MKTAG('c','h','a','p'), mov_read_chap },
  2705. { MKTAG('t','r','e','x'), mov_read_trex },
  2706. { MKTAG('t','r','u','n'), mov_read_trun },
  2707. { MKTAG('u','d','t','a'), mov_read_default },
  2708. { MKTAG('w','a','v','e'), mov_read_wave },
  2709. { MKTAG('e','s','d','s'), mov_read_esds },
  2710. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2711. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2712. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2713. { MKTAG('w','f','e','x'), mov_read_wfex },
  2714. { MKTAG('c','m','o','v'), mov_read_cmov },
  2715. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2716. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2717. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2718. { MKTAG('h','v','c','C'), mov_read_glbl },
  2719. { MKTAG('-','-','-','-'), mov_read_custom },
  2720. { 0, NULL }
  2721. };
  2722. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2723. {
  2724. int64_t total_size = 0;
  2725. MOVAtom a;
  2726. int i;
  2727. if (atom.size < 0)
  2728. atom.size = INT64_MAX;
  2729. while (total_size + 8 < atom.size && !pb->eof_reached) {
  2730. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2731. a.size = atom.size;
  2732. a.type=0;
  2733. if (atom.size >= 8) {
  2734. a.size = avio_rb32(pb);
  2735. a.type = avio_rl32(pb);
  2736. }
  2737. av_log(c->fc, AV_LOG_TRACE, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2738. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2739. total_size += 8;
  2740. if (a.size == 1) { /* 64 bit extended size */
  2741. a.size = avio_rb64(pb) - 8;
  2742. total_size += 8;
  2743. }
  2744. if (a.size == 0) {
  2745. a.size = atom.size - total_size;
  2746. if (a.size <= 8)
  2747. break;
  2748. }
  2749. a.size -= 8;
  2750. if (a.size < 0)
  2751. break;
  2752. a.size = FFMIN(a.size, atom.size - total_size);
  2753. for (i = 0; mov_default_parse_table[i].type; i++)
  2754. if (mov_default_parse_table[i].type == a.type) {
  2755. parse = mov_default_parse_table[i].parse;
  2756. break;
  2757. }
  2758. // container is user data
  2759. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2760. atom.type == MKTAG('i','l','s','t')))
  2761. parse = mov_read_udta_string;
  2762. if (!parse) { /* skip leaf atoms data */
  2763. avio_skip(pb, a.size);
  2764. } else {
  2765. int64_t start_pos = avio_tell(pb);
  2766. int64_t left;
  2767. int err = parse(c, pb, a);
  2768. if (err < 0)
  2769. return err;
  2770. if (c->found_moov && c->found_mdat &&
  2771. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2772. start_pos + a.size == avio_size(pb))) {
  2773. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2774. c->next_root_atom = start_pos + a.size;
  2775. return 0;
  2776. }
  2777. left = a.size - avio_tell(pb) + start_pos;
  2778. if (left > 0) /* skip garbage at atom end */
  2779. avio_skip(pb, left);
  2780. else if (left < 0) {
  2781. av_log(c->fc, AV_LOG_WARNING,
  2782. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  2783. (char*)&a.type, -left);
  2784. avio_seek(pb, left, SEEK_CUR);
  2785. }
  2786. }
  2787. total_size += a.size;
  2788. }
  2789. if (total_size < atom.size && atom.size < 0x7ffff)
  2790. avio_skip(pb, atom.size - total_size);
  2791. return 0;
  2792. }
  2793. static int mov_probe(AVProbeData *p)
  2794. {
  2795. unsigned int offset;
  2796. uint32_t tag;
  2797. int score = 0;
  2798. /* check file header */
  2799. offset = 0;
  2800. for (;;) {
  2801. /* ignore invalid offset */
  2802. if ((offset + 8) > (unsigned int)p->buf_size)
  2803. return score;
  2804. tag = AV_RL32(p->buf + offset + 4);
  2805. switch(tag) {
  2806. /* check for obvious tags */
  2807. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2808. case MKTAG('m','o','o','v'):
  2809. case MKTAG('m','d','a','t'):
  2810. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2811. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2812. case MKTAG('f','t','y','p'):
  2813. return AVPROBE_SCORE_MAX;
  2814. /* those are more common words, so rate then a bit less */
  2815. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2816. case MKTAG('w','i','d','e'):
  2817. case MKTAG('f','r','e','e'):
  2818. case MKTAG('j','u','n','k'):
  2819. case MKTAG('p','i','c','t'):
  2820. return AVPROBE_SCORE_MAX - 5;
  2821. case MKTAG(0x82,0x82,0x7f,0x7d):
  2822. case MKTAG('s','k','i','p'):
  2823. case MKTAG('u','u','i','d'):
  2824. case MKTAG('p','r','f','l'):
  2825. offset = AV_RB32(p->buf+offset) + offset;
  2826. /* if we only find those cause probedata is too small at least rate them */
  2827. score = AVPROBE_SCORE_EXTENSION;
  2828. break;
  2829. default:
  2830. /* unrecognized tag */
  2831. return score;
  2832. }
  2833. }
  2834. }
  2835. // must be done after parsing all trak because there's no order requirement
  2836. static void mov_read_chapters(AVFormatContext *s)
  2837. {
  2838. MOVContext *mov = s->priv_data;
  2839. AVStream *st = NULL;
  2840. MOVStreamContext *sc;
  2841. int64_t cur_pos;
  2842. int i;
  2843. for (i = 0; i < s->nb_streams; i++)
  2844. if (s->streams[i]->id == mov->chapter_track) {
  2845. st = s->streams[i];
  2846. break;
  2847. }
  2848. if (!st) {
  2849. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2850. return;
  2851. }
  2852. st->discard = AVDISCARD_ALL;
  2853. sc = st->priv_data;
  2854. cur_pos = avio_tell(sc->pb);
  2855. for (i = 0; i < st->nb_index_entries; i++) {
  2856. AVIndexEntry *sample = &st->index_entries[i];
  2857. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2858. uint8_t *title;
  2859. uint16_t ch;
  2860. int len, title_len;
  2861. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2862. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2863. goto finish;
  2864. }
  2865. // the first two bytes are the length of the title
  2866. len = avio_rb16(sc->pb);
  2867. if (len > sample->size-2)
  2868. continue;
  2869. title_len = 2*len + 1;
  2870. if (!(title = av_mallocz(title_len)))
  2871. goto finish;
  2872. // The samples could theoretically be in any encoding if there's an encd
  2873. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2874. // instead by the presence of a BOM
  2875. if (!len) {
  2876. title[0] = 0;
  2877. } else {
  2878. ch = avio_rb16(sc->pb);
  2879. if (ch == 0xfeff)
  2880. avio_get_str16be(sc->pb, len, title, title_len);
  2881. else if (ch == 0xfffe)
  2882. avio_get_str16le(sc->pb, len, title, title_len);
  2883. else {
  2884. AV_WB16(title, ch);
  2885. if (len == 1 || len == 2)
  2886. title[len] = 0;
  2887. else
  2888. avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
  2889. }
  2890. }
  2891. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2892. av_freep(&title);
  2893. }
  2894. finish:
  2895. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2896. }
  2897. static int mov_read_close(AVFormatContext *s)
  2898. {
  2899. MOVContext *mov = s->priv_data;
  2900. int i, j;
  2901. for (i = 0; i < s->nb_streams; i++) {
  2902. AVStream *st = s->streams[i];
  2903. MOVStreamContext *sc = st->priv_data;
  2904. av_freep(&sc->ctts_data);
  2905. for (j = 0; j < sc->drefs_count; j++) {
  2906. av_freep(&sc->drefs[j].path);
  2907. av_freep(&sc->drefs[j].dir);
  2908. }
  2909. av_freep(&sc->drefs);
  2910. if (sc->pb && sc->pb != s->pb)
  2911. ff_format_io_close(s, &sc->pb);
  2912. av_freep(&sc->chunk_offsets);
  2913. av_freep(&sc->stsc_data);
  2914. av_freep(&sc->sample_sizes);
  2915. av_freep(&sc->keyframes);
  2916. av_freep(&sc->stts_data);
  2917. av_freep(&sc->stps_data);
  2918. av_freep(&sc->rap_group);
  2919. av_freep(&sc->display_matrix);
  2920. }
  2921. if (mov->dv_demux) {
  2922. avformat_free_context(mov->dv_fctx);
  2923. mov->dv_fctx = NULL;
  2924. }
  2925. av_freep(&mov->trex_data);
  2926. return 0;
  2927. }
  2928. static int mov_read_header(AVFormatContext *s)
  2929. {
  2930. MOVContext *mov = s->priv_data;
  2931. AVIOContext *pb = s->pb;
  2932. int err;
  2933. MOVAtom atom = { AV_RL32("root") };
  2934. int i;
  2935. mov->fc = s;
  2936. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2937. if (pb->seekable)
  2938. atom.size = avio_size(pb);
  2939. else
  2940. atom.size = INT64_MAX;
  2941. /* check MOV header */
  2942. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2943. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2944. mov_read_close(s);
  2945. return err;
  2946. }
  2947. if (!mov->found_moov) {
  2948. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2949. mov_read_close(s);
  2950. return AVERROR_INVALIDDATA;
  2951. }
  2952. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2953. if (pb->seekable && mov->chapter_track > 0)
  2954. mov_read_chapters(s);
  2955. for (i = 0; i < s->nb_streams; i++) {
  2956. AVStream *st = s->streams[i];
  2957. MOVStreamContext *sc = st->priv_data;
  2958. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2959. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  2960. st->codecpar->width = sc->width;
  2961. st->codecpar->height = sc->height;
  2962. }
  2963. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  2964. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  2965. return err;
  2966. }
  2967. }
  2968. }
  2969. if (mov->trex_data) {
  2970. for (i = 0; i < s->nb_streams; i++) {
  2971. AVStream *st = s->streams[i];
  2972. MOVStreamContext *sc = st->priv_data;
  2973. if (st->duration > 0)
  2974. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  2975. }
  2976. }
  2977. for (i = 0; i < s->nb_streams; i++) {
  2978. AVStream *st = s->streams[i];
  2979. MOVStreamContext *sc = st->priv_data;
  2980. switch (st->codecpar->codec_type) {
  2981. case AVMEDIA_TYPE_AUDIO:
  2982. err = ff_replaygain_export(st, s->metadata);
  2983. if (err < 0) {
  2984. mov_read_close(s);
  2985. return err;
  2986. }
  2987. break;
  2988. case AVMEDIA_TYPE_VIDEO:
  2989. if (sc->display_matrix) {
  2990. AVPacketSideData *sd, *tmp;
  2991. tmp = av_realloc_array(st->side_data,
  2992. st->nb_side_data + 1, sizeof(*tmp));
  2993. if (!tmp)
  2994. return AVERROR(ENOMEM);
  2995. st->side_data = tmp;
  2996. st->nb_side_data++;
  2997. sd = &st->side_data[st->nb_side_data - 1];
  2998. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  2999. sd->size = sizeof(int32_t) * 9;
  3000. sd->data = (uint8_t*)sc->display_matrix;
  3001. sc->display_matrix = NULL;
  3002. }
  3003. break;
  3004. }
  3005. }
  3006. return 0;
  3007. }
  3008. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  3009. {
  3010. AVIndexEntry *sample = NULL;
  3011. int64_t best_dts = INT64_MAX;
  3012. int i;
  3013. for (i = 0; i < s->nb_streams; i++) {
  3014. AVStream *avst = s->streams[i];
  3015. MOVStreamContext *msc = avst->priv_data;
  3016. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  3017. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  3018. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  3019. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  3020. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  3021. (s->pb->seekable &&
  3022. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  3023. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  3024. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  3025. sample = current_sample;
  3026. best_dts = dts;
  3027. *st = avst;
  3028. }
  3029. }
  3030. }
  3031. return sample;
  3032. }
  3033. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  3034. {
  3035. MOVContext *mov = s->priv_data;
  3036. MOVStreamContext *sc;
  3037. AVIndexEntry *sample;
  3038. AVStream *st = NULL;
  3039. int ret;
  3040. retry:
  3041. sample = mov_find_next_sample(s, &st);
  3042. if (!sample) {
  3043. mov->found_mdat = 0;
  3044. if (!mov->next_root_atom)
  3045. return AVERROR_EOF;
  3046. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  3047. mov->next_root_atom = 0;
  3048. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  3049. s->pb->eof_reached)
  3050. return AVERROR_EOF;
  3051. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  3052. goto retry;
  3053. }
  3054. sc = st->priv_data;
  3055. /* must be done just before reading, to avoid infinite loop on sample */
  3056. sc->current_sample++;
  3057. if (st->discard != AVDISCARD_ALL) {
  3058. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3059. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  3060. sc->ffindex, sample->pos);
  3061. return AVERROR_INVALIDDATA;
  3062. }
  3063. ret = av_get_packet(sc->pb, pkt, sample->size);
  3064. if (ret < 0)
  3065. return ret;
  3066. if (sc->has_palette) {
  3067. uint8_t *pal;
  3068. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  3069. if (!pal) {
  3070. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  3071. } else {
  3072. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  3073. sc->has_palette = 0;
  3074. }
  3075. }
  3076. #if CONFIG_DV_DEMUXER
  3077. if (mov->dv_demux && sc->dv_audio_container) {
  3078. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  3079. av_free(pkt->data);
  3080. pkt->size = 0;
  3081. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  3082. if (ret < 0)
  3083. return ret;
  3084. }
  3085. #endif
  3086. }
  3087. pkt->stream_index = sc->ffindex;
  3088. pkt->dts = sample->timestamp;
  3089. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  3090. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  3091. /* update ctts context */
  3092. sc->ctts_sample++;
  3093. if (sc->ctts_index < sc->ctts_count &&
  3094. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  3095. sc->ctts_index++;
  3096. sc->ctts_sample = 0;
  3097. }
  3098. if (sc->wrong_dts)
  3099. pkt->dts = AV_NOPTS_VALUE;
  3100. } else {
  3101. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  3102. st->index_entries[sc->current_sample].timestamp : st->duration;
  3103. pkt->duration = next_dts - pkt->dts;
  3104. pkt->pts = pkt->dts;
  3105. }
  3106. if (st->discard == AVDISCARD_ALL)
  3107. goto retry;
  3108. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  3109. pkt->pos = sample->pos;
  3110. av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
  3111. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  3112. return 0;
  3113. }
  3114. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  3115. {
  3116. MOVStreamContext *sc = st->priv_data;
  3117. int sample, time_sample;
  3118. int i;
  3119. sample = av_index_search_timestamp(st, timestamp, flags);
  3120. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  3121. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  3122. sample = 0;
  3123. if (sample < 0) /* not sure what to do */
  3124. return AVERROR_INVALIDDATA;
  3125. sc->current_sample = sample;
  3126. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  3127. /* adjust ctts index */
  3128. if (sc->ctts_data) {
  3129. time_sample = 0;
  3130. for (i = 0; i < sc->ctts_count; i++) {
  3131. int next = time_sample + sc->ctts_data[i].count;
  3132. if (next > sc->current_sample) {
  3133. sc->ctts_index = i;
  3134. sc->ctts_sample = sc->current_sample - time_sample;
  3135. break;
  3136. }
  3137. time_sample = next;
  3138. }
  3139. }
  3140. return sample;
  3141. }
  3142. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  3143. {
  3144. MOVContext *mc = s->priv_data;
  3145. AVStream *st;
  3146. int sample;
  3147. int i;
  3148. if (stream_index >= s->nb_streams)
  3149. return AVERROR_INVALIDDATA;
  3150. if (sample_time < 0)
  3151. sample_time = 0;
  3152. st = s->streams[stream_index];
  3153. sample = mov_seek_stream(s, st, sample_time, flags);
  3154. if (sample < 0)
  3155. return sample;
  3156. if (mc->seek_individually) {
  3157. /* adjust seek timestamp to found sample timestamp */
  3158. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  3159. for (i = 0; i < s->nb_streams; i++) {
  3160. int64_t timestamp;
  3161. st = s->streams[i];
  3162. if (stream_index == i)
  3163. continue;
  3164. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  3165. mov_seek_stream(s, st, timestamp, flags);
  3166. }
  3167. } else {
  3168. for (i = 0; i < s->nb_streams; i++) {
  3169. MOVStreamContext *sc;
  3170. st = s->streams[i];
  3171. sc = st->priv_data;
  3172. sc->current_sample = 0;
  3173. }
  3174. while (1) {
  3175. MOVStreamContext *sc;
  3176. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  3177. if (!entry)
  3178. return AVERROR_INVALIDDATA;
  3179. sc = st->priv_data;
  3180. if (sc->ffindex == stream_index && sc->current_sample == sample)
  3181. break;
  3182. sc->current_sample++;
  3183. }
  3184. }
  3185. return 0;
  3186. }
  3187. #define OFFSET(x) offsetof(MOVContext, x)
  3188. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  3189. static const AVOption mov_options[] = {
  3190. {"seek_streams_individually",
  3191. "Seek each stream individually to the to the closest point",
  3192. OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
  3193. 0, 1, FLAGS},
  3194. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  3195. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3196. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  3197. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3198. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs),
  3199. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3200. { NULL },
  3201. };
  3202. static const AVClass mov_class = {
  3203. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  3204. .item_name = av_default_item_name,
  3205. .option = mov_options,
  3206. .version = LIBAVUTIL_VERSION_INT,
  3207. };
  3208. AVInputFormat ff_mov_demuxer = {
  3209. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  3210. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3211. .priv_class = &mov_class,
  3212. .priv_data_size = sizeof(MOVContext),
  3213. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  3214. .read_probe = mov_probe,
  3215. .read_header = mov_read_header,
  3216. .read_packet = mov_read_packet,
  3217. .read_close = mov_read_close,
  3218. .read_seek = mov_read_seek,
  3219. };