Merge pull request #4539 from Matricom/amcodec
[vuplus_xbmc] / lib / ffmpeg / libavformat / flacdec.c
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 "id3v2.h"
25 #include "internal.h"
26 #include "rawdec.h"
27 #include "oggdec.h"
28 #include "vorbiscomment.h"
29 #include "libavcodec/bytestream.h"
30
31 #define RETURN_ERROR(code) do { ret = (code); goto fail; } while (0)
32
33 static int parse_picture(AVFormatContext *s, uint8_t *buf, int buf_size)
34 {
35     const CodecMime *mime = ff_id3v2_mime_tags;
36     enum  AVCodecID      id = AV_CODEC_ID_NONE;
37     uint8_t mimetype[64], *desc = NULL, *data = NULL;
38     AVIOContext *pb = NULL;
39     AVStream *st;
40     int type, width, height;
41     int len, ret = 0;
42
43     pb = avio_alloc_context(buf, buf_size, 0, NULL, NULL, NULL, NULL);
44     if (!pb)
45         return AVERROR(ENOMEM);
46
47     /* read the picture type */
48     type      = avio_rb32(pb);
49     if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) {
50         av_log(s, AV_LOG_ERROR, "Invalid picture type: %d.\n", type);
51         if (s->error_recognition & AV_EF_EXPLODE) {
52             RETURN_ERROR(AVERROR_INVALIDDATA);
53         }
54         type = 0;
55     }
56
57     /* picture mimetype */
58     len  = avio_rb32(pb);
59     if (len <= 0 ||
60         avio_read(pb, mimetype, FFMIN(len, sizeof(mimetype) - 1)) != len) {
61         av_log(s, AV_LOG_ERROR, "Could not read mimetype from an attached "
62                "picture.\n");
63         if (s->error_recognition & AV_EF_EXPLODE)
64             ret = AVERROR_INVALIDDATA;
65         goto fail;
66     }
67     mimetype[len] = 0;
68
69     while (mime->id != AV_CODEC_ID_NONE) {
70         if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {
71             id = mime->id;
72             break;
73         }
74         mime++;
75     }
76     if (id == AV_CODEC_ID_NONE) {
77         av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n",
78                mimetype);
79         if (s->error_recognition & AV_EF_EXPLODE)
80             ret = AVERROR_INVALIDDATA;
81         goto fail;
82     }
83
84     /* picture description */
85     len = avio_rb32(pb);
86     if (len > 0) {
87         if (!(desc = av_malloc(len + 1))) {
88             RETURN_ERROR(AVERROR(ENOMEM));
89         }
90
91         if (avio_read(pb, desc, len) != len) {
92             av_log(s, AV_LOG_ERROR, "Error reading attached picture description.\n");
93             if (s->error_recognition & AV_EF_EXPLODE)
94                 ret = AVERROR(EIO);
95             goto fail;
96         }
97         desc[len] = 0;
98     }
99
100     /* picture metadata */
101     width  = avio_rb32(pb);
102     height = avio_rb32(pb);
103     avio_skip(pb, 8);
104
105     /* picture data */
106     len = avio_rb32(pb);
107     if (len <= 0) {
108         av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len);
109         if (s->error_recognition & AV_EF_EXPLODE)
110             ret = AVERROR_INVALIDDATA;
111         goto fail;
112     }
113     if (!(data = av_malloc(len))) {
114         RETURN_ERROR(AVERROR(ENOMEM));
115     }
116     if (avio_read(pb, data, len) != len) {
117         av_log(s, AV_LOG_ERROR, "Error reading attached picture data.\n");
118         if (s->error_recognition & AV_EF_EXPLODE)
119             ret = AVERROR(EIO);
120         goto fail;
121     }
122
123     st = avformat_new_stream(s, NULL);
124     if (!st) {
125         RETURN_ERROR(AVERROR(ENOMEM));
126     }
127
128     av_init_packet(&st->attached_pic);
129     st->attached_pic.data         = data;
130     st->attached_pic.size         = len;
131     st->attached_pic.destruct     = av_destruct_packet;
132     st->attached_pic.stream_index = st->index;
133     st->attached_pic.flags       |= AV_PKT_FLAG_KEY;
134
135     st->disposition      |= AV_DISPOSITION_ATTACHED_PIC;
136     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
137     st->codec->codec_id   = id;
138     st->codec->width      = width;
139     st->codec->height     = height;
140     av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0);
141     if (desc)
142         av_dict_set(&st->metadata, "title",   desc, AV_DICT_DONT_STRDUP_VAL);
143
144     av_freep(&pb);
145
146     return 0;
147
148 fail:
149     av_freep(&desc);
150     av_freep(&data);
151     av_freep(&pb);
152     return ret;
153
154 }
155
156 static int flac_read_header(AVFormatContext *s)
157 {
158     int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
159     uint8_t header[4];
160     uint8_t *buffer=NULL;
161     AVStream *st = avformat_new_stream(s, NULL);
162     if (!st)
163         return AVERROR(ENOMEM);
164     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
165     st->codec->codec_id = AV_CODEC_ID_FLAC;
166     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
167     /* the parameters will be extracted from the compressed bitstream */
168
169     /* if fLaC marker is not found, assume there is no header */
170     if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {
171         avio_seek(s->pb, -4, SEEK_CUR);
172         return 0;
173     }
174
175     /* process metadata blocks */
176     while (!url_feof(s->pb) && !metadata_last) {
177         avio_read(s->pb, header, 4);
178         avpriv_flac_parse_block_header(header, &metadata_last, &metadata_type,
179                                    &metadata_size);
180         switch (metadata_type) {
181         /* allocate and read metadata block for supported types */
182         case FLAC_METADATA_TYPE_STREAMINFO:
183         case FLAC_METADATA_TYPE_CUESHEET:
184         case FLAC_METADATA_TYPE_PICTURE:
185         case FLAC_METADATA_TYPE_VORBIS_COMMENT:
186             buffer = av_mallocz(metadata_size + FF_INPUT_BUFFER_PADDING_SIZE);
187             if (!buffer) {
188                 return AVERROR(ENOMEM);
189             }
190             if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {
191                 RETURN_ERROR(AVERROR(EIO));
192             }
193             break;
194         /* skip metadata block for unsupported types */
195         default:
196             ret = avio_skip(s->pb, metadata_size);
197             if (ret < 0)
198                 return ret;
199         }
200
201         if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
202             FLACStreaminfo si;
203             /* STREAMINFO can only occur once */
204             if (found_streaminfo) {
205                 RETURN_ERROR(AVERROR_INVALIDDATA);
206             }
207             if (metadata_size != FLAC_STREAMINFO_SIZE) {
208                 RETURN_ERROR(AVERROR_INVALIDDATA);
209             }
210             found_streaminfo = 1;
211             st->codec->extradata      = buffer;
212             st->codec->extradata_size = metadata_size;
213             buffer = NULL;
214
215             /* get codec params from STREAMINFO header */
216             avpriv_flac_parse_streaminfo(st->codec, &si, st->codec->extradata);
217
218             /* set time base and duration */
219             if (si.samplerate > 0) {
220                 avpriv_set_pts_info(st, 64, 1, si.samplerate);
221                 if (si.samples > 0)
222                     st->duration = si.samples;
223             }
224         } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
225             uint8_t isrc[13];
226             uint64_t start;
227             const uint8_t *offset;
228             int i, chapters, track, ti;
229             if (metadata_size < 431)
230                 RETURN_ERROR(AVERROR_INVALIDDATA);
231             offset = buffer + 395;
232             chapters = bytestream_get_byte(&offset) - 1;
233             if (chapters <= 0)
234                 RETURN_ERROR(AVERROR_INVALIDDATA);
235             for (i = 0; i < chapters; i++) {
236                 if (offset + 36 - buffer > metadata_size)
237                     RETURN_ERROR(AVERROR_INVALIDDATA);
238                 start = bytestream_get_be64(&offset);
239                 track = bytestream_get_byte(&offset);
240                 bytestream_get_buffer(&offset, isrc, 12);
241                 isrc[12] = 0;
242                 offset += 14;
243                 ti = bytestream_get_byte(&offset);
244                 if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
245                 offset += ti * 12;
246                 avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
247             }
248             av_freep(&buffer);
249         } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
250             ret = parse_picture(s, buffer, metadata_size);
251             av_freep(&buffer);
252             if (ret < 0) {
253                 av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
254                 return ret;
255             }
256         } else {
257             /* STREAMINFO must be the first block */
258             if (!found_streaminfo) {
259                 RETURN_ERROR(AVERROR_INVALIDDATA);
260             }
261             /* process supported blocks other than STREAMINFO */
262             if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
263                 if (ff_vorbis_comment(s, &s->metadata, buffer, metadata_size)) {
264                     av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
265                 }
266             }
267             av_freep(&buffer);
268         }
269     }
270
271     return 0;
272
273 fail:
274     av_free(buffer);
275     return ret;
276 }
277
278 static int flac_probe(AVProbeData *p)
279 {
280     const uint8_t *bufptr = p->buf;
281     const uint8_t *end    = p->buf + p->buf_size;
282
283     if(bufptr > end-4 || memcmp(bufptr, "fLaC", 4)) return 0;
284     else                                            return AVPROBE_SCORE_MAX/2;
285 }
286
287 static av_unused int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
288                                              int64_t *ppos, int64_t pos_limit)
289 {
290     AVPacket pkt, out_pkt;
291     AVStream *st = s->streams[stream_index];
292     int ret;
293
294     if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
295         return AV_NOPTS_VALUE;
296
297     av_init_packet(&pkt);
298     st->parser = av_parser_init(st->codec->codec_id);
299     if (!st->parser){
300         return AV_NOPTS_VALUE;
301     }
302     st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;
303
304     for (;;){
305         ret = ff_raw_read_partial_packet(s, &pkt);
306         if (ret < 0){
307             if (ret == AVERROR(EAGAIN))
308                 continue;
309             else
310                 return AV_NOPTS_VALUE;
311         }
312         av_init_packet(&out_pkt);
313         ret = av_parser_parse2(st->parser, st->codec,
314                                &out_pkt.data, &out_pkt.size, pkt.data, pkt.size,
315                                pkt.pts, pkt.dts, *ppos);
316
317         if (out_pkt.size){
318             int size = out_pkt.size;
319             av_free_packet(&out_pkt);
320             if (st->parser->pts != AV_NOPTS_VALUE){
321                 // seeking may not have started from beginning of a frame
322                 // calculate frame start position from next frame backwards
323                 *ppos = st->parser->next_frame_offset - size;
324                 return st->parser->pts;
325             }
326         }
327     }
328     return AV_NOPTS_VALUE;
329 }
330
331 AVInputFormat ff_flac_demuxer = {
332     .name           = "flac",
333     .long_name      = NULL_IF_CONFIG_SMALL("raw FLAC"),
334     .read_probe     = flac_probe,
335     .read_header    = flac_read_header,
336     .read_packet    = ff_raw_read_partial_packet,
337     .read_timestamp = flac_read_timestamp,
338     .flags          = AVFMT_GENERIC_INDEX,
339     .extensions     = "flac",
340     .raw_codec_id   = AV_CODEC_ID_FLAC,
341 };