2 * Copyright (C) 2009 Justin Ruggles
3 * Copyright (c) 2009 Xuggle Incorporated
5 * This file is part of Libav.
7 * Libav 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.
12 * Libav 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * libspeex Speex audio encoder
27 * This explains the values that need to be set prior to initialization in
28 * order to control various encoding parameters.
31 * Speex only supports mono or stereo, so avctx->channels must be set to
34 * Sample Rate / Encoding Mode
35 * Speex has 3 modes, each of which uses a specific sample rate.
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.
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
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
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.
68 * Speex encoder supports several optional features, which can be useful
69 * for some conditions.
71 * Voice Activity Detection
72 * When enabled, voice activity detection detects whether the audio
73 * being encoded is speech or silence/background noise. VAD is always
74 * implicitly activated when encoding in VBR, so the option is only useful
75 * in non-VBR operation. In this case, Speex detects non-speech periods and
76 * encodes them with just enough bits to reproduce the background noise.
78 * Discontinuous Transmission (DTX)
79 * DTX is an addition to VAD/VBR operation, that allows to stop transmitting
80 * completely when the background noise is stationary.
81 * In file-based operation only 5 bits are used for such frames.
84 #include <speex/speex.h>
85 #include <speex/speex_header.h>
86 #include <speex/speex_stereo.h>
88 #include "libavutil/channel_layout.h"
89 #include "libavutil/common.h"
90 #include "libavutil/opt.h"
93 #include "audio_frame_queue.h"
96 AVClass
*class; ///< AVClass for private options
97 SpeexBits bits
; ///< libspeex bitwriter context
98 SpeexHeader header
; ///< libspeex header struct
99 void *enc_state
; ///< libspeex encoder state
100 int frames_per_packet
; ///< number of frames to encode in each packet
101 float vbr_quality
; ///< VBR quality 0.0 to 10.0
102 int cbr_quality
; ///< CBR quality 0 to 10
103 int abr
; ///< flag to enable ABR
104 int vad
; ///< flag to enable VAD
105 int dtx
; ///< flag to enable DTX
106 int pkt_frame_count
; ///< frame count for the current packet
107 AudioFrameQueue afq
; ///< frame queue
108 } LibSpeexEncContext
;
110 static av_cold
void print_enc_params(AVCodecContext
*avctx
,
111 LibSpeexEncContext
*s
)
113 const char *mode_str
= "unknown";
115 av_log(avctx
, AV_LOG_DEBUG
, "channels: %d\n", avctx
->channels
);
116 switch (s
->header
.mode
) {
117 case SPEEX_MODEID_NB
: mode_str
= "narrowband"; break;
118 case SPEEX_MODEID_WB
: mode_str
= "wideband"; break;
119 case SPEEX_MODEID_UWB
: mode_str
= "ultra-wideband"; break;
121 av_log(avctx
, AV_LOG_DEBUG
, "mode: %s\n", mode_str
);
123 av_log(avctx
, AV_LOG_DEBUG
, "rate control: VBR\n");
124 av_log(avctx
, AV_LOG_DEBUG
, " quality: %f\n", s
->vbr_quality
);
126 av_log(avctx
, AV_LOG_DEBUG
, "rate control: ABR\n");
127 av_log(avctx
, AV_LOG_DEBUG
, " bitrate: %d bps\n", avctx
->bit_rate
);
129 av_log(avctx
, AV_LOG_DEBUG
, "rate control: CBR\n");
130 av_log(avctx
, AV_LOG_DEBUG
, " bitrate: %d bps\n", avctx
->bit_rate
);
132 av_log(avctx
, AV_LOG_DEBUG
, "complexity: %d\n",
133 avctx
->compression_level
);
134 av_log(avctx
, AV_LOG_DEBUG
, "frame size: %d samples\n",
136 av_log(avctx
, AV_LOG_DEBUG
, "frames per packet: %d\n",
137 s
->frames_per_packet
);
138 av_log(avctx
, AV_LOG_DEBUG
, "packet size: %d\n",
139 avctx
->frame_size
* s
->frames_per_packet
);
140 av_log(avctx
, AV_LOG_DEBUG
, "voice activity detection: %d\n", s
->vad
);
141 av_log(avctx
, AV_LOG_DEBUG
, "discontinuous transmission: %d\n", s
->dtx
);
144 static av_cold
int encode_init(AVCodecContext
*avctx
)
146 LibSpeexEncContext
*s
= avctx
->priv_data
;
147 const SpeexMode
*mode
;
148 uint8_t *header_data
;
153 if (avctx
->channels
< 1 || avctx
->channels
> 2) {
154 av_log(avctx
, AV_LOG_ERROR
, "Invalid channels (%d). Only stereo and "
155 "mono are supported\n", avctx
->channels
);
156 return AVERROR(EINVAL
);
159 /* sample rate and encoding mode */
160 switch (avctx
->sample_rate
) {
161 case 8000: mode
= &speex_nb_mode
; break;
162 case 16000: mode
= &speex_wb_mode
; break;
163 case 32000: mode
= &speex_uwb_mode
; break;
165 av_log(avctx
, AV_LOG_ERROR
, "Sample rate of %d Hz is not supported. "
166 "Resample to 8, 16, or 32 kHz.\n", avctx
->sample_rate
);
167 return AVERROR(EINVAL
);
170 /* initialize libspeex */
171 s
->enc_state
= speex_encoder_init(mode
);
173 av_log(avctx
, AV_LOG_ERROR
, "Error initializing libspeex\n");
176 speex_init_header(&s
->header
, avctx
->sample_rate
, avctx
->channels
, mode
);
178 /* rate control method and parameters */
179 if (avctx
->flags
& CODEC_FLAG_QSCALE
) {
182 s
->vad
= 1; /* VAD is always implicitly activated for VBR */
183 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_VBR
, &s
->header
.vbr
);
184 s
->vbr_quality
= av_clipf(avctx
->global_quality
/ (float)FF_QP2LAMBDA
,
186 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_VBR_QUALITY
, &s
->vbr_quality
);
188 s
->header
.bitrate
= avctx
->bit_rate
;
189 if (avctx
->bit_rate
> 0) {
190 /* CBR or ABR by bitrate */
192 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_ABR
,
194 speex_encoder_ctl(s
->enc_state
, SPEEX_GET_ABR
,
197 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_BITRATE
,
199 speex_encoder_ctl(s
->enc_state
, SPEEX_GET_BITRATE
,
204 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_QUALITY
,
206 speex_encoder_ctl(s
->enc_state
, SPEEX_GET_BITRATE
,
209 /* stereo side information adds about 800 bps to the base bitrate */
210 /* TODO: this should be calculated exactly */
211 avctx
->bit_rate
= s
->header
.bitrate
+ (avctx
->channels
== 2 ? 800 : 0);
214 /* VAD is activated with VBR or can be turned on by itself */
216 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_VAD
, &s
->vad
);
218 /* Activiting Discontinuous Transmission */
220 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_DTX
, &s
->dtx
);
221 if (!(s
->abr
|| s
->vad
|| s
->header
.vbr
))
222 av_log(avctx
, AV_LOG_WARNING
, "DTX is not much of use without ABR, VAD or VBR\n");
225 /* set encoding complexity */
226 if (avctx
->compression_level
> FF_COMPRESSION_DEFAULT
) {
227 complexity
= av_clip(avctx
->compression_level
, 0, 10);
228 speex_encoder_ctl(s
->enc_state
, SPEEX_SET_COMPLEXITY
, &complexity
);
230 speex_encoder_ctl(s
->enc_state
, SPEEX_GET_COMPLEXITY
, &complexity
);
231 avctx
->compression_level
= complexity
;
233 /* set packet size */
234 avctx
->frame_size
= s
->header
.frame_size
;
235 s
->header
.frames_per_packet
= s
->frames_per_packet
;
237 /* set encoding delay */
238 speex_encoder_ctl(s
->enc_state
, SPEEX_GET_LOOKAHEAD
, &avctx
->delay
);
239 ff_af_queue_init(avctx
, &s
->afq
);
241 /* create header packet bytes from header struct */
242 /* note: libspeex allocates the memory for header_data, which is freed
243 below with speex_header_free() */
244 header_data
= speex_header_to_packet(&s
->header
, &header_size
);
246 /* allocate extradata and coded_frame */
247 avctx
->extradata
= av_malloc(header_size
+ FF_INPUT_BUFFER_PADDING_SIZE
);
248 if (!avctx
->extradata
) {
249 speex_header_free(header_data
);
250 speex_encoder_destroy(s
->enc_state
);
251 av_log(avctx
, AV_LOG_ERROR
, "memory allocation error\n");
252 return AVERROR(ENOMEM
);
254 #if FF_API_OLD_ENCODE_AUDIO
255 avctx
->coded_frame
= avcodec_alloc_frame();
256 if (!avctx
->coded_frame
) {
257 av_freep(&avctx
->extradata
);
258 speex_header_free(header_data
);
259 speex_encoder_destroy(s
->enc_state
);
260 av_log(avctx
, AV_LOG_ERROR
, "memory allocation error\n");
261 return AVERROR(ENOMEM
);
265 /* copy header packet to extradata */
266 memcpy(avctx
->extradata
, header_data
, header_size
);
267 avctx
->extradata_size
= header_size
;
268 speex_header_free(header_data
);
270 /* init libspeex bitwriter */
271 speex_bits_init(&s
->bits
);
273 print_enc_params(avctx
, s
);
277 static int encode_frame(AVCodecContext
*avctx
, AVPacket
*avpkt
,
278 const AVFrame
*frame
, int *got_packet_ptr
)
280 LibSpeexEncContext
*s
= avctx
->priv_data
;
281 int16_t *samples
= frame
? (int16_t *)frame
->data
[0] : NULL
;
285 /* encode Speex frame */
286 if (avctx
->channels
== 2)
287 speex_encode_stereo_int(samples
, s
->header
.frame_size
, &s
->bits
);
288 speex_encode_int(s
->enc_state
, samples
, &s
->bits
);
289 s
->pkt_frame_count
++;
290 if ((ret
= ff_af_queue_add(&s
->afq
, frame
)) < 0)
293 /* handle end-of-stream */
294 if (!s
->pkt_frame_count
)
296 /* add extra terminator codes for unused frames in last packet */
297 while (s
->pkt_frame_count
< s
->frames_per_packet
) {
298 speex_bits_pack(&s
->bits
, 15, 5);
299 s
->pkt_frame_count
++;
303 /* write output if all frames for the packet have been encoded */
304 if (s
->pkt_frame_count
== s
->frames_per_packet
) {
305 s
->pkt_frame_count
= 0;
306 if ((ret
= ff_alloc_packet(avpkt
, speex_bits_nbytes(&s
->bits
)))) {
307 av_log(avctx
, AV_LOG_ERROR
, "Error getting output packet\n");
310 ret
= speex_bits_write(&s
->bits
, avpkt
->data
, avpkt
->size
);
311 speex_bits_reset(&s
->bits
);
313 /* Get the next frame pts/duration */
314 ff_af_queue_remove(&s
->afq
, s
->frames_per_packet
* avctx
->frame_size
,
315 &avpkt
->pts
, &avpkt
->duration
);
324 static av_cold
int encode_close(AVCodecContext
*avctx
)
326 LibSpeexEncContext
*s
= avctx
->priv_data
;
328 speex_bits_destroy(&s
->bits
);
329 speex_encoder_destroy(s
->enc_state
);
331 ff_af_queue_close(&s
->afq
);
332 #if FF_API_OLD_ENCODE_AUDIO
333 av_freep(&avctx
->coded_frame
);
335 av_freep(&avctx
->extradata
);
340 #define OFFSET(x) offsetof(LibSpeexEncContext, x)
341 #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
342 static const AVOption options
[] = {
343 { "abr", "Use average bit rate", OFFSET(abr
), AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, 1, AE
},
344 { "cbr_quality", "Set quality value (0 to 10) for CBR", OFFSET(cbr_quality
), AV_OPT_TYPE_INT
, { .i64
= 8 }, 0, 10, AE
},
345 { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet
), AV_OPT_TYPE_INT
, { .i64
= 1 }, 1, 8, AE
},
346 { "vad", "Voice Activity Detection", OFFSET(vad
), AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, 1, AE
},
347 { "dtx", "Discontinuous Transmission", OFFSET(dtx
), AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, 1, AE
},
351 static const AVClass
class = {
352 .class_name
= "libspeex",
353 .item_name
= av_default_item_name
,
355 .version
= LIBAVUTIL_VERSION_INT
,
358 static const AVCodecDefault defaults
[] = {
360 { "compression_level", "3" },
364 AVCodec ff_libspeex_encoder
= {
366 .type
= AVMEDIA_TYPE_AUDIO
,
367 .id
= AV_CODEC_ID_SPEEX
,
368 .priv_data_size
= sizeof(LibSpeexEncContext
),
370 .encode2
= encode_frame
,
371 .close
= encode_close
,
372 .capabilities
= CODEC_CAP_DELAY
,
373 .sample_fmts
= (const enum AVSampleFormat
[]){ AV_SAMPLE_FMT_S16
,
374 AV_SAMPLE_FMT_NONE
},
375 .channel_layouts
= (const uint64_t[]){ AV_CH_LAYOUT_MONO
,
378 .supported_samplerates
= (const int[]){ 8000, 16000, 32000, 0 },
379 .long_name
= NULL_IF_CONFIG_SMALL("libspeex Speex"),
380 .priv_class
= &class,
381 .defaults
= defaults
,