FFmpeg  4.0
flacenc.c
Go to the documentation of this file.
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 
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;
38 
41  /* audio packets are queued here until we get all the attached pictures */
43 
44  /* updated streaminfo sent by the encoder at the end */
46 
47  unsigned attached_types;
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 
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 
67 
68  len = ff_vorbiscomment_length(*m, vendor);
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);
79 
80  avio_write(pb, p0, len+4);
81  av_freep(&p0);
82  p = NULL;
83 
84  return 0;
85 }
86 
88 {
90  AVIOContext *pb = s->pb;
91  const AVPixFmtDescriptor *pixdesc;
92  const CodecMime *mime = ff_id3v2_mime_tags;
94  const char *mimetype = NULL, *desc = "";
95  const AVStream *st = s->streams[pkt->stream_index];
96  int i, mimelen, desclen, type = 0;
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++) {
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  avio_w8(pb, 0x06);
144  avio_wb24(pb, 4 + 4 + mimelen + 4 + desclen + 4 + 4 + 4 + 4 + 4 + pkt->size);
145 
146  avio_wb32(pb, type);
147 
148  avio_wb32(pb, mimelen);
149  avio_write(pb, mimetype, mimelen);
150 
151  avio_wb32(pb, desclen);
152  avio_write(pb, desc, desclen);
153 
154  avio_wb32(pb, st->codecpar->width);
155  avio_wb32(pb, st->codecpar->height);
156  if ((pixdesc = av_pix_fmt_desc_get(st->codecpar->format)))
157  avio_wb32(pb, av_get_bits_per_pixel(pixdesc));
158  else
159  avio_wb32(pb, 0);
160  avio_wb32(pb, 0);
161 
162  avio_wb32(pb, pkt->size);
163  avio_write(pb, pkt->data, pkt->size);
164  return 0;
165 }
166 
168 {
169  int i, ret, padding = s->metadata_header_padding;
170  if (padding < 0)
171  padding = 8192;
172  /* The FLAC specification states that 24 bits are used to represent the
173  * size of a metadata block so we must clip this value to 2^24-1. */
174  padding = av_clip_uintp2(padding, 24);
175 
176  for (i = 0; i < s->nb_streams; i++) {
177  AVStream *st = s->streams[i];
178  AVPacket *pkt = st->priv_data;
179  if (!pkt)
180  continue;
181  ret = flac_write_picture(s, pkt);
182  av_packet_unref(pkt);
183  if (ret < 0 && (s->error_recognition & AV_EF_EXPLODE))
184  return ret;
185  }
186 
187  ret = flac_write_block_comment(s->pb, &s->metadata, !padding,
189  if (ret)
190  return ret;
191 
192  /* The command line flac encoder defaults to placing a seekpoint
193  * every 10s. So one might add padding to allow that later
194  * but there seems to be no simple way to get the duration here.
195  * So just add the amount requested by the user. */
196  if (padding)
197  flac_write_block_padding(s->pb, padding, 1);
198 
199  return 0;
200 }
201 
202 static int flac_init(struct AVFormatContext *s)
203 {
204  AVCodecParameters *par;
206  int i;
207 
208  c->audio_stream_idx = -1;
209  for (i = 0; i < s->nb_streams; i++) {
210  AVStream *st = s->streams[i];
211  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
212  if (c->audio_stream_idx >= 0 || st->codecpar->codec_id != AV_CODEC_ID_FLAC) {
213  av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one FLAC "
214  "audio stream is required.\n");
215  return AVERROR(EINVAL);
216  }
217  par = s->streams[i]->codecpar;
218  c->audio_stream_idx = i;
219  } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
221  av_log(s, AV_LOG_WARNING, "Video stream #%d is not an attached picture. Ignoring\n", i);
222  continue;
223  } else if (st->codecpar->codec_id == AV_CODEC_ID_GIF) {
224  av_log(s, AV_LOG_ERROR, "GIF image support is not implemented.\n");
225  return AVERROR_PATCHWELCOME;
226  } else if (!c->write_header) {
227  av_log(s, AV_LOG_ERROR, "Can't write attached pictures without a header.\n");
228  return AVERROR(EINVAL);
229  }
230  c->waiting_pics++;
231  } else {
232  av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in FLAC.\n");
233  return AVERROR(EINVAL);
234  }
235  }
236  if (c->audio_stream_idx < 0) {
237  av_log(s, AV_LOG_ERROR, "No audio stream present.\n");
238  return AVERROR(EINVAL);
239  }
240 
241  /* add the channel layout tag */
242  if (par->channel_layout &&
243  !(par->channel_layout & ~0x3ffffULL) &&
245  AVDictionaryEntry *chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK",
246  NULL, 0);
247 
248  if (chmask) {
249  av_log(s, AV_LOG_WARNING, "A WAVEFORMATEXTENSIBLE_CHANNEL_MASK is "
250  "already present, this muxer will not overwrite it.\n");
251  } else {
252  uint8_t buf[32];
253  snprintf(buf, sizeof(buf), "0x%"PRIx64, par->channel_layout);
254  av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", buf, 0);
255  }
256  }
257 
258  return 0;
259 }
260 
262 {
265  int ret;
266 
267  if (!c->write_header)
268  return 0;
269 
270  ret = ff_flac_write_header(s->pb, par->extradata,
271  par->extradata_size, 0);
272  if (ret < 0)
273  return ret;
274 
275  if (!c->waiting_pics)
276  ret = flac_finish_header(s);
277 
278  return ret;
279 }
280 
282 {
285  int streaminfo_size;
286 
287  /* check for updated streaminfo */
289  &streaminfo_size);
290  if (streaminfo && streaminfo_size == FLAC_STREAMINFO_SIZE) {
291  av_freep(&c->streaminfo);
292 
294  if (!c->streaminfo)
295  return AVERROR(ENOMEM);
296  memcpy(c->streaminfo, streaminfo, FLAC_STREAMINFO_SIZE);
297  }
298 
299  if (pkt->size)
300  avio_write(s->pb, pkt->data, pkt->size);
301  return 0;
302 }
303 
305 {
307  AVPacket pkt;
308  int ret, write = 1;
309 
310  ret = flac_finish_header(s);
311  if (ret < 0)
312  write = 0;
313 
314  while (c->queue) {
315  ff_packet_list_get(&c->queue, &c->queue_end, &pkt);
316  if (write && (ret = flac_write_audio_packet(s, &pkt)) < 0)
317  write = 0;
318  av_packet_unref(&pkt);
319  }
320  return ret;
321 }
322 
324 {
325  AVIOContext *pb = s->pb;
326  int64_t file_size;
330 
331  if (c->waiting_pics) {
332  av_log(s, AV_LOG_WARNING, "No packets were sent for some of the "
333  "attached pictures.\n");
334  flac_queue_flush(s);
335  }
336 
337  if (!c->write_header || !streaminfo)
338  return 0;
339 
340  if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
341  /* rewrite the STREAMINFO header block data */
342  file_size = avio_tell(pb);
343  avio_seek(pb, 8, SEEK_SET);
344  avio_write(pb, streaminfo, FLAC_STREAMINFO_SIZE);
345  avio_seek(pb, file_size, SEEK_SET);
346  avio_flush(pb);
347  } else {
348  av_log(s, AV_LOG_WARNING, "unable to rewrite FLAC header.\n");
349  }
350 
351  av_freep(&c->streaminfo);
352 
353  return 0;
354 }
355 
357 {
359  int ret;
360 
361  if (pkt->stream_index == c->audio_stream_idx) {
362  if (c->waiting_pics) {
363  /* buffer audio packets until we get all the pictures */
365  if (ret < 0) {
366  av_log(s, AV_LOG_ERROR, "Out of memory in packet queue; skipping attached pictures\n");
367  c->waiting_pics = 0;
368  ret = flac_queue_flush(s);
369  if (ret < 0)
370  return ret;
371  return flac_write_audio_packet(s, pkt);
372  }
373  } else
374  return flac_write_audio_packet(s, pkt);
375  } else {
376  AVStream *st = s->streams[pkt->stream_index];
377 
378  if (!c->waiting_pics ||
380  return 0;
381 
382  /* warn only once for each stream */
383  if (st->nb_frames == 1) {
384  av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
385  " ignoring.\n", pkt->stream_index);
386  }
387  if (st->nb_frames >= 1)
388  return 0;
389 
390  st->priv_data = av_packet_clone(pkt);
391  if (!st->priv_data)
392  av_log(s, AV_LOG_ERROR, "Out of memory queueing an attached picture; skipping\n");
393  c->waiting_pics--;
394 
395  /* flush the buffered audio packets */
396  if (!c->waiting_pics &&
397  (ret = flac_queue_flush(s)) < 0)
398  return ret;
399  }
400 
401  return 0;
402 }
403 
404 static const AVOption flacenc_options[] = {
405  { "write_header", "Write the file header", offsetof(FlacMuxerContext, write_header), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM },
406  { NULL },
407 };
408 
409 static const AVClass flac_muxer_class = {
410  .class_name = "flac muxer",
411  .item_name = av_default_item_name,
412  .option = flacenc_options,
413  .version = LIBAVUTIL_VERSION_INT,
414 };
415 
417  .name = "flac",
418  .long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
419  .priv_data_size = sizeof(FlacMuxerContext),
420  .mime_type = "audio/x-flac",
421  .extensions = "flac",
422  .audio_codec = AV_CODEC_ID_FLAC,
423  .video_codec = AV_CODEC_ID_PNG,
424  .init = flac_init,
429  .priv_class = &flac_muxer_class,
430 };
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:679
#define NULL
Definition: coverity.c:32
const char * s
Definition: avisynth_c.h:768
Bytestream IO Context.
Definition: avio.h:161
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2363
AVOption.
Definition: opt.h:246
int ff_packet_list_put(AVPacketList **head, AVPacketList **tail, AVPacket *pkt, int flags)
Append an AVPacket to the list.
Definition: utils.c:447
static int flac_init(struct AVFormatContext *s)
Definition: flacenc.c:202
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
const char * desc
Definition: nvenc.c:65
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
AVPacketList * queue
Definition: flacenc.c:42
int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc)
Return the number of bits per pixel used by the pixel format described by pixdesc.
Definition: pixdesc.c:2315
static int flac_write_block_padding(AVIOContext *pb, unsigned int n_padding_bytes, int last_block)
Definition: flacenc.c:50
AVOutputFormat ff_flac_muxer
Definition: flacenc.c:416
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:3884
int index
stream index in AVFormatContext
Definition: avformat.h:874
int size
Definition: avcodec.h:1431
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:246
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:191
int ff_flac_is_native_layout(uint64_t channel_layout)
void * priv_data
Definition: avformat.h:888
static AVPacket pkt
This struct describes the properties of an encoded stream.
Definition: avcodec.h:3876
int ff_vorbiscomment_write(uint8_t **p, AVDictionary **m, const char *vendor_string)
Write a VorbisComment into a buffer.
Definition: vorbiscomment.c:54
Format I/O context.
Definition: avformat.h:1342
char str[32]
Definition: internal.h:50
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
static int flac_queue_flush(AVFormatContext *s)
Definition: flacenc.c:304
uint8_t
#define av_malloc(s)
int width
Video only.
Definition: avcodec.h:3950
AVOptions.
uint8_t * streaminfo
Definition: flacenc.c:45
static int flac_write_header(struct AVFormatContext *s)
Definition: flacenc.c:261
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1410
#define FF_PACKETLIST_FLAG_REF_PACKET
Create a new reference for the packet instead of transferring the ownership of the existing one to th...
Definition: internal.h:744
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1473
uint8_t * data
Definition: avcodec.h:1430
static int flags
Definition: log.c:55
enum AVCodecID id
Definition: internal.h:51
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
static int flac_finish_header(struct AVFormatContext *s)
Definition: flacenc.c:167
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:218
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1490
static int flac_write_trailer(struct AVFormatContext *s)
Definition: flacenc.c:323
uint64_t channel_layout
Audio only.
Definition: avcodec.h:3986
#define av_log(a,...)
#define AV_OPT_FLAG_ENCODING_PARAM
a generic parameter which can be set by the user for muxing or encoding
Definition: opt.h:276
static int flac_write_audio_packet(struct AVFormatContext *s, AVPacket *pkt)
Definition: flacenc.c:281
static int flac_write_picture(struct AVFormatContext *s, AVPacket *pkt)
Definition: flacenc.c:87
const AVMetadataConv ff_vorbiscomment_metadata_conv[]
VorbisComment metadata conversion mapping.
Definition: vorbiscomment.c:33
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1580
AVPacket * av_packet_clone(const AVPacket *src)
Create a new packet that references the same data as src.
Definition: avpacket.c:634
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
#define AVERROR(e)
Definition: error.h:43
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, int *size)
Get side information from packet.
Definition: avpacket.c:350
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:3880
int64_t ff_vorbiscomment_length(AVDictionary *m, const char *vendor_string)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:41
int extradata_size
Size of the extradata content in bytes.
Definition: avcodec.h:3902
static const AVOption flacenc_options[]
Definition: flacenc.c:404
const CodecMime ff_id3v2_mime_tags[]
Definition: id3v2.c:130
int write_header
Definition: flacenc.c:37
unsigned attached_types
Definition: flacenc.c:47
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1398
#define LIBAVFORMAT_IDENT
Definition: version.h:46
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:260
int void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:238
audio channel layout utility functions
void ffio_fill(AVIOContext *s, int b, int count)
Definition: aviobuf.c:204
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:94
void avio_wb24(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:487
const char * name
Definition: avformat.h:507
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
int ff_flac_write_header(AVIOContext *pb, uint8_t *extradata, int extradata_size, int last_block)
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition: avcodec.h:2653
AVDictionary * metadata
Definition: avformat.h:937
static int flac_write_block_comment(AVIOContext *pb, AVDictionary **m, int last_block, int bitexact)
Definition: flacenc.c:59
#define FF_ARRAY_ELEMS(a)
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:842
int metadata_header_padding
Number of bytes to be written as padding in a metadata header.
Definition: avformat.h:1840
Stream structure.
Definition: avformat.h:873
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition: avformat.h:469
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition: avio.h:40
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition: avcodec.h:1158
static const AVClass flac_muxer_class
Definition: flacenc.c:409
AVIOContext * pb
I/O context.
Definition: avformat.h:1384
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:81
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:196
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:592
void * buf
Definition: avisynth_c.h:690
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
Describe the class of an AVClass context structure.
Definition: log.h:67
cl_device_type type
int waiting_pics
Definition: flacenc.c:40
#define snprintf
Definition: snprintf.h:34
AVPacketList * queue_end
Definition: flacenc.c:42
static int flac_write_packet(struct AVFormatContext *s, AVPacket *pkt)
Definition: flacenc.c:356
int ff_packet_list_get(AVPacketList **head, AVPacketList **tail, AVPacket *pkt)
Remove the oldest AVPacket in the list and return it.
Definition: utils.c:1549
Main libavformat public API header.
int audio_stream_idx
Definition: flacenc.c:39
static double c[64]
int error_recognition
Error recognition; higher values will detect more errors but may misdetect some more or less valid pa...
Definition: avformat.h:1607
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:926
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:924
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:26
char * value
Definition: dict.h:87
int len
void * priv_data
Format private data.
Definition: avformat.h:1370
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: avcodec.h:3898
void avio_wb32(AVIOContext *s, unsigned int val)
Definition: aviobuf.c:377
#define av_freep(p)
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1020
const char *const ff_id3v2_picture_types[21]
Definition: id3v2.c:106
int stream_index
Definition: avcodec.h:1432
This structure stores compressed data.
Definition: avcodec.h:1407