]> git.sesse.net Git - ffmpeg/blob - libavformat/flacenc.c
avformat/flacenc: Don't allocate updated streaminfo separately
[ffmpeg] / libavformat / flacenc.c
1 /*
2  * raw FLAC muxer
3  * Copyright (c) 2006-2009 Justin Ruggles
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 "libavutil/opt.h"
24 #include "libavutil/pixdesc.h"
25 #include "libavcodec/flac.h"
26 #include "avformat.h"
27 #include "avio_internal.h"
28 #include "flacenc.h"
29 #include "id3v2.h"
30 #include "internal.h"
31 #include "vorbiscomment.h"
32 #include "libavcodec/bytestream.h"
33
34
35 typedef struct FlacMuxerContext {
36     const AVClass *class;
37     int write_header;
38
39     int audio_stream_idx;
40     int waiting_pics;
41     /* audio packets are queued here until we get all the attached pictures */
42     AVPacketList *queue, *queue_end;
43
44     /* updated streaminfo sent by the encoder at the end */
45     uint8_t streaminfo[FLAC_STREAMINFO_SIZE];
46     int updated_streaminfo;
47
48     unsigned attached_types;
49 } FlacMuxerContext;
50
51 static int flac_write_block_padding(AVIOContext *pb, unsigned int n_padding_bytes,
52                                     int last_block)
53 {
54     avio_w8(pb, last_block ? 0x81 : 0x01);
55     avio_wb24(pb, n_padding_bytes);
56     ffio_fill(pb, 0, n_padding_bytes);
57     return 0;
58 }
59
60 static int flac_write_block_comment(AVIOContext *pb, AVDictionary **m,
61                                     int last_block, int bitexact)
62 {
63     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
64     int64_t len;
65     uint8_t *p, *p0;
66
67     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
68
69     len = ff_vorbiscomment_length(*m, vendor, NULL, 0);
70     if (len >= ((1<<24) - 4))
71         return AVERROR(EINVAL);
72     p0 = av_malloc(len+4);
73     if (!p0)
74         return AVERROR(ENOMEM);
75     p = p0;
76
77     bytestream_put_byte(&p, last_block ? 0x84 : 0x04);
78     bytestream_put_be24(&p, len);
79     ff_vorbiscomment_write(&p, m, vendor, NULL, 0);
80
81     avio_write(pb, p0, len+4);
82     av_freep(&p0);
83     p = NULL;
84
85     return 0;
86 }
87
88 static int flac_write_picture(struct AVFormatContext *s, AVPacket *pkt)
89 {
90     FlacMuxerContext *c = s->priv_data;
91     AVIOContext *pb = s->pb;
92     const AVPixFmtDescriptor *pixdesc;
93     const CodecMime *mime = ff_id3v2_mime_tags;
94     AVDictionaryEntry *e;
95     const char *mimetype = NULL, *desc = "";
96     const AVStream *st = s->streams[pkt->stream_index];
97     int i, mimelen, desclen, type = 0, blocklen;
98
99     if (!pkt->data)
100         return 0;
101
102     while (mime->id != AV_CODEC_ID_NONE) {
103         if (mime->id == st->codecpar->codec_id) {
104             mimetype = mime->str;
105             break;
106         }
107         mime++;
108     }
109     if (!mimetype) {
110         av_log(s, AV_LOG_ERROR, "No mimetype is known for stream %d, cannot "
111                "write an attached picture.\n", st->index);
112         return AVERROR(EINVAL);
113     }
114     mimelen = strlen(mimetype);
115
116     /* get the picture type */
117     e = av_dict_get(st->metadata, "comment", NULL, 0);
118     for (i = 0; e && i < FF_ARRAY_ELEMS(ff_id3v2_picture_types); i++) {
119         if (!av_strcasecmp(e->value, ff_id3v2_picture_types[i])) {
120             type = i;
121             break;
122         }
123     }
124
125     if ((c->attached_types & (1 << type)) & 0x6) {
126         av_log(s, AV_LOG_ERROR, "Duplicate attachment for type '%s'\n", ff_id3v2_picture_types[type]);
127         return AVERROR(EINVAL);
128     }
129
130     if (type == 1 && (st->codecpar->codec_id != AV_CODEC_ID_PNG ||
131                       st->codecpar->width != 32 ||
132                       st->codecpar->height != 32)) {
133         av_log(s, AV_LOG_ERROR, "File icon attachment must be a 32x32 PNG");
134         return AVERROR(EINVAL);
135     }
136
137     c->attached_types |= (1 << type);
138
139     /* get the description */
140     if ((e = av_dict_get(st->metadata, "title", NULL, 0)))
141         desc = e->value;
142     desclen = strlen(desc);
143
144     blocklen = 4 + 4 + mimelen + 4 + desclen + 4 + 4 + 4 + 4 + 4 + pkt->size;
145     if (blocklen >= 1<<24) {
146         av_log(s, AV_LOG_ERROR, "Picture block too big %d >= %d\n", blocklen, 1<<24);
147         return AVERROR(EINVAL);
148     }
149
150     avio_w8(pb, 0x06);
151     avio_wb24(pb, blocklen);
152
153     avio_wb32(pb, type);
154
155     avio_wb32(pb, mimelen);
156     avio_write(pb, mimetype, mimelen);
157
158     avio_wb32(pb, desclen);
159     avio_write(pb, desc, desclen);
160
161     avio_wb32(pb, st->codecpar->width);
162     avio_wb32(pb, st->codecpar->height);
163     if ((pixdesc = av_pix_fmt_desc_get(st->codecpar->format)))
164         avio_wb32(pb, av_get_bits_per_pixel(pixdesc));
165     else
166         avio_wb32(pb, 0);
167     avio_wb32(pb, 0);
168
169     avio_wb32(pb, pkt->size);
170     avio_write(pb, pkt->data, pkt->size);
171     return 0;
172 }
173
174 static int flac_finish_header(struct AVFormatContext *s)
175 {
176     int i, ret, padding = s->metadata_header_padding;
177     if (padding < 0)
178         padding = 8192;
179     /* The FLAC specification states that 24 bits are used to represent the
180      * size of a metadata block so we must clip this value to 2^24-1. */
181     padding = av_clip_uintp2(padding, 24);
182
183     for (i = 0; i < s->nb_streams; i++) {
184         AVStream *st = s->streams[i];
185         AVPacket *pkt = st->priv_data;
186         if (!pkt)
187             continue;
188         ret = flac_write_picture(s, pkt);
189         av_packet_unref(pkt);
190         if (ret < 0 && (s->error_recognition & AV_EF_EXPLODE))
191             return ret;
192     }
193
194     ret = flac_write_block_comment(s->pb, &s->metadata, !padding,
195                                    s->flags & AVFMT_FLAG_BITEXACT);
196     if (ret)
197         return ret;
198
199     /* The command line flac encoder defaults to placing a seekpoint
200      * every 10s.  So one might add padding to allow that later
201      * but there seems to be no simple way to get the duration here.
202      * So just add the amount requested by the user. */
203     if (padding)
204         flac_write_block_padding(s->pb, padding, 1);
205
206     return 0;
207 }
208
209 static int flac_init(struct AVFormatContext *s)
210 {
211     AVCodecParameters *par;
212     FlacMuxerContext *c = s->priv_data;
213     int i;
214
215     c->audio_stream_idx = -1;
216     for (i = 0; i < s->nb_streams; i++) {
217         AVStream *st = s->streams[i];
218         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
219             if (c->audio_stream_idx >= 0 || st->codecpar->codec_id != AV_CODEC_ID_FLAC) {
220                 av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one FLAC "
221                        "audio stream is required.\n");
222                 return AVERROR(EINVAL);
223             }
224             par = s->streams[i]->codecpar;
225             c->audio_stream_idx = i;
226         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
227             if (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC)) {
228                 av_log(s, AV_LOG_WARNING, "Video stream #%d is not an attached picture. Ignoring\n", i);
229                 continue;
230             } else if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
231                 av_log(s, AV_LOG_ERROR, "GIF image support is not implemented.\n");
232                 return AVERROR_PATCHWELCOME;
233             } else if (!c->write_header) {
234                 av_log(s, AV_LOG_ERROR, "Can't write attached pictures without a header.\n");
235                 return AVERROR(EINVAL);
236             }
237             c->waiting_pics++;
238         } else {
239             av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in FLAC.\n");
240             return AVERROR(EINVAL);
241         }
242     }
243     if (c->audio_stream_idx < 0) {
244         av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
245         return AVERROR(EINVAL);
246     }
247
248     /* add the channel layout tag */
249     if (par->channel_layout &&
250         !(par->channel_layout & ~0x3ffffULL) &&
251         !ff_flac_is_native_layout(par->channel_layout)) {
252         AVDictionaryEntry *chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK",
253                                                 NULL, 0);
254
255         if (chmask) {
256             av_log(s, AV_LOG_WARNING, "A WAVEFORMATEXTENSIBLE_CHANNEL_MASK is "
257                    "already present, this muxer will not overwrite it.\n");
258         } else {
259             uint8_t buf[32];
260             snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
261             av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
262         }
263     }
264
265     return 0;
266 }
267
268 static int flac_write_header(struct AVFormatContext *s)
269 {
270     FlacMuxerContext *c = s->priv_data;
271     AVCodecParameters *par = s->streams[c->audio_stream_idx]->codecpar;
272     int ret;
273
274     if (!c->write_header)
275         return 0;
276
277     ret = ff_flac_write_header(s->pb, par->extradata,
278                                par->extradata_size, 0);
279     if (ret < 0)
280         return ret;
281
282     if (!c->waiting_pics)
283         ret = flac_finish_header(s);
284
285     return ret;
286 }
287
288 static int flac_write_audio_packet(struct AVFormatContext *s, AVPacket *pkt)
289 {
290     FlacMuxerContext *c = s->priv_data;
291     uint8_t *streaminfo;
292     int streaminfo_size;
293
294     /* check for updated streaminfo */
295     streaminfo = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
296                                          &streaminfo_size);
297     if (streaminfo && streaminfo_size == FLAC_STREAMINFO_SIZE) {
298         memcpy(c->streaminfo, streaminfo, FLAC_STREAMINFO_SIZE);
299         c->updated_streaminfo = 1;
300     }
301
302     if (pkt->size)
303         avio_write(s->pb, pkt->data, pkt->size);
304     return 0;
305 }
306
307 static int flac_queue_flush(AVFormatContext *s)
308 {
309     FlacMuxerContext *c = s->priv_data;
310     AVPacket pkt;
311     int ret, write = 1;
312
313     ret = flac_finish_header(s);
314     if (ret < 0)
315         write = 0;
316
317     while (c->queue) {
318         ff_packet_list_get(&c->queue, &c->queue_end, &pkt);
319         if (write && (ret = flac_write_audio_packet(s, &pkt)) < 0)
320             write = 0;
321         av_packet_unref(&pkt);
322     }
323     return ret;
324 }
325
326 static int flac_write_trailer(struct AVFormatContext *s)
327 {
328     AVIOContext *pb = s->pb;
329     int64_t file_size;
330     FlacMuxerContext *c = s->priv_data;
331
332     if (c->waiting_pics) {
333         av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
334                "attached pictures.\n");
335         flac_queue_flush(s);
336     }
337
338     if (!c->write_header || !c->updated_streaminfo)
339         return 0;
340
341     if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
342         /* rewrite the STREAMINFO header block data */
343         file_size = avio_tell(pb);
344         avio_seek(pb, 8, SEEK_SET);
345         avio_write(pb, c->streaminfo, FLAC_STREAMINFO_SIZE);
346         avio_seek(pb, file_size, SEEK_SET);
347     } else {
348         av_log(s, AV_LOG_WARNING, "unable to rewrite FLAC header.\n");
349     }
350
351     return 0;
352 }
353
354 static void flac_deinit(struct AVFormatContext *s)
355 {
356     FlacMuxerContext *c = s->priv_data;
357
358     ff_packet_list_free(&c->queue, &c->queue_end);
359 }
360
361 static int flac_write_packet(struct AVFormatContext *s, AVPacket *pkt)
362 {
363     FlacMuxerContext *c = s->priv_data;
364     int ret;
365
366     if (pkt->stream_index == c->audio_stream_idx) {
367         if (c->waiting_pics) {
368             /* buffer audio packets until we get all the pictures */
369             ret = ff_packet_list_put(&c->queue, &c->queue_end, pkt, FF_PACKETLIST_FLAG_REF_PACKET);
370             if (ret < 0) {
371                 av_log(s, AV_LOG_ERROR, "Out of memory in packet queue; skipping attached pictures\n");
372                 c->waiting_pics = 0;
373                 ret = flac_queue_flush(s);
374                 if (ret < 0)
375                     return ret;
376                 return flac_write_audio_packet(s, pkt);
377             }
378         } else
379             return flac_write_audio_packet(s, pkt);
380     } else {
381         AVStream *st = s->streams[pkt->stream_index];
382
383         if (!c->waiting_pics ||
384             !(st->disposition & AV_DISPOSITION_ATTACHED_PIC))
385             return 0;
386
387         /* warn only once for each stream */
388         if (st->nb_frames == 1) {
389             av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
390                    " ignoring.\n", pkt->stream_index);
391         }
392         if (st->nb_frames >= 1)
393             return 0;
394
395         st->priv_data = av_packet_clone(pkt);
396         if (!st->priv_data)
397             av_log(s, AV_LOG_ERROR, "Out of memory queueing an attached picture; skipping\n");
398         c->waiting_pics--;
399
400         /* flush the buffered audio packets */
401         if (!c->waiting_pics &&
402             (ret = flac_queue_flush(s)) < 0)
403             return ret;
404     }
405
406     return 0;
407 }
408
409 static const AVOption flacenc_options[] = {
410     { "write_header", "Write the file header", offsetof(FlacMuxerContext, write_header), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
411     { NULL },
412 };
413
414 static const AVClass flac_muxer_class = {
415     .class_name = "flac muxer",
416     .item_name  = av_default_item_name,
417     .option     = flacenc_options,
418     .version    = LIBAVUTIL_VERSION_INT,
419 };
420
421 AVOutputFormat ff_flac_muxer = {
422     .name              = "flac",
423     .long_name         = NULL_IF_CONFIG_SMALL("raw FLAC"),
424     .priv_data_size    = sizeof(FlacMuxerContext),
425     .mime_type         = "audio/x-flac",
426     .extensions        = "flac",
427     .audio_codec       = AV_CODEC_ID_FLAC,
428     .video_codec       = AV_CODEC_ID_PNG,
429     .init              = flac_init,
430     .write_header      = flac_write_header,
431     .write_packet      = flac_write_packet,
432     .write_trailer     = flac_write_trailer,
433     .deinit            = flac_deinit,
434     .flags             = AVFMT_NOTIMESTAMPS,
435     .priv_class        = &flac_muxer_class,
436 };