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.

3291 lines
106KB

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