FFmpeg
Loading...
Searching...
No Matches
flacdec.c
Go to the documentation of this file.
1/*
2 * Raw FLAC demuxer
3 * Copyright (c) 2001 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
23#include "libavutil/mem.h"
24#include "libavcodec/avcodec.h"
26#include "libavcodec/flac.h"
27#include "avformat.h"
28#include "avio_internal.h"
29#include "demux.h"
30#include "flac_picture.h"
31#include "internal.h"
32#include "rawdec.h"
33#include "oggdec.h"
34#include "replaygain.h"
35
36#define SEEKPOINT_SIZE 18
37
44
45static void reset_index_position(int64_t metadata_head_size, AVStream *st)
46{
47 FFStream *const sti = ffstream(st);
48 /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
49 for (int i = 0; i < sti->nb_index_entries; i++)
50 sti->index_entries[i].pos += metadata_head_size;
51}
52
53static const uint16_t sr_table[16] = {
54 0, 1764, 3528, 3840, 160, 320, 441, 480, 640, 882, 960, 1920, 0, 0, 0, 0
55};
56
58{
59 int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
60 uint8_t header[4];
61 uint8_t *buffer=NULL;
62 uint32_t marker;
63 FLACDecContext *flac = s->priv_data;
65 if (!st)
66 return AVERROR(ENOMEM);
70 /* the parameters will be extracted from the compressed bitstream */
71
72 /* if fLaC marker is not found, assume there is no header */
73 marker = avio_rl32(s->pb);
74 if (marker != MKTAG('f','L','a','C')) {
75 const int sample_rate = 50 * sr_table[(marker >> 16) & 0xF];
76 if (sample_rate)
77 avpriv_set_pts_info(st, 64, 1, sample_rate);
78 avio_seek(s->pb, -4, SEEK_CUR);
79 return 0;
80 }
81
82 /* process metadata blocks */
83 while (!avio_feof(s->pb) && !metadata_last) {
84 ret = avio_read(s->pb, header, 4);
85 if (ret < 0) {
86 return ret;
87 } else if (ret != 4) {
88 return AVERROR_EOF;
89 }
90
91 flac_parse_block_header(header, &metadata_last, &metadata_type,
92 &metadata_size);
93 switch (metadata_type) {
94 /* allocate and read metadata block for supported types */
101 if (!buffer) {
102 return AVERROR(ENOMEM);
103 }
104 ret = ffio_read_size(s->pb, buffer, metadata_size);
105 if (ret < 0)
106 goto fail;
107
108 break;
109 /* skip metadata block for unsupported types */
110 default:
111 ret = avio_skip(s->pb, metadata_size);
112 if (ret < 0)
113 return ret;
114 }
115
116 if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
117 uint32_t samplerate;
118 uint64_t samples;
119
120 /* STREAMINFO can only occur once */
121 if (found_streaminfo) {
123 }
124 if (metadata_size != FLAC_STREAMINFO_SIZE) {
126 }
127 found_streaminfo = 1;
129 st->codecpar->extradata_size = metadata_size;
130 buffer = NULL;
131
132 /* get sample rate and sample count from STREAMINFO header;
133 * other parameters will be extracted by the parser */
134 samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
135 samples = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
136
137 /* set time base and duration */
138 if (samplerate > 0) {
139 avpriv_set_pts_info(st, 64, 1, samplerate);
140 if (samples > 0)
141 st->duration = samples;
142 }
143 } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
144 uint8_t isrc[13];
145 uint64_t start;
146 const uint8_t *offset;
147 int i, chapters, track, ti;
148 if (metadata_size < 431)
150 offset = buffer + 395;
151 chapters = bytestream_get_byte(&offset) - 1;
152 if (chapters <= 0)
154 for (i = 0; i < chapters; i++) {
155 if (offset + 36 - buffer > metadata_size)
157 start = bytestream_get_be64(&offset);
158 track = bytestream_get_byte(&offset);
159 bytestream_get_buffer(&offset, isrc, 12);
160 isrc[12] = 0;
161 offset += 14;
162 ti = bytestream_get_byte(&offset);
163 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
164 offset += ti * 12;
165 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
166 }
168 } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
169 ret = ff_flac_parse_picture(s, &buffer, metadata_size, 1);
171 if (ret < 0) {
172 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
173 return ret;
174 }
175 } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
176 const uint8_t *seekpoint = buffer;
177 int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
178 flac->found_seektable = 1;
179 if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
180 for(i=0; i<seek_point_count; i++) {
181 int64_t timestamp = bytestream_get_be64(&seekpoint);
182 int64_t pos = bytestream_get_be64(&seekpoint);
183 /* skip number of samples */
184 bytestream_get_be16(&seekpoint);
185 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
186 }
187 }
189 }
190 else {
191
192 /* STREAMINFO must be the first block */
193 if (!found_streaminfo) {
195 }
196 /* process supported blocks other than STREAMINFO */
197 if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
198 AVDictionaryEntry *chmask;
199
200 ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
201 if (ret < 0) {
202 av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
203 } else if (ret > 0) {
204 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
205 }
206
207 /* parse the channels mask if present */
208 chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
209 if (chmask) {
210 uint64_t mask = strtol(chmask->value, NULL, 0);
211 if (!mask || mask & ~0x3ffffULL) {
213 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
214 } else {
216 av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
217 }
218 }
219 }
221 }
222 }
223
224 ret = ff_replaygain_export(st, s->metadata);
225 if (ret < 0)
226 return ret;
227
229 return 0;
230
231fail:
233 return ret;
234}
235
236static int raw_flac_probe(const AVProbeData *p)
237{
238 if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
239 return 0;
240 if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
241 return 0;
242 if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
243 // channel mode invalid
244 return 0;
245 if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
246 return 0;
247 if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
248 return 0;
249 return AVPROBE_SCORE_EXTENSION / 4 + 1;
250}
251
252static int flac_probe(const AVProbeData *p)
253{
254 if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
255 return raw_flac_probe(p);
256
257 /* file header + metadata header + checked bytes of streaminfo */
258 if (p->buf_size >= 4 + 4 + 13) {
259 int type = p->buf[4] & 0x7f;
260 int size = AV_RB24(p->buf + 5);
261 int min_block_size = AV_RB16(p->buf + 8);
262 int max_block_size = AV_RB16(p->buf + 10);
263 int sample_rate = AV_RB24(p->buf + 18) >> 4;
264
265 if (memcmp(p->buf, "fLaC", 4))
266 return 0;
269 min_block_size >= 16 &&
270 max_block_size >= min_block_size &&
271 sample_rate && sample_rate <= 655350)
272 return AVPROBE_SCORE_MAX;
274 }
275
276 return 0;
277}
278
280 int64_t *ppos, int64_t pos_limit)
281{
282 FLACDecContext *flac = s->priv_data;
283 FFFormatContext *const si = ffformatcontext(s);
284 AVPacket *const pkt = si->parse_pkt;
285 AVStream *st = s->streams[stream_index];
286 AVCodecParserContext *parser;
287 int ret;
289
290 if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
291 return AV_NOPTS_VALUE;
292
293 if (!flac->parser_dec) {
295 if (!flac->parser_dec)
296 return AV_NOPTS_VALUE;
297
299 if (ret < 0)
300 return ret;
301 }
302
303 parser = av_parser_init(st->codecpar->codec_id);
304 if (!parser)
305 return AV_NOPTS_VALUE;
307
308 for (;;){
309 uint8_t *data;
310 int size;
311
313 if (ret < 0){
314 if (ret == AVERROR(EAGAIN))
315 continue;
316 else {
318 av_assert1(!pkt->size);
319 }
320 }
321 av_parser_parse2(parser, flac->parser_dec,
322 &data, &size, pkt->data, pkt->size,
323 pkt->pts, pkt->dts, *ppos);
324
326 if (size) {
327 if (parser->pts != AV_NOPTS_VALUE){
328 // seeking may not have started from beginning of a frame
329 // calculate frame start position from next frame backwards
330 *ppos = parser->next_frame_offset - size;
331 pts = parser->pts;
332 break;
333 }
334 } else if (ret < 0)
335 break;
336 }
337 av_parser_close(parser);
338 return pts;
339}
340
342{
343 FLACDecContext *flac = s->priv_data;
344
346
347 return 0;
348}
349
350static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
351 AVStream *const st = s->streams[0];
352 FFStream *const sti = ffstream(st);
353 int index;
354 int64_t pos;
355 AVIndexEntry e;
356 FLACDecContext *flac = s->priv_data;
357
358 if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
359 return -1;
360 }
361
362 index = av_index_search_timestamp(st, timestamp, flags);
364 return -1;
365
366 e = sti->index_entries[index];
367 pos = avio_seek(s->pb, e.pos, SEEK_SET);
368 if (pos >= 0) {
369 return 0;
370 }
371 return -1;
372}
373
375 .p.name = "flac",
376 .p.long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
377 .p.flags = AVFMT_GENERIC_INDEX,
378 .p.extensions = "flac",
379 .p.priv_class = &ff_raw_demuxer_class,
380 .read_probe = flac_probe,
381 .read_header = flac_read_header,
382 .read_close = flac_close,
383 .read_packet = ff_raw_read_partial_packet,
384 .read_seek = flac_seek,
385 .read_timestamp = flac_read_timestamp,
386 .raw_codec_id = AV_CODEC_ID_FLAC,
387 .priv_data_size = sizeof(FLACDecContext),
388 .flags_internal = FF_INFMT_FLAG_ID3V2_AUTO,
389};
const FFInputFormat ff_flac_demuxer
Definition flacdec.c:374
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
Libavcodec external API header.
#define PARSER_FLAG_USE_CODEC_TS
Definition avcodec.h:2655
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:834
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition avformat.h:1727
#define AVINDEX_KEYFRAME
Definition avformat.h:628
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:483
#define AVFMT_FLAG_FAST_SEEK
Enable fast, but inaccurate seeks for some formats.
Definition avformat.h:1503
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition avformat.h:481
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition avformat.h:499
@ AVSTREAM_PARSE_FULL_RAW
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition avformat.h:615
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:494
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:615
unsigned int avio_rl32(AVIOContext *s)
Definition aviobuf.c:733
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:665
static av_always_inline unsigned int bytestream_get_buffer(const uint8_t **b, uint8_t *dst, unsigned int size)
Definition bytestream.h:363
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
Public libavutil channel layout APIs header.
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Definition codec_par.c:206
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
AVChapter * avpriv_new_chapter(AVFormatContext *s, int64_t id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition demux_utils.c:43
#define FF_INFMT_FLAG_ID3V2_AUTO
Automatically parse ID3v2 metadata.
Definition demux.h:45
static AVPacket * pkt
FLAC (Free Lossless Audio Codec) common stuff.
@ FLAC_CHMODE_MID_SIDE
Definition flac.h:42
@ FLAC_METADATA_TYPE_SEEKTABLE
Definition flac.h:49
@ FLAC_METADATA_TYPE_CUESHEET
Definition flac.h:51
@ FLAC_METADATA_TYPE_PICTURE
Definition flac.h:52
@ FLAC_METADATA_TYPE_VORBIS_COMMENT
Definition flac.h:50
@ FLAC_METADATA_TYPE_STREAMINFO
Definition flac.h:46
static av_always_inline void flac_parse_block_header(const uint8_t *block_header, int *last, int *type, int *size)
Parse the metadata block parameters from the header.
Definition flac.h:63
#define FLAC_MAX_CHANNELS
Definition flac.h:33
#define FLAC_STREAMINFO_SIZE
Definition flac.h:32
int ff_flac_parse_picture(AVFormatContext *s, uint8_t **bufp, int buf_size, int truncate_workaround)
Parse a FLAC METADATA_BLOCK_PICTURE.
#define RETURN_ERROR(code)
#define fail
Definition test.h:479
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition options.c:149
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition options.c:164
@ AV_CODEC_ID_FLAC
Definition codec_id.h:465
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
AVCodecParserContext * av_parser_init(enum AVCodecID codec_id)
Definition parser.c:35
void av_parser_close(AVCodecParserContext *s)
Definition parser.c:203
int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos)
Parse a packet.
Definition parser.c:120
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
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 seek.c:122
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition seek.c:245
int av_channel_layout_from_mask(AVChannelLayout *channel_layout, uint64_t mask)
Initialize a native channel layout from a bitmask indicating which channels are present.
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:60
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:86
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
int index
Definition gxfenc.c:90
cl_device_type type
#define AV_RB64(p)
#define AV_RB24(x)
#define AV_RB16(p)
unsigned offset
Definition libaomenc.c:763
static const uint16_t sr_table[16]
Definition flacdec.c:53
static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
Definition flacdec.c:279
static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition flacdec.c:350
#define SEEKPOINT_SIZE
Definition flacdec.c:36
static int flac_read_header(AVFormatContext *s)
Definition flacdec.c:57
static int flac_probe(const AVProbeData *p)
Definition flacdec.c:252
static int flac_close(AVFormatContext *s)
Definition flacdec.c:341
static int raw_flac_probe(const AVProbeData *p)
Definition flacdec.c:236
static void reset_index_position(int64_t metadata_head_size, AVStream *st)
Definition flacdec.c:45
static av_always_inline FFStream * ffstream(AVStream *st)
Definition internal.h:365
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition internal.h:130
const AVClass ff_raw_demuxer_class
Definition rawdec.c:141
int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
Definition rawdec.c:33
#define av_unused
Definition attributes.h:164
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:88
static const uint16_t mask[17]
Definition lzw.c:38
#define MKTAG(a, b, c, d)
Definition macros.h:55
Memory handling functions.
const char data[16]
Definition mxf.c:149
int ff_vorbis_comment(AVFormatContext *ms, AVDictionary **m, const uint8_t *buf, int size, int parse_picture)
Parse Vorbis comments.
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition replaygain.c:94
static const uint8_t header[24]
Definition sdr2.c:68
unsigned int pos
Definition spdifenc.c:431
main external API structure.
Definition avcodec.h:443
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int64_t next_frame_offset
Definition avcodec.h:2623
char * value
Definition dict.h:92
Format I/O context.
Definition avformat.h:1333
int64_t pos
Definition avformat.h:621
This structure stores compressed data.
Definition packet.h:580
This structure contains the data a format has to probe a file.
Definition avformat.h:471
Stream structure.
Definition avformat.h:766
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:789
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition avformat.h:825
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:805
AVPacket * parse_pkt
The generic code uses this as a temporary packet to parse packets or for muxing, especially flushing.
Definition internal.h:104
int nb_index_entries
Definition internal.h:193
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition internal.h:191
enum AVStreamParseType need_parsing
Definition internal.h:321
AVCodecContext * parser_dec
Definition flacdec.c:42
FFRawDemuxerContext rawctx
Definition flacdec.c:39
int found_seektable
Definition flacdec.c:40
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static char buffer[20]
Definition seek.c:32
static int64_t pts
int size