FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /**
24  * @file
25  * Core Audio Format demuxer
26  */
27 
28 #include "avformat.h"
29 #include "internal.h"
30 #include "isom.h"
31 #include "mov_chan.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/intfloat.h"
34 #include "libavutil/dict.h"
35 #include "caf.h"
36 
37 typedef struct {
38  int bytes_per_packet; ///< bytes in a packet, or 0 if variable
39  int frames_per_packet; ///< frames in a packet, or 0 if variable
40  int64_t num_bytes; ///< total number of bytes in stream
41 
42  int64_t packet_cnt; ///< packet counter
43  int64_t frame_cnt; ///< frame counter
44 
45  int64_t data_start; ///< data start position, in bytes
46  int64_t data_size; ///< raw data size, in bytes
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 
56 /** Read audio description chunk */
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_rl32(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 == MKTAG('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 
96 /** Read magic cookie chunk */
97 static int read_kuki_chunk(AVFormatContext *s, int64_t size)
98 {
99  AVIOContext *pb = s->pb;
100  AVStream *st = s->streams[0];
101 
103  return -1;
104 
105  if (st->codec->codec_id == AV_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 != AV_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 == AV_CODEC_ID_ALAC) {
122 #define ALAC_PREAMBLE 12
123 #define ALAC_HEADER 36
124 #define ALAC_NEW_KUKI 24
125  uint8_t preamble[12];
126  if (size < ALAC_NEW_KUKI) {
127  av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
128  avio_skip(pb, size);
129  return AVERROR_INVALIDDATA;
130  }
131  avio_read(pb, preamble, ALAC_PREAMBLE);
132 
134  return AVERROR(ENOMEM);
135 
136  /* For the old style cookie, we skip 12 bytes, then read 36 bytes.
137  * The new style cookie only contains the last 24 bytes of what was
138  * 36 bytes in the old style cookie, so we fabricate the first 12 bytes
139  * in that case to maintain compatibility. */
140  if (!memcmp(&preamble[4], "frmaalac", 8)) {
141  if (size < ALAC_PREAMBLE + ALAC_HEADER) {
142  av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
143  av_freep(&st->codec->extradata);
144  return AVERROR_INVALIDDATA;
145  }
147  avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
148  } else {
149  AV_WB32(st->codec->extradata, 36);
150  memcpy(&st->codec->extradata[4], "alac", 4);
151  AV_WB32(&st->codec->extradata[8], 0);
152  memcpy(&st->codec->extradata[12], preamble, 12);
153  avio_read(pb, &st->codec->extradata[24], ALAC_NEW_KUKI - 12);
154  avio_skip(pb, size - ALAC_NEW_KUKI);
155  }
156  } else {
157  if (ff_get_extradata(st->codec, pb, size) < 0)
158  return AVERROR(ENOMEM);
159  }
160 
161  return 0;
162 }
163 
164 /** Read packet table chunk */
165 static int read_pakt_chunk(AVFormatContext *s, int64_t size)
166 {
167  AVIOContext *pb = s->pb;
168  AVStream *st = s->streams[0];
169  CaffContext *caf = s->priv_data;
170  int64_t pos = 0, ccount, num_packets;
171  int i;
172 
173  ccount = avio_tell(pb);
174 
175  num_packets = avio_rb64(pb);
176  if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
177  return AVERROR_INVALIDDATA;
178 
179  st->nb_frames = avio_rb64(pb); /* valid frames */
180  st->nb_frames += avio_rb32(pb); /* priming frames */
181  st->nb_frames += avio_rb32(pb); /* remainder frames */
182 
183  st->duration = 0;
184  for (i = 0; i < num_packets; i++) {
185  av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);
188  }
189 
190  if (avio_tell(pb) - ccount > size) {
191  av_log(s, AV_LOG_ERROR, "error reading packet table\n");
192  return AVERROR_INVALIDDATA;
193  }
194  avio_skip(pb, ccount + size - avio_tell(pb));
195 
196  caf->num_bytes = pos;
197  return 0;
198 }
199 
200 /** Read information chunk */
201 static void read_info_chunk(AVFormatContext *s, int64_t size)
202 {
203  AVIOContext *pb = s->pb;
204  unsigned int i;
205  unsigned int nb_entries = avio_rb32(pb);
206  for (i = 0; i < nb_entries; i++) {
207  char key[32];
208  char value[1024];
209  avio_get_str(pb, INT_MAX, key, sizeof(key));
210  avio_get_str(pb, INT_MAX, value, sizeof(value));
211  av_dict_set(&s->metadata, key, value, 0);
212  }
213 }
214 
216 {
217  AVIOContext *pb = s->pb;
218  CaffContext *caf = s->priv_data;
219  AVStream *st;
220  uint32_t tag = 0;
221  int found_data, ret;
222  int64_t size, pos;
223 
224  avio_skip(pb, 8); /* magic, version, file flags */
225 
226  /* audio description chunk */
227  if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
228  av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
229  return AVERROR_INVALIDDATA;
230  }
231  size = avio_rb64(pb);
232  if (size != 32)
233  return AVERROR_INVALIDDATA;
234 
235  ret = read_desc_chunk(s);
236  if (ret)
237  return ret;
238  st = s->streams[0];
239 
240  /* parse each chunk */
241  found_data = 0;
242  while (!url_feof(pb)) {
243 
244  /* stop at data chunk if seeking is not supported or
245  data chunk size is unknown */
246  if (found_data && (caf->data_size < 0 || !pb->seekable))
247  break;
248 
249  tag = avio_rb32(pb);
250  size = avio_rb64(pb);
251  pos = avio_tell(pb);
252  if (url_feof(pb))
253  break;
254 
255  switch (tag) {
256  case MKBETAG('d','a','t','a'):
257  avio_skip(pb, 4); /* edit count */
258  caf->data_start = avio_tell(pb);
259  caf->data_size = size < 0 ? -1 : size - 4;
260  if (caf->data_size > 0 && pb->seekable)
261  avio_skip(pb, caf->data_size);
262  found_data = 1;
263  break;
264 
265  case MKBETAG('c','h','a','n'):
266  if ((ret = ff_mov_read_chan(s, s->pb, st, size)) < 0)
267  return ret;
268  break;
269 
270  /* magic cookie chunk */
271  case MKBETAG('k','u','k','i'):
272  if (read_kuki_chunk(s, size))
273  return AVERROR_INVALIDDATA;
274  break;
275 
276  /* packet table chunk */
277  case MKBETAG('p','a','k','t'):
278  if (read_pakt_chunk(s, size))
279  return AVERROR_INVALIDDATA;
280  break;
281 
282  case MKBETAG('i','n','f','o'):
283  read_info_chunk(s, size);
284  break;
285 
286  default:
287 #define _(x) ((x) >= ' ' ? (x) : ' ')
288  av_log(s, AV_LOG_WARNING, "skipping CAF chunk: %08X (%c%c%c%c), size %"PRId64"\n",
289  tag, _(tag>>24), _((tag>>16)&0xFF), _((tag>>8)&0xFF), _(tag&0xFF), size);
290 #undef _
291  case MKBETAG('f','r','e','e'):
292  if (size < 0)
293  return AVERROR_INVALIDDATA;
294  break;
295  }
296 
297  if (size > 0) {
298  if (pos > INT64_MAX - size)
299  return AVERROR_INVALIDDATA;
300  avio_skip(pb, FFMAX(0, pos + size - avio_tell(pb)));
301  }
302  }
303 
304  if (!found_data)
305  return AVERROR_INVALIDDATA;
306 
307  if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
308  if (caf->data_size > 0)
309  st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
310  } else if (st->nb_index_entries && st->duration > 0) {
311  st->codec->bit_rate = st->codec->sample_rate * caf->data_size * 8 /
312  st->duration;
313  } else {
314  av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
315  "block size or frame size are variable.\n");
316  return AVERROR_INVALIDDATA;
317  }
318 
319  avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
320  st->start_time = 0;
321 
322  /* position the stream at the start of data */
323  if (caf->data_size >= 0)
324  avio_seek(pb, caf->data_start, SEEK_SET);
325 
326  return 0;
327 }
328 
329 #define CAF_MAX_PKT_SIZE 4096
330 
332 {
333  AVIOContext *pb = s->pb;
334  AVStream *st = s->streams[0];
335  CaffContext *caf = s->priv_data;
336  int res, pkt_size = 0, pkt_frames = 0;
337  int64_t left = CAF_MAX_PKT_SIZE;
338 
339  if (url_feof(pb))
340  return AVERROR_EOF;
341 
342  /* don't read past end of data chunk */
343  if (caf->data_size > 0) {
344  left = (caf->data_start + caf->data_size) - avio_tell(pb);
345  if (!left)
346  return AVERROR_EOF;
347  if (left < 0)
348  return AVERROR(EIO);
349  }
350 
351  pkt_frames = caf->frames_per_packet;
352  pkt_size = caf->bytes_per_packet;
353 
354  if (pkt_size > 0 && pkt_frames == 1) {
355  pkt_size = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
356  pkt_size = FFMIN(pkt_size, left);
357  pkt_frames = pkt_size / caf->bytes_per_packet;
358  } else if (st->nb_index_entries) {
359  if (caf->packet_cnt < st->nb_index_entries - 1) {
360  pkt_size = st->index_entries[caf->packet_cnt + 1].pos - st->index_entries[caf->packet_cnt].pos;
361  pkt_frames = st->index_entries[caf->packet_cnt + 1].timestamp - st->index_entries[caf->packet_cnt].timestamp;
362  } else if (caf->packet_cnt == st->nb_index_entries - 1) {
363  pkt_size = caf->num_bytes - st->index_entries[caf->packet_cnt].pos;
364  pkt_frames = st->duration - st->index_entries[caf->packet_cnt].timestamp;
365  } else {
366  return AVERROR(EIO);
367  }
368  }
369 
370  if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
371  return AVERROR(EIO);
372 
373  res = av_get_packet(pb, pkt, pkt_size);
374  if (res < 0)
375  return res;
376 
377  pkt->size = res;
378  pkt->stream_index = 0;
379  pkt->dts = pkt->pts = caf->frame_cnt;
380 
381  caf->packet_cnt++;
382  caf->frame_cnt += pkt_frames;
383 
384  return 0;
385 }
386 
387 static int read_seek(AVFormatContext *s, int stream_index,
388  int64_t timestamp, int flags)
389 {
390  AVStream *st = s->streams[0];
391  CaffContext *caf = s->priv_data;
392  int64_t pos, packet_cnt, frame_cnt;
393 
394  timestamp = FFMAX(timestamp, 0);
395 
396  if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
397  /* calculate new byte position based on target frame position */
398  pos = caf->bytes_per_packet * (timestamp / caf->frames_per_packet);
399  if (caf->data_size > 0)
400  pos = FFMIN(pos, caf->data_size);
401  packet_cnt = pos / caf->bytes_per_packet;
402  frame_cnt = caf->frames_per_packet * packet_cnt;
403  } else if (st->nb_index_entries) {
404  packet_cnt = av_index_search_timestamp(st, timestamp, flags);
405  frame_cnt = st->index_entries[packet_cnt].timestamp;
406  pos = st->index_entries[packet_cnt].pos;
407  } else {
408  return -1;
409  }
410 
411  if (avio_seek(s->pb, pos + caf->data_start, SEEK_SET) < 0)
412  return -1;
413 
414  caf->packet_cnt = packet_cnt;
415  caf->frame_cnt = frame_cnt;
416 
417  return 0;
418 }
419 
421  .name = "caf",
422  .long_name = NULL_IF_CONFIG_SMALL("Apple CAF (Core Audio Format)"),
423  .priv_data_size = sizeof(CaffContext),
424  .read_probe = probe,
427  .read_seek = read_seek,
428  .codec_tag = (const AVCodecTag* const []){ ff_codec_caf_tags, 0 },
429 };