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