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.

4143 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 0;
  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 (entries <= 0) {
  1618. av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries);
  1619. return AVERROR_INVALIDDATA;
  1620. }
  1621. if (sc->extradata) {
  1622. av_log(c->fc, AV_LOG_ERROR,
  1623. "Duplicate stsd found in this track.\n");
  1624. return AVERROR_INVALIDDATA;
  1625. }
  1626. /* Prepare space for hosting multiple extradata. */
  1627. sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata));
  1628. if (!sc->extradata)
  1629. return AVERROR(ENOMEM);
  1630. sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size));
  1631. if (!sc->extradata_size) {
  1632. ret = AVERROR(ENOMEM);
  1633. goto fail;
  1634. }
  1635. ret = ff_mov_read_stsd_entries(c, pb, entries);
  1636. if (ret < 0)
  1637. goto fail;
  1638. sc->stsd_count = entries;
  1639. /* Restore back the primary extradata. */
  1640. av_free(st->codecpar->extradata);
  1641. st->codecpar->extradata_size = sc->extradata_size[0];
  1642. st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);
  1643. if (!st->codecpar->extradata) {
  1644. ret = AVERROR(ENOMEM);
  1645. goto fail;
  1646. }
  1647. memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);
  1648. return mov_finalize_stsd_codec(c, pb, st, sc);
  1649. fail:
  1650. av_freep(&sc->extradata);
  1651. av_freep(&sc->extradata_size);
  1652. return ret;
  1653. }
  1654. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1655. {
  1656. AVStream *st;
  1657. MOVStreamContext *sc;
  1658. unsigned int i, entries;
  1659. if (c->fc->nb_streams < 1)
  1660. return 0;
  1661. st = c->fc->streams[c->fc->nb_streams-1];
  1662. sc = st->priv_data;
  1663. avio_r8(pb); /* version */
  1664. avio_rb24(pb); /* flags */
  1665. entries = avio_rb32(pb);
  1666. av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries);
  1667. if (!entries)
  1668. return 0;
  1669. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1670. return AVERROR_INVALIDDATA;
  1671. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1672. if (!sc->stsc_data)
  1673. return AVERROR(ENOMEM);
  1674. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1675. sc->stsc_data[i].first = avio_rb32(pb);
  1676. sc->stsc_data[i].count = avio_rb32(pb);
  1677. sc->stsc_data[i].id = avio_rb32(pb);
  1678. if (sc->stsc_data[i].id <= 0 || sc->stsc_data[i].id > sc->stsd_count) {
  1679. sc->stsc_data[i].id = 1;
  1680. if (c->fc->error_recognition & AV_EF_EXPLODE) {
  1681. av_log(c->fc, AV_LOG_ERROR, "Invalid stsc index.\n");
  1682. return AVERROR_INVALIDDATA;
  1683. }
  1684. }
  1685. }
  1686. sc->stsc_count = i;
  1687. if (pb->eof_reached)
  1688. return AVERROR_EOF;
  1689. return 0;
  1690. }
  1691. static inline int mov_stsc_index_valid(unsigned int index, unsigned int count)
  1692. {
  1693. return index < count - 1;
  1694. }
  1695. /* Compute the samples value for the stsc entry at the given index. */
  1696. static inline int mov_get_stsc_samples(MOVStreamContext *sc, unsigned int index)
  1697. {
  1698. int chunk_count;
  1699. if (mov_stsc_index_valid(index, sc->stsc_count))
  1700. chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first;
  1701. else
  1702. chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1);
  1703. return sc->stsc_data[index].count * chunk_count;
  1704. }
  1705. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1706. {
  1707. AVStream *st;
  1708. MOVStreamContext *sc;
  1709. unsigned i, entries;
  1710. if (c->fc->nb_streams < 1)
  1711. return 0;
  1712. st = c->fc->streams[c->fc->nb_streams-1];
  1713. sc = st->priv_data;
  1714. avio_rb32(pb); // version + flags
  1715. entries = avio_rb32(pb);
  1716. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1717. return AVERROR_INVALIDDATA;
  1718. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1719. if (!sc->stps_data)
  1720. return AVERROR(ENOMEM);
  1721. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1722. sc->stps_data[i] = avio_rb32(pb);
  1723. }
  1724. sc->stps_count = i;
  1725. if (pb->eof_reached)
  1726. return AVERROR_EOF;
  1727. return 0;
  1728. }
  1729. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1730. {
  1731. AVStream *st;
  1732. MOVStreamContext *sc;
  1733. unsigned int i, entries;
  1734. if (c->fc->nb_streams < 1)
  1735. return 0;
  1736. st = c->fc->streams[c->fc->nb_streams-1];
  1737. sc = st->priv_data;
  1738. avio_r8(pb); /* version */
  1739. avio_rb24(pb); /* flags */
  1740. entries = avio_rb32(pb);
  1741. av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries);
  1742. if (!entries)
  1743. {
  1744. sc->keyframe_absent = 1;
  1745. return 0;
  1746. }
  1747. if (entries >= UINT_MAX / sizeof(int))
  1748. return AVERROR_INVALIDDATA;
  1749. av_freep(&sc->keyframes);
  1750. sc->keyframes = av_malloc(entries * sizeof(int));
  1751. if (!sc->keyframes)
  1752. return AVERROR(ENOMEM);
  1753. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1754. sc->keyframes[i] = avio_rb32(pb);
  1755. }
  1756. sc->keyframe_count = i;
  1757. if (pb->eof_reached)
  1758. return AVERROR_EOF;
  1759. return 0;
  1760. }
  1761. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1762. {
  1763. AVStream *st;
  1764. MOVStreamContext *sc;
  1765. unsigned int i, entries, sample_size, field_size, num_bytes;
  1766. BitstreamContext bc;
  1767. unsigned char* buf;
  1768. int ret;
  1769. if (c->fc->nb_streams < 1)
  1770. return 0;
  1771. st = c->fc->streams[c->fc->nb_streams-1];
  1772. sc = st->priv_data;
  1773. avio_r8(pb); /* version */
  1774. avio_rb24(pb); /* flags */
  1775. if (atom.type == MKTAG('s','t','s','z')) {
  1776. sample_size = avio_rb32(pb);
  1777. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1778. sc->sample_size = sample_size;
  1779. field_size = 32;
  1780. } else {
  1781. sample_size = 0;
  1782. avio_rb24(pb); /* reserved */
  1783. field_size = avio_r8(pb);
  1784. }
  1785. entries = avio_rb32(pb);
  1786. av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries);
  1787. sc->sample_count = entries;
  1788. if (sample_size)
  1789. return 0;
  1790. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1791. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size);
  1792. return AVERROR_INVALIDDATA;
  1793. }
  1794. if (!entries)
  1795. return 0;
  1796. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1797. return AVERROR_INVALIDDATA;
  1798. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1799. if (!sc->sample_sizes)
  1800. return AVERROR(ENOMEM);
  1801. num_bytes = (entries*field_size+4)>>3;
  1802. buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE);
  1803. if (!buf) {
  1804. av_freep(&sc->sample_sizes);
  1805. return AVERROR(ENOMEM);
  1806. }
  1807. ret = ffio_read_size(pb, buf, num_bytes);
  1808. if (ret < 0) {
  1809. av_freep(&sc->sample_sizes);
  1810. av_free(buf);
  1811. return ret;
  1812. }
  1813. bitstream_init8(&bc, buf, num_bytes);
  1814. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1815. sc->sample_sizes[i] = bitstream_read(&bc, field_size);
  1816. sc->data_size += sc->sample_sizes[i];
  1817. }
  1818. sc->sample_count = i;
  1819. av_free(buf);
  1820. if (pb->eof_reached)
  1821. return AVERROR_EOF;
  1822. return 0;
  1823. }
  1824. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1825. {
  1826. AVStream *st;
  1827. MOVStreamContext *sc;
  1828. unsigned int i, entries;
  1829. int64_t duration=0;
  1830. int64_t total_sample_count=0;
  1831. if (c->fc->nb_streams < 1)
  1832. return 0;
  1833. st = c->fc->streams[c->fc->nb_streams-1];
  1834. sc = st->priv_data;
  1835. avio_r8(pb); /* version */
  1836. avio_rb24(pb); /* flags */
  1837. entries = avio_rb32(pb);
  1838. av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n",
  1839. c->fc->nb_streams-1, entries);
  1840. if (!entries)
  1841. return 0;
  1842. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1843. return AVERROR(EINVAL);
  1844. av_free(sc->stts_data);
  1845. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1846. if (!sc->stts_data)
  1847. return AVERROR(ENOMEM);
  1848. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1849. int sample_duration;
  1850. int sample_count;
  1851. sample_count=avio_rb32(pb);
  1852. sample_duration = avio_rb32(pb);
  1853. if (sample_count < 0) {
  1854. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1855. return AVERROR_INVALIDDATA;
  1856. }
  1857. sc->stts_data[i].count= sample_count;
  1858. sc->stts_data[i].duration= sample_duration;
  1859. av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n",
  1860. sample_count, sample_duration);
  1861. duration+=(int64_t)sample_duration*sample_count;
  1862. total_sample_count+=sample_count;
  1863. }
  1864. sc->stts_count = i;
  1865. if (pb->eof_reached)
  1866. return AVERROR_EOF;
  1867. st->nb_frames= total_sample_count;
  1868. if (duration)
  1869. st->duration= duration;
  1870. sc->track_end = duration;
  1871. return 0;
  1872. }
  1873. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1874. {
  1875. AVStream *st;
  1876. MOVStreamContext *sc;
  1877. unsigned int i, entries;
  1878. if (c->fc->nb_streams < 1)
  1879. return 0;
  1880. st = c->fc->streams[c->fc->nb_streams-1];
  1881. sc = st->priv_data;
  1882. avio_r8(pb); /* version */
  1883. avio_rb24(pb); /* flags */
  1884. entries = avio_rb32(pb);
  1885. av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries);
  1886. av_freep(&sc->ctts_data);
  1887. if (!entries)
  1888. return 0;
  1889. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1890. return AVERROR_INVALIDDATA;
  1891. sc->ctts_data = av_realloc(NULL, entries * sizeof(*sc->ctts_data));
  1892. if (!sc->ctts_data)
  1893. return AVERROR(ENOMEM);
  1894. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1895. int count =avio_rb32(pb);
  1896. int duration =avio_rb32(pb);
  1897. sc->ctts_data[i].count = count;
  1898. sc->ctts_data[i].duration= duration;
  1899. if (duration < 0)
  1900. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1901. }
  1902. sc->ctts_count = i;
  1903. if (pb->eof_reached)
  1904. return AVERROR_EOF;
  1905. av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift);
  1906. return 0;
  1907. }
  1908. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1909. {
  1910. AVStream *st;
  1911. MOVStreamContext *sc;
  1912. unsigned int i, entries;
  1913. uint8_t version;
  1914. uint32_t grouping_type;
  1915. if (c->fc->nb_streams < 1)
  1916. return 0;
  1917. st = c->fc->streams[c->fc->nb_streams-1];
  1918. sc = st->priv_data;
  1919. version = avio_r8(pb); /* version */
  1920. avio_rb24(pb); /* flags */
  1921. grouping_type = avio_rl32(pb);
  1922. if (grouping_type != MKTAG( 'r','a','p',' '))
  1923. return 0; /* only support 'rap ' grouping */
  1924. if (version == 1)
  1925. avio_rb32(pb); /* grouping_type_parameter */
  1926. entries = avio_rb32(pb);
  1927. if (!entries)
  1928. return 0;
  1929. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1930. return AVERROR_INVALIDDATA;
  1931. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1932. if (!sc->rap_group)
  1933. return AVERROR(ENOMEM);
  1934. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1935. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1936. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1937. }
  1938. sc->rap_group_count = i;
  1939. return pb->eof_reached ? AVERROR_EOF : 0;
  1940. }
  1941. static void mov_build_index(MOVContext *mov, AVStream *st)
  1942. {
  1943. MOVStreamContext *sc = st->priv_data;
  1944. int64_t current_offset;
  1945. int64_t current_dts = 0;
  1946. unsigned int stts_index = 0;
  1947. unsigned int stsc_index = 0;
  1948. unsigned int stss_index = 0;
  1949. unsigned int stps_index = 0;
  1950. unsigned int i, j;
  1951. uint64_t stream_size = 0;
  1952. /* adjust first dts according to edit list */
  1953. if (sc->time_offset && mov->time_scale > 0) {
  1954. if (sc->time_offset < 0)
  1955. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1956. current_dts = -sc->time_offset;
  1957. }
  1958. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1959. if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1960. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1961. unsigned int current_sample = 0;
  1962. unsigned int stts_sample = 0;
  1963. unsigned int sample_size;
  1964. unsigned int distance = 0;
  1965. unsigned int rap_group_index = 0;
  1966. unsigned int rap_group_sample = 0;
  1967. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1968. int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
  1969. current_dts -= sc->dts_shift;
  1970. if (!sc->sample_count)
  1971. return;
  1972. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1973. return;
  1974. if (av_reallocp_array(&st->index_entries,
  1975. st->nb_index_entries + sc->sample_count,
  1976. sizeof(*st->index_entries)) < 0) {
  1977. st->nb_index_entries = 0;
  1978. return;
  1979. }
  1980. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1981. for (i = 0; i < sc->chunk_count; i++) {
  1982. current_offset = sc->chunk_offsets[i];
  1983. while (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  1984. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1985. stsc_index++;
  1986. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1987. int keyframe = 0;
  1988. if (current_sample >= sc->sample_count) {
  1989. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1990. return;
  1991. }
  1992. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1993. keyframe = 1;
  1994. if (stss_index + 1 < sc->keyframe_count)
  1995. stss_index++;
  1996. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1997. keyframe = 1;
  1998. if (stps_index + 1 < sc->stps_count)
  1999. stps_index++;
  2000. }
  2001. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  2002. if (sc->rap_group[rap_group_index].index > 0)
  2003. keyframe = 1;
  2004. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  2005. rap_group_sample = 0;
  2006. rap_group_index++;
  2007. }
  2008. }
  2009. if (keyframe)
  2010. distance = 0;
  2011. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  2012. if (sc->pseudo_stream_id == -1 ||
  2013. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  2014. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  2015. e->pos = current_offset;
  2016. e->timestamp = current_dts;
  2017. e->size = sample_size;
  2018. e->min_distance = distance;
  2019. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  2020. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
  2021. "size %u, distance %u, keyframe %d\n", st->index, current_sample,
  2022. current_offset, current_dts, sample_size, distance, keyframe);
  2023. }
  2024. current_offset += sample_size;
  2025. stream_size += sample_size;
  2026. current_dts += sc->stts_data[stts_index].duration;
  2027. distance++;
  2028. stts_sample++;
  2029. current_sample++;
  2030. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  2031. stts_sample = 0;
  2032. stts_index++;
  2033. }
  2034. }
  2035. }
  2036. if (st->duration > 0)
  2037. st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration;
  2038. } else {
  2039. unsigned chunk_samples, total = 0;
  2040. // compute total chunk count
  2041. for (i = 0; i < sc->stsc_count; i++) {
  2042. unsigned count, chunk_count;
  2043. chunk_samples = sc->stsc_data[i].count;
  2044. if (i != sc->stsc_count - 1 &&
  2045. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  2046. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  2047. return;
  2048. }
  2049. if (sc->samples_per_frame >= 160) { // gsm
  2050. count = chunk_samples / sc->samples_per_frame;
  2051. } else if (sc->samples_per_frame > 1) {
  2052. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  2053. count = (chunk_samples+samples-1) / samples;
  2054. } else {
  2055. count = (chunk_samples+1023) / 1024;
  2056. }
  2057. if (mov_stsc_index_valid(i, sc->stsc_count))
  2058. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  2059. else
  2060. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  2061. total += chunk_count * count;
  2062. }
  2063. av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total);
  2064. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  2065. return;
  2066. if (av_reallocp_array(&st->index_entries,
  2067. st->nb_index_entries + total,
  2068. sizeof(*st->index_entries)) < 0) {
  2069. st->nb_index_entries = 0;
  2070. return;
  2071. }
  2072. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  2073. // populate index
  2074. for (i = 0; i < sc->chunk_count; i++) {
  2075. current_offset = sc->chunk_offsets[i];
  2076. if (mov_stsc_index_valid(stsc_index, sc->stsc_count) &&
  2077. i + 1 == sc->stsc_data[stsc_index + 1].first)
  2078. stsc_index++;
  2079. chunk_samples = sc->stsc_data[stsc_index].count;
  2080. while (chunk_samples > 0) {
  2081. AVIndexEntry *e;
  2082. unsigned size, samples;
  2083. if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) {
  2084. avpriv_request_sample(mov->fc,
  2085. "Zero bytes per frame, but %d samples per frame",
  2086. sc->samples_per_frame);
  2087. return;
  2088. }
  2089. if (sc->samples_per_frame >= 160) { // gsm
  2090. samples = sc->samples_per_frame;
  2091. size = sc->bytes_per_frame;
  2092. } else {
  2093. if (sc->samples_per_frame > 1) {
  2094. samples = FFMIN((1024 / sc->samples_per_frame)*
  2095. sc->samples_per_frame, chunk_samples);
  2096. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  2097. } else {
  2098. samples = FFMIN(1024, chunk_samples);
  2099. size = samples * sc->sample_size;
  2100. }
  2101. }
  2102. if (st->nb_index_entries >= total) {
  2103. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total);
  2104. return;
  2105. }
  2106. e = &st->index_entries[st->nb_index_entries++];
  2107. e->pos = current_offset;
  2108. e->timestamp = current_dts;
  2109. e->size = size;
  2110. e->min_distance = 0;
  2111. e->flags = AVINDEX_KEYFRAME;
  2112. av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", "
  2113. "size %u, duration %u\n", st->index, i, current_offset, current_dts,
  2114. size, samples);
  2115. current_offset += size;
  2116. current_dts += samples;
  2117. chunk_samples -= samples;
  2118. }
  2119. }
  2120. }
  2121. }
  2122. static int mov_open_dref(AVFormatContext *s, AVIOContext **pb, char *src,
  2123. MOVDref *ref)
  2124. {
  2125. /* try relative path, we do not try the absolute because it can leak information about our
  2126. system to an attacker */
  2127. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  2128. char filename[1024];
  2129. char *src_path;
  2130. int i, l;
  2131. /* find a source dir */
  2132. src_path = strrchr(src, '/');
  2133. if (src_path)
  2134. src_path++;
  2135. else
  2136. src_path = src;
  2137. /* find a next level down to target */
  2138. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  2139. if (ref->path[l] == '/') {
  2140. if (i == ref->nlvl_to - 1)
  2141. break;
  2142. else
  2143. i++;
  2144. }
  2145. /* compose filename if next level down to target was found */
  2146. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  2147. memcpy(filename, src, src_path - src);
  2148. filename[src_path - src] = 0;
  2149. for (i = 1; i < ref->nlvl_from; i++)
  2150. av_strlcat(filename, "../", 1024);
  2151. av_strlcat(filename, ref->path + l + 1, 1024);
  2152. if (!s->io_open(s, pb, filename, AVIO_FLAG_READ, NULL))
  2153. return 0;
  2154. }
  2155. }
  2156. return AVERROR(ENOENT);
  2157. }
  2158. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2159. {
  2160. AVStream *st;
  2161. MOVStreamContext *sc;
  2162. int ret;
  2163. st = avformat_new_stream(c->fc, NULL);
  2164. if (!st) return AVERROR(ENOMEM);
  2165. st->id = c->fc->nb_streams;
  2166. sc = av_mallocz(sizeof(MOVStreamContext));
  2167. if (!sc) return AVERROR(ENOMEM);
  2168. st->priv_data = sc;
  2169. st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
  2170. sc->ffindex = st->index;
  2171. if ((ret = mov_read_default(c, pb, atom)) < 0)
  2172. return ret;
  2173. /* sanity checks */
  2174. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  2175. (!sc->sample_size && !sc->sample_count))) {
  2176. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  2177. st->index);
  2178. return 0;
  2179. }
  2180. if (sc->time_scale <= 0) {
  2181. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  2182. sc->time_scale = c->time_scale;
  2183. if (sc->time_scale <= 0)
  2184. sc->time_scale = 1;
  2185. }
  2186. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  2187. mov_build_index(c, st);
  2188. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  2189. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  2190. if (c->enable_drefs) {
  2191. if (mov_open_dref(c->fc, &sc->pb, c->fc->filename, dref) < 0)
  2192. av_log(c->fc, AV_LOG_ERROR,
  2193. "stream %d, error opening alias: path='%s', dir='%s', "
  2194. "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"\n",
  2195. st->index, dref->path, dref->dir, dref->filename,
  2196. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2197. } else {
  2198. av_log(c->fc, AV_LOG_WARNING,
  2199. "Skipped opening external track: "
  2200. "stream %d, alias: path='%s', dir='%s', "
  2201. "filename='%s', volume='%s', nlvl_from=%"PRId16", nlvl_to=%"PRId16"."
  2202. "Set enable_drefs to allow this.\n",
  2203. st->index, dref->path, dref->dir, dref->filename,
  2204. dref->volume, dref->nlvl_from, dref->nlvl_to);
  2205. }
  2206. } else
  2207. sc->pb = c->fc->pb;
  2208. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  2209. if (!st->sample_aspect_ratio.num &&
  2210. (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) {
  2211. st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) /
  2212. ((double)st->codecpar->width * sc->height), INT_MAX);
  2213. }
  2214. }
  2215. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  2216. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 &&
  2217. TAG_IS_AVCI(st->codecpar->codec_tag)) {
  2218. ret = ff_generate_avci_extradata(st);
  2219. if (ret < 0)
  2220. return ret;
  2221. }
  2222. switch (st->codecpar->codec_id) {
  2223. #if CONFIG_H261_DECODER
  2224. case AV_CODEC_ID_H261:
  2225. #endif
  2226. #if CONFIG_H263_DECODER
  2227. case AV_CODEC_ID_H263:
  2228. #endif
  2229. #if CONFIG_MPEG4_DECODER
  2230. case AV_CODEC_ID_MPEG4:
  2231. #endif
  2232. st->codecpar->width = 0; /* let decoder init width/height */
  2233. st->codecpar->height= 0;
  2234. break;
  2235. case AV_CODEC_ID_MP3:
  2236. st->need_parsing = AVSTREAM_PARSE_FULL;
  2237. break;
  2238. }
  2239. /* Do not need those anymore. */
  2240. av_freep(&sc->chunk_offsets);
  2241. av_freep(&sc->sample_sizes);
  2242. av_freep(&sc->keyframes);
  2243. av_freep(&sc->stts_data);
  2244. av_freep(&sc->stps_data);
  2245. av_freep(&sc->rap_group);
  2246. return 0;
  2247. }
  2248. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2249. {
  2250. int ret;
  2251. c->itunes_metadata = 1;
  2252. ret = mov_read_default(c, pb, atom);
  2253. c->itunes_metadata = 0;
  2254. return ret;
  2255. }
  2256. static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int64_t size)
  2257. {
  2258. int64_t end = avio_tell(pb) + size;
  2259. uint8_t *key = NULL, *val = NULL;
  2260. int i;
  2261. for (i = 0; i < 2; i++) {
  2262. uint8_t **p;
  2263. uint32_t len, tag;
  2264. int ret;
  2265. if (end - avio_tell(pb) <= 12)
  2266. break;
  2267. len = avio_rb32(pb);
  2268. tag = avio_rl32(pb);
  2269. avio_skip(pb, 4); // flags
  2270. if (len < 12 || len - 12 > end - avio_tell(pb))
  2271. break;
  2272. len -= 12;
  2273. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2274. p = &key;
  2275. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2276. avio_skip(pb, 4);
  2277. len -= 4;
  2278. p = &val;
  2279. } else
  2280. break;
  2281. *p = av_malloc(len + 1);
  2282. if (!*p)
  2283. break;
  2284. ret = ffio_read_size(pb, *p, len);
  2285. if (ret < 0) {
  2286. av_freep(p);
  2287. return ret;
  2288. }
  2289. (*p)[len] = 0;
  2290. }
  2291. if (key && val) {
  2292. av_dict_set(&c->fc->metadata, key, val,
  2293. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2294. key = val = NULL;
  2295. }
  2296. avio_seek(pb, end, SEEK_SET);
  2297. av_freep(&key);
  2298. av_freep(&val);
  2299. return 0;
  2300. }
  2301. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2302. {
  2303. int64_t end = avio_tell(pb) + atom.size;
  2304. uint32_t tag, len;
  2305. if (atom.size < 8)
  2306. goto fail;
  2307. len = avio_rb32(pb);
  2308. tag = avio_rl32(pb);
  2309. if (len > atom.size)
  2310. goto fail;
  2311. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2312. uint8_t domain[128];
  2313. int domain_len;
  2314. avio_skip(pb, 4); // flags
  2315. len -= 12;
  2316. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2317. avio_skip(pb, len - domain_len);
  2318. if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
  2319. return mov_read_replaygain(c, pb, end - avio_tell(pb));
  2320. }
  2321. fail:
  2322. av_log(c->fc, AV_LOG_VERBOSE,
  2323. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2324. return 0;
  2325. }
  2326. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2327. {
  2328. while (atom.size > 8) {
  2329. uint32_t tag = avio_rl32(pb);
  2330. atom.size -= 4;
  2331. if (tag == MKTAG('h','d','l','r')) {
  2332. avio_seek(pb, -8, SEEK_CUR);
  2333. atom.size += 8;
  2334. return mov_read_default(c, pb, atom);
  2335. }
  2336. }
  2337. return 0;
  2338. }
  2339. // return 1 when matrix is identity, 0 otherwise
  2340. #define IS_MATRIX_IDENT(matrix) \
  2341. ( (matrix)[0][0] == (1 << 16) && \
  2342. (matrix)[1][1] == (1 << 16) && \
  2343. (matrix)[2][2] == (1 << 30) && \
  2344. !(matrix)[0][1] && !(matrix)[0][2] && \
  2345. !(matrix)[1][0] && !(matrix)[1][2] && \
  2346. !(matrix)[2][0] && !(matrix)[2][1])
  2347. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2348. {
  2349. int i, j, e;
  2350. int width;
  2351. int height;
  2352. int64_t disp_transform[2];
  2353. int display_matrix[3][3];
  2354. int res_display_matrix[3][3] = { { 0 } };
  2355. AVStream *st;
  2356. MOVStreamContext *sc;
  2357. int version;
  2358. int flags;
  2359. if (c->fc->nb_streams < 1)
  2360. return 0;
  2361. st = c->fc->streams[c->fc->nb_streams-1];
  2362. sc = st->priv_data;
  2363. version = avio_r8(pb);
  2364. flags = avio_rb24(pb);
  2365. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2366. if (version == 1) {
  2367. avio_rb64(pb);
  2368. avio_rb64(pb);
  2369. } else {
  2370. avio_rb32(pb); /* creation time */
  2371. avio_rb32(pb); /* modification time */
  2372. }
  2373. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2374. avio_rb32(pb); /* reserved */
  2375. /* highlevel (considering edits) duration in movie timebase */
  2376. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2377. avio_rb32(pb); /* reserved */
  2378. avio_rb32(pb); /* reserved */
  2379. avio_rb16(pb); /* layer */
  2380. avio_rb16(pb); /* alternate group */
  2381. avio_rb16(pb); /* volume */
  2382. avio_rb16(pb); /* reserved */
  2383. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2384. // they're kept in fixed point format through all calculations
  2385. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2386. // side data, but the scale factor is not needed to calculate aspect ratio
  2387. for (i = 0; i < 3; i++) {
  2388. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2389. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2390. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2391. }
  2392. width = avio_rb32(pb); // 16.16 fixed point track width
  2393. height = avio_rb32(pb); // 16.16 fixed point track height
  2394. sc->width = width >> 16;
  2395. sc->height = height >> 16;
  2396. // apply the moov display matrix (after the tkhd one)
  2397. for (i = 0; i < 3; i++) {
  2398. const int sh[3] = { 16, 16, 30 };
  2399. for (j = 0; j < 3; j++) {
  2400. for (e = 0; e < 3; e++) {
  2401. res_display_matrix[i][j] +=
  2402. ((int64_t) display_matrix[i][e] *
  2403. c->movie_display_matrix[e][j]) >> sh[e];
  2404. }
  2405. }
  2406. }
  2407. // save the matrix when it is not the default identity
  2408. if (!IS_MATRIX_IDENT(res_display_matrix)) {
  2409. av_freep(&sc->display_matrix);
  2410. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2411. if (!sc->display_matrix)
  2412. return AVERROR(ENOMEM);
  2413. for (i = 0; i < 3; i++)
  2414. for (j = 0; j < 3; j++)
  2415. sc->display_matrix[i * 3 + j] = res_display_matrix[i][j];
  2416. }
  2417. // transform the display width/height according to the matrix
  2418. // skip this when the display matrix is the identity one
  2419. // to keep the same scale, use [width height 1<<16]
  2420. if (width && height && sc->display_matrix) {
  2421. for (i = 0; i < 2; i++)
  2422. disp_transform[i] =
  2423. (int64_t) width * sc->display_matrix[0 + i] +
  2424. (int64_t) height * sc->display_matrix[3 + i] +
  2425. ((int64_t) sc->display_matrix[6 + i] << 16);
  2426. //sample aspect ratio is new width/height divided by old width/height
  2427. if (disp_transform[0] > 0 && disp_transform[1] > 0)
  2428. st->sample_aspect_ratio = av_d2q(
  2429. ((double) disp_transform[0] * height) /
  2430. ((double) disp_transform[1] * width), INT_MAX);
  2431. }
  2432. return 0;
  2433. }
  2434. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2435. {
  2436. MOVFragment *frag = &c->fragment;
  2437. MOVTrackExt *trex = NULL;
  2438. int flags, track_id, i;
  2439. avio_r8(pb); /* version */
  2440. flags = avio_rb24(pb);
  2441. track_id = avio_rb32(pb);
  2442. if (!track_id)
  2443. return AVERROR_INVALIDDATA;
  2444. frag->track_id = track_id;
  2445. for (i = 0; i < c->trex_count; i++)
  2446. if (c->trex_data[i].track_id == frag->track_id) {
  2447. trex = &c->trex_data[i];
  2448. break;
  2449. }
  2450. if (!trex) {
  2451. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2452. return AVERROR_INVALIDDATA;
  2453. }
  2454. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2455. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2456. frag->moof_offset : frag->implicit_offset;
  2457. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2458. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2459. avio_rb32(pb) : trex->duration;
  2460. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2461. avio_rb32(pb) : trex->size;
  2462. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2463. avio_rb32(pb) : trex->flags;
  2464. av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags);
  2465. return 0;
  2466. }
  2467. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2468. {
  2469. c->chapter_track = avio_rb32(pb);
  2470. return 0;
  2471. }
  2472. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2473. {
  2474. MOVTrackExt *trex;
  2475. int err;
  2476. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2477. return AVERROR_INVALIDDATA;
  2478. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2479. sizeof(*c->trex_data))) < 0) {
  2480. c->trex_count = 0;
  2481. return err;
  2482. }
  2483. trex = &c->trex_data[c->trex_count++];
  2484. avio_r8(pb); /* version */
  2485. avio_rb24(pb); /* flags */
  2486. trex->track_id = avio_rb32(pb);
  2487. trex->stsd_id = avio_rb32(pb);
  2488. trex->duration = avio_rb32(pb);
  2489. trex->size = avio_rb32(pb);
  2490. trex->flags = avio_rb32(pb);
  2491. return 0;
  2492. }
  2493. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2494. {
  2495. MOVFragment *frag = &c->fragment;
  2496. AVStream *st = NULL;
  2497. MOVStreamContext *sc;
  2498. int version, i;
  2499. for (i = 0; i < c->fc->nb_streams; i++) {
  2500. if (c->fc->streams[i]->id == frag->track_id) {
  2501. st = c->fc->streams[i];
  2502. break;
  2503. }
  2504. }
  2505. if (!st) {
  2506. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  2507. return AVERROR_INVALIDDATA;
  2508. }
  2509. sc = st->priv_data;
  2510. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  2511. return 0;
  2512. version = avio_r8(pb);
  2513. avio_rb24(pb); /* flags */
  2514. if (version) {
  2515. sc->track_end = avio_rb64(pb);
  2516. } else {
  2517. sc->track_end = avio_rb32(pb);
  2518. }
  2519. return 0;
  2520. }
  2521. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2522. {
  2523. MOVFragment *frag = &c->fragment;
  2524. AVStream *st = NULL;
  2525. MOVStreamContext *sc;
  2526. MOVStts *ctts_data;
  2527. uint64_t offset;
  2528. int64_t dts;
  2529. int data_offset = 0;
  2530. unsigned entries, first_sample_flags = frag->flags;
  2531. int flags, distance, i, err;
  2532. for (i = 0; i < c->fc->nb_streams; i++) {
  2533. if (c->fc->streams[i]->id == frag->track_id) {
  2534. st = c->fc->streams[i];
  2535. break;
  2536. }
  2537. }
  2538. if (!st) {
  2539. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);
  2540. return AVERROR_INVALIDDATA;
  2541. }
  2542. sc = st->priv_data;
  2543. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  2544. return 0;
  2545. avio_r8(pb); /* version */
  2546. flags = avio_rb24(pb);
  2547. entries = avio_rb32(pb);
  2548. av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);
  2549. /* Always assume the presence of composition time offsets.
  2550. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2551. * 1) in the initial movie, there are no samples.
  2552. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2553. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2554. if (!sc->ctts_count && sc->sample_count)
  2555. {
  2556. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2557. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2558. if (!ctts_data)
  2559. return AVERROR(ENOMEM);
  2560. sc->ctts_data = ctts_data;
  2561. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2562. sc->ctts_data[sc->ctts_count].duration = 0;
  2563. sc->ctts_count++;
  2564. }
  2565. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2566. return AVERROR_INVALIDDATA;
  2567. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2568. sizeof(*sc->ctts_data))) < 0) {
  2569. sc->ctts_count = 0;
  2570. return err;
  2571. }
  2572. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2573. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2574. dts = sc->track_end - sc->time_offset;
  2575. offset = frag->base_data_offset + data_offset;
  2576. distance = 0;
  2577. av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);
  2578. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2579. unsigned sample_size = frag->size;
  2580. int sample_flags = i ? frag->flags : first_sample_flags;
  2581. unsigned sample_duration = frag->duration;
  2582. int keyframe = 0;
  2583. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2584. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2585. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2586. sc->ctts_data[sc->ctts_count].count = 1;
  2587. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2588. avio_rb32(pb) : 0;
  2589. sc->ctts_count++;
  2590. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
  2591. keyframe = 1;
  2592. else
  2593. keyframe =
  2594. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2595. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2596. if (keyframe)
  2597. distance = 0;
  2598. av_add_index_entry(st, offset, dts, sample_size, distance,
  2599. keyframe ? AVINDEX_KEYFRAME : 0);
  2600. av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", "
  2601. "size %u, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2602. offset, dts, sample_size, distance, keyframe);
  2603. distance++;
  2604. dts += sample_duration;
  2605. offset += sample_size;
  2606. sc->data_size += sample_size;
  2607. }
  2608. if (pb->eof_reached)
  2609. return AVERROR_EOF;
  2610. frag->implicit_offset = offset;
  2611. st->duration = sc->track_end = dts + sc->time_offset;
  2612. return 0;
  2613. }
  2614. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2615. /* like the files created with Adobe Premiere 5.0, for samples see */
  2616. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2617. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2618. {
  2619. int err;
  2620. if (atom.size < 8)
  2621. return 0; /* continue */
  2622. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2623. avio_skip(pb, atom.size - 4);
  2624. return 0;
  2625. }
  2626. atom.type = avio_rl32(pb);
  2627. atom.size -= 8;
  2628. if (atom.type != MKTAG('m','d','a','t')) {
  2629. avio_skip(pb, atom.size);
  2630. return 0;
  2631. }
  2632. err = mov_read_mdat(c, pb, atom);
  2633. return err;
  2634. }
  2635. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2636. {
  2637. #if CONFIG_ZLIB
  2638. AVIOContext ctx;
  2639. uint8_t *cmov_data;
  2640. uint8_t *moov_data; /* uncompressed data */
  2641. long cmov_len, moov_len;
  2642. int ret = -1;
  2643. avio_rb32(pb); /* dcom atom */
  2644. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2645. return AVERROR_INVALIDDATA;
  2646. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2647. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  2648. return AVERROR_INVALIDDATA;
  2649. }
  2650. avio_rb32(pb); /* cmvd atom */
  2651. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2652. return AVERROR_INVALIDDATA;
  2653. moov_len = avio_rb32(pb); /* uncompressed size */
  2654. cmov_len = atom.size - 6 * 4;
  2655. cmov_data = av_malloc(cmov_len);
  2656. if (!cmov_data)
  2657. return AVERROR(ENOMEM);
  2658. moov_data = av_malloc(moov_len);
  2659. if (!moov_data) {
  2660. av_free(cmov_data);
  2661. return AVERROR(ENOMEM);
  2662. }
  2663. ret = ffio_read_size(pb, cmov_data, cmov_len);
  2664. if (ret < 0)
  2665. goto free_and_return;
  2666. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2667. goto free_and_return;
  2668. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2669. goto free_and_return;
  2670. atom.type = MKTAG('m','o','o','v');
  2671. atom.size = moov_len;
  2672. ret = mov_read_default(c, &ctx, atom);
  2673. free_and_return:
  2674. av_free(moov_data);
  2675. av_free(cmov_data);
  2676. return ret;
  2677. #else
  2678. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2679. return AVERROR(ENOSYS);
  2680. #endif
  2681. }
  2682. /* edit list atom */
  2683. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2684. {
  2685. MOVStreamContext *sc;
  2686. int i, edit_count, version;
  2687. if (c->fc->nb_streams < 1)
  2688. return 0;
  2689. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2690. version = avio_r8(pb); /* version */
  2691. avio_rb24(pb); /* flags */
  2692. edit_count = avio_rb32(pb); /* entries */
  2693. if ((uint64_t)edit_count*12+8 > atom.size)
  2694. return AVERROR_INVALIDDATA;
  2695. for (i=0; i<edit_count; i++){
  2696. int64_t time;
  2697. int64_t duration;
  2698. if (version == 1) {
  2699. duration = avio_rb64(pb);
  2700. time = avio_rb64(pb);
  2701. } else {
  2702. duration = avio_rb32(pb); /* segment duration */
  2703. time = (int32_t)avio_rb32(pb); /* media time */
  2704. }
  2705. avio_rb32(pb); /* Media rate */
  2706. if (i == 0 && time >= -1) {
  2707. sc->time_offset = time != -1 ? time : -duration;
  2708. }
  2709. }
  2710. if (edit_count > 1)
  2711. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2712. "a/v desync might occur, patch welcome\n");
  2713. av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count);
  2714. return 0;
  2715. }
  2716. static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2717. {
  2718. AVStream *st;
  2719. MOVStreamContext *sc;
  2720. enum AVStereo3DType type;
  2721. int mode;
  2722. if (c->fc->nb_streams < 1)
  2723. return 0;
  2724. st = c->fc->streams[c->fc->nb_streams - 1];
  2725. sc = st->priv_data;
  2726. if (atom.size < 5) {
  2727. av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n");
  2728. return AVERROR_INVALIDDATA;
  2729. }
  2730. avio_skip(pb, 4); /* version + flags */
  2731. mode = avio_r8(pb);
  2732. switch (mode) {
  2733. case 0:
  2734. type = AV_STEREO3D_2D;
  2735. break;
  2736. case 1:
  2737. type = AV_STEREO3D_TOPBOTTOM;
  2738. break;
  2739. case 2:
  2740. type = AV_STEREO3D_SIDEBYSIDE;
  2741. break;
  2742. default:
  2743. av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode);
  2744. return 0;
  2745. }
  2746. sc->stereo3d = av_stereo3d_alloc();
  2747. if (!sc->stereo3d)
  2748. return AVERROR(ENOMEM);
  2749. sc->stereo3d->type = type;
  2750. return 0;
  2751. }
  2752. static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2753. {
  2754. AVStream *st;
  2755. MOVStreamContext *sc;
  2756. int size, version, layout;
  2757. int32_t yaw, pitch, roll;
  2758. uint32_t l = 0, t = 0, r = 0, b = 0;
  2759. uint32_t tag, padding = 0;
  2760. enum AVSphericalProjection projection;
  2761. if (c->fc->nb_streams < 1)
  2762. return 0;
  2763. st = c->fc->streams[c->fc->nb_streams - 1];
  2764. sc = st->priv_data;
  2765. if (atom.size < 8) {
  2766. av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n");
  2767. return AVERROR_INVALIDDATA;
  2768. }
  2769. size = avio_rb32(pb);
  2770. if (size <= 12 || size > atom.size)
  2771. return AVERROR_INVALIDDATA;
  2772. tag = avio_rl32(pb);
  2773. if (tag != MKTAG('s','v','h','d')) {
  2774. av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n");
  2775. return 0;
  2776. }
  2777. version = avio_r8(pb);
  2778. if (version != 0) {
  2779. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  2780. version);
  2781. return 0;
  2782. }
  2783. avio_skip(pb, 3); /* flags */
  2784. avio_skip(pb, size - 12); /* metadata_source */
  2785. size = avio_rb32(pb);
  2786. if (size > atom.size)
  2787. return AVERROR_INVALIDDATA;
  2788. tag = avio_rl32(pb);
  2789. if (tag != MKTAG('p','r','o','j')) {
  2790. av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n");
  2791. return 0;
  2792. }
  2793. size = avio_rb32(pb);
  2794. if (size > atom.size)
  2795. return AVERROR_INVALIDDATA;
  2796. tag = avio_rl32(pb);
  2797. if (tag != MKTAG('p','r','h','d')) {
  2798. av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n");
  2799. return 0;
  2800. }
  2801. version = avio_r8(pb);
  2802. if (version != 0) {
  2803. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  2804. version);
  2805. return 0;
  2806. }
  2807. avio_skip(pb, 3); /* flags */
  2808. /* 16.16 fixed point */
  2809. yaw = avio_rb32(pb);
  2810. pitch = avio_rb32(pb);
  2811. roll = avio_rb32(pb);
  2812. size = avio_rb32(pb);
  2813. if (size > atom.size)
  2814. return AVERROR_INVALIDDATA;
  2815. tag = avio_rl32(pb);
  2816. version = avio_r8(pb);
  2817. if (version != 0) {
  2818. av_log(c->fc, AV_LOG_WARNING, "Unknown spherical version %d\n",
  2819. version);
  2820. return 0;
  2821. }
  2822. avio_skip(pb, 3); /* flags */
  2823. switch (tag) {
  2824. case MKTAG('c','b','m','p'):
  2825. layout = avio_rb32(pb);
  2826. if (layout) {
  2827. av_log(c->fc, AV_LOG_WARNING,
  2828. "Unsupported cubemap layout %d\n", layout);
  2829. return 0;
  2830. }
  2831. projection = AV_SPHERICAL_CUBEMAP;
  2832. padding = avio_rb32(pb);
  2833. break;
  2834. case MKTAG('e','q','u','i'):
  2835. t = avio_rb32(pb);
  2836. b = avio_rb32(pb);
  2837. l = avio_rb32(pb);
  2838. r = avio_rb32(pb);
  2839. if (b >= UINT_MAX - t || r >= UINT_MAX - l) {
  2840. av_log(c->fc, AV_LOG_ERROR,
  2841. "Invalid bounding rectangle coordinates "
  2842. "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b);
  2843. return AVERROR_INVALIDDATA;
  2844. }
  2845. if (l || t || r || b)
  2846. projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE;
  2847. else
  2848. projection = AV_SPHERICAL_EQUIRECTANGULAR;
  2849. break;
  2850. default:
  2851. av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n");
  2852. return 0;
  2853. }
  2854. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  2855. if (!sc->spherical)
  2856. return AVERROR(ENOMEM);
  2857. sc->spherical->projection = projection;
  2858. sc->spherical->yaw = yaw;
  2859. sc->spherical->pitch = pitch;
  2860. sc->spherical->roll = roll;
  2861. sc->spherical->padding = padding;
  2862. sc->spherical->bound_left = l;
  2863. sc->spherical->bound_top = t;
  2864. sc->spherical->bound_right = r;
  2865. sc->spherical->bound_bottom = b;
  2866. return 0;
  2867. }
  2868. static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len)
  2869. {
  2870. int ret = 0;
  2871. uint8_t *buffer = av_malloc(len + 1);
  2872. const char *val;
  2873. if (!buffer)
  2874. return AVERROR(ENOMEM);
  2875. buffer[len] = '\0';
  2876. ret = ffio_read_size(pb, buffer, len);
  2877. if (ret < 0)
  2878. goto out;
  2879. /* Check for mandatory keys and values, try to support XML as best-effort */
  2880. if (!sc->spherical &&
  2881. av_stristr(buffer, "<GSpherical:StitchingSoftware>") &&
  2882. (val = av_stristr(buffer, "<GSpherical:Spherical>")) &&
  2883. av_stristr(val, "true") &&
  2884. (val = av_stristr(buffer, "<GSpherical:Stitched>")) &&
  2885. av_stristr(val, "true") &&
  2886. (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) &&
  2887. av_stristr(val, "equirectangular")) {
  2888. sc->spherical = av_spherical_alloc(&sc->spherical_size);
  2889. if (!sc->spherical)
  2890. goto out;
  2891. sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR;
  2892. if (av_stristr(buffer, "<GSpherical:StereoMode>") && !sc->stereo3d) {
  2893. enum AVStereo3DType mode;
  2894. if (av_stristr(buffer, "left-right"))
  2895. mode = AV_STEREO3D_SIDEBYSIDE;
  2896. else if (av_stristr(buffer, "top-bottom"))
  2897. mode = AV_STEREO3D_TOPBOTTOM;
  2898. else
  2899. mode = AV_STEREO3D_2D;
  2900. sc->stereo3d = av_stereo3d_alloc();
  2901. if (!sc->stereo3d)
  2902. goto out;
  2903. sc->stereo3d->type = mode;
  2904. }
  2905. /* orientation */
  2906. val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>");
  2907. if (val)
  2908. sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16);
  2909. val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>");
  2910. if (val)
  2911. sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16);
  2912. val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>");
  2913. if (val)
  2914. sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16);
  2915. }
  2916. out:
  2917. av_free(buffer);
  2918. return ret;
  2919. }
  2920. static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2921. {
  2922. AVStream *st;
  2923. MOVStreamContext *sc;
  2924. int ret;
  2925. uint8_t uuid[16];
  2926. static const uint8_t uuid_spherical[] = {
  2927. 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93,
  2928. 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd,
  2929. };
  2930. if (atom.size < sizeof(uuid) || atom.size == INT64_MAX)
  2931. return AVERROR_INVALIDDATA;
  2932. if (c->fc->nb_streams < 1)
  2933. return 0;
  2934. st = c->fc->streams[c->fc->nb_streams - 1];
  2935. sc = st->priv_data;
  2936. ret = ffio_read_size(pb, uuid, sizeof(uuid));
  2937. if (ret < 0)
  2938. return ret;
  2939. if (!memcmp(uuid, uuid_spherical, sizeof(uuid)) && !sc->spherical) {
  2940. size_t len = atom.size - sizeof(uuid);
  2941. ret = mov_parse_uuid_spherical(sc, pb, len);
  2942. if (ret < 0)
  2943. return ret;
  2944. if (!sc->spherical)
  2945. av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n");
  2946. } else {
  2947. int i;
  2948. av_log(c->fc, AV_LOG_VERBOSE, "Unknown UUID found: 0x");
  2949. for (i = 0; i < sizeof(uuid); i++)
  2950. av_log(c->fc, AV_LOG_WARNING, "%02x", uuid[i]);
  2951. av_log(c->fc, AV_LOG_WARNING, "\n");
  2952. }
  2953. return 0;
  2954. }
  2955. static const MOVParseTableEntry mov_default_parse_table[] = {
  2956. { MKTAG('a','v','s','s'), mov_read_extradata },
  2957. { MKTAG('c','h','p','l'), mov_read_chpl },
  2958. { MKTAG('c','o','6','4'), mov_read_stco },
  2959. { MKTAG('c','o','l','r'), mov_read_colr },
  2960. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2961. { MKTAG('d','i','n','f'), mov_read_default },
  2962. { MKTAG('d','r','e','f'), mov_read_dref },
  2963. { MKTAG('e','d','t','s'), mov_read_default },
  2964. { MKTAG('e','l','s','t'), mov_read_elst },
  2965. { MKTAG('e','n','d','a'), mov_read_enda },
  2966. { MKTAG('f','i','e','l'), mov_read_fiel },
  2967. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2968. { MKTAG('g','l','b','l'), mov_read_glbl },
  2969. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2970. { MKTAG('i','l','s','t'), mov_read_ilst },
  2971. { MKTAG('j','p','2','h'), mov_read_extradata },
  2972. { MKTAG('m','d','a','t'), mov_read_mdat },
  2973. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2974. { MKTAG('m','d','i','a'), mov_read_default },
  2975. { MKTAG('m','e','t','a'), mov_read_meta },
  2976. { MKTAG('m','i','n','f'), mov_read_default },
  2977. { MKTAG('m','o','o','f'), mov_read_moof },
  2978. { MKTAG('m','o','o','v'), mov_read_moov },
  2979. { MKTAG('m','v','e','x'), mov_read_default },
  2980. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2981. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  2982. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  2983. { MKTAG('a','v','c','C'), mov_read_glbl },
  2984. { MKTAG('p','a','s','p'), mov_read_pasp },
  2985. { MKTAG('s','t','b','l'), mov_read_default },
  2986. { MKTAG('s','t','c','o'), mov_read_stco },
  2987. { MKTAG('s','t','p','s'), mov_read_stps },
  2988. { MKTAG('s','t','r','f'), mov_read_strf },
  2989. { MKTAG('s','t','s','c'), mov_read_stsc },
  2990. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2991. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2992. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2993. { MKTAG('s','t','t','s'), mov_read_stts },
  2994. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2995. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2996. { MKTAG('t','f','d','t'), mov_read_tfdt },
  2997. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2998. { MKTAG('t','r','a','k'), mov_read_trak },
  2999. { MKTAG('t','r','a','f'), mov_read_default },
  3000. { MKTAG('t','r','e','f'), mov_read_default },
  3001. { MKTAG('c','h','a','p'), mov_read_chap },
  3002. { MKTAG('t','r','e','x'), mov_read_trex },
  3003. { MKTAG('t','r','u','n'), mov_read_trun },
  3004. { MKTAG('u','d','t','a'), mov_read_default },
  3005. { MKTAG('w','a','v','e'), mov_read_wave },
  3006. { MKTAG('e','s','d','s'), mov_read_esds },
  3007. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  3008. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  3009. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  3010. { MKTAG('w','f','e','x'), mov_read_wfex },
  3011. { MKTAG('c','m','o','v'), mov_read_cmov },
  3012. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  3013. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  3014. { MKTAG('s','b','g','p'), mov_read_sbgp },
  3015. { MKTAG('h','v','c','C'), mov_read_glbl },
  3016. { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */
  3017. { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */
  3018. { MKTAG('u','u','i','d'), mov_read_uuid }, /* universal unique identifier */
  3019. { MKTAG('-','-','-','-'), mov_read_custom },
  3020. { 0, NULL }
  3021. };
  3022. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  3023. {
  3024. int64_t total_size = 0;
  3025. MOVAtom a;
  3026. int i;
  3027. if (atom.size < 0)
  3028. atom.size = INT64_MAX;
  3029. while (total_size + 8 < atom.size && !pb->eof_reached) {
  3030. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  3031. a.size = atom.size;
  3032. a.type=0;
  3033. if (atom.size >= 8) {
  3034. a.size = avio_rb32(pb);
  3035. a.type = avio_rl32(pb);
  3036. }
  3037. av_log(c->fc, AV_LOG_TRACE, "type: %08"PRIx32" '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  3038. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  3039. total_size += 8;
  3040. if (a.size == 1) { /* 64 bit extended size */
  3041. a.size = avio_rb64(pb) - 8;
  3042. total_size += 8;
  3043. }
  3044. if (a.size == 0) {
  3045. a.size = atom.size - total_size;
  3046. if (a.size <= 8)
  3047. break;
  3048. }
  3049. a.size -= 8;
  3050. if (a.size < 0)
  3051. break;
  3052. a.size = FFMIN(a.size, atom.size - total_size);
  3053. for (i = 0; mov_default_parse_table[i].type; i++)
  3054. if (mov_default_parse_table[i].type == a.type) {
  3055. parse = mov_default_parse_table[i].parse;
  3056. break;
  3057. }
  3058. // container is user data
  3059. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  3060. atom.type == MKTAG('i','l','s','t')))
  3061. parse = mov_read_udta_string;
  3062. if (!parse) { /* skip leaf atoms data */
  3063. avio_skip(pb, a.size);
  3064. } else {
  3065. int64_t start_pos = avio_tell(pb);
  3066. int64_t left;
  3067. int err = parse(c, pb, a);
  3068. if (err < 0)
  3069. return err;
  3070. if (c->found_moov && c->found_mdat &&
  3071. ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  3072. start_pos + a.size == avio_size(pb))) {
  3073. if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX)
  3074. c->next_root_atom = start_pos + a.size;
  3075. return 0;
  3076. }
  3077. left = a.size - avio_tell(pb) + start_pos;
  3078. if (left > 0) /* skip garbage at atom end */
  3079. avio_skip(pb, left);
  3080. else if (left < 0) {
  3081. av_log(c->fc, AV_LOG_WARNING,
  3082. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  3083. (char*)&a.type, -left);
  3084. avio_seek(pb, left, SEEK_CUR);
  3085. }
  3086. }
  3087. total_size += a.size;
  3088. }
  3089. if (total_size < atom.size && atom.size < 0x7ffff)
  3090. avio_skip(pb, atom.size - total_size);
  3091. return 0;
  3092. }
  3093. static int mov_probe(AVProbeData *p)
  3094. {
  3095. unsigned int offset;
  3096. uint32_t tag;
  3097. int score = 0;
  3098. /* check file header */
  3099. offset = 0;
  3100. for (;;) {
  3101. /* ignore invalid offset */
  3102. if ((offset + 8) > (unsigned int)p->buf_size)
  3103. return score;
  3104. tag = AV_RL32(p->buf + offset + 4);
  3105. switch(tag) {
  3106. /* check for obvious tags */
  3107. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  3108. case MKTAG('m','o','o','v'):
  3109. case MKTAG('m','d','a','t'):
  3110. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  3111. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  3112. case MKTAG('f','t','y','p'):
  3113. return AVPROBE_SCORE_MAX;
  3114. /* those are more common words, so rate then a bit less */
  3115. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  3116. case MKTAG('w','i','d','e'):
  3117. case MKTAG('f','r','e','e'):
  3118. case MKTAG('j','u','n','k'):
  3119. case MKTAG('p','i','c','t'):
  3120. return AVPROBE_SCORE_MAX - 5;
  3121. case MKTAG(0x82,0x82,0x7f,0x7d):
  3122. case MKTAG('s','k','i','p'):
  3123. case MKTAG('u','u','i','d'):
  3124. case MKTAG('p','r','f','l'):
  3125. offset = AV_RB32(p->buf+offset) + offset;
  3126. /* if we only find those cause probedata is too small at least rate them */
  3127. score = AVPROBE_SCORE_EXTENSION;
  3128. break;
  3129. default:
  3130. /* unrecognized tag */
  3131. return score;
  3132. }
  3133. }
  3134. }
  3135. // must be done after parsing all trak because there's no order requirement
  3136. static void mov_read_chapters(AVFormatContext *s)
  3137. {
  3138. MOVContext *mov = s->priv_data;
  3139. AVStream *st = NULL;
  3140. MOVStreamContext *sc;
  3141. int64_t cur_pos;
  3142. int i;
  3143. for (i = 0; i < s->nb_streams; i++)
  3144. if (s->streams[i]->id == mov->chapter_track) {
  3145. st = s->streams[i];
  3146. break;
  3147. }
  3148. if (!st) {
  3149. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  3150. return;
  3151. }
  3152. st->discard = AVDISCARD_ALL;
  3153. sc = st->priv_data;
  3154. cur_pos = avio_tell(sc->pb);
  3155. for (i = 0; i < st->nb_index_entries; i++) {
  3156. AVIndexEntry *sample = &st->index_entries[i];
  3157. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  3158. uint8_t *title;
  3159. uint16_t ch;
  3160. int len, title_len;
  3161. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3162. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  3163. goto finish;
  3164. }
  3165. // the first two bytes are the length of the title
  3166. len = avio_rb16(sc->pb);
  3167. if (len > sample->size-2)
  3168. continue;
  3169. title_len = 2*len + 1;
  3170. if (!(title = av_mallocz(title_len)))
  3171. goto finish;
  3172. // The samples could theoretically be in any encoding if there's an encd
  3173. // atom following, but in practice are only utf-8 or utf-16, distinguished
  3174. // instead by the presence of a BOM
  3175. if (!len) {
  3176. title[0] = 0;
  3177. } else {
  3178. ch = avio_rb16(sc->pb);
  3179. if (ch == 0xfeff)
  3180. avio_get_str16be(sc->pb, len, title, title_len);
  3181. else if (ch == 0xfffe)
  3182. avio_get_str16le(sc->pb, len, title, title_len);
  3183. else {
  3184. AV_WB16(title, ch);
  3185. if (len == 1 || len == 2)
  3186. title[len] = 0;
  3187. else
  3188. avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
  3189. }
  3190. }
  3191. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  3192. av_freep(&title);
  3193. }
  3194. finish:
  3195. avio_seek(sc->pb, cur_pos, SEEK_SET);
  3196. }
  3197. static int mov_read_close(AVFormatContext *s)
  3198. {
  3199. MOVContext *mov = s->priv_data;
  3200. int i, j;
  3201. for (i = 0; i < s->nb_streams; i++) {
  3202. AVStream *st = s->streams[i];
  3203. MOVStreamContext *sc = st->priv_data;
  3204. av_freep(&sc->ctts_data);
  3205. for (j = 0; j < sc->drefs_count; j++) {
  3206. av_freep(&sc->drefs[j].path);
  3207. av_freep(&sc->drefs[j].dir);
  3208. }
  3209. av_freep(&sc->drefs);
  3210. if (sc->pb && sc->pb != s->pb)
  3211. ff_format_io_close(s, &sc->pb);
  3212. av_freep(&sc->chunk_offsets);
  3213. av_freep(&sc->stsc_data);
  3214. av_freep(&sc->sample_sizes);
  3215. av_freep(&sc->keyframes);
  3216. av_freep(&sc->stts_data);
  3217. av_freep(&sc->stps_data);
  3218. av_freep(&sc->rap_group);
  3219. av_freep(&sc->display_matrix);
  3220. for (j = 0; j < sc->stsd_count; j++)
  3221. av_free(sc->extradata[j]);
  3222. av_freep(&sc->extradata);
  3223. av_freep(&sc->extradata_size);
  3224. av_freep(&sc->stereo3d);
  3225. av_freep(&sc->spherical);
  3226. }
  3227. if (mov->dv_demux) {
  3228. avformat_free_context(mov->dv_fctx);
  3229. mov->dv_fctx = NULL;
  3230. }
  3231. av_freep(&mov->trex_data);
  3232. return 0;
  3233. }
  3234. static int mov_read_header(AVFormatContext *s)
  3235. {
  3236. MOVContext *mov = s->priv_data;
  3237. AVIOContext *pb = s->pb;
  3238. int err;
  3239. MOVAtom atom = { AV_RL32("root") };
  3240. int i;
  3241. mov->fc = s;
  3242. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  3243. if (pb->seekable & AVIO_SEEKABLE_NORMAL)
  3244. atom.size = avio_size(pb);
  3245. else
  3246. atom.size = INT64_MAX;
  3247. /* check MOV header */
  3248. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  3249. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  3250. mov_read_close(s);
  3251. return err;
  3252. }
  3253. if (!mov->found_moov) {
  3254. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  3255. mov_read_close(s);
  3256. return AVERROR_INVALIDDATA;
  3257. }
  3258. av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  3259. if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && mov->chapter_track > 0)
  3260. mov_read_chapters(s);
  3261. for (i = 0; i < s->nb_streams; i++) {
  3262. AVStream *st = s->streams[i];
  3263. MOVStreamContext *sc = st->priv_data;
  3264. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  3265. if (st->codecpar->width <= 0 || st->codecpar->height <= 0) {
  3266. st->codecpar->width = sc->width;
  3267. st->codecpar->height = sc->height;
  3268. }
  3269. if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  3270. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  3271. return err;
  3272. }
  3273. }
  3274. }
  3275. if (mov->trex_data) {
  3276. for (i = 0; i < s->nb_streams; i++) {
  3277. AVStream *st = s->streams[i];
  3278. MOVStreamContext *sc = st->priv_data;
  3279. if (st->duration > 0)
  3280. st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  3281. }
  3282. }
  3283. for (i = 0; i < s->nb_streams; i++) {
  3284. AVStream *st = s->streams[i];
  3285. MOVStreamContext *sc = st->priv_data;
  3286. switch (st->codecpar->codec_type) {
  3287. case AVMEDIA_TYPE_AUDIO:
  3288. err = ff_replaygain_export(st, s->metadata);
  3289. if (err < 0) {
  3290. mov_read_close(s);
  3291. return err;
  3292. }
  3293. break;
  3294. case AVMEDIA_TYPE_VIDEO:
  3295. if (sc->display_matrix) {
  3296. err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
  3297. (uint8_t *)sc->display_matrix,
  3298. sizeof(int32_t) * 9);
  3299. if (err < 0)
  3300. return err;
  3301. sc->display_matrix = NULL;
  3302. }
  3303. if (sc->stereo3d) {
  3304. err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D,
  3305. (uint8_t *)sc->stereo3d,
  3306. sizeof(*sc->stereo3d));
  3307. if (err < 0)
  3308. return err;
  3309. sc->stereo3d = NULL;
  3310. }
  3311. if (sc->spherical) {
  3312. err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL,
  3313. (uint8_t *)sc->spherical,
  3314. sc->spherical_size);
  3315. if (err < 0)
  3316. return err;
  3317. sc->spherical = NULL;
  3318. }
  3319. break;
  3320. }
  3321. }
  3322. return 0;
  3323. }
  3324. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  3325. {
  3326. AVIndexEntry *sample = NULL;
  3327. int64_t best_dts = INT64_MAX;
  3328. int i;
  3329. for (i = 0; i < s->nb_streams; i++) {
  3330. AVStream *avst = s->streams[i];
  3331. MOVStreamContext *msc = avst->priv_data;
  3332. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  3333. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  3334. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  3335. av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  3336. if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
  3337. ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  3338. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  3339. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  3340. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  3341. sample = current_sample;
  3342. best_dts = dts;
  3343. *st = avst;
  3344. }
  3345. }
  3346. }
  3347. return sample;
  3348. }
  3349. static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt)
  3350. {
  3351. uint8_t *side, *extradata;
  3352. int extradata_size;
  3353. /* Save the current index. */
  3354. sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1;
  3355. /* Notify the decoder that extradata changed. */
  3356. extradata_size = sc->extradata_size[sc->last_stsd_index];
  3357. extradata = sc->extradata[sc->last_stsd_index];
  3358. if (extradata_size > 0 && extradata) {
  3359. side = av_packet_new_side_data(pkt,
  3360. AV_PKT_DATA_NEW_EXTRADATA,
  3361. extradata_size);
  3362. if (!side)
  3363. return AVERROR(ENOMEM);
  3364. memcpy(side, extradata, extradata_size);
  3365. }
  3366. return 0;
  3367. }
  3368. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  3369. {
  3370. MOVContext *mov = s->priv_data;
  3371. MOVStreamContext *sc;
  3372. AVIndexEntry *sample;
  3373. AVStream *st = NULL;
  3374. int ret;
  3375. retry:
  3376. sample = mov_find_next_sample(s, &st);
  3377. if (!sample) {
  3378. mov->found_mdat = 0;
  3379. if (!mov->next_root_atom)
  3380. return AVERROR_EOF;
  3381. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  3382. mov->next_root_atom = 0;
  3383. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  3384. s->pb->eof_reached)
  3385. return AVERROR_EOF;
  3386. av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  3387. goto retry;
  3388. }
  3389. sc = st->priv_data;
  3390. /* must be done just before reading, to avoid infinite loop on sample */
  3391. sc->current_sample++;
  3392. if (st->discard != AVDISCARD_ALL) {
  3393. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  3394. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  3395. sc->ffindex, sample->pos);
  3396. return AVERROR_INVALIDDATA;
  3397. }
  3398. ret = av_get_packet(sc->pb, pkt, sample->size);
  3399. if (ret < 0)
  3400. return ret;
  3401. if (sc->has_palette) {
  3402. uint8_t *pal;
  3403. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  3404. if (!pal) {
  3405. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  3406. } else {
  3407. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  3408. sc->has_palette = 0;
  3409. }
  3410. }
  3411. #if CONFIG_DV_DEMUXER
  3412. if (mov->dv_demux && sc->dv_audio_container) {
  3413. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  3414. av_free(pkt->data);
  3415. pkt->size = 0;
  3416. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  3417. if (ret < 0)
  3418. return ret;
  3419. }
  3420. #endif
  3421. }
  3422. pkt->stream_index = sc->ffindex;
  3423. pkt->dts = sample->timestamp;
  3424. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  3425. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  3426. /* update ctts context */
  3427. sc->ctts_sample++;
  3428. if (sc->ctts_index < sc->ctts_count &&
  3429. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  3430. sc->ctts_index++;
  3431. sc->ctts_sample = 0;
  3432. }
  3433. } else {
  3434. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  3435. st->index_entries[sc->current_sample].timestamp : st->duration;
  3436. pkt->duration = next_dts - pkt->dts;
  3437. pkt->pts = pkt->dts;
  3438. }
  3439. if (st->discard == AVDISCARD_ALL)
  3440. goto retry;
  3441. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  3442. pkt->pos = sample->pos;
  3443. av_log(s, AV_LOG_TRACE, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %"PRId64"\n",
  3444. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  3445. /* Multiple stsd handling. */
  3446. if (sc->stsc_data) {
  3447. /* Keep track of the stsc index for the given sample, then check
  3448. * if the stsd index is different from the last used one. */
  3449. sc->stsc_sample++;
  3450. if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) &&
  3451. mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) {
  3452. sc->stsc_index++;
  3453. sc->stsc_sample = 0;
  3454. /* Do not check indexes after a switch. */
  3455. } else if (sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) {
  3456. ret = mov_change_extradata(sc, pkt);
  3457. if (ret < 0)
  3458. return ret;
  3459. }
  3460. }
  3461. return 0;
  3462. }
  3463. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  3464. {
  3465. MOVStreamContext *sc = st->priv_data;
  3466. int sample, time_sample;
  3467. unsigned int i;
  3468. sample = av_index_search_timestamp(st, timestamp, flags);
  3469. av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  3470. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  3471. sample = 0;
  3472. if (sample < 0) /* not sure what to do */
  3473. return AVERROR_INVALIDDATA;
  3474. sc->current_sample = sample;
  3475. av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample);
  3476. /* adjust ctts index */
  3477. if (sc->ctts_data) {
  3478. time_sample = 0;
  3479. for (i = 0; i < sc->ctts_count; i++) {
  3480. int next = time_sample + sc->ctts_data[i].count;
  3481. if (next > sc->current_sample) {
  3482. sc->ctts_index = i;
  3483. sc->ctts_sample = sc->current_sample - time_sample;
  3484. break;
  3485. }
  3486. time_sample = next;
  3487. }
  3488. }
  3489. /* adjust stsd index */
  3490. time_sample = 0;
  3491. for (i = 0; i < sc->stsc_count; i++) {
  3492. int next = time_sample + mov_get_stsc_samples(sc, i);
  3493. if (next > sc->current_sample) {
  3494. sc->stsc_index = i;
  3495. sc->stsc_sample = sc->current_sample - time_sample;
  3496. break;
  3497. }
  3498. time_sample = next;
  3499. }
  3500. return sample;
  3501. }
  3502. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  3503. {
  3504. MOVContext *mc = s->priv_data;
  3505. AVStream *st;
  3506. int sample;
  3507. int i;
  3508. if (stream_index >= s->nb_streams)
  3509. return AVERROR_INVALIDDATA;
  3510. if (sample_time < 0)
  3511. sample_time = 0;
  3512. st = s->streams[stream_index];
  3513. sample = mov_seek_stream(s, st, sample_time, flags);
  3514. if (sample < 0)
  3515. return sample;
  3516. if (mc->seek_individually) {
  3517. /* adjust seek timestamp to found sample timestamp */
  3518. int64_t seek_timestamp = st->index_entries[sample].timestamp;
  3519. for (i = 0; i < s->nb_streams; i++) {
  3520. int64_t timestamp;
  3521. st = s->streams[i];
  3522. if (stream_index == i)
  3523. continue;
  3524. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  3525. mov_seek_stream(s, st, timestamp, flags);
  3526. }
  3527. } else {
  3528. for (i = 0; i < s->nb_streams; i++) {
  3529. MOVStreamContext *sc;
  3530. st = s->streams[i];
  3531. sc = st->priv_data;
  3532. sc->current_sample = 0;
  3533. }
  3534. while (1) {
  3535. MOVStreamContext *sc;
  3536. AVIndexEntry *entry = mov_find_next_sample(s, &st);
  3537. if (!entry)
  3538. return AVERROR_INVALIDDATA;
  3539. sc = st->priv_data;
  3540. if (sc->ffindex == stream_index && sc->current_sample == sample)
  3541. break;
  3542. sc->current_sample++;
  3543. }
  3544. }
  3545. return 0;
  3546. }
  3547. #define OFFSET(x) offsetof(MOVContext, x)
  3548. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  3549. static const AVOption mov_options[] = {
  3550. {"seek_streams_individually",
  3551. "Seek each stream individually to the to the closest point",
  3552. OFFSET(seek_individually), AV_OPT_TYPE_INT, { .i64 = 1 },
  3553. 0, 1, FLAGS},
  3554. { "export_all", "Export unrecognized metadata entries", OFFSET(export_all),
  3555. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3556. { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp),
  3557. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3558. { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs),
  3559. AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = FLAGS },
  3560. { NULL },
  3561. };
  3562. static const AVClass mov_class = {
  3563. .class_name = "mov,mp4,m4a,3gp,3g2,mj2",
  3564. .item_name = av_default_item_name,
  3565. .option = mov_options,
  3566. .version = LIBAVUTIL_VERSION_INT,
  3567. };
  3568. AVInputFormat ff_mov_demuxer = {
  3569. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  3570. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  3571. .priv_class = &mov_class,
  3572. .priv_data_size = sizeof(MOVContext),
  3573. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  3574. .read_probe = mov_probe,
  3575. .read_header = mov_read_header,
  3576. .read_packet = mov_read_packet,
  3577. .read_close = mov_read_close,
  3578. .read_seek = mov_read_seek,
  3579. };