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.

3333 lines
108KB

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