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.

3096 lines
105KB

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