• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "libavutil/channel_layout.h"
23 #include "libavcodec/flac.h"
24 #include "avformat.h"
25 #include "demux.h"
26 #include "flac_picture.h"
27 #include "internal.h"
28 #include "rawdec.h"
29 #include "oggdec.h"
30 #include "replaygain.h"
31 
32 #define SEEKPOINT_SIZE 18
33 
34 typedef struct FLACDecContext {
35     FFRawDemuxerContext rawctx;
36     int found_seektable;
37 } FLACDecContext;
38 
reset_index_position(int64_t metadata_head_size,AVStream * st)39 static void reset_index_position(int64_t metadata_head_size, AVStream *st)
40 {
41     FFStream *const sti = ffstream(st);
42     /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
43     for (int i = 0; i < sti->nb_index_entries; i++)
44         sti->index_entries[i].pos += metadata_head_size;
45 }
46 
flac_read_header(AVFormatContext * s)47 static int flac_read_header(AVFormatContext *s)
48 {
49     int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
50     uint8_t header[4];
51     uint8_t *buffer=NULL;
52     FLACDecContext *flac = s->priv_data;
53     AVStream *st = avformat_new_stream(s, NULL);
54     if (!st)
55         return AVERROR(ENOMEM);
56     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
57     st->codecpar->codec_id = AV_CODEC_ID_FLAC;
58     ffstream(st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
59     /* the parameters will be extracted from the compressed bitstream */
60 
61     /* if fLaC marker is not found, assume there is no header */
62     if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
63         avio_seek(s->pb, -4, SEEK_CUR);
64         return 0;
65     }
66 
67     /* process metadata blocks */
68     while (!avio_feof(s->pb) && !metadata_last) {
69         if (avio_read(s->pb, header, 4) != 4)
70             return AVERROR(AVERROR_INVALIDDATA);
71         flac_parse_block_header(header, &metadata_last, &metadata_type,
72                                    &metadata_size);
73         switch (metadata_type) {
74         /* allocate and read metadata block for supported types */
75         case FLAC_METADATA_TYPE_STREAMINFO:
76         case FLAC_METADATA_TYPE_CUESHEET:
77         case FLAC_METADATA_TYPE_PICTURE:
78         case FLAC_METADATA_TYPE_VORBIS_COMMENT:
79         case FLAC_METADATA_TYPE_SEEKTABLE:
80             buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
81             if (!buffer) {
82                 return AVERROR(ENOMEM);
83             }
84             if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
85                 RETURN_ERROR(AVERROR(EIO));
86             }
87             break;
88         /* skip metadata block for unsupported types */
89         default:
90             ret = avio_skip(s->pb, metadata_size);
91             if (ret < 0)
92                 return ret;
93         }
94 
95         if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
96             uint32_t samplerate;
97             uint64_t samples;
98 
99             /* STREAMINFO can only occur once */
100             if (found_streaminfo) {
101                 RETURN_ERROR(AVERROR_INVALIDDATA);
102             }
103             if (metadata_size != FLAC_STREAMINFO_SIZE) {
104                 RETURN_ERROR(AVERROR_INVALIDDATA);
105             }
106             found_streaminfo = 1;
107             st->codecpar->extradata      = buffer;
108             st->codecpar->extradata_size = metadata_size;
109             buffer = NULL;
110 
111             /* get sample rate and sample count from STREAMINFO header;
112              * other parameters will be extracted by the parser */
113             samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
114             samples    = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
115 
116             /* set time base and duration */
117             if (samplerate > 0) {
118                 avpriv_set_pts_info(st, 64, 1, samplerate);
119                 if (samples > 0)
120                     st->duration = samples;
121             }
122         } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
123             uint8_t isrc[13];
124             uint64_t start;
125             const uint8_t *offset;
126             int i, chapters, track, ti;
127             if (metadata_size < 431)
128                 RETURN_ERROR(AVERROR_INVALIDDATA);
129             offset = buffer + 395;
130             chapters = bytestream_get_byte(&offset) - 1;
131             if (chapters <= 0)
132                 RETURN_ERROR(AVERROR_INVALIDDATA);
133             for (i = 0; i < chapters; i++) {
134                 if (offset + 36 - buffer > metadata_size)
135                     RETURN_ERROR(AVERROR_INVALIDDATA);
136                 start = bytestream_get_be64(&offset);
137                 track = bytestream_get_byte(&offset);
138                 bytestream_get_buffer(&offset, isrc, 12);
139                 isrc[12] = 0;
140                 offset += 14;
141                 ti = bytestream_get_byte(&offset);
142                 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
143                 offset += ti * 12;
144                 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
145             }
146             av_freep(&buffer);
147         } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
148             ret = ff_flac_parse_picture(s, &buffer, metadata_size, 1);
149             av_freep(&buffer);
150             if (ret < 0) {
151                 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
152                 return ret;
153             }
154         } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
155             const uint8_t *seekpoint = buffer;
156             int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
157             flac->found_seektable = 1;
158             if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
159                 for(i=0; i<seek_point_count; i++) {
160                     int64_t timestamp = bytestream_get_be64(&seekpoint);
161                     int64_t pos = bytestream_get_be64(&seekpoint);
162                     /* skip number of samples */
163                     bytestream_get_be16(&seekpoint);
164                     av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
165                 }
166             }
167             av_freep(&buffer);
168         }
169         else {
170 
171             /* STREAMINFO must be the first block */
172             if (!found_streaminfo) {
173                 RETURN_ERROR(AVERROR_INVALIDDATA);
174             }
175             /* process supported blocks other than STREAMINFO */
176             if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
177                 AVDictionaryEntry *chmask;
178 
179                 ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
180                 if (ret < 0) {
181                     av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
182                 } else if (ret > 0) {
183                     s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
184                 }
185 
186                 /* parse the channels mask if present */
187                 chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
188                 if (chmask) {
189                     uint64_t mask = strtol(chmask->value, NULL, 0);
190                     if (!mask || mask & ~0x3ffffULL) {
191                         av_log(s, AV_LOG_WARNING,
192                                "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
193                     } else {
194                         av_channel_layout_from_mask(&st->codecpar->ch_layout, mask);
195                         av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
196                     }
197                 }
198             }
199             av_freep(&buffer);
200         }
201     }
202 
203     ret = ff_replaygain_export(st, s->metadata);
204     if (ret < 0)
205         return ret;
206 
207     reset_index_position(avio_tell(s->pb), st);
208     return 0;
209 
210 fail:
211     av_free(buffer);
212     return ret;
213 }
214 
raw_flac_probe(const AVProbeData * p)215 static int raw_flac_probe(const AVProbeData *p)
216 {
217     if ((p->buf[2] & 0xF0) == 0)    // blocksize code invalid
218         return 0;
219     if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
220         return 0;
221     if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
222         // channel mode invalid
223         return 0;
224     if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
225         return 0;
226     if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
227         return 0;
228     return AVPROBE_SCORE_EXTENSION / 4 + 1;
229 }
230 
flac_probe(const AVProbeData * p)231 static int flac_probe(const AVProbeData *p)
232 {
233     if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
234         return raw_flac_probe(p);
235 
236     /* file header + metadata header + checked bytes of streaminfo */
237     if (p->buf_size >= 4 + 4 + 13) {
238         int type           = p->buf[4] & 0x7f;
239         int size           = AV_RB24(p->buf + 5);
240         int min_block_size = AV_RB16(p->buf + 8);
241         int max_block_size = AV_RB16(p->buf + 10);
242         int sample_rate    = AV_RB24(p->buf + 18) >> 4;
243 
244         if (memcmp(p->buf, "fLaC", 4))
245             return 0;
246         if (type == FLAC_METADATA_TYPE_STREAMINFO &&
247             size == FLAC_STREAMINFO_SIZE          &&
248             min_block_size >= 16                  &&
249             max_block_size >= min_block_size      &&
250             sample_rate && sample_rate <= 655350)
251             return AVPROBE_SCORE_MAX;
252         return AVPROBE_SCORE_EXTENSION;
253     }
254 
255     return 0;
256 }
257 
flac_read_timestamp(AVFormatContext * s,int stream_index,int64_t * ppos,int64_t pos_limit)258 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
259                                              int64_t *ppos, int64_t pos_limit)
260 {
261     FFFormatContext *const si = ffformatcontext(s);
262     AVPacket *const pkt = si->parse_pkt;
263     AVStream *st = s->streams[stream_index];
264     AVCodecParserContext *parser;
265     int ret;
266     int64_t pts = AV_NOPTS_VALUE;
267 
268     if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
269         return AV_NOPTS_VALUE;
270 
271     parser = av_parser_init(st->codecpar->codec_id);
272     if (!parser){
273         return AV_NOPTS_VALUE;
274     }
275     parser->flags |= PARSER_FLAG_USE_CODEC_TS;
276 
277     for (;;){
278         uint8_t *data;
279         int size;
280 
281         ret = ff_raw_read_partial_packet(s, pkt);
282         if (ret < 0){
283             if (ret == AVERROR(EAGAIN))
284                 continue;
285             else {
286                 av_packet_unref(pkt);
287                 av_assert1(!pkt->size);
288             }
289         }
290         av_parser_parse2(parser, ffstream(st)->avctx,
291                          &data, &size, pkt->data, pkt->size,
292                          pkt->pts, pkt->dts, *ppos);
293 
294         av_packet_unref(pkt);
295         if (size) {
296             if (parser->pts != AV_NOPTS_VALUE){
297                 // seeking may not have started from beginning of a frame
298                 // calculate frame start position from next frame backwards
299                 *ppos = parser->next_frame_offset - size;
300                 pts = parser->pts;
301                 break;
302             }
303         } else if (ret < 0)
304             break;
305     }
306     av_parser_close(parser);
307     return pts;
308 }
309 
flac_seek(AVFormatContext * s,int stream_index,int64_t timestamp,int flags)310 static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
311     AVStream *const st  = s->streams[0];
312     FFStream *const sti = ffstream(st);
313     int index;
314     int64_t pos;
315     AVIndexEntry e;
316     FLACDecContext *flac = s->priv_data;
317 
318     if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
319         return -1;
320     }
321 
322     index = av_index_search_timestamp(st, timestamp, flags);
323     if (index < 0 || index >= sti->nb_index_entries)
324         return -1;
325 
326     e   = sti->index_entries[index];
327     pos = avio_seek(s->pb, e.pos, SEEK_SET);
328     if (pos >= 0) {
329         return 0;
330     }
331     return -1;
332 }
333 
334 const AVInputFormat ff_flac_demuxer = {
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     = &ff_raw_demuxer_class,
347 };
348