3 * Copyright (c) 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavcodec/flac.h"
24 #include "flac_picture.h"
28 #include "vorbiscomment.h"
29 #include "replaygain.h"
31 #define SEEKPOINT_SIZE 18
33 typedef struct FLACDecContext {
39 static void reset_index_position(int64_t metadata_head_size, AVStream *st)
41 /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
43 for(i=0; i<st->nb_index_entries; i++) {
44 st->index_entries[i].pos += metadata_head_size;
48 static int flac_read_header(AVFormatContext *s)
50 int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
53 FLACDecContext *flac = s->priv_data;
54 AVStream *st = avformat_new_stream(s, NULL);
56 return AVERROR(ENOMEM);
57 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
58 st->codecpar->codec_id = AV_CODEC_ID_FLAC;
59 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
60 /* the parameters will be extracted from the compressed bitstream */
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);
68 /* process metadata blocks */
69 while (!avio_feof(s->pb) && !metadata_last) {
70 if (avio_read(s->pb, header, 4) != 4)
71 return AVERROR(AVERROR_INVALIDDATA);
72 flac_parse_block_header(header, &metadata_last, &metadata_type,
74 switch (metadata_type) {
75 /* allocate and read metadata block for supported types */
76 case FLAC_METADATA_TYPE_STREAMINFO:
77 case FLAC_METADATA_TYPE_CUESHEET:
78 case FLAC_METADATA_TYPE_PICTURE:
79 case FLAC_METADATA_TYPE_VORBIS_COMMENT:
80 case FLAC_METADATA_TYPE_SEEKTABLE:
81 buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
83 return AVERROR(ENOMEM);
85 if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
86 RETURN_ERROR(AVERROR(EIO));
89 /* skip metadata block for unsupported types */
91 ret = avio_skip(s->pb, metadata_size);
96 if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
100 /* STREAMINFO can only occur once */
101 if (found_streaminfo) {
102 RETURN_ERROR(AVERROR_INVALIDDATA);
104 if (metadata_size != FLAC_STREAMINFO_SIZE) {
105 RETURN_ERROR(AVERROR_INVALIDDATA);
107 found_streaminfo = 1;
108 st->codecpar->extradata = buffer;
109 st->codecpar->extradata_size = metadata_size;
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);
117 /* set time base and duration */
118 if (samplerate > 0) {
119 avpriv_set_pts_info(st, 64, 1, samplerate);
121 st->duration = samples;
123 } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
126 const uint8_t *offset;
127 int i, chapters, track, ti;
128 if (metadata_size < 431)
129 RETURN_ERROR(AVERROR_INVALIDDATA);
130 offset = buffer + 395;
131 chapters = bytestream_get_byte(&offset) - 1;
133 RETURN_ERROR(AVERROR_INVALIDDATA);
134 for (i = 0; i < chapters; i++) {
135 if (offset + 36 - buffer > metadata_size)
136 RETURN_ERROR(AVERROR_INVALIDDATA);
137 start = bytestream_get_be64(&offset);
138 track = bytestream_get_byte(&offset);
139 bytestream_get_buffer(&offset, isrc, 12);
142 ti = bytestream_get_byte(&offset);
143 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
145 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
148 } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
149 ret = ff_flac_parse_picture(s, buffer, metadata_size);
152 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
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);
172 /* STREAMINFO must be the first block */
173 if (!found_streaminfo) {
174 RETURN_ERROR(AVERROR_INVALIDDATA);
176 /* process supported blocks other than STREAMINFO */
177 if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
178 AVDictionaryEntry *chmask;
180 ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
182 av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
183 } else if (ret > 0) {
184 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
187 /* parse the channels mask if present */
188 chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
190 uint64_t mask = strtol(chmask->value, NULL, 0);
191 if (!mask || mask & ~0x3ffffULL) {
192 av_log(s, AV_LOG_WARNING,
193 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
195 st->codecpar->channel_layout = mask;
196 av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
204 ret = ff_replaygain_export(st, s->metadata);
208 reset_index_position(avio_tell(s->pb), st);
216 static int raw_flac_probe(const AVProbeData *p)
218 if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
220 if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
222 if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
223 // channel mode invalid
225 if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
227 if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
229 return AVPROBE_SCORE_EXTENSION / 4 + 1;
232 static int flac_probe(const AVProbeData *p)
234 if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
235 return raw_flac_probe(p);
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;
245 if (memcmp(p->buf, "fLaC", 4))
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;
253 return AVPROBE_SCORE_EXTENSION;
259 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
260 int64_t *ppos, int64_t pos_limit)
263 AVStream *st = s->streams[stream_index];
264 AVCodecParserContext *parser;
266 int64_t pts = AV_NOPTS_VALUE;
268 if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
269 return AV_NOPTS_VALUE;
271 av_init_packet(&pkt);
272 parser = av_parser_init(st->codecpar->codec_id);
274 return AV_NOPTS_VALUE;
276 parser->flags |= PARSER_FLAG_USE_CODEC_TS;
282 ret = ff_raw_read_partial_packet(s, &pkt);
284 if (ret == AVERROR(EAGAIN))
287 av_packet_unref(&pkt);
288 av_assert1(!pkt.size);
291 av_parser_parse2(parser, st->internal->avctx,
292 &data, &size, pkt.data, pkt.size,
293 pkt.pts, pkt.dts, *ppos);
295 av_packet_unref(&pkt);
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;
307 av_parser_close(parser);
311 static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
315 FLACDecContext *flac = s->priv_data;
317 if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
321 index = av_index_search_timestamp(s->streams[0], timestamp, flags);
322 if(index<0 || index >= s->streams[0]->nb_index_entries)
325 e = s->streams[0]->index_entries[index];
326 pos = avio_seek(s->pb, e.pos, SEEK_SET);
333 FF_RAW_DEMUXER_CLASS(flac)
334 AVInputFormat ff_flac_demuxer = {
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,