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.

3085 lines
104KB

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