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.

2784 lines
93KB

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