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.

4129 lines
135KB

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