avcodec/x86/h264_idct: Fix ff_h264_luma_dc_dequant_idct_sse2 checkasm failures
[ffmpeg.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 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 <inttypes.h>
29
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "demux.h"
33 #include "internal.h"
34 #include "isom.h"
35 #include "mov_chan.h"
36 #include "libavcodec/flac.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/intfloat.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/mem.h"
41 #include "caf.h"
42
43 typedef struct CafContext {
44 int bytes_per_packet; ///< bytes in a packet, or 0 if variable
45 int frames_per_packet; ///< frames in a packet, or 0 if variable
46 int64_t num_bytes; ///< total number of bytes in stream
47
48 int64_t packet_cnt; ///< packet counter
49 int64_t frame_cnt; ///< frame counter
50
51 int64_t data_start; ///< data start position, in bytes
52 int64_t data_size; ///< raw data size, in bytes
53 } CafContext;
54
55 static int probe(const AVProbeData *p)
56 {
57 if (AV_RB32(p->buf) != MKBETAG('c','a','f','f'))
58 return 0;
59 if (AV_RB16(&p->buf[4]) != 1)
60 return 0;
61 if (AV_RB32(p->buf + 8) != MKBETAG('d','e','s','c'))
62 return 0;
63 if (AV_RB64(p->buf + 12) != 32)
64 return 0;
65 return AVPROBE_SCORE_MAX;
66 }
67
68 /** Read audio description chunk */
69 static int read_desc_chunk(AVFormatContext *s)
70 {
71 AVIOContext *pb = s->pb;
72 CafContext *caf = s->priv_data;
73 AVStream *st;
74 int flags;
75
76 /* new audio stream */
77 st = avformat_new_stream(s, NULL);
78 if (!st)
79 return AVERROR(ENOMEM);
80
81 /* parse format description */
82 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
83 st->codecpar->sample_rate = av_clipd(av_int2double(avio_rb64(pb)), 0, INT_MAX);
84 st->codecpar->codec_tag = avio_rl32(pb);
85 flags = avio_rb32(pb);
86 caf->bytes_per_packet = avio_rb32(pb);
87 st->codecpar->block_align = caf->bytes_per_packet;
88 caf->frames_per_packet = avio_rb32(pb);
89 st->codecpar->ch_layout.nb_channels = avio_rb32(pb);
90 st->codecpar->bits_per_coded_sample = avio_rb32(pb);
91
92 if (caf->bytes_per_packet < 0 || caf->frames_per_packet < 0 || st->codecpar->ch_layout.nb_channels < 0)
93 return AVERROR_INVALIDDATA;
94
95 /* calculate bit rate for constant size packets */
96 if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
97 st->codecpar->bit_rate = (uint64_t)st->codecpar->sample_rate * (uint64_t)caf->bytes_per_packet * 8
98 / (uint64_t)caf->frames_per_packet;
99 } else {
100 st->codecpar->bit_rate = 0;
101 }
102
103 /* determine codec */
104 if (st->codecpar->codec_tag == MKTAG('l','p','c','m'))
105 st->codecpar->codec_id = ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample, (flags ^ 0x2) | 0x4);
106 else
107 st->codecpar->codec_id = ff_codec_get_id(ff_codec_caf_tags, st->codecpar->codec_tag);
108 return 0;
109 }
110
111 /** Read magic cookie chunk */
112 static int read_kuki_chunk(AVFormatContext *s, int64_t size)
113 {
114 AVIOContext *pb = s->pb;
115 AVStream *st = s->streams[0];
116 int ret;
117
118 if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE)
119 return -1;
120
121 if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
122 /* The magic cookie format for AAC is an mp4 esds atom.
123 The lavc AAC decoder requires the data from the codec specific
124 description as extradata input. */
125 int strt, skip;
126
127 strt = avio_tell(pb);
128 ff_mov_read_esds(s, pb);
129 skip = size - (avio_tell(pb) - strt);
130 if (skip < 0 || !st->codecpar->extradata ||
131 st->codecpar->codec_id != AV_CODEC_ID_AAC) {
132 av_log(s, AV_LOG_ERROR, "invalid AAC magic cookie\n");
133 return AVERROR_INVALIDDATA;
134 }
135 avio_skip(pb, skip);
136 } else if (st->codecpar->codec_id == AV_CODEC_ID_ALAC) {
137 #define ALAC_PREAMBLE 12
138 #define ALAC_HEADER 36
139 #define ALAC_NEW_KUKI 24
140 uint8_t preamble[12];
141 if (size < ALAC_NEW_KUKI) {
142 av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
143 avio_skip(pb, size);
144 return AVERROR_INVALIDDATA;
145 }
146 if ((ret = ffio_read_size(pb, preamble, ALAC_PREAMBLE)) < 0) {
147 av_log(s, AV_LOG_ERROR, "failed to read preamble\n");
148 return ret;
149 }
150
151 if ((ret = ff_alloc_extradata(st->codecpar, ALAC_HEADER)) < 0)
152 return ret;
153
154 /* For the old style cookie, we skip 12 bytes, then read 36 bytes.
155 * The new style cookie only contains the last 24 bytes of what was
156 * 36 bytes in the old style cookie, so we fabricate the first 12 bytes
157 * in that case to maintain compatibility. */
158 if (!memcmp(&preamble[4], "frmaalac", 8)) {
159 if (size < ALAC_PREAMBLE + ALAC_HEADER) {
160 av_log(s, AV_LOG_ERROR, "invalid ALAC magic cookie\n");
161 av_freep(&st->codecpar->extradata);
162 return AVERROR_INVALIDDATA;
163 }
164 if (avio_read(pb, st->codecpar->extradata, ALAC_HEADER) != ALAC_HEADER) {
165 av_log(s, AV_LOG_ERROR, "failed to read kuki header\n");
166 av_freep(&st->codecpar->extradata);
167 return AVERROR_INVALIDDATA;
168 }
169 avio_skip(pb, size - ALAC_PREAMBLE - ALAC_HEADER);
170 } else {
171 AV_WB32(st->codecpar->extradata, 36);
172 memcpy(&st->codecpar->extradata[4], "alac", 4);
173 AV_WB32(&st->codecpar->extradata[8], 0);
174 memcpy(&st->codecpar->extradata[12], preamble, 12);
175 if (avio_read(pb, &st->codecpar->extradata[24], ALAC_NEW_KUKI - 12) != ALAC_NEW_KUKI - 12) {
176 av_log(s, AV_LOG_ERROR, "failed to read new kuki header\n");
177 av_freep(&st->codecpar->extradata);
178 return AVERROR_INVALIDDATA;
179 }
180 avio_skip(pb, size - ALAC_NEW_KUKI);
181 }
182 } else if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) {
183 int last, type, flac_metadata_size;
184 uint8_t buf[4];
185 /* The magic cookie format for FLAC consists mostly of an mp4 dfLa atom. */
186 if (size < (16 + FLAC_STREAMINFO_SIZE)) {
187 av_log(s, AV_LOG_ERROR, "invalid FLAC magic cookie\n");
188 return AVERROR_INVALIDDATA;
189 }
190 /* Check cookie version. */
191 if (avio_r8(pb) != 0) {
192 av_log(s, AV_LOG_ERROR, "unknown FLAC magic cookie\n");
193 return AVERROR_INVALIDDATA;
194 }
195 avio_rb24(pb); /* Flags */
196 /* read dfLa fourcc */
197 if (avio_read(pb, buf, 4) != 4) {
198 av_log(s, AV_LOG_ERROR, "failed to read FLAC magic cookie\n");
199 return pb->error < 0 ? pb->error : AVERROR_INVALIDDATA;
200 }
201 if (memcmp(buf, "dfLa", 4)) {
202 av_log(s, AV_LOG_ERROR, "invalid FLAC magic cookie\n");
203 return AVERROR_INVALIDDATA;
204 }
205 /* Check dfLa version. */
206 if (avio_r8(pb) != 0) {
207 av_log(s, AV_LOG_ERROR, "unknown dfLa version\n");
208 return AVERROR_INVALIDDATA;
209 }
210 avio_rb24(pb); /* Flags */
211 if (avio_read(pb, buf, sizeof(buf)) != sizeof(buf)) {
212 av_log(s, AV_LOG_ERROR, "failed to read FLAC metadata block header\n");
213 return pb->error < 0 ? pb->error : AVERROR_INVALIDDATA;
214 }
215 flac_parse_block_header(buf, &last, &type, &flac_metadata_size);
216 if (type != FLAC_METADATA_TYPE_STREAMINFO || flac_metadata_size != FLAC_STREAMINFO_SIZE) {
217 av_log(s, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n");
218 return AVERROR_INVALIDDATA;
219 }
220 ret = ff_get_extradata(s, st->codecpar, pb, FLAC_STREAMINFO_SIZE);
221 if (ret < 0)
222 return ret;
223 if (!last)
224 av_log(s, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n");
225 } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
226 // The data layout for Opus is currently unknown, so we do not export
227 // extradata at all. Multichannel streams are not supported.
228 if (st->codecpar->ch_layout.nb_channels > 2) {
229 avpriv_request_sample(s, "multichannel Opus in CAF");
230 return AVERROR_PATCHWELCOME;
231 }
232 avio_skip(pb, size);
233 } else if ((ret = ff_get_extradata(s, st->codecpar, pb, size)) < 0) {
234 return ret;
235 }
236
237 return 0;
238 }
239
240 /** Read packet table chunk */
241 static int read_pakt_chunk(AVFormatContext *s, int64_t size)
242 {
243 AVIOContext *pb = s->pb;
244 AVStream *st = s->streams[0];
245 CafContext *caf = s->priv_data;
246 int64_t pos = 0, ccount, num_packets;
247 int i;
248 int ret;
249
250 ccount = avio_tell(pb);
251
252 num_packets = avio_rb64(pb);
253 if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)
254 return AVERROR_INVALIDDATA;
255
256 st->nb_frames = avio_rb64(pb); /* valid frames */
257 st->nb_frames += avio_rb32(pb); /* priming frames */
258 st->nb_frames += avio_rb32(pb); /* remainder frames */
259
260 if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
261 st->duration = caf->frames_per_packet * num_packets;
262 pos = caf-> bytes_per_packet * num_packets;
263 } else {
264 st->duration = 0;
265 for (i = 0; i < num_packets; i++) {
266 if (avio_feof(pb))
267 return AVERROR_INVALIDDATA;
268 ret = av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);
269 if (ret < 0)
270 return ret;
271 pos += caf->bytes_per_packet ? caf->bytes_per_packet : ff_mp4_read_descr_len(pb);
272 st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);
273 }
274 }
275
276 if (avio_tell(pb) - ccount > size || size > INT64_MAX - ccount) {
277 av_log(s, AV_LOG_ERROR, "error reading packet table\n");
278 return AVERROR_INVALIDDATA;
279 }
280 avio_seek(pb, ccount + size, SEEK_SET);
281
282 caf->num_bytes = pos;
283 return 0;
284 }
285
286 /** Read information chunk */
287 static void read_info_chunk(AVFormatContext *s, int64_t size)
288 {
289 AVIOContext *pb = s->pb;
290 unsigned int i;
291 unsigned int nb_entries = avio_rb32(pb);
292 for (i = 0; i < nb_entries && !avio_feof(pb); i++) {
293 char key[32];
294 char value[1024];
295 avio_get_str(pb, INT_MAX, key, sizeof(key));
296 avio_get_str(pb, INT_MAX, value, sizeof(value));
297 if (!*key)
298 continue;
299 av_dict_set(&s->metadata, key, value, 0);
300 }
301 }
302
303 static int read_header(AVFormatContext *s)
304 {
305 AVIOContext *pb = s->pb;
306 CafContext *caf = s->priv_data;
307 AVStream *st;
308 uint32_t tag = 0;
309 int found_data, ret;
310 int64_t size, pos;
311
312 avio_skip(pb, 8); /* magic, version, file flags */
313
314 /* audio description chunk */
315 if (avio_rb32(pb) != MKBETAG('d','e','s','c')) {
316 av_log(s, AV_LOG_ERROR, "desc chunk not present\n");
317 return AVERROR_INVALIDDATA;
318 }
319 size = avio_rb64(pb);
320 if (size != 32)
321 return AVERROR_INVALIDDATA;
322
323 ret = read_desc_chunk(s);
324 if (ret)
325 return ret;
326 st = s->streams[0];
327
328 /* parse each chunk */
329 found_data = 0;
330 while (!avio_feof(pb)) {
331
332 /* stop at data chunk if seeking is not supported or
333 data chunk size is unknown */
334 if (found_data && (caf->data_size < 0 || !(pb->seekable & AVIO_SEEKABLE_NORMAL)))
335 break;
336
337 tag = avio_rb32(pb);
338 size = avio_rb64(pb);
339 pos = avio_tell(pb);
340 if (avio_feof(pb))
341 break;
342
343 switch (tag) {
344 case MKBETAG('d','a','t','a'):
345 avio_skip(pb, 4); /* edit count */
346 caf->data_start = avio_tell(pb);
347 caf->data_size = size < 0 ? -1 : size - 4;
348 if (caf->data_start < 0 || caf->data_size > INT64_MAX - caf->data_start)
349 return AVERROR_INVALIDDATA;
350
351 if (caf->data_size > 0 && (pb->seekable & AVIO_SEEKABLE_NORMAL))
352 avio_skip(pb, caf->data_size);
353 found_data = 1;
354 break;
355
356 case MKBETAG('c','h','a','n'):
357 if ((ret = ff_mov_read_chan(s, s->pb, st, size)) < 0)
358 return ret;
359 break;
360
361 /* magic cookie chunk */
362 case MKBETAG('k','u','k','i'):
363 if (read_kuki_chunk(s, size))
364 return AVERROR_INVALIDDATA;
365 break;
366
367 /* packet table chunk */
368 case MKBETAG('p','a','k','t'):
369 if (read_pakt_chunk(s, size))
370 return AVERROR_INVALIDDATA;
371 break;
372
373 case MKBETAG('i','n','f','o'):
374 read_info_chunk(s, size);
375 break;
376
377 default:
378 av_log(s, AV_LOG_WARNING,
379 "skipping CAF chunk: %08"PRIX32" (%s), size %"PRId64"\n",
380 tag, av_fourcc2str(av_bswap32(tag)), size);
381 case MKBETAG('f','r','e','e'):
382 if (size < 0 && found_data)
383 goto found_data;
384 if (size < 0)
385 return AVERROR_INVALIDDATA;
386 break;
387 }
388
389 if (size > 0 && (pb->seekable & AVIO_SEEKABLE_NORMAL)) {
390 if (pos > INT64_MAX - size)
391 return AVERROR_INVALIDDATA;
392 avio_seek(pb, pos + size, SEEK_SET);
393 }
394 }
395
396 if (!found_data)
397 return AVERROR_INVALIDDATA;
398
399 found_data:
400 if (caf->bytes_per_packet > 0 && caf->frames_per_packet > 0) {
401 if (caf->data_size > 0 && caf->data_size / caf->bytes_per_packet < INT64_MAX / caf->frames_per_packet)
402 st->nb_frames = (caf->data_size / caf->bytes_per_packet) * caf->frames_per_packet;
403 } else if (ffstream(st)->nb_index_entries && st->duration > 0) {
404 if (st->codecpar->sample_rate && caf->data_size / st->duration > INT64_MAX / st->codecpar->sample_rate / 8) {
405 av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %d * 8 * %"PRId64"\n",
406 st->codecpar->sample_rate, caf->data_size / st->duration);
407 return AVERROR_INVALIDDATA;
408 }
409 st->codecpar->bit_rate = st->codecpar->sample_rate * 8LL *
410 (caf->data_size / st->duration);
411 } else {
412 av_log(s, AV_LOG_ERROR, "Missing packet table. It is required when "
413 "block size or frame size are variable.\n");
414 return AVERROR_INVALIDDATA;
415 }
416
417 avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
418 st->start_time = 0;
419
420 /* position the stream at the start of data */
421 if (caf->data_size >= 0)
422 avio_seek(pb, caf->data_start, SEEK_SET);
423
424 return 0;
425 }
426
427 #define CAF_MAX_PKT_SIZE 4096
428
429 static int read_packet(AVFormatContext *s, AVPacket *pkt)
430 {
431 AVIOContext *pb = s->pb;
432 AVStream *st = s->streams[0];
433 FFStream *const sti = ffstream(st);
434 CafContext *caf = s->priv_data;
435 int res, pkt_size = 0, pkt_frames = 0;
436 int64_t left = CAF_MAX_PKT_SIZE;
437
438 if (avio_feof(pb))
439 return AVERROR_EOF;
440
441 /* don't read past end of data chunk */
442 if (caf->data_size > 0) {
443 left = (caf->data_start + caf->data_size) - avio_tell(pb);
444 if (!left)
445 return AVERROR_EOF;
446 if (left < 0)
447 return AVERROR_INVALIDDATA;
448 }
449
450 pkt_frames = caf->frames_per_packet;
451 pkt_size = caf->bytes_per_packet;
452
453 if (pkt_size > 0 && pkt_frames == 1) {
454 pkt_size = (CAF_MAX_PKT_SIZE / pkt_size) * pkt_size;
455 pkt_size = FFMIN(pkt_size, left);
456 pkt_frames = pkt_size / caf->bytes_per_packet;
457 } else if (sti->nb_index_entries) {
458 if (caf->packet_cnt < sti->nb_index_entries - 1) {
459 pkt_size = sti->index_entries[caf->packet_cnt + 1].pos - sti->index_entries[caf->packet_cnt].pos;
460 pkt_frames = sti->index_entries[caf->packet_cnt + 1].timestamp - sti->index_entries[caf->packet_cnt].timestamp;
461 } else if (caf->packet_cnt == sti->nb_index_entries - 1) {
462 pkt_size = caf->num_bytes - sti->index_entries[caf->packet_cnt].pos;
463 pkt_frames = st->duration - sti->index_entries[caf->packet_cnt].timestamp;
464 } else {
465 return AVERROR_INVALIDDATA;
466 }
467 }
468
469 if (pkt_size == 0 || pkt_frames == 0 || pkt_size > left)
470 return AVERROR_INVALIDDATA;
471
472 res = av_get_packet(pb, pkt, pkt_size);
473 if (res < 0)
474 return res;
475
476 pkt->size = res;
477 pkt->stream_index = 0;
478 pkt->dts = pkt->pts = caf->frame_cnt;
479
480 caf->packet_cnt++;
481 caf->frame_cnt += pkt_frames;
482
483 return 0;
484 }
485
486 static int read_seek(AVFormatContext *s, int stream_index,
487 int64_t timestamp, int flags)
488 {
489 AVStream *st = s->streams[0];
490 FFStream *const sti = ffstream(st);
491 CafContext *caf = s->priv_data;
492 int64_t pos, packet_cnt, frame_cnt;
493
494 timestamp = FFMAX(timestamp, 0);
495
496 if (caf->frames_per_packet > 0 && caf->bytes_per_packet > 0) {
497 /* calculate new byte position based on target frame position */
498 pos = caf->bytes_per_packet * (timestamp / caf->frames_per_packet);
499 if (caf->data_size > 0)
500 pos = FFMIN(pos, caf->data_size);
501 packet_cnt = pos / caf->bytes_per_packet;
502 frame_cnt = caf->frames_per_packet * packet_cnt;
503 } else if (sti->nb_index_entries) {
504 packet_cnt = av_index_search_timestamp(st, timestamp, flags);
505 frame_cnt = sti->index_entries[packet_cnt].timestamp;
506 pos = sti->index_entries[packet_cnt].pos;
507 } else {
508 return -1;
509 }
510
511 if (avio_seek(s->pb, pos + caf->data_start, SEEK_SET) < 0)
512 return -1;
513
514 caf->packet_cnt = packet_cnt;
515 caf->frame_cnt = frame_cnt;
516
517 return 0;
518 }
519
520 const FFInputFormat ff_caf_demuxer = {
521 .p.name = "caf",
522 .p.long_name = NULL_IF_CONFIG_SMALL("Apple CAF (Core Audio Format)"),
523 .p.codec_tag = ff_caf_codec_tags_list,
524 .priv_data_size = sizeof(CafContext),
525 .read_probe = probe,
526 .read_header = read_header,
527 .read_packet = read_packet,
528 .read_seek = read_seek,
529 };