]> git.sesse.net Git - ffmpeg/blob - libavcodec/g729dec.c
Add packet_type
[ffmpeg] / libavcodec / g729dec.c
1 /*
2  * G.729 decoder
3  * Copyright (c) 2008 Vladimir Voroshilov
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 #include <stdlib.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <math.h>
27 #include <assert.h>
28
29 #include "avcodec.h"
30 #include "libavutil/avutil.h"
31 #include "get_bits.h"
32
33 #include "g729.h"
34 #include "lsp.h"
35 #include "celp_math.h"
36 #include "acelp_filters.h"
37 #include "acelp_pitch_delay.h"
38 #include "acelp_vectors.h"
39 #include "g729data.h"
40
41 /**
42  * minimum quantized LSF value (3.2.4)
43  * 0.005 in Q13
44  */
45 #define LSFQ_MIN                   40
46
47 /**
48  * maximum quantized LSF value (3.2.4)
49  * 3.135 in Q13
50  */
51 #define LSFQ_MAX                   25681
52
53 /**
54  * minimum LSF distance (3.2.4)
55  * 0.0391 in Q13
56  */
57 #define LSFQ_DIFF_MIN              321
58
59 /**
60  * minimum gain pitch value (3.8, Equation 47)
61  * 0.2 in (1.14)
62  */
63 #define SHARP_MIN                  3277
64
65 /**
66  * maximum gain pitch value (3.8, Equation 47)
67  * (EE) This does not comply with the specification.
68  * Specification says about 0.8, which should be
69  * 13107 in (1.14), but reference C code uses
70  * 13017 (equals to 0.7945) instead of it.
71  */
72 #define SHARP_MAX                  13017
73
74 typedef enum {
75     FORMAT_G729_8K = 0,
76     FORMAT_G729D_6K4,
77     FORMAT_COUNT,
78 } G729Formats;
79
80 typedef struct {
81     uint8_t ac_index_bits[2];   ///< adaptive codebook index for second subframe (size in bits)
82     uint8_t parity_bit;         ///< parity bit for pitch delay
83     uint8_t gc_1st_index_bits;  ///< gain codebook (first stage) index (size in bits)
84     uint8_t gc_2nd_index_bits;  ///< gain codebook (second stage) index (size in bits)
85     uint8_t fc_signs_bits;      ///< number of pulses in fixed-codebook vector
86     uint8_t fc_indexes_bits;    ///< size (in bits) of fixed-codebook index entry
87 } G729FormatDescription;
88
89 typedef struct {
90     int pitch_delay_int_prev;   ///< integer part of previous subframe's pitch delay (4.1.3)
91
92     /// (2.13) LSP quantizer outputs
93     int16_t  past_quantizer_output_buf[MA_NP + 1][10];
94     int16_t* past_quantizer_outputs[MA_NP + 1];
95
96     int16_t lsfq[10];           ///< (2.13) quantized LSF coefficients from previous frame
97     int16_t lsp_buf[2][10];     ///< (0.15) LSP coefficients (previous and current frames) (3.2.5)
98     int16_t *lsp[2];            ///< pointers to lsp_buf
99
100     int ma_predictor_prev;      ///< switched MA predictor of LSP quantizer from last good frame
101 }  G729Context;
102
103 static const G729FormatDescription format_g729_8k = {
104     .ac_index_bits     = {8,5},
105     .parity_bit        = 1,
106     .gc_1st_index_bits = GC_1ST_IDX_BITS_8K,
107     .gc_2nd_index_bits = GC_2ND_IDX_BITS_8K,
108     .fc_signs_bits     = 4,
109     .fc_indexes_bits   = 13,
110 };
111
112 static const G729FormatDescription format_g729d_6k4 = {
113     .ac_index_bits     = {8,4},
114     .parity_bit        = 0,
115     .gc_1st_index_bits = GC_1ST_IDX_BITS_6K4,
116     .gc_2nd_index_bits = GC_2ND_IDX_BITS_6K4,
117     .fc_signs_bits     = 2,
118     .fc_indexes_bits   = 9,
119 };
120
121 /**
122  * @brief pseudo random number generator
123  */
124 static inline uint16_t g729_prng(uint16_t value)
125 {
126     return 31821 * value + 13849;
127 }
128
129 /**
130  * Get parity bit of bit 2..7
131  */
132 static inline int get_parity(uint8_t value)
133 {
134    return (0x6996966996696996ULL >> (value >> 2)) & 1;
135 }
136
137 /*
138  * Decodes LSF (Line Spectral Frequencies) from L0-L3 (3.2.4).
139  * @param lsfq [out] (2.13) quantized LSF coefficients
140  * @param past_quantizer_outputs [in/out] (2.13) quantizer outputs from previous frames
141  * @param ma_predictor switched MA predictor of LSP quantizer
142  * @param vq_1st first stage vector of quantizer
143  * @param vq_2nd_low second stage lower vector of LSP quantizer
144  * @param vq_2nd_high second stage higher vector of LSP quantizer
145  */
146 static void lsf_decode(int16_t* lsfq, int16_t* past_quantizer_outputs[MA_NP + 1],
147                        int16_t ma_predictor,
148                        int16_t vq_1st, int16_t vq_2nd_low, int16_t vq_2nd_high)
149 {
150     int i,j;
151     static const uint8_t min_distance[2]={10, 5}; //(2.13)
152     int16_t* quantizer_output = past_quantizer_outputs[MA_NP];
153
154     for (i = 0; i < 5; i++) {
155         quantizer_output[i]     = cb_lsp_1st[vq_1st][i    ] + cb_lsp_2nd[vq_2nd_low ][i    ];
156         quantizer_output[i + 5] = cb_lsp_1st[vq_1st][i + 5] + cb_lsp_2nd[vq_2nd_high][i + 5];
157     }
158
159     for (j = 0; j < 2; j++) {
160         for (i = 1; i < 10; i++) {
161             int diff = (quantizer_output[i - 1] - quantizer_output[i] + min_distance[j]) >> 1;
162             if (diff > 0) {
163                 quantizer_output[i - 1] -= diff;
164                 quantizer_output[i    ] += diff;
165             }
166         }
167     }
168
169     for (i = 0; i < 10; i++) {
170         int sum = quantizer_output[i] * cb_ma_predictor_sum[ma_predictor][i];
171         for (j = 0; j < MA_NP; j++)
172             sum += past_quantizer_outputs[j][i] * cb_ma_predictor[ma_predictor][j][i];
173
174         lsfq[i] = sum >> 15;
175     }
176
177     ff_acelp_reorder_lsf(lsfq, LSFQ_DIFF_MIN, LSFQ_MIN, LSFQ_MAX, 10);
178 }
179
180 /**
181  * Restores past LSP quantizer output using LSF from previous frame
182  * @param lsfq [in/out] (2.13) quantized LSF coefficients
183  * @param past_quantizer_outputs [in/out] (2.13) quantizer outputs from previous frames
184  * @param ma_predictor_prev MA predictor from previous frame
185  * @param lsfq_prev (2.13) quantized LSF coefficients from previous frame
186  */
187 static void lsf_restore_from_previous(int16_t* lsfq,
188                                       int16_t* past_quantizer_outputs[MA_NP + 1],
189                                       int ma_predictor_prev)
190 {
191     int16_t* quantizer_output = past_quantizer_outputs[MA_NP];
192     int i,k;
193
194     for (i = 0; i < 10; i++) {
195         int tmp = lsfq[i] << 15;
196
197         for (k = 0; k < MA_NP; k++)
198             tmp -= past_quantizer_outputs[k][i] * cb_ma_predictor[ma_predictor_prev][k][i];
199
200         quantizer_output[i] = ((tmp >> 15) * cb_ma_predictor_sum_inv[ma_predictor_prev][i]) >> 12;
201     }
202 }
203
204 static av_cold int decoder_init(AVCodecContext * avctx)
205 {
206     G729Context* ctx = avctx->priv_data;
207     int i,k;
208
209     if (avctx->channels != 1) {
210         av_log(avctx, AV_LOG_ERROR, "Only mono sound is supported (requested channels: %d).\n", avctx->channels);
211         return AVERROR(EINVAL);
212     }
213
214     /* Both 8kbit/s and 6.4kbit/s modes uses two subframes per frame. */
215     avctx->frame_size = SUBFRAME_SIZE << 1;
216
217     for (k = 0; k < MA_NP + 1; k++) {
218         ctx->past_quantizer_outputs[k] = ctx->past_quantizer_output_buf[k];
219         for (i = 1; i < 11; i++)
220             ctx->past_quantizer_outputs[k][i - 1] = (18717 * i) >> 3;
221     }
222
223     ctx->lsp[0] = ctx->lsp_buf[0];
224     ctx->lsp[1] = ctx->lsp_buf[1];
225     memcpy(ctx->lsp[0], lsp_init, 10 * sizeof(int16_t));
226
227     return 0;
228 }
229
230 static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,
231                         AVPacket *avpkt)
232 {
233     const uint8_t *buf = avpkt->data;
234     int buf_size       = avpkt->size;
235     int16_t *out_frame = data;
236     GetBitContext gb;
237     G729FormatDescription format;
238     int frame_erasure = 0;    ///< frame erasure detected during decoding
239     int bad_pitch = 0;        ///< parity check failed
240     int i;
241     int16_t *tmp;
242     G729Formats packet_type;
243     G729Context *ctx = avctx->priv_data;
244     int16_t lp[2][11];           // (3.12)
245     uint8_t ma_predictor;     ///< switched MA predictor of LSP quantizer
246     uint8_t quantizer_1st;    ///< first stage vector of quantizer
247     uint8_t quantizer_2nd_lo; ///< second stage lower vector of quantizer (size in bits)
248     uint8_t quantizer_2nd_hi; ///< second stage higher vector of quantizer (size in bits)
249
250     int pitch_delay_int;         // pitch delay, integer part
251     int pitch_delay_3x;          // pitch delay, multiplied by 3
252
253     if (*data_size < SUBFRAME_SIZE << 2) {
254         av_log(avctx, AV_LOG_ERROR, "Error processing packet: output buffer too small\n");
255         return AVERROR(EIO);
256     }
257
258     if (buf_size == 10) {
259         packet_type = FORMAT_G729_8K;
260         format = format_g729_8k;
261         av_log(avctx, AV_LOG_DEBUG, "Packet type: %s\n", "G.729 @ 8kbit/s");
262     } else if (buf_size == 8) {
263         packet_type = FORMAT_G729D_6K4;
264         format = format_g729d_6k4;
265         av_log(avctx, AV_LOG_DEBUG, "Packet type: %s\n", "G.729D @ 6.4kbit/s");
266     } else {
267         av_log(avctx, AV_LOG_ERROR, "Packet size %d is unknown.\n", buf_size);
268         return AVERROR_INVALIDDATA;
269     }
270
271     for (i=0; i < buf_size; i++)
272         frame_erasure |= buf[i];
273     frame_erasure = !frame_erasure;
274
275     init_get_bits(&gb, buf, buf_size);
276
277     ma_predictor     = get_bits(&gb, 1);
278     quantizer_1st    = get_bits(&gb, VQ_1ST_BITS);
279     quantizer_2nd_lo = get_bits(&gb, VQ_2ND_BITS);
280     quantizer_2nd_hi = get_bits(&gb, VQ_2ND_BITS);
281
282     if(frame_erasure)
283         lsf_restore_from_previous(ctx->lsfq, ctx->past_quantizer_outputs,
284                                   ctx->ma_predictor_prev);
285     else {
286         lsf_decode(ctx->lsfq, ctx->past_quantizer_outputs,
287                    ma_predictor,
288                    quantizer_1st, quantizer_2nd_lo, quantizer_2nd_hi);
289         ctx->ma_predictor_prev = ma_predictor;
290     }
291
292     tmp = ctx->past_quantizer_outputs[MA_NP];
293     memmove(ctx->past_quantizer_outputs + 1, ctx->past_quantizer_outputs,
294             MA_NP * sizeof(int16_t*));
295     ctx->past_quantizer_outputs[0] = tmp;
296
297     ff_acelp_lsf2lsp(ctx->lsp[1], ctx->lsfq, 10);
298
299     ff_acelp_lp_decode(&lp[0][0], &lp[1][0], ctx->lsp[1], ctx->lsp[0], 10);
300
301     FFSWAP(int16_t*, ctx->lsp[1], ctx->lsp[0]);
302
303     for (i = 0; i < 2; i++) {
304         uint8_t ac_index;      ///< adaptive codebook index
305         uint8_t pulses_signs;  ///< fixed-codebook vector pulse signs
306         int fc_indexes;        ///< fixed-codebook indexes
307         uint8_t gc_1st_index;  ///< gain codebook (first stage) index
308         uint8_t gc_2nd_index;  ///< gain codebook (second stage) index
309
310         ac_index      = get_bits(&gb, format.ac_index_bits[i]);
311         if(!i && format.parity_bit)
312             bad_pitch = get_parity(ac_index) == get_bits1(&gb);
313         fc_indexes    = get_bits(&gb, format.fc_indexes_bits);
314         pulses_signs  = get_bits(&gb, format.fc_signs_bits);
315         gc_1st_index  = get_bits(&gb, format.gc_1st_index_bits);
316         gc_2nd_index  = get_bits(&gb, format.gc_2nd_index_bits);
317
318         if (frame_erasure)
319             pitch_delay_3x   = 3 * ctx->pitch_delay_int_prev;
320         else if(!i) {
321             if (bad_pitch)
322                 pitch_delay_3x   = 3 * ctx->pitch_delay_int_prev;
323             else
324                 pitch_delay_3x = ff_acelp_decode_8bit_to_1st_delay3(ac_index);
325         } else {
326             int pitch_delay_min = av_clip(ctx->pitch_delay_int_prev - 5,
327                                           PITCH_DELAY_MIN, PITCH_DELAY_MAX - 9);
328
329             if(packet_type == FORMAT_G729D_6K4)
330                 pitch_delay_3x = ff_acelp_decode_4bit_to_2nd_delay3(ac_index, pitch_delay_min);
331             else
332                 pitch_delay_3x = ff_acelp_decode_5_6_bit_to_2nd_delay3(ac_index, pitch_delay_min);
333         }
334
335         /* Round pitch delay to nearest (used everywhere except ff_acelp_interpolate). */
336         pitch_delay_int  = (pitch_delay_3x + 1) / 3;
337
338         ff_acelp_weighted_vector_sum(fc + pitch_delay_int,
339                                      fc + pitch_delay_int,
340                                      fc, 1 << 14,
341                                      av_clip(ctx->gain_pitch, SHARP_MIN, SHARP_MAX),
342                                      0, 14,
343                                      SUBFRAME_SIZE - pitch_delay_int);
344
345         if (frame_erasure) {
346             ctx->gain_pitch = (29491 * ctx->gain_pitch) >> 15; // 0.90 (0.15)
347             ctx->gain_code  = ( 2007 * ctx->gain_code ) >> 11; // 0.98 (0.11)
348
349             gain_corr_factor = 0;
350         } else {
351             ctx->gain_pitch  = cb_gain_1st_8k[gc_1st_index][0] +
352                                cb_gain_2nd_8k[gc_2nd_index][0];
353             gain_corr_factor = cb_gain_1st_8k[gc_1st_index][1] +
354                                cb_gain_2nd_8k[gc_2nd_index][1];
355
356         ff_acelp_weighted_vector_sum(ctx->exc + i * SUBFRAME_SIZE,
357                                      ctx->exc + i * SUBFRAME_SIZE, fc,
358                                      (!voicing && frame_erasure) ? 0 : ctx->gain_pitch,
359                                      ( voicing && frame_erasure) ? 0 : ctx->gain_code,
360                                      1 << 13, 14, SUBFRAME_SIZE);
361
362         if (frame_erasure)
363             ctx->pitch_delay_int_prev = FFMIN(ctx->pitch_delay_int_prev + 1, PITCH_DELAY_MAX);
364         else
365             ctx->pitch_delay_int_prev = pitch_delay_int;
366     }
367
368     *data_size = SUBFRAME_SIZE << 2;
369     return buf_size;
370 }
371
372 AVCodec ff_g729_decoder =
373 {
374     "g729",
375     AVMEDIA_TYPE_AUDIO,
376     CODEC_ID_G729,
377     sizeof(G729Context),
378     decoder_init,
379     NULL,
380     NULL,
381     decode_frame,
382     .long_name = NULL_IF_CONFIG_SMALL("G.729"),
383 };