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.

2580 lines
86KB

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