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.

2068 lines
70KB

  1. /*
  2. * MOV decoder.
  3. * Copyright (c) 2001 Fabrice Bellard.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #include <limits.h>
  20. #include "avformat.h"
  21. #include "avi.h"
  22. #ifdef CONFIG_ZLIB
  23. #include <zlib.h>
  24. #endif
  25. /*
  26. * First version by Francois Revol revol@free.fr
  27. * Seek function by Gael Chardon gael.dev@4now.net
  28. *
  29. * Features and limitations:
  30. * - reads most of the QT files I have (at least the structure),
  31. * the exceptions are .mov with zlib compressed headers ('cmov' section). It shouldn't be hard to implement.
  32. * FIXED, Francois Revol, 07/17/2002
  33. * - ffmpeg has nearly none of the usual QuickTime codecs,
  34. * although I succesfully dumped raw and mp3 audio tracks off .mov files.
  35. * Sample QuickTime files with mp3 audio can be found at: http://www.3ivx.com/showcase.html
  36. * - .mp4 parsing is still hazardous, although the format really is QuickTime with some minor changes
  37. * (to make .mov parser crash maybe ?), despite what they say in the MPEG FAQ at
  38. * http://mpeg.telecomitalialab.com/faq.htm
  39. * - the code is quite ugly... maybe I won't do it recursive next time :-)
  40. * - seek is not supported with files that contain edit list
  41. *
  42. * Funny I didn't know about http://sourceforge.net/projects/qt-ffmpeg/
  43. * when coding this :) (it's a writer anyway)
  44. *
  45. * Reference documents:
  46. * http://www.geocities.com/xhelmboyx/quicktime/formats/qtm-layout.txt
  47. * Apple:
  48. * http://developer.apple.com/documentation/QuickTime/QTFF/
  49. * http://developer.apple.com/documentation/QuickTime/QTFF/qtff.pdf
  50. * QuickTime is a trademark of Apple (AFAIK :))
  51. */
  52. //#define DEBUG
  53. #ifdef DEBUG
  54. #include <stdio.h>
  55. #include <fcntl.h>
  56. #endif
  57. #include "qtpalette.h"
  58. /* Allows seeking (MOV_SPLIT_CHUNKS should also be defined) */
  59. #define MOV_SEEK
  60. /* allows chunk splitting - should work now... */
  61. /* in case you can't read a file, try commenting */
  62. #define MOV_SPLIT_CHUNKS
  63. /* Special handling for movies created with Minolta Dimaxe Xi*/
  64. /* this fix should not interfere with other .mov files, but just in case*/
  65. #define MOV_MINOLTA_FIX
  66. /* some streams in QT (and in MP4 mostly) aren't either video nor audio */
  67. /* so we first list them as this, then clean up the list of streams we give back, */
  68. /* getting rid of these */
  69. #define CODEC_TYPE_MOV_OTHER (enum CodecType) 2
  70. static const CodecTag mov_video_tags[] = {
  71. /* { CODEC_ID_, MKTAG('c', 'v', 'i', 'd') }, *//* Cinepak */
  72. /* { CODEC_ID_H263, MKTAG('r', 'a', 'w', ' ') }, *//* Uncompressed RGB */
  73. /* { CODEC_ID_H263, MKTAG('Y', 'u', 'v', '2') }, *//* Uncompressed YUV422 */
  74. /* { CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, *//* YUV with alpha-channel (AVID Uncompressed) */
  75. /* Graphics */
  76. /* Animation */
  77. /* Apple video */
  78. /* Kodak Photo CD */
  79. { CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
  80. { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
  81. { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
  82. { CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
  83. { CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
  84. /* { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
  85. /* { CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, *//* embedded gif files as frames (usually one "click to play movie" frame) */
  86. /* Sorenson video */
  87. { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
  88. { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
  89. { CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
  90. { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
  91. { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
  92. { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
  93. { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
  94. /* { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
  95. { CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
  96. { CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
  97. { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
  98. { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
  99. /* { CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, *//* AVID dv */
  100. { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
  101. { CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
  102. { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
  103. { CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
  104. { CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
  105. { CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
  106. { CODEC_ID_NONE, 0 },
  107. };
  108. static const CodecTag mov_audio_tags[] = {
  109. /* { CODEC_ID_PCM_S16BE, MKTAG('N', 'O', 'N', 'E') }, *//* uncompressed */
  110. { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') }, /* 16 bits */
  111. /* { CODEC_ID_PCM_S8, MKTAG('t', 'w', 'o', 's') },*/ /* 8 bits */
  112. { CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') }, /* 8 bits unsigned */
  113. { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') }, /* */
  114. { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') }, /* */
  115. { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') }, /* */
  116. { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') }, /* IMA-4 ADPCM */
  117. { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') }, /* Macintosh Audio Compression and Expansion 3:1 */
  118. { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') }, /* Macintosh Audio Compression and Expansion 6:1 */
  119. { CODEC_ID_MP2, MKTAG('.', 'm', 'p', '3') }, /* MPEG layer 3 */ /* sample files at http://www.3ivx.com/showcase.html use this tag */
  120. { CODEC_ID_MP2, 0x6D730055 }, /* MPEG layer 3 */
  121. { CODEC_ID_MP2, 0x5500736D }, /* MPEG layer 3 *//* XXX: check endianness */
  122. /* { CODEC_ID_OGG_VORBIS, MKTAG('O', 'g', 'g', 'S') }, *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
  123. /* MP4 tags */
  124. { CODEC_ID_MPEG4AAC, MKTAG('m', 'p', '4', 'a') }, /* MPEG-4 AAC */
  125. /* The standard for mpeg4 audio is still not normalised AFAIK anyway */
  126. { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
  127. { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
  128. { CODEC_ID_AC3, MKTAG('m', 's', 0x20, 0x00) }, /* Dolby AC-3 */
  129. { CODEC_ID_NONE, 0 },
  130. };
  131. /* the QuickTime file format is quite convoluted...
  132. * it has lots of index tables, each indexing something in another one...
  133. * Here we just use what is needed to read the chunks
  134. */
  135. typedef struct MOV_sample_to_chunk_tbl {
  136. long first;
  137. long count;
  138. long id;
  139. } MOV_sample_to_chunk_tbl;
  140. typedef struct {
  141. uint32_t type;
  142. int64_t offset;
  143. int64_t size; /* total size (excluding the size and type fields) */
  144. } MOV_atom_t;
  145. typedef struct {
  146. int seed;
  147. int flags;
  148. int size;
  149. void* clrs;
  150. } MOV_ctab_t;
  151. typedef struct {
  152. uint8_t version;
  153. uint32_t flags; // 24bit
  154. /* 0x03 ESDescrTag */
  155. uint16_t es_id;
  156. #define MP4ODescrTag 0x01
  157. #define MP4IODescrTag 0x02
  158. #define MP4ESDescrTag 0x03
  159. #define MP4DecConfigDescrTag 0x04
  160. #define MP4DecSpecificDescrTag 0x05
  161. #define MP4SLConfigDescrTag 0x06
  162. #define MP4ContentIdDescrTag 0x07
  163. #define MP4SupplContentIdDescrTag 0x08
  164. #define MP4IPIPtrDescrTag 0x09
  165. #define MP4IPMPPtrDescrTag 0x0A
  166. #define MP4IPMPDescrTag 0x0B
  167. #define MP4RegistrationDescrTag 0x0D
  168. #define MP4ESIDIncDescrTag 0x0E
  169. #define MP4ESIDRefDescrTag 0x0F
  170. #define MP4FileIODescrTag 0x10
  171. #define MP4FileODescrTag 0x11
  172. #define MP4ExtProfileLevelDescrTag 0x13
  173. #define MP4ExtDescrTagsStart 0x80
  174. #define MP4ExtDescrTagsEnd 0xFE
  175. uint8_t stream_priority;
  176. /* 0x04 DecConfigDescrTag */
  177. uint8_t object_type_id;
  178. uint8_t stream_type;
  179. /* XXX: really streamType is
  180. * only 6bit, followed by:
  181. * 1bit upStream
  182. * 1bit reserved
  183. */
  184. uint32_t buffer_size_db; // 24
  185. uint32_t max_bitrate;
  186. uint32_t avg_bitrate;
  187. /* 0x05 DecSpecificDescrTag */
  188. uint8_t decoder_cfg_len;
  189. uint8_t *decoder_cfg;
  190. /* 0x06 SLConfigDescrTag */
  191. uint8_t sl_config_len;
  192. uint8_t *sl_config;
  193. } MOV_esds_t;
  194. struct MOVParseTableEntry;
  195. typedef struct MOVStreamContext {
  196. int ffindex; /* the ffmpeg stream id */
  197. int is_ff_stream; /* Is this stream presented to ffmpeg ? i.e. is this an audio or video stream ? */
  198. long next_chunk;
  199. long chunk_count;
  200. int64_t *chunk_offsets;
  201. int32_t stts_count;
  202. uint64_t *stts_data; /* concatenated data from the time-to-sample atom (count|duration) */
  203. int32_t edit_count; /* number of 'edit' (elst atom) */
  204. long sample_to_chunk_sz;
  205. MOV_sample_to_chunk_tbl *sample_to_chunk;
  206. long sample_to_chunk_index;
  207. long sample_size;
  208. long sample_count;
  209. long *sample_sizes;
  210. long keyframe_count;
  211. long *keyframes;
  212. int time_scale;
  213. long current_sample;
  214. long left_in_chunk; /* how many samples before next chunk */
  215. /* specific MPEG4 header which is added at the beginning of the stream */
  216. int header_len;
  217. uint8_t *header_data;
  218. MOV_esds_t esds;
  219. } MOVStreamContext;
  220. typedef struct MOVContext {
  221. int mp4; /* set to 1 as soon as we are sure that the file is an .mp4 file (even some header parsing depends on this) */
  222. AVFormatContext *fc;
  223. int time_scale;
  224. int duration; /* duration of the longest track */
  225. int found_moov; /* when both 'moov' and 'mdat' sections has been found */
  226. int found_mdat; /* we suppose we have enough data to read the file */
  227. int64_t mdat_size;
  228. int64_t mdat_offset;
  229. int total_streams;
  230. /* some streams listed here aren't presented to the ffmpeg API, since they aren't either video nor audio
  231. * but we need the info to be able to skip data from those streams in the 'mdat' section
  232. */
  233. MOVStreamContext *streams[MAX_STREAMS];
  234. int64_t next_chunk_offset;
  235. MOVStreamContext *partial; /* != 0 : there is still to read in the current chunk */
  236. int ctab_size;
  237. MOV_ctab_t **ctab; /* color tables */
  238. const struct MOVParseTableEntry *parse_table; /* could be eventually used to change the table */
  239. /* NOTE: for recursion save to/ restore from local variable! */
  240. AVPaletteControl palette_control;
  241. } MOVContext;
  242. /* XXX: it's the first time I make a recursive parser I think... sorry if it's ugly :P */
  243. /* those functions parse an atom */
  244. /* return code:
  245. 1: found what I wanted, exit
  246. 0: continue to parse next atom
  247. -1: error occured, exit
  248. */
  249. typedef int (*mov_parse_function)(MOVContext *ctx, ByteIOContext *pb, MOV_atom_t atom);
  250. /* links atom IDs to parse functions */
  251. typedef struct MOVParseTableEntry {
  252. uint32_t type;
  253. mov_parse_function func;
  254. } MOVParseTableEntry;
  255. #ifdef DEBUG
  256. /*
  257. * XXX: static sux, even more in a multithreaded environment...
  258. * Avoid them. This is here just to help debugging.
  259. */
  260. static int debug_indent = 0;
  261. void print_atom(const char *str, MOV_atom_t atom)
  262. {
  263. unsigned int tag, i;
  264. tag = (unsigned int) atom.type;
  265. i=debug_indent;
  266. if(tag == 0) tag = MKTAG('N', 'U', 'L', 'L');
  267. while(i--)
  268. av_log(NULL, AV_LOG_DEBUG, "|");
  269. av_log(NULL, AV_LOG_DEBUG, "parse:");
  270. av_log(NULL, AV_LOG_DEBUG, " %s: tag=%c%c%c%c offset=0x%x size=0x%x\n",
  271. str, tag & 0xff,
  272. (tag >> 8) & 0xff,
  273. (tag >> 16) & 0xff,
  274. (tag >> 24) & 0xff,
  275. (unsigned int)atom.offset,
  276. (unsigned int)atom.size);
  277. assert((unsigned int)atom.size < 0x7fffffff);// catching errors
  278. }
  279. #else
  280. #define print_atom(a,b)
  281. #endif
  282. static int mov_read_leaf(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  283. {
  284. print_atom("leaf", atom);
  285. if (atom.size>1)
  286. url_fskip(pb, atom.size);
  287. /* url_seek(pb, atom_offset+atom.size, SEEK_SET); */
  288. return 0;
  289. }
  290. static int mov_read_default(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  291. {
  292. int64_t total_size = 0;
  293. MOV_atom_t a;
  294. int i;
  295. int err = 0;
  296. #ifdef DEBUG
  297. print_atom("default", atom);
  298. debug_indent++;
  299. #endif
  300. a.offset = atom.offset;
  301. if (atom.size < 0)
  302. atom.size = 0x7fffffffffffffffLL;
  303. while(((total_size + 8) < atom.size) && !url_feof(pb) && !err) {
  304. a.size = atom.size;
  305. a.type=0L;
  306. if(atom.size >= 8) {
  307. a.size = get_be32(pb);
  308. a.type = get_le32(pb);
  309. }
  310. total_size += 8;
  311. a.offset += 8;
  312. //av_log(NULL, AV_LOG_DEBUG, "type: %08x %.4s sz: %Lx %Lx %Lx\n", type, (char*)&type, size, atom.size, total_size);
  313. if (a.size == 1) { /* 64 bit extended size */
  314. a.size = get_be64(pb) - 8;
  315. a.offset += 8;
  316. total_size += 8;
  317. }
  318. if (a.size == 0) {
  319. a.size = atom.size - total_size;
  320. if (a.size <= 8)
  321. break;
  322. }
  323. for (i = 0; c->parse_table[i].type != 0L
  324. && c->parse_table[i].type != a.type; i++)
  325. /* empty */;
  326. a.size -= 8;
  327. // av_log(NULL, AV_LOG_DEBUG, " i=%ld\n", i);
  328. if (c->parse_table[i].type == 0) { /* skip leaf atoms data */
  329. // url_seek(pb, atom.offset+atom.size, SEEK_SET);
  330. #ifdef DEBUG
  331. print_atom("unknown", a);
  332. #endif
  333. url_fskip(pb, a.size);
  334. } else {
  335. #ifdef DEBUG
  336. //char b[5] = { type & 0xff, (type >> 8) & 0xff, (type >> 16) & 0xff, (type >> 24) & 0xff, 0 };
  337. //print_atom(b, type, offset, size);
  338. #endif
  339. err = (c->parse_table[i].func)(c, pb, a);
  340. }
  341. a.offset += a.size;
  342. total_size += a.size;
  343. }
  344. if (!err && total_size < atom.size && atom.size < 0x7ffff) {
  345. //av_log(NULL, AV_LOG_DEBUG, "RESET %Ld %Ld err:%d\n", atom.size, total_size, err);
  346. url_fskip(pb, atom.size - total_size);
  347. }
  348. #ifdef DEBUG
  349. debug_indent--;
  350. #endif
  351. return err;
  352. }
  353. static int mov_read_ctab(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  354. {
  355. unsigned int len;
  356. MOV_ctab_t *t;
  357. //url_fskip(pb, atom.size); // for now
  358. c->ctab = av_realloc(c->ctab, ++c->ctab_size);
  359. t = c->ctab[c->ctab_size];
  360. t->seed = get_be32(pb);
  361. t->flags = get_be16(pb);
  362. t->size = get_be16(pb) + 1;
  363. len = 2 * t->size * 4;
  364. if (len > 0) {
  365. t->clrs = av_malloc(len); // 16bit A R G B
  366. if (t->clrs)
  367. get_buffer(pb, t->clrs, len);
  368. }
  369. return 0;
  370. }
  371. static int mov_read_hdlr(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  372. {
  373. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  374. int len = 0;
  375. uint32_t type;
  376. uint32_t ctype;
  377. print_atom("hdlr", atom);
  378. get_byte(pb); /* version */
  379. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  380. /* component type */
  381. ctype = get_le32(pb);
  382. type = get_le32(pb); /* component subtype */
  383. #ifdef DEBUG
  384. av_log(NULL, AV_LOG_DEBUG, "ctype= %c%c%c%c (0x%08lx)\n", *((char *)&ctype), ((char *)&ctype)[1], ((char *)&ctype)[2], ((char *)&ctype)[3], (long) ctype);
  385. av_log(NULL, AV_LOG_DEBUG, "stype= %c%c%c%c\n", *((char *)&type), ((char *)&type)[1], ((char *)&type)[2], ((char *)&type)[3]);
  386. #endif
  387. #ifdef DEBUG
  388. /* XXX: yeah this is ugly... */
  389. if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
  390. if(type == MKTAG('v', 'i', 'd', 'e'))
  391. puts("hdlr: vide");
  392. else if(type == MKTAG('s', 'o', 'u', 'n'))
  393. puts("hdlr: soun");
  394. } else if(ctype == 0) { /* MP4 */
  395. if(type == MKTAG('v', 'i', 'd', 'e'))
  396. puts("hdlr: vide");
  397. else if(type == MKTAG('s', 'o', 'u', 'n'))
  398. puts("hdlr: soun");
  399. else if(type == MKTAG('o', 'd', 's', 'm'))
  400. puts("hdlr: odsm");
  401. else if(type == MKTAG('s', 'd', 's', 'm'))
  402. puts("hdlr: sdsm");
  403. } else puts("hdlr: meta");
  404. #endif
  405. if(ctype == MKTAG('m', 'h', 'l', 'r')) { /* MOV */
  406. /* helps parsing the string hereafter... */
  407. c->mp4 = 0;
  408. if(type == MKTAG('v', 'i', 'd', 'e'))
  409. st->codec.codec_type = CODEC_TYPE_VIDEO;
  410. else if(type == MKTAG('s', 'o', 'u', 'n'))
  411. st->codec.codec_type = CODEC_TYPE_AUDIO;
  412. } else if(ctype == 0) { /* MP4 */
  413. /* helps parsing the string hereafter... */
  414. c->mp4 = 1;
  415. if(type == MKTAG('v', 'i', 'd', 'e'))
  416. st->codec.codec_type = CODEC_TYPE_VIDEO;
  417. else if(type == MKTAG('s', 'o', 'u', 'n'))
  418. st->codec.codec_type = CODEC_TYPE_AUDIO;
  419. }
  420. get_be32(pb); /* component manufacture */
  421. get_be32(pb); /* component flags */
  422. get_be32(pb); /* component flags mask */
  423. if(atom.size <= 24)
  424. return 0; /* nothing left to read */
  425. /* XXX: MP4 uses a C string, not a pascal one */
  426. /* component name */
  427. if(c->mp4) {
  428. /* .mp4: C string */
  429. while(get_byte(pb) && (++len < (atom.size - 24)));
  430. } else {
  431. /* .mov: PASCAL string */
  432. #ifdef DEBUG
  433. char* buf;
  434. #endif
  435. len = get_byte(pb);
  436. #ifdef DEBUG
  437. buf = (uint8_t*) av_malloc(len+1);
  438. if (buf) {
  439. get_buffer(pb, buf, len);
  440. buf[len] = '\0';
  441. av_log(NULL, AV_LOG_DEBUG, "**buf='%s'\n", buf);
  442. av_free(buf);
  443. } else
  444. #endif
  445. url_fskip(pb, len);
  446. }
  447. url_fskip(pb, atom.size - (url_ftell(pb) - atom.offset));
  448. return 0;
  449. }
  450. static int mov_mp4_read_descr_len(ByteIOContext *pb)
  451. {
  452. int len = 0;
  453. int count = 4;
  454. while (count--) {
  455. int c = get_byte(pb);
  456. len = (len << 7) | (c & 0x7f);
  457. if (!(c & 0x80))
  458. break;
  459. }
  460. return len;
  461. }
  462. static int mov_mp4_read_descr(ByteIOContext *pb, int *tag)
  463. {
  464. int len;
  465. *tag = get_byte(pb);
  466. len = mov_mp4_read_descr_len(pb);
  467. #ifdef DEBUG
  468. av_log(NULL, AV_LOG_DEBUG, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
  469. #endif
  470. return len;
  471. }
  472. static inline unsigned int get_be24(ByteIOContext *s)
  473. {
  474. unsigned int val;
  475. val = get_byte(s) << 16;
  476. val |= get_byte(s) << 8;
  477. val |= get_byte(s);
  478. return val;
  479. }
  480. static int mov_read_esds(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  481. {
  482. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  483. MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  484. int64_t start_pos = url_ftell(pb);
  485. int tag, len;
  486. print_atom("esds", atom);
  487. /* Well, broken but suffisant for some MP4 streams */
  488. get_be32(pb); /* version + flags */
  489. len = mov_mp4_read_descr(pb, &tag);
  490. if (tag == MP4ESDescrTag) {
  491. get_be16(pb); /* ID */
  492. get_byte(pb); /* priority */
  493. } else
  494. get_be16(pb); /* ID */
  495. len = mov_mp4_read_descr(pb, &tag);
  496. if (tag == MP4DecConfigDescrTag) {
  497. sc->esds.object_type_id = get_byte(pb);
  498. sc->esds.stream_type = get_byte(pb);
  499. sc->esds.buffer_size_db = get_be24(pb);
  500. sc->esds.max_bitrate = get_be32(pb);
  501. sc->esds.avg_bitrate = get_be32(pb);
  502. len = mov_mp4_read_descr(pb, &tag);
  503. //av_log(NULL, AV_LOG_DEBUG, "LEN %d TAG %d m:%d a:%d\n", len, tag, sc->esds.max_bitrate, sc->esds.avg_bitrate);
  504. if (tag == MP4DecSpecificDescrTag) {
  505. #ifdef DEBUG
  506. av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
  507. #endif
  508. st->codec.extradata = (uint8_t*) av_mallocz(len);
  509. if (st->codec.extradata) {
  510. get_buffer(pb, st->codec.extradata, len);
  511. st->codec.extradata_size = len;
  512. }
  513. }
  514. }
  515. /* in any case, skip garbage */
  516. url_fskip(pb, atom.size - ((url_ftell(pb) - start_pos)));
  517. return 0;
  518. }
  519. /* this atom contains actual media data */
  520. static int mov_read_mdat(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  521. {
  522. print_atom("mdat", atom);
  523. if(atom.size == 0) /* wrong one (MP4) */
  524. return 0;
  525. c->found_mdat=1;
  526. c->mdat_offset = atom.offset;
  527. c->mdat_size = atom.size;
  528. if(c->found_moov)
  529. return 1; /* found both, just go */
  530. url_fskip(pb, atom.size);
  531. return 0; /* now go for moov */
  532. }
  533. /* this atom should contain all header atoms */
  534. static int mov_read_moov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  535. {
  536. int err;
  537. print_atom("moov", atom);
  538. err = mov_read_default(c, pb, atom);
  539. /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */
  540. /* so we don't parse the whole file if over a network */
  541. c->found_moov=1;
  542. if(c->found_mdat)
  543. return 1; /* found both, just go */
  544. return 0; /* now go for mdat */
  545. }
  546. static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  547. {
  548. print_atom("mdhd", atom);
  549. get_byte(pb); /* version */
  550. get_byte(pb); get_byte(pb);
  551. get_byte(pb); /* flags */
  552. get_be32(pb); /* creation time */
  553. get_be32(pb); /* modification time */
  554. c->streams[c->fc->nb_streams-1]->time_scale = get_be32(pb);
  555. #ifdef DEBUG
  556. av_log(NULL, AV_LOG_DEBUG, "track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->time_scale); /* time scale */
  557. #endif
  558. get_be32(pb); /* duration */
  559. get_be16(pb); /* language */
  560. get_be16(pb); /* quality */
  561. return 0;
  562. }
  563. static int mov_read_mvhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  564. {
  565. print_atom("mvhd", atom);
  566. get_byte(pb); /* version */
  567. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  568. get_be32(pb); /* creation time */
  569. get_be32(pb); /* modification time */
  570. c->time_scale = get_be32(pb); /* time scale */
  571. #ifdef DEBUG
  572. av_log(NULL, AV_LOG_DEBUG, "time scale = %i\n", c->time_scale);
  573. #endif
  574. c->duration = get_be32(pb); /* duration */
  575. get_be32(pb); /* preferred scale */
  576. get_be16(pb); /* preferred volume */
  577. url_fskip(pb, 10); /* reserved */
  578. url_fskip(pb, 36); /* display matrix */
  579. get_be32(pb); /* preview time */
  580. get_be32(pb); /* preview duration */
  581. get_be32(pb); /* poster time */
  582. get_be32(pb); /* selection time */
  583. get_be32(pb); /* selection duration */
  584. get_be32(pb); /* current time */
  585. get_be32(pb); /* next track ID */
  586. return 0;
  587. }
  588. static int mov_read_smi(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  589. {
  590. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  591. // currently SVQ3 decoder expect full STSD header - so let's fake it
  592. // this should be fixed and just SMI header should be passed
  593. av_free(st->codec.extradata);
  594. st->codec.extradata_size = 0x5a + atom.size;
  595. st->codec.extradata = (uint8_t*) av_mallocz(st->codec.extradata_size);
  596. if (st->codec.extradata) {
  597. strcpy(st->codec.extradata, "SVQ3"); // fake
  598. get_buffer(pb, st->codec.extradata + 0x5a, atom.size);
  599. //av_log(NULL, AV_LOG_DEBUG, "Reading SMI %Ld %s\n", atom.size, (char*)st->codec.extradata + 0x5a);
  600. } else
  601. url_fskip(pb, atom.size);
  602. return 0;
  603. }
  604. static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  605. {
  606. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  607. MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  608. int entries, i;
  609. print_atom("stco", atom);
  610. get_byte(pb); /* version */
  611. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  612. entries = get_be32(pb);
  613. sc->chunk_count = entries;
  614. sc->chunk_offsets = (int64_t*) av_malloc(entries * sizeof(int64_t));
  615. if (!sc->chunk_offsets)
  616. return -1;
  617. if (atom.type == MKTAG('s', 't', 'c', 'o')) {
  618. for(i=0; i<entries; i++) {
  619. sc->chunk_offsets[i] = get_be32(pb);
  620. }
  621. } else if (atom.type == MKTAG('c', 'o', '6', '4')) {
  622. for(i=0; i<entries; i++) {
  623. sc->chunk_offsets[i] = get_be64(pb);
  624. }
  625. } else
  626. return -1;
  627. #ifdef DEBUG
  628. /*
  629. for(i=0; i<entries; i++) {
  630. av_log(NULL, AV_LOG_DEBUG, "chunk offset=0x%Lx\n", sc->chunk_offsets[i]);
  631. }
  632. */
  633. #endif
  634. return 0;
  635. }
  636. static int mov_read_stsd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  637. {
  638. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  639. //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  640. int entries, frames_per_sample;
  641. uint32_t format;
  642. /* for palette traversal */
  643. int color_depth;
  644. int color_start;
  645. int color_count;
  646. int color_end;
  647. int color_index;
  648. int color_dec;
  649. int color_greyscale;
  650. unsigned char *color_table;
  651. int j;
  652. unsigned char r, g, b;
  653. print_atom("stsd", atom);
  654. get_byte(pb); /* version */
  655. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  656. entries = get_be32(pb);
  657. while(entries--) { //Parsing Sample description table
  658. enum CodecID id;
  659. int size = get_be32(pb); /* size */
  660. format = get_le32(pb); /* data format */
  661. get_be32(pb); /* reserved */
  662. get_be16(pb); /* reserved */
  663. get_be16(pb); /* index */
  664. /* for MPEG4: set codec type by looking for it */
  665. id = codec_get_id(mov_video_tags, format);
  666. if (id >= 0) {
  667. AVCodec *codec;
  668. codec = avcodec_find_decoder(id);
  669. if (codec)
  670. st->codec.codec_type = codec->type;
  671. }
  672. #ifdef DEBUG
  673. av_log(NULL, AV_LOG_DEBUG, "size=%d 4CC= %c%c%c%c codec_type=%d\n",
  674. size,
  675. (format >> 0) & 0xff,
  676. (format >> 8) & 0xff,
  677. (format >> 16) & 0xff,
  678. (format >> 24) & 0xff,
  679. st->codec.codec_type);
  680. #endif
  681. st->codec.codec_tag = format;
  682. if(st->codec.codec_type==CODEC_TYPE_VIDEO) {
  683. MOV_atom_t a = { 0, 0, 0 };
  684. st->codec.codec_id = id;
  685. get_be16(pb); /* version */
  686. get_be16(pb); /* revision level */
  687. get_be32(pb); /* vendor */
  688. get_be32(pb); /* temporal quality */
  689. get_be32(pb); /* spacial quality */
  690. st->codec.width = get_be16(pb); /* width */
  691. st->codec.height = get_be16(pb); /* height */
  692. #if 1
  693. if (st->codec.codec_id == CODEC_ID_MPEG4) {
  694. /* in some MPEG4 the width/height are not correct, so
  695. we ignore this info */
  696. st->codec.width = 0;
  697. st->codec.height = 0;
  698. }
  699. #endif
  700. get_be32(pb); /* horiz resolution */
  701. get_be32(pb); /* vert resolution */
  702. get_be32(pb); /* data size, always 0 */
  703. frames_per_sample = get_be16(pb); /* frames per samples */
  704. #ifdef DEBUG
  705. av_log(NULL, AV_LOG_DEBUG, "frames/samples = %d\n", frames_per_sample);
  706. #endif
  707. get_buffer(pb, (uint8_t *)st->codec.codec_name, 32); /* codec name */
  708. st->codec.bits_per_sample = get_be16(pb); /* depth */
  709. st->codec.color_table_id = get_be16(pb); /* colortable id */
  710. /* These are set in mov_read_stts and might already be set!
  711. st->codec.frame_rate = 25;
  712. st->codec.frame_rate_base = 1;
  713. */
  714. size -= (16+8*4+2+32+2*2);
  715. #if 0
  716. while (size >= 8) {
  717. MOV_atom_t a;
  718. int64_t start_pos;
  719. a.size = get_be32(pb);
  720. a.type = get_le32(pb);
  721. size -= 8;
  722. #ifdef DEBUG
  723. av_log(NULL, AV_LOG_DEBUG, "VIDEO: atom_type=%c%c%c%c atom.size=%Ld size_left=%d\n",
  724. (a.type >> 0) & 0xff,
  725. (a.type >> 8) & 0xff,
  726. (a.type >> 16) & 0xff,
  727. (a.type >> 24) & 0xff,
  728. a.size, size);
  729. #endif
  730. start_pos = url_ftell(pb);
  731. switch(a.type) {
  732. case MKTAG('e', 's', 'd', 's'):
  733. {
  734. int tag, len;
  735. /* Well, broken but suffisant for some MP4 streams */
  736. get_be32(pb); /* version + flags */
  737. len = mov_mp4_read_descr(pb, &tag);
  738. if (tag == 0x03) {
  739. /* MP4ESDescrTag */
  740. get_be16(pb); /* ID */
  741. get_byte(pb); /* priority */
  742. len = mov_mp4_read_descr(pb, &tag);
  743. if (tag != 0x04)
  744. goto fail;
  745. /* MP4DecConfigDescrTag */
  746. get_byte(pb); /* objectTypeId */
  747. get_be32(pb); /* streamType + buffer size */
  748. get_be32(pb); /* max bit rate */
  749. get_be32(pb); /* avg bit rate */
  750. len = mov_mp4_read_descr(pb, &tag);
  751. if (tag != 0x05)
  752. goto fail;
  753. /* MP4DecSpecificDescrTag */
  754. #ifdef DEBUG
  755. av_log(NULL, AV_LOG_DEBUG, "Specific MPEG4 header len=%d\n", len);
  756. #endif
  757. sc->header_data = av_mallocz(len);
  758. if (sc->header_data) {
  759. get_buffer(pb, sc->header_data, len);
  760. sc->header_len = len;
  761. }
  762. }
  763. /* in any case, skip garbage */
  764. }
  765. break;
  766. default:
  767. break;
  768. }
  769. fail:
  770. av_log(NULL, AV_LOG_DEBUG, "ATOMENEWSIZE %Ld %d\n", atom.size, url_ftell(pb) - start_pos);
  771. if (atom.size > 8) {
  772. url_fskip(pb, (atom.size - 8) -
  773. ((url_ftell(pb) - start_pos)));
  774. size -= atom.size - 8;
  775. }
  776. }
  777. if (size > 0) {
  778. /* unknown extension */
  779. url_fskip(pb, size);
  780. }
  781. #else
  782. /* figure out the palette situation */
  783. color_depth = st->codec.bits_per_sample & 0x1F;
  784. color_greyscale = st->codec.bits_per_sample & 0x20;
  785. /* if the depth is 2, 4, or 8 bpp, file is palettized */
  786. if ((color_depth == 2) || (color_depth == 4) ||
  787. (color_depth == 8)) {
  788. if (color_greyscale) {
  789. /* compute the greyscale palette */
  790. color_count = 1 << color_depth;
  791. color_index = 255;
  792. color_dec = 256 / (color_count - 1);
  793. for (j = 0; j < color_count; j++) {
  794. r = g = b = color_index;
  795. c->palette_control.palette[j] =
  796. (r << 16) | (g << 8) | (b);
  797. color_index -= color_dec;
  798. if (color_index < 0)
  799. color_index = 0;
  800. }
  801. } else if (st->codec.color_table_id & 0x08) {
  802. /* if flag bit 3 is set, use the default palette */
  803. color_count = 1 << color_depth;
  804. if (color_depth == 2)
  805. color_table = ff_qt_default_palette_4;
  806. else if (color_depth == 4)
  807. color_table = ff_qt_default_palette_16;
  808. else
  809. color_table = ff_qt_default_palette_256;
  810. for (j = 0; j < color_count; j++) {
  811. r = color_table[j * 4 + 0];
  812. g = color_table[j * 4 + 1];
  813. b = color_table[j * 4 + 2];
  814. c->palette_control.palette[j] =
  815. (r << 16) | (g << 8) | (b);
  816. }
  817. } else {
  818. /* load the palette from the file */
  819. color_start = get_be32(pb);
  820. color_count = get_be16(pb);
  821. color_end = get_be16(pb);
  822. for (j = color_start; j <= color_end; j++) {
  823. /* each R, G, or B component is 16 bits;
  824. * only use the top 8 bits; skip alpha bytes
  825. * up front */
  826. get_byte(pb);
  827. get_byte(pb);
  828. r = get_byte(pb);
  829. get_byte(pb);
  830. g = get_byte(pb);
  831. get_byte(pb);
  832. b = get_byte(pb);
  833. get_byte(pb);
  834. c->palette_control.palette[j] =
  835. (r << 16) | (g << 8) | (b);
  836. }
  837. }
  838. st->codec.palctrl = &c->palette_control;
  839. st->codec.palctrl->palette_changed = 1;
  840. } else
  841. st->codec.palctrl = NULL;
  842. a.size = size;
  843. mov_read_default(c, pb, a);
  844. #endif
  845. } else {
  846. st->codec.codec_id = codec_get_id(mov_audio_tags, format);
  847. if(st->codec.codec_id==CODEC_ID_AMR_NB || st->codec.codec_id==CODEC_ID_AMR_WB) //from TS26.244
  848. {
  849. #ifdef DEBUG
  850. av_log(NULL, AV_LOG_DEBUG, "AMR-NB or AMR-WB audio identified!!\n");
  851. #endif
  852. get_be32(pb);get_be32(pb); //Reserved_8
  853. get_be16(pb);//Reserved_2
  854. get_be16(pb);//Reserved_2
  855. get_be32(pb);//Reserved_4
  856. get_be16(pb);//TimeScale
  857. get_be16(pb);//Reserved_2
  858. //AMRSpecificBox.(10 bytes)
  859. get_be32(pb); //size
  860. get_be32(pb); //type=='damr'
  861. get_be32(pb); //vendor
  862. get_byte(pb); //decoder version
  863. get_be16(pb); //mode_set
  864. get_byte(pb); //mode_change_period
  865. get_byte(pb); //frames_per_sample
  866. st->duration = AV_NOPTS_VALUE;//Not possible to get from this info, must count number of AMR frames
  867. if(st->codec.codec_id==CODEC_ID_AMR_NB)
  868. {
  869. st->codec.sample_rate=8000;
  870. st->codec.channels=1;
  871. }
  872. else //AMR-WB
  873. {
  874. st->codec.sample_rate=16000;
  875. st->codec.channels=1;
  876. }
  877. st->codec.bits_per_sample=16;
  878. st->codec.bit_rate=0; /*It is not possible to tell this before we have
  879. an audio frame and even then every frame can be different*/
  880. }
  881. else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 's' ))
  882. {
  883. //This is some stuff for the hint track, lets ignore it!
  884. //Do some mp4 auto detect.
  885. c->mp4=1;
  886. size-=(16);
  887. url_fskip(pb, size); /* The mp4s atom also contians a esds atom that we can skip*/
  888. }
  889. else if( st->codec.codec_tag == MKTAG( 'm', 'p', '4', 'a' ))
  890. {
  891. /* Handle mp4 audio tag */
  892. get_be32(pb); /* version */
  893. get_be32(pb);
  894. st->codec.channels = get_be16(pb); /* channels */
  895. st->codec.bits_per_sample = get_be16(pb); /* bits per sample */
  896. get_be32(pb);
  897. st->codec.sample_rate = get_be16(pb); /* sample rate, not always correct */
  898. get_be16(pb);
  899. c->mp4=1;
  900. {
  901. MOV_atom_t a = { format, url_ftell(pb), size - (20 + 20 + 8) };
  902. mov_read_default(c, pb, a);
  903. }
  904. /* Get correct sample rate from extradata */
  905. if(st->codec.extradata_size) {
  906. const int samplerate_table[] = {
  907. 96000, 88200, 64000, 48000, 44100, 32000,
  908. 24000, 22050, 16000, 12000, 11025, 8000,
  909. 7350, 0, 0, 0
  910. };
  911. unsigned char *px = st->codec.extradata;
  912. // 5 bits objectTypeIndex, 4 bits sampleRateIndex, 4 bits channels
  913. int samplerate_index = ((px[0] & 7) << 1) + ((px[1] >> 7) & 1);
  914. st->codec.sample_rate = samplerate_table[samplerate_index];
  915. }
  916. }
  917. else if(size>=(16+20))
  918. {//16 bytes read, reading atleast 20 more
  919. #ifdef DEBUG
  920. av_log(NULL, AV_LOG_DEBUG, "audio size=0x%X\n",size);
  921. #endif
  922. uint16_t version = get_be16(pb); /* version */
  923. get_be16(pb); /* revision level */
  924. get_be32(pb); /* vendor */
  925. st->codec.channels = get_be16(pb); /* channel count */
  926. st->codec.bits_per_sample = get_be16(pb); /* sample size */
  927. /* handle specific s8 codec */
  928. get_be16(pb); /* compression id = 0*/
  929. get_be16(pb); /* packet size = 0 */
  930. st->codec.sample_rate = ((get_be32(pb) >> 16));
  931. //av_log(NULL, AV_LOG_DEBUG, "CODECID %d %d %.4s\n", st->codec.codec_id, CODEC_ID_PCM_S16BE, (char*)&format);
  932. switch (st->codec.codec_id) {
  933. case CODEC_ID_PCM_S16BE:
  934. if (st->codec.bits_per_sample == 8)
  935. st->codec.codec_id = CODEC_ID_PCM_S8;
  936. /* fall */
  937. case CODEC_ID_PCM_U8:
  938. st->codec.bit_rate = st->codec.sample_rate * 8;
  939. break;
  940. default:
  941. ;
  942. }
  943. //Read QT version 1 fields. In version 0 theese dont exist
  944. #ifdef DEBUG
  945. av_log(NULL, AV_LOG_DEBUG, "version =%d mp4=%d\n",version,c->mp4);
  946. av_log(NULL, AV_LOG_DEBUG, "size-(16+20+16)=%d\n",size-(16+20+16));
  947. #endif
  948. if((version==1) && size>=(16+20+16))
  949. {
  950. get_be32(pb); /* samples per packet */
  951. get_be32(pb); /* bytes per packet */
  952. get_be32(pb); /* bytes per frame */
  953. get_be32(pb); /* bytes per sample */
  954. if(size>(16+20+16))
  955. {
  956. //Optional, additional atom-based fields
  957. #ifdef DEBUG
  958. av_log(NULL, AV_LOG_DEBUG, "offest=0x%X, sizeleft=%d=0x%x,format=%c%c%c%c\n",(int)url_ftell(pb),size - (16 + 20 + 16 ),size - (16 + 20 + 16 ),
  959. (format >> 0) & 0xff,
  960. (format >> 8) & 0xff,
  961. (format >> 16) & 0xff,
  962. (format >> 24) & 0xff);
  963. #endif
  964. MOV_atom_t a = { format, url_ftell(pb), size - (16 + 20 + 16 + 8) };
  965. mov_read_default(c, pb, a);
  966. }
  967. }
  968. else
  969. {
  970. //We should be down to 0 bytes here, but lets make sure.
  971. size-=(16+20);
  972. #ifdef DEBUG
  973. if(size>0)
  974. av_log(NULL, AV_LOG_DEBUG, "skipping 0x%X bytes\n",size-(16+20));
  975. #endif
  976. url_fskip(pb, size);
  977. }
  978. }
  979. else
  980. {
  981. size-=16;
  982. //Unknown size, but lets do our best and skip the rest.
  983. #ifdef DEBUG
  984. av_log(NULL, AV_LOG_DEBUG, "Strange size, skipping 0x%X bytes\n",size);
  985. #endif
  986. url_fskip(pb, size);
  987. }
  988. }
  989. }
  990. return 0;
  991. }
  992. static int mov_read_stsc(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  993. {
  994. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  995. MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  996. int entries, i;
  997. print_atom("stsc", atom);
  998. get_byte(pb); /* version */
  999. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  1000. entries = get_be32(pb);
  1001. #ifdef DEBUG
  1002. av_log(NULL, AV_LOG_DEBUG, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
  1003. #endif
  1004. sc->sample_to_chunk_sz = entries;
  1005. sc->sample_to_chunk = (MOV_sample_to_chunk_tbl*) av_malloc(entries * sizeof(MOV_sample_to_chunk_tbl));
  1006. if (!sc->sample_to_chunk)
  1007. return -1;
  1008. for(i=0; i<entries; i++) {
  1009. sc->sample_to_chunk[i].first = get_be32(pb);
  1010. sc->sample_to_chunk[i].count = get_be32(pb);
  1011. sc->sample_to_chunk[i].id = get_be32(pb);
  1012. #ifdef DEBUG
  1013. /* av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id); */
  1014. #endif
  1015. }
  1016. return 0;
  1017. }
  1018. static int mov_read_stss(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1019. {
  1020. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1021. MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  1022. int entries, i;
  1023. print_atom("stss", atom);
  1024. get_byte(pb); /* version */
  1025. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  1026. entries = get_be32(pb);
  1027. sc->keyframe_count = entries;
  1028. #ifdef DEBUG
  1029. av_log(NULL, AV_LOG_DEBUG, "keyframe_count = %ld\n", sc->keyframe_count);
  1030. #endif
  1031. sc->keyframes = (long*) av_malloc(entries * sizeof(long));
  1032. if (!sc->keyframes)
  1033. return -1;
  1034. for(i=0; i<entries; i++) {
  1035. sc->keyframes[i] = get_be32(pb);
  1036. #ifdef DEBUG
  1037. /* av_log(NULL, AV_LOG_DEBUG, "keyframes[]=%ld\n", sc->keyframes[i]); */
  1038. #endif
  1039. }
  1040. return 0;
  1041. }
  1042. static int mov_read_stsz(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1043. {
  1044. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1045. MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  1046. int entries, i;
  1047. print_atom("stsz", atom);
  1048. get_byte(pb); /* version */
  1049. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  1050. sc->sample_size = get_be32(pb);
  1051. entries = get_be32(pb);
  1052. sc->sample_count = entries;
  1053. #ifdef DEBUG
  1054. av_log(NULL, AV_LOG_DEBUG, "sample_size = %ld sample_count = %ld\n", sc->sample_size, sc->sample_count);
  1055. #endif
  1056. if(sc->sample_size)
  1057. return 0; /* there isn't any table following */
  1058. sc->sample_sizes = (long*) av_malloc(entries * sizeof(long));
  1059. if (!sc->sample_sizes)
  1060. return -1;
  1061. for(i=0; i<entries; i++) {
  1062. sc->sample_sizes[i] = get_be32(pb);
  1063. #ifdef DEBUG
  1064. /* av_log(NULL, AV_LOG_DEBUG, "sample_sizes[]=%ld\n", sc->sample_sizes[i]); */
  1065. #endif
  1066. }
  1067. return 0;
  1068. }
  1069. static int mov_read_stts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1070. {
  1071. AVStream *st = c->fc->streams[c->fc->nb_streams-1];
  1072. //MOVStreamContext *sc = (MOVStreamContext *)st->priv_data;
  1073. int entries, i;
  1074. int64_t duration=0;
  1075. int64_t total_sample_count=0;
  1076. print_atom("stts", atom);
  1077. get_byte(pb); /* version */
  1078. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  1079. entries = get_be32(pb);
  1080. c->streams[c->fc->nb_streams-1]->stts_count = entries;
  1081. c->streams[c->fc->nb_streams-1]->stts_data = (uint64_t*) av_malloc(entries * sizeof(uint64_t));
  1082. #ifdef DEBUG
  1083. av_log(NULL, AV_LOG_DEBUG, "track[%i].stts.entries = %i\n", c->fc->nb_streams-1, entries);
  1084. #endif
  1085. for(i=0; i<entries; i++) {
  1086. int32_t sample_duration;
  1087. int32_t sample_count;
  1088. sample_count=get_be32(pb);
  1089. sample_duration = get_be32(pb);
  1090. c->streams[c->fc->nb_streams - 1]->stts_data[i] = (uint64_t)sample_count<<32 | (uint64_t)sample_duration;
  1091. #ifdef DEBUG
  1092. av_log(NULL, AV_LOG_DEBUG, "sample_count=%d, sample_duration=%d\n",sample_count,sample_duration);
  1093. #endif
  1094. duration+=sample_duration*sample_count;
  1095. total_sample_count+=sample_count;
  1096. #if 0 //We calculate an average instead, needed by .mp4-files created with nec e606 3g phone
  1097. if (!i && st->codec.codec_type==CODEC_TYPE_VIDEO) {
  1098. st->codec.frame_rate_base = sample_duration ? sample_duration : 1;
  1099. st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
  1100. #ifdef DEBUG
  1101. av_log(NULL, AV_LOG_DEBUG, "VIDEO FRAME RATE= %i (sd= %i)\n", st->codec.frame_rate, sample_duration);
  1102. #endif
  1103. }
  1104. #endif
  1105. }
  1106. /*The stsd atom which contain codec type sometimes comes after the stts so we cannot check for codec_type*/
  1107. if(duration>0)
  1108. {
  1109. av_reduce(
  1110. &st->codec.frame_rate,
  1111. &st->codec.frame_rate_base,
  1112. c->streams[c->fc->nb_streams-1]->time_scale * total_sample_count,
  1113. duration,
  1114. INT_MAX
  1115. );
  1116. #ifdef DEBUG
  1117. av_log(NULL, AV_LOG_DEBUG, "FRAME RATE average (video or audio)= %f (tot sample count= %i ,tot dur= %i timescale=%d)\n", (float)st->codec.frame_rate/st->codec.frame_rate_base,total_sample_count,duration,c->streams[c->fc->nb_streams-1]->time_scale);
  1118. #endif
  1119. }
  1120. else
  1121. {
  1122. st->codec.frame_rate_base = 1;
  1123. st->codec.frame_rate = c->streams[c->fc->nb_streams-1]->time_scale;
  1124. }
  1125. return 0;
  1126. }
  1127. static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1128. {
  1129. AVStream *st;
  1130. MOVStreamContext *sc;
  1131. print_atom("trak", atom);
  1132. st = av_new_stream(c->fc, c->fc->nb_streams);
  1133. if (!st) return -2;
  1134. sc = (MOVStreamContext*) av_mallocz(sizeof(MOVStreamContext));
  1135. if (!sc) {
  1136. av_free(st);
  1137. return -1;
  1138. }
  1139. sc->sample_to_chunk_index = -1;
  1140. st->priv_data = sc;
  1141. st->codec.codec_type = CODEC_TYPE_MOV_OTHER;
  1142. st->start_time = 0; /* XXX: check */
  1143. st->duration = (c->duration * (int64_t)AV_TIME_BASE) / c->time_scale;
  1144. c->streams[c->fc->nb_streams-1] = sc;
  1145. return mov_read_default(c, pb, atom);
  1146. }
  1147. static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1148. {
  1149. AVStream *st;
  1150. print_atom("tkhd", atom);
  1151. st = c->fc->streams[c->fc->nb_streams-1];
  1152. get_byte(pb); /* version */
  1153. get_byte(pb); get_byte(pb);
  1154. get_byte(pb); /* flags */
  1155. /*
  1156. MOV_TRACK_ENABLED 0x0001
  1157. MOV_TRACK_IN_MOVIE 0x0002
  1158. MOV_TRACK_IN_PREVIEW 0x0004
  1159. MOV_TRACK_IN_POSTER 0x0008
  1160. */
  1161. get_be32(pb); /* creation time */
  1162. get_be32(pb); /* modification time */
  1163. st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/
  1164. get_be32(pb); /* reserved */
  1165. st->start_time = 0; /* check */
  1166. st->duration = (get_be32(pb) * (int64_t)AV_TIME_BASE) / c->time_scale; /* duration */
  1167. get_be32(pb); /* reserved */
  1168. get_be32(pb); /* reserved */
  1169. get_be16(pb); /* layer */
  1170. get_be16(pb); /* alternate group */
  1171. get_be16(pb); /* volume */
  1172. get_be16(pb); /* reserved */
  1173. url_fskip(pb, 36); /* display matrix */
  1174. /* those are fixed-point */
  1175. st->codec.width = get_be32(pb) >> 16; /* track width */
  1176. st->codec.height = get_be32(pb) >> 16; /* track height */
  1177. return 0;
  1178. }
  1179. /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */
  1180. /* like the files created with Adobe Premiere 5.0, for samples see */
  1181. /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */
  1182. static int mov_read_wide(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1183. {
  1184. int err;
  1185. #ifdef DEBUG
  1186. print_atom("wide", atom);
  1187. debug_indent++;
  1188. #endif
  1189. if (atom.size < 8)
  1190. return 0; /* continue */
  1191. if (get_be32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */
  1192. url_fskip(pb, atom.size - 4);
  1193. return 0;
  1194. }
  1195. atom.type = get_le32(pb);
  1196. atom.offset += 8;
  1197. atom.size -= 8;
  1198. if (atom.type != MKTAG('m', 'd', 'a', 't')) {
  1199. url_fskip(pb, atom.size);
  1200. return 0;
  1201. }
  1202. err = mov_read_mdat(c, pb, atom);
  1203. #ifdef DEBUG
  1204. debug_indent--;
  1205. #endif
  1206. return err;
  1207. }
  1208. #ifdef CONFIG_ZLIB
  1209. static int null_read_packet(void *opaque, uint8_t *buf, int buf_size)
  1210. {
  1211. return -1;
  1212. }
  1213. static int mov_read_cmov(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1214. {
  1215. ByteIOContext ctx;
  1216. uint8_t *cmov_data;
  1217. uint8_t *moov_data; /* uncompressed data */
  1218. long cmov_len, moov_len;
  1219. int ret;
  1220. print_atom("cmov", atom);
  1221. get_be32(pb); /* dcom atom */
  1222. if (get_le32(pb) != MKTAG( 'd', 'c', 'o', 'm' ))
  1223. return -1;
  1224. if (get_le32(pb) != MKTAG( 'z', 'l', 'i', 'b' )) {
  1225. av_log(NULL, AV_LOG_DEBUG, "unknown compression for cmov atom !");
  1226. return -1;
  1227. }
  1228. get_be32(pb); /* cmvd atom */
  1229. if (get_le32(pb) != MKTAG( 'c', 'm', 'v', 'd' ))
  1230. return -1;
  1231. moov_len = get_be32(pb); /* uncompressed size */
  1232. cmov_len = atom.size - 6 * 4;
  1233. cmov_data = (uint8_t *) av_malloc(cmov_len);
  1234. if (!cmov_data)
  1235. return -1;
  1236. moov_data = (uint8_t *) av_malloc(moov_len);
  1237. if (!moov_data) {
  1238. av_free(cmov_data);
  1239. return -1;
  1240. }
  1241. get_buffer(pb, cmov_data, cmov_len);
  1242. if(uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK)
  1243. return -1;
  1244. if(init_put_byte(&ctx, moov_data, moov_len, 0, NULL, null_read_packet, NULL, NULL) != 0)
  1245. return -1;
  1246. ctx.buf_end = ctx.buffer + moov_len;
  1247. atom.type = MKTAG( 'm', 'o', 'o', 'v' );
  1248. atom.offset = 0;
  1249. atom.size = moov_len;
  1250. #ifdef DEBUG
  1251. { int fd = open("/tmp/uncompheader.mov", O_WRONLY | O_CREAT); write(fd, moov_data, moov_len); close(fd); }
  1252. #endif
  1253. ret = mov_read_default(c, &ctx, atom);
  1254. av_free(moov_data);
  1255. av_free(cmov_data);
  1256. return ret;
  1257. }
  1258. #endif
  1259. /* edit list atom */
  1260. static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)
  1261. {
  1262. int i, edit_count;
  1263. print_atom("elst", atom);
  1264. get_byte(pb); /* version */
  1265. get_byte(pb); get_byte(pb); get_byte(pb); /* flags */
  1266. edit_count= c->streams[c->fc->nb_streams-1]->edit_count = get_be32(pb); /* entries */
  1267. for(i=0; i<edit_count; i++){
  1268. get_be32(pb); /* Track duration */
  1269. get_be32(pb); /* Media time */
  1270. get_be32(pb); /* Media rate */
  1271. }
  1272. #ifdef DEBUG
  1273. av_log(NULL, AV_LOG_DEBUG, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, c->streams[c->fc->nb_streams-1]->edit_count);
  1274. #endif
  1275. return 0;
  1276. }
  1277. static const MOVParseTableEntry mov_default_parse_table[] = {
  1278. /* mp4 atoms */
  1279. { MKTAG( 'c', 'o', '6', '4' ), mov_read_stco },
  1280. { MKTAG( 'c', 'p', 'r', 't' ), mov_read_default },
  1281. { MKTAG( 'c', 'r', 'h', 'd' ), mov_read_default },
  1282. { MKTAG( 'c', 't', 't', 's' ), mov_read_leaf }, /* composition time to sample */
  1283. { MKTAG( 'd', 'i', 'n', 'f' ), mov_read_default }, /* data information */
  1284. { MKTAG( 'd', 'p', 'n', 'd' ), mov_read_leaf },
  1285. { MKTAG( 'd', 'r', 'e', 'f' ), mov_read_leaf },
  1286. { MKTAG( 'e', 'd', 't', 's' ), mov_read_default },
  1287. { MKTAG( 'e', 'l', 's', 't' ), mov_read_elst },
  1288. { MKTAG( 'f', 'r', 'e', 'e' ), mov_read_leaf },
  1289. { MKTAG( 'h', 'd', 'l', 'r' ), mov_read_hdlr },
  1290. { MKTAG( 'h', 'i', 'n', 't' ), mov_read_leaf },
  1291. { MKTAG( 'h', 'm', 'h', 'd' ), mov_read_leaf },
  1292. { MKTAG( 'i', 'o', 'd', 's' ), mov_read_leaf },
  1293. { MKTAG( 'm', 'd', 'a', 't' ), mov_read_mdat },
  1294. { MKTAG( 'm', 'd', 'h', 'd' ), mov_read_mdhd },
  1295. { MKTAG( 'm', 'd', 'i', 'a' ), mov_read_default },
  1296. { MKTAG( 'm', 'i', 'n', 'f' ), mov_read_default },
  1297. { MKTAG( 'm', 'o', 'o', 'v' ), mov_read_moov },
  1298. { MKTAG( 'm', 'p', '4', 'a' ), mov_read_default },
  1299. { MKTAG( 'm', 'p', '4', 's' ), mov_read_default },
  1300. { MKTAG( 'm', 'p', '4', 'v' ), mov_read_default },
  1301. { MKTAG( 'm', 'p', 'o', 'd' ), mov_read_leaf },
  1302. { MKTAG( 'm', 'v', 'h', 'd' ), mov_read_mvhd },
  1303. { MKTAG( 'n', 'm', 'h', 'd' ), mov_read_leaf },
  1304. { MKTAG( 'o', 'd', 'h', 'd' ), mov_read_default },
  1305. { MKTAG( 's', 'd', 'h', 'd' ), mov_read_default },
  1306. { MKTAG( 's', 'k', 'i', 'p' ), mov_read_leaf },
  1307. { MKTAG( 's', 'm', 'h', 'd' ), mov_read_leaf }, /* sound media info header */
  1308. { MKTAG( 'S', 'M', 'I', ' ' ), mov_read_smi }, /* Sorrenson extension ??? */
  1309. { MKTAG( 's', 't', 'b', 'l' ), mov_read_default },
  1310. { MKTAG( 's', 't', 'c', 'o' ), mov_read_stco },
  1311. { MKTAG( 's', 't', 'd', 'p' ), mov_read_default },
  1312. { MKTAG( 's', 't', 's', 'c' ), mov_read_stsc },
  1313. { MKTAG( 's', 't', 's', 'd' ), mov_read_stsd }, /* sample description */
  1314. { MKTAG( 's', 't', 's', 'h' ), mov_read_default },
  1315. { MKTAG( 's', 't', 's', 's' ), mov_read_stss }, /* sync sample */
  1316. { MKTAG( 's', 't', 's', 'z' ), mov_read_stsz }, /* sample size */
  1317. { MKTAG( 's', 't', 't', 's' ), mov_read_stts },
  1318. { MKTAG( 't', 'k', 'h', 'd' ), mov_read_tkhd }, /* track header */
  1319. { MKTAG( 't', 'r', 'a', 'k' ), mov_read_trak },
  1320. { MKTAG( 't', 'r', 'e', 'f' ), mov_read_default }, /* not really */
  1321. { MKTAG( 'u', 'd', 't', 'a' ), mov_read_leaf },
  1322. { MKTAG( 'u', 'r', 'l', ' ' ), mov_read_leaf },
  1323. { MKTAG( 'u', 'r', 'n', ' ' ), mov_read_leaf },
  1324. { MKTAG( 'u', 'u', 'i', 'd' ), mov_read_default },
  1325. { MKTAG( 'v', 'm', 'h', 'd' ), mov_read_leaf }, /* video media info header */
  1326. { MKTAG( 'w', 'a', 'v', 'e' ), mov_read_default },
  1327. /* extra mp4 */
  1328. { MKTAG( 'M', 'D', 'E', 'S' ), mov_read_leaf },
  1329. /* QT atoms */
  1330. { MKTAG( 'c', 'h', 'a', 'p' ), mov_read_leaf },
  1331. { MKTAG( 'c', 'l', 'i', 'p' ), mov_read_default },
  1332. { MKTAG( 'c', 'r', 'g', 'n' ), mov_read_leaf },
  1333. { MKTAG( 'c', 't', 'a', 'b' ), mov_read_ctab },
  1334. { MKTAG( 'e', 's', 'd', 's' ), mov_read_esds },
  1335. { MKTAG( 'k', 'm', 'a', 't' ), mov_read_leaf },
  1336. { MKTAG( 'm', 'a', 't', 't' ), mov_read_default },
  1337. { MKTAG( 'r', 'd', 'r', 'f' ), mov_read_leaf },
  1338. { MKTAG( 'r', 'm', 'd', 'a' ), mov_read_default },
  1339. { MKTAG( 'r', 'm', 'd', 'r' ), mov_read_leaf },
  1340. { MKTAG( 'r', 'm', 'r', 'a' ), mov_read_default },
  1341. { MKTAG( 's', 'c', 'p', 't' ), mov_read_leaf },
  1342. { MKTAG( 's', 's', 'r', 'c' ), mov_read_leaf },
  1343. { MKTAG( 's', 'y', 'n', 'c' ), mov_read_leaf },
  1344. { MKTAG( 't', 'c', 'm', 'd' ), mov_read_leaf },
  1345. { MKTAG( 'w', 'i', 'd', 'e' ), mov_read_wide }, /* place holder */
  1346. //{ MKTAG( 'r', 'm', 'q', 'u' ), mov_read_leaf },
  1347. #ifdef CONFIG_ZLIB
  1348. { MKTAG( 'c', 'm', 'o', 'v' ), mov_read_cmov },
  1349. #else
  1350. { MKTAG( 'c', 'm', 'o', 'v' ), mov_read_leaf },
  1351. #endif
  1352. { 0L, mov_read_leaf }
  1353. };
  1354. static void mov_free_stream_context(MOVStreamContext *sc)
  1355. {
  1356. if(sc) {
  1357. av_free(sc->chunk_offsets);
  1358. av_free(sc->sample_to_chunk);
  1359. av_free(sc->sample_sizes);
  1360. av_free(sc->keyframes);
  1361. av_free(sc->header_data);
  1362. av_free(sc->stts_data);
  1363. av_free(sc);
  1364. }
  1365. }
  1366. static inline uint32_t mov_to_tag(uint8_t *buf)
  1367. {
  1368. return MKTAG(buf[0], buf[1], buf[2], buf[3]);
  1369. }
  1370. static inline uint32_t to_be32(uint8_t *buf)
  1371. {
  1372. return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
  1373. }
  1374. /* XXX: is it sufficient ? */
  1375. static int mov_probe(AVProbeData *p)
  1376. {
  1377. unsigned int offset;
  1378. uint32_t tag;
  1379. /* check file header */
  1380. if (p->buf_size <= 12)
  1381. return 0;
  1382. offset = 0;
  1383. for(;;) {
  1384. /* ignore invalid offset */
  1385. if ((offset + 8) > (unsigned int)p->buf_size)
  1386. return 0;
  1387. tag = mov_to_tag(p->buf + offset + 4);
  1388. switch(tag) {
  1389. case MKTAG( 'm', 'o', 'o', 'v' ):
  1390. case MKTAG( 'w', 'i', 'd', 'e' ):
  1391. case MKTAG( 'f', 'r', 'e', 'e' ):
  1392. case MKTAG( 'm', 'd', 'a', 't' ):
  1393. case MKTAG( 'p', 'n', 'o', 't' ): /* detect movs with preview pics like ew.mov and april.mov */
  1394. case MKTAG( 'u', 'd', 't', 'a' ): /* Packet Video PVAuthor adds this and a lot of more junk */
  1395. return AVPROBE_SCORE_MAX;
  1396. case MKTAG( 'f', 't', 'y', 'p' ):
  1397. case MKTAG( 's', 'k', 'i', 'p' ):
  1398. offset = to_be32(p->buf+offset) + offset;
  1399. break;
  1400. default:
  1401. /* unrecognized tag */
  1402. return 0;
  1403. }
  1404. }
  1405. return 0;
  1406. }
  1407. static int mov_read_header(AVFormatContext *s, AVFormatParameters *ap)
  1408. {
  1409. MOVContext *mov = (MOVContext *) s->priv_data;
  1410. ByteIOContext *pb = &s->pb;
  1411. int i, j, nb, err;
  1412. MOV_atom_t atom = { 0, 0, 0 };
  1413. mov->fc = s;
  1414. mov->parse_table = mov_default_parse_table;
  1415. #if 0
  1416. /* XXX: I think we should auto detect */
  1417. if(s->iformat->name[1] == 'p')
  1418. mov->mp4 = 1;
  1419. #endif
  1420. if(!url_is_streamed(pb)) /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */
  1421. atom.size = url_filesize(url_fileno(pb));
  1422. else
  1423. atom.size = 0x7FFFFFFFFFFFFFFFLL;
  1424. #ifdef DEBUG
  1425. av_log(NULL, AV_LOG_DEBUG, "filesz=%Ld\n", atom.size);
  1426. #endif
  1427. /* check MOV header */
  1428. err = mov_read_default(mov, pb, atom);
  1429. if (err<0 || (!mov->found_moov && !mov->found_mdat)) {
  1430. av_log(s, AV_LOG_ERROR, "mov: header not found !!! (err:%d, moov:%d, mdat:%d) pos:%lld\n",
  1431. err, mov->found_moov, mov->found_mdat, url_ftell(pb));
  1432. return -1;
  1433. }
  1434. #ifdef DEBUG
  1435. av_log(NULL, AV_LOG_DEBUG, "on_parse_exit_offset=%d\n", (int) url_ftell(pb));
  1436. #endif
  1437. /* some cleanup : make sure we are on the mdat atom */
  1438. if(!url_is_streamed(pb) && (url_ftell(pb) != mov->mdat_offset))
  1439. url_fseek(pb, mov->mdat_offset, SEEK_SET);
  1440. mov->next_chunk_offset = mov->mdat_offset; /* initialise reading */
  1441. #ifdef DEBUG
  1442. av_log(NULL, AV_LOG_DEBUG, "mdat_reset_offset=%d\n", (int) url_ftell(pb));
  1443. #endif
  1444. #ifdef DEBUG
  1445. av_log(NULL, AV_LOG_DEBUG, "streams= %d\n", s->nb_streams);
  1446. #endif
  1447. mov->total_streams = nb = s->nb_streams;
  1448. #if 1
  1449. for(i=0; i<s->nb_streams;) {
  1450. if(s->streams[i]->codec.codec_type == CODEC_TYPE_MOV_OTHER) {/* not audio, not video, delete */
  1451. av_free(s->streams[i]);
  1452. for(j=i+1; j<s->nb_streams; j++)
  1453. s->streams[j-1] = s->streams[j];
  1454. s->nb_streams--;
  1455. } else
  1456. i++;
  1457. }
  1458. for(i=0; i<s->nb_streams;i++) {
  1459. MOVStreamContext *sc;
  1460. sc = (MOVStreamContext *)s->streams[i]->priv_data;
  1461. sc->ffindex = i;
  1462. sc->is_ff_stream = 1;
  1463. }
  1464. #endif
  1465. #ifdef DEBUG
  1466. av_log(NULL, AV_LOG_DEBUG, "real streams= %d\n", s->nb_streams);
  1467. #endif
  1468. return 0;
  1469. }
  1470. /* Yes, this is ugly... I didn't write the specs of QT :p */
  1471. /* XXX:remove useless commented code sometime */
  1472. static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
  1473. {
  1474. MOVContext *mov = (MOVContext *) s->priv_data;
  1475. MOVStreamContext *sc;
  1476. int64_t offset = 0x0FFFFFFFFFFFFFFFLL;
  1477. int i, a, b, m;
  1478. int size;
  1479. size = 0x0FFFFFFF;
  1480. #ifdef MOV_SPLIT_CHUNKS
  1481. if (mov->partial) {
  1482. int idx;
  1483. sc = mov->partial;
  1484. idx = sc->sample_to_chunk_index;
  1485. if (idx < 0) return 0;
  1486. size = sc->sample_sizes[sc->current_sample];
  1487. sc->current_sample++;
  1488. sc->left_in_chunk--;
  1489. if (sc->left_in_chunk <= 0)
  1490. mov->partial = 0;
  1491. offset = mov->next_chunk_offset;
  1492. /* extract the sample */
  1493. goto readchunk;
  1494. }
  1495. #endif
  1496. again:
  1497. sc = 0;
  1498. for(i=0; i<mov->total_streams; i++) {
  1499. MOVStreamContext *msc = mov->streams[i];
  1500. //av_log(NULL, AV_LOG_DEBUG, "MOCHUNK %ld %d %p pos:%Ld\n", mov->streams[i]->next_chunk, mov->total_streams, mov->streams[i], url_ftell(&s->pb));
  1501. if ((msc->next_chunk < msc->chunk_count) && msc->next_chunk >= 0
  1502. && (msc->chunk_offsets[msc->next_chunk] < offset)) {
  1503. sc = msc;
  1504. offset = msc->chunk_offsets[msc->next_chunk];
  1505. //av_log(NULL, AV_LOG_DEBUG, "SELETED %Ld i:%d\n", offset, i);
  1506. }
  1507. }
  1508. if (!sc || offset==0x0FFFFFFFFFFFFFFFLL)
  1509. return -1;
  1510. sc->next_chunk++;
  1511. if(mov->next_chunk_offset < offset) { /* some meta data */
  1512. url_fskip(&s->pb, (offset - mov->next_chunk_offset));
  1513. mov->next_chunk_offset = offset;
  1514. }
  1515. //av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli\n", st_id, mov->next_chunk_offset, offset);
  1516. if(!sc->is_ff_stream) {
  1517. url_fskip(&s->pb, (offset - mov->next_chunk_offset));
  1518. mov->next_chunk_offset = offset;
  1519. offset = 0x0FFFFFFFFFFFFFFFLL;
  1520. goto again;
  1521. }
  1522. /* now get the chunk size... */
  1523. for(i=0; i<mov->total_streams; i++) {
  1524. MOVStreamContext *msc = mov->streams[i];
  1525. if ((msc->next_chunk < msc->chunk_count)
  1526. && ((msc->chunk_offsets[msc->next_chunk] - offset) < size))
  1527. size = msc->chunk_offsets[msc->next_chunk] - offset;
  1528. }
  1529. #ifdef MOV_MINOLTA_FIX
  1530. //Make sure that size is according to sample_size (Needed by .mov files
  1531. //created on a Minolta Dimage Xi where audio chunks contains waste data in the end)
  1532. //Maybe we should really not only check sc->sample_size, but also sc->sample_sizes
  1533. //but I have no such movies
  1534. if (sc->sample_size > 0) {
  1535. int foundsize=0;
  1536. for(i=0; i<(sc->sample_to_chunk_sz); i++) {
  1537. if( (sc->sample_to_chunk[i].first)<=(sc->next_chunk) && (sc->sample_size>0) )
  1538. {
  1539. // I can't figure out why for PCM audio sample_size is always 1
  1540. // (it should actually be channels*bits_per_second/8) but it is.
  1541. AVCodecContext* cod = &s->streams[sc->ffindex]->codec;
  1542. if (sc->sample_size == 1 && (cod->codec_id == CODEC_ID_PCM_S16BE || cod->codec_id == CODEC_ID_PCM_S16LE))
  1543. foundsize=(sc->sample_to_chunk[i].count*cod->channels*cod->bits_per_sample)/8;
  1544. else
  1545. foundsize=sc->sample_to_chunk[i].count*sc->sample_size;
  1546. }
  1547. #ifdef DEBUG
  1548. /*av_log(NULL, AV_LOG_DEBUG, "sample_to_chunk first=%ld count=%ld, id=%ld\n", sc->sample_to_chunk[i].first, sc->sample_to_chunk[i].count, sc->sample_to_chunk[i].id);*/
  1549. #endif
  1550. }
  1551. if( (foundsize>0) && (foundsize<size) )
  1552. {
  1553. #ifdef DEBUG
  1554. /*av_log(NULL, AV_LOG_DEBUG, "this size should actually be %d\n",foundsize);*/
  1555. #endif
  1556. size=foundsize;
  1557. }
  1558. }
  1559. #endif //MOV_MINOLTA_FIX
  1560. #ifdef MOV_SPLIT_CHUNKS
  1561. /* split chunks into samples */
  1562. if (sc->sample_size == 0) {
  1563. int idx = sc->sample_to_chunk_index;
  1564. if ((idx + 1 < sc->sample_to_chunk_sz)
  1565. && (sc->next_chunk >= sc->sample_to_chunk[idx + 1].first))
  1566. idx++;
  1567. sc->sample_to_chunk_index = idx;
  1568. if (idx >= 0 && sc->sample_to_chunk[idx].count != 1) {
  1569. mov->partial = sc;
  1570. /* we'll have to get those samples before next chunk */
  1571. sc->left_in_chunk = sc->sample_to_chunk[idx].count - 1;
  1572. size = sc->sample_sizes[sc->current_sample];
  1573. }
  1574. sc->current_sample++;
  1575. }
  1576. #endif
  1577. readchunk:
  1578. //av_log(NULL, AV_LOG_DEBUG, "chunk: [%i] %lli -> %lli (%i)\n", st_id, offset, offset + size, size);
  1579. if(size == 0x0FFFFFFF)
  1580. size = mov->mdat_size + mov->mdat_offset - offset;
  1581. if(size < 0)
  1582. return -1;
  1583. if(size == 0)
  1584. return -1;
  1585. url_fseek(&s->pb, offset, SEEK_SET);
  1586. //av_log(NULL, AV_LOG_DEBUG, "READCHUNK hlen: %d %d off: %Ld pos:%Ld\n", size, sc->header_len, offset, url_ftell(&s->pb));
  1587. if (sc->header_len > 0) {
  1588. av_new_packet(pkt, size + sc->header_len);
  1589. memcpy(pkt->data, sc->header_data, sc->header_len);
  1590. get_buffer(&s->pb, pkt->data + sc->header_len, size);
  1591. /* free header */
  1592. av_freep(&sc->header_data);
  1593. sc->header_len = 0;
  1594. } else {
  1595. av_new_packet(pkt, size);
  1596. get_buffer(&s->pb, pkt->data, pkt->size);
  1597. }
  1598. pkt->stream_index = sc->ffindex;
  1599. // If the keyframes table exists, mark any samples that are in the table as key frames.
  1600. // If no table exists, treat very sample as a key frame.
  1601. if (sc->keyframes) {
  1602. a = 0;
  1603. b = sc->keyframe_count - 1;
  1604. while (a < b) {
  1605. m = (a + b + 1) >> 1;
  1606. if (sc->keyframes[m] > sc->current_sample) {
  1607. b = m - 1;
  1608. } else {
  1609. a = m;
  1610. }
  1611. }
  1612. if (sc->keyframes[a] == sc->current_sample)
  1613. pkt->flags |= PKT_FLAG_KEY;
  1614. }
  1615. else
  1616. pkt->flags |= PKT_FLAG_KEY;
  1617. #ifdef DEBUG
  1618. /*
  1619. av_log(NULL, AV_LOG_DEBUG, "Packet (%d, %d, %ld) ", pkt->stream_index, st_id, pkt->size);
  1620. for(i=0; i<8; i++)
  1621. av_log(NULL, AV_LOG_DEBUG, "%02x ", pkt->data[i]);
  1622. for(i=0; i<8; i++)
  1623. av_log(NULL, AV_LOG_DEBUG, "%c ", (pkt->data[i]) & 0x7F);
  1624. puts("");
  1625. */
  1626. #endif
  1627. mov->next_chunk_offset = offset + size;
  1628. return 0;
  1629. }
  1630. #if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
  1631. /**
  1632. * Seek method based on the one described in the Appendix C of QTFileFormat.pdf
  1633. */
  1634. static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp)
  1635. {
  1636. MOVContext* mov = (MOVContext *) s->priv_data;
  1637. MOVStreamContext* sc;
  1638. int32_t i, a, b, m;
  1639. int64_t sample_time;
  1640. int64_t start_time;
  1641. int32_t seek_sample, sample;
  1642. int32_t duration;
  1643. int32_t count;
  1644. int32_t chunk;
  1645. int32_t left_in_chunk;
  1646. int64_t chunk_file_offset;
  1647. int64_t sample_file_offset;
  1648. int32_t first_chunk_sample;
  1649. int32_t sample_to_chunk_idx;
  1650. int mov_idx;
  1651. // Find the corresponding mov stream
  1652. for (mov_idx = 0; mov_idx < mov->total_streams; mov_idx++)
  1653. if (mov->streams[mov_idx]->ffindex == stream_index)
  1654. break;
  1655. if (mov_idx == mov->total_streams) {
  1656. av_log(s, AV_LOG_ERROR, "mov: requested stream was not found in mov streams (idx=%i)\n", stream_index);
  1657. return -1;
  1658. }
  1659. sc = mov->streams[mov_idx];
  1660. // Step 1. Find the edit that contains the requested time (elst)
  1661. if (sc->edit_count) {
  1662. // FIXME should handle edit list
  1663. av_log(s, AV_LOG_ERROR, "mov: does not handle seeking in files that contain edit list (c:%d)\n", sc->edit_count);
  1664. return -1;
  1665. }
  1666. // Step 2. Find the corresponding sample using the Time-to-sample atom (stts) */
  1667. #ifdef DEBUG
  1668. av_log(s, AV_LOG_DEBUG, "Searching for time %li in stream #%i (time_scale=%i)\n", (long)timestamp, mov_idx, sc->time_scale);
  1669. #endif
  1670. // convert timestamp from time_base unit to timescale unit
  1671. sample_time = av_rescale( timestamp,
  1672. (int64_t)sc->time_scale * s->streams[stream_index]->time_base.num,
  1673. (int64_t)s->streams[stream_index]->time_base.den);
  1674. start_time = 0; // FIXME use elst atom
  1675. sample = 1; // sample are 0 based in table
  1676. #ifdef DEBUG
  1677. av_log(s, AV_LOG_DEBUG, "Searching for sample_time %li \n", (long)sample_time);
  1678. #endif
  1679. for (i = 0; i < sc->stts_count; i++) {
  1680. count = (uint32_t)(sc->stts_data[i]>>32);
  1681. duration = (uint32_t)(sc->stts_data[i]&0xffff);
  1682. //av_log(s, AV_LOG_DEBUG, "> sample_time %lli \n", (long)sample_time);
  1683. //av_log(s, AV_LOG_DEBUG, "> count=%i duration=%i\n", count, duration);
  1684. if ((start_time + count*duration) > sample_time) {
  1685. sample += (sample_time - start_time) / duration;
  1686. break;
  1687. }
  1688. sample += count;
  1689. start_time += count * duration;
  1690. }
  1691. /* NOTE: despite what qt doc say, the dt value (Display Time in qt vocabulary) computed with the stts atom
  1692. is a decoding time stamp (dts) not a presentation time stamp. And as usual dts != pts for stream with b frames */
  1693. #ifdef DEBUG
  1694. av_log(s, AV_LOG_DEBUG, "Found time %li at sample #%u\n", (long)sample_time, sample);
  1695. #endif
  1696. if (sample > sc->sample_count) {
  1697. av_log(s, AV_LOG_ERROR, "mov: sample pos is too high, unable to seek (req. sample=%i, sample count=%ld)\n", sample, sc->sample_count);
  1698. return -1;
  1699. }
  1700. // Step 3. Find the prior sync. sample using the Sync sample atom (stss)
  1701. if (sc->keyframes) {
  1702. a = 0;
  1703. b = sc->keyframe_count - 1;
  1704. while (a < b) {
  1705. m = (a + b + 1) >> 1;
  1706. if (sc->keyframes[m] > sample) {
  1707. b = m - 1;
  1708. } else {
  1709. a = m;
  1710. }
  1711. #ifdef DEBUG
  1712. // av_log(s, AV_LOG_DEBUG, "a=%i (%i) b=%i (%i) m=%i (%i) stream #%i\n", a, sc->keyframes[a], b, sc->keyframes[b], m, sc->keyframes[m], mov_idx);
  1713. #endif
  1714. }
  1715. seek_sample = sc->keyframes[a];
  1716. }
  1717. else
  1718. seek_sample = sample; // else all samples are key frames
  1719. #ifdef DEBUG
  1720. av_log(s, AV_LOG_DEBUG, "Found nearest keyframe at sample #%i \n", seek_sample);
  1721. #endif
  1722. // Step 4. Find the chunk of the sample using the Sample-to-chunk-atom (stsc)
  1723. for (first_chunk_sample = 1, i = 0; i < (sc->sample_to_chunk_sz - 1); i++) {
  1724. b = (sc->sample_to_chunk[i + 1].first - sc->sample_to_chunk[i].first) * sc->sample_to_chunk[i].count;
  1725. if (seek_sample >= first_chunk_sample && seek_sample < (first_chunk_sample + b))
  1726. break;
  1727. first_chunk_sample += b;
  1728. }
  1729. chunk = sc->sample_to_chunk[i].first + (seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count;
  1730. left_in_chunk = sc->sample_to_chunk[i].count - (seek_sample - first_chunk_sample) % sc->sample_to_chunk[i].count;
  1731. first_chunk_sample += ((seek_sample - first_chunk_sample) / sc->sample_to_chunk[i].count) * sc->sample_to_chunk[i].count;
  1732. sample_to_chunk_idx = i;
  1733. #ifdef DEBUG
  1734. av_log(s, AV_LOG_DEBUG, "Sample was found in chunk #%i at sample offset %i (idx %i)\n", chunk, seek_sample - first_chunk_sample, sample_to_chunk_idx);
  1735. #endif
  1736. // Step 5. Find the offset of the chunk using the chunk offset atom
  1737. if (!sc->chunk_offsets) {
  1738. av_log(s, AV_LOG_ERROR, "mov: no chunk offset atom, unable to seek\n");
  1739. return -1;
  1740. }
  1741. if (chunk > sc->chunk_count) {
  1742. av_log(s, AV_LOG_ERROR, "mov: chunk offset atom too short, unable to seek (req. chunk=%i, chunk count=%li)\n", chunk, sc->chunk_count);
  1743. return -1;
  1744. }
  1745. chunk_file_offset = sc->chunk_offsets[chunk - 1];
  1746. #ifdef DEBUG
  1747. av_log(s, AV_LOG_DEBUG, "Chunk file offset is #%llu \n", chunk_file_offset);
  1748. #endif
  1749. // Step 6. Find the byte offset within the chunk using the sample size atom
  1750. sample_file_offset = chunk_file_offset;
  1751. if (sc->sample_size)
  1752. sample_file_offset += (seek_sample - first_chunk_sample) * sc->sample_size;
  1753. else {
  1754. for (i = 0; i < (seek_sample - first_chunk_sample); i++) {
  1755. sample_file_offset += sc->sample_sizes[first_chunk_sample + i - 1];
  1756. }
  1757. }
  1758. #ifdef DEBUG
  1759. av_log(s, AV_LOG_DEBUG, "Sample file offset is #%llu \n", sample_file_offset);
  1760. #endif
  1761. // Step 6. Update the parser
  1762. mov->partial = sc;
  1763. mov->next_chunk_offset = sample_file_offset;
  1764. // Update current stream state
  1765. sc->current_sample = seek_sample - 1; // zero based
  1766. sc->left_in_chunk = left_in_chunk;
  1767. sc->next_chunk = chunk; // +1 -1 (zero based)
  1768. sc->sample_to_chunk_index = sample_to_chunk_idx;
  1769. // Update other streams
  1770. for (i = 0; i<mov->total_streams; i++) {
  1771. MOVStreamContext *msc;
  1772. if (i == mov_idx) continue;
  1773. // Find the nearest 'next' chunk
  1774. msc = mov->streams[i];
  1775. a = 0;
  1776. b = msc->chunk_count - 1;
  1777. while (a < b) {
  1778. m = (a + b + 1) >> 1;
  1779. if (msc->chunk_offsets[m] > chunk_file_offset) {
  1780. b = m - 1;
  1781. } else {
  1782. a = m;
  1783. }
  1784. #ifdef DEBUG
  1785. /* av_log(s, AV_LOG_DEBUG, "a=%i (%li) b=%i (%li) m=%i (%li) stream #%i\n"
  1786. , a, (long)msc->chunk_offsets[a], b, (long)msc->chunk_offsets[b], m, (long)msc->chunk_offsets[m], i); */
  1787. #endif
  1788. }
  1789. msc->next_chunk = a;
  1790. if (msc->chunk_offsets[a] < chunk_file_offset && a < (msc->chunk_count-1))
  1791. msc->next_chunk ++;
  1792. #ifdef DEBUG
  1793. av_log(s, AV_LOG_DEBUG, "Nearest next chunk for stream #%i is #%i @%lli\n", i, msc->next_chunk+1, msc->chunk_offsets[msc->next_chunk]);
  1794. #endif
  1795. // Compute sample count and index in the sample_to_chunk table (what a pity)
  1796. msc->sample_to_chunk_index = 0;
  1797. msc->current_sample = 0;
  1798. for(; msc->sample_to_chunk_index < (msc->sample_to_chunk_sz - 1)
  1799. && msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first <= (1 + msc->next_chunk); msc->sample_to_chunk_index++) {
  1800. msc->current_sample += (msc->sample_to_chunk[msc->sample_to_chunk_index + 1].first - msc->sample_to_chunk[msc->sample_to_chunk_index].first) \
  1801. * msc->sample_to_chunk[msc->sample_to_chunk_index].count;
  1802. }
  1803. msc->current_sample += (msc->next_chunk - (msc->sample_to_chunk[msc->sample_to_chunk_index].first - 1)) * sc->sample_to_chunk[msc->sample_to_chunk_index].count;
  1804. msc->left_in_chunk = msc->sample_to_chunk[msc->sample_to_chunk_index].count - 1;
  1805. #ifdef DEBUG
  1806. av_log(s, AV_LOG_DEBUG, "Next Sample for stream #%i is #%i @%i\n", i, msc->current_sample + 1, msc->sample_to_chunk_index + 1);
  1807. #endif
  1808. }
  1809. return 0;
  1810. }
  1811. #endif
  1812. static int mov_read_close(AVFormatContext *s)
  1813. {
  1814. int i;
  1815. MOVContext *mov = (MOVContext *) s->priv_data;
  1816. for(i=0; i<mov->total_streams; i++)
  1817. mov_free_stream_context(mov->streams[i]);
  1818. /* free color tabs */
  1819. for(i=0; i<mov->ctab_size; i++)
  1820. av_freep(&mov->ctab[i]);
  1821. av_freep(&mov->ctab);
  1822. return 0;
  1823. }
  1824. static AVInputFormat mov_iformat = {
  1825. "mov,mp4,m4a,3gp",
  1826. "QuickTime/MPEG4 format",
  1827. sizeof(MOVContext),
  1828. mov_probe,
  1829. mov_read_header,
  1830. mov_read_packet,
  1831. mov_read_close,
  1832. #if defined(MOV_SPLIT_CHUNKS) && defined(MOV_SEEK)
  1833. mov_read_seek,
  1834. #endif
  1835. };
  1836. int mov_init(void)
  1837. {
  1838. av_register_input_format(&mov_iformat);
  1839. return 0;
  1840. }