caf: support either old or new style ALAC magic kuki chunk
[libav.git] / libavformat / cafdec.c
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
23 /**
24 * @file
25 * Core Audio Format demuxer
26 */
27
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 {
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 */
57 static int read_desc_chunk(AVFormatContext *s)
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 */
70 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
71 st->codec->sample_rate = av_int2double(avio_rb64(pb));
72 st->codec->codec_tag = avio_rb32(pb);
73 flags = avio_rb32(pb);
74 caf->bytes_per_packet = avio_rb32(pb);
75 st->codec->block_align = caf->bytes_per_packet;
76 caf->frames_per_packet = avio_rb32(pb);
77 st->codec->channels = avio_rb32(pb);
78 st->codec->bits_per_coded_sample = 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
92 st->codec->codec_id = ff_codec_get_id(ff_codec_caf_tags, st->codec->codec_tag);
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
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 #define ALAC_NEW_KUKI 24
125 uint8_t preamble[12];
126 if (size < ALAC_NEW_KUKI || size > ALAC_PREAMBLE + ALAC_HEADER) {
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
133 st->codec->extradata = av_mallocz(ALAC_HEADER + FF_INPUT_BUFFER_PADDING_SIZE);
134 if (!st->codec->extradata)
135 return AVERROR(ENOMEM);
136
137 /* For the old style cookie, we skip 12 bytes, then read 36 bytes.
138 * The new style cookie only contains the last 24 bytes of what was
139 * 36 bytes in the old style cookie, so we fabricate the first 12 bytes
140 * in that case to maintain compatibility. */
141 if (!memcmp(&preamble[4], "frmaalac", 8)) {
142 if (size < ALAC_PREAMBLE + ALAC_HEADER) {
143 av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
144 av_freep(&st->codec->extradata);
145 return AVERROR_INVALIDDATA;
146 }
147 avio_read(pb, st->codec->extradata, ALAC_HEADER);
148 avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
149 } else {
150 AV_WB32(st->codec->extradata, 36);
151 memcpy(&st->codec->extradata[4], "alac", 4);
152 AV_WB32(&st->codec->extradata[8], 0);
153 memcpy(&st->codec->extradata[12], preamble, 12);
154 avio_read(pb, &st->codec->extradata[24], ALAC_NEW_KUKI - 12);
155 avio_skip(pb, size - ALAC_NEW_KUKI);
156 }
157 st->codec->extradata_size = ALAC_HEADER;
158 } else {
159 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
160 if (!st->codec->extradata)
161 return AVERROR(ENOMEM);
162 avio_read(pb, st->codec->extradata, size);
163 st->codec->extradata_size = size;
164 }
165
166 return 0;
167 }
168
169 /** Read packet table chunk */
170 static int read_pakt_chunk(AVFormatContext *s, int64_t size)
171 {
172 AVIOContext *pb = s->pb;
173 AVStream *st = s->streams[0];
174 CaffContext *caf = s->priv_data;
175 int64_t pos = 0, ccount;
176 int num_packets, i;
177
178 ccount = avio_tell(pb);
179
180 num_packets = avio_rb64(pb);
181 if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
182 return AVERROR_INVALIDDATA;
183
184 st->nb_frames = avio_rb64(pb); /* valid frames */
185 st->nb_frames += avio_rb32(pb); /* priming frames */
186 st->nb_frames += avio_rb32(pb); /* remainder frames */
187
188 st->duration = 0;
189 for (i = 0; i < num_packets; i++) {
190 av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);
191 pos += caf->bytes_per_packet ? caf->bytes_per_packet : ff_mp4_read_descr_len(pb);
192 st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);
193 }
194
195 if (avio_tell(pb) - ccount != size) {
196 av_log(s, AV_LOG_ERROR, "error reading packet table\n");
197 return -1;
198 }
199
200 caf->num_bytes = pos;
201 return 0;
202 }
203
204 /** Read information chunk */
205 static void read_info_chunk(AVFormatContext *s, int64_t size)
206 {
207 AVIOContext *pb = s->pb;
208 unsigned int i;
209 unsigned int nb_entries = avio_rb32(pb);
210 for (i = 0; i < nb_entries; i++) {
211 char key[32];
212 char value[1024];
213 avio_get_str(pb, INT_MAX, key, sizeof(key));
214 avio_get_str(pb, INT_MAX, value, sizeof(value));
215 av_dict_set(&s->metadata, key, value, 0);
216 }
217 }
218
219 static int read_header(AVFormatContext *s)
220 {
221 AVIOContext *pb = s->pb;
222 CaffContext *caf = s->priv_data;
223 AVStream *st;
224 uint32_t tag = 0;
225 int found_data, ret;
226 int64_t size;
227
228 avio_skip(pb, 8); /* magic, version, file flags */
229
230 /* audio description chunk */
231 if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
232 av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
233 return AVERROR_INVALIDDATA;
234 }
235 size = avio_rb64(pb);
236 if (size != 32)
237 return AVERROR_INVALIDDATA;
238
239 ret = read_desc_chunk(s);
240 if (ret)
241 return ret;
242 st = s->streams[0];
243
244 /* parse each chunk */
245 found_data = 0;
246 while (!pb->eof_reached) {
247
248 /* stop at data chunk if seeking is not supported or
249 data chunk size is unknown */
250 if (found_data && (caf->data_size < 0 || !pb->seekable))
251 break;
252
253 tag = avio_rb32(pb);
254 size = avio_rb64(pb);
255 if (pb->eof_reached)
256 break;
257
258 switch (tag) {
259 case MKBETAG('d','a','t','a'):
260 avio_skip(pb, 4); /* edit count */
261 caf->data_start = avio_tell(pb);
262 caf->data_size = size < 0 ? -1 : size - 4;
263 if (caf->data_size > 0 && pb->seekable)
264 avio_skip(pb, caf->data_size);
265 found_data = 1;
266 break;
267
268 /* magic cookie chunk */
269 case MKBETAG('k','u','k','i'):
270 if (read_kuki_chunk(s, size))
271 return AVERROR_INVALIDDATA;
272 break;
273
274 /* packet table chunk */
275 case MKBETAG('p','a','k','t'):
276 if (read_pakt_chunk(s, size))
277 return AVERROR_INVALIDDATA;
278 break;
279
280 case MKBETAG('i','n','f','o'):
281 read_info_chunk(s, size);
282 break;
283
284 default:
285 #define _(x) ((x) >= ' ' ? (x) : ' ')
286 av_log(s, AV_LOG_WARNING, "skipping CAF chunk: %08X (%c%c%c%c)\n",
287 tag, _(tag>>24), _((tag>>16)&0xFF), _((tag>>8)&0xFF), _(tag&0xFF));
288 #undef _
289 case MKBETAG('f','r','e','e'):
290 if (size < 0)
291 return AVERROR_INVALIDDATA;
292 avio_skip(pb, size);
293 break;
294 }
295 }
296
297 if (!found_data)
298 return AVERROR_INVALIDDATA;
299
300 if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
301 if (caf->data_size > 0)
302 st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
303 } else if (st->nb_index_entries) {
304 st->codec->bit_rate = st->codec->sample_rate * caf->data_size * 8 /
305 st->duration;
306 } else {
307 av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
308 "block size or frame size are variable.\n");
309 return AVERROR_INVALIDDATA;
310 }
311
312 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
313 st->start_time = 0;
314
315 /* position the stream at the start of data */
316 if (caf->data_size >= 0)
317 avio_seek(pb, caf->data_start, SEEK_SET);
318
319 return 0;
320 }
321
322 #define CAF_MAX_PKT_SIZE 4096
323
324 static int read_packet(AVFormatContext *s, AVPacket *pkt)
325 {
326 AVIOContext *pb = s->pb;
327 AVStream *st = s->streams[0];
328 CaffContext *caf = s->priv_data;
329 int res, pkt_size = 0, pkt_frames = 0;
330 int64_t left = CAF_MAX_PKT_SIZE;
331
332 if (pb->eof_reached)
333 return AVERROR(EIO);
334
335 /* don't read past end of data chunk */
336 if (caf->data_size > 0) {
337 left = (caf->data_start + caf->data_size) - avio_tell(pb);
338 if (left <= 0)
339 return AVERROR(EIO);
340 }
341
342 pkt_frames = caf->frames_per_packet;
343 pkt_size = caf->bytes_per_packet;
344
345 if (pkt_size > 0 && pkt_frames == 1) {
346 pkt_size = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
347 pkt_size = FFMIN(pkt_size, left);
348 pkt_frames = pkt_size / caf->bytes_per_packet;
349 } else if (st->nb_index_entries) {
350 if (caf->packet_cnt < st->nb_index_entries - 1) {
351 pkt_size = st->index_entries[caf->packet_cnt + 1].pos - st->index_entries[caf->packet_cnt].pos;
352 pkt_frames = st->index_entries[caf->packet_cnt + 1].timestamp - st->index_entries[caf->packet_cnt].timestamp;
353 } else if (caf->packet_cnt == st->nb_index_entries - 1) {
354 pkt_size = caf->num_bytes - st->index_entries[caf->packet_cnt].pos;
355 pkt_frames = st->duration - st->index_entries[caf->packet_cnt].timestamp;
356 } else {
357 return AVERROR(EIO);
358 }
359 }
360
361 if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
362 return AVERROR(EIO);
363
364 res = av_get_packet(pb, pkt, pkt_size);
365 if (res < 0)
366 return res;
367
368 pkt->size = res;
369 pkt->stream_index = 0;
370 pkt->dts = pkt->pts = caf->frame_cnt;
371
372 caf->packet_cnt++;
373 caf->frame_cnt += pkt_frames;
374
375 return 0;
376 }
377
378 static int read_seek(AVFormatContext *s, int stream_index,
379 int64_t timestamp, int flags)
380 {
381 AVStream *st = s->streams[0];
382 CaffContext *caf = s->priv_data;
383 int64_t pos, packet_cnt, frame_cnt;
384
385 timestamp = FFMAX(timestamp, 0);
386
387 if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
388 /* calculate new byte position based on target frame position */
389 pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;
390 if (caf->data_size > 0)
391 pos = FFMIN(pos, caf->data_size);
392 packet_cnt = pos / caf->bytes_per_packet;
393 frame_cnt = caf->frames_per_packet * packet_cnt;
394 } else if (st->nb_index_entries) {
395 packet_cnt = av_index_search_timestamp(st, timestamp, flags);
396 frame_cnt = st->index_entries[packet_cnt].timestamp;
397 pos = st->index_entries[packet_cnt].pos;
398 } else {
399 return -1;
400 }
401
402 if (avio_seek(s->pb, pos + caf->data_start, SEEK_SET) < 0)
403 return -1;
404
405 caf->packet_cnt = packet_cnt;
406 caf->frame_cnt = frame_cnt;
407
408 return 0;
409 }
410
411 AVInputFormat ff_caf_demuxer = {
412 .name = "caf",
413 .long_name = NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
414 .priv_data_size = sizeof(CaffContext),
415 .read_probe = probe,
416 .read_header = read_header,
417 .read_packet = read_packet,
418 .read_seek = read_seek,
419 .codec_tag = (const AVCodecTag* const []){ ff_codec_caf_tags, 0 },
420 };