FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
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 {
36 
37 static void reset_index_position(int64_t metadata_head_size, AVStream *st)
38 {
39  /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
40  int i;
41  for(i=0; i<st->nb_index_entries; i++) {
42  st->index_entries[i].pos += metadata_head_size;
43  }
44 }
45 
47 {
48  int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
49  uint8_t header[4];
51  FLACDecContext *flac = s->priv_data;
53  if (!st)
54  return AVERROR(ENOMEM);
58  /* the parameters will be extracted from the compressed bitstream */
59 
60  /* if fLaC marker is not found, assume there is no header */
61  if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
62  avio_seek(s->pb, -4, SEEK_CUR);
63  return 0;
64  }
65 
66  /* process metadata blocks */
67  while (!avio_feof(s->pb) && !metadata_last) {
68  avio_read(s->pb, header, 4);
69  flac_parse_block_header(header, &metadata_last, &metadata_type,
70  &metadata_size);
71  switch (metadata_type) {
72  /* allocate and read metadata block for supported types */
78  buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
79  if (!buffer) {
80  return AVERROR(ENOMEM);
81  }
82  if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
83  RETURN_ERROR(AVERROR(EIO));
84  }
85  break;
86  /* skip metadata block for unsupported types */
87  default:
88  ret = avio_skip(s->pb, metadata_size);
89  if (ret < 0)
90  return ret;
91  }
92 
93  if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
94  uint32_t samplerate;
95  uint64_t samples;
96 
97  /* STREAMINFO can only occur once */
98  if (found_streaminfo) {
100  }
101  if (metadata_size != FLAC_STREAMINFO_SIZE) {
103  }
104  found_streaminfo = 1;
105  st->codecpar->extradata = buffer;
106  st->codecpar->extradata_size = metadata_size;
107  buffer = NULL;
108 
109  /* get sample rate and sample count from STREAMINFO header;
110  * other parameters will be extracted by the parser */
111  samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
112  samples = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
113 
114  /* set time base and duration */
115  if (samplerate > 0) {
116  avpriv_set_pts_info(st, 64, 1, samplerate);
117  if (samples > 0)
118  st->duration = samples;
119  }
120  } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
121  uint8_t isrc[13];
122  uint64_t start;
123  const uint8_t *offset;
124  int i, chapters, track, ti;
125  if (metadata_size < 431)
127  offset = buffer + 395;
128  chapters = bytestream_get_byte(&offset) - 1;
129  if (chapters <= 0)
131  for (i = 0; i < chapters; i++) {
132  if (offset + 36 - buffer > metadata_size)
134  start = bytestream_get_be64(&offset);
135  track = bytestream_get_byte(&offset);
136  bytestream_get_buffer(&offset, isrc, 12);
137  isrc[12] = 0;
138  offset += 14;
139  ti = bytestream_get_byte(&offset);
140  if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
141  offset += ti * 12;
142  avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
143  }
144  av_freep(&buffer);
145  } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
146  ret = ff_flac_parse_picture(s, buffer, metadata_size);
147  av_freep(&buffer);
148  if (ret < 0) {
149  av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
150  return ret;
151  }
152  } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
153  const uint8_t *seekpoint = buffer;
154  int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
155  flac->found_seektable = 1;
156  if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
157  for(i=0; i<seek_point_count; i++) {
158  int64_t timestamp = bytestream_get_be64(&seekpoint);
159  int64_t pos = bytestream_get_be64(&seekpoint);
160  /* skip number of samples */
161  bytestream_get_be16(&seekpoint);
162  av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
163  }
164  }
165  av_freep(&buffer);
166  }
167  else {
168 
169  /* STREAMINFO must be the first block */
170  if (!found_streaminfo) {
172  }
173  /* process supported blocks other than STREAMINFO */
174  if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
175  AVDictionaryEntry *chmask;
176 
177  ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
178  if (ret < 0) {
179  av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
180  } else if (ret > 0) {
182  }
183 
184  /* parse the channels mask if present */
185  chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
186  if (chmask) {
187  uint64_t mask = strtol(chmask->value, NULL, 0);
188  if (!mask || mask & ~0x3ffffULL) {
190  "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
191  } else {
193  av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
194  }
195  }
196  }
197  av_freep(&buffer);
198  }
199  }
200 
201  ret = ff_replaygain_export(st, s->metadata);
202  if (ret < 0)
203  return ret;
204 
206  return 0;
207 
208 fail:
209  av_free(buffer);
210  return ret;
211 }
212 
214 {
215  if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
216  return 0;
217  if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
218  return 0;
219  if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
220  // channel mode invalid
221  return 0;
222  if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
223  return 0;
224  if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
225  return 0;
226  return AVPROBE_SCORE_EXTENSION / 4 + 1;
227 }
228 
229 static int flac_probe(AVProbeData *p)
230 {
231  if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
232  return raw_flac_probe(p);
233  if (p->buf_size < 4 || memcmp(p->buf, "fLaC", 4))
234  return 0;
236 }
237 
238 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
239  int64_t *ppos, int64_t pos_limit)
240 {
241  AVPacket pkt, out_pkt;
242  AVStream *st = s->streams[stream_index];
243  AVCodecParserContext *parser;
244  int ret;
245  int64_t pts = AV_NOPTS_VALUE;
246 
247  if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
248  return AV_NOPTS_VALUE;
249 
250  av_init_packet(&pkt);
251  parser = av_parser_init(st->codecpar->codec_id);
252  if (!parser){
253  return AV_NOPTS_VALUE;
254  }
255  parser->flags |= PARSER_FLAG_USE_CODEC_TS;
256 
257  for (;;){
258  ret = ff_raw_read_partial_packet(s, &pkt);
259  if (ret < 0){
260  if (ret == AVERROR(EAGAIN))
261  continue;
262  else {
263  av_packet_unref(&pkt);
264  av_assert1(!pkt.size);
265  }
266  }
267  av_init_packet(&out_pkt);
268  av_parser_parse2(parser, st->internal->avctx,
269  &out_pkt.data, &out_pkt.size, pkt.data, pkt.size,
270  pkt.pts, pkt.dts, *ppos);
271 
272  av_packet_unref(&pkt);
273  if (out_pkt.size){
274  int size = out_pkt.size;
275  if (parser->pts != AV_NOPTS_VALUE){
276  // seeking may not have started from beginning of a frame
277  // calculate frame start position from next frame backwards
278  *ppos = parser->next_frame_offset - size;
279  pts = parser->pts;
280  break;
281  }
282  } else if (ret < 0)
283  break;
284  }
285  av_parser_close(parser);
286  return pts;
287 }
288 
289 static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
290  int index;
291  int64_t pos;
292  AVIndexEntry e;
293  FLACDecContext *flac = s->priv_data;
294 
295  if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
296  return -1;
297  }
298 
299  index = av_index_search_timestamp(s->streams[0], timestamp, flags);
300  if(index<0 || index >= s->streams[0]->nb_index_entries)
301  return -1;
302 
303  e = s->streams[0]->index_entries[index];
304  pos = avio_seek(s->pb, e.pos, SEEK_SET);
305  if (pos >= 0) {
306  return 0;
307  }
308  return -1;
309 }
310 
312  .name = "flac",
313  .long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
314  .read_probe = flac_probe,
315  .read_header = flac_read_header,
316  .read_packet = ff_raw_read_partial_packet,
317  .read_seek = flac_seek,
318  .read_timestamp = flac_read_timestamp,
319  .flags = AVFMT_GENERIC_INDEX,
320  .extensions = "flac",
321  .raw_codec_id = AV_CODEC_ID_FLAC,
322  .priv_data_size = sizeof(FLACDecContext),
323 };
#define NULL
Definition: coverity.c:32
const char * s
Definition: avisynth_c.h:631
#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:238
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:1909
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
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:4493
int64_t next_frame_offset
Definition: avcodec.h:4946
int64_t pos
Definition: avformat.h:816
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3939
int size
Definition: avcodec.h:1589
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:230
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:1074
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1614
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:304
static AVPacket pkt
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_WB24 unsigned int_TMPL AV_RB16
Definition: bytestream.h:87
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:4255
Format I/O context.
Definition: avformat.h:1325
uint8_t
enum AVStreamParseType need_parsing
Definition: avformat.h:1063
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4131
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1393
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:39
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1436
uint8_t * data
Definition: avcodec.h:1588
int ff_vorbis_comment(AVFormatContext *ms, AVDictionary **m, const uint8_t *buf, int size, int parse_picture)
ptrdiff_t size
Definition: opengl_enc.c:101
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:511
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:810
uint64_t channel_layout
Audio only.
Definition: avcodec.h:4041
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:598
#define AVINDEX_KEYFRAME
Definition: avformat.h:823
#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:1539
int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags)
Get the index for a specific timestamp.
Definition: utils.c:2008
int found_seektable
Definition: flacdec.c:34
AVInputFormat ff_flac_demuxer
Definition: flacdec.c:311
static const uint16_t mask[17]
Definition: lzw.c:38
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:720
#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:176
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3935
static int flac_probe(AVProbeData *p)
Definition: flacdec.c:229
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
#define fail()
Definition: checkasm.h:82
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3957
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:462
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:461
#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:136
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:235
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1615
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
int ff_flac_parse_picture(AVFormatContext *s, uint8_t *buf, int buf_size)
Definition: flac_picture.c:28
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
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:51
AVStreamInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1217
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_WB64 unsigned int_TMPL AV_WB32 unsigned int_TMPL AV_RB24
Definition: bytestream.h:87
AVIOContext * pb
I/O context.
Definition: avformat.h:1367
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:563
static int flac_read_header(AVFormatContext *s)
Definition: flacdec.c:46
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:69
int nb_index_entries
Definition: avformat.h:1076
int index
Definition: gxfenc.c:89
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:485
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:143
#define RETURN_ERROR(code)
Definition: flac_picture.h:27
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:469
This structure contains the data a format has to probe a file.
Definition: avformat.h:459
static int64_t pts
Global timestamp for the audio frames.
static int flags
Definition: cpu.c:47
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:930
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_WL32 unsigned int_TMPL AV_WL24 unsigned int_TMPL AV_WL16 uint64_t_TMPL AV_RB64
Definition: bytestream.h:87
Main libavformat public API header.
static int raw_flac_probe(AVProbeData *p)
Definition: flacdec.c:213
static void reset_index_position(int64_t metadata_head_size, AVStream *st)
Definition: flacdec.c:37
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:33
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:731
#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:1458
void * priv_data
Format private data.
Definition: avformat.h:1353
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3953
AVCodecContext * avctx
The codec context used by avformat_find_stream_info, the parser, etc.
Definition: internal.h:153
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1587
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:553
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:660
AVCodecParameters * codecpar
Definition: avformat.h:1228
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:328
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:913
#define MKTAG(a, b, c, d)
Definition: common.h:342
#define SEEKPOINT_SIZE
Definition: flacdec.c:31
static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: flacdec.c:289
This structure stores compressed data.
Definition: avcodec.h:1565
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:252
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1581
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:240
GLuint buffer
Definition: opengl_enc.c:102
#define FLAC_MAX_CHANNELS
Definition: flac.h:35
#define av_unused
Definition: attributes.h:126
#define PARSER_FLAG_USE_CODEC_TS
Definition: avcodec.h:4978