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 {
37 static void reset_index_position(int64_t metadata_head_size, AVStream *st)
39 /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
41 for(i=0; i<st->nb_index_entries; i++) {
42 st->index_entries[i].pos += metadata_head_size;
46 static int flac_read_header(AVFormatContext *s)
48 int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
51 FLACDecContext *flac = s->priv_data;
52 AVStream *st = avformat_new_stream(s, NULL);
54 return AVERROR(ENOMEM);
55 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
56 st->codecpar->codec_id = AV_CODEC_ID_FLAC;
57 st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
58 /* the parameters will be extracted from the compressed bitstream */
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);
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,
71 switch (metadata_type) {
72 /* allocate and read metadata block for supported types */
73 case FLAC_METADATA_TYPE_STREAMINFO:
74 case FLAC_METADATA_TYPE_CUESHEET:
75 case FLAC_METADATA_TYPE_PICTURE:
76 case FLAC_METADATA_TYPE_VORBIS_COMMENT:
77 case FLAC_METADATA_TYPE_SEEKTABLE:
78 buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
80 return AVERROR(ENOMEM);
82 if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
83 RETURN_ERROR(AVERROR(EIO));
86 /* skip metadata block for unsupported types */
88 ret = avio_skip(s->pb, metadata_size);
93 if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
97 /* STREAMINFO can only occur once */
98 if (found_streaminfo) {
99 RETURN_ERROR(AVERROR_INVALIDDATA);
101 if (metadata_size != FLAC_STREAMINFO_SIZE) {
102 RETURN_ERROR(AVERROR_INVALIDDATA);
104 found_streaminfo = 1;
105 st->codecpar->extradata = buffer;
106 st->codecpar->extradata_size = metadata_size;
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);
114 /* set time base and duration */
115 if (samplerate > 0) {
116 avpriv_set_pts_info(st, 64, 1, samplerate);
118 st->duration = samples;
120 } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
123 const uint8_t *offset;
124 int i, chapters, track, ti;
125 if (metadata_size < 431)
126 RETURN_ERROR(AVERROR_INVALIDDATA);
127 offset = buffer + 395;
128 chapters = bytestream_get_byte(&offset) - 1;
130 RETURN_ERROR(AVERROR_INVALIDDATA);
131 for (i = 0; i < chapters; i++) {
132 if (offset + 36 - buffer > metadata_size)
133 RETURN_ERROR(AVERROR_INVALIDDATA);
134 start = bytestream_get_be64(&offset);
135 track = bytestream_get_byte(&offset);
136 bytestream_get_buffer(&offset, isrc, 12);
139 ti = bytestream_get_byte(&offset);
140 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
142 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
145 } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
146 ret = ff_flac_parse_picture(s, buffer, metadata_size);
149 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
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);
169 /* STREAMINFO must be the first block */
170 if (!found_streaminfo) {
171 RETURN_ERROR(AVERROR_INVALIDDATA);
173 /* process supported blocks other than STREAMINFO */
174 if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
175 AVDictionaryEntry *chmask;
177 ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
179 av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
180 } else if (ret > 0) {
181 s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
184 /* parse the channels mask if present */
185 chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
187 uint64_t mask = strtol(chmask->value, NULL, 0);
188 if (!mask || mask & ~0x3ffffULL) {
189 av_log(s, AV_LOG_WARNING,
190 "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
192 st->codecpar->channel_layout = mask;
193 av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
201 ret = ff_replaygain_export(st, s->metadata);
205 reset_index_position(avio_tell(s->pb), st);
213 static int raw_flac_probe(AVProbeData *p)
215 if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
217 if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
219 if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
220 // channel mode invalid
222 if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
224 if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
226 return AVPROBE_SCORE_EXTENSION / 4 + 1;
229 static int flac_probe(AVProbeData *p)
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))
235 return AVPROBE_SCORE_EXTENSION;
238 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
239 int64_t *ppos, int64_t pos_limit)
241 AVPacket pkt, out_pkt;
242 AVStream *st = s->streams[stream_index];
243 AVCodecParserContext *parser;
245 int64_t pts = AV_NOPTS_VALUE;
247 if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
248 return AV_NOPTS_VALUE;
250 av_init_packet(&pkt);
251 parser = av_parser_init(st->codecpar->codec_id);
253 return AV_NOPTS_VALUE;
255 parser->flags |= PARSER_FLAG_USE_CODEC_TS;
258 ret = ff_raw_read_partial_packet(s, &pkt);
260 if (ret == AVERROR(EAGAIN))
263 av_packet_unref(&pkt);
264 av_assert1(!pkt.size);
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);
272 av_packet_unref(&pkt);
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;
285 av_parser_close(parser);
289 static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
293 FLACDecContext *flac = s->priv_data;
295 if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
299 index = av_index_search_timestamp(s->streams[0], timestamp, flags);
300 if(index<0 || index >= s->streams[0]->nb_index_entries)
303 e = s->streams[0]->index_entries[index];
304 pos = avio_seek(s->pb, e.pos, SEEK_SET);
311 AVInputFormat ff_flac_demuxer = {
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),