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.

3328 lines
107KB

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