]> git.sesse.net Git - ffmpeg/blob - libavcodec/libspeexenc.c
libspeexdec: move the SpeexHeader from LibSpeexContext to where it is used
[ffmpeg] / libavcodec / libspeexenc.c
1 /*
2  * Copyright (C) 2009 Justin Ruggles
3  * Copyright (c) 2009 Xuggle Incorporated
4  *
5  * This file is part of Libav.
6  *
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.
11  *
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.
16  *
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
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
71 #include "libavutil/audioconvert.h"
72 #include "libavutil/common.h"
73 #include "libavutil/opt.h"
74 #include "avcodec.h"
75 #include "internal.h"
76 #include "audio_frame_queue.h"
77
78 typedef struct {
79     AVClass *class;             ///< AVClass for private options
80     SpeexBits bits;             ///< libspeex bitwriter context
81     SpeexHeader header;         ///< libspeex header struct
82     void *enc_state;            ///< libspeex encoder state
83     int frames_per_packet;      ///< number of frames to encode in each packet
84     float vbr_quality;          ///< VBR quality 0.0 to 10.0
85     int cbr_quality;            ///< CBR quality 0 to 10
86     int abr;                    ///< flag to enable ABR
87     int vad;                    ///< flag to enable VAD
88     int pkt_frame_count;        ///< frame count for the current packet
89     AudioFrameQueue afq;        ///< frame queue
90 } LibSpeexEncContext;
91
92 static av_cold void print_enc_params(AVCodecContext *avctx,
93                                      LibSpeexEncContext *s)
94 {
95     const char *mode_str = "unknown";
96
97     av_log(avctx, AV_LOG_DEBUG, "channels: %d\n", avctx->channels);
98     switch (s->header.mode) {
99     case SPEEX_MODEID_NB:  mode_str = "narrowband";     break;
100     case SPEEX_MODEID_WB:  mode_str = "wideband";       break;
101     case SPEEX_MODEID_UWB: mode_str = "ultra-wideband"; break;
102     }
103     av_log(avctx, AV_LOG_DEBUG, "mode: %s\n", mode_str);
104     if (s->header.vbr) {
105         av_log(avctx, AV_LOG_DEBUG, "rate control: VBR\n");
106         av_log(avctx, AV_LOG_DEBUG, "  quality: %f\n", s->vbr_quality);
107     } else if (s->abr) {
108         av_log(avctx, AV_LOG_DEBUG, "rate control: ABR\n");
109         av_log(avctx, AV_LOG_DEBUG, "  bitrate: %d bps\n", avctx->bit_rate);
110     } else {
111         av_log(avctx, AV_LOG_DEBUG, "rate control: CBR\n");
112         av_log(avctx, AV_LOG_DEBUG, "  bitrate: %d bps\n", avctx->bit_rate);
113     }
114     av_log(avctx, AV_LOG_DEBUG, "complexity: %d\n",
115            avctx->compression_level);
116     av_log(avctx, AV_LOG_DEBUG, "frame size: %d samples\n",
117            avctx->frame_size);
118     av_log(avctx, AV_LOG_DEBUG, "frames per packet: %d\n",
119            s->frames_per_packet);
120     av_log(avctx, AV_LOG_DEBUG, "packet size: %d\n",
121            avctx->frame_size * s->frames_per_packet);
122     av_log(avctx, AV_LOG_DEBUG, "voice activity detection: %d\n", s->vad);
123 }
124
125 static av_cold int encode_init(AVCodecContext *avctx)
126 {
127     LibSpeexEncContext *s = avctx->priv_data;
128     const SpeexMode *mode;
129     uint8_t *header_data;
130     int header_size;
131     int32_t complexity;
132
133     /* channels */
134     if (avctx->channels < 1 || avctx->channels > 2) {
135         av_log(avctx, AV_LOG_ERROR, "Invalid channels (%d). Only stereo and "
136                "mono are supported\n", avctx->channels);
137         return AVERROR(EINVAL);
138     }
139
140     /* sample rate and encoding mode */
141     switch (avctx->sample_rate) {
142     case  8000: mode = &speex_nb_mode;  break;
143     case 16000: mode = &speex_wb_mode;  break;
144     case 32000: mode = &speex_uwb_mode; break;
145     default:
146         av_log(avctx, AV_LOG_ERROR, "Sample rate of %d Hz is not supported. "
147                "Resample to 8, 16, or 32 kHz.\n", avctx->sample_rate);
148         return AVERROR(EINVAL);
149     }
150
151     /* initialize libspeex */
152     s->enc_state = speex_encoder_init(mode);
153     if (!s->enc_state) {
154         av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex\n");
155         return -1;
156     }
157     speex_init_header(&s->header, avctx->sample_rate, avctx->channels, mode);
158
159     /* rate control method and parameters */
160     if (avctx->flags & CODEC_FLAG_QSCALE) {
161         /* VBR */
162         s->header.vbr = 1;
163         s->vad = 1; /* VAD is always implicitly activated for VBR */
164         speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR, &s->header.vbr);
165         s->vbr_quality = av_clipf(avctx->global_quality / (float)FF_QP2LAMBDA,
166                                   0.0f, 10.0f);
167         speex_encoder_ctl(s->enc_state, SPEEX_SET_VBR_QUALITY, &s->vbr_quality);
168     } else {
169         s->header.bitrate = avctx->bit_rate;
170         if (avctx->bit_rate > 0) {
171             /* CBR or ABR by bitrate */
172             if (s->abr) {
173                 speex_encoder_ctl(s->enc_state, SPEEX_SET_ABR,
174                                   &s->header.bitrate);
175                 speex_encoder_ctl(s->enc_state, SPEEX_GET_ABR,
176                                   &s->header.bitrate);
177             } else {
178                 speex_encoder_ctl(s->enc_state, SPEEX_SET_BITRATE,
179                                   &s->header.bitrate);
180                 speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
181                                   &s->header.bitrate);
182             }
183         } else {
184             /* CBR by quality */
185             speex_encoder_ctl(s->enc_state, SPEEX_SET_QUALITY,
186                               &s->cbr_quality);
187             speex_encoder_ctl(s->enc_state, SPEEX_GET_BITRATE,
188                               &s->header.bitrate);
189         }
190         /* stereo side information adds about 800 bps to the base bitrate */
191         /* TODO: this should be calculated exactly */
192         avctx->bit_rate = s->header.bitrate + (avctx->channels == 2 ? 800 : 0);
193     }
194
195     /* VAD is activated with VBR or can be turned on by itself */
196     if (s->vad)
197         speex_encoder_ctl(s->enc_state, SPEEX_SET_VAD, &s->vad);
198
199     /* set encoding complexity */
200     if (avctx->compression_level > FF_COMPRESSION_DEFAULT) {
201         complexity = av_clip(avctx->compression_level, 0, 10);
202         speex_encoder_ctl(s->enc_state, SPEEX_SET_COMPLEXITY, &complexity);
203     }
204     speex_encoder_ctl(s->enc_state, SPEEX_GET_COMPLEXITY, &complexity);
205     avctx->compression_level = complexity;
206
207     /* set packet size */
208     avctx->frame_size = s->header.frame_size;
209     s->header.frames_per_packet = s->frames_per_packet;
210
211     /* set encoding delay */
212     speex_encoder_ctl(s->enc_state, SPEEX_GET_LOOKAHEAD, &avctx->delay);
213     ff_af_queue_init(avctx, &s->afq);
214
215     /* create header packet bytes from header struct */
216     /* note: libspeex allocates the memory for header_data, which is freed
217              below with speex_header_free() */
218     header_data = speex_header_to_packet(&s->header, &header_size);
219
220     /* allocate extradata and coded_frame */
221     avctx->extradata   = av_malloc(header_size + FF_INPUT_BUFFER_PADDING_SIZE);
222     if (!avctx->extradata) {
223         speex_header_free(header_data);
224         speex_encoder_destroy(s->enc_state);
225         av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
226         return AVERROR(ENOMEM);
227     }
228 #if FF_API_OLD_ENCODE_AUDIO
229     avctx->coded_frame = avcodec_alloc_frame();
230     if (!avctx->coded_frame) {
231         av_freep(&avctx->extradata);
232         speex_header_free(header_data);
233         speex_encoder_destroy(s->enc_state);
234         av_log(avctx, AV_LOG_ERROR, "memory allocation error\n");
235         return AVERROR(ENOMEM);
236     }
237 #endif
238
239     /* copy header packet to extradata */
240     memcpy(avctx->extradata, header_data, header_size);
241     avctx->extradata_size = header_size;
242     speex_header_free(header_data);
243
244     /* init libspeex bitwriter */
245     speex_bits_init(&s->bits);
246
247     print_enc_params(avctx, s);
248     return 0;
249 }
250
251 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
252                         const AVFrame *frame, int *got_packet_ptr)
253 {
254     LibSpeexEncContext *s = avctx->priv_data;
255     int16_t *samples      = frame ? (int16_t *)frame->data[0] : NULL;
256     int ret;
257
258     if (samples) {
259         /* encode Speex frame */
260         if (avctx->channels == 2)
261             speex_encode_stereo_int(samples, s->header.frame_size, &s->bits);
262         speex_encode_int(s->enc_state, samples, &s->bits);
263         s->pkt_frame_count++;
264         if ((ret = ff_af_queue_add(&s->afq, frame) < 0))
265             return ret;
266     } else {
267         /* handle end-of-stream */
268         if (!s->pkt_frame_count)
269             return 0;
270         /* add extra terminator codes for unused frames in last packet */
271         while (s->pkt_frame_count < s->frames_per_packet) {
272             speex_bits_pack(&s->bits, 15, 5);
273             s->pkt_frame_count++;
274         }
275     }
276
277     /* write output if all frames for the packet have been encoded */
278     if (s->pkt_frame_count == s->frames_per_packet) {
279         s->pkt_frame_count = 0;
280         if ((ret = ff_alloc_packet(avpkt, speex_bits_nbytes(&s->bits)))) {
281             av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
282             return ret;
283         }
284         ret = speex_bits_write(&s->bits, avpkt->data, avpkt->size);
285         speex_bits_reset(&s->bits);
286
287         /* Get the next frame pts/duration */
288         ff_af_queue_remove(&s->afq, s->frames_per_packet * avctx->frame_size,
289                            &avpkt->pts, &avpkt->duration);
290
291         avpkt->size = ret;
292         *got_packet_ptr = 1;
293         return 0;
294     }
295     return 0;
296 }
297
298 static av_cold int encode_close(AVCodecContext *avctx)
299 {
300     LibSpeexEncContext *s = avctx->priv_data;
301
302     speex_bits_destroy(&s->bits);
303     speex_encoder_destroy(s->enc_state);
304
305     ff_af_queue_close(&s->afq);
306 #if FF_API_OLD_ENCODE_AUDIO
307     av_freep(&avctx->coded_frame);
308 #endif
309     av_freep(&avctx->extradata);
310
311     return 0;
312 }
313
314 #define OFFSET(x) offsetof(LibSpeexEncContext, x)
315 #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
316 static const AVOption options[] = {
317     { "abr",               "Use average bit rate",                      OFFSET(abr),               AV_OPT_TYPE_INT, { .i64 = 0 }, 0,   1, AE },
318     { "cbr_quality",       "Set quality value (0 to 10) for CBR",       OFFSET(cbr_quality),       AV_OPT_TYPE_INT, { .i64 = 8 }, 0,  10, AE },
319     { "frames_per_packet", "Number of frames to encode in each packet", OFFSET(frames_per_packet), AV_OPT_TYPE_INT, { .i64 = 1 }, 1,   8, AE },
320     { "vad",               "Voice Activity Detection",                  OFFSET(vad),               AV_OPT_TYPE_INT, { .i64 = 0 }, 0,   1, AE },
321     { NULL },
322 };
323
324 static const AVClass class = {
325     .class_name = "libspeex",
326     .item_name  = av_default_item_name,
327     .option     = options,
328     .version    = LIBAVUTIL_VERSION_INT,
329 };
330
331 static const AVCodecDefault defaults[] = {
332     { "b",                 "0" },
333     { "compression_level", "3" },
334     { NULL },
335 };
336
337 AVCodec ff_libspeex_encoder = {
338     .name           = "libspeex",
339     .type           = AVMEDIA_TYPE_AUDIO,
340     .id             = AV_CODEC_ID_SPEEX,
341     .priv_data_size = sizeof(LibSpeexEncContext),
342     .init           = encode_init,
343     .encode2        = encode_frame,
344     .close          = encode_close,
345     .capabilities   = CODEC_CAP_DELAY,
346     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
347                                                      AV_SAMPLE_FMT_NONE },
348     .channel_layouts = (const uint64_t[]){ AV_CH_LAYOUT_MONO,
349                                            AV_CH_LAYOUT_STEREO,
350                                            0 },
351     .supported_samplerates = (const int[]){ 8000, 16000, 32000, 0 },
352     .long_name      = NULL_IF_CONFIG_SMALL("libspeex Speex"),
353     .priv_class     = &class,
354     .defaults       = defaults,
355 };