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.

2578 lines
86KB

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