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.

4110 lines
134KB

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