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.

3850 lines
127KB

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