cafdec.c
Go to the documentation of this file.
1 /*
2  * Core Audio Format demuxer
3  * Copyright (c) 2007 Justin Ruggles
4  * Copyright (c) 2009 Peter Ross
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
28 #include "avformat.h"
29 #include "internal.h"
30 #include "riff.h"
31 #include "isom.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/dict.h"
35 #include "caf.h"
36 
37 typedef struct {
40  int64_t num_bytes;
41 
42  int64_t packet_cnt;
43  int64_t frame_cnt;
44 
45  int64_t data_start;
46  int64_t data_size;
47 } CaffContext;
48 
49 static int probe(AVProbeData *p)
50 {
51  if (AV_RB32(p->buf) == MKBETAG('c','a','f','f') && AV_RB16(&p->buf[4]) == 1)
52  return AVPROBE_SCORE_MAX;
53  return 0;
54 }
55 
58 {
59  AVIOContext *pb = s->pb;
60  CaffContext *caf = s->priv_data;
61  AVStream *st;
62  int flags;
63 
64  /* new audio stream */
65  st = avformat_new_stream(s, NULL);
66  if (!st)
67  return AVERROR(ENOMEM);
68 
69  /* parse format description */
72  st->codec->codec_tag = avio_rb32(pb);
73  flags = avio_rb32(pb);
74  caf->bytes_per_packet = avio_rb32(pb);
76  caf->frames_per_packet = avio_rb32(pb);
77  st->codec->channels = avio_rb32(pb);
79 
80  /* calculate bit rate for constant size packets */
81  if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
82  st->codec->bit_rate = (uint64_t)st->codec->sample_rate * (uint64_t)caf->bytes_per_packet * 8
83  / (uint64_t)caf->frames_per_packet;
84  } else {
85  st->codec->bit_rate = 0;
86  }
87 
88  /* determine codec */
89  if (st->codec->codec_tag == MKBETAG('l','p','c','m'))
90  st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, (flags ^ 0x2) | 0x4);
91  else
93  return 0;
94 }
95 
97 static int read_kuki_chunk(AVFormatContext *s, int64_t size)
98 {
99  AVIOContext *pb = s->pb;
100  AVStream *st = s->streams[0];
101 
102  if (size < 0 || size > INT_MAX - FF_INPUT_BUFFER_PADDING_SIZE)
103  return -1;
104 
105  if (st->codec->codec_id == CODEC_ID_AAC) {
106  /* The magic cookie format for AAC is an mp4 esds atom.
107  The lavc AAC decoder requires the data from the codec specific
108  description as extradata input. */
109  int strt, skip;
110  MOVAtom atom;
111 
112  strt = avio_tell(pb);
113  ff_mov_read_esds(s, pb, atom);
114  skip = size - (avio_tell(pb) - strt);
115  if (skip < 0 || !st->codec->extradata ||
116  st->codec->codec_id != CODEC_ID_AAC) {
117  av_log(s, AV_LOG_ERROR, "invalid AAC magic cookie\n");
118  return AVERROR_INVALIDDATA;
119  }
120  avio_skip(pb, skip);
121  } else if (st->codec->codec_id == CODEC_ID_ALAC) {
122 #define ALAC_PREAMBLE 12
123 #define ALAC_HEADER 36
124  if (size < ALAC_PREAMBLE + ALAC_HEADER) {
125  av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
126  avio_skip(pb, size);
127  return AVERROR_INVALIDDATA;
128  }
131  if (!st->codec->extradata)
132  return AVERROR(ENOMEM);
135  avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
136  } else {
138  if (!st->codec->extradata)
139  return AVERROR(ENOMEM);
140  avio_read(pb, st->codec->extradata, size);
141  st->codec->extradata_size = size;
142  }
143 
144  return 0;
145 }
146 
148 static int read_pakt_chunk(AVFormatContext *s, int64_t size)
149 {
150  AVIOContext *pb = s->pb;
151  AVStream *st = s->streams[0];
152  CaffContext *caf = s->priv_data;
153  int64_t pos = 0, ccount;
154  int num_packets, i;
155 
156  ccount = avio_tell(pb);
157 
158  num_packets = avio_rb64(pb);
159  if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
160  return AVERROR_INVALIDDATA;
161 
162  st->nb_frames = avio_rb64(pb); /* valid frames */
163  st->nb_frames += avio_rb32(pb); /* priming frames */
164  st->nb_frames += avio_rb32(pb); /* remainder frames */
165 
166  st->duration = 0;
167  for (i = 0; i < num_packets; i++) {
168  av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);
171  }
172 
173  if (avio_tell(pb) - ccount != size) {
174  av_log(s, AV_LOG_ERROR, "error reading packet table\n");
175  return -1;
176  }
177 
178  caf->num_bytes = pos;
179  return 0;
180 }
181 
183 static void read_info_chunk(AVFormatContext *s, int64_t size)
184 {
185  AVIOContext *pb = s->pb;
186  unsigned int i;
187  unsigned int nb_entries = avio_rb32(pb);
188  for (i = 0; i < nb_entries; i++) {
189  char key[32];
190  char value[1024];
191  avio_get_str(pb, INT_MAX, key, sizeof(key));
192  avio_get_str(pb, INT_MAX, value, sizeof(value));
193  av_dict_set(&s->metadata, key, value, 0);
194  }
195 }
196 
198  AVFormatParameters *ap)
199 {
200  AVIOContext *pb = s->pb;
201  CaffContext *caf = s->priv_data;
202  AVStream *st;
203  uint32_t tag = 0;
204  int found_data, ret;
205  int64_t size;
206 
207  avio_skip(pb, 8); /* magic, version, file flags */
208 
209  /* audio description chunk */
210  if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
211  av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
212  return AVERROR_INVALIDDATA;
213  }
214  size = avio_rb64(pb);
215  if (size != 32)
216  return AVERROR_INVALIDDATA;
217 
218  ret = read_desc_chunk(s);
219  if (ret)
220  return ret;
221  st = s->streams[0];
222 
223  /* parse each chunk */
224  found_data = 0;
225  while (!pb->eof_reached) {
226 
227  /* stop at data chunk if seeking is not supported or
228  data chunk size is unknown */
229  if (found_data && (caf->data_size < 0 || !pb->seekable))
230  break;
231 
232  tag = avio_rb32(pb);
233  size = avio_rb64(pb);
234  if (pb->eof_reached)
235  break;
236 
237  switch (tag) {
238  case MKBETAG('d','a','t','a'):
239  avio_skip(pb, 4); /* edit count */
240  caf->data_start = avio_tell(pb);
241  caf->data_size = size < 0 ? -1 : size - 4;
242  if (caf->data_size > 0 && pb->seekable)
243  avio_skip(pb, caf->data_size);
244  found_data = 1;
245  break;
246 
247  /* magic cookie chunk */
248  case MKBETAG('k','u','k','i'):
249  if (read_kuki_chunk(s, size))
250  return AVERROR_INVALIDDATA;
251  break;
252 
253  /* packet table chunk */
254  case MKBETAG('p','a','k','t'):
255  if (read_pakt_chunk(s, size))
256  return AVERROR_INVALIDDATA;
257  break;
258 
259  case MKBETAG('i','n','f','o'):
260  read_info_chunk(s, size);
261  break;
262 
263  default:
264 #define _(x) ((x) >= ' ' ? (x) : ' ')
265  av_log(s, AV_LOG_WARNING, "skipping CAF chunk: %08X (%c%c%c%c)\n",
266  tag, _(tag>>24), _((tag>>16)&0xFF), _((tag>>8)&0xFF), _(tag&0xFF));
267 #undef _
268  case MKBETAG('f','r','e','e'):
269  if (size < 0)
270  return AVERROR_INVALIDDATA;
271  avio_skip(pb, size);
272  break;
273  }
274  }
275 
276  if (!found_data)
277  return AVERROR_INVALIDDATA;
278 
279  if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
280  if (caf->data_size > 0)
281  st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
282  } else if (st->nb_index_entries) {
283  st->codec->bit_rate = st->codec->sample_rate * caf->data_size * 8 /
284  st->duration;
285  } else {
286  av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
287  "block size or frame size are variable.\n");
288  return AVERROR_INVALIDDATA;
289  }
290 
291  avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
292  st->start_time = 0;
293 
294  /* position the stream at the start of data */
295  if (caf->data_size >= 0)
296  avio_seek(pb, caf->data_start, SEEK_SET);
297 
298  return 0;
299 }
300 
301 #define CAF_MAX_PKT_SIZE 4096
302 
304 {
305  AVIOContext *pb = s->pb;
306  AVStream *st = s->streams[0];
307  CaffContext *caf = s->priv_data;
308  int res, pkt_size = 0, pkt_frames = 0;
309  int64_t left = CAF_MAX_PKT_SIZE;
310 
311  if (pb->eof_reached)
312  return AVERROR(EIO);
313 
314  /* don't read past end of data chunk */
315  if (caf->data_size > 0) {
316  left = (caf->data_start + caf->data_size) - avio_tell(pb);
317  if (left <= 0)
318  return AVERROR(EIO);
319  }
320 
321  pkt_frames = caf->frames_per_packet;
322  pkt_size = caf->bytes_per_packet;
323 
324  if (pkt_size > 0 && pkt_frames == 1) {
325  pkt_size = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
326  pkt_size = FFMIN(pkt_size, left);
327  pkt_frames = pkt_size / caf->bytes_per_packet;
328  } else if (st->nb_index_entries) {
329  if (caf->packet_cnt < st->nb_index_entries - 1) {
330  pkt_size = st->index_entries[caf->packet_cnt + 1].pos - st->index_entries[caf->packet_cnt].pos;
331  pkt_frames = st->index_entries[caf->packet_cnt + 1].timestamp - st->index_entries[caf->packet_cnt].timestamp;
332  } else if (caf->packet_cnt == st->nb_index_entries - 1) {
333  pkt_size = caf->num_bytes - st->index_entries[caf->packet_cnt].pos;
334  pkt_frames = st->duration - st->index_entries[caf->packet_cnt].timestamp;
335  } else {
336  return AVERROR(EIO);
337  }
338  }
339 
340  if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
341  return AVERROR(EIO);
342 
343  res = av_get_packet(pb, pkt, pkt_size);
344  if (res < 0)
345  return res;
346 
347  pkt->size = res;
348  pkt->stream_index = 0;
349  pkt->dts = pkt->pts = caf->frame_cnt;
350 
351  caf->packet_cnt++;
352  caf->frame_cnt += pkt_frames;
353 
354  return 0;
355 }
356 
357 static int read_seek(AVFormatContext *s, int stream_index,
358  int64_t timestamp, int flags)
359 {
360  AVStream *st = s->streams[0];
361  CaffContext *caf = s->priv_data;
362  int64_t pos;
363 
364  timestamp = FFMAX(timestamp, 0);
365 
366  if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
367  /* calculate new byte position based on target frame position */
368  pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;
369  if (caf->data_size > 0)
370  pos = FFMIN(pos, caf->data_size);
371  caf->packet_cnt = pos / caf->bytes_per_packet;
372  caf->frame_cnt = caf->frames_per_packet * caf->packet_cnt;
373  } else if (st->nb_index_entries) {
374  caf->packet_cnt = av_index_search_timestamp(st, timestamp, flags);
375  caf->frame_cnt = st->index_entries[caf->packet_cnt].timestamp;
376  pos = st->index_entries[caf->packet_cnt].pos;
377  } else {
378  return -1;
379  }
380 
381  avio_seek(s->pb, pos + caf->data_start, SEEK_SET);
382  return 0;
383 }
384 
386  .name = "caf",
387  .long_name = NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
388  .priv_data_size = sizeof(CaffContext),
389  .read_probe = probe,
392  .read_seek = read_seek,
393  .codec_tag = (const AVCodecTag*[]){ff_codec_caf_tags, 0},
394 };
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:154
Bytestream IO Context.
Definition: avio.h:68
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:54
AV_WL32 AV_WL24 AV_WL16 AV_WB32 AV_WB24 AV_RB16
Definition: bytestream.h:89
int size
static int read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: cafdec.c:303
int64_t data_size
raw data size, in bytes
Definition: cafdec.c:46
AV_WL32 AV_WL24 AV_WL16 AV_RB32
Definition: bytestream.h:89
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1474
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the pts for a given stream.
Definition: utils.c:3828
int64_t pos
Definition: avformat.h:588
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:117
int size
Definition: avcodec.h:909
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:211
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:818
CAF common code.
#define INT32_MAX
Definition: internal.h:68
#define CAF_MAX_PKT_SIZE
Definition: cafdec.c:301
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:1751
static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: cafdec.c:357
#define _(x)
int64_t data_start
data start position, in bytes
Definition: cafdec.c:45
Format I/O context.
Definition: avformat.h:863
#define ALAC_PREAMBLE
Public dictionary API.
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:58
static int read_kuki_chunk(AVFormatContext *s, int64_t size)
Read magic cookie chunk.
Definition: cafdec.c:97
int64_t num_bytes
total number of bytes in stream
Definition: cafdec.c:40
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:769
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1387
AVStream ** streams
Definition: avformat.h:908
static int flags
Definition: log.c:34
uint32_t tag
Definition: movenc.c:670
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:269
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:842
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:492
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:1974
enum CodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag)
Definition: utils.c:2206
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:652
#define AVINDEX_KEYFRAME
Definition: avformat.h:590
AVDictionary * metadata
Definition: avformat.h:1085
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:1516
int ff_mp4_read_descr_len(AVIOContext *pb)
Definition: isom.c:359
#define AVERROR(e)
Definition: error.h:43
int64_t timestamp
Definition: avformat.h:589
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:191
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:140
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2776
#define FFMAX(a, b)
Definition: common.h:53
AVCodecContext * codec
codec context
Definition: avformat.h:623
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:341
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:122
int bit_rate
the average bitrate
Definition: avcodec.h:1340
#define FFMIN(a, b)
Definition: common.h:55
static int read_header(AVFormatContext *s, AVFormatParameters *ap)
Definition: cafdec.c:197
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:483
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
AVInputFormat ff_caf_demuxer
Definition: cafdec.c:385
static int read_probe(AVProbeData *p)
Definition: img2.c:185
enum CodecID ff_mov_get_lpcm_codec_id(int bps, int flags)
Compute codec id for 'lpcm' tag.
Definition: mov.c:1060
int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb, MOVAtom atom)
Definition: mov.c:518
Stream structure.
Definition: avformat.h:620
NULL
Definition: eval.c:50
enum AVMediaType codec_type
Definition: avcodec.h:1574
int sample_rate
samples per second
Definition: avcodec.h:1456
AVIOContext * pb
Definition: avformat.h:896
int bytes_per_packet
bytes in a packet, or 0 if variable
Definition: cafdec.c:38
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:111
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1590
int extradata_size
Definition: avcodec.h:1388
int64_t packet_cnt
packet counter
Definition: cafdec.c:42
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:50
int nb_index_entries
Definition: avformat.h:820
static void read_info_chunk(AVFormatContext *s, int64_t size)
Read information chunk.
Definition: cafdec.c:183
Definition: isom.h:65
#define FF_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:497
This structure contains the data a format has to probe a file.
Definition: avformat.h:339
static int read_pakt_chunk(AVFormatContext *s, int64_t size)
Read packet table chunk.
Definition: cafdec.c:148
static int probe(AVProbeData *p)
Definition: cafdec.c:49
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:684
#define AVPROBE_SCORE_MAX
maximum score, half of that is used for file-extension-based detection
Definition: avformat.h:345
Main libavformat public API header.
int64_t start_time
Decoding: pts of the first frame of the stream, in stream time base.
Definition: avformat.h:677
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:701
#define ALAC_HEADER
#define MKBETAG(a, b, c, d)
Definition: common.h:232
int eof_reached
true if eof reached
Definition: avio.h:98
int channels
number of audio channels
Definition: avcodec.h:1457
void * priv_data
Format private data.
Definition: avformat.h:883
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:907
int64_t frame_cnt
frame counter
Definition: cafdec.c:43
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:460
int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a string from pb into buf.
Definition: aviobuf.c:800
static int read_desc_chunk(AVFormatContext *s)
Read audio description chunk.
Definition: cafdec.c:57
int stream_index
Definition: avcodec.h:910
const AVCodecTag ff_codec_caf_tags[]
Known codec tags for CAF.
Definition: caf.c:34
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:901
int frames_per_packet
frames in a packet, or 0 if variable
Definition: cafdec.c:39
enum CodecID codec_id
Definition: avcodec.h:1575