1/*
2 * Copyright (C) 2008 David Conrad
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <speex/speex.h>
22#include <speex/speex_header.h>
23#include <speex/speex_stereo.h>
24#include <speex/speex_callbacks.h>
25
26#include "libavutil/channel_layout.h"
27#include "libavutil/common.h"
28#include "avcodec.h"
29#include "codec_internal.h"
30#include "internal.h"
31
32typedef struct LibSpeexContext {
33    SpeexBits bits;
34    SpeexStereoState stereo;
35    void *dec_state;
36    int frame_size;
37    int pktsize;
38} LibSpeexContext;
39
40
41static av_cold int libspeex_decode_init(AVCodecContext *avctx)
42{
43    LibSpeexContext *s = avctx->priv_data;
44    const SpeexMode *mode;
45    SpeexHeader *header = NULL;
46    int spx_mode, channels = avctx->ch_layout.nb_channels;
47
48    if (avctx->extradata && avctx->extradata_size >= 80) {
49        header = speex_packet_to_header(avctx->extradata,
50                                        avctx->extradata_size);
51        if (!header)
52            av_log(avctx, AV_LOG_WARNING, "Invalid Speex header\n");
53    }
54    if (avctx->codec_tag == MKTAG('S', 'P', 'X', 'N')) {
55        int quality;
56        if (!avctx->extradata || avctx->extradata && avctx->extradata_size < 47) {
57            av_log(avctx, AV_LOG_ERROR, "Missing or invalid extradata.\n");
58            return AVERROR_INVALIDDATA;
59        }
60
61        quality = avctx->extradata[37];
62        if (quality > 10) {
63            av_log(avctx, AV_LOG_ERROR, "Unsupported quality mode %d.\n", quality);
64            return AVERROR_PATCHWELCOME;
65        }
66
67        s->pktsize = ((const int[]){5,10,15,20,20,28,28,38,38,46,62})[quality];
68
69        spx_mode           = 0;
70    } else if (header) {
71        avctx->sample_rate = header->rate;
72        channels           = header->nb_channels;
73        spx_mode           = header->mode;
74        speex_header_free(header);
75    } else {
76        switch (avctx->sample_rate) {
77        case 8000:  spx_mode = 0; break;
78        case 16000: spx_mode = 1; break;
79        case 32000: spx_mode = 2; break;
80        default:
81            /* libspeex can handle any mode if initialized as ultra-wideband */
82            av_log(avctx, AV_LOG_WARNING, "Invalid sample rate: %d\n"
83                                          "Decoding as 32kHz ultra-wideband\n",
84                                          avctx->sample_rate);
85            spx_mode = 2;
86        }
87    }
88
89    mode = speex_lib_get_mode(spx_mode);
90    if (!mode) {
91        av_log(avctx, AV_LOG_ERROR, "Unknown Speex mode %d", spx_mode);
92        return AVERROR_INVALIDDATA;
93    }
94    s->frame_size      =  160 << spx_mode;
95    if (!avctx->sample_rate)
96        avctx->sample_rate = 8000 << spx_mode;
97
98    if (channels < 1 || channels > 2) {
99        /* libspeex can handle mono or stereo if initialized as stereo */
100        av_log(avctx, AV_LOG_ERROR, "Invalid channel count: %d.\n"
101                                    "Decoding as stereo.\n", channels);
102        channels = 2;
103    }
104    av_channel_layout_uninit(&avctx->ch_layout);
105    avctx->ch_layout = channels == 2 ? (AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO :
106                                       (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO;
107
108    speex_bits_init(&s->bits);
109    s->dec_state = speex_decoder_init(mode);
110    if (!s->dec_state) {
111        av_log(avctx, AV_LOG_ERROR, "Error initializing libspeex decoder.\n");
112        return -1;
113    }
114
115    if (channels == 2) {
116        SpeexCallback callback;
117        callback.callback_id = SPEEX_INBAND_STEREO;
118        callback.func = speex_std_stereo_request_handler;
119        callback.data = &s->stereo;
120        s->stereo = (SpeexStereoState)SPEEX_STEREO_STATE_INIT;
121        speex_decoder_ctl(s->dec_state, SPEEX_SET_HANDLER, &callback);
122    }
123
124    return 0;
125}
126
127static int libspeex_decode_frame(AVCodecContext *avctx, AVFrame *frame,
128                                 int *got_frame_ptr, AVPacket *avpkt)
129{
130    uint8_t *buf = avpkt->data;
131    int buf_size = avpkt->size;
132    LibSpeexContext *s = avctx->priv_data;
133    int16_t *output;
134    int ret, consumed = 0;
135    avctx->sample_fmt = AV_SAMPLE_FMT_S16;
136
137    /* get output buffer */
138    frame->nb_samples = s->frame_size;
139    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
140        return ret;
141    output = (int16_t *)frame->data[0];
142
143    /* if there is not enough data left for the smallest possible frame or the
144       next 5 bits are a terminator code, reset the libspeex buffer using the
145       current packet, otherwise ignore the current packet and keep decoding
146       frames from the libspeex buffer. */
147    if (speex_bits_remaining(&s->bits) < 5 ||
148        speex_bits_peek_unsigned(&s->bits, 5) == 0xF) {
149        /* check for flush packet */
150        if (!buf || !buf_size) {
151            *got_frame_ptr = 0;
152            return buf_size;
153        }
154        if (s->pktsize && buf_size == 62)
155            buf_size = s->pktsize;
156        /* set new buffer */
157        speex_bits_read_from(&s->bits, buf, buf_size);
158        consumed = avpkt->size;
159    }
160
161    /* decode a single frame */
162    ret = speex_decode_int(s->dec_state, &s->bits, output);
163    if (ret <= -2) {
164        av_log(avctx, AV_LOG_ERROR, "Error decoding Speex frame.\n");
165        return AVERROR_INVALIDDATA;
166    }
167    if (avctx->ch_layout.nb_channels == 2)
168        speex_decode_stereo_int(output, s->frame_size, &s->stereo);
169
170    *got_frame_ptr = 1;
171
172    if (!avctx->bit_rate)
173        speex_decoder_ctl(s->dec_state, SPEEX_GET_BITRATE, &avctx->bit_rate);
174    return consumed;
175}
176
177static av_cold int libspeex_decode_close(AVCodecContext *avctx)
178{
179    LibSpeexContext *s = avctx->priv_data;
180
181    speex_bits_destroy(&s->bits);
182    speex_decoder_destroy(s->dec_state);
183
184    return 0;
185}
186
187static av_cold void libspeex_decode_flush(AVCodecContext *avctx)
188{
189    LibSpeexContext *s = avctx->priv_data;
190    speex_bits_reset(&s->bits);
191}
192
193const FFCodec ff_libspeex_decoder = {
194    .p.name         = "libspeex",
195    .p.long_name    = NULL_IF_CONFIG_SMALL("libspeex Speex"),
196    .p.type         = AVMEDIA_TYPE_AUDIO,
197    .p.id           = AV_CODEC_ID_SPEEX,
198    .p.capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1 | AV_CODEC_CAP_CHANNEL_CONF,
199    .p.wrapper_name = "libspeex",
200    .priv_data_size = sizeof(LibSpeexContext),
201    .init           = libspeex_decode_init,
202    .close          = libspeex_decode_close,
203    FF_CODEC_DECODE_CB(libspeex_decode_frame),
204    .flush          = libspeex_decode_flush,
205};
206