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.

3403 lines
110KB

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