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.

2577 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. av_dlog(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. av_dlog(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. av_dlog(c->fc, "ctype= %.4s (0x%08x)\n", (char*)&ctype, ctype);
  383. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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. av_dlog(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->frame_size = sc->samples_per_frame;
  1074. st->codec->block_align = sc->bytes_per_frame;
  1075. break;
  1076. case CODEC_ID_ALAC:
  1077. if (st->codec->extradata_size == 36) {
  1078. st->codec->frame_size = AV_RB32(st->codec->extradata+12);
  1079. st->codec->channels = AV_RB8 (st->codec->extradata+21);
  1080. st->codec->sample_rate = AV_RB32(st->codec->extradata+32);
  1081. }
  1082. break;
  1083. default:
  1084. break;
  1085. }
  1086. return 0;
  1087. }
  1088. static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1089. {
  1090. int entries;
  1091. get_byte(pb); /* version */
  1092. get_be24(pb); /* flags */
  1093. entries = get_be32(pb);
  1094. return ff_mov_read_stsd_entries(c, pb, entries);
  1095. }
  1096. static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1097. {
  1098. AVStream *st;
  1099. MOVStreamContext *sc;
  1100. unsigned int i, entries;
  1101. if (c->fc->nb_streams < 1)
  1102. return 0;
  1103. st = c->fc->streams[c->fc->nb_streams-1];
  1104. sc = st->priv_data;
  1105. get_byte(pb); /* version */
  1106. get_be24(pb); /* flags */
  1107. entries = get_be32(pb);
  1108. av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1109. if(entries >= UINT_MAX / sizeof(*sc->stsc_data))
  1110. return -1;
  1111. sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
  1112. if (!sc->stsc_data)
  1113. return AVERROR(ENOMEM);
  1114. sc->stsc_count = entries;
  1115. for(i=0; i<entries; i++) {
  1116. sc->stsc_data[i].first = get_be32(pb);
  1117. sc->stsc_data[i].count = get_be32(pb);
  1118. sc->stsc_data[i].id = get_be32(pb);
  1119. }
  1120. return 0;
  1121. }
  1122. static int mov_read_stps(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1123. {
  1124. AVStream *st;
  1125. MOVStreamContext *sc;
  1126. unsigned i, entries;
  1127. if (c->fc->nb_streams < 1)
  1128. return 0;
  1129. st = c->fc->streams[c->fc->nb_streams-1];
  1130. sc = st->priv_data;
  1131. get_be32(pb); // version + flags
  1132. entries = get_be32(pb);
  1133. if (entries >= UINT_MAX / sizeof(*sc->stps_data))
  1134. return -1;
  1135. sc->stps_data = av_malloc(entries * sizeof(*sc->stps_data));
  1136. if (!sc->stps_data)
  1137. return AVERROR(ENOMEM);
  1138. sc->stps_count = entries;
  1139. for (i = 0; i < entries; i++) {
  1140. sc->stps_data[i] = get_be32(pb);
  1141. //av_dlog(c->fc, "stps %d\n", sc->stps_data[i]);
  1142. }
  1143. return 0;
  1144. }
  1145. static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1146. {
  1147. AVStream *st;
  1148. MOVStreamContext *sc;
  1149. unsigned int i, entries;
  1150. if (c->fc->nb_streams < 1)
  1151. return 0;
  1152. st = c->fc->streams[c->fc->nb_streams-1];
  1153. sc = st->priv_data;
  1154. get_byte(pb); /* version */
  1155. get_be24(pb); /* flags */
  1156. entries = get_be32(pb);
  1157. av_dlog(c->fc, "keyframe_count = %d\n", entries);
  1158. if(entries >= UINT_MAX / sizeof(int))
  1159. return -1;
  1160. sc->keyframes = av_malloc(entries * sizeof(int));
  1161. if (!sc->keyframes)
  1162. return AVERROR(ENOMEM);
  1163. sc->keyframe_count = entries;
  1164. for(i=0; i<entries; i++) {
  1165. sc->keyframes[i] = get_be32(pb);
  1166. //av_dlog(c->fc, "keyframes[]=%d\n", sc->keyframes[i]);
  1167. }
  1168. return 0;
  1169. }
  1170. static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1171. {
  1172. AVStream *st;
  1173. MOVStreamContext *sc;
  1174. unsigned int i, entries, sample_size, field_size, num_bytes;
  1175. GetBitContext gb;
  1176. unsigned char* buf;
  1177. if (c->fc->nb_streams < 1)
  1178. return 0;
  1179. st = c->fc->streams[c->fc->nb_streams-1];
  1180. sc = st->priv_data;
  1181. get_byte(pb); /* version */
  1182. get_be24(pb); /* flags */
  1183. if (atom.type == MKTAG('s','t','s','z')) {
  1184. sample_size = get_be32(pb);
  1185. if (!sc->sample_size) /* do not overwrite value computed in stsd */
  1186. sc->sample_size = sample_size;
  1187. field_size = 32;
  1188. } else {
  1189. sample_size = 0;
  1190. get_be24(pb); /* reserved */
  1191. field_size = get_byte(pb);
  1192. }
  1193. entries = get_be32(pb);
  1194. av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);
  1195. sc->sample_count = entries;
  1196. if (sample_size)
  1197. return 0;
  1198. if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {
  1199. av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);
  1200. return -1;
  1201. }
  1202. if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)
  1203. return -1;
  1204. sc->sample_sizes = av_malloc(entries * sizeof(int));
  1205. if (!sc->sample_sizes)
  1206. return AVERROR(ENOMEM);
  1207. num_bytes = (entries*field_size+4)>>3;
  1208. buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);
  1209. if (!buf) {
  1210. av_freep(&sc->sample_sizes);
  1211. return AVERROR(ENOMEM);
  1212. }
  1213. if (get_buffer(pb, buf, num_bytes) < num_bytes) {
  1214. av_freep(&sc->sample_sizes);
  1215. av_free(buf);
  1216. return -1;
  1217. }
  1218. init_get_bits(&gb, buf, 8*num_bytes);
  1219. for(i=0; i<entries; i++)
  1220. sc->sample_sizes[i] = get_bits_long(&gb, field_size);
  1221. av_free(buf);
  1222. return 0;
  1223. }
  1224. static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1225. {
  1226. AVStream *st;
  1227. MOVStreamContext *sc;
  1228. unsigned int i, entries;
  1229. int64_t duration=0;
  1230. int64_t total_sample_count=0;
  1231. if (c->fc->nb_streams < 1)
  1232. return 0;
  1233. st = c->fc->streams[c->fc->nb_streams-1];
  1234. sc = st->priv_data;
  1235. get_byte(pb); /* version */
  1236. get_be24(pb); /* flags */
  1237. entries = get_be32(pb);
  1238. av_dlog(c->fc, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1239. if(entries >= UINT_MAX / sizeof(*sc->stts_data))
  1240. return -1;
  1241. sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));
  1242. if (!sc->stts_data)
  1243. return AVERROR(ENOMEM);
  1244. sc->stts_count = entries;
  1245. for(i=0; i<entries; i++) {
  1246. int sample_duration;
  1247. int sample_count;
  1248. sample_count=get_be32(pb);
  1249. sample_duration = get_be32(pb);
  1250. sc->stts_data[i].count= sample_count;
  1251. sc->stts_data[i].duration= sample_duration;
  1252. av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1253. duration+=(int64_t)sample_duration*sample_count;
  1254. total_sample_count+=sample_count;
  1255. }
  1256. st->nb_frames= total_sample_count;
  1257. if(duration)
  1258. st->duration= duration;
  1259. return 0;
  1260. }
  1261. static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1262. {
  1263. AVStream *st;
  1264. MOVStreamContext *sc;
  1265. unsigned int i, entries;
  1266. if (c->fc->nb_streams < 1)
  1267. return 0;
  1268. st = c->fc->streams[c->fc->nb_streams-1];
  1269. sc = st->priv_data;
  1270. get_byte(pb); /* version */
  1271. get_be24(pb); /* flags */
  1272. entries = get_be32(pb);
  1273. av_dlog(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);
  1274. if(entries >= UINT_MAX / sizeof(*sc->ctts_data))
  1275. return -1;
  1276. sc->ctts_data = av_malloc(entries * sizeof(*sc->ctts_data));
  1277. if (!sc->ctts_data)
  1278. return AVERROR(ENOMEM);
  1279. sc->ctts_count = entries;
  1280. for(i=0; i<entries; i++) {
  1281. int count =get_be32(pb);
  1282. int duration =get_be32(pb);
  1283. sc->ctts_data[i].count = count;
  1284. sc->ctts_data[i].duration= duration;
  1285. if (duration < 0)
  1286. sc->dts_shift = FFMAX(sc->dts_shift, -duration);
  1287. }
  1288. av_dlog(c->fc, "dts shift %d\n", sc->dts_shift);
  1289. return 0;
  1290. }
  1291. static void mov_build_index(MOVContext *mov, AVStream *st)
  1292. {
  1293. MOVStreamContext *sc = st->priv_data;
  1294. int64_t current_offset;
  1295. int64_t current_dts = 0;
  1296. unsigned int stts_index = 0;
  1297. unsigned int stsc_index = 0;
  1298. unsigned int stss_index = 0;
  1299. unsigned int stps_index = 0;
  1300. unsigned int i, j;
  1301. uint64_t stream_size = 0;
  1302. /* adjust first dts according to edit list */
  1303. if (sc->time_offset && mov->time_scale > 0) {
  1304. int rescaled = sc->time_offset < 0 ? av_rescale(sc->time_offset, sc->time_scale, mov->time_scale) : sc->time_offset;
  1305. current_dts = -rescaled;
  1306. if (sc->ctts_data && sc->stts_data &&
  1307. sc->ctts_data[0].duration / sc->stts_data[0].duration > 16) {
  1308. /* more than 16 frames delay, dts are likely wrong
  1309. this happens with files created by iMovie */
  1310. sc->wrong_dts = 1;
  1311. st->codec->has_b_frames = 1;
  1312. }
  1313. }
  1314. /* only use old uncompressed audio chunk demuxing when stts specifies it */
  1315. if (!(st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1316. sc->stts_count == 1 && sc->stts_data[0].duration == 1)) {
  1317. unsigned int current_sample = 0;
  1318. unsigned int stts_sample = 0;
  1319. unsigned int sample_size;
  1320. unsigned int distance = 0;
  1321. int key_off = sc->keyframes && sc->keyframes[0] == 1;
  1322. current_dts -= sc->dts_shift;
  1323. if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries))
  1324. return;
  1325. st->index_entries = av_malloc(sc->sample_count*sizeof(*st->index_entries));
  1326. if (!st->index_entries)
  1327. return;
  1328. st->index_entries_allocated_size = sc->sample_count*sizeof(*st->index_entries);
  1329. for (i = 0; i < sc->chunk_count; i++) {
  1330. current_offset = sc->chunk_offsets[i];
  1331. if (stsc_index + 1 < sc->stsc_count &&
  1332. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1333. stsc_index++;
  1334. for (j = 0; j < sc->stsc_data[stsc_index].count; j++) {
  1335. int keyframe = 0;
  1336. if (current_sample >= sc->sample_count) {
  1337. av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n");
  1338. return;
  1339. }
  1340. if (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index]) {
  1341. keyframe = 1;
  1342. if (stss_index + 1 < sc->keyframe_count)
  1343. stss_index++;
  1344. } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) {
  1345. keyframe = 1;
  1346. if (stps_index + 1 < sc->stps_count)
  1347. stps_index++;
  1348. }
  1349. if (keyframe)
  1350. distance = 0;
  1351. sample_size = sc->sample_size > 0 ? sc->sample_size : sc->sample_sizes[current_sample];
  1352. if(sc->pseudo_stream_id == -1 ||
  1353. sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) {
  1354. AVIndexEntry *e = &st->index_entries[st->nb_index_entries++];
  1355. e->pos = current_offset;
  1356. e->timestamp = current_dts;
  1357. e->size = sample_size;
  1358. e->min_distance = distance;
  1359. e->flags = keyframe ? AVINDEX_KEYFRAME : 0;
  1360. av_dlog(mov->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1361. "size %d, distance %d, keyframe %d\n", st->index, current_sample,
  1362. current_offset, current_dts, sample_size, distance, keyframe);
  1363. }
  1364. current_offset += sample_size;
  1365. stream_size += sample_size;
  1366. current_dts += sc->stts_data[stts_index].duration;
  1367. distance++;
  1368. stts_sample++;
  1369. current_sample++;
  1370. if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) {
  1371. stts_sample = 0;
  1372. stts_index++;
  1373. }
  1374. }
  1375. }
  1376. if (st->duration > 0)
  1377. st->codec->bit_rate = stream_size*8*sc->time_scale/st->duration;
  1378. } else {
  1379. unsigned chunk_samples, total = 0;
  1380. // compute total chunk count
  1381. for (i = 0; i < sc->stsc_count; i++) {
  1382. unsigned count, chunk_count;
  1383. chunk_samples = sc->stsc_data[i].count;
  1384. if (sc->samples_per_frame && chunk_samples % sc->samples_per_frame) {
  1385. av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n");
  1386. return;
  1387. }
  1388. if (sc->samples_per_frame >= 160) { // gsm
  1389. count = chunk_samples / sc->samples_per_frame;
  1390. } else if (sc->samples_per_frame > 1) {
  1391. unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame;
  1392. count = (chunk_samples+samples-1) / samples;
  1393. } else {
  1394. count = (chunk_samples+1023) / 1024;
  1395. }
  1396. if (i < sc->stsc_count - 1)
  1397. chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first;
  1398. else
  1399. chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1);
  1400. total += chunk_count * count;
  1401. }
  1402. av_dlog(mov->fc, "chunk count %d\n", total);
  1403. if (total >= UINT_MAX / sizeof(*st->index_entries))
  1404. return;
  1405. st->index_entries = av_malloc(total*sizeof(*st->index_entries));
  1406. if (!st->index_entries)
  1407. return;
  1408. st->index_entries_allocated_size = total*sizeof(*st->index_entries);
  1409. // populate index
  1410. for (i = 0; i < sc->chunk_count; i++) {
  1411. current_offset = sc->chunk_offsets[i];
  1412. if (stsc_index + 1 < sc->stsc_count &&
  1413. i + 1 == sc->stsc_data[stsc_index + 1].first)
  1414. stsc_index++;
  1415. chunk_samples = sc->stsc_data[stsc_index].count;
  1416. while (chunk_samples > 0) {
  1417. AVIndexEntry *e;
  1418. unsigned size, samples;
  1419. if (sc->samples_per_frame >= 160) { // gsm
  1420. samples = sc->samples_per_frame;
  1421. size = sc->bytes_per_frame;
  1422. } else {
  1423. if (sc->samples_per_frame > 1) {
  1424. samples = FFMIN((1024 / sc->samples_per_frame)*
  1425. sc->samples_per_frame, chunk_samples);
  1426. size = (samples / sc->samples_per_frame) * sc->bytes_per_frame;
  1427. } else {
  1428. samples = FFMIN(1024, chunk_samples);
  1429. size = samples * sc->sample_size;
  1430. }
  1431. }
  1432. if (st->nb_index_entries >= total) {
  1433. av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %d\n", total);
  1434. return;
  1435. }
  1436. e = &st->index_entries[st->nb_index_entries++];
  1437. e->pos = current_offset;
  1438. e->timestamp = current_dts;
  1439. e->size = size;
  1440. e->min_distance = 0;
  1441. e->flags = AVINDEX_KEYFRAME;
  1442. av_dlog(mov->fc, "AVIndex stream %d, chunk %d, offset %"PRIx64", dts %"PRId64", "
  1443. "size %d, duration %d\n", st->index, i, current_offset, current_dts,
  1444. size, samples);
  1445. current_offset += size;
  1446. current_dts += samples;
  1447. chunk_samples -= samples;
  1448. }
  1449. }
  1450. }
  1451. }
  1452. static int mov_open_dref(ByteIOContext **pb, char *src, MOVDref *ref)
  1453. {
  1454. /* try relative path, we do not try the absolute because it can leak information about our
  1455. system to an attacker */
  1456. if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
  1457. char filename[1024];
  1458. char *src_path;
  1459. int i, l;
  1460. /* find a source dir */
  1461. src_path = strrchr(src, '/');
  1462. if (src_path)
  1463. src_path++;
  1464. else
  1465. src_path = src;
  1466. /* find a next level down to target */
  1467. for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
  1468. if (ref->path[l] == '/') {
  1469. if (i == ref->nlvl_to - 1)
  1470. break;
  1471. else
  1472. i++;
  1473. }
  1474. /* compose filename if next level down to target was found */
  1475. if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
  1476. memcpy(filename, src, src_path - src);
  1477. filename[src_path - src] = 0;
  1478. for (i = 1; i < ref->nlvl_from; i++)
  1479. av_strlcat(filename, "../", 1024);
  1480. av_strlcat(filename, ref->path + l + 1, 1024);
  1481. if (!url_fopen(pb, filename, URL_RDONLY))
  1482. return 0;
  1483. }
  1484. }
  1485. return AVERROR(ENOENT);
  1486. };
  1487. static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1488. {
  1489. AVStream *st;
  1490. MOVStreamContext *sc;
  1491. int ret;
  1492. st = av_new_stream(c->fc, c->fc->nb_streams);
  1493. if (!st) return AVERROR(ENOMEM);
  1494. sc = av_mallocz(sizeof(MOVStreamContext));
  1495. if (!sc) return AVERROR(ENOMEM);
  1496. st->priv_data = sc;
  1497. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  1498. sc->ffindex = st->index;
  1499. if ((ret = mov_read_default(c, pb, atom)) < 0)
  1500. return ret;
  1501. /* sanity checks */
  1502. if (sc->chunk_count && (!sc->stts_count || !sc->stsc_count ||
  1503. (!sc->sample_size && !sc->sample_count))) {
  1504. av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",
  1505. st->index);
  1506. return 0;
  1507. }
  1508. if (sc->time_scale <= 0) {
  1509. av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", st->index);
  1510. sc->time_scale = c->time_scale;
  1511. if (sc->time_scale <= 0)
  1512. sc->time_scale = 1;
  1513. }
  1514. av_set_pts_info(st, 64, 1, sc->time_scale);
  1515. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  1516. !st->codec->frame_size && sc->stts_count == 1) {
  1517. st->codec->frame_size = av_rescale(sc->stts_data[0].duration,
  1518. st->codec->sample_rate, sc->time_scale);
  1519. av_dlog(c->fc, "frame size %d\n", st->codec->frame_size);
  1520. }
  1521. mov_build_index(c, st);
  1522. if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {
  1523. MOVDref *dref = &sc->drefs[sc->dref_id - 1];
  1524. if (mov_open_dref(&sc->pb, c->fc->filename, dref) < 0)
  1525. av_log(c->fc, AV_LOG_ERROR,
  1526. "stream %d, error opening alias: path='%s', dir='%s', "
  1527. "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n",
  1528. st->index, dref->path, dref->dir, dref->filename,
  1529. dref->volume, dref->nlvl_from, dref->nlvl_to);
  1530. } else
  1531. sc->pb = c->fc->pb;
  1532. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1533. if (!st->sample_aspect_ratio.num &&
  1534. (st->codec->width != sc->width || st->codec->height != sc->height)) {
  1535. st->sample_aspect_ratio = av_d2q(((double)st->codec->height * sc->width) /
  1536. ((double)st->codec->width * sc->height), INT_MAX);
  1537. }
  1538. av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,
  1539. sc->time_scale*st->nb_frames, st->duration, INT_MAX);
  1540. if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1))
  1541. av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den,
  1542. sc->time_scale, sc->stts_data[0].duration, INT_MAX);
  1543. }
  1544. switch (st->codec->codec_id) {
  1545. #if CONFIG_H261_DECODER
  1546. case CODEC_ID_H261:
  1547. #endif
  1548. #if CONFIG_H263_DECODER
  1549. case CODEC_ID_H263:
  1550. #endif
  1551. #if CONFIG_H264_DECODER
  1552. case CODEC_ID_H264:
  1553. #endif
  1554. #if CONFIG_MPEG4_DECODER
  1555. case CODEC_ID_MPEG4:
  1556. #endif
  1557. st->codec->width = 0; /* let decoder init width/height */
  1558. st->codec->height= 0;
  1559. break;
  1560. }
  1561. /* Do not need those anymore. */
  1562. av_freep(&sc->chunk_offsets);
  1563. av_freep(&sc->stsc_data);
  1564. av_freep(&sc->sample_sizes);
  1565. av_freep(&sc->keyframes);
  1566. av_freep(&sc->stts_data);
  1567. av_freep(&sc->stps_data);
  1568. return 0;
  1569. }
  1570. static int mov_read_ilst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1571. {
  1572. int ret;
  1573. c->itunes_metadata = 1;
  1574. ret = mov_read_default(c, pb, atom);
  1575. c->itunes_metadata = 0;
  1576. return ret;
  1577. }
  1578. static int mov_read_meta(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1579. {
  1580. while (atom.size > 8) {
  1581. uint32_t tag = get_le32(pb);
  1582. atom.size -= 4;
  1583. if (tag == MKTAG('h','d','l','r')) {
  1584. url_fseek(pb, -8, SEEK_CUR);
  1585. atom.size += 8;
  1586. return mov_read_default(c, pb, atom);
  1587. }
  1588. }
  1589. return 0;
  1590. }
  1591. static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1592. {
  1593. int i;
  1594. int width;
  1595. int height;
  1596. int64_t disp_transform[2];
  1597. int display_matrix[3][2];
  1598. AVStream *st;
  1599. MOVStreamContext *sc;
  1600. int version;
  1601. if (c->fc->nb_streams < 1)
  1602. return 0;
  1603. st = c->fc->streams[c->fc->nb_streams-1];
  1604. sc = st->priv_data;
  1605. version = get_byte(pb);
  1606. get_be24(pb); /* flags */
  1607. /*
  1608. MOV_TRACK_ENABLED 0x0001
  1609. MOV_TRACK_IN_MOVIE 0x0002
  1610. MOV_TRACK_IN_PREVIEW 0x0004
  1611. MOV_TRACK_IN_POSTER 0x0008
  1612. */
  1613. if (version == 1) {
  1614. get_be64(pb);
  1615. get_be64(pb);
  1616. } else {
  1617. get_be32(pb); /* creation time */
  1618. get_be32(pb); /* modification time */
  1619. }
  1620. st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
  1621. get_be32(pb); /* reserved */
  1622. /* highlevel (considering edits) duration in movie timebase */
  1623. (version == 1) ? get_be64(pb) : get_be32(pb);
  1624. get_be32(pb); /* reserved */
  1625. get_be32(pb); /* reserved */
  1626. get_be16(pb); /* layer */
  1627. get_be16(pb); /* alternate group */
  1628. get_be16(pb); /* volume */
  1629. get_be16(pb); /* reserved */
  1630. //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)
  1631. // they're kept in fixed point format through all calculations
  1632. // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio
  1633. for (i = 0; i < 3; i++) {
  1634. display_matrix[i][0] = get_be32(pb); // 16.16 fixed point
  1635. display_matrix[i][1] = get_be32(pb); // 16.16 fixed point
  1636. get_be32(pb); // 2.30 fixed point (not used)
  1637. }
  1638. width = get_be32(pb); // 16.16 fixed point track width
  1639. height = get_be32(pb); // 16.16 fixed point track height
  1640. sc->width = width >> 16;
  1641. sc->height = height >> 16;
  1642. // transform the display width/height according to the matrix
  1643. // skip this if the display matrix is the default identity matrix
  1644. // or if it is rotating the picture, ex iPhone 3GS
  1645. // to keep the same scale, use [width height 1<<16]
  1646. if (width && height &&
  1647. ((display_matrix[0][0] != 65536 ||
  1648. display_matrix[1][1] != 65536) &&
  1649. !display_matrix[0][1] &&
  1650. !display_matrix[1][0] &&
  1651. !display_matrix[2][0] && !display_matrix[2][1])) {
  1652. for (i = 0; i < 2; i++)
  1653. disp_transform[i] =
  1654. (int64_t) width * display_matrix[0][i] +
  1655. (int64_t) height * display_matrix[1][i] +
  1656. ((int64_t) display_matrix[2][i] << 16);
  1657. //sample aspect ratio is new width/height divided by old width/height
  1658. st->sample_aspect_ratio = av_d2q(
  1659. ((double) disp_transform[0] * height) /
  1660. ((double) disp_transform[1] * width), INT_MAX);
  1661. }
  1662. return 0;
  1663. }
  1664. static int mov_read_tfhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1665. {
  1666. MOVFragment *frag = &c->fragment;
  1667. MOVTrackExt *trex = NULL;
  1668. int flags, track_id, i;
  1669. get_byte(pb); /* version */
  1670. flags = get_be24(pb);
  1671. track_id = get_be32(pb);
  1672. if (!track_id)
  1673. return -1;
  1674. frag->track_id = track_id;
  1675. for (i = 0; i < c->trex_count; i++)
  1676. if (c->trex_data[i].track_id == frag->track_id) {
  1677. trex = &c->trex_data[i];
  1678. break;
  1679. }
  1680. if (!trex) {
  1681. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n");
  1682. return -1;
  1683. }
  1684. if (flags & 0x01) frag->base_data_offset = get_be64(pb);
  1685. else frag->base_data_offset = frag->moof_offset;
  1686. if (flags & 0x02) frag->stsd_id = get_be32(pb);
  1687. else frag->stsd_id = trex->stsd_id;
  1688. frag->duration = flags & 0x08 ? get_be32(pb) : trex->duration;
  1689. frag->size = flags & 0x10 ? get_be32(pb) : trex->size;
  1690. frag->flags = flags & 0x20 ? get_be32(pb) : trex->flags;
  1691. av_dlog(c->fc, "frag flags 0x%x\n", frag->flags);
  1692. return 0;
  1693. }
  1694. static int mov_read_chap(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1695. {
  1696. c->chapter_track = get_be32(pb);
  1697. return 0;
  1698. }
  1699. static int mov_read_trex(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1700. {
  1701. MOVTrackExt *trex;
  1702. if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data))
  1703. return -1;
  1704. trex = av_realloc(c->trex_data, (c->trex_count+1)*sizeof(*c->trex_data));
  1705. if (!trex)
  1706. return AVERROR(ENOMEM);
  1707. c->trex_data = trex;
  1708. trex = &c->trex_data[c->trex_count++];
  1709. get_byte(pb); /* version */
  1710. get_be24(pb); /* flags */
  1711. trex->track_id = get_be32(pb);
  1712. trex->stsd_id = get_be32(pb);
  1713. trex->duration = get_be32(pb);
  1714. trex->size = get_be32(pb);
  1715. trex->flags = get_be32(pb);
  1716. return 0;
  1717. }
  1718. static int mov_read_trun(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1719. {
  1720. MOVFragment *frag = &c->fragment;
  1721. AVStream *st = NULL;
  1722. MOVStreamContext *sc;
  1723. uint64_t offset;
  1724. int64_t dts;
  1725. int data_offset = 0;
  1726. unsigned entries, first_sample_flags = frag->flags;
  1727. int flags, distance, i;
  1728. for (i = 0; i < c->fc->nb_streams; i++) {
  1729. if (c->fc->streams[i]->id == frag->track_id) {
  1730. st = c->fc->streams[i];
  1731. break;
  1732. }
  1733. }
  1734. if (!st) {
  1735. av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %d\n", frag->track_id);
  1736. return -1;
  1737. }
  1738. sc = st->priv_data;
  1739. if (sc->pseudo_stream_id+1 != frag->stsd_id)
  1740. return 0;
  1741. get_byte(pb); /* version */
  1742. flags = get_be24(pb);
  1743. entries = get_be32(pb);
  1744. av_dlog(c->fc, "flags 0x%x entries %d\n", flags, entries);
  1745. if (flags & 0x001) data_offset = get_be32(pb);
  1746. if (flags & 0x004) first_sample_flags = get_be32(pb);
  1747. if (flags & 0x800) {
  1748. MOVStts *ctts_data;
  1749. if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))
  1750. return -1;
  1751. ctts_data = av_realloc(sc->ctts_data,
  1752. (entries+sc->ctts_count)*sizeof(*sc->ctts_data));
  1753. if (!ctts_data)
  1754. return AVERROR(ENOMEM);
  1755. sc->ctts_data = ctts_data;
  1756. }
  1757. dts = st->duration;
  1758. offset = frag->base_data_offset + data_offset;
  1759. distance = 0;
  1760. av_dlog(c->fc, "first sample flags 0x%x\n", first_sample_flags);
  1761. for (i = 0; i < entries; i++) {
  1762. unsigned sample_size = frag->size;
  1763. int sample_flags = i ? frag->flags : first_sample_flags;
  1764. unsigned sample_duration = frag->duration;
  1765. int keyframe;
  1766. if (flags & 0x100) sample_duration = get_be32(pb);
  1767. if (flags & 0x200) sample_size = get_be32(pb);
  1768. if (flags & 0x400) sample_flags = get_be32(pb);
  1769. if (flags & 0x800) {
  1770. sc->ctts_data[sc->ctts_count].count = 1;
  1771. sc->ctts_data[sc->ctts_count].duration = get_be32(pb);
  1772. sc->ctts_count++;
  1773. }
  1774. if ((keyframe = st->codec->codec_type == AVMEDIA_TYPE_AUDIO ||
  1775. (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))
  1776. distance = 0;
  1777. av_add_index_entry(st, offset, dts, sample_size, distance,
  1778. keyframe ? AVINDEX_KEYFRAME : 0);
  1779. av_dlog(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "
  1780. "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,
  1781. offset, dts, sample_size, distance, keyframe);
  1782. distance++;
  1783. dts += sample_duration;
  1784. offset += sample_size;
  1785. }
  1786. frag->moof_offset = offset;
  1787. st->duration = dts;
  1788. return 0;
  1789. }
  1790. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1791. /* like the files created with Adobe Premiere 5.0, for samples see */
  1792. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1793. static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1794. {
  1795. int err;
  1796. if (atom.size < 8)
  1797. return 0; /* continue */
  1798. if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1799. url_fskip(pb, atom.size - 4);
  1800. return 0;
  1801. }
  1802. atom.type = get_le32(pb);
  1803. atom.size -= 8;
  1804. if (atom.type != MKTAG('m','d','a','t')) {
  1805. url_fskip(pb, atom.size);
  1806. return 0;
  1807. }
  1808. err = mov_read_mdat(c, pb, atom);
  1809. return err;
  1810. }
  1811. static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1812. {
  1813. #if CONFIG_ZLIB
  1814. ByteIOContext ctx;
  1815. uint8_t *cmov_data;
  1816. uint8_t *moov_data; /* uncompressed data */
  1817. long cmov_len, moov_len;
  1818. int ret = -1;
  1819. get_be32(pb); /* dcom atom */
  1820. if (get_le32(pb) != MKTAG('d','c','o','m'))
  1821. return -1;
  1822. if (get_le32(pb) != MKTAG('z','l','i','b')) {
  1823. av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !");
  1824. return -1;
  1825. }
  1826. get_be32(pb); /* cmvd atom */
  1827. if (get_le32(pb) != MKTAG('c','m','v','d'))
  1828. return -1;
  1829. moov_len = get_be32(pb); /* uncompressed size */
  1830. cmov_len = atom.size - 6 * 4;
  1831. cmov_data = av_malloc(cmov_len);
  1832. if (!cmov_data)
  1833. return AVERROR(ENOMEM);
  1834. moov_data = av_malloc(moov_len);
  1835. if (!moov_data) {
  1836. av_free(cmov_data);
  1837. return AVERROR(ENOMEM);
  1838. }
  1839. get_buffer(pb, cmov_data, cmov_len);
  1840. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1841. goto free_and_return;
  1842. if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0)
  1843. goto free_and_return;
  1844. atom.type = MKTAG('m','o','o','v');
  1845. atom.size = moov_len;
  1846. #ifdef DEBUG
  1847. // { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
  1848. #endif
  1849. ret = mov_read_default(c, &ctx, atom);
  1850. free_and_return:
  1851. av_free(moov_data);
  1852. av_free(cmov_data);
  1853. return ret;
  1854. #else
  1855. av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n");
  1856. return -1;
  1857. #endif
  1858. }
  1859. /* edit list atom */
  1860. static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)
  1861. {
  1862. MOVStreamContext *sc;
  1863. int i, edit_count;
  1864. if (c->fc->nb_streams < 1)
  1865. return 0;
  1866. sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;
  1867. get_byte(pb); /* version */
  1868. get_be24(pb); /* flags */
  1869. edit_count = get_be32(pb); /* entries */
  1870. if((uint64_t)edit_count*12+8 > atom.size)
  1871. return -1;
  1872. for(i=0; i<edit_count; i++){
  1873. int time;
  1874. int duration = get_be32(pb); /* Track duration */
  1875. time = get_be32(pb); /* Media time */
  1876. get_be32(pb); /* Media rate */
  1877. if (i == 0 && time >= -1) {
  1878. sc->time_offset = time != -1 ? time : -duration;
  1879. }
  1880. }
  1881. if(edit_count > 1)
  1882. av_log(c->fc, AV_LOG_WARNING, "multiple edit list entries, "
  1883. "a/v desync might occur, patch welcome\n");
  1884. av_dlog(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, edit_count);
  1885. return 0;
  1886. }
  1887. static const MOVParseTableEntry mov_default_parse_table[] = {
  1888. { MKTAG('a','v','s','s'), mov_read_extradata },
  1889. { MKTAG('c','h','p','l'), mov_read_chpl },
  1890. { MKTAG('c','o','6','4'), mov_read_stco },
  1891. { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */
  1892. { MKTAG('d','i','n','f'), mov_read_default },
  1893. { MKTAG('d','r','e','f'), mov_read_dref },
  1894. { MKTAG('e','d','t','s'), mov_read_default },
  1895. { MKTAG('e','l','s','t'), mov_read_elst },
  1896. { MKTAG('e','n','d','a'), mov_read_enda },
  1897. { MKTAG('f','i','e','l'), mov_read_extradata },
  1898. { MKTAG('f','t','y','p'), mov_read_ftyp },
  1899. { MKTAG('g','l','b','l'), mov_read_glbl },
  1900. { MKTAG('h','d','l','r'), mov_read_hdlr },
  1901. { MKTAG('i','l','s','t'), mov_read_ilst },
  1902. { MKTAG('j','p','2','h'), mov_read_extradata },
  1903. { MKTAG('m','d','a','t'), mov_read_mdat },
  1904. { MKTAG('m','d','h','d'), mov_read_mdhd },
  1905. { MKTAG('m','d','i','a'), mov_read_default },
  1906. { MKTAG('m','e','t','a'), mov_read_meta },
  1907. { MKTAG('m','i','n','f'), mov_read_default },
  1908. { MKTAG('m','o','o','f'), mov_read_moof },
  1909. { MKTAG('m','o','o','v'), mov_read_moov },
  1910. { MKTAG('m','v','e','x'), mov_read_default },
  1911. { MKTAG('m','v','h','d'), mov_read_mvhd },
  1912. { MKTAG('S','M','I',' '), mov_read_smi }, /* Sorenson extension ??? */
  1913. { MKTAG('a','l','a','c'), mov_read_extradata }, /* alac specific atom */
  1914. { MKTAG('a','v','c','C'), mov_read_glbl },
  1915. { MKTAG('p','a','s','p'), mov_read_pasp },
  1916. { MKTAG('s','t','b','l'), mov_read_default },
  1917. { MKTAG('s','t','c','o'), mov_read_stco },
  1918. { MKTAG('s','t','p','s'), mov_read_stps },
  1919. { MKTAG('s','t','r','f'), mov_read_strf },
  1920. { MKTAG('s','t','s','c'), mov_read_stsc },
  1921. { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */
  1922. { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */
  1923. { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */
  1924. { MKTAG('s','t','t','s'), mov_read_stts },
  1925. { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */
  1926. { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */
  1927. { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */
  1928. { MKTAG('t','r','a','k'), mov_read_trak },
  1929. { MKTAG('t','r','a','f'), mov_read_default },
  1930. { MKTAG('t','r','e','f'), mov_read_default },
  1931. { MKTAG('c','h','a','p'), mov_read_chap },
  1932. { MKTAG('t','r','e','x'), mov_read_trex },
  1933. { MKTAG('t','r','u','n'), mov_read_trun },
  1934. { MKTAG('u','d','t','a'), mov_read_default },
  1935. { MKTAG('w','a','v','e'), mov_read_wave },
  1936. { MKTAG('e','s','d','s'), mov_read_esds },
  1937. { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */
  1938. { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */
  1939. { MKTAG('c','m','o','v'), mov_read_cmov },
  1940. { 0, NULL }
  1941. };
  1942. static int mov_probe(AVProbeData *p)
  1943. {
  1944. unsigned int offset;
  1945. uint32_t tag;
  1946. int score = 0;
  1947. /* check file header */
  1948. offset = 0;
  1949. for(;;) {
  1950. /* ignore invalid offset */
  1951. if ((offset + 8) > (unsigned int)p->buf_size)
  1952. return score;
  1953. tag = AV_RL32(p->buf + offset + 4);
  1954. switch(tag) {
  1955. /* check for obvious tags */
  1956. case MKTAG('j','P',' ',' '): /* jpeg 2000 signature */
  1957. case MKTAG('m','o','o','v'):
  1958. case MKTAG('m','d','a','t'):
  1959. case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */
  1960. case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */
  1961. case MKTAG('f','t','y','p'):
  1962. return AVPROBE_SCORE_MAX;
  1963. /* those are more common words, so rate then a bit less */
  1964. case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */
  1965. case MKTAG('w','i','d','e'):
  1966. case MKTAG('f','r','e','e'):
  1967. case MKTAG('j','u','n','k'):
  1968. case MKTAG('p','i','c','t'):
  1969. return AVPROBE_SCORE_MAX - 5;
  1970. case MKTAG(0x82,0x82,0x7f,0x7d):
  1971. case MKTAG('s','k','i','p'):
  1972. case MKTAG('u','u','i','d'):
  1973. case MKTAG('p','r','f','l'):
  1974. offset = AV_RB32(p->buf+offset) + offset;
  1975. /* if we only find those cause probedata is too small at least rate them */
  1976. score = AVPROBE_SCORE_MAX - 50;
  1977. break;
  1978. default:
  1979. /* unrecognized tag */
  1980. return score;
  1981. }
  1982. }
  1983. return score;
  1984. }
  1985. // must be done after parsing all trak because there's no order requirement
  1986. static void mov_read_chapters(AVFormatContext *s)
  1987. {
  1988. MOVContext *mov = s->priv_data;
  1989. AVStream *st = NULL;
  1990. MOVStreamContext *sc;
  1991. int64_t cur_pos;
  1992. int i;
  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. uint8_t *title;
  2009. uint16_t ch;
  2010. int len, title_len;
  2011. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2012. av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);
  2013. goto finish;
  2014. }
  2015. // the first two bytes are the length of the title
  2016. len = get_be16(sc->pb);
  2017. if (len > sample->size-2)
  2018. continue;
  2019. title_len = 2*len + 1;
  2020. if (!(title = av_mallocz(title_len)))
  2021. goto finish;
  2022. // The samples could theoretically be in any encoding if there's an encd
  2023. // atom following, but in practice are only utf-8 or utf-16, distinguished
  2024. // instead by the presence of a BOM
  2025. ch = get_be16(sc->pb);
  2026. if (ch == 0xfeff)
  2027. avio_get_str16be(sc->pb, len, title, title_len);
  2028. else if (ch == 0xfffe)
  2029. avio_get_str16le(sc->pb, len, title, title_len);
  2030. else {
  2031. AV_WB16(title, ch);
  2032. get_strz(sc->pb, title + 2, len - 1);
  2033. }
  2034. ff_new_chapter(s, i, st->time_base, sample->timestamp, end, title);
  2035. av_freep(&title);
  2036. }
  2037. finish:
  2038. url_fseek(sc->pb, cur_pos, SEEK_SET);
  2039. }
  2040. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  2041. {
  2042. MOVContext *mov = s->priv_data;
  2043. ByteIOContext *pb = s->pb;
  2044. int err;
  2045. MOVAtom atom = { AV_RL32("root") };
  2046. mov->fc = s;
  2047. /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  2048. if(!url_is_streamed(pb))
  2049. atom.size = url_fsize(pb);
  2050. else
  2051. atom.size = INT64_MAX;
  2052. /* check MOV header */
  2053. if ((err = mov_read_default(mov, pb, atom)) < 0) {
  2054. av_log(s, AV_LOG_ERROR, "error reading header: %d\n", err);
  2055. return err;
  2056. }
  2057. if (!mov->found_moov) {
  2058. av_log(s, AV_LOG_ERROR, "moov atom not found\n");
  2059. return -1;
  2060. }
  2061. av_dlog(mov->fc, "on_parse_exit_offset=%lld\n", url_ftell(pb));
  2062. if (!url_is_streamed(pb) && mov->chapter_track > 0)
  2063. mov_read_chapters(s);
  2064. return 0;
  2065. }
  2066. static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
  2067. {
  2068. AVIndexEntry *sample = NULL;
  2069. int64_t best_dts = INT64_MAX;
  2070. int i;
  2071. for (i = 0; i < s->nb_streams; i++) {
  2072. AVStream *avst = s->streams[i];
  2073. MOVStreamContext *msc = avst->priv_data;
  2074. if (msc->pb && msc->current_sample < avst->nb_index_entries) {
  2075. AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample];
  2076. int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale);
  2077. av_dlog(s, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts);
  2078. if (!sample || (url_is_streamed(s->pb) && current_sample->pos < sample->pos) ||
  2079. (!url_is_streamed(s->pb) &&
  2080. ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb &&
  2081. ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
  2082. (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
  2083. sample = current_sample;
  2084. best_dts = dts;
  2085. *st = avst;
  2086. }
  2087. }
  2088. }
  2089. return sample;
  2090. }
  2091. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  2092. {
  2093. MOVContext *mov = s->priv_data;
  2094. MOVStreamContext *sc;
  2095. AVIndexEntry *sample;
  2096. AVStream *st = NULL;
  2097. int ret;
  2098. retry:
  2099. sample = mov_find_next_sample(s, &st);
  2100. if (!sample) {
  2101. mov->found_mdat = 0;
  2102. if (!url_is_streamed(s->pb) ||
  2103. mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
  2104. url_feof(s->pb))
  2105. return AVERROR_EOF;
  2106. av_dlog(s, "read fragments, offset 0x%llx\n", url_ftell(s->pb));
  2107. goto retry;
  2108. }
  2109. sc = st->priv_data;
  2110. /* must be done just before reading, to avoid infinite loop on sample */
  2111. sc->current_sample++;
  2112. if (st->discard != AVDISCARD_ALL) {
  2113. if (url_fseek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
  2114. av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
  2115. sc->ffindex, sample->pos);
  2116. return -1;
  2117. }
  2118. ret = av_get_packet(sc->pb, pkt, sample->size);
  2119. if (ret < 0)
  2120. return ret;
  2121. #if CONFIG_DV_DEMUXER
  2122. if (mov->dv_demux && sc->dv_audio_container) {
  2123. dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size);
  2124. av_free(pkt->data);
  2125. pkt->size = 0;
  2126. ret = dv_get_packet(mov->dv_demux, pkt);
  2127. if (ret < 0)
  2128. return ret;
  2129. }
  2130. #endif
  2131. }
  2132. pkt->stream_index = sc->ffindex;
  2133. pkt->dts = sample->timestamp;
  2134. if (sc->ctts_data) {
  2135. pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
  2136. /* update ctts context */
  2137. sc->ctts_sample++;
  2138. if (sc->ctts_index < sc->ctts_count &&
  2139. sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
  2140. sc->ctts_index++;
  2141. sc->ctts_sample = 0;
  2142. }
  2143. if (sc->wrong_dts)
  2144. pkt->dts = AV_NOPTS_VALUE;
  2145. } else {
  2146. int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
  2147. st->index_entries[sc->current_sample].timestamp : st->duration;
  2148. pkt->duration = next_dts - pkt->dts;
  2149. pkt->pts = pkt->dts;
  2150. }
  2151. if (st->discard == AVDISCARD_ALL)
  2152. goto retry;
  2153. pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
  2154. pkt->pos = sample->pos;
  2155. av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
  2156. pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
  2157. return 0;
  2158. }
  2159. static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags)
  2160. {
  2161. MOVStreamContext *sc = st->priv_data;
  2162. int sample, time_sample;
  2163. int i;
  2164. sample = av_index_search_timestamp(st, timestamp, flags);
  2165. av_dlog(s, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample);
  2166. if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp)
  2167. sample = 0;
  2168. if (sample < 0) /* not sure what to do */
  2169. return -1;
  2170. sc->current_sample = sample;
  2171. av_dlog(s, "stream %d, found sample %d\n", st->index, sc->current_sample);
  2172. /* adjust ctts index */
  2173. if (sc->ctts_data) {
  2174. time_sample = 0;
  2175. for (i = 0; i < sc->ctts_count; i++) {
  2176. int next = time_sample + sc->ctts_data[i].count;
  2177. if (next > sc->current_sample) {
  2178. sc->ctts_index = i;
  2179. sc->ctts_sample = sc->current_sample - time_sample;
  2180. break;
  2181. }
  2182. time_sample = next;
  2183. }
  2184. }
  2185. return sample;
  2186. }
  2187. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags)
  2188. {
  2189. AVStream *st;
  2190. int64_t seek_timestamp, timestamp;
  2191. int sample;
  2192. int i;
  2193. if (stream_index >= s->nb_streams)
  2194. return -1;
  2195. if (sample_time < 0)
  2196. sample_time = 0;
  2197. st = s->streams[stream_index];
  2198. sample = mov_seek_stream(s, st, sample_time, flags);
  2199. if (sample < 0)
  2200. return -1;
  2201. /* adjust seek timestamp to found sample timestamp */
  2202. seek_timestamp = st->index_entries[sample].timestamp;
  2203. for (i = 0; i < s->nb_streams; i++) {
  2204. st = s->streams[i];
  2205. if (stream_index == i)
  2206. continue;
  2207. timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base);
  2208. mov_seek_stream(s, st, timestamp, flags);
  2209. }
  2210. return 0;
  2211. }
  2212. static int mov_read_close(AVFormatContext *s)
  2213. {
  2214. MOVContext *mov = s->priv_data;
  2215. int i, j;
  2216. for (i = 0; i < s->nb_streams; i++) {
  2217. AVStream *st = s->streams[i];
  2218. MOVStreamContext *sc = st->priv_data;
  2219. av_freep(&sc->ctts_data);
  2220. for (j = 0; j < sc->drefs_count; j++) {
  2221. av_freep(&sc->drefs[j].path);
  2222. av_freep(&sc->drefs[j].dir);
  2223. }
  2224. av_freep(&sc->drefs);
  2225. if (sc->pb && sc->pb != s->pb)
  2226. url_fclose(sc->pb);
  2227. av_freep(&st->codec->palctrl);
  2228. }
  2229. if (mov->dv_demux) {
  2230. for(i = 0; i < mov->dv_fctx->nb_streams; i++) {
  2231. av_freep(&mov->dv_fctx->streams[i]->codec);
  2232. av_freep(&mov->dv_fctx->streams[i]);
  2233. }
  2234. av_freep(&mov->dv_fctx);
  2235. av_freep(&mov->dv_demux);
  2236. }
  2237. av_freep(&mov->trex_data);
  2238. return 0;
  2239. }
  2240. AVInputFormat ff_mov_demuxer = {
  2241. "mov,mp4,m4a,3gp,3g2,mj2",
  2242. NULL_IF_CONFIG_SMALL("QuickTime/MPEG-4/Motion JPEG 2000 format"),
  2243. sizeof(MOVContext),
  2244. mov_probe,
  2245. mov_read_header,
  2246. mov_read_packet,
  2247. mov_read_close,
  2248. mov_read_seek,
  2249. };