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 
32 {
33  int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
34  uint8_t header[4];
37  if (!st)
38  return AVERROR(ENOMEM);
42  /* the parameters will be extracted from the compressed bitstream */
43 
44  /* if fLaC marker is not found, assume there is no header */
45  if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
46  avio_seek(s->pb, -4, SEEK_CUR);
47  return 0;
48  }
49 
50  /* process metadata blocks */
51  while (!avio_feof(s->pb) && !metadata_last) {
52  avio_read(s->pb, header, 4);
53  flac_parse_block_header(header, &metadata_last, &metadata_type,
54  &metadata_size);
55  switch (metadata_type) {
56  /* allocate and read metadata block for supported types */
61  buffer = av_mallocz(metadata_size + FF_INPUT_BUFFER_PADDING_SIZE);
62  if (!buffer) {
63  return AVERROR(ENOMEM);
64  }
65  if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
66  RETURN_ERROR(AVERROR(EIO));
67  }
68  break;
69  /* skip metadata block for unsupported types */
70  default:
71  ret = avio_skip(s->pb, metadata_size);
72  if (ret < 0)
73  return ret;
74  }
75 
76  if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
77  uint32_t samplerate;
78  uint64_t samples;
79 
80  /* STREAMINFO can only occur once */
81  if (found_streaminfo) {
83  }
84  if (metadata_size != FLAC_STREAMINFO_SIZE) {
86  }
87  found_streaminfo = 1;
88  st->codec->extradata = buffer;
89  st->codec->extradata_size = metadata_size;
90  buffer = NULL;
91 
92  /* get sample rate and sample count from STREAMINFO header;
93  * other parameters will be extracted by the parser */
94  samplerate = AV_RB24(st->codec->extradata + 10) >> 4;
95  samples = (AV_RB64(st->codec->extradata + 13) >> 24) & ((1ULL << 36) - 1);
96 
97  /* set time base and duration */
98  if (samplerate > 0) {
99  avpriv_set_pts_info(st, 64, 1, samplerate);
100  if (samples > 0)
101  st->duration = samples;
102  }
103  } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
104  uint8_t isrc[13];
105  uint64_t start;
106  const uint8_t *offset;
107  int i, chapters, track, ti;
108  if (metadata_size < 431)
110  offset = buffer + 395;
111  chapters = bytestream_get_byte(&offset) - 1;
112  if (chapters <= 0)
114  for (i = 0; i < chapters; i++) {
115  if (offset + 36 - buffer > metadata_size)
117  start = bytestream_get_be64(&offset);
118  track = bytestream_get_byte(&offset);
119  bytestream_get_buffer(&offset, isrc, 12);
120  isrc[12] = 0;
121  offset += 14;
122  ti = bytestream_get_byte(&offset);
123  if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
124  offset += ti * 12;
125  avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
126  }
127  av_freep(&buffer);
128  } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
129  ret = ff_flac_parse_picture(s, buffer, metadata_size);
130  av_freep(&buffer);
131  if (ret < 0) {
132  av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
133  return ret;
134  }
135  } else {
136  /* STREAMINFO must be the first block */
137  if (!found_streaminfo) {
139  }
140  /* process supported blocks other than STREAMINFO */
141  if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
142  AVDictionaryEntry *chmask;
143 
144  ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
145  if (ret < 0) {
146  av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
147  } else if (ret > 0) {
149  }
150 
151  /* parse the channels mask if present */
152  chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
153  if (chmask) {
154  uint64_t mask = strtol(chmask->value, NULL, 0);
155  if (!mask || mask & ~0x3ffffULL) {
157  "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
158  } else {
159  st->codec->channel_layout = mask;
160  av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
161  }
162  }
163  }
164  av_freep(&buffer);
165  }
166  }
167 
168  ret = ff_replaygain_export(st, s->metadata);
169  if (ret < 0)
170  return ret;
171 
172  return 0;
173 
174 fail:
175  av_free(buffer);
176  return ret;
177 }
178 
180 {
181  if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
182  return 0;
183  if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
184  return 0;
185  if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
186  // channel mode invalid
187  return 0;
188  if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
189  return 0;
190  if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
191  return 0;
192  return AVPROBE_SCORE_EXTENSION / 4 + 1;
193 }
194 
195 static int flac_probe(AVProbeData *p)
196 {
197  if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
198  return raw_flac_probe(p);
199  if (p->buf_size < 4 || memcmp(p->buf, "fLaC", 4))
200  return 0;
202 }
203 
204 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
205  int64_t *ppos, int64_t pos_limit)
206 {
207  AVPacket pkt, out_pkt;
208  AVStream *st = s->streams[stream_index];
209  AVCodecParserContext *parser;
210  int ret;
211  int64_t pts = AV_NOPTS_VALUE;
212 
213  if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
214  return AV_NOPTS_VALUE;
215 
216  av_init_packet(&pkt);
217  parser = av_parser_init(st->codec->codec_id);
218  if (!parser){
219  return AV_NOPTS_VALUE;
220  }
221  parser->flags |= PARSER_FLAG_USE_CODEC_TS;
222 
223  for (;;){
224  ret = ff_raw_read_partial_packet(s, &pkt);
225  if (ret < 0){
226  if (ret == AVERROR(EAGAIN))
227  continue;
228  else
229  break;
230  }
231  av_init_packet(&out_pkt);
232  ret = av_parser_parse2(parser, st->codec,
233  &out_pkt.data, &out_pkt.size, pkt.data, pkt.size,
234  pkt.pts, pkt.dts, *ppos);
235 
236  av_free_packet(&pkt);
237  if (out_pkt.size){
238  int size = out_pkt.size;
239  if (parser->pts != AV_NOPTS_VALUE){
240  // seeking may not have started from beginning of a frame
241  // calculate frame start position from next frame backwards
242  *ppos = parser->next_frame_offset - size;
243  pts = parser->pts;
244  break;
245  }
246  }
247  }
248  av_parser_close(parser);
249  return pts;
250 }
251 
253  .name = "flac",
254  .long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
255  .read_probe = flac_probe,
256  .read_header = flac_read_header,
257  .read_packet = ff_raw_read_partial_packet,
258  .read_timestamp = flac_read_timestamp,
259  .flags = AVFMT_GENERIC_INDEX,
260  .extensions = "flac",
261  .raw_codec_id = AV_CODEC_ID_FLAC,
262 };
#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:204
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:280
#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:4006
int64_t next_frame_offset
Definition: avcodec.h:4253
int size
Definition: avcodec.h:1163
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:203
int event_flags
Flags for the user to detect events happening on the file.
Definition: avformat.h:1557
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:276
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:85
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:3768
Format I/O context.
Definition: avformat.h:1272
uint8_t
enum AVStreamParseType need_parsing
Definition: avformat.h:1035
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1355
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:3672
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1340
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
uint8_t * data
Definition: avcodec.h:1162
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 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:778
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:537
#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:1482
AVInputFormat ff_flac_demuxer
Definition: flacdec.c:252
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:658
#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:175
#define PARSER_FLAG_USE_CODEC_TS
Definition: avcodec.h:4285
static int flac_probe(AVProbeData *p)
Definition: flacdec.c:195
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2046
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:861
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:451
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:450
#define FF_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:630
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:131
ret
Definition: avfilter.c:974
void av_parser_close(AVCodecParserContext *s)
Definition: parser.c:221
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
The call resulted in updated metadata.
Definition: avformat.h:1558
#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:357
Stream structure.
Definition: avformat.h:842
AVCodecParserContext * av_parser_init(int codec_id)
Definition: parser.c:50
enum AVMediaType codec_type
Definition: avcodec.h:1249
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:85
enum AVCodecID codec_id
Definition: avcodec.h:1258
AVIOContext * pb
I/O context.
Definition: avformat.h:1314
int extradata_size
Definition: avcodec.h:1356
static int flac_read_header(AVFormatContext *s)
Definition: flacdec.c:31
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
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:473
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:151
#define RETURN_ERROR(code)
Definition: flac_picture.h:27
#define AVPROBE_SCORE_EXTENSION
score for file extension
Definition: avformat.h:458
This structure contains the data a format has to probe a file.
Definition: avformat.h:448
static int64_t pts
Global timestamp for the audio frames.
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:901
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:85
Main libavformat public API header.
static int raw_flac_probe(AVProbeData *p)
Definition: flacdec.c:179
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:49
#define av_free(p)
char * value
Definition: dict.h:88
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1161
#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:628
int avio_feof(AVIOContext *s)
feof() equivalent for AVIOContext.
Definition: aviobuf.c:300
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:884
#define MKTAG(a, b, c, d)
Definition: common.h:315
This structure stores compressed data.
Definition: avcodec.h:1139
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:250
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1155
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:241
GLuint buffer
Definition: opengl_enc.c:102
#define FLAC_MAX_CHANNELS
Definition: flac.h:35
#define av_unused
Definition: attributes.h:118