FFmpeg  4.3.9
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 
22 #include "libavcodec/flac.h"
23 #include "avformat.h"
24 #include "flac_picture.h"
25 #include "internal.h"
26 #include "rawdec.h"
27 #include "oggdec.h"
28 #include "vorbiscomment.h"
29 #include "replaygain.h"
30 
31 #define SEEKPOINT_SIZE 18
32 
33 typedef struct FLACDecContext {
34  AVClass *class;
38 
39 static void reset_index_position(int64_t metadata_head_size, AVStream *st)
40 {
41  /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
42  int i;
43  for(i=0; i<st->nb_index_entries; i++) {
44  st->index_entries[i].pos += metadata_head_size;
45  }
46 }
47 
49 {
50  int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
51  uint8_t header[4];
53  FLACDecContext *flac = s->priv_data;
55  if (!st)
56  return AVERROR(ENOMEM);
60  /* the parameters will be extracted from the compressed bitstream */
61 
62  /* if fLaC marker is not found, assume there is no header */
63  if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
64  avio_seek(s->pb, -4, SEEK_CUR);
65  return 0;
66  }
67 
68  /* process metadata blocks */
69  while (!avio_feof(s->pb) && !metadata_last) {
70  if (avio_read(s->pb, header, 4) != 4)
71  return AVERROR_INVALIDDATA;
72  flac_parse_block_header(header, &metadata_last, &metadata_type,
73  &metadata_size);
74  switch (metadata_type) {
75  /* allocate and read metadata block for supported types */
81  buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
82  if (!buffer) {
83  return AVERROR(ENOMEM);
84  }
85  if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
86  RETURN_ERROR(AVERROR(EIO));
87  }
88  break;
89  /* skip metadata block for unsupported types */
90  default:
91  ret = avio_skip(s->pb, metadata_size);
92  if (ret < 0)
93  return ret;
94  }
95 
96  if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
97  uint32_t samplerate;
98  uint64_t samples;
99 
100  /* STREAMINFO can only occur once */
101  if (found_streaminfo) {
103  }
104  if (metadata_size != FLAC_STREAMINFO_SIZE) {
106  }
107  found_streaminfo = 1;
108  st->codecpar->extradata = buffer;
109  st->codecpar->extradata_size = metadata_size;
110  buffer = NULL;
111 
112  /* get sample rate and sample count from STREAMINFO header;
113  * other parameters will be extracted by the parser */
114  samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
115  samples = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
116 
117  /* set time base and duration */
118  if (samplerate > 0) {
119  avpriv_set_pts_info(st, 64, 1, samplerate);
120  if (samples > 0)
121  st->duration = samples;
122  }
123  } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
124  uint8_t isrc[13];
125  uint64_t start;
126  const uint8_t *offset;
127  int i, chapters, track, ti;
128  if (metadata_size < 431)
130  offset = buffer + 395;
131  chapters = bytestream_get_byte(&offset) - 1;
132  if (chapters <= 0)
134  for (i = 0; i < chapters; i++) {
135  if (offset + 36 - buffer > metadata_size)
137  start = bytestream_get_be64(&offset);
138  track = bytestream_get_byte(&offset);
139  bytestream_get_buffer(&offset, isrc, 12);
140  isrc[12] = 0;
141  offset += 14;
142  ti = bytestream_get_byte(&offset);
143  if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
144  offset += ti * 12;
145  avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
146  }
147  av_freep(&buffer);
148  } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
149  ret = ff_flac_parse_picture(s, buffer, metadata_size, 1);
150  av_freep(&buffer);
151  if (ret < 0) {
152  av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
153  return ret;
154  }
155  } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
156  const uint8_t *seekpoint = buffer;
157  int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
158  flac->found_seektable = 1;
159  if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
160  for(i=0; i<seek_point_count; i++) {
161  int64_t timestamp = bytestream_get_be64(&seekpoint);
162  int64_t pos = bytestream_get_be64(&seekpoint);
163  /* skip number of samples */
164  bytestream_get_be16(&seekpoint);
165  av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
166  }
167  }
168  av_freep(&buffer);
169  }
170  else {
171 
172  /* STREAMINFO must be the first block */
173  if (!found_streaminfo) {
175  }
176  /* process supported blocks other than STREAMINFO */
177  if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
178  AVDictionaryEntry *chmask;
179 
180  ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
181  if (ret < 0) {
182  av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
183  } else if (ret > 0) {
185  }
186 
187  /* parse the channels mask if present */
188  chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
189  if (chmask) {
190  uint64_t mask = strtol(chmask->value, NULL, 0);
191  if (!mask || mask & ~0x3ffffULL) {
193  "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
194  } else {
196  av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
197  }
198  }
199  }
200  av_freep(&buffer);
201  }
202  }
203 
204  ret = ff_replaygain_export(st, s->metadata);
205  if (ret < 0)
206  return ret;
207 
209  return 0;
210 
211 fail:
212  av_free(buffer);
213  return ret;
214 }
215 
216 static int raw_flac_probe(const AVProbeData *p)
217 {
218  if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
219  return 0;
220  if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
221  return 0;
222  if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
223  // channel mode invalid
224  return 0;
225  if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
226  return 0;
227  if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
228  return 0;
229  return AVPROBE_SCORE_EXTENSION / 4 + 1;
230 }
231 
232 static int flac_probe(const AVProbeData *p)
233 {
234  if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
235  return raw_flac_probe(p);
236 
237  /* file header + metadata header + checked bytes of streaminfo */
238  if (p->buf_size >= 4 + 4 + 13) {
239  int type = p->buf[4] & 0x7f;
240  int size = AV_RB24(p->buf + 5);
241  int min_block_size = AV_RB16(p->buf + 8);
242  int max_block_size = AV_RB16(p->buf + 10);
243  int sample_rate = AV_RB24(p->buf + 18) >> 4;
244 
245  if (memcmp(p->buf, "fLaC", 4))
246  return 0;
247  if (type == FLAC_METADATA_TYPE_STREAMINFO &&
248  size == FLAC_STREAMINFO_SIZE &&
249  min_block_size >= 16 &&
250  max_block_size >= min_block_size &&
251  sample_rate && sample_rate <= 655350)
252  return AVPROBE_SCORE_MAX;
254  }
255 
256  return 0;
257 }
258 
260  int64_t *ppos, int64_t pos_limit)
261 {
262  AVPacket pkt;
263  AVStream *st = s->streams[stream_index];
264  AVCodecParserContext *parser;
265  int ret;
267 
268  if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
269  return AV_NOPTS_VALUE;
270 
271  av_init_packet(&pkt);
272  parser = av_parser_init(st->codecpar->codec_id);
273  if (!parser){
274  return AV_NOPTS_VALUE;
275  }
276  parser->flags |= PARSER_FLAG_USE_CODEC_TS;
277 
278  for (;;){
279  uint8_t *data;
280  int size;
281 
282  ret = ff_raw_read_partial_packet(s, &pkt);
283  if (ret < 0){
284  if (ret == AVERROR(EAGAIN))
285  continue;
286  else {
287  av_packet_unref(&pkt);
288  av_assert1(!pkt.size);
289  }
290  }
291  av_parser_parse2(parser, st->internal->avctx,
292  &data, &size, pkt.data, pkt.size,
293  pkt.pts, pkt.dts, *ppos);
294 
295  av_packet_unref(&pkt);
296  if (size) {
297  if (parser->pts != AV_NOPTS_VALUE){
298  // seeking may not have started from beginning of a frame
299  // calculate frame start position from next frame backwards
300  *ppos = parser->next_frame_offset - size;
301  pts = parser->pts;
302  break;
303  }
304  } else if (ret < 0)
305  break;
306  }
307  av_parser_close(parser);
308  return pts;
309 }
310 
311 static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
312  int index;
313  int64_t pos;
314  AVIndexEntry e;
315  FLACDecContext *flac = s->priv_data;
316 
317  if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
318  return -1;
319  }
320 
321  index = av_index_search_timestamp(s->streams[0], timestamp, flags);
322  if(index<0 || index >= s->streams[0]->nb_index_entries)
323  return -1;
324 
325  e = s->streams[0]->index_entries[index];
326  pos = avio_seek(s->pb, e.pos, SEEK_SET);
327  if (pos >= 0) {
328  return 0;
329  }
330  return -1;
331 }
332 
335  .name = "flac",
336  .long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
337  .read_probe = flac_probe,
338  .read_header = flac_read_header,
339  .read_packet = ff_raw_read_partial_packet,
340  .read_seek = flac_seek,
341  .read_timestamp = flac_read_timestamp,
342  .flags = AVFMT_GENERIC_INDEX,
343  .extensions = "flac",
344  .raw_codec_id = AV_CODEC_ID_FLAC,
345  .priv_data_size = sizeof(FLACDecContext),
346  .priv_class = &flac_demuxer_class,
347 };
#define NULL
Definition: coverity.c:32
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
Definition: flacdec.c:259
int size
int raw_packet_size
Definition: flacdec.c:35
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: utils.c:2052
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define AV_RB64
Definition: intreadwrite.h:164
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4948
int64_t next_frame_offset
Definition: avcodec.h:3363
int64_t pos
Definition: avformat.h:805
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
int size
Definition: packet.h:356
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:241
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1105
#define AV_RB24
Definition: intreadwrite.h:64
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1666
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:329
static AVPacket pkt
AVChapter * avpriv_new_chapter(AVFormatContext *s, int id, AVRational time_base, int64_t start, int64_t end, const char *title)
Add a new chapter.
Definition: utils.c:4654
Format I/O context.
Definition: avformat.h:1351
static char buffer[20]
Definition: seek.c:32
uint8_t
enum AVStreamParseType need_parsing
Definition: avformat.h:1094
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4526
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1419
const char data[16]
Definition: mxf.c:91
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:40
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1482
uint8_t * data
Definition: packet.h:355
int ff_vorbis_comment(AVFormatContext *ms, AVDictionary **m, const uint8_t *buf, int size, int parse_picture)
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
static const uint8_t header[24]
Definition: sdr2.c:67
int ff_replaygain_export(AVStream *st, AVDictionary *metadata)
Parse replaygain tags and export them as per-stream side data.
Definition: replaygain.c:91
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition: avformat.h:799
uint64_t channel_layout
Audio only.
Definition: codec_par.h:162
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:625
#define AVINDEX_KEYFRAME
Definition: avformat.h:812
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:269
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1591
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:2169
int found_seektable
Definition: flacdec.c:36
AVInputFormat ff_flac_demuxer
Definition: flacdec.c:334
static const uint16_t mask[17]
Definition: lzw.c:38
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
#define AV_RB16
Definition: intreadwrite.h:53
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:747
#define AVERROR(e)
Definition: error.h:43
int ff_raw_read_partial_packet(AVFormatContext *s, AVPacket *pkt)
Definition: rawdec.c:35
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:188
unsigned int pos
Definition: spdifenc.c:412
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
static const uint8_t offset[127][2]
Definition: vf_spp.c:93
#define FF_RAW_DEMUXER_CLASS(name)
Definition: rawdec.h:55
#define fail()
Definition: checkasm.h:123
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:444
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:443
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
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
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:224
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1667
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
#define s(width, name)
Definition: cbs_vp9.c:257
static av_always_inline unsigned int bytestream_get_buffer(const uint8_t **b, uint8_t *dst, unsigned int size)
Definition: bytestream.h:359
Stream structure.
Definition: avformat.h:876
static int flac_probe(const AVProbeData *p)
Definition: flacdec.c:232
sample_rate
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:34
AVStreamInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1231
AVIOContext * pb
I/O context.
Definition: avformat.h:1393
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:605
long long int64_t
Definition: coverity.c:34
static int flac_read_header(AVFormatContext *s)
Definition: flacdec.c:48
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:70
int nb_index_entries
Definition: avformat.h:1107
Describe the class of an AVClass context structure.
Definition: log.h:67
int index
Definition: gxfenc.c:89
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:463
cl_device_type type
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:145
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:451
This structure contains the data a format has to probe a file.
Definition: avformat.h:441
static int64_t pts
#define flags(name, subs,...)
Definition: cbs_av1.c:576
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:925
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:453
Main libavformat public API header.
static void reset_index_position(int64_t metadata_head_size, AVStream *st)
Definition: flacdec.c:39
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:35
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:215
#define av_free(p)
char * value
Definition: dict.h:87
#define AVFMT_FLAG_FAST_SEEK
Enable fast, but inaccurate seeks for some formats.
Definition: avformat.h:1508
void * priv_data
Format private data.
Definition: avformat.h:1379
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
AVCodecContext * avctx
The codec context used by avformat_find_stream_info, the parser, etc.
Definition: internal.h:169
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: packet.h:354
int ff_flac_parse_picture(AVFormatContext *s, uint8_t *buf, int buf_size, int truncate_workaround)
Definition: flac_picture.c:32
#define av_freep(p)
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:650
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1023
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:356
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:905
#define MKTAG(a, b, c, d)
Definition: common.h:406
#define SEEKPOINT_SIZE
Definition: flacdec.c:31
static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: flacdec.c:311
This structure stores compressed data.
Definition: packet.h:332
static int raw_flac_probe(const AVProbeData *p)
Definition: flacdec.c:216
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:348
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define RETURN_ERROR(code)
Definition: avidec.c:481
#define FLAC_MAX_CHANNELS
Definition: flac.h:35
#define av_unused
Definition: attributes.h:131
#define PARSER_FLAG_USE_CODEC_TS
Definition: avcodec.h:3395