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.

2567 lines
85KB

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