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.

3435 lines
111KB

  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 &&
  784. color_trc <= AVCOL_TRC_LOG_SQRT) ||
  785. color_trc >= AVCOL_TRC_BT2020_10)
  786. color_trc = AVCOL_TRC_UNSPECIFIED;
  787. if (color_matrix >= AVCOL_SPC_BT2020_NCL)
  788. color_matrix = AVCOL_SPC_UNSPECIFIED;
  789. st->codec->color_primaries = color_primaries;
  790. st->codec->color_trc = color_trc;
  791. st->codec->colorspace = color_matrix;
  792. } else {
  793. /* color primaries, Table 4-4 */
  794. switch (color_primaries) {
  795. case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;
  796. case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;
  797. case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;
  798. }
  799. /* color transfer, Table 4-5 */
  800. switch (color_trc) {
  801. case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;
  802. case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;
  803. }
  804. /* color matrix, Table 4-6 */
  805. switch (color_matrix) {
  806. case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;
  807. case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;
  808. case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;
  809. }
  810. }
  811. av_dlog(c->fc, "\n")
  812. return 0;
  813. }
  814. static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  815. {
  816. AVStream *st;
  817. unsigned mov_field_order;
  818. enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN;
  819. if (c->fc->nb_streams < 1) // will happen with jp2 files
  820. return 0;
  821. st = c->fc->streams[c->fc->nb_streams-1];
  822. if (atom.size < 2)
  823. return AVERROR_INVALIDDATA;
  824. mov_field_order = avio_rb16(pb);
  825. if ((mov_field_order & 0xFF00) == 0x0100)
  826. decoded_field_order = AV_FIELD_PROGRESSIVE;
  827. else if ((mov_field_order & 0xFF00) == 0x0200) {
  828. switch (mov_field_order & 0xFF) {
  829. case 0x01: decoded_field_order = AV_FIELD_TT;
  830. break;
  831. case 0x06: decoded_field_order = AV_FIELD_BB;
  832. break;
  833. case 0x09: decoded_field_order = AV_FIELD_TB;
  834. break;
  835. case 0x0E: decoded_field_order = AV_FIELD_BT;
  836. break;
  837. }
  838. }
  839. if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) {
  840. av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order);
  841. }
  842. st->codec->field_order = decoded_field_order;
  843. return 0;
  844. }
  845. /* FIXME modify qdm2/svq3/h264 decoders to take full atom as extradata */
  846. static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  847. {
  848. AVStream *st;
  849. uint64_t size;
  850. uint8_t *buf;
  851. int err;
  852. if (c->fc->nb_streams < 1) // will happen with jp2 files
  853. return 0;
  854. st= c->fc->streams[c->fc->nb_streams-1];
  855. size= (uint64_t)st->codec->extradata_size + atom.size + 8 + FF_INPUT_BUFFER_PADDING_SIZE;
  856. if (size > INT_MAX || (uint64_t)atom.size > INT_MAX)
  857. return AVERROR_INVALIDDATA;
  858. if ((err = av_reallocp(&st->codec->extradata, size)) < 0) {
  859. st->codec->extradata_size = 0;
  860. return err;
  861. }
  862. buf = st->codec->extradata + st->codec->extradata_size;
  863. st->codec->extradata_size= size - FF_INPUT_BUFFER_PADDING_SIZE;
  864. AV_WB32( buf , atom.size + 8);
  865. AV_WL32( buf + 4, atom.type);
  866. avio_read(pb, buf + 8, atom.size);
  867. return 0;
  868. }
  869. static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  870. {
  871. AVStream *st;
  872. if (c->fc->nb_streams < 1)
  873. return 0;
  874. st = c->fc->streams[c->fc->nb_streams-1];
  875. if ((uint64_t)atom.size > (1<<30))
  876. return AVERROR_INVALIDDATA;
  877. if (st->codec->codec_id == AV_CODEC_ID_QDM2 || st->codec->codec_id == AV_CODEC_ID_QDMC) {
  878. // pass all frma atom to codec, needed at least for QDMC and QDM2
  879. av_free(st->codec->extradata);
  880. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  881. if (!st->codec->extradata)
  882. return AVERROR(ENOMEM);
  883. st->codec->extradata_size = atom.size;
  884. avio_read(pb, st->codec->extradata, atom.size);
  885. } else if (atom.size > 8) { /* to read frma, esds atoms */
  886. int ret;
  887. if ((ret = mov_read_default(c, pb, atom)) < 0)
  888. return ret;
  889. } else
  890. avio_skip(pb, atom.size);
  891. return 0;
  892. }
  893. /**
  894. * This function reads atom content and puts data in extradata without tag
  895. * nor size unlike mov_read_extradata.
  896. */
  897. static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  898. {
  899. AVStream *st;
  900. if (c->fc->nb_streams < 1)
  901. return 0;
  902. st = c->fc->streams[c->fc->nb_streams-1];
  903. if ((uint64_t)atom.size > (1<<30))
  904. return AVERROR_INVALIDDATA;
  905. if (atom.size >= 10) {
  906. // Broken files created by legacy versions of libavformat will
  907. // wrap a whole fiel atom inside of a glbl atom.
  908. unsigned size = avio_rb32(pb);
  909. unsigned type = avio_rl32(pb);
  910. avio_seek(pb, -8, SEEK_CUR);
  911. if (type == MKTAG('f','i','e','l') && size == atom.size)
  912. return mov_read_default(c, pb, atom);
  913. }
  914. av_free(st->codec->extradata);
  915. st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);
  916. if (!st->codec->extradata)
  917. return AVERROR(ENOMEM);
  918. st->codec->extradata_size = atom.size;
  919. avio_read(pb, st->codec->extradata, atom.size);
  920. return 0;
  921. }
  922. static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  923. {
  924. AVStream *st;
  925. uint8_t profile_level;
  926. if (c->fc->nb_streams < 1)
  927. return 0;
  928. st = c->fc->streams[c->fc->nb_streams-1];
  929. if (atom.size >= (1<<28) || atom.size < 7)
  930. return AVERROR_INVALIDDATA;
  931. profile_level = avio_r8(pb);
  932. if ((profile_level & 0xf0) != 0xc0)
  933. return 0;
  934. av_free(st->codec->extradata);
  935. st->codec->extradata = av_mallocz(atom.size - 7 + FF_INPUT_BUFFER_PADDING_SIZE);
  936. if (!st->codec->extradata)
  937. return AVERROR(ENOMEM);
  938. st->codec->extradata_size = atom.size - 7;
  939. avio_seek(pb, 6, SEEK_CUR);
  940. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  941. return 0;
  942. }
  943. /**
  944. * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself,
  945. * but can have extradata appended at the end after the 40 bytes belonging
  946. * to the struct.
  947. */
  948. static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  949. {
  950. AVStream *st;
  951. if (c->fc->nb_streams < 1)
  952. return 0;
  953. if (atom.size <= 40)
  954. return 0;
  955. st = c->fc->streams[c->fc->nb_streams-1];
  956. if ((uint64_t)atom.size > (1<<30))
  957. return AVERROR_INVALIDDATA;
  958. av_free(st->codec->extradata);
  959. st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);
  960. if (!st->codec->extradata)
  961. return AVERROR(ENOMEM);
  962. st->codec->extradata_size = atom.size - 40;
  963. avio_skip(pb, 40);
  964. avio_read(pb, st->codec->extradata, atom.size - 40);
  965. return 0;
  966. }
  967. static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  968. {
  969. AVStream *st;
  970. MOVStreamContext *sc;
  971. unsigned int i, entries;
  972. if (c->fc->nb_streams < 1)
  973. return 0;
  974. st = c->fc->streams[c->fc->nb_streams-1];
  975. sc = st->priv_data;
  976. avio_r8(pb); /* version */
  977. avio_rb24(pb); /* flags */
  978. entries = avio_rb32(pb);
  979. if (!entries)
  980. return 0;
  981. if (entries >= UINT_MAX/sizeof(int64_t))
  982. return AVERROR_INVALIDDATA;
  983. sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));
  984. if (!sc->chunk_offsets)
  985. return AVERROR(ENOMEM);
  986. sc->chunk_count = entries;
  987. if (atom.type == MKTAG('s','t','c','o'))
  988. for (i = 0; i < entries && !pb->eof_reached; i++)
  989. sc->chunk_offsets[i] = avio_rb32(pb);
  990. else if (atom.type == MKTAG('c','o','6','4'))
  991. for (i = 0; i < entries && !pb->eof_reached; i++)
  992. sc->chunk_offsets[i] = avio_rb64(pb);
  993. else
  994. return AVERROR_INVALIDDATA;
  995. sc->chunk_count = i;
  996. if (pb->eof_reached)
  997. return AVERROR_EOF;
  998. return 0;
  999. }
  1000. /**
  1001. * Compute codec id for 'lpcm' tag.
  1002. * See CoreAudioTypes and AudioStreamBasicDescription at Apple.
  1003. */
  1004. enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
  1005. {
  1006. /* lpcm flags:
  1007. * 0x1 = float
  1008. * 0x2 = big-endian
  1009. * 0x4 = signed
  1010. */
  1011. return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0);
  1012. }
  1013. static int mov_codec_id(AVStream *st, uint32_t format)
  1014. {
  1015. int id = ff_codec_get_id(ff_codec_movaudio_tags, format);
  1016. if (id <= 0 &&
  1017. ((format & 0xFFFF) == 'm' + ('s' << 8) ||
  1018. (format & 0xFFFF) == 'T' + ('S' << 8)))
  1019. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF);
  1020. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  1021. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1022. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO &&
  1023. /* skip old asf mpeg4 tag */
  1024. format && format != MKTAG('m','p','4','s')) {
  1025. id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1026. if (id <= 0)
  1027. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  1028. if (id > 0)
  1029. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  1030. else if (st->codec->codec_type == AVMEDIA_TYPE_DATA) {
  1031. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  1032. if (id > 0)
  1033. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  1034. }
  1035. }
  1036. st->codec->codec_tag = format;
  1037. return id;
  1038. }
  1039. static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,
  1040. AVStream *st, MOVStreamContext *sc)
  1041. {
  1042. uint8_t codec_name[32];
  1043. unsigned int color_depth, len, j;
  1044. int color_greyscale;
  1045. int color_table_id;
  1046. avio_rb16(pb); /* version */
  1047. avio_rb16(pb); /* revision level */
  1048. avio_rb32(pb); /* vendor */
  1049. avio_rb32(pb); /* temporal quality */
  1050. avio_rb32(pb); /* spatial quality */
  1051. st->codec->width = avio_rb16(pb); /* width */
  1052. st->codec->height = avio_rb16(pb); /* height */
  1053. avio_rb32(pb); /* horiz resolution */
  1054. avio_rb32(pb); /* vert resolution */
  1055. avio_rb32(pb); /* data size, always 0 */
  1056. avio_rb16(pb); /* frames per samples */
  1057. len = avio_r8(pb); /* codec name, pascal string */
  1058. if (len > 31)
  1059. len = 31;
  1060. mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));
  1061. if (len < 31)
  1062. avio_skip(pb, 31 - len);
  1063. if (codec_name[0])
  1064. av_dict_set(&st->metadata, "encoder", codec_name, 0);
  1065. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  1066. if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
  1067. st->codec->codec_tag = MKTAG('I', '4', '2', '0');
  1068. /* Flash Media Server uses tag H263 with Sorenson Spark */
  1069. if (st->codec->codec_tag == MKTAG('H','2','6','3') &&
  1070. !memcmp(codec_name, "Sorenson H263", 13))
  1071. st->codec->codec_id = AV_CODEC_ID_FLV1;
  1072. st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */
  1073. color_table_id = avio_rb16(pb); /* colortable id */
  1074. av_dlog(c->fc, "depth %d, ctab id %d\n",
  1075. st->codec->bits_per_coded_sample, color_table_id);
  1076. /* figure out the palette situation */
  1077. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  1078. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  1079. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  1080. if ((color_depth == 2) || (color_depth == 4) || (color_depth == 8)) {
  1081. /* for palette traversal */
  1082. unsigned int color_start, color_count, color_end;
  1083. unsigned char r, g, b;
  1084. if (color_greyscale) {
  1085. int color_index, color_dec;
  1086. /* compute the greyscale palette */
  1087. st->codec->bits_per_coded_sample = color_depth;
  1088. color_count = 1 << color_depth;
  1089. color_index = 255;
  1090. color_dec = 256 / (color_count - 1);
  1091. for (j = 0; j < color_count; j++) {
  1092. r = g = b = color_index;
  1093. sc->palette[j] = (r << 16) | (g << 8) | (b);
  1094. color_index -= color_dec;
  1095. if (color_index < 0)
  1096. color_index = 0;
  1097. }
  1098. } else if (color_table_id) {
  1099. const uint8_t *color_table;
  1100. /* if flag bit 3 is set, use the default palette */
  1101. color_count = 1 << color_depth;
  1102. if (color_depth == 2)
  1103. color_table = ff_qt_default_palette_4;
  1104. else if (color_depth == 4)
  1105. color_table = ff_qt_default_palette_16;
  1106. else
  1107. color_table = ff_qt_default_palette_256;
  1108. for (j = 0; j < color_count; j++) {
  1109. r = color_table[j * 3 + 0];
  1110. g = color_table[j * 3 + 1];
  1111. b = color_table[j * 3 + 2];
  1112. sc->palette[j] = (r << 16) | (g << 8) | (b);
  1113. }
  1114. } else {
  1115. /* load the palette from the file */
  1116. color_start = avio_rb32(pb);
  1117. color_count = avio_rb16(pb);
  1118. color_end = avio_rb16(pb);
  1119. if ((color_start <= 255) && (color_end <= 255)) {
  1120. for (j = color_start; j <= color_end; j++) {
  1121. /* each R, G, or B component is 16 bits;
  1122. * only use the top 8 bits; skip alpha bytes
  1123. * up front */
  1124. avio_r8(pb);
  1125. avio_r8(pb);
  1126. r = avio_r8(pb);
  1127. avio_r8(pb);
  1128. g = avio_r8(pb);
  1129. avio_r8(pb);
  1130. b = avio_r8(pb);
  1131. avio_r8(pb);
  1132. sc->palette[j] = (r << 16) | (g << 8) | (b);
  1133. }
  1134. }
  1135. }
  1136. sc->has_palette = 1;
  1137. }
  1138. }
  1139. static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb,
  1140. AVStream *st, MOVStreamContext *sc)
  1141. {
  1142. int bits_per_sample, flags;
  1143. uint16_t version = avio_rb16(pb);
  1144. avio_rb16(pb); /* revision level */
  1145. avio_rb32(pb); /* vendor */
  1146. st->codec->channels = avio_rb16(pb); /* channel count */
  1147. st->codec->bits_per_coded_sample = avio_rb16(pb); /* sample size */
  1148. av_dlog(c->fc, "audio channels %d\n", st->codec->channels);
  1149. sc->audio_cid = avio_rb16(pb);
  1150. avio_rb16(pb); /* packet size = 0 */
  1151. st->codec->sample_rate = ((avio_rb32(pb) >> 16));
  1152. // Read QT version 1 fields. In version 0 these do not exist.
  1153. av_dlog(c->fc, "version =%d, isom =%d\n", version, c->isom);
  1154. if (!c->isom) {
  1155. if (version == 1) {
  1156. sc->samples_per_frame = avio_rb32(pb);
  1157. avio_rb32(pb); /* bytes per packet */
  1158. sc->bytes_per_frame = avio_rb32(pb);
  1159. avio_rb32(pb); /* bytes per sample */
  1160. } else if (version == 2) {
  1161. avio_rb32(pb); /* sizeof struct only */
  1162. st->codec->sample_rate = av_int2double(avio_rb64(pb));
  1163. st->codec->channels = avio_rb32(pb);
  1164. avio_rb32(pb); /* always 0x7F000000 */
  1165. st->codec->bits_per_coded_sample = avio_rb32(pb);
  1166. flags = avio_rb32(pb); /* lpcm format specific flag */
  1167. sc->bytes_per_frame = avio_rb32(pb);
  1168. sc->samples_per_frame = avio_rb32(pb);
  1169. if (st->codec->codec_tag == MKTAG('l','p','c','m'))
  1170. st->codec->codec_id =
  1171. ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample,
  1172. flags);
  1173. }
  1174. }
  1175. switch (st->codec->codec_id) {
  1176. case AV_CODEC_ID_PCM_S8:
  1177. case AV_CODEC_ID_PCM_U8:
  1178. if (st->codec->bits_per_coded_sample == 16)
  1179. st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;
  1180. break;
  1181. case AV_CODEC_ID_PCM_S16LE:
  1182. case AV_CODEC_ID_PCM_S16BE:
  1183. if (st->codec->bits_per_coded_sample == 8)
  1184. st->codec->codec_id = AV_CODEC_ID_PCM_S8;
  1185. else if (st->codec->bits_per_coded_sample == 24)
  1186. st->codec->codec_id =
  1187. st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?
  1188. AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
  1189. break;
  1190. /* set values for old format before stsd version 1 appeared */
  1191. case AV_CODEC_ID_MACE3:
  1192. sc->samples_per_frame = 6;
  1193. sc->bytes_per_frame = 2 * st->codec->channels;
  1194. break;
  1195. case AV_CODEC_ID_MACE6:
  1196. sc->samples_per_frame = 6;
  1197. sc->bytes_per_frame = 1 * st->codec->channels;
  1198. break;
  1199. case AV_CODEC_ID_ADPCM_IMA_QT:
  1200. sc->samples_per_frame = 64;
  1201. sc->bytes_per_frame = 34 * st->codec->channels;
  1202. break;
  1203. case AV_CODEC_ID_GSM:
  1204. sc->samples_per_frame = 160;
  1205. sc->bytes_per_frame = 33;
  1206. break;
  1207. default:
  1208. break;
  1209. }
  1210. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1211. if (bits_per_sample) {
  1212. st->codec->bits_per_coded_sample = bits_per_sample;
  1213. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1214. }
  1215. }
  1216. static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb,
  1217. AVStream *st, MOVStreamContext *sc,
  1218. int size)
  1219. {
  1220. // ttxt stsd contains display flags, justification, background
  1221. // color, fonts, and default styles, so fake an atom to read it
  1222. MOVAtom fake_atom = { .size = size };
  1223. // mp4s contains a regular esds atom
  1224. if (st->codec->codec_tag != AV_RL32("mp4s"))
  1225. mov_read_glbl(c, pb, fake_atom);
  1226. st->codec->width = sc->width;
  1227. st->codec->height = sc->height;
  1228. }
  1229. static uint32_t yuv_to_rgba(uint32_t ycbcr)
  1230. {
  1231. uint8_t r, g, b;
  1232. int y, cb, cr;
  1233. y = (ycbcr >> 16) & 0xFF;
  1234. cr = (ycbcr >> 8) & 0xFF;
  1235. cb = ycbcr & 0xFF;
  1236. b = av_clip_uint8(1.164 * (y - 16) + 2.018 * (cb - 128));
  1237. g = av_clip_uint8(1.164 * (y - 16) - 0.813 * (cr - 128) - 0.391 * (cb - 128));
  1238. r = av_clip_uint8(1.164 * (y - 16) + 1.596 * (cr - 128));
  1239. return (r << 16) | (g << 8) | b;
  1240. }
  1241. static int mov_rewrite_dvd_sub_extradata(AVStream *st)
  1242. {
  1243. char buf[256] = {0};
  1244. uint8_t *src = st->codec->extradata;
  1245. int i;
  1246. if (st->codec->extradata_size != 64)
  1247. return 0;
  1248. if (st->codec->width > 0 && st->codec->height > 0)
  1249. snprintf(buf, sizeof(buf), "size: %dx%d\n",
  1250. st->codec->width, st->codec->height);
  1251. av_strlcat(buf, "palette: ", sizeof(buf));
  1252. for (i = 0; i < 16; i++) {
  1253. uint32_t yuv = AV_RB32(src + i * 4);
  1254. uint32_t rgba = yuv_to_rgba(yuv);
  1255. av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : "");
  1256. }
  1257. if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf))
  1258. return 0;
  1259. av_freep(&st->codec->extradata);
  1260. st->codec->extradata_size = 0;
  1261. st->codec->extradata = av_mallocz(strlen(buf) + FF_INPUT_BUFFER_PADDING_SIZE);
  1262. if (!st->codec->extradata)
  1263. return AVERROR(ENOMEM);
  1264. st->codec->extradata_size = strlen(buf);
  1265. memcpy(st->codec->extradata, buf, st->codec->extradata_size);
  1266. return 0;
  1267. }
  1268. static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,
  1269. AVStream *st, MOVStreamContext *sc,
  1270. int size)
  1271. {
  1272. if (st->codec->codec_tag == MKTAG('t','m','c','d')) {
  1273. st->codec->extradata_size = size;
  1274. st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
  1275. if (!st->codec->extradata)
  1276. return AVERROR(ENOMEM);
  1277. avio_read(pb, st->codec->extradata, size);
  1278. } else {
  1279. /* other codec type, just skip (rtp, mp4s ...) */
  1280. avio_skip(pb, size);
  1281. }
  1282. return 0;
  1283. }
  1284. static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,
  1285. AVStream *st, MOVStreamContext *sc)
  1286. {
  1287. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1288. !st->codec->sample_rate && sc->time_scale > 1)
  1289. st->codec->sample_rate = sc->time_scale;
  1290. /* special codec parameters handling */
  1291. switch (st->codec->codec_id) {
  1292. #if CONFIG_DV_DEMUXER
  1293. case AV_CODEC_ID_DVAUDIO:
  1294. c->dv_fctx = avformat_alloc_context();
  1295. c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);
  1296. if (!c->dv_demux) {
  1297. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1298. return AVERROR(ENOMEM);
  1299. }
  1300. sc->dv_audio_container = 1;
  1301. st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
  1302. break;
  1303. #endif
  1304. /* no ifdef since parameters are always those */
  1305. case AV_CODEC_ID_QCELP:
  1306. st->codec->channels = 1;
  1307. // force sample rate for qcelp when not stored in mov
  1308. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1309. st->codec->sample_rate = 8000;
  1310. break;
  1311. case AV_CODEC_ID_AMR_NB:
  1312. st->codec->channels = 1;
  1313. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1314. st->codec->sample_rate = 8000;
  1315. break;
  1316. case AV_CODEC_ID_AMR_WB:
  1317. st->codec->channels = 1;
  1318. st->codec->sample_rate = 16000;
  1319. break;
  1320. case AV_CODEC_ID_MP2:
  1321. case AV_CODEC_ID_MP3:
  1322. /* force type after stsd for m1a hdlr */
  1323. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  1324. st->need_parsing = AVSTREAM_PARSE_FULL;
  1325. break;
  1326. case AV_CODEC_ID_GSM:
  1327. case AV_CODEC_ID_ADPCM_MS:
  1328. case AV_CODEC_ID_ADPCM_IMA_WAV:
  1329. case AV_CODEC_ID_ILBC:
  1330. st->codec->block_align = sc->bytes_per_frame;
  1331. break;
  1332. case AV_CODEC_ID_ALAC:
  1333. if (st->codec->extradata_size == 36) {
  1334. st->codec->channels = AV_RB8 (st->codec->extradata + 21);
  1335. st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);
  1336. }
  1337. break;
  1338. case AV_CODEC_ID_VC1:
  1339. st->need_parsing = AVSTREAM_PARSE_FULL;
  1340. break;
  1341. default:
  1342. break;
  1343. }
  1344. return 0;
  1345. }
  1346. static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb,
  1347. int codec_tag, int format,
  1348. int size)
  1349. {
  1350. int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format);
  1351. if (codec_tag &&
  1352. (codec_tag == AV_RL32("avc1") ||
  1353. codec_tag == AV_RL32("hvc1") ||
  1354. codec_tag == AV_RL32("hev1") ||
  1355. (codec_tag != format &&
  1356. (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id
  1357. : codec_tag != MKTAG('j','p','e','g'))))) {
  1358. /* Multiple fourcc, we skip JPEG. This is not correct, we should
  1359. * export it as a separate AVStream but this needs a few changes
  1360. * in the MOV demuxer, patch welcome. */
  1361. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  1362. avio_skip(pb, size);
  1363. return 1;
  1364. }
  1365. return 0;
  1366. }
  1367. int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)
  1368. {
  1369. AVStream *st;
  1370. MOVStreamContext *sc;
  1371. int pseudo_stream_id;
  1372. if (c->fc->nb_streams < 1)
  1373. return 0;
  1374. st = c->fc->streams[c->fc->nb_streams-1];
  1375. sc = st->priv_data;
  1376. for (pseudo_stream_id = 0;
  1377. pseudo_stream_id < entries && !pb->eof_reached;
  1378. pseudo_stream_id++) {
  1379. //Parsing Sample description table
  1380. enum AVCodecID id;
  1381. int ret, dref_id = 1;
  1382. MOVAtom a = { AV_RL32("stsd") };
  1383. int64_t start_pos = avio_tell(pb);
  1384. uint32_t size = avio_rb32(pb); /* size */
  1385. uint32_t format = avio_rl32(pb); /* data format */
  1386. if (size >= 16) {
  1387. avio_rb32(pb); /* reserved */
  1388. avio_rb16(pb); /* reserved */
  1389. dref_id = avio_rb16(pb);
  1390. } else {
  1391. av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRIu32" in stsd\n", size);
  1392. return AVERROR_INVALIDDATA;
  1393. }
  1394. if (mov_skip_multiple_stsd(c, pb, st->codec->codec_tag, format,
  1395. size - (avio_tell(pb) - start_pos)))
  1396. continue;
  1397. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  1398. sc->dref_id= dref_id;
  1399. id = mov_codec_id(st, format);
  1400. av_dlog(c->fc, "size=%"PRIu32" 4CC= %"PRIu8"%"PRIu8"%"PRIu8"%"PRIu8" codec_type=%d\n", size,
  1401. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  1402. (format >> 24) & 0xff, st->codec->codec_type);
  1403. if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  1404. st->codec->codec_id = id;
  1405. mov_parse_stsd_video(c, pb, st, sc);
  1406. } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  1407. st->codec->codec_id = id;
  1408. mov_parse_stsd_audio(c, pb, st, sc);
  1409. } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1410. st->codec->codec_id = id;
  1411. mov_parse_stsd_subtitle(c, pb, st, sc,
  1412. size - (avio_tell(pb) - start_pos));
  1413. } else {
  1414. ret = mov_parse_stsd_data(c, pb, st, sc,
  1415. size - (avio_tell(pb) - start_pos));
  1416. if (ret < 0)
  1417. return ret;
  1418. }
  1419. /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */
  1420. a.size = size - (avio_tell(pb) - start_pos);
  1421. if (a.size > 8) {
  1422. if ((ret = mov_read_default(c, pb, a)) < 0)
  1423. return ret;
  1424. } else if (a.size > 0)
  1425. avio_skip(pb, a.size);
  1426. }
  1427. if (pb->eof_reached)
  1428. return AVERROR_EOF;
  1429. return mov_finalize_stsd_codec(c, pb, st, sc);
  1430. }
  1431. static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1432. {
  1433. int entries;
  1434. avio_r8(pb); /* version */
  1435. avio_rb24(pb); /* flags */
  1436. entries = avio_rb32(pb);
  1437. return ff_mov_read_stsd_entries(c, pb, entries);
  1438. }
  1439. static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1440. {
  1441. AVStream *st;
  1442. MOVStreamContext *sc;
  1443. unsigned int i, entries;
  1444. if (c->fc->nb_streams < 1)
  1445. return 0;
  1446. st = c->fc->streams[c->fc->nb_streams-1];
  1447. sc = st->priv_data;
  1448. avio_r8(pb); /* version */
  1449. avio_rb24(pb); /* flags */
  1450. entries = avio_rb32(pb);
  1451. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1452. if (!entries)
  1453. return 0;
  1454. if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1455. return AVERROR_INVALIDDATA;
  1456. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1457. if (!sc->stsc_data)
  1458. return AVERROR(ENOMEM);
  1459. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1460. sc->stsc_data[i].first = avio_rb32(pb);
  1461. sc->stsc_data[i].count = avio_rb32(pb);
  1462. sc->stsc_data[i].id = avio_rb32(pb);
  1463. }
  1464. sc->stsc_count = i;
  1465. if (pb->eof_reached)
  1466. return AVERROR_EOF;
  1467. return 0;
  1468. }
  1469. static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1470. {
  1471. AVStream *st;
  1472. MOVStreamContext *sc;
  1473. unsigned i, entries;
  1474. if (c->fc->nb_streams < 1)
  1475. return 0;
  1476. st = c->fc->streams[c->fc->nb_streams-1];
  1477. sc = st->priv_data;
  1478. avio_rb32(pb); // version + flags
  1479. entries = avio_rb32(pb);
  1480. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1481. return AVERROR_INVALIDDATA;
  1482. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1483. if (!sc->stps_data)
  1484. return AVERROR(ENOMEM);
  1485. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1486. sc->stps_data[i] = avio_rb32(pb);
  1487. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1488. }
  1489. sc->stps_count = i;
  1490. if (pb->eof_reached)
  1491. return AVERROR_EOF;
  1492. return 0;
  1493. }
  1494. static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1495. {
  1496. AVStream *st;
  1497. MOVStreamContext *sc;
  1498. unsigned int i, entries;
  1499. if (c->fc->nb_streams < 1)
  1500. return 0;
  1501. st = c->fc->streams[c->fc->nb_streams-1];
  1502. sc = st->priv_data;
  1503. avio_r8(pb); /* version */
  1504. avio_rb24(pb); /* flags */
  1505. entries = avio_rb32(pb);
  1506. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1507. if (!entries)
  1508. {
  1509. sc->keyframe_absent = 1;
  1510. return 0;
  1511. }
  1512. if (entries >= UINT_MAX / sizeof(int))
  1513. return AVERROR_INVALIDDATA;
  1514. sc->keyframes = av_malloc(entries * sizeof(int));
  1515. if (!sc->keyframes)
  1516. return AVERROR(ENOMEM);
  1517. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1518. sc->keyframes[i] = avio_rb32(pb);
  1519. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1520. }
  1521. sc->keyframe_count = i;
  1522. if (pb->eof_reached)
  1523. return AVERROR_EOF;
  1524. return 0;
  1525. }
  1526. static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1527. {
  1528. AVStream *st;
  1529. MOVStreamContext *sc;
  1530. unsigned int i, entries, sample_size, field_size, num_bytes;
  1531. GetBitContext gb;
  1532. unsigned char* buf;
  1533. if (c->fc->nb_streams < 1)
  1534. return 0;
  1535. st = c->fc->streams[c->fc->nb_streams-1];
  1536. sc = st->priv_data;
  1537. avio_r8(pb); /* version */
  1538. avio_rb24(pb); /* flags */
  1539. if (atom.type == MKTAG('s','t','s','z')) {
  1540. sample_size = avio_rb32(pb);
  1541. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1542. sc->sample_size = sample_size;
  1543. field_size = 32;
  1544. } else {
  1545. sample_size = 0;
  1546. avio_rb24(pb); /* reserved */
  1547. field_size = avio_r8(pb);
  1548. }
  1549. entries = avio_rb32(pb);
  1550. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1551. sc->sample_count = entries;
  1552. if (sample_size)
  1553. return 0;
  1554. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1555. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1556. return AVERROR_INVALIDDATA;
  1557. }
  1558. if (!entries)
  1559. return 0;
  1560. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1561. return AVERROR_INVALIDDATA;
  1562. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1563. if (!sc->sample_sizes)
  1564. return AVERROR(ENOMEM);
  1565. num_bytes = (entries*field_size+4)>>3;
  1566. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1567. if (!buf) {
  1568. av_freep(&sc->sample_sizes);
  1569. return AVERROR(ENOMEM);
  1570. }
  1571. if (avio_read(pb, buf, num_bytes) < num_bytes) {
  1572. av_freep(&sc->sample_sizes);
  1573. av_free(buf);
  1574. return AVERROR_INVALIDDATA;
  1575. }
  1576. init_get_bits(&gb, buf, 8*num_bytes);
  1577. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1578. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1579. sc->data_size += sc->sample_sizes[i];
  1580. }
  1581. sc->sample_count = i;
  1582. if (pb->eof_reached)
  1583. return AVERROR_EOF;
  1584. av_free(buf);
  1585. return 0;
  1586. }
  1587. static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1588. {
  1589. AVStream *st;
  1590. MOVStreamContext *sc;
  1591. unsigned int i, entries;
  1592. int64_t duration=0;
  1593. int64_t total_sample_count=0;
  1594. if (c->fc->nb_streams < 1)
  1595. return 0;
  1596. st = c->fc->streams[c->fc->nb_streams-1];
  1597. sc = st->priv_data;
  1598. avio_r8(pb); /* version */
  1599. avio_rb24(pb); /* flags */
  1600. entries = avio_rb32(pb);
  1601. av_dlog(c->fc, "track[%i].stts.entries = %i\n",
  1602. c->fc->nb_streams-1, entries);
  1603. if (!entries)
  1604. return 0;
  1605. if (entries >= UINT_MAX / sizeof(*sc->stts_data))
  1606. return AVERROR(EINVAL);
  1607. av_free(sc->stts_data);
  1608. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1609. if (!sc->stts_data)
  1610. return AVERROR(ENOMEM);
  1611. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1612. int sample_duration;
  1613. int sample_count;
  1614. sample_count=avio_rb32(pb);
  1615. sample_duration = avio_rb32(pb);
  1616. if (sample_count < 0) {
  1617. av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count);
  1618. return AVERROR_INVALIDDATA;
  1619. }
  1620. sc->stts_data[i].count= sample_count;
  1621. sc->stts_data[i].duration= sample_duration;
  1622. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",
  1623. sample_count, sample_duration);
  1624. duration+=(int64_t)sample_duration*sample_count;
  1625. total_sample_count+=sample_count;
  1626. }
  1627. sc->stts_count = i;
  1628. if (pb->eof_reached)
  1629. return AVERROR_EOF;
  1630. st->nb_frames= total_sample_count;
  1631. if (duration)
  1632. st->duration= duration;
  1633. sc->track_end = duration;
  1634. return 0;
  1635. }
  1636. static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1637. {
  1638. AVStream *st;
  1639. MOVStreamContext *sc;
  1640. unsigned int i, entries;
  1641. if (c->fc->nb_streams < 1)
  1642. return 0;
  1643. st = c->fc->streams[c->fc->nb_streams-1];
  1644. sc = st->priv_data;
  1645. avio_r8(pb); /* version */
  1646. avio_rb24(pb); /* flags */
  1647. entries = avio_rb32(pb);
  1648. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1649. if (!entries)
  1650. return 0;
  1651. if (entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1652. return AVERROR_INVALIDDATA;
  1653. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1654. if (!sc->ctts_data)
  1655. return AVERROR(ENOMEM);
  1656. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1657. int count =avio_rb32(pb);
  1658. int duration =avio_rb32(pb);
  1659. sc->ctts_data[i].count = count;
  1660. sc->ctts_data[i].duration= duration;
  1661. if (duration < 0)
  1662. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1663. }
  1664. sc->ctts_count = i;
  1665. if (pb->eof_reached)
  1666. return AVERROR_EOF;
  1667. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1668. return 0;
  1669. }
  1670. static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1671. {
  1672. AVStream *st;
  1673. MOVStreamContext *sc;
  1674. unsigned int i, entries;
  1675. uint8_t version;
  1676. uint32_t grouping_type;
  1677. if (c->fc->nb_streams < 1)
  1678. return 0;
  1679. st = c->fc->streams[c->fc->nb_streams-1];
  1680. sc = st->priv_data;
  1681. version = avio_r8(pb); /* version */
  1682. avio_rb24(pb); /* flags */
  1683. grouping_type = avio_rl32(pb);
  1684. if (grouping_type != MKTAG( 'r','a','p',' '))
  1685. return 0; /* only support 'rap ' grouping */
  1686. if (version == 1)
  1687. avio_rb32(pb); /* grouping_type_parameter */
  1688. entries = avio_rb32(pb);
  1689. if (!entries)
  1690. return 0;
  1691. if (entries >= UINT_MAX / sizeof(*sc->rap_group))
  1692. return AVERROR_INVALIDDATA;
  1693. sc->rap_group = av_malloc(entries * sizeof(*sc->rap_group));
  1694. if (!sc->rap_group)
  1695. return AVERROR(ENOMEM);
  1696. for (i = 0; i < entries && !pb->eof_reached; i++) {
  1697. sc->rap_group[i].count = avio_rb32(pb); /* sample_count */
  1698. sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */
  1699. }
  1700. sc->rap_group_count = i;
  1701. return pb->eof_reached ? AVERROR_EOF : 0;
  1702. }
  1703. static void mov_build_index(MOVContext *mov, AVStream *st)
  1704. {
  1705. MOVStreamContext *sc = st->priv_data;
  1706. int64_t current_offset;
  1707. int64_t current_dts = 0;
  1708. unsigned int stts_index = 0;
  1709. unsigned int stsc_index = 0;
  1710. unsigned int stss_index = 0;
  1711. unsigned int stps_index = 0;
  1712. unsigned int i, j;
  1713. uint64_t stream_size = 0;
  1714. /* adjust first dts according to edit list */
  1715. if (sc->time_offset && mov->time_scale > 0) {
  1716. if (sc->time_offset < 0)
  1717. sc->time_offset = av_rescale(sc->time_offset, sc->time_scale, mov->time_scale);
  1718. current_dts = -sc->time_offset;
  1719. if (sc->ctts_data && sc->stts_data && sc->stts_data[0].duration &&
  1720. sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1721. /* more than 16 frames delay, dts are likely wrong
  1722. this happens with files created by iMovie */
  1723. sc->wrong_dts = 1;
  1724. st->codec->has_b_frames = 1;
  1725. }
  1726. }
  1727. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1728. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1729. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1730. unsigned int current_sample = 0;
  1731. unsigned int stts_sample = 0;
  1732. unsigned int sample_size;
  1733. unsigned int distance = 0;
  1734. unsigned int rap_group_index = 0;
  1735. unsigned int rap_group_sample = 0;
  1736. int rap_group_present = sc->rap_group_count && sc->rap_group;
  1737. int key_off = (sc->keyframes && sc->keyframes[0] > 0) || (sc->stps_data && sc->stps_data[0] > 0);
  1738. current_dts -= sc->dts_shift;
  1739. if (!sc->sample_count)
  1740. return;
  1741. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1742. return;
  1743. if (av_reallocp_array(&st->index_entries,
  1744. st->nb_index_entries + sc->sample_count,
  1745. sizeof(*st->index_entries)) < 0) {
  1746. st->nb_index_entries = 0;
  1747. return;
  1748. }
  1749. st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries);
  1750. for (i = 0; i < sc->chunk_count; i++) {
  1751. current_offset = sc->chunk_offsets[i];
  1752. while (stsc_index + 1 < sc->stsc_count &&
  1753. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1754. stsc_index++;
  1755. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1756. int keyframe = 0;
  1757. if (current_sample >= sc->sample_count) {
  1758. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1759. return;
  1760. }
  1761. if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) {
  1762. keyframe = 1;
  1763. if (stss_index + 1 < sc->keyframe_count)
  1764. stss_index++;
  1765. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1766. keyframe = 1;
  1767. if (stps_index + 1 < sc->stps_count)
  1768. stps_index++;
  1769. }
  1770. if (rap_group_present && rap_group_index < sc->rap_group_count) {
  1771. if (sc->rap_group[rap_group_index].index > 0)
  1772. keyframe = 1;
  1773. if (++rap_group_sample == sc->rap_group[rap_group_index].count) {
  1774. rap_group_sample = 0;
  1775. rap_group_index++;
  1776. }
  1777. }
  1778. if (keyframe)
  1779. distance = 0;
  1780. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1781. if (sc->pseudo_stream_id == -1 ||
  1782. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1783. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1784. e->pos = current_offset;
  1785. e->timestamp = current_dts;
  1786. e->size = sample_size;
  1787. e->min_distance = distance;
  1788. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1789. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1790. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1791. current_offset, current_dts, sample_size, distance, keyframe);
  1792. }
  1793. current_offset += sample_size;
  1794. stream_size += sample_size;
  1795. current_dts += sc->stts_data[stts_index].duration;
  1796. distance++;
  1797. stts_sample++;
  1798. current_sample++;
  1799. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1800. stts_sample = 0;
  1801. stts_index++;
  1802. }
  1803. }
  1804. }
  1805. if (st->duration > 0)
  1806. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1807. } else {
  1808. unsigned chunk_samples, total = 0;
  1809. // compute total chunk count
  1810. for (i = 0; i < sc->stsc_count; i++) {
  1811. unsigned count, chunk_count;
  1812. chunk_samples = sc->stsc_data[i].count;
  1813. if (i != sc->stsc_count - 1 &&
  1814. sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1815. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1816. return;
  1817. }
  1818. if (sc->samples_per_frame >= 160) { // gsm
  1819. count = chunk_samples / sc->samples_per_frame;
  1820. } else if (sc->samples_per_frame > 1) {
  1821. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1822. count = (chunk_samples+samples-1) / samples;
  1823. } else {
  1824. count = (chunk_samples+1023) / 1024;
  1825. }
  1826. if (i < sc->stsc_count - 1)
  1827. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1828. else
  1829. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1830. total += chunk_count * count;
  1831. }
  1832. av_dlog(mov->fc, "chunk count %d\n", total);
  1833. if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries)
  1834. return;
  1835. if (av_reallocp_array(&st->index_entries,
  1836. st->nb_index_entries + total,
  1837. sizeof(*st->index_entries)) < 0) {
  1838. st->nb_index_entries = 0;
  1839. return;
  1840. }
  1841. st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries);
  1842. // populate index
  1843. for (i = 0; i < sc->chunk_count; i++) {
  1844. current_offset = sc->chunk_offsets[i];
  1845. if (stsc_index + 1 < sc->stsc_count &&
  1846. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1847. stsc_index++;
  1848. chunk_samples = sc->stsc_data[stsc_index].count;
  1849. while (chunk_samples > 0) {
  1850. AVIndexEntry *e;
  1851. unsigned size, samples;
  1852. if (sc->samples_per_frame >= 160) { // gsm
  1853. samples = sc->samples_per_frame;
  1854. size = sc->bytes_per_frame;
  1855. } else {
  1856. if (sc->samples_per_frame > 1) {
  1857. samples = FFMIN((1024 / sc->samples_per_frame)*
  1858. sc->samples_per_frame, chunk_samples);
  1859. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1860. } else {
  1861. samples = FFMIN(1024, chunk_samples);
  1862. size = samples * sc->sample_size;
  1863. }
  1864. }
  1865. if (st->nb_index_entries >= total) {
  1866. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1867. return;
  1868. }
  1869. e = &st->index_entries[st->nb_index_entries++];
  1870. e->pos = current_offset;
  1871. e->timestamp = current_dts;
  1872. e->size = size;
  1873. e->min_distance = 0;
  1874. e->flags = AVINDEX_KEYFRAME;
  1875. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1876. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1877. size, samples);
  1878. current_offset += size;
  1879. current_dts += samples;
  1880. chunk_samples -= samples;
  1881. }
  1882. }
  1883. }
  1884. }
  1885. static int mov_open_dref(AVIOContext **pb, char *src, MOVDref *ref,
  1886. AVIOInterruptCB *int_cb)
  1887. {
  1888. /* try relative path, we do not try the absolute because it can leak information about our
  1889. system to an attacker */
  1890. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1891. char filename[1024];
  1892. char *src_path;
  1893. int i, l;
  1894. /* find a source dir */
  1895. src_path = strrchr(src, '/');
  1896. if (src_path)
  1897. src_path++;
  1898. else
  1899. src_path = src;
  1900. /* find a next level down to target */
  1901. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1902. if (ref->path[l] == '/') {
  1903. if (i == ref->nlvl_to - 1)
  1904. break;
  1905. else
  1906. i++;
  1907. }
  1908. /* compose filename if next level down to target was found */
  1909. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1910. memcpy(filename, src, src_path - src);
  1911. filename[src_path - src] = 0;
  1912. for (i = 1; i < ref->nlvl_from; i++)
  1913. av_strlcat(filename, "../", 1024);
  1914. av_strlcat(filename, ref->path + l + 1, 1024);
  1915. if (!avio_open2(pb, filename, AVIO_FLAG_READ, int_cb, NULL))
  1916. return 0;
  1917. }
  1918. }
  1919. return AVERROR(ENOENT);
  1920. }
  1921. static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  1922. {
  1923. AVStream *st;
  1924. MOVStreamContext *sc;
  1925. int ret;
  1926. st = avformat_new_stream(c->fc, NULL);
  1927. if (!st) return AVERROR(ENOMEM);
  1928. st->id = c->fc->nb_streams;
  1929. sc = av_mallocz(sizeof(MOVStreamContext));
  1930. if (!sc) return AVERROR(ENOMEM);
  1931. st->priv_data = sc;
  1932. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1933. sc->ffindex = st->index;
  1934. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1935. return ret;
  1936. /* sanity checks */
  1937. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1938. (!sc->sample_size && !sc->sample_count))) {
  1939. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1940. st->index);
  1941. return 0;
  1942. }
  1943. if (sc->time_scale <= 0) {
  1944. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1945. sc->time_scale = c->time_scale;
  1946. if (sc->time_scale <= 0)
  1947. sc->time_scale = 1;
  1948. }
  1949. avpriv_set_pts_info(st, 64, 1, sc->time_scale);
  1950. mov_build_index(c, st);
  1951. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1952. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1953. if (mov_open_dref(&sc->pb, c->fc->filename, dref, &c->fc->interrupt_callback) < 0)
  1954. av_log(c->fc, AV_LOG_ERROR,
  1955. "stream %d, error opening alias: path='%s', dir='%s', "
  1956. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1957. st->index, dref->path, dref->dir, dref->filename,
  1958. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1959. } else
  1960. sc->pb = c->fc->pb;
  1961. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1962. if (!st->sample_aspect_ratio.num &&
  1963. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1964. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1965. ((double)st->codec->width * sc->height), INT_MAX);
  1966. }
  1967. }
  1968. // done for ai5q, ai52, ai55, ai1q, ai12 and ai15.
  1969. if (!st->codec->extradata_size && st->codec->codec_id == AV_CODEC_ID_H264 &&
  1970. TAG_IS_AVCI(st->codec->codec_tag)) {
  1971. ret = ff_generate_avci_extradata(st);
  1972. if (ret < 0)
  1973. return ret;
  1974. }
  1975. switch (st->codec->codec_id) {
  1976. #if CONFIG_H261_DECODER
  1977. case AV_CODEC_ID_H261:
  1978. #endif
  1979. #if CONFIG_H263_DECODER
  1980. case AV_CODEC_ID_H263:
  1981. #endif
  1982. #if CONFIG_MPEG4_DECODER
  1983. case AV_CODEC_ID_MPEG4:
  1984. #endif
  1985. st->codec->width = 0; /* let decoder init width/height */
  1986. st->codec->height= 0;
  1987. break;
  1988. }
  1989. /* Do not need those anymore. */
  1990. av_freep(&sc->chunk_offsets);
  1991. av_freep(&sc->stsc_data);
  1992. av_freep(&sc->sample_sizes);
  1993. av_freep(&sc->keyframes);
  1994. av_freep(&sc->stts_data);
  1995. av_freep(&sc->stps_data);
  1996. av_freep(&sc->rap_group);
  1997. return 0;
  1998. }
  1999. static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2000. {
  2001. int ret;
  2002. c->itunes_metadata = 1;
  2003. ret = mov_read_default(c, pb, atom);
  2004. c->itunes_metadata = 0;
  2005. return ret;
  2006. }
  2007. static int mov_read_replaygain(MOVContext *c, AVIOContext *pb, int size)
  2008. {
  2009. int64_t end = avio_tell(pb) + size;
  2010. uint8_t *key = NULL, *val = NULL;
  2011. int i;
  2012. for (i = 0; i < 2; i++) {
  2013. uint8_t **p;
  2014. uint32_t len, tag;
  2015. if (end - avio_tell(pb) <= 12)
  2016. break;
  2017. len = avio_rb32(pb);
  2018. tag = avio_rl32(pb);
  2019. avio_skip(pb, 4); // flags
  2020. if (len < 12 || len - 12 > end - avio_tell(pb))
  2021. break;
  2022. len -= 12;
  2023. if (tag == MKTAG('n', 'a', 'm', 'e'))
  2024. p = &key;
  2025. else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) {
  2026. avio_skip(pb, 4);
  2027. len -= 4;
  2028. p = &val;
  2029. } else
  2030. break;
  2031. *p = av_malloc(len + 1);
  2032. if (!*p)
  2033. break;
  2034. avio_read(pb, *p, len);
  2035. (*p)[len] = 0;
  2036. }
  2037. if (key && val) {
  2038. av_dict_set(&c->fc->metadata, key, val,
  2039. AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
  2040. key = val = NULL;
  2041. }
  2042. avio_seek(pb, end, SEEK_SET);
  2043. av_freep(&key);
  2044. av_freep(&val);
  2045. return 0;
  2046. }
  2047. static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2048. {
  2049. int64_t end = avio_tell(pb) + atom.size;
  2050. uint32_t tag, len;
  2051. if (atom.size < 8)
  2052. goto fail;
  2053. len = avio_rb32(pb);
  2054. tag = avio_rl32(pb);
  2055. if (len > atom.size)
  2056. goto fail;
  2057. if (tag == MKTAG('m', 'e', 'a', 'n') && len > 12) {
  2058. uint8_t domain[128];
  2059. int domain_len;
  2060. avio_skip(pb, 4); // flags
  2061. len -= 12;
  2062. domain_len = avio_get_str(pb, len, domain, sizeof(domain));
  2063. avio_skip(pb, len - domain_len);
  2064. if (!strcmp(domain, "org.hydrogenaudio.replaygain"))
  2065. return mov_read_replaygain(c, pb, end - avio_tell(pb));
  2066. }
  2067. fail:
  2068. av_log(c->fc, AV_LOG_VERBOSE,
  2069. "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size);
  2070. return 0;
  2071. }
  2072. static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2073. {
  2074. while (atom.size > 8) {
  2075. uint32_t tag = avio_rl32(pb);
  2076. atom.size -= 4;
  2077. if (tag == MKTAG('h','d','l','r')) {
  2078. avio_seek(pb, -8, SEEK_CUR);
  2079. atom.size += 8;
  2080. return mov_read_default(c, pb, atom);
  2081. }
  2082. }
  2083. return 0;
  2084. }
  2085. static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2086. {
  2087. int i;
  2088. int width;
  2089. int height;
  2090. int64_t disp_transform[2];
  2091. int display_matrix[3][3];
  2092. AVStream *st;
  2093. MOVStreamContext *sc;
  2094. int version;
  2095. int flags;
  2096. if (c->fc->nb_streams < 1)
  2097. return 0;
  2098. st = c->fc->streams[c->fc->nb_streams-1];
  2099. sc = st->priv_data;
  2100. version = avio_r8(pb);
  2101. flags = avio_rb24(pb);
  2102. st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;
  2103. if (version == 1) {
  2104. avio_rb64(pb);
  2105. avio_rb64(pb);
  2106. } else {
  2107. avio_rb32(pb); /* creation time */
  2108. avio_rb32(pb); /* modification time */
  2109. }
  2110. st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/
  2111. avio_rb32(pb); /* reserved */
  2112. /* highlevel (considering edits) duration in movie timebase */
  2113. (version == 1) ? avio_rb64(pb) : avio_rb32(pb);
  2114. avio_rb32(pb); /* reserved */
  2115. avio_rb32(pb); /* reserved */
  2116. avio_rb16(pb); /* layer */
  2117. avio_rb16(pb); /* alternate group */
  2118. avio_rb16(pb); /* volume */
  2119. avio_rb16(pb); /* reserved */
  2120. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  2121. // they're kept in fixed point format through all calculations
  2122. // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX
  2123. // side data, but the scale factor is not needed to calculate aspect ratio
  2124. for (i = 0; i < 3; i++) {
  2125. display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point
  2126. display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point
  2127. display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point
  2128. }
  2129. width = avio_rb32(pb); // 16.16 fixed point track width
  2130. height = avio_rb32(pb); // 16.16 fixed point track height
  2131. sc->width = width >> 16;
  2132. sc->height = height >> 16;
  2133. // save the matrix when it is not the default identity
  2134. if (display_matrix[0][0] != (1 << 16) ||
  2135. display_matrix[1][1] != (1 << 16) ||
  2136. display_matrix[2][2] != (1 << 30) ||
  2137. display_matrix[0][1] || display_matrix[0][2] ||
  2138. display_matrix[1][0] || display_matrix[1][2] ||
  2139. display_matrix[2][0] || display_matrix[2][1]) {
  2140. int i, j;
  2141. av_freep(&sc->display_matrix);
  2142. sc->display_matrix = av_malloc(sizeof(int32_t) * 9);
  2143. if (!sc->display_matrix)
  2144. return AVERROR(ENOMEM);
  2145. for (i = 0; i < 3; i++)
  2146. for (j = 0; j < 3; j++)
  2147. sc->display_matrix[i * 3 + j] = display_matrix[j][i];
  2148. }
  2149. // transform the display width/height according to the matrix
  2150. // skip this if the display matrix is the default identity matrix
  2151. // or if it is rotating the picture, ex iPhone 3GS
  2152. // to keep the same scale, use [width height 1<<16]
  2153. if (width && height &&
  2154. ((display_matrix[0][0] != 65536 ||
  2155. display_matrix[1][1] != 65536) &&
  2156. !display_matrix[0][1] &&
  2157. !display_matrix[1][0] &&
  2158. !display_matrix[2][0] && !display_matrix[2][1])) {
  2159. for (i = 0; i < 2; i++)
  2160. disp_transform[i] =
  2161. (int64_t) width * display_matrix[0][i] +
  2162. (int64_t) height * display_matrix[1][i] +
  2163. ((int64_t) display_matrix[2][i] << 16);
  2164. //sample aspect ratio is new width/height divided by old width/height
  2165. st->sample_aspect_ratio = av_d2q(
  2166. ((double) disp_transform[0] * height) /
  2167. ((double) disp_transform[1] * width), INT_MAX);
  2168. }
  2169. return 0;
  2170. }
  2171. static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2172. {
  2173. MOVFragment *frag = &c->fragment;
  2174. MOVTrackExt *trex = NULL;
  2175. int flags, track_id, i;
  2176. avio_r8(pb); /* version */
  2177. flags = avio_rb24(pb);
  2178. track_id = avio_rb32(pb);
  2179. if (!track_id)
  2180. return AVERROR_INVALIDDATA;
  2181. frag->track_id = track_id;
  2182. for (i = 0; i < c->trex_count; i++)
  2183. if (c->trex_data[i].track_id == frag->track_id) {
  2184. trex = &c->trex_data[i];
  2185. break;
  2186. }
  2187. if (!trex) {
  2188. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  2189. return AVERROR_INVALIDDATA;
  2190. }
  2191. frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ?
  2192. avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ?
  2193. frag->moof_offset : frag->implicit_offset;
  2194. frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id;
  2195. frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ?
  2196. avio_rb32(pb) : trex->duration;
  2197. frag->size = flags & MOV_TFHD_DEFAULT_SIZE ?
  2198. avio_rb32(pb) : trex->size;
  2199. frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ?
  2200. avio_rb32(pb) : trex->flags;
  2201. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  2202. return 0;
  2203. }
  2204. static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2205. {
  2206. c->chapter_track = avio_rb32(pb);
  2207. return 0;
  2208. }
  2209. static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2210. {
  2211. MOVTrackExt *trex;
  2212. int err;
  2213. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  2214. return AVERROR_INVALIDDATA;
  2215. if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1,
  2216. sizeof(*c->trex_data))) < 0) {
  2217. c->trex_count = 0;
  2218. return err;
  2219. }
  2220. trex = &c->trex_data[c->trex_count++];
  2221. avio_r8(pb); /* version */
  2222. avio_rb24(pb); /* flags */
  2223. trex->track_id = avio_rb32(pb);
  2224. trex->stsd_id = avio_rb32(pb);
  2225. trex->duration = avio_rb32(pb);
  2226. trex->size = avio_rb32(pb);
  2227. trex->flags = avio_rb32(pb);
  2228. return 0;
  2229. }
  2230. static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2231. {
  2232. MOVFragment *frag = &c->fragment;
  2233. AVStream *st = NULL;
  2234. MOVStreamContext *sc;
  2235. int version, i;
  2236. for (i = 0; i < c->fc->nb_streams; i++) {
  2237. if (c->fc->streams[i]->id == frag->track_id) {
  2238. st = c->fc->streams[i];
  2239. break;
  2240. }
  2241. }
  2242. if (!st) {
  2243. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2244. return AVERROR_INVALIDDATA;
  2245. }
  2246. sc = st->priv_data;
  2247. if (sc->pseudo_stream_id + 1 != frag->stsd_id)
  2248. return 0;
  2249. version = avio_r8(pb);
  2250. avio_rb24(pb); /* flags */
  2251. if (version) {
  2252. sc->track_end = avio_rb64(pb);
  2253. } else {
  2254. sc->track_end = avio_rb32(pb);
  2255. }
  2256. return 0;
  2257. }
  2258. static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2259. {
  2260. MOVFragment *frag = &c->fragment;
  2261. AVStream *st = NULL;
  2262. MOVStreamContext *sc;
  2263. MOVStts *ctts_data;
  2264. uint64_t offset;
  2265. int64_t dts;
  2266. int data_offset = 0;
  2267. unsigned entries, first_sample_flags = frag->flags;
  2268. int flags, distance, i, found_keyframe = 0, err;
  2269. for (i = 0; i < c->fc->nb_streams; i++) {
  2270. if (c->fc->streams[i]->id == frag->track_id) {
  2271. st = c->fc->streams[i];
  2272. break;
  2273. }
  2274. }
  2275. if (!st) {
  2276. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  2277. return AVERROR_INVALIDDATA;
  2278. }
  2279. sc = st->priv_data;
  2280. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  2281. return 0;
  2282. avio_r8(pb); /* version */
  2283. flags = avio_rb24(pb);
  2284. entries = avio_rb32(pb);
  2285. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  2286. /* Always assume the presence of composition time offsets.
  2287. * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.
  2288. * 1) in the initial movie, there are no samples.
  2289. * 2) in the first movie fragment, there is only one sample without composition time offset.
  2290. * 3) in the subsequent movie fragments, there are samples with composition time offset. */
  2291. if (!sc->ctts_count && sc->sample_count)
  2292. {
  2293. /* Complement ctts table if moov atom doesn't have ctts atom. */
  2294. ctts_data = av_realloc(NULL, sizeof(*sc->ctts_data));
  2295. if (!ctts_data)
  2296. return AVERROR(ENOMEM);
  2297. sc->ctts_data = ctts_data;
  2298. sc->ctts_data[sc->ctts_count].count = sc->sample_count;
  2299. sc->ctts_data[sc->ctts_count].duration = 0;
  2300. sc->ctts_count++;
  2301. }
  2302. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  2303. return AVERROR_INVALIDDATA;
  2304. if ((err = av_reallocp_array(&sc->ctts_data, entries + sc->ctts_count,
  2305. sizeof(*sc->ctts_data))) < 0) {
  2306. sc->ctts_count = 0;
  2307. return err;
  2308. }
  2309. if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb);
  2310. if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);
  2311. dts = sc->track_end - sc->time_offset;
  2312. offset = frag->base_data_offset + data_offset;
  2313. distance = 0;
  2314. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  2315. for (i = 0; i < entries && !pb->eof_reached; i++) {
  2316. unsigned sample_size = frag->size;
  2317. int sample_flags = i ? frag->flags : first_sample_flags;
  2318. unsigned sample_duration = frag->duration;
  2319. int keyframe = 0;
  2320. if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);
  2321. if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb);
  2322. if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb);
  2323. sc->ctts_data[sc->ctts_count].count = 1;
  2324. sc->ctts_data[sc->ctts_count].duration = (flags & MOV_TRUN_SAMPLE_CTS) ?
  2325. avio_rb32(pb) : 0;
  2326. sc->ctts_count++;
  2327. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  2328. keyframe = 1;
  2329. else if (!found_keyframe)
  2330. keyframe = found_keyframe =
  2331. !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |
  2332. MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));
  2333. if (keyframe)
  2334. distance = 0;
  2335. av_add_index_entry(st, offset, dts, sample_size, distance,
  2336. keyframe ? AVINDEX_KEYFRAME : 0);
  2337. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  2338. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  2339. offset, dts, sample_size, distance, keyframe);
  2340. distance++;
  2341. dts += sample_duration;
  2342. offset += sample_size;
  2343. sc->data_size += sample_size;
  2344. }
  2345. if (pb->eof_reached)
  2346. return AVERROR_EOF;
  2347. frag->implicit_offset = offset;
  2348. st->duration = sc->track_end = dts + sc->time_offset;
  2349. return 0;
  2350. }
  2351. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  2352. /* like the files created with Adobe Premiere 5.0, for samples see */
  2353. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  2354. static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2355. {
  2356. int err;
  2357. if (atom.size < 8)
  2358. return 0; /* continue */
  2359. if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  2360. avio_skip(pb, atom.size - 4);
  2361. return 0;
  2362. }
  2363. atom.type = avio_rl32(pb);
  2364. atom.size -= 8;
  2365. if (atom.type != MKTAG('m','d','a','t')) {
  2366. avio_skip(pb, atom.size);
  2367. return 0;
  2368. }
  2369. err = mov_read_mdat(c, pb, atom);
  2370. return err;
  2371. }
  2372. static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2373. {
  2374. #if CONFIG_ZLIB
  2375. AVIOContext ctx;
  2376. uint8_t *cmov_data;
  2377. uint8_t *moov_data; /* uncompressed data */
  2378. long cmov_len, moov_len;
  2379. int ret = -1;
  2380. avio_rb32(pb); /* dcom atom */
  2381. if (avio_rl32(pb) != MKTAG('d','c','o','m'))
  2382. return AVERROR_INVALIDDATA;
  2383. if (avio_rl32(pb) != MKTAG('z','l','i','b')) {
  2384. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  2385. return AVERROR_INVALIDDATA;
  2386. }
  2387. avio_rb32(pb); /* cmvd atom */
  2388. if (avio_rl32(pb) != MKTAG('c','m','v','d'))
  2389. return AVERROR_INVALIDDATA;
  2390. moov_len = avio_rb32(pb); /* uncompressed size */
  2391. cmov_len = atom.size - 6 * 4;
  2392. cmov_data = av_malloc(cmov_len);
  2393. if (!cmov_data)
  2394. return AVERROR(ENOMEM);
  2395. moov_data = av_malloc(moov_len);
  2396. if (!moov_data) {
  2397. av_free(cmov_data);
  2398. return AVERROR(ENOMEM);
  2399. }
  2400. avio_read(pb, cmov_data, cmov_len);
  2401. if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  2402. goto free_and_return;
  2403. if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  2404. goto free_and_return;
  2405. atom.type = MKTAG('m','o','o','v');
  2406. atom.size = moov_len;
  2407. ret = mov_read_default(c, &ctx, atom);
  2408. free_and_return:
  2409. av_free(moov_data);
  2410. av_free(cmov_data);
  2411. return ret;
  2412. #else
  2413. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  2414. return AVERROR(ENOSYS);
  2415. #endif
  2416. }
  2417. /* edit list atom */
  2418. static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2419. {
  2420. MOVStreamContext *sc;
  2421. int i, edit_count, version;
  2422. if (c->fc->nb_streams < 1)
  2423. return 0;
  2424. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  2425. version = avio_r8(pb); /* version */
  2426. avio_rb24(pb); /* flags */
  2427. edit_count = avio_rb32(pb); /* entries */
  2428. if ((uint64_t)edit_count*12+8 > atom.size)
  2429. return AVERROR_INVALIDDATA;
  2430. for (i=0; i<edit_count; i++){
  2431. int64_t time;
  2432. int64_t duration;
  2433. if (version == 1) {
  2434. duration = avio_rb64(pb);
  2435. time = avio_rb64(pb);
  2436. } else {
  2437. duration = avio_rb32(pb); /* segment duration */
  2438. time = (int32_t)avio_rb32(pb); /* media time */
  2439. }
  2440. avio_rb32(pb); /* Media rate */
  2441. if (i == 0 && time >= -1) {
  2442. sc->time_offset = time != -1 ? time : -duration;
  2443. }
  2444. }
  2445. if (edit_count > 1)
  2446. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  2447. "a/v desync might occur, patch welcome\n");
  2448. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  2449. return 0;
  2450. }
  2451. static const MOVParseTableEntry mov_default_parse_table[] = {
  2452. { MKTAG('a','v','s','s'), mov_read_extradata },
  2453. { MKTAG('c','h','p','l'), mov_read_chpl },
  2454. { MKTAG('c','o','6','4'), mov_read_stco },
  2455. { MKTAG('c','o','l','r'), mov_read_colr },
  2456. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  2457. { MKTAG('d','i','n','f'), mov_read_default },
  2458. { MKTAG('d','r','e','f'), mov_read_dref },
  2459. { MKTAG('e','d','t','s'), mov_read_default },
  2460. { MKTAG('e','l','s','t'), mov_read_elst },
  2461. { MKTAG('e','n','d','a'), mov_read_enda },
  2462. { MKTAG('f','i','e','l'), mov_read_fiel },
  2463. { MKTAG('f','t','y','p'), mov_read_ftyp },
  2464. { MKTAG('g','l','b','l'), mov_read_glbl },
  2465. { MKTAG('h','d','l','r'), mov_read_hdlr },
  2466. { MKTAG('i','l','s','t'), mov_read_ilst },
  2467. { MKTAG('j','p','2','h'), mov_read_extradata },
  2468. { MKTAG('m','d','a','t'), mov_read_mdat },
  2469. { MKTAG('m','d','h','d'), mov_read_mdhd },
  2470. { MKTAG('m','d','i','a'), mov_read_default },
  2471. { MKTAG('m','e','t','a'), mov_read_meta },
  2472. { MKTAG('m','i','n','f'), mov_read_default },
  2473. { MKTAG('m','o','o','f'), mov_read_moof },
  2474. { MKTAG('m','o','o','v'), mov_read_moov },
  2475. { MKTAG('m','v','e','x'), mov_read_default },
  2476. { MKTAG('m','v','h','d'), mov_read_mvhd },
  2477. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  2478. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  2479. { MKTAG('a','v','c','C'), mov_read_glbl },
  2480. { MKTAG('p','a','s','p'), mov_read_pasp },
  2481. { MKTAG('s','t','b','l'), mov_read_default },
  2482. { MKTAG('s','t','c','o'), mov_read_stco },
  2483. { MKTAG('s','t','p','s'), mov_read_stps },
  2484. { MKTAG('s','t','r','f'), mov_read_strf },
  2485. { MKTAG('s','t','s','c'), mov_read_stsc },
  2486. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  2487. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  2488. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  2489. { MKTAG('s','t','t','s'), mov_read_stts },
  2490. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  2491. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  2492. { MKTAG('t','f','d','t'), mov_read_tfdt },
  2493. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  2494. { MKTAG('t','r','a','k'), mov_read_trak },
  2495. { MKTAG('t','r','a','f'), mov_read_default },
  2496. { MKTAG('t','r','e','f'), mov_read_default },
  2497. { MKTAG('c','h','a','p'), mov_read_chap },
  2498. { MKTAG('t','r','e','x'), mov_read_trex },
  2499. { MKTAG('t','r','u','n'), mov_read_trun },
  2500. { MKTAG('u','d','t','a'), mov_read_default },
  2501. { MKTAG('w','a','v','e'), mov_read_wave },
  2502. { MKTAG('e','s','d','s'), mov_read_esds },
  2503. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  2504. { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */
  2505. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  2506. { MKTAG('w','f','e','x'), mov_read_wfex },
  2507. { MKTAG('c','m','o','v'), mov_read_cmov },
  2508. { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */
  2509. { MKTAG('d','v','c','1'), mov_read_dvc1 },
  2510. { MKTAG('s','b','g','p'), mov_read_sbgp },
  2511. { MKTAG('h','v','c','C'), mov_read_glbl },
  2512. { MKTAG('-','-','-','-'), mov_read_custom },
  2513. { 0, NULL }
  2514. };
  2515. static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom)
  2516. {
  2517. int64_t total_size = 0;
  2518. MOVAtom a;
  2519. int i;
  2520. if (atom.size < 0)
  2521. atom.size = INT64_MAX;
  2522. while (total_size + 8 < atom.size && !pb->eof_reached) {
  2523. int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL;
  2524. a.size = atom.size;
  2525. a.type=0;
  2526. if (atom.size >= 8) {
  2527. a.size = avio_rb32(pb);
  2528. a.type = avio_rl32(pb);
  2529. }
  2530. av_dlog(c->fc, "type: %08x '%.4s' parent:'%.4s' sz: %"PRId64" %"PRId64" %"PRId64"\n",
  2531. a.type, (char*)&a.type, (char*)&atom.type, a.size, total_size, atom.size);
  2532. total_size += 8;
  2533. if (a.size == 1) { /* 64 bit extended size */
  2534. a.size = avio_rb64(pb) - 8;
  2535. total_size += 8;
  2536. }
  2537. if (a.size == 0) {
  2538. a.size = atom.size - total_size;
  2539. if (a.size <= 8)
  2540. break;
  2541. }
  2542. a.size -= 8;
  2543. if (a.size < 0)
  2544. break;
  2545. a.size = FFMIN(a.size, atom.size - total_size);
  2546. for (i = 0; mov_default_parse_table[i].type; i++)
  2547. if (mov_default_parse_table[i].type == a.type) {
  2548. parse = mov_default_parse_table[i].parse;
  2549. break;
  2550. }
  2551. // container is user data
  2552. if (!parse && (atom.type == MKTAG('u','d','t','a') ||
  2553. atom.type == MKTAG('i','l','s','t')))
  2554. parse = mov_read_udta_string;
  2555. if (!parse) { /* skip leaf atoms data */
  2556. avio_skip(pb, a.size);
  2557. } else {
  2558. int64_t start_pos = avio_tell(pb);
  2559. int64_t left;
  2560. int err = parse(c, pb, a);
  2561. if (err < 0)
  2562. return err;
  2563. if (c->found_moov && c->found_mdat &&
  2564. ((!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX) ||
  2565. start_pos + a.size == avio_size(pb))) {
  2566. if (!pb->seekable || c->fc->flags & AVFMT_FLAG_IGNIDX)
  2567. c->next_root_atom = start_pos + a.size;
  2568. return 0;
  2569. }
  2570. left = a.size - avio_tell(pb) + start_pos;
  2571. if (left > 0) /* skip garbage at atom end */
  2572. avio_skip(pb, left);
  2573. else if (left < 0) {
  2574. av_log(c->fc, AV_LOG_WARNING,
  2575. "overread end of atom '%.4s' by %"PRId64" bytes\n",
  2576. (char*)&a.type, -left);
  2577. avio_seek(pb, left, SEEK_CUR);
  2578. }
  2579. }
  2580. total_size += a.size;
  2581. }
  2582. if (total_size < atom.size && atom.size < 0x7ffff)
  2583. avio_skip(pb, atom.size - total_size);
  2584. return 0;
  2585. }
  2586. static int mov_probe(AVProbeData *p)
  2587. {
  2588. unsigned int offset;
  2589. uint32_t tag;
  2590. int score = 0;
  2591. /* check file header */
  2592. offset = 0;
  2593. for (;;) {
  2594. /* ignore invalid offset */
  2595. if ((offset + 8) > (unsigned int)p->buf_size)
  2596. return score;
  2597. tag = AV_RL32(p->buf + offset + 4);
  2598. switch(tag) {
  2599. /* check for obvious tags */
  2600. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  2601. case MKTAG('m','o','o','v'):
  2602. case MKTAG('m','d','a','t'):
  2603. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  2604. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  2605. case MKTAG('f','t','y','p'):
  2606. return AVPROBE_SCORE_MAX;
  2607. /* those are more common words, so rate then a bit less */
  2608. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  2609. case MKTAG('w','i','d','e'):
  2610. case MKTAG('f','r','e','e'):
  2611. case MKTAG('j','u','n','k'):
  2612. case MKTAG('p','i','c','t'):
  2613. return AVPROBE_SCORE_MAX - 5;
  2614. case MKTAG(0x82,0x82,0x7f,0x7d):
  2615. case MKTAG('s','k','i','p'):
  2616. case MKTAG('u','u','i','d'):
  2617. case MKTAG('p','r','f','l'):
  2618. offset = AV_RB32(p->buf+offset) + offset;
  2619. /* if we only find those cause probedata is too small at least rate them */
  2620. score = AVPROBE_SCORE_EXTENSION;
  2621. break;
  2622. default:
  2623. /* unrecognized tag */
  2624. return score;
  2625. }
  2626. }
  2627. }
  2628. // must be done after parsing all trak because there's no order requirement
  2629. static void mov_read_chapters(AVFormatContext *s)
  2630. {
  2631. MOVContext *mov = s->priv_data;
  2632. AVStream *st = NULL;
  2633. MOVStreamContext *sc;
  2634. int64_t cur_pos;
  2635. int i;
  2636. for (i = 0; i < s->nb_streams; i++)
  2637. if (s->streams[i]->id == mov->chapter_track) {
  2638. st = s->streams[i];
  2639. break;
  2640. }
  2641. if (!st) {
  2642. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  2643. return;
  2644. }
  2645. st->discard = AVDISCARD_ALL;
  2646. sc = st->priv_data;
  2647. cur_pos = avio_tell(sc->pb);
  2648. for (i = 0; i < st->nb_index_entries; i++) {
  2649. AVIndexEntry *sample = &st->index_entries[i];
  2650. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2651. uint8_t *title;
  2652. uint16_t ch;
  2653. int len, title_len;
  2654. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2655. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2656. goto finish;
  2657. }
  2658. // the first two bytes are the length of the title
  2659. len = avio_rb16(sc->pb);
  2660. if (len > sample->size-2)
  2661. continue;
  2662. title_len = 2*len + 1;
  2663. if (!(title = av_mallocz(title_len)))
  2664. goto finish;
  2665. // The samples could theoretically be in any encoding if there's an encd
  2666. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2667. // instead by the presence of a BOM
  2668. if (!len) {
  2669. title[0] = 0;
  2670. } else {
  2671. ch = avio_rb16(sc->pb);
  2672. if (ch == 0xfeff)
  2673. avio_get_str16be(sc->pb, len, title, title_len);
  2674. else if (ch == 0xfffe)
  2675. avio_get_str16le(sc->pb, len, title, title_len);
  2676. else {
  2677. AV_WB16(title, ch);
  2678. if (len == 1 || len == 2)
  2679. title[len] = 0;
  2680. else
  2681. avio_get_str(sc->pb, len - 2, title + 2, title_len - 2);
  2682. }
  2683. }
  2684. avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2685. av_freep(&title);
  2686. }
  2687. finish:
  2688. avio_seek(sc->pb, cur_pos, SEEK_SET);
  2689. }
  2690. static int mov_read_close(AVFormatContext *s)
  2691. {
  2692. MOVContext *mov = s->priv_data;
  2693. int i, j;
  2694. for (i = 0; i < s->nb_streams; i++) {
  2695. AVStream *st = s->streams[i];
  2696. MOVStreamContext *sc = st->priv_data;
  2697. av_freep(&sc->ctts_data);
  2698. for (j = 0; j < sc->drefs_count; j++) {
  2699. av_freep(&sc->drefs[j].path);
  2700. av_freep(&sc->drefs[j].dir);
  2701. }
  2702. av_freep(&sc->drefs);
  2703. if (sc->pb && sc->pb != s->pb)
  2704. avio_close(sc->pb);
  2705. av_freep(&sc->chunk_offsets);
  2706. av_freep(&sc->stsc_data);
  2707. av_freep(&sc->sample_sizes);
  2708. av_freep(&sc->keyframes);
  2709. av_freep(&sc->stts_data);
  2710. av_freep(&sc->stps_data);
  2711. av_freep(&sc->rap_group);
  2712. av_freep(&sc->display_matrix);
  2713. }
  2714. if (mov->dv_demux) {
  2715. avformat_free_context(mov->dv_fctx);
  2716. mov->dv_fctx = NULL;
  2717. }
  2718. av_freep(&mov->trex_data);
  2719. return 0;
  2720. }
  2721. static int mov_read_header(AVFormatContext *s)
  2722. {
  2723. MOVContext *mov = s->priv_data;
  2724. AVIOContext *pb = s->pb;
  2725. int err;
  2726. MOVAtom atom = { AV_RL32("root") };
  2727. int i;
  2728. mov->fc = s;
  2729. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2730. if (pb->seekable)
  2731. atom.size = avio_size(pb);
  2732. else
  2733. atom.size = INT64_MAX;
  2734. /* check MOV header */
  2735. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2736. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2737. mov_read_close(s);
  2738. return err;
  2739. }
  2740. if (!mov->found_moov) {
  2741. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2742. mov_read_close(s);
  2743. return AVERROR_INVALIDDATA;
  2744. }
  2745. av_dlog(mov->fc, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb));
  2746. if (pb->seekable && mov->chapter_track > 0)
  2747. mov_read_chapters(s);
  2748. for (i = 0; i < s->nb_streams; i++) {
  2749. AVStream *st = s->streams[i];
  2750. MOVStreamContext *sc = st->priv_data;
  2751. if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  2752. if (st->codec->width <= 0 && st->codec->width <= 0) {
  2753. st->codec->width = sc->width;
  2754. st->codec->height = sc->height;
  2755. }
  2756. if (st->codec->codec_id == AV_CODEC_ID_DVD_SUBTITLE) {
  2757. if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0)
  2758. return err;
  2759. }
  2760. }
  2761. }
  2762. if (mov->trex_data) {
  2763. for (i = 0; i < s->nb_streams; i++) {
  2764. AVStream *st = s->streams[i];
  2765. MOVStreamContext *sc = st->priv_data;
  2766. if (st->duration > 0)
  2767. st->codec->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration;
  2768. }
  2769. }
  2770. for (i = 0; i < s->nb_streams; i++) {
  2771. AVStream *st = s->streams[i];
  2772. MOVStreamContext *sc = st->priv_data;
  2773. switch (st->codec->codec_type) {
  2774. case AVMEDIA_TYPE_AUDIO:
  2775. err = ff_replaygain_export(st, s->metadata);
  2776. if (err < 0) {
  2777. mov_read_close(s);
  2778. return err;
  2779. }
  2780. break;
  2781. case AVMEDIA_TYPE_VIDEO:
  2782. if (sc->display_matrix) {
  2783. AVPacketSideData *sd, *tmp;
  2784. tmp = av_realloc_array(st->side_data,
  2785. st->nb_side_data + 1, sizeof(*tmp));
  2786. if (!tmp)
  2787. return AVERROR(ENOMEM);
  2788. st->side_data = tmp;
  2789. st->nb_side_data++;
  2790. sd = &st->side_data[st->nb_side_data - 1];
  2791. sd->type = AV_PKT_DATA_DISPLAYMATRIX;
  2792. sd->size = sizeof(int32_t) * 9;
  2793. sd->data = (uint8_t*)sc->display_matrix;
  2794. sc->display_matrix = NULL;
  2795. }
  2796. break;
  2797. }
  2798. }
  2799. return 0;
  2800. }
  2801. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2802. {
  2803. AVIndexEntry *sample = NULL;
  2804. int64_t best_dts = INT64_MAX;
  2805. int i;
  2806. for (i = 0; i < s->nb_streams; i++) {
  2807. AVStream *avst = s->streams[i];
  2808. MOVStreamContext *msc = avst->priv_data;
  2809. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2810. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2811. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2812. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2813. if (!sample || (!s->pb->seekable && current_sample->pos < sample->pos) ||
  2814. (s->pb->seekable &&
  2815. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2816. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2817. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2818. sample = current_sample;
  2819. best_dts = dts;
  2820. *st = avst;
  2821. }
  2822. }
  2823. }
  2824. return sample;
  2825. }
  2826. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2827. {
  2828. MOVContext *mov = s->priv_data;
  2829. MOVStreamContext *sc;
  2830. AVIndexEntry *sample;
  2831. AVStream *st = NULL;
  2832. int ret;
  2833. retry:
  2834. sample = mov_find_next_sample(s, &st);
  2835. if (!sample) {
  2836. mov->found_mdat = 0;
  2837. if (!mov->next_root_atom)
  2838. return AVERROR_EOF;
  2839. avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
  2840. mov->next_root_atom = 0;
  2841. if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2842. s->pb->eof_reached)
  2843. return AVERROR_EOF;
  2844. av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
  2845. goto retry;
  2846. }
  2847. sc = st->priv_data;
  2848. /* must be done just before reading, to avoid infinite loop on sample */
  2849. sc->current_sample++;
  2850. if (st->discard != AVDISCARD_ALL) {
  2851. if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2852. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2853. sc->ffindex, sample->pos);
  2854. return AVERROR_INVALIDDATA;
  2855. }
  2856. ret = av_get_packet(sc->pb, pkt, sample->size);
  2857. if (ret < 0)
  2858. return ret;
  2859. if (sc->has_palette) {
  2860. uint8_t *pal;
  2861. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  2862. if (!pal) {
  2863. av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
  2864. } else {
  2865. memcpy(pal, sc->palette, AVPALETTE_SIZE);
  2866. sc->has_palette = 0;
  2867. }
  2868. }
  2869. #if CONFIG_DV_DEMUXER
  2870. if (mov->dv_demux && sc->dv_audio_container) {
  2871. avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  2872. av_free(pkt->data);
  2873. pkt->size = 0;
  2874. ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
  2875. if (ret < 0)
  2876. return ret;
  2877. }
  2878. #endif
  2879. }
  2880. pkt->stream_index = sc->ffindex;
  2881. pkt->dts = sample->timestamp;
  2882. if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
  2883. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2884. /* update ctts context */
  2885. sc->ctts_sample++;
  2886. if (sc->ctts_index < sc->ctts_count &&
  2887. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2888. sc->ctts_index++;
  2889. sc->ctts_sample = 0;
  2890. }
  2891. if (sc->wrong_dts)
  2892. pkt->dts = AV_NOPTS_VALUE;
  2893. } else {
  2894. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2895. st->index_entries[sc->current_sample].timestamp : st->duration;
  2896. pkt->duration = next_dts - pkt->dts;
  2897. pkt->pts = pkt->dts;
  2898. }
  2899. if (st->discard == AVDISCARD_ALL)
  2900. goto retry;
  2901. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2902. pkt->pos = sample->pos;
  2903. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2904. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2905. return 0;
  2906. }
  2907. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2908. {
  2909. MOVStreamContext *sc = st->priv_data;
  2910. int sample, time_sample;
  2911. int i;
  2912. sample = av_index_search_timestamp(st, timestamp, flags);
  2913. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2914. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2915. sample = 0;
  2916. if (sample < 0) /* not sure what to do */
  2917. return AVERROR_INVALIDDATA;
  2918. sc->current_sample = sample;
  2919. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2920. /* adjust ctts index */
  2921. if (sc->ctts_data) {
  2922. time_sample = 0;
  2923. for (i = 0; i < sc->ctts_count; i++) {
  2924. int next = time_sample + sc->ctts_data[i].count;
  2925. if (next > sc->current_sample) {
  2926. sc->ctts_index = i;
  2927. sc->ctts_sample = sc->current_sample - time_sample;
  2928. break;
  2929. }
  2930. time_sample = next;
  2931. }
  2932. }
  2933. return sample;
  2934. }
  2935. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2936. {
  2937. AVStream *st;
  2938. int64_t seek_timestamp, timestamp;
  2939. int sample;
  2940. int i;
  2941. if (stream_index >= s->nb_streams)
  2942. return AVERROR_INVALIDDATA;
  2943. if (sample_time < 0)
  2944. sample_time = 0;
  2945. st = s->streams[stream_index];
  2946. sample = mov_seek_stream(s, st, sample_time, flags);
  2947. if (sample < 0)
  2948. return sample;
  2949. /* adjust seek timestamp to found sample timestamp */
  2950. seek_timestamp = st->index_entries[sample].timestamp;
  2951. for (i = 0; i < s->nb_streams; i++) {
  2952. st = s->streams[i];
  2953. if (stream_index == i)
  2954. continue;
  2955. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2956. mov_seek_stream(s, st, timestamp, flags);
  2957. }
  2958. return 0;
  2959. }
  2960. AVInputFormat ff_mov_demuxer = {
  2961. .name = "mov,mp4,m4a,3gp,3g2,mj2",
  2962. .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
  2963. .priv_data_size = sizeof(MOVContext),
  2964. .extensions = "mov,mp4,m4a,3gp,3g2,mj2",
  2965. .read_probe = mov_probe,
  2966. .read_header = mov_read_header,
  2967. .read_packet = mov_read_packet,
  2968. .read_close = mov_read_close,
  2969. .read_seek = mov_read_seek,
  2970. };