yop: Check return value of avio_seek and avoid modifying state if it fails
[libav.git] / libavformat / cafdec.c
CommitLineData
5f14b565
PR
1/*
2 * Core Audio Format demuxer
3 * Copyright (c) 2007 Justin Ruggles
4 * Copyright (c) 2009 Peter Ross
5 *
2912e87a 6 * This file is part of Libav.
5f14b565 7 *
2912e87a 8 * Libav is free software; you can redistribute it and/or
5f14b565
PR
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 *
2912e87a 13 * Libav is distributed in the hope that it will be useful,
5f14b565
PR
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
2912e87a 19 * License along with Libav; if not, write to the Free Software
5f14b565
PR
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23/**
ba87f080 24 * @file
5f14b565
PR
25 * Core Audio Format demuxer
26 */
27
28#include "avformat.h"
c3f9ebf7 29#include "internal.h"
5f14b565
PR
30#include "riff.h"
31#include "isom.h"
32#include "libavutil/intreadwrite.h"
3383a53e 33#include "libavutil/intfloat.h"
d2d67e42 34#include "libavutil/dict.h"
5f14b565
PR
35#include "caf.h"
36
37typedef 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
49static 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 */
57static int read_desc_chunk(AVFormatContext *s)
58{
ae628ec1 59 AVIOContext *pb = s->pb;
5f14b565
PR
60 CaffContext *caf = s->priv_data;
61 AVStream *st;
62 int flags;
63
64 /* new audio stream */
3b3bbdd3 65 st = avformat_new_stream(s, NULL);
5f14b565 66 if (!st)
2874c81c 67 return AVERROR(ENOMEM);
5f14b565
PR
68
69 /* parse format description */
72415b2a 70 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
3383a53e 71 st->codec->sample_rate = av_int2double(avio_rb64(pb));
b7effd4e
AK
72 st->codec->codec_tag = avio_rb32(pb);
73 flags = avio_rb32(pb);
74 caf->bytes_per_packet = avio_rb32(pb);
5f14b565 75 st->codec->block_align = caf->bytes_per_packet;
b7effd4e
AK
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);
5f14b565
PR
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 */
97static int read_kuki_chunk(AVFormatContext *s, int64_t size)
98{
ae628ec1 99 AVIOContext *pb = s->pb;
5f14b565
PR
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
a2704c97 112 strt = avio_tell(pb);
5f14b565 113 ff_mov_read_esds(s, pb, atom);
a2704c97 114 skip = size - (avio_tell(pb) - strt);
5f14b565
PR
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 }
45a8a02a 120 avio_skip(pb, skip);
1e6f8d53
PR
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");
45a8a02a 126 avio_skip(pb, size);
1e6f8d53
PR
127 return AVERROR_INVALIDDATA;
128 }
45a8a02a 129 avio_skip(pb, ALAC_PREAMBLE);
1e6f8d53
PR
130 st->codec->extradata = av_mallocz(ALAC_HEADER + FF_INPUT_BUFFER_PADDING_SIZE);
131 if (!st->codec->extradata)
132 return AVERROR(ENOMEM);
b7effd4e 133 avio_read(pb, st->codec->extradata, ALAC_HEADER);
1e6f8d53 134 st->codec->extradata_size = ALAC_HEADER;
45a8a02a 135 avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
5f14b565
PR
136 } else {
137 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
138 if (!st->codec->extradata)
139 return AVERROR(ENOMEM);
b7effd4e 140 avio_read(pb, st->codec->extradata, size);
5f14b565
PR
141 st->codec->extradata_size = size;
142 }
143
144 return 0;
145}
146
147/** Read packet table chunk */
148static int read_pakt_chunk(AVFormatContext *s, int64_t size)
149{
ae628ec1 150 AVIOContext *pb = s->pb;
5f14b565
PR
151 AVStream *st = s->streams[0];
152 CaffContext *caf = s->priv_data;
153 int64_t pos = 0, ccount;
154 int num_packets, i;
155
a2704c97 156 ccount = avio_tell(pb);
5f14b565 157
b7effd4e 158 num_packets = avio_rb64(pb);
5f14b565
PR
159 if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
160 return AVERROR_INVALIDDATA;
161
b7effd4e
AK
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 */
5f14b565
PR
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);
169 pos += caf->bytes_per_packet ? caf->bytes_per_packet : ff_mp4_read_descr_len(pb);
170 st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);
171 }
172
a2704c97 173 if (avio_tell(pb) - ccount != size) {
5f14b565
PR
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
182/** Read information chunk */
183static void read_info_chunk(AVFormatContext *s, int64_t size)
184{
ae628ec1 185 AVIOContext *pb = s->pb;
5f14b565 186 unsigned int i;
b7effd4e 187 unsigned int nb_entries = avio_rb32(pb);
5f14b565
PR
188 for (i = 0; i < nb_entries; i++) {
189 char key[32];
190 char value[1024];
e16ead07
AK
191 avio_get_str(pb, INT_MAX, key, sizeof(key));
192 avio_get_str(pb, INT_MAX, value, sizeof(value));
d2d67e42 193 av_dict_set(&s->metadata, key, value, 0);
5f14b565
PR
194 }
195}
196
6e9651d1 197static int read_header(AVFormatContext *s)
5f14b565 198{
ae628ec1 199 AVIOContext *pb = s->pb;
5f14b565
PR
200 CaffContext *caf = s->priv_data;
201 AVStream *st;
202 uint32_t tag = 0;
203 int found_data, ret;
204 int64_t size;
205
45a8a02a 206 avio_skip(pb, 8); /* magic, version, file flags */
5f14b565
PR
207
208 /* audio description chunk */
b7effd4e 209 if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
5f14b565
PR
210 av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
211 return AVERROR_INVALIDDATA;
212 }
b7effd4e 213 size = avio_rb64(pb);
5f14b565
PR
214 if (size != 32)
215 return AVERROR_INVALIDDATA;
216
217 ret = read_desc_chunk(s);
218 if (ret)
219 return ret;
220 st = s->streams[0];
221
222 /* parse each chunk */
223 found_data = 0;
66e5b1df 224 while (!pb->eof_reached) {
5f14b565
PR
225
226 /* stop at data chunk if seeking is not supported or
227 data chunk size is unknown */
8978feda 228 if (found_data && (caf->data_size < 0 || !pb->seekable))
5f14b565
PR
229 break;
230
b7effd4e
AK
231 tag = avio_rb32(pb);
232 size = avio_rb64(pb);
66e5b1df 233 if (pb->eof_reached)
5f14b565
PR
234 break;
235
236 switch (tag) {
237 case MKBETAG('d','a','t','a'):
45a8a02a 238 avio_skip(pb, 4); /* edit count */
a2704c97 239 caf->data_start = avio_tell(pb);
5f14b565 240 caf->data_size = size < 0 ? -1 : size - 4;
8978feda 241 if (caf->data_size > 0 && pb->seekable)
45a8a02a 242 avio_skip(pb, caf->data_size);
5f14b565
PR
243 found_data = 1;
244 break;
245
246 /* magic cookie chunk */
247 case MKBETAG('k','u','k','i'):
248 if (read_kuki_chunk(s, size))
249 return AVERROR_INVALIDDATA;
250 break;
251
252 /* packet table chunk */
253 case MKBETAG('p','a','k','t'):
254 if (read_pakt_chunk(s, size))
255 return AVERROR_INVALIDDATA;
256 break;
257
258 case MKBETAG('i','n','f','o'):
259 read_info_chunk(s, size);
260 break;
261
262 default:
263#define _(x) ((x) >= ' ' ? (x) : ' ')
264 av_log(s, AV_LOG_WARNING, "skipping CAF chunk: %08X (%c%c%c%c)\n",
265 tag, _(tag>>24), _((tag>>16)&0xFF), _((tag>>8)&0xFF), _(tag&0xFF));
266#undef _
267 case MKBETAG('f','r','e','e'):
268 if (size < 0)
269 return AVERROR_INVALIDDATA;
45a8a02a 270 avio_skip(pb, size);
5f14b565
PR
271 break;
272 }
273 }
274
275 if (!found_data)
276 return AVERROR_INVALIDDATA;
277
278 if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
279 if (caf->data_size > 0)
280 st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
281 } else if (st->nb_index_entries) {
282 st->codec->bit_rate = st->codec->sample_rate * caf->data_size * 8 /
283 st->duration;
284 } else {
285 av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
286 "block size or frame size are variable.\n");
287 return AVERROR_INVALIDDATA;
288 }
5f14b565 289
c3f9ebf7 290 avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
5f14b565
PR
291 st->start_time = 0;
292
293 /* position the stream at the start of data */
294 if (caf->data_size >= 0)
6b4aa5da 295 avio_seek(pb, caf->data_start, SEEK_SET);
5f14b565
PR
296
297 return 0;
298}
299
300#define CAF_MAX_PKT_SIZE 4096
301
302static int read_packet(AVFormatContext *s, AVPacket *pkt)
303{
ae628ec1 304 AVIOContext *pb = s->pb;
5f14b565
PR
305 AVStream *st = s->streams[0];
306 CaffContext *caf = s->priv_data;
307 int res, pkt_size = 0, pkt_frames = 0;
308 int64_t left = CAF_MAX_PKT_SIZE;
309
66e5b1df 310 if (pb->eof_reached)
5ae092ee 311 return AVERROR(EIO);
5f14b565
PR
312
313 /* don't read past end of data chunk */
314 if (caf->data_size > 0) {
a2704c97 315 left = (caf->data_start + caf->data_size) - avio_tell(pb);
5f14b565 316 if (left <= 0)
5ae092ee 317 return AVERROR(EIO);
5f14b565
PR
318 }
319
320 pkt_frames = caf->frames_per_packet;
321 pkt_size = caf->bytes_per_packet;
322
323 if (pkt_size > 0 && pkt_frames == 1) {
324 pkt_size = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
325 pkt_size = FFMIN(pkt_size, left);
326 pkt_frames = pkt_size / caf->bytes_per_packet;
327 } else if (st->nb_index_entries) {
328 if (caf->packet_cnt < st->nb_index_entries - 1) {
329 pkt_size = st->index_entries[caf->packet_cnt + 1].pos - st->index_entries[caf->packet_cnt].pos;
330 pkt_frames = st->index_entries[caf->packet_cnt + 1].timestamp - st->index_entries[caf->packet_cnt].timestamp;
331 } else if (caf->packet_cnt == st->nb_index_entries - 1) {
332 pkt_size = caf->num_bytes - st->index_entries[caf->packet_cnt].pos;
333 pkt_frames = st->duration - st->index_entries[caf->packet_cnt].timestamp;
334 } else {
5ae092ee 335 return AVERROR(EIO);
5f14b565
PR
336 }
337 }
338
339 if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
5ae092ee 340 return AVERROR(EIO);
5f14b565
PR
341
342 res = av_get_packet(pb, pkt, pkt_size);
343 if (res < 0)
344 return res;
345
346 pkt->size = res;
347 pkt->stream_index = 0;
348 pkt->dts = pkt->pts = caf->frame_cnt;
349
350 caf->packet_cnt++;
351 caf->frame_cnt += pkt_frames;
352
353 return 0;
354}
355
356static int read_seek(AVFormatContext *s, int stream_index,
357 int64_t timestamp, int flags)
358{
359 AVStream *st = s->streams[0];
360 CaffContext *caf = s->priv_data;
361 int64_t pos;
362
363 timestamp = FFMAX(timestamp, 0);
364
365 if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
366 /* calculate new byte position based on target frame position */
367 pos = caf->bytes_per_packet * timestamp / caf->frames_per_packet;
368 if (caf->data_size > 0)
369 pos = FFMIN(pos, caf->data_size);
370 caf->packet_cnt = pos / caf->bytes_per_packet;
371 caf->frame_cnt = caf->frames_per_packet * caf->packet_cnt;
372 } else if (st->nb_index_entries) {
373 caf->packet_cnt = av_index_search_timestamp(st, timestamp, flags);
374 caf->frame_cnt = st->index_entries[caf->packet_cnt].timestamp;
375 pos = st->index_entries[caf->packet_cnt].pos;
376 } else {
377 return -1;
378 }
379
6b4aa5da 380 avio_seek(s->pb, pos + caf->data_start, SEEK_SET);
5f14b565
PR
381 return 0;
382}
383
c6610a21 384AVInputFormat ff_caf_demuxer = {
dfc2c4d9
AK
385 .name = "caf",
386 .long_name = NULL_IF_CONFIG_SMALL("Apple Core Audio Format"),
387 .priv_data_size = sizeof(CaffContext),
388 .read_probe = probe,
389 .read_header = read_header,
390 .read_packet = read_packet,
391 .read_seek = read_seek,
5f14b565
PR
392 .codec_tag = (const AVCodecTag*[]){ff_codec_caf_tags, 0},
393};