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.

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