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.

2572 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. multiple_stsd:
  807. av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");
  808. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  809. continue;
  810. }
  811. /* we cannot demux concatenated h264 streams because of different extradata */
  812. if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))
  813. goto multiple_stsd;
  814. sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;
  815. sc->dref_id= dref_id;
  816. st->codec->codec_tag = format;
  817. id = ff_codec_get_id(codec_movaudio_tags, format);
  818. if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))
  819. id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);
  820. if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {
  821. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  822. } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */
  823. format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */
  824. id = ff_codec_get_id(codec_movvideo_tags, format);
  825. if (id <= 0)
  826. id = ff_codec_get_id(ff_codec_bmp_tags, format);
  827. if (id > 0)
  828. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  829. else if(st->codec->codec_type == AVMEDIA_TYPE_DATA){
  830. id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);
  831. if(id > 0)
  832. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  833. }
  834. }
  835. dprintf(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,
  836. (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,
  837. (format >> 24) & 0xff, st->codec->codec_type);
  838. if(st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
  839. unsigned int color_depth, len;
  840. int color_greyscale;
  841. st->codec->codec_id = id;
  842. get_be16(pb); /* version */
  843. get_be16(pb); /* revision level */
  844. get_be32(pb); /* vendor */
  845. get_be32(pb); /* temporal quality */
  846. get_be32(pb); /* spatial quality */
  847. st->codec->width = get_be16(pb); /* width */
  848. st->codec->height = get_be16(pb); /* height */
  849. get_be32(pb); /* horiz resolution */
  850. get_be32(pb); /* vert resolution */
  851. get_be32(pb); /* data size, always 0 */
  852. get_be16(pb); /* frames per samples */
  853. len = get_byte(pb); /* codec name, pascal string */
  854. if (len > 31)
  855. len = 31;
  856. mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);
  857. if (len < 31)
  858. url_fskip(pb, 31 - len);
  859. /* codec_tag YV12 triggers an UV swap in rawdec.c */
  860. if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))
  861. st->codec->codec_tag=MKTAG('I', '4', '2', '0');
  862. st->codec->bits_per_coded_sample = get_be16(pb); /* depth */
  863. st->codec->color_table_id = get_be16(pb); /* colortable id */
  864. dprintf(c->fc, "depth %d, ctab id %d\n",
  865. st->codec->bits_per_coded_sample, st->codec->color_table_id);
  866. /* figure out the palette situation */
  867. color_depth = st->codec->bits_per_coded_sample & 0x1F;
  868. color_greyscale = st->codec->bits_per_coded_sample & 0x20;
  869. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  870. if ((color_depth == 2) || (color_depth == 4) ||
  871. (color_depth == 8)) {
  872. /* for palette traversal */
  873. unsigned int color_start, color_count, color_end;
  874. unsigned char r, g, b;
  875. st->codec->palctrl = av_malloc(sizeof(*st->codec->palctrl));
  876. if (color_greyscale) {
  877. int color_index, color_dec;
  878. /* compute the greyscale palette */
  879. st->codec->bits_per_coded_sample = color_depth;
  880. color_count = 1 << color_depth;
  881. color_index = 255;
  882. color_dec = 256 / (color_count - 1);
  883. for (j = 0; j < color_count; j++) {
  884. r = g = b = color_index;
  885. st->codec->palctrl->palette[j] =
  886. (r << 16) | (g << 8) | (b);
  887. color_index -= color_dec;
  888. if (color_index < 0)
  889. color_index = 0;
  890. }
  891. } else if (st->codec->color_table_id) {
  892. const uint8_t *color_table;
  893. /* if flag bit 3 is set, use the default palette */
  894. color_count = 1 << color_depth;
  895. if (color_depth == 2)
  896. color_table = ff_qt_default_palette_4;
  897. else if (color_depth == 4)
  898. color_table = ff_qt_default_palette_16;
  899. else
  900. color_table = ff_qt_default_palette_256;
  901. for (j = 0; j < color_count; j++) {
  902. r = color_table[j * 3 + 0];
  903. g = color_table[j * 3 + 1];
  904. b = color_table[j * 3 + 2];
  905. st->codec->palctrl->palette[j] =
  906. (r << 16) | (g << 8) | (b);
  907. }
  908. } else {
  909. /* load the palette from the file */
  910. color_start = get_be32(pb);
  911. color_count = get_be16(pb);
  912. color_end = get_be16(pb);
  913. if ((color_start <= 255) &&
  914. (color_end <= 255)) {
  915. for (j = color_start; j <= color_end; j++) {
  916. /* each R, G, or B component is 16 bits;
  917. * only use the top 8 bits; skip alpha bytes
  918. * up front */
  919. get_byte(pb);
  920. get_byte(pb);
  921. r = get_byte(pb);
  922. get_byte(pb);
  923. g = get_byte(pb);
  924. get_byte(pb);
  925. b = get_byte(pb);
  926. get_byte(pb);
  927. st->codec->palctrl->palette[j] =
  928. (r << 16) | (g << 8) | (b);
  929. }
  930. }
  931. }
  932. st->codec->palctrl->palette_changed = 1;
  933. }
  934. } else if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {
  935. int bits_per_sample, flags;
  936. uint16_t version = get_be16(pb);
  937. st->codec->codec_id = id;
  938. get_be16(pb); /* revision level */
  939. get_be32(pb); /* vendor */
  940. st->codec->channels = get_be16(pb); /* channel count */
  941. dprintf(c->fc, "audio channels %d\n", st->codec->channels);
  942. st->codec->bits_per_coded_sample = get_be16(pb); /* sample size */
  943. sc->audio_cid = get_be16(pb);
  944. get_be16(pb); /* packet size = 0 */
  945. st->codec->sample_rate = ((get_be32(pb) >> 16));
  946. //Read QT version 1 fields. In version 0 these do not exist.
  947. dprintf(c->fc, "version =%d, isom =%d\n",version,c->isom);
  948. if(!c->isom) {
  949. if(version==1) {
  950. sc->samples_per_frame = get_be32(pb);
  951. get_be32(pb); /* bytes per packet */
  952. sc->bytes_per_frame = get_be32(pb);
  953. get_be32(pb); /* bytes per sample */
  954. } else if(version==2) {
  955. get_be32(pb); /* sizeof struct only */
  956. st->codec->sample_rate = av_int2dbl(get_be64(pb)); /* float 64 */
  957. st->codec->channels = get_be32(pb);
  958. get_be32(pb); /* always 0x7F000000 */
  959. st->codec->bits_per_coded_sample = get_be32(pb); /* bits per channel if sound is uncompressed */
  960. flags = get_be32(pb); /* lpcm format specific flag */
  961. sc->bytes_per_frame = get_be32(pb); /* bytes per audio packet if constant */
  962. sc->samples_per_frame = get_be32(pb); /* lpcm frames per audio packet if constant */
  963. if (format == MKTAG('l','p','c','m'))
  964. st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);
  965. }
  966. }
  967. switch (st->codec->codec_id) {
  968. case CODEC_ID_PCM_S8:
  969. case CODEC_ID_PCM_U8:
  970. if (st->codec->bits_per_coded_sample == 16)
  971. st->codec->codec_id = CODEC_ID_PCM_S16BE;
  972. break;
  973. case CODEC_ID_PCM_S16LE:
  974. case CODEC_ID_PCM_S16BE:
  975. if (st->codec->bits_per_coded_sample == 8)
  976. st->codec->codec_id = CODEC_ID_PCM_S8;
  977. else if (st->codec->bits_per_coded_sample == 24)
  978. st->codec->codec_id =
  979. st->codec->codec_id == CODEC_ID_PCM_S16BE ?
  980. CODEC_ID_PCM_S24BE : CODEC_ID_PCM_S24LE;
  981. break;
  982. /* set values for old format before stsd version 1 appeared */
  983. case CODEC_ID_MACE3:
  984. sc->samples_per_frame = 6;
  985. sc->bytes_per_frame = 2*st->codec->channels;
  986. break;
  987. case CODEC_ID_MACE6:
  988. sc->samples_per_frame = 6;
  989. sc->bytes_per_frame = 1*st->codec->channels;
  990. break;
  991. case CODEC_ID_ADPCM_IMA_QT:
  992. sc->samples_per_frame = 64;
  993. sc->bytes_per_frame = 34*st->codec->channels;
  994. break;
  995. case CODEC_ID_GSM:
  996. sc->samples_per_frame = 160;
  997. sc->bytes_per_frame = 33;
  998. break;
  999. default:
  1000. break;
  1001. }
  1002. bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);
  1003. if (bits_per_sample) {
  1004. st->codec->bits_per_coded_sample = bits_per_sample;
  1005. sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;
  1006. }
  1007. } else if(st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){
  1008. // ttxt stsd contains display flags, justification, background
  1009. // color, fonts, and default styles, so fake an atom to read it
  1010. MOVAtom fake_atom = { .size = size - (url_ftell(pb) - start_pos) };
  1011. if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom
  1012. mov_read_glbl(c, pb, fake_atom);
  1013. st->codec->codec_id= id;
  1014. st->codec->width = sc->width;
  1015. st->codec->height = sc->height;
  1016. } else {
  1017. /* other codec type, just skip (rtp, mp4s, tmcd ...) */
  1018. url_fskip(pb, size - (url_ftell(pb) - start_pos));
  1019. }
  1020. /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */
  1021. a.size = size - (url_ftell(pb) - start_pos);
  1022. if (a.size > 8) {
  1023. if (mov_read_default(c, pb, a) < 0)
  1024. return -1;
  1025. } else if (a.size > 0)
  1026. url_fskip(pb, a.size);
  1027. }
  1028. if(st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)
  1029. st->codec->sample_rate= sc->time_scale;
  1030. /* special codec parameters handling */
  1031. switch (st->codec->codec_id) {
  1032. #if CONFIG_DV_DEMUXER
  1033. case CODEC_ID_DVAUDIO:
  1034. c->dv_fctx = avformat_alloc_context();
  1035. c->dv_demux = dv_init_demux(c->dv_fctx);
  1036. if (!c->dv_demux) {
  1037. av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");
  1038. return -1;
  1039. }
  1040. sc->dv_audio_container = 1;
  1041. st->codec->codec_id = CODEC_ID_PCM_S16LE;
  1042. break;
  1043. #endif
  1044. /* no ifdef since parameters are always those */
  1045. case CODEC_ID_QCELP:
  1046. // force sample rate for qcelp when not stored in mov
  1047. if (st->codec->codec_tag != MKTAG('Q','c','l','p'))
  1048. st->codec->sample_rate = 8000;
  1049. st->codec->frame_size= 160;
  1050. st->codec->channels= 1; /* really needed */
  1051. break;
  1052. case CODEC_ID_AMR_NB:
  1053. case CODEC_ID_AMR_WB:
  1054. st->codec->frame_size= sc->samples_per_frame;
  1055. st->codec->channels= 1; /* really needed */
  1056. /* force sample rate for amr, stsd in 3gp does not store sample rate */
  1057. if (st->codec->codec_id == CODEC_ID_AMR_NB)
  1058. st->codec->sample_rate = 8000;
  1059. else if (st->codec->codec_id == CODEC_ID_AMR_WB)
  1060. st->codec->sample_rate = 16000;
  1061. break;
  1062. case CODEC_ID_MP2:
  1063. case CODEC_ID_MP3:
  1064. st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */
  1065. st->need_parsing = AVSTREAM_PARSE_FULL;
  1066. break;
  1067. case CODEC_ID_GSM:
  1068. case CODEC_ID_ADPCM_MS:
  1069. case CODEC_ID_ADPCM_IMA_WAV:
  1070. st->codec->block_align = sc->bytes_per_frame;
  1071. break;
  1072. case CODEC_ID_ALAC:
  1073. if (st->codec->extradata_size == 36) {
  1074. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  1075. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1076. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1077. }
  1078. break;
  1079. default:
  1080. break;
  1081. }
  1082. return 0;
  1083. }
  1084. static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1085. {
  1086. int entries;
  1087. get_byte(pb); /* version */
  1088. get_be24(pb); /* flags */
  1089. entries = get_be32(pb);
  1090. return ff_mov_read_stsd_entries(c, pb, entries);
  1091. }
  1092. static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1093. {
  1094. AVStream *st;
  1095. MOVStreamContext *sc;
  1096. unsigned int i, entries;
  1097. if (c->fc->nb_streams < 1)
  1098. return 0;
  1099. st = c->fc->streams[c->fc->nb_streams-1];
  1100. sc = st->priv_data;
  1101. get_byte(pb); /* version */
  1102. get_be24(pb); /* flags */
  1103. entries = get_be32(pb);
  1104. dprintf(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1105. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1106. return -1;
  1107. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1108. if (!sc->stsc_data)
  1109. return AVERROR(ENOMEM);
  1110. sc->stsc_count = entries;
  1111. for(i=0; i<entries; i++) {
  1112. sc->stsc_data[i].first = get_be32(pb);
  1113. sc->stsc_data[i].count = get_be32(pb);
  1114. sc->stsc_data[i].id = get_be32(pb);
  1115. }
  1116. return 0;
  1117. }
  1118. static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1119. {
  1120. AVStream *st;
  1121. MOVStreamContext *sc;
  1122. unsigned i, entries;
  1123. if (c->fc->nb_streams < 1)
  1124. return 0;
  1125. st = c->fc->streams[c->fc->nb_streams-1];
  1126. sc = st->priv_data;
  1127. get_be32(pb); // version + flags
  1128. entries = get_be32(pb);
  1129. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1130. return -1;
  1131. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1132. if (!sc->stps_data)
  1133. return AVERROR(ENOMEM);
  1134. sc->stps_count = entries;
  1135. for (i = 0; i < entries; i++) {
  1136. sc->stps_data[i] = get_be32(pb);
  1137. //dprintf(c->fc, "stps %d\n", sc->stps_data[i]);
  1138. }
  1139. return 0;
  1140. }
  1141. static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1142. {
  1143. AVStream *st;
  1144. MOVStreamContext *sc;
  1145. unsigned int i, entries;
  1146. if (c->fc->nb_streams < 1)
  1147. return 0;
  1148. st = c->fc->streams[c->fc->nb_streams-1];
  1149. sc = st->priv_data;
  1150. get_byte(pb); /* version */
  1151. get_be24(pb); /* flags */
  1152. entries = get_be32(pb);
  1153. dprintf(c->fc, "keyframe_count = %d\n", entries);
  1154. if(entries >= UINT_MAX / sizeof(int))
  1155. return -1;
  1156. sc->keyframes = av_malloc(entries * sizeof(int));
  1157. if (!sc->keyframes)
  1158. return AVERROR(ENOMEM);
  1159. sc->keyframe_count = entries;
  1160. for(i=0; i<entries; i++) {
  1161. sc->keyframes[i] = get_be32(pb);
  1162. //dprintf(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1163. }
  1164. return 0;
  1165. }
  1166. static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1167. {
  1168. AVStream *st;
  1169. MOVStreamContext *sc;
  1170. unsigned int i, entries, sample_size, field_size, num_bytes;
  1171. GetBitContext gb;
  1172. unsigned char* buf;
  1173. if (c->fc->nb_streams < 1)
  1174. return 0;
  1175. st = c->fc->streams[c->fc->nb_streams-1];
  1176. sc = st->priv_data;
  1177. get_byte(pb); /* version */
  1178. get_be24(pb); /* flags */
  1179. if (atom.type == MKTAG('s','t','s','z')) {
  1180. sample_size = get_be32(pb);
  1181. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1182. sc->sample_size = sample_size;
  1183. field_size = 32;
  1184. } else {
  1185. sample_size = 0;
  1186. get_be24(pb); /* reserved */
  1187. field_size = get_byte(pb);
  1188. }
  1189. entries = get_be32(pb);
  1190. dprintf(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1191. sc->sample_count = entries;
  1192. if (sample_size)
  1193. return 0;
  1194. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1195. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1196. return -1;
  1197. }
  1198. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1199. return -1;
  1200. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1201. if (!sc->sample_sizes)
  1202. return AVERROR(ENOMEM);
  1203. num_bytes = (entries*field_size+4)>>3;
  1204. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1205. if (!buf) {
  1206. av_freep(&sc->sample_sizes);
  1207. return AVERROR(ENOMEM);
  1208. }
  1209. if (get_buffer(pb, buf, num_bytes) < num_bytes) {
  1210. av_freep(&sc->sample_sizes);
  1211. av_free(buf);
  1212. return -1;
  1213. }
  1214. init_get_bits(&gb, buf, 8*num_bytes);
  1215. for(i=0; i<entries; i++)
  1216. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1217. av_free(buf);
  1218. return 0;
  1219. }
  1220. static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1221. {
  1222. AVStream *st;
  1223. MOVStreamContext *sc;
  1224. unsigned int i, entries;
  1225. int64_t duration=0;
  1226. int64_t total_sample_count=0;
  1227. if (c->fc->nb_streams < 1)
  1228. return 0;
  1229. st = c->fc->streams[c->fc->nb_streams-1];
  1230. sc = st->priv_data;
  1231. get_byte(pb); /* version */
  1232. get_be24(pb); /* flags */
  1233. entries = get_be32(pb);
  1234. dprintf(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1235. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1236. return -1;
  1237. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1238. if (!sc->stts_data)
  1239. return AVERROR(ENOMEM);
  1240. sc->stts_count = entries;
  1241. for(i=0; i<entries; i++) {
  1242. int sample_duration;
  1243. int sample_count;
  1244. sample_count=get_be32(pb);
  1245. sample_duration = get_be32(pb);
  1246. sc->stts_data[i].count= sample_count;
  1247. sc->stts_data[i].duration= sample_duration;
  1248. dprintf(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1249. duration+=(int64_t)sample_duration*sample_count;
  1250. total_sample_count+=sample_count;
  1251. }
  1252. st->nb_frames= total_sample_count;
  1253. if(duration)
  1254. st->duration= duration;
  1255. return 0;
  1256. }
  1257. static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1258. {
  1259. AVStream *st;
  1260. MOVStreamContext *sc;
  1261. unsigned int i, entries;
  1262. if (c->fc->nb_streams < 1)
  1263. return 0;
  1264. st = c->fc->streams[c->fc->nb_streams-1];
  1265. sc = st->priv_data;
  1266. get_byte(pb); /* version */
  1267. get_be24(pb); /* flags */
  1268. entries = get_be32(pb);
  1269. dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1270. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1271. return -1;
  1272. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1273. if (!sc->ctts_data)
  1274. return AVERROR(ENOMEM);
  1275. sc->ctts_count = entries;
  1276. for(i=0; i<entries; i++) {
  1277. int count =get_be32(pb);
  1278. int duration =get_be32(pb);
  1279. sc->ctts_data[i].count = count;
  1280. sc->ctts_data[i].duration= duration;
  1281. if (duration < 0)
  1282. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1283. }
  1284. dprintf(c->fc, "dts shift %d\n", sc->dts_shift);
  1285. return 0;
  1286. }
  1287. static void mov_build_index(MOVContext *mov, AVStream *st)
  1288. {
  1289. MOVStreamContext *sc = st->priv_data;
  1290. int64_t current_offset;
  1291. int64_t current_dts = 0;
  1292. unsigned int stts_index = 0;
  1293. unsigned int stsc_index = 0;
  1294. unsigned int stss_index = 0;
  1295. unsigned int stps_index = 0;
  1296. unsigned int i, j;
  1297. uint64_t stream_size = 0;
  1298. /* adjust first dts according to edit list */
  1299. if (sc->time_offset) {
  1300. int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
  1301. current_dts = -rescaled;
  1302. if (sc->ctts_data && sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1303. /* more than 16 frames delay, dts are likely wrong
  1304. this happens with files created by iMovie */
  1305. sc->wrong_dts = 1;
  1306. st->codec->has_b_frames = 1;
  1307. }
  1308. }
  1309. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1310. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1311. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1312. unsigned int current_sample = 0;
  1313. unsigned int stts_sample = 0;
  1314. unsigned int sample_size;
  1315. unsigned int distance = 0;
  1316. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1317. current_dts -= sc->dts_shift;
  1318. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
  1319. return;
  1320. st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
  1321. if (!st->index_entries)
  1322. return;
  1323. st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
  1324. for (i = 0; i < sc->chunk_count; i++) {
  1325. current_offset = sc->chunk_offsets[i];
  1326. if (stsc_index + 1 < sc->stsc_count &&
  1327. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1328. stsc_index++;
  1329. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1330. int keyframe = 0;
  1331. if (current_sample >= sc->sample_count) {
  1332. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1333. return;
  1334. }
  1335. if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
  1336. keyframe = 1;
  1337. if (stss_index + 1 < sc->keyframe_count)
  1338. stss_index++;
  1339. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1340. keyframe = 1;
  1341. if (stps_index + 1 < sc->stps_count)
  1342. stps_index++;
  1343. }
  1344. if (keyframe)
  1345. distance = 0;
  1346. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1347. if(sc->pseudo_stream_id == -1 ||
  1348. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1349. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1350. e->pos = current_offset;
  1351. e->timestamp = current_dts;
  1352. e->size = sample_size;
  1353. e->min_distance = distance;
  1354. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1355. dprintf(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1356. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1357. current_offset, current_dts, sample_size, distance, keyframe);
  1358. }
  1359. current_offset += sample_size;
  1360. stream_size += sample_size;
  1361. current_dts += sc->stts_data[stts_index].duration;
  1362. distance++;
  1363. stts_sample++;
  1364. current_sample++;
  1365. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1366. stts_sample = 0;
  1367. stts_index++;
  1368. }
  1369. }
  1370. }
  1371. if (st->duration > 0)
  1372. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1373. } else {
  1374. unsigned chunk_samples, total = 0;
  1375. // compute total chunk count
  1376. for (i = 0; i < sc->stsc_count; i++) {
  1377. unsigned count, chunk_count;
  1378. chunk_samples = sc->stsc_data[i].count;
  1379. if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1380. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1381. return;
  1382. }
  1383. if (sc->samples_per_frame >= 160) { // gsm
  1384. count = chunk_samples / sc->samples_per_frame;
  1385. } else if (sc->samples_per_frame > 1) {
  1386. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1387. count = (chunk_samples+samples-1) / samples;
  1388. } else {
  1389. count = (chunk_samples+1023) / 1024;
  1390. }
  1391. if (i < sc->stsc_count - 1)
  1392. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1393. else
  1394. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1395. total += chunk_count * count;
  1396. }
  1397. dprintf(mov->fc, "chunk count %d\n", total);
  1398. if (total >= UINT_MAX / sizeof(*st->index_entries))
  1399. return;
  1400. st->index_entries = av_malloc(total*sizeof(*st->index_entries));
  1401. if (!st->index_entries)
  1402. return;
  1403. st->index_entries_allocated_size = total*sizeof(*st->index_entries);
  1404. // populate index
  1405. for (i = 0; i < sc->chunk_count; i++) {
  1406. current_offset = sc->chunk_offsets[i];
  1407. if (stsc_index + 1 < sc->stsc_count &&
  1408. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1409. stsc_index++;
  1410. chunk_samples = sc->stsc_data[stsc_index].count;
  1411. while (chunk_samples > 0) {
  1412. AVIndexEntry *e;
  1413. unsigned size, samples;
  1414. if (sc->samples_per_frame >= 160) { // gsm
  1415. samples = sc->samples_per_frame;
  1416. size = sc->bytes_per_frame;
  1417. } else {
  1418. if (sc->samples_per_frame > 1) {
  1419. samples = FFMIN((1024 / sc->samples_per_frame)*
  1420. sc->samples_per_frame, chunk_samples);
  1421. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1422. } else {
  1423. samples = FFMIN(1024, chunk_samples);
  1424. size = samples * sc->sample_size;
  1425. }
  1426. }
  1427. if (st->nb_index_entries >= total) {
  1428. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1429. return;
  1430. }
  1431. e = &st->index_entries[st->nb_index_entries++];
  1432. e->pos = current_offset;
  1433. e->timestamp = current_dts;
  1434. e->size = size;
  1435. e->min_distance = 0;
  1436. e->flags = AVINDEX_KEYFRAME;
  1437. dprintf(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1438. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1439. size, samples);
  1440. current_offset += size;
  1441. current_dts += samples;
  1442. chunk_samples -= samples;
  1443. }
  1444. }
  1445. }
  1446. }
  1447. static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
  1448. {
  1449. /* try relative path, we do not try the absolute because it can leak information about our
  1450. system to an attacker */
  1451. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1452. char filename[1024];
  1453. char *src_path;
  1454. int i, l;
  1455. /* find a source dir */
  1456. src_path = strrchr(src, '/');
  1457. if (src_path)
  1458. src_path++;
  1459. else
  1460. src_path = src;
  1461. /* find a next level down to target */
  1462. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1463. if (ref->path[l] == '/') {
  1464. if (i == ref->nlvl_to - 1)
  1465. break;
  1466. else
  1467. i++;
  1468. }
  1469. /* compose filename if next level down to target was found */
  1470. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1471. memcpy(filename, src, src_path - src);
  1472. filename[src_path - src] = 0;
  1473. for (i = 1; i < ref->nlvl_from; i++)
  1474. av_strlcat(filename, "../", 1024);
  1475. av_strlcat(filename, ref->path + l + 1, 1024);
  1476. if (!url_fopen(pb, filename, URL_RDONLY))
  1477. return 0;
  1478. }
  1479. }
  1480. return AVERROR(ENOENT);
  1481. };
  1482. static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1483. {
  1484. AVStream *st;
  1485. MOVStreamContext *sc;
  1486. int ret;
  1487. st = av_new_stream(c->fc, c->fc->nb_streams);
  1488. if (!st) return AVERROR(ENOMEM);
  1489. sc = av_mallocz(sizeof(MOVStreamContext));
  1490. if (!sc) return AVERROR(ENOMEM);
  1491. st->priv_data = sc;
  1492. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1493. sc->ffindex = st->index;
  1494. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1495. return ret;
  1496. /* sanity checks */
  1497. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1498. (!sc->sample_size && !sc->sample_count))) {
  1499. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1500. st->index);
  1501. return 0;
  1502. }
  1503. if (!sc->time_scale) {
  1504. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1505. sc->time_scale = c->time_scale;
  1506. if (!sc->time_scale)
  1507. sc->time_scale = 1;
  1508. }
  1509. av_set_pts_info(st, 64, 1, sc->time_scale);
  1510. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1511. !st->codec->frame_size && sc->stts_count == 1) {
  1512. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1513. st->codec->sample_rate, sc->time_scale);
  1514. dprintf(c->fc, "frame size %d\n", st->codec->frame_size);
  1515. }
  1516. mov_build_index(c, st);
  1517. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1518. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1519. if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
  1520. av_log(c->fc, AV_LOG_ERROR,
  1521. "stream %d, error opening alias: path='%s', dir='%s', "
  1522. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1523. st->index, dref->path, dref->dir, dref->filename,
  1524. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1525. } else
  1526. sc->pb = c->fc->pb;
  1527. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1528. if (!st->sample_aspect_ratio.num &&
  1529. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1530. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1531. ((double)st->codec->width * sc->height), INT_MAX);
  1532. }
  1533. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1534. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1535. }
  1536. switch (st->codec->codec_id) {
  1537. #if CONFIG_H261_DECODER
  1538. case CODEC_ID_H261:
  1539. #endif
  1540. #if CONFIG_H263_DECODER
  1541. case CODEC_ID_H263:
  1542. #endif
  1543. #if CONFIG_H264_DECODER
  1544. case CODEC_ID_H264:
  1545. #endif
  1546. #if CONFIG_MPEG4_DECODER
  1547. case CODEC_ID_MPEG4:
  1548. #endif
  1549. st->codec->width = 0; /* let decoder init width/height */
  1550. st->codec->height= 0;
  1551. break;
  1552. }
  1553. /* Do not need those anymore. */
  1554. av_freep(&sc->chunk_offsets);
  1555. av_freep(&sc->stsc_data);
  1556. av_freep(&sc->sample_sizes);
  1557. av_freep(&sc->keyframes);
  1558. av_freep(&sc->stts_data);
  1559. av_freep(&sc->stps_data);
  1560. return 0;
  1561. }
  1562. static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1563. {
  1564. int ret;
  1565. c->itunes_metadata = 1;
  1566. ret = mov_read_default(c, pb, atom);
  1567. c->itunes_metadata = 0;
  1568. return ret;
  1569. }
  1570. static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1571. {
  1572. while (atom.size > 8) {
  1573. uint32_t tag = get_le32(pb);
  1574. atom.size -= 4;
  1575. if (tag == MKTAG('h','d','l','r')) {
  1576. url_fseek(pb, -8, SEEK_CUR);
  1577. atom.size += 8;
  1578. return mov_read_default(c, pb, atom);
  1579. }
  1580. }
  1581. return 0;
  1582. }
  1583. static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1584. {
  1585. int i;
  1586. int width;
  1587. int height;
  1588. int64_t disp_transform[2];
  1589. int display_matrix[3][2];
  1590. AVStream *st;
  1591. MOVStreamContext *sc;
  1592. int version;
  1593. if (c->fc->nb_streams < 1)
  1594. return 0;
  1595. st = c->fc->streams[c->fc->nb_streams-1];
  1596. sc = st->priv_data;
  1597. version = get_byte(pb);
  1598. get_be24(pb); /* flags */
  1599. /*
  1600. MOV_TRACK_ENABLED 0x0001
  1601. MOV_TRACK_IN_MOVIE 0x0002
  1602. MOV_TRACK_IN_PREVIEW 0x0004
  1603. MOV_TRACK_IN_POSTER 0x0008
  1604. */
  1605. if (version == 1) {
  1606. get_be64(pb);
  1607. get_be64(pb);
  1608. } else {
  1609. get_be32(pb); /* creation time */
  1610. get_be32(pb); /* modification time */
  1611. }
  1612. st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
  1613. get_be32(pb); /* reserved */
  1614. /* highlevel (considering edits) duration in movie timebase */
  1615. (version == 1) ? get_be64(pb) : get_be32(pb);
  1616. get_be32(pb); /* reserved */
  1617. get_be32(pb); /* reserved */
  1618. get_be16(pb); /* layer */
  1619. get_be16(pb); /* alternate group */
  1620. get_be16(pb); /* volume */
  1621. get_be16(pb); /* reserved */
  1622. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1623. // they're kept in fixed point format through all calculations
  1624. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1625. for (i = 0; i < 3; i++) {
  1626. display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
  1627. display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
  1628. get_be32(pb); // 2.30 fixed point (not used)
  1629. }
  1630. width = get_be32(pb); // 16.16 fixed point track width
  1631. height = get_be32(pb); // 16.16 fixed point track height
  1632. sc->width = width >> 16;
  1633. sc->height = height >> 16;
  1634. // transform the display width/height according to the matrix
  1635. // skip this if the display matrix is the default identity matrix
  1636. // or if it is rotating the picture, ex iPhone 3GS
  1637. // to keep the same scale, use [width height 1<<16]
  1638. if (width && height &&
  1639. ((display_matrix[0][0] != 65536 ||
  1640. display_matrix[1][1] != 65536) &&
  1641. !display_matrix[0][1] &&
  1642. !display_matrix[1][0] &&
  1643. !display_matrix[2][0] && !display_matrix[2][1])) {
  1644. for (i = 0; i < 2; i++)
  1645. disp_transform[i] =
  1646. (int64_t) width * display_matrix[0][i] +
  1647. (int64_t) height * display_matrix[1][i] +
  1648. ((int64_t) display_matrix[2][i] << 16);
  1649. //sample aspect ratio is new width/height divided by old width/height
  1650. st->sample_aspect_ratio = av_d2q(
  1651. ((double) disp_transform[0] * height) /
  1652. ((double) disp_transform[1] * width), INT_MAX);
  1653. }
  1654. return 0;
  1655. }
  1656. static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1657. {
  1658. MOVFragment *frag = &c->fragment;
  1659. MOVTrackExt *trex = NULL;
  1660. int flags, track_id, i;
  1661. get_byte(pb); /* version */
  1662. flags = get_be24(pb);
  1663. track_id = get_be32(pb);
  1664. if (!track_id)
  1665. return -1;
  1666. frag->track_id = track_id;
  1667. for (i = 0; i < c->trex_count; i++)
  1668. if (c->trex_data[i].track_id == frag->track_id) {
  1669. trex = &c->trex_data[i];
  1670. break;
  1671. }
  1672. if (!trex) {
  1673. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1674. return -1;
  1675. }
  1676. if (flags & 0x01) frag->base_data_offset = get_be64(pb);
  1677. else frag->base_data_offset = frag->moof_offset;
  1678. if (flags & 0x02) frag->stsd_id = get_be32(pb);
  1679. else frag->stsd_id = trex->stsd_id;
  1680. frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
  1681. frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
  1682. frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
  1683. dprintf(c->fc, "frag flags 0x%x\n", frag->flags);
  1684. return 0;
  1685. }
  1686. static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1687. {
  1688. c->chapter_track = get_be32(pb);
  1689. return 0;
  1690. }
  1691. static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1692. {
  1693. MOVTrackExt *trex;
  1694. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1695. return -1;
  1696. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1697. if (!trex)
  1698. return AVERROR(ENOMEM);
  1699. c->trex_data = trex;
  1700. trex = &c->trex_data[c->trex_count++];
  1701. get_byte(pb); /* version */
  1702. get_be24(pb); /* flags */
  1703. trex->track_id = get_be32(pb);
  1704. trex->stsd_id = get_be32(pb);
  1705. trex->duration = get_be32(pb);
  1706. trex->size = get_be32(pb);
  1707. trex->flags = get_be32(pb);
  1708. return 0;
  1709. }
  1710. static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1711. {
  1712. MOVFragment *frag = &c->fragment;
  1713. AVStream *st = NULL;
  1714. MOVStreamContext *sc;
  1715. uint64_t offset;
  1716. int64_t dts;
  1717. int data_offset = 0;
  1718. unsigned entries, first_sample_flags = frag->flags;
  1719. int flags, distance, i;
  1720. for (i = 0; i < c->fc->nb_streams; i++) {
  1721. if (c->fc->streams[i]->id == frag->track_id) {
  1722. st = c->fc->streams[i];
  1723. break;
  1724. }
  1725. }
  1726. if (!st) {
  1727. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1728. return -1;
  1729. }
  1730. sc = st->priv_data;
  1731. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1732. return 0;
  1733. get_byte(pb); /* version */
  1734. flags = get_be24(pb);
  1735. entries = get_be32(pb);
  1736. dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1737. if (flags & 0x001) data_offset = get_be32(pb);
  1738. if (flags & 0x004) first_sample_flags = get_be32(pb);
  1739. if (flags & 0x800) {
  1740. MOVStts *ctts_data;
  1741. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1742. return -1;
  1743. ctts_data = av_realloc(sc->ctts_data,
  1744. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1745. if (!ctts_data)
  1746. return AVERROR(ENOMEM);
  1747. sc->ctts_data = ctts_data;
  1748. }
  1749. dts = st->duration;
  1750. offset = frag->base_data_offset + data_offset;
  1751. distance = 0;
  1752. dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1753. for (i = 0; i < entries; i++) {
  1754. unsigned sample_size = frag->size;
  1755. int sample_flags = i ? frag->flags : first_sample_flags;
  1756. unsigned sample_duration = frag->duration;
  1757. int keyframe;
  1758. if (flags & 0x100) sample_duration = get_be32(pb);
  1759. if (flags & 0x200) sample_size = get_be32(pb);
  1760. if (flags & 0x400) sample_flags = get_be32(pb);
  1761. if (flags & 0x800) {
  1762. sc->ctts_data[sc->ctts_count].count = 1;
  1763. sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
  1764. sc->ctts_count++;
  1765. }
  1766. if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
  1767. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1768. distance = 0;
  1769. av_add_index_entry(st, offset, dts, sample_size, distance,
  1770. keyframe ? AVINDEX_KEYFRAME : 0);
  1771. dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1772. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1773. offset, dts, sample_size, distance, keyframe);
  1774. distance++;
  1775. dts += sample_duration;
  1776. offset += sample_size;
  1777. }
  1778. frag->moof_offset = offset;
  1779. st->duration = dts;
  1780. return 0;
  1781. }
  1782. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1783. /* like the files created with Adobe Premiere 5.0, for samples see */
  1784. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1785. static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1786. {
  1787. int err;
  1788. if (atom.size < 8)
  1789. return 0; /* continue */
  1790. if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1791. url_fskip(pb, atom.size - 4);
  1792. return 0;
  1793. }
  1794. atom.type = get_le32(pb);
  1795. atom.size -= 8;
  1796. if (atom.type != MKTAG('m','d','a','t')) {
  1797. url_fskip(pb, atom.size);
  1798. return 0;
  1799. }
  1800. err = mov_read_mdat(c, pb, atom);
  1801. return err;
  1802. }
  1803. static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1804. {
  1805. #if CONFIG_ZLIB
  1806. ByteIOContext ctx;
  1807. uint8_t *cmov_data;
  1808. uint8_t *moov_data; /* uncompressed data */
  1809. long cmov_len, moov_len;
  1810. int ret = -1;
  1811. get_be32(pb); /* dcom atom */
  1812. if (get_le32(pb) != MKTAG('d','c','o','m'))
  1813. return -1;
  1814. if (get_le32(pb) != MKTAG('z','l','i','b')) {
  1815. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1816. return -1;
  1817. }
  1818. get_be32(pb); /* cmvd atom */
  1819. if (get_le32(pb) != MKTAG('c','m','v','d'))
  1820. return -1;
  1821. moov_len = get_be32(pb); /* uncompressed size */
  1822. cmov_len = atom.size - 6 * 4;
  1823. cmov_data = av_malloc(cmov_len);
  1824. if (!cmov_data)
  1825. return AVERROR(ENOMEM);
  1826. moov_data = av_malloc(moov_len);
  1827. if (!moov_data) {
  1828. av_free(cmov_data);
  1829. return AVERROR(ENOMEM);
  1830. }
  1831. get_buffer(pb, cmov_data, cmov_len);
  1832. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1833. goto free_and_return;
  1834. if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1835. goto free_and_return;
  1836. atom.type = MKTAG('m','o','o','v');
  1837. atom.size = moov_len;
  1838. #ifdef DEBUG
  1839. // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
  1840. #endif
  1841. ret = mov_read_default(c, &ctx, atom);
  1842. free_and_return:
  1843. av_free(moov_data);
  1844. av_free(cmov_data);
  1845. return ret;
  1846. #else
  1847. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1848. return -1;
  1849. #endif
  1850. }
  1851. /* edit list atom */
  1852. static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1853. {
  1854. MOVStreamContext *sc;
  1855. int i, edit_count;
  1856. if (c->fc->nb_streams < 1)
  1857. return 0;
  1858. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1859. get_byte(pb); /* version */
  1860. get_be24(pb); /* flags */
  1861. edit_count = get_be32(pb); /* entries */
  1862. if((uint64_t)edit_count*12+8 > atom.size)
  1863. return -1;
  1864. for(i=0; i<edit_count; i++){
  1865. int time;
  1866. int duration = get_be32(pb); /* Track duration */
  1867. time = get_be32(pb); /* Media time */
  1868. get_be32(pb); /* Media rate */
  1869. if (i == 0 && time >= -1) {
  1870. sc->time_offset = time != -1 ? time : -duration;
  1871. }
  1872. }
  1873. if(edit_count > 1)
  1874. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1875. "a/v desync might occur, patch welcome\n");
  1876. dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1877. return 0;
  1878. }
  1879. static const MOVParseTableEntry mov_default_parse_table[] = {
  1880. { MKTAG('a','v','s','s'), mov_read_extradata },
  1881. { MKTAG('c','h','p','l'), mov_read_chpl },
  1882. { MKTAG('c','o','6','4'), mov_read_stco },
  1883. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1884. { MKTAG('d','i','n','f'), mov_read_default },
  1885. { MKTAG('d','r','e','f'), mov_read_dref },
  1886. { MKTAG('e','d','t','s'), mov_read_default },
  1887. { MKTAG('e','l','s','t'), mov_read_elst },
  1888. { MKTAG('e','n','d','a'), mov_read_enda },
  1889. { MKTAG('f','i','e','l'), mov_read_extradata },
  1890. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1891. { MKTAG('g','l','b','l'), mov_read_glbl },
  1892. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1893. { MKTAG('i','l','s','t'), mov_read_ilst },
  1894. { MKTAG('j','p','2','h'), mov_read_extradata },
  1895. { MKTAG('m','d','a','t'), mov_read_mdat },
  1896. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1897. { MKTAG('m','d','i','a'), mov_read_default },
  1898. { MKTAG('m','e','t','a'), mov_read_meta },
  1899. { MKTAG('m','i','n','f'), mov_read_default },
  1900. { MKTAG('m','o','o','f'), mov_read_moof },
  1901. { MKTAG('m','o','o','v'), mov_read_moov },
  1902. { MKTAG('m','v','e','x'), mov_read_default },
  1903. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1904. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1905. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1906. { MKTAG('a','v','c','C'), mov_read_glbl },
  1907. { MKTAG('p','a','s','p'), mov_read_pasp },
  1908. { MKTAG('s','t','b','l'), mov_read_default },
  1909. { MKTAG('s','t','c','o'), mov_read_stco },
  1910. { MKTAG('s','t','p','s'), mov_read_stps },
  1911. { MKTAG('s','t','r','f'), mov_read_strf },
  1912. { MKTAG('s','t','s','c'), mov_read_stsc },
  1913. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1914. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1915. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1916. { MKTAG('s','t','t','s'), mov_read_stts },
  1917. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  1918. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1919. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1920. { MKTAG('t','r','a','k'), mov_read_trak },
  1921. { MKTAG('t','r','a','f'), mov_read_default },
  1922. { MKTAG('t','r','e','f'), mov_read_default },
  1923. { MKTAG('c','h','a','p'), mov_read_chap },
  1924. { MKTAG('t','r','e','x'), mov_read_trex },
  1925. { MKTAG('t','r','u','n'), mov_read_trun },
  1926. { MKTAG('u','d','t','a'), mov_read_default },
  1927. { MKTAG('w','a','v','e'), mov_read_wave },
  1928. { MKTAG('e','s','d','s'), mov_read_esds },
  1929. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  1930. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1931. { MKTAG('c','m','o','v'), mov_read_cmov },
  1932. { 0, NULL }
  1933. };
  1934. static int mov_probe(AVProbeData *p)
  1935. {
  1936. unsigned int offset;
  1937. uint32_t tag;
  1938. int score = 0;
  1939. /* check file header */
  1940. offset = 0;
  1941. for(;;) {
  1942. /* ignore invalid offset */
  1943. if ((offset + 8) > (unsigned int)p->buf_size)
  1944. return score;
  1945. tag = AV_RL32(p->buf + offset + 4);
  1946. switch(tag) {
  1947. /* check for obvious tags */
  1948. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  1949. case MKTAG('m','o','o','v'):
  1950. case MKTAG('m','d','a','t'):
  1951. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  1952. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  1953. case MKTAG('f','t','y','p'):
  1954. return AVPROBE_SCORE_MAX;
  1955. /* those are more common words, so rate then a bit less */
  1956. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  1957. case MKTAG('w','i','d','e'):
  1958. case MKTAG('f','r','e','e'):
  1959. case MKTAG('j','u','n','k'):
  1960. case MKTAG('p','i','c','t'):
  1961. return AVPROBE_SCORE_MAX - 5;
  1962. case MKTAG(0x82,0x82,0x7f,0x7d):
  1963. case MKTAG('s','k','i','p'):
  1964. case MKTAG('u','u','i','d'):
  1965. case MKTAG('p','r','f','l'):
  1966. offset = AV_RB32(p->buf+offset) + offset;
  1967. /* if we only find those cause probedata is too small at least rate them */
  1968. score = AVPROBE_SCORE_MAX - 50;
  1969. break;
  1970. default:
  1971. /* unrecognized tag */
  1972. return score;
  1973. }
  1974. }
  1975. return score;
  1976. }
  1977. // must be done after parsing all trak because there's no order requirement
  1978. static void mov_read_chapters(AVFormatContext *s)
  1979. {
  1980. MOVContext *mov = s->priv_data;
  1981. AVStream *st = NULL;
  1982. MOVStreamContext *sc;
  1983. int64_t cur_pos;
  1984. uint8_t *title = NULL;
  1985. int i, len, i8, i16;
  1986. for (i = 0; i < s->nb_streams; i++)
  1987. if (s->streams[i]->id == mov->chapter_track) {
  1988. st = s->streams[i];
  1989. break;
  1990. }
  1991. if (!st) {
  1992. av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");
  1993. return;
  1994. }
  1995. st->discard = AVDISCARD_ALL;
  1996. sc = st->priv_data;
  1997. cur_pos = url_ftell(sc->pb);
  1998. for (i = 0; i < st->nb_index_entries; i++) {
  1999. AVIndexEntry *sample = &st->index_entries[i];
  2000. int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;
  2001. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2002. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2003. goto finish;
  2004. }
  2005. title = av_malloc(sample->size+2);
  2006. get_buffer(sc->pb, title, sample->size);
  2007. // the first two bytes are the length of the title
  2008. len = AV_RB16(title);
  2009. if (len > sample->size-2)
  2010. continue;
  2011. // The samples could theoretically be in any encoding if there's an encd
  2012. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2013. // instead by the presence of a BOM
  2014. if (AV_RB16(title+2) == 0xfeff) {
  2015. uint8_t *utf8 = av_malloc(2*len+3);
  2016. i8 = i16 = 0;
  2017. while (i16 < len) {
  2018. uint32_t ch;
  2019. uint8_t tmp;
  2020. GET_UTF16(ch, i16 < len ? AV_RB16(title + (i16+=2)) : 0, break;)
  2021. PUT_UTF8(ch, tmp, if (i8 < 2*len) utf8[2+i8++] = tmp;)
  2022. }
  2023. utf8[2+i8] = 0;
  2024. av_freep(&title);
  2025. title = utf8;
  2026. }
  2027. ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title+2);
  2028. av_freep(&title);
  2029. }
  2030. finish:
  2031. av_free(title);
  2032. url_fseek(sc->pb, cur_pos, SEEK_SET);
  2033. }
  2034. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  2035. {
  2036. MOVContext *mov = s->priv_data;
  2037. ByteIOContext *pb = s->pb;
  2038. int err;
  2039. MOVAtom atom = { AV_RL32("root") };
  2040. mov->fc = s;
  2041. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2042. if(!url_is_streamed(pb))
  2043. atom.size = url_fsize(pb);
  2044. else
  2045. atom.size = INT64_MAX;
  2046. /* check MOV header */
  2047. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2048. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2049. return err;
  2050. }
  2051. if (!mov->found_moov) {
  2052. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2053. return -1;
  2054. }
  2055. dprintf(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
  2056. if (!url_is_streamed(pb) && mov->chapter_track > 0)
  2057. mov_read_chapters(s);
  2058. return 0;
  2059. }
  2060. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2061. {
  2062. AVIndexEntry *sample = NULL;
  2063. int64_t best_dts = INT64_MAX;
  2064. int i;
  2065. for (i = 0; i < s->nb_streams; i++) {
  2066. AVStream *avst = s->streams[i];
  2067. MOVStreamContext *msc = avst->priv_data;
  2068. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2069. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2070. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2071. dprintf(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2072. if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
  2073. (!url_is_streamed(s->pb) &&
  2074. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2075. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2076. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2077. sample = current_sample;
  2078. best_dts = dts;
  2079. *st = avst;
  2080. }
  2081. }
  2082. }
  2083. return sample;
  2084. }
  2085. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2086. {
  2087. MOVContext *mov = s->priv_data;
  2088. MOVStreamContext *sc;
  2089. AVIndexEntry *sample;
  2090. AVStream *st = NULL;
  2091. int ret;
  2092. retry:
  2093. sample = mov_find_next_sample(s, &st);
  2094. if (!sample) {
  2095. mov->found_mdat = 0;
  2096. if (!url_is_streamed(s->pb) ||
  2097. mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2098. url_feof(s->pb))
  2099. return AVERROR_EOF;
  2100. dprintf(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
  2101. goto retry;
  2102. }
  2103. sc = st->priv_data;
  2104. /* must be done just before reading, to avoid infinite loop on sample */
  2105. sc->current_sample++;
  2106. if (st->discard != AVDISCARD_ALL) {
  2107. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2108. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2109. sc->ffindex, sample->pos);
  2110. return -1;
  2111. }
  2112. ret = av_get_packet(sc->pb, pkt, sample->size);
  2113. if (ret < 0)
  2114. return ret;
  2115. #if CONFIG_DV_DEMUXER
  2116. if (mov->dv_demux && sc->dv_audio_container) {
  2117. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  2118. av_free(pkt->data);
  2119. pkt->size = 0;
  2120. ret = dv_get_packet(mov->dv_demux, pkt);
  2121. if (ret < 0)
  2122. return ret;
  2123. }
  2124. #endif
  2125. }
  2126. pkt->stream_index = sc->ffindex;
  2127. pkt->dts = sample->timestamp;
  2128. if (sc->ctts_data) {
  2129. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2130. /* update ctts context */
  2131. sc->ctts_sample++;
  2132. if (sc->ctts_index < sc->ctts_count &&
  2133. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2134. sc->ctts_index++;
  2135. sc->ctts_sample = 0;
  2136. }
  2137. if (sc->wrong_dts)
  2138. pkt->dts = AV_NOPTS_VALUE;
  2139. } else {
  2140. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2141. st->index_entries[sc->current_sample].timestamp : st->duration;
  2142. pkt->duration = next_dts - pkt->dts;
  2143. pkt->pts = pkt->dts;
  2144. }
  2145. if (st->discard == AVDISCARD_ALL)
  2146. goto retry;
  2147. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2148. pkt->pos = sample->pos;
  2149. dprintf(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2150. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2151. return 0;
  2152. }
  2153. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2154. {
  2155. MOVStreamContext *sc = st->priv_data;
  2156. int sample, time_sample;
  2157. int i;
  2158. sample = av_index_search_timestamp(st, timestamp, flags);
  2159. dprintf(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2160. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2161. sample = 0;
  2162. if (sample < 0) /* not sure what to do */
  2163. return -1;
  2164. sc->current_sample = sample;
  2165. dprintf(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2166. /* adjust ctts index */
  2167. if (sc->ctts_data) {
  2168. time_sample = 0;
  2169. for (i = 0; i < sc->ctts_count; i++) {
  2170. int next = time_sample + sc->ctts_data[i].count;
  2171. if (next > sc->current_sample) {
  2172. sc->ctts_index = i;
  2173. sc->ctts_sample = sc->current_sample - time_sample;
  2174. break;
  2175. }
  2176. time_sample = next;
  2177. }
  2178. }
  2179. return sample;
  2180. }
  2181. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2182. {
  2183. AVStream *st;
  2184. int64_t seek_timestamp, timestamp;
  2185. int sample;
  2186. int i;
  2187. if (stream_index >= s->nb_streams)
  2188. return -1;
  2189. if (sample_time < 0)
  2190. sample_time = 0;
  2191. st = s->streams[stream_index];
  2192. sample = mov_seek_stream(s, st, sample_time, flags);
  2193. if (sample < 0)
  2194. return -1;
  2195. /* adjust seek timestamp to found sample timestamp */
  2196. seek_timestamp = st->index_entries[sample].timestamp;
  2197. for (i = 0; i < s->nb_streams; i++) {
  2198. st = s->streams[i];
  2199. if (stream_index == i)
  2200. continue;
  2201. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2202. mov_seek_stream(s, st, timestamp, flags);
  2203. }
  2204. return 0;
  2205. }
  2206. static int mov_read_close(AVFormatContext *s)
  2207. {
  2208. MOVContext *mov = s->priv_data;
  2209. int i, j;
  2210. for (i = 0; i < s->nb_streams; i++) {
  2211. AVStream *st = s->streams[i];
  2212. MOVStreamContext *sc = st->priv_data;
  2213. av_freep(&sc->ctts_data);
  2214. for (j = 0; j < sc->drefs_count; j++) {
  2215. av_freep(&sc->drefs[j].path);
  2216. av_freep(&sc->drefs[j].dir);
  2217. }
  2218. av_freep(&sc->drefs);
  2219. if (sc->pb && sc->pb != s->pb)
  2220. url_fclose(sc->pb);
  2221. av_freep(&st->codec->palctrl);
  2222. }
  2223. if (mov->dv_demux) {
  2224. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2225. av_freep(&mov->dv_fctx->streams[i]->codec);
  2226. av_freep(&mov->dv_fctx->streams[i]);
  2227. }
  2228. av_freep(&mov->dv_fctx);
  2229. av_freep(&mov->dv_demux);
  2230. }
  2231. av_freep(&mov->trex_data);
  2232. return 0;
  2233. }
  2234. AVInputFormat mov_demuxer = {
  2235. "mov,mp4,m4a,3gp,3g2,mj2",
  2236. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  2237. sizeof(MOVContext),
  2238. mov_probe,
  2239. mov_read_header,
  2240. mov_read_packet,
  2241. mov_read_close,
  2242. mov_read_seek,
  2243. };