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 int 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 if (0x7FFFFFFFFFFFFFFF - metadata_head_size < sti->index_entries[i].pos)
52 sti->index_entries[i].pos += metadata_head_size;
53 }
54 return 0;
55}
56
57static const uint16_t sr_table[16] = {
58 0, 1764, 3528, 3840, 160, 320, 441, 480, 640, 882, 960, 1920, 0, 0, 0, 0
59};
60
62{
63 int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
64 uint8_t header[4];
65 uint8_t *buffer=NULL;
66 uint32_t marker;
67 FLACDecContext *flac = s->priv_data;
69 if (!st)
70 return AVERROR(ENOMEM);
74 /* the parameters will be extracted from the compressed bitstream */
75
76 /* if fLaC marker is not found, assume there is no header */
77 marker = avio_rl32(s->pb);
78 if (marker != MKTAG('f','L','a','C')) {
79 const int sample_rate = 50 * sr_table[(marker >> 16) & 0xF];
80 if (sample_rate)
81 avpriv_set_pts_info(st, 64, 1, sample_rate);
82 avio_seek(s->pb, -4, SEEK_CUR);
83 return 0;
84 }
85
86 /* process metadata blocks */
87 while (!avio_feof(s->pb) && !metadata_last) {
88 ret = avio_read(s->pb, header, 4);
89 if (ret < 0) {
90 return ret;
91 } else if (ret != 4) {
92 return AVERROR_EOF;
93 }
94
95 flac_parse_block_header(header, &metadata_last, &metadata_type,
96 &metadata_size);
97 switch (metadata_type) {
98 /* allocate and read metadata block for supported types */
105 if (!buffer) {
106 return AVERROR(ENOMEM);
107 }
108 ret = ffio_read_size(s->pb, buffer, metadata_size);
109 if (ret < 0)
110 goto fail;
111
112 break;
113 /* skip metadata block for unsupported types */
114 default:
115 ret = avio_skip(s->pb, metadata_size);
116 if (ret < 0)
117 return ret;
118 }
119
120 if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
121 uint32_t samplerate;
122 uint64_t samples;
123
124 /* STREAMINFO can only occur once */
125 if (found_streaminfo) {
127 }
128 if (metadata_size != FLAC_STREAMINFO_SIZE) {
130 }
131 found_streaminfo = 1;
133 st->codecpar->extradata_size = metadata_size;
134 buffer = NULL;
135
136 /* get sample rate and sample count from STREAMINFO header;
137 * other parameters will be extracted by the parser */
138 samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
139 samples = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
140
141 /* set time base and duration */
142 if (samplerate > 0) {
143 avpriv_set_pts_info(st, 64, 1, samplerate);
144 if (samples > 0)
145 st->duration = samples;
146 }
147 } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
148 uint8_t isrc[13];
149 uint64_t start;
150 const uint8_t *offset;
151 int i, chapters, track, ti;
152 if (metadata_size < 431)
154 offset = buffer + 395;
155 chapters = bytestream_get_byte(&offset) - 1;
156 if (chapters <= 0)
158 for (i = 0; i < chapters; i++) {
159 if (offset + 36 - buffer > metadata_size)
161 start = bytestream_get_be64(&offset);
162 track = bytestream_get_byte(&offset);
163 bytestream_get_buffer(&offset, isrc, 12);
164 isrc[12] = 0;
165 offset += 14;
166 ti = bytestream_get_byte(&offset);
167 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
168 offset += ti * 12;
169 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
170 }
172 } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
173 ret = ff_flac_parse_picture(s, &buffer, metadata_size, 1);
175 if (ret < 0) {
176 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
177 return ret;
178 }
179 } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
180 const uint8_t *seekpoint = buffer;
181 int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
182 flac->found_seektable = 1;
183 if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
184 for(i=0; i<seek_point_count; i++) {
185 int64_t timestamp = bytestream_get_be64(&seekpoint);
186 int64_t pos = bytestream_get_be64(&seekpoint);
187 /* skip number of samples */
188 bytestream_get_be16(&seekpoint);
189 av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
190 }
191 }
193 }
194 else {
195
196 /* STREAMINFO must be the first block */
197 if (!found_streaminfo) {
199 }
200 /* process supported blocks other than STREAMINFO */
201 if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
202 AVDictionaryEntry *chmask;
203
204 ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
205 if (ret < 0) {
206 av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
207 } else if (ret > 0) {
208 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
209 }
210
211 /* parse the channels mask if present */
212 chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
213 if (chmask) {
214 uint64_t mask = strtol(chmask->value, NULL, 0);
215 if (!mask || mask & ~0x3ffffULL) {
217 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
218 } else {
220 av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
221 }
222 }
223 }
225 }
226 }
227
228 ret = ff_replaygain_export(st, s->metadata);
229 if (ret < 0)
230 return ret;
231
232 if (ret = reset_index_position(avio_tell(s->pb), st))
233 return ret;
234 return 0;
235
236fail:
238 return ret;
239}
240
241static int raw_flac_probe(const AVProbeData *p)
242{
243 if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
244 return 0;
245 if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
246 return 0;
247 if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
248 // channel mode invalid
249 return 0;
250 if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
251 return 0;
252 if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
253 return 0;
254 return AVPROBE_SCORE_EXTENSION / 4 + 1;
255}
256
257static int flac_probe(const AVProbeData *p)
258{
259 if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
260 return raw_flac_probe(p);
261
262 /* file header + metadata header + checked bytes of streaminfo */
263 if (p->buf_size >= 4 + 4 + 13) {
264 int type = p->buf[4] & 0x7f;
265 int size = AV_RB24(p->buf + 5);
266 int min_block_size = AV_RB16(p->buf + 8);
267 int max_block_size = AV_RB16(p->buf + 10);
268 int sample_rate = AV_RB24(p->buf + 18) >> 4;
269
270 if (memcmp(p->buf, "fLaC", 4))
271 return 0;
274 min_block_size >= 16 &&
275 max_block_size >= min_block_size &&
276 sample_rate && sample_rate <= 655350)
277 return AVPROBE_SCORE_MAX;
279 }
280
281 return 0;
282}
283
285 int64_t *ppos, int64_t pos_limit)
286{
287 FLACDecContext *flac = s->priv_data;
288 FFFormatContext *const si = ffformatcontext(s);
289 AVPacket *const pkt = si->parse_pkt;
290 AVStream *st = s->streams[stream_index];
291 AVCodecParserContext *parser;
292 int ret = 0;
294
295 if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
296 return AV_NOPTS_VALUE;
297
298 if (!flac->parser_dec) {
300 if (!flac->parser_dec)
301 return AV_NOPTS_VALUE;
302
304 if (ret < 0)
305 return ret;
306 }
307
308 parser = av_parser_init(st->codecpar->codec_id);
309 if (!parser)
310 return AV_NOPTS_VALUE;
312
313 for (;;){
314 uint8_t *data;
315 int size;
316
317 if (ret >= 0 || ret == AVERROR(EAGAIN))
319 if (!ret) {
321 continue;
322 }
323 if (ret < 0){
324 if (ret == AVERROR(EAGAIN))
325 continue;
326 else {
328 av_assert1(!pkt->size);
329 }
330 }
331 av_parser_parse2(parser, flac->parser_dec,
332 &data, &size, pkt->data, pkt->size,
333 pkt->pts, pkt->dts, *ppos);
334
336 if (size) {
337 if (parser->pts != AV_NOPTS_VALUE){
338 // seeking may not have started from beginning of a frame
339 // calculate frame start position from next frame backwards
340 *ppos = parser->next_frame_offset - size;
341 pts = parser->pts;
342 break;
343 }
344 } else if (ret < 0)
345 break;
346 }
347 av_parser_close(parser);
348 return pts;
349}
350
352{
353 FLACDecContext *flac = s->priv_data;
354
356
357 return 0;
358}
359
360static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
361 AVStream *const st = s->streams[0];
362 FFStream *const sti = ffstream(st);
363 int index;
364 int64_t pos;
365 AVIndexEntry e;
366 FLACDecContext *flac = s->priv_data;
367
368 if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
369 return -1;
370 }
371
372 index = av_index_search_timestamp(st, timestamp, flags);
374 return -1;
375
376 e = sti->index_entries[index];
377 pos = avio_seek(s->pb, e.pos, SEEK_SET);
378 if (pos >= 0) {
379 return 0;
380 }
381 return -1;
382}
383
385 .p.name = "flac",
386 .p.long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
387 .p.flags = AVFMT_GENERIC_INDEX,
388 .p.extensions = "flac",
389 .p.priv_class = &ff_raw_demuxer_class,
390 .read_probe = flac_probe,
391 .read_header = flac_read_header,
392 .read_close = flac_close,
393 .read_packet = ff_raw_read_partial_packet,
394 .read_seek = flac_seek,
395 .read_timestamp = flac_read_timestamp,
396 .raw_codec_id = AV_CODEC_ID_FLAC,
397 .priv_data_size = sizeof(FLACDecContext),
398 .flags_internal = FF_INFMT_FLAG_ID3V2_AUTO,
399};
const FFInputFormat ff_flac_demuxer
Definition flacdec.c:384
#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:2673
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:865
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition avformat.h:1796
#define AVINDEX_KEYFRAME
Definition avformat.h:630
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:485
#define AVFMT_FLAG_FAST_SEEK
Enable fast, but inaccurate seeks for some formats.
Definition avformat.h:1572
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition avformat.h:483
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition avformat.h:501
@ AVSTREAM_PARSE_FULL_RAW
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition avformat.h:617
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:507
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:620
unsigned int avio_rl32(AVIOContext *s)
int ffio_read_size(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:674
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:46
#define FF_INFMT_FLAG_ID3V2_AUTO
Automatically parse ID3v2 metadata.
Definition demux.h:45
static AVPacket * pkt
int ret
Definition ffplay.c:391
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:168
@ AV_CODEC_ID_FLAC
Definition codec_id.h:470
#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:435
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:61
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:87
#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
#define AV_RB64(p)
#define AV_RB24(x)
#define AV_RB16(p)
enum MPFType type
Definition jpegmpfenc.c:55
unsigned offset
Definition libaomenc.c:763
static const uint16_t sr_table[16]
Definition flacdec.c:57
static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
Definition flacdec.c:284
static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition flacdec.c:360
#define SEEKPOINT_SIZE
Definition flacdec.c:36
static int flac_read_header(AVFormatContext *s)
Definition flacdec.c:61
static int flac_probe(const AVProbeData *p)
Definition flacdec.c:257
static int flac_close(AVFormatContext *s)
Definition flacdec.c:351
static int raw_flac_probe(const AVProbeData *p)
Definition flacdec.c:241
static int 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:384
static av_always_inline FFFormatContext * ffformatcontext(AVFormatContext *s)
Definition internal.h:135
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:97
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:2641
char * value
Definition dict.h:92
Format I/O context.
Definition avformat.h:1401
int64_t pos
Definition avformat.h:623
This structure stores compressed data.
Definition packet.h:587
This structure contains the data a format has to probe a file.
Definition avformat.h:473
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition avformat.h:827
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
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:198
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition internal.h:196
enum AVStreamParseType need_parsing
Definition internal.h:340
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:33
static int64_t pts
int size