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.

2625 lines
88KB

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