]> git.sesse.net Git - ffmpeg/blob - libavcodec/libspeexenc.c
Set Beam Software VB palette opaque.
[ffmpeg] / libavcodec / libspeexenc.c
1 /*
2  * Copyright (C) 2009 Justin Ruggles
3  * Copyright (c) 2009 Xuggle Incorporated
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 /**
23  * @file
24  * libspeex Speex audio encoder
25  *
26  * Usage Guide
27  * This explains the values that need to be set prior to initialization in
28  * order to control various encoding parameters.
29  *
30  * Channels
31  *     Speex only supports mono or stereo, so avctx->channels must be set to
32  *     1 or 2.
33  *
34  * Sample Rate / Encoding Mode
35  *     Speex has 3 modes, each of which uses a specific sample rate.
36  *         narrowband     :  8 kHz
37  *         wideband       : 16 kHz
38  *         ultra-wideband : 32 kHz
39  *     avctx->sample_rate must be set to one of these 3 values.  This will be
40  *     used to set the encoding mode.
41  *
42  * Rate Control
43  *     VBR mode is turned on by setting CODEC_FLAG_QSCALE in avctx->flags.
44  *     avctx->global_quality is used to set the encoding quality.
45  *     For CBR mode, avctx->bit_rate can be used to set the constant bitrate.
46  *     Alternatively, the 'cbr_quality' option can be set from 0 to 10 to set
47  *     a constant bitrate based on quality.
48  *     For ABR mode, set avctx->bit_rate and set the 'abr' option to 1.
49  *     Approx. Bitrate Range:
50  *         narrowband     : 2400 - 25600 bps
51  *         wideband       : 4000 - 43200 bps
52  *         ultra-wideband : 4400 - 45200 bps
53  *
54  * Complexity
55  *     Encoding complexity is controlled by setting avctx->compression_level.
56  *     The valid range is 0 to 10.  A higher setting gives generally better
57  *     quality at the expense of encoding speed.  This does not affect the
58  *     bit rate.
59  *
60  * Frames-per-Packet
61  *     The encoder defaults to using 1 frame-per-packet.  However, it is
62  *     sometimes desirable to use multiple frames-per-packet to reduce the
63  *     amount of container overhead.  This can be done by setting the
64  *     'frames_per_packet' option to a value 1 to 8.
65  */
66
67 #include <speex/speex.h>
68 #include <speex/speex_header.h>
69 #include <speex/speex_stereo.h>
70 #include "libavutil/mathematics.h"
71 #include "libavutil/opt.h"
72 #include "avcodec.h"
73 #include "internal.h"
74
75 typedef struct {
76     AVClass *class;             ///< AVClass for private options
77     SpeexBits bits;             ///< libspeex bitwriter context
78     SpeexHeader header;         ///< libspeex header struct
79     void *enc_state;            ///< libspeex encoder state
80     int frames_per_packet;      ///< number of frames to encode in each packet
81     float vbr_quality;          ///< VBR quality 0.0 to 10.0
82     int cbr_quality;            ///< CBR quality 0 to 10
83     int abr;                    ///< flag to enable ABR
84     int pkt_frame_count;        ///< frame count for the current packet
85     int lookahead;              ///< encoder delay
86     int sample_count;           ///< total sample count (used for pts)
87 } LibSpeexEncContext;
88
89 static av_cold void print_enc_params(AVCodecContext *avctx,
90                                      LibSpeexEncContext *s)
91 {
92     const char *mode_str = "unknown";
93
94     av_log(avctx, AV_LOG_DEBUG, "channels: %d\n", avctx->channels);
95     switch (s->header.mode) {
96     case SPEEX_MODEID_NB:  mode_str = "narrowband";     break;
97     case SPEEX_MODEID_WB:  mode_str = "wideband";       break;
98     case SPEEX_MODEID_UWB: mode_str = "ultra-wideband"; break;
99     }
100     av_log(avctx, AV_LOG_DEBUG, "mode: %s\n", mode_str);
101     if (s->header.vbr) {
102         av_log(avctx, AV_LOG_DEBUG, "rate control: VBR\n");
103         av_log(avctx, AV_LOG_DEBUG, "  quality: %f\n", s->vbr_quality);
104     } else if (s->abr) {
105         av_log(avctx, AV_LOG_DEBUG, "rate control: ABR\n");
106         av_log(avctx, AV_LOG_DEBUG, "  bitrate: %d bps\n", avctx->bit_rate);
107     } else {
108         av_log(avctx, AV_LOG_DEBUG, "rate control: CBR\n");
109         av_log(avctx, AV_LOG_DEBUG, "  bitrate: %d bps\n", avctx->bit_rate);
110     }
111     av_log(avctx, AV_LOG_DEBUG, "complexity: %d\n",
112            avctx->compression_level);
113     av_log(avctx, AV_LOG_DEBUG, "frame size: %d samples\n",
114            avctx->frame_size);
115     av_log(avctx, AV_LOG_DEBUG, "frames per packet: %d\n",
116            s->frames_per_packet);
117     av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
118            avctx->frame_size * s->frames_per_packet);
119 }
120
121 static av_cold int encode_init(AVCodecContext *avctx)
122 {
123     LibSpeexEncContext *s = avctx->priv_data;
124     const SpeexMode *mode;
125     uint8_t *header_data;
126     int header_size;
127     int32_t complexity;
128
129     /* channels */
130     if (avctx->channels < 1 || avctx->channels > 2) {
131         av_log(avctx, AV_LOG_ERROR, "Invalid channels (%d). Only stereo and "
132                "mono are supported\n", avctx->channels);
133         return AVERROR(EINVAL);
134     }
135
136     /* sample rate and encoding mode */
137     switch (avctx->sample_rate) {
138     case  8000: mode = &speex_nb_mode;  break;
139     case 16000: mode = &speex_wb_mode;  break;
140     case 32000: mode = &speex_uwb_mode; break;
141     default:
142         av_log(avctx, AV_LOG_ERROR, "Sample rate of %d Hz is not supported. "
143                "Resample to 8, 16, or 32 kHz.\n", avctx->sample_rate);
144         return AVERROR(EINVAL);
145     }
146
147     /* initialize libspeex */
148     s->enc_state = speex_encoder_init(mode);
149     if (!s->enc_state) {
150         av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex\n");
151         return -1;
152     }
153     speex_init_header(&s->header, avctx->sample_rate, avctx->channels, mode);
154
155     /* rate control method and parameters */
156     if (avctx->flags & CODEC_FLAG_QSCALE) {
157         /* VBR */
158         s->header.vbr = 1;
159         speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
160         s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
161                                   0.0f, 10.0f);
162         speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR_QUALITY, &s->vbr_quality);
163     } else {
164         s->header.bitrate = avctx->bit_rate;
165         if (avctx->bit_rate > 0) {
166             /* CBR or ABR by bitrate */
167             if (s->abr) {
168                 speex_encoder_ctl(s->enc_state, SPEEX_SET_ABR,
169                                   &s->header.bitrate);
170                 speex_encoder_ctl(s->enc_state, SPEEX_GET_ABR,
171                                   &s->header.bitrate);
172             } else {
173                 speex_encoder_ctl(s->enc_state, SPEEX_SET_BITRATE,
174                                   &s->header.bitrate);
175                 speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
176                                   &s->header.bitrate);
177             }
178         } else {
179             /* CBR by quality */
180             speex_encoder_ctl(s->enc_state, SPEEX_SET_QUALITY,
181                               &s->cbr_quality);
182             speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
183                               &s->header.bitrate);
184         }
185         /* stereo side information adds about 800 bps to the base bitrate */
186         /* TODO: this should be calculated exactly */
187         avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
188     }
189
190     /* set encoding complexity */
191     if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
192         complexity = av_clip(avctx->compression_level, 0, 10);
193         speex_encoder_ctl(s->enc_state, SPEEX_SET_COMPLEXITY, &complexity);
194     }
195     speex_encoder_ctl(s->enc_state, SPEEX_GET_COMPLEXITY, &complexity);
196     avctx->compression_level = complexity;
197
198     /* set packet size */
199     avctx->frame_size = s->header.frame_size;
200     s->header.frames_per_packet = s->frames_per_packet;
201
202     /* set encoding delay */
203     speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &s->lookahead);
204     s->sample_count = -s->lookahead;
205
206     /* create header packet bytes from header struct */
207     /* note: libspeex allocates the memory for header_data, which is freed
208              below with speex_header_free() */
209     header_data = speex_header_to_packet(&s->header, &header_size);
210
211     /* allocate extradata and coded_frame */
212     avctx->extradata   = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
213     avctx->coded_frame = avcodec_alloc_frame();
214     if (!avctx->extradata || !avctx->coded_frame) {
215         speex_header_free(header_data);
216         speex_encoder_destroy(s->enc_state);
217         av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
218         return AVERROR(ENOMEM);
219     }
220
221     /* copy header packet to extradata */
222     memcpy(avctx->extradata, header_data, header_size);
223     avctx->extradata_size = header_size;
224     speex_header_free(header_data);
225
226     /* init libspeex bitwriter */
227     speex_bits_init(&s->bits);
228
229     print_enc_params(avctx, s);
230     return 0;
231 }
232
233 static int encode_frame(AVCodecContext *avctx, uint8_t *frame, int buf_size,
234                         void *data)
235 {
236     LibSpeexEncContext *s = avctx->priv_data;
237     int16_t *samples      = data;
238     int sample_count      = s->sample_count;
239
240     if (data) {
241         /* encode Speex frame */
242         if (avctx->channels == 2)
243             speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
244         speex_encode_int(s->enc_state, samples, &s->bits);
245         s->pkt_frame_count++;
246         s->sample_count += avctx->frame_size;
247     } else {
248         /* handle end-of-stream */
249         if (!s->pkt_frame_count)
250             return 0;
251         /* add extra terminator codes for unused frames in last packet */
252         while (s->pkt_frame_count < s->frames_per_packet) {
253             speex_bits_pack(&s->bits, 15, 5);
254             s->pkt_frame_count++;
255         }
256     }
257
258     /* write output if all frames for the packet have been encoded */
259     if (s->pkt_frame_count == s->frames_per_packet) {
260         s->pkt_frame_count = 0;
261         avctx->coded_frame->pts =
262             av_rescale_q(sample_count, (AVRational){ 1, avctx->sample_rate },
263                          avctx->time_base);
264         if (buf_size > speex_bits_nbytes(&s->bits)) {
265             int ret = speex_bits_write(&s->bits, frame, buf_size);
266             speex_bits_reset(&s->bits);
267             return ret;
268         } else {
269             av_log(avctx, AV_LOG_ERROR, "output buffer too small");
270             return AVERROR(EINVAL);
271         }
272     }
273     return 0;
274 }
275
276 static av_cold int encode_close(AVCodecContext *avctx)
277 {
278     LibSpeexEncContext *s = avctx->priv_data;
279
280     speex_bits_destroy(&s->bits);
281     speex_encoder_destroy(s->enc_state);
282
283     av_freep(&avctx->coded_frame);
284     av_freep(&avctx->extradata);
285
286     return 0;
287 }
288
289 #define OFFSET(x) offsetof(LibSpeexEncContext, x)
290 #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
291 static const AVOption options[] = {
292     { "abr",               "Use average bit rate",                      OFFSET(abr),               AV_OPT_TYPE_INT, { 0 }, 0,   1, AE },
293     { "cbr_quality",       "Set quality value (0 to 10) for CBR",       OFFSET(cbr_quality),       AV_OPT_TYPE_INT, { 8 }, 0,  10, AE },
294     { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { 1 }, 1,   8, AE },
295     { NULL },
296 };
297
298 static const AVClass class = {
299     .class_name = "libspeex",
300     .item_name  = av_default_item_name,
301     .option     = options,
302     .version    = LIBAVUTIL_VERSION_INT,
303 };
304
305 static const AVCodecDefault defaults[] = {
306     { "b",                 "0" },
307     { "compression_level", "3" },
308     { NULL },
309 };
310
311 AVCodec ff_libspeex_encoder = {
312     .name           = "libspeex",
313     .type           = AVMEDIA_TYPE_AUDIO,
314     .id             = CODEC_ID_SPEEX,
315     .priv_data_size = sizeof(LibSpeexEncContext),
316     .init           = encode_init,
317     .encode         = encode_frame,
318     .close          = encode_close,
319     .capabilities   = CODEC_CAP_DELAY,
320     .sample_fmts    = (const enum SampleFormat[]){ AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE },
321     .long_name      = NULL_IF_CONFIG_SMALL("libspeex Speex"),
322     .priv_class     = &class,
323     .defaults       = defaults,
324 };