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.

2622 lines
87KB

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