]> git.sesse.net Git - ffmpeg/blob - libavcodec/qdmc.c
avcodec/qdmc: Apply offset when creating VLC
[ffmpeg] / libavcodec / qdmc.c
1 /*
2  * QDMC compatible decoder
3  * Copyright (c) 2017 Paul B Mahol
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 #include <math.h>
23 #include <stddef.h>
24 #include <stdio.h>
25
26 #define BITSTREAM_READER_LE
27
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/thread.h"
30
31 #include "avcodec.h"
32 #include "bytestream.h"
33 #include "get_bits.h"
34 #include "internal.h"
35 #include "fft.h"
36
37 typedef struct QDMCTone {
38     uint8_t mode;
39     uint8_t phase;
40     uint8_t offset;
41     int16_t freq;
42     int16_t amplitude;
43 } QDMCTone;
44
45 typedef struct QDMCContext {
46     AVCodecContext *avctx;
47
48     uint8_t frame_bits;
49     int band_index;
50     int frame_size;
51     int subframe_size;
52     int fft_offset;
53     int buffer_offset;
54     int nb_channels;
55     int checksum_size;
56
57     uint8_t noise[2][19][17];
58     QDMCTone tones[5][8192];
59     int nb_tones[5];
60     int cur_tone[5];
61     float alt_sin[5][31];
62     float fft_buffer[4][8192 * 2];
63     float noise2_buffer[4096 * 2];
64     float noise_buffer[4096 * 2];
65     float buffer[2 * 32768];
66     float *buffer_ptr;
67     int rndval;
68
69     DECLARE_ALIGNED(32, FFTComplex, cmplx)[2][512];
70     FFTContext fft_ctx;
71 } QDMCContext;
72
73 static float sin_table[512];
74 static VLC vtable[6];
75
76 static const unsigned code_prefix[] = {
77     0x0, 0x1, 0x2, 0x3, 0x4, 0x6, 0x8, 0xA,
78     0xC, 0x10, 0x14, 0x18, 0x1C, 0x24, 0x2C, 0x34,
79     0x3C, 0x4C, 0x5C, 0x6C, 0x7C, 0x9C, 0xBC, 0xDC,
80     0xFC, 0x13C, 0x17C, 0x1BC, 0x1FC, 0x27C, 0x2FC, 0x37C,
81     0x3FC, 0x4FC, 0x5FC, 0x6FC, 0x7FC, 0x9FC, 0xBFC, 0xDFC,
82     0xFFC, 0x13FC, 0x17FC, 0x1BFC, 0x1FFC, 0x27FC, 0x2FFC, 0x37FC,
83     0x3FFC, 0x4FFC, 0x5FFC, 0x6FFC, 0x7FFC, 0x9FFC, 0xBFFC, 0xDFFC,
84     0xFFFC, 0x13FFC, 0x17FFC, 0x1BFFC, 0x1FFFC, 0x27FFC, 0x2FFFC, 0x37FFC,
85     0x3FFFC
86 };
87
88 static const float amplitude_tab[64] = {
89     1.18750000f, 1.68359380f, 2.37500000f, 3.36718750f, 4.75000000f,
90     6.73437500f, 9.50000000f, 13.4687500f, 19.0000000f, 26.9375000f,
91     38.0000000f, 53.8750000f, 76.0000000f, 107.750000f, 152.000000f,
92     215.500000f, 304.000000f, 431.000000f, 608.000000f, 862.000000f,
93     1216.00000f, 1724.00000f, 2432.00000f, 3448.00000f, 4864.00000f,
94     6896.00000f, 9728.00000f, 13792.0000f, 19456.0000f, 27584.0000f,
95     38912.0000f, 55168.0000f, 77824.0000f, 110336.000f, 155648.000f,
96     220672.000f, 311296.000f, 441344.000f, 622592.000f, 882688.000f,
97     1245184.00f, 1765376.00f, 2490368.00f, 3530752.00f, 4980736.00f,
98     7061504.00f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99 };
100
101 static const uint16_t qdmc_nodes[112] = {
102     0, 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 56, 64,
103     80, 96, 120, 144, 176, 208, 240, 256,
104     0, 2, 4, 8, 16, 24, 32, 48, 56, 64, 80, 104,
105     128, 160, 208, 256, 0, 0, 0, 0, 0,
106     0, 2, 4, 8, 16, 32, 48, 64, 80, 112, 160, 208,
107     256, 0, 0, 0, 0, 0, 0, 0, 0,
108     0, 4, 8, 16, 32, 48, 64, 96, 144, 208, 256,
109     0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
110     0, 4, 16, 32, 64, 256, 0, 0, 0, 0, 0, 0, 0, 0,
111     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
112 };
113
114 static const uint8_t noise_bands_size[] = {
115     19, 14, 11, 9, 4, 2, 0
116 };
117
118 static const uint8_t noise_bands_selector[] = {
119     4, 3, 2, 1, 0, 0, 0,
120 };
121
122 static const uint8_t noise_value[][2] = {
123     {  1,  2 }, { 10,  7 }, { 26,  9 }, { 22,  9 }, { 24,  9 }, { 14,  9 },
124     {  8,  6 }, {  6,  5 }, {  7,  5 }, {  9,  7 }, { 30,  9 }, { 32, 10 },
125     { 13, 10 }, { 20,  9 }, { 28,  9 }, { 12,  7 }, { 15, 11 }, { 36, 12 },
126     {  0, 12 }, { 34, 10 }, { 18,  9 }, { 11,  9 }, { 16,  9 }, {  5,  3 },
127     {  2,  3 }, {  4,  3 }, {  3,  2 },
128 };
129
130 static const uint8_t noise_segment_length[][2] = {
131     {  1,  1 }, {  2,  2 }, {  3,  4 }, {  8,  9 }, {  9, 10 }, {  0, 10 },
132     { 13,  8 }, {  7,  7 }, {  6,  6 }, { 17,  5 }, {  4,  4 }, {  5,  4 },
133 };
134
135 static const uint8_t amplitude[][2] = {
136     { 18,  3 }, { 16,  3 }, { 22,  7 }, {  8, 10 }, {  4, 10 }, {  3,  9 },
137     {  2,  8 }, { 23,  8 }, { 10,  8 }, { 11,  7 }, { 21,  5 }, { 20,  4 },
138     {  1,  7 }, {  7, 10 }, {  5, 10 }, {  9,  9 }, {  6, 10 }, { 25, 11 },
139     { 26, 12 }, { 27, 13 }, {  0, 13 }, { 24,  9 }, { 12,  6 }, { 13,  5 },
140     { 14,  4 }, { 19,  3 }, { 15,  3 }, { 17,  2 },
141 };
142
143 static const uint8_t freq_diff[][2] = {
144     {  2,  4 }, { 14,  6 }, { 26,  7 }, { 31,  8 }, { 32,  9 }, { 35,  9 },
145     {  7,  5 }, { 10,  5 }, { 22,  7 }, { 27,  7 }, { 19,  7 }, { 20,  7 },
146     {  4,  5 }, { 13,  5 }, { 17,  6 }, { 15,  6 }, {  8,  5 }, {  5,  4 },
147     { 28,  7 }, { 33,  9 }, { 36, 11 }, { 38, 12 }, { 42, 14 }, { 45, 16 },
148     { 44, 18 }, {  0, 18 }, { 46, 17 }, { 43, 15 }, { 40, 13 }, { 37, 11 },
149     { 39, 12 }, { 41, 12 }, { 34,  8 }, { 16,  6 }, { 11,  5 }, {  9,  4 },
150     {  1,  2 }, {  3,  4 }, { 30,  7 }, { 29,  7 }, { 23,  6 }, { 24,  6 },
151     { 18,  6 }, {  6,  4 }, { 12,  5 }, { 21,  6 }, { 25,  6 },
152 };
153
154 static const uint8_t amplitude_diff[][2] = {
155     {  1,  2 }, {  3,  3 }, {  4,  4 }, {  5,  5 }, {  6,  6 }, {  7,  7 },
156     {  8,  8 }, {  0,  8 }, {  2,  1 },
157 };
158
159 static const uint8_t phase_diff[][2] = {
160     {  2,  2 }, {  1,  2 }, {  3,  4 }, {  7,  4 }, {  6,  5 }, {  5,  6 },
161     {  0,  6 }, {  4,  4 }, {  8,  2 },
162 };
163
164 static av_cold void qdmc_init_static_data(void)
165 {
166     int i;
167
168     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[0], 12, FF_ARRAY_ELEMS(noise_value),
169                                  &noise_value[0][1], 2,
170                                  &noise_value[0][0], 2, 1, -1, INIT_VLC_LE, 4096);
171     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[1], 10, FF_ARRAY_ELEMS(noise_segment_length),
172                                  &noise_segment_length[0][1], 2,
173                                  &noise_segment_length[0][0], 2, 1, -1, INIT_VLC_LE, 1024);
174     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[2], 12, FF_ARRAY_ELEMS(amplitude),
175                                  &amplitude[0][1], 2,
176                                  &amplitude[0][0], 2, 1, -1, INIT_VLC_LE, 4098);
177     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[3], 12, FF_ARRAY_ELEMS(freq_diff),
178                                  &freq_diff[0][1], 2,
179                                  &freq_diff[0][0], 2, 1, -1, INIT_VLC_LE, 4160);
180     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[4], 8, FF_ARRAY_ELEMS(amplitude_diff),
181                                  &amplitude_diff[0][1], 2,
182                                  &amplitude_diff[0][0], 2, 1, -1, INIT_VLC_LE, 256);
183     INIT_VLC_STATIC_FROM_LENGTHS(&vtable[5], 6, FF_ARRAY_ELEMS(phase_diff),
184                                  &phase_diff[0][1], 2,
185                                  &phase_diff[0][0], 2, 1, -1, INIT_VLC_LE, 64);
186
187     for (i = 0; i < 512; i++)
188         sin_table[i] = sin(2.0f * i * M_PI * 0.001953125f);
189 }
190
191 static void make_noises(QDMCContext *s)
192 {
193     int i, j, n0, n1, n2, diff;
194     float *nptr;
195
196     for (j = 0; j < noise_bands_size[s->band_index]; j++) {
197         n0 = qdmc_nodes[j + 21 * s->band_index    ];
198         n1 = qdmc_nodes[j + 21 * s->band_index + 1];
199         n2 = qdmc_nodes[j + 21 * s->band_index + 2];
200         nptr = s->noise_buffer + 256 * j;
201
202         for (i = 0; i + n0 < n1; i++, nptr++)
203             nptr[0] = i / (float)(n1 - n0);
204
205         diff = n2 - n1;
206         nptr = s->noise_buffer + (j << 8) + n1 - n0;
207
208         for (i = n1; i < n2; i++, nptr++, diff--)
209             nptr[0] = diff / (float)(n2 - n1);
210     }
211 }
212
213 static av_cold int qdmc_decode_init(AVCodecContext *avctx)
214 {
215     static AVOnce init_static_once = AV_ONCE_INIT;
216     QDMCContext *s = avctx->priv_data;
217     int ret, fft_size, fft_order, size, g, j, x;
218     GetByteContext b;
219
220     ff_thread_once(&init_static_once, qdmc_init_static_data);
221
222     if (!avctx->extradata || (avctx->extradata_size < 48)) {
223         av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
224         return AVERROR_INVALIDDATA;
225     }
226
227     bytestream2_init(&b, avctx->extradata, avctx->extradata_size);
228
229     while (bytestream2_get_bytes_left(&b) > 8) {
230         if (bytestream2_peek_be64(&b) == (((uint64_t)MKBETAG('f','r','m','a') << 32) |
231                                            (uint64_t)MKBETAG('Q','D','M','C')))
232             break;
233         bytestream2_skipu(&b, 1);
234     }
235     bytestream2_skipu(&b, 8);
236
237     if (bytestream2_get_bytes_left(&b) < 36) {
238         av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
239                bytestream2_get_bytes_left(&b));
240         return AVERROR_INVALIDDATA;
241     }
242
243     size = bytestream2_get_be32u(&b);
244     if (size > bytestream2_get_bytes_left(&b)) {
245         av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
246                bytestream2_get_bytes_left(&b), size);
247         return AVERROR_INVALIDDATA;
248     }
249
250     if (bytestream2_get_be32u(&b) != MKBETAG('Q','D','C','A')) {
251         av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
252         return AVERROR_INVALIDDATA;
253     }
254     bytestream2_skipu(&b, 4);
255
256     avctx->channels = s->nb_channels = bytestream2_get_be32u(&b);
257     if (s->nb_channels <= 0 || s->nb_channels > 2) {
258         av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
259         return AVERROR_INVALIDDATA;
260     }
261     avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
262                                                    AV_CH_LAYOUT_MONO;
263
264     avctx->sample_rate = bytestream2_get_be32u(&b);
265     avctx->bit_rate = bytestream2_get_be32u(&b);
266     bytestream2_skipu(&b, 4);
267     fft_size = bytestream2_get_be32u(&b);
268     fft_order = av_log2(fft_size) + 1;
269     s->checksum_size = bytestream2_get_be32u(&b);
270     if (s->checksum_size >= 1U << 28) {
271         av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
272         return AVERROR_INVALIDDATA;
273     }
274
275     if (avctx->sample_rate >= 32000) {
276         x = 28000;
277         s->frame_bits = 13;
278     } else if (avctx->sample_rate >= 16000) {
279         x = 20000;
280         s->frame_bits = 12;
281     } else {
282         x = 16000;
283         s->frame_bits = 11;
284     }
285     s->frame_size = 1 << s->frame_bits;
286     s->subframe_size = s->frame_size >> 5;
287
288     if (avctx->channels == 2)
289         x = 3 * x / 2;
290     s->band_index = noise_bands_selector[FFMIN(6, llrint(floor(avctx->bit_rate * 3.0 / (double)x + 0.5)))];
291
292     if ((fft_order < 7) || (fft_order > 9)) {
293         avpriv_request_sample(avctx, "Unknown FFT order %d", fft_order);
294         return AVERROR_PATCHWELCOME;
295     }
296
297     if (fft_size != (1 << (fft_order - 1))) {
298         av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", fft_size);
299         return AVERROR_INVALIDDATA;
300     }
301
302     ret = ff_fft_init(&s->fft_ctx, fft_order, 1);
303     if (ret < 0)
304         return ret;
305
306     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
307
308     for (g = 5; g > 0; g--) {
309         for (j = 0; j < (1 << g) - 1; j++)
310             s->alt_sin[5-g][j] = sin_table[(((j+1) << (8 - g)) & 0x1FF)];
311     }
312
313     make_noises(s);
314
315     return 0;
316 }
317
318 static av_cold int qdmc_decode_close(AVCodecContext *avctx)
319 {
320     QDMCContext *s = avctx->priv_data;
321
322     ff_fft_end(&s->fft_ctx);
323
324     return 0;
325 }
326
327 static int qdmc_get_vlc(GetBitContext *gb, VLC *table, int flag)
328 {
329     int v;
330
331     if (get_bits_left(gb) < 1)
332         return AVERROR_INVALIDDATA;
333     v = get_vlc2(gb, table->table, table->bits, 2);
334     if (v < 0)
335         v = get_bits(gb, get_bits(gb, 3) + 1);
336
337     if (flag) {
338         if (v >= FF_ARRAY_ELEMS(code_prefix))
339             return AVERROR_INVALIDDATA;
340
341         v = code_prefix[v] + get_bitsz(gb, v >> 2);
342     }
343
344     return v;
345 }
346
347 static int skip_label(QDMCContext *s, GetBitContext *gb)
348 {
349     uint32_t label = get_bits_long(gb, 32);
350     uint16_t sum = 226, checksum = get_bits(gb, 16);
351     const uint8_t *ptr = gb->buffer + 6;
352     int i;
353
354     if (label != MKTAG('Q', 'M', 'C', 1))
355         return AVERROR_INVALIDDATA;
356
357     for (i = 0; i < s->checksum_size - 6; i++)
358         sum += ptr[i];
359
360     return sum != checksum;
361 }
362
363 static int read_noise_data(QDMCContext *s, GetBitContext *gb)
364 {
365     int ch, j, k, v, idx, band, lastval, newval, len;
366
367     for (ch = 0; ch < s->nb_channels; ch++) {
368         for (band = 0; band < noise_bands_size[s->band_index]; band++) {
369             v = qdmc_get_vlc(gb, &vtable[0], 0);
370             if (v < 0)
371                 return AVERROR_INVALIDDATA;
372
373             if (v & 1)
374                 v = v + 1;
375             else
376                 v = -v;
377
378             lastval = v / 2;
379             s->noise[ch][band][0] = lastval - 1;
380             for (j = 0; j < 15;) {
381                 len = qdmc_get_vlc(gb, &vtable[1], 1);
382                 if (len < 0)
383                     return AVERROR_INVALIDDATA;
384                 len += 1;
385
386                 v = qdmc_get_vlc(gb, &vtable[0], 0);
387                 if (v < 0)
388                     return AVERROR_INVALIDDATA;
389
390                 if (v & 1)
391                     newval = lastval + (v + 1) / 2;
392                 else
393                     newval = lastval - v / 2;
394
395                 idx = j + 1;
396                 if (len + idx > 16)
397                     return AVERROR_INVALIDDATA;
398
399                 for (k = 1; idx <= j + len; k++, idx++)
400                     s->noise[ch][band][idx] = lastval + k * (newval - lastval) / len - 1;
401
402                 lastval = newval;
403                 j += len;
404             }
405         }
406     }
407
408     return 0;
409 }
410
411 static void add_tone(QDMCContext *s, int group, int offset, int freq, int stereo_mode, int amplitude, int phase)
412 {
413     const int index = s->nb_tones[group];
414
415     if (index >= FF_ARRAY_ELEMS(s->tones[group])) {
416         av_log(s->avctx, AV_LOG_WARNING, "Too many tones already in buffer, ignoring tone!\n");
417         return;
418     }
419
420     s->tones[group][index].offset    = offset;
421     s->tones[group][index].freq      = freq;
422     s->tones[group][index].mode      = stereo_mode;
423     s->tones[group][index].amplitude = amplitude;
424     s->tones[group][index].phase     = phase;
425     s->nb_tones[group]++;
426 }
427
428 static int read_wave_data(QDMCContext *s, GetBitContext *gb)
429 {
430     int amp, phase, stereo_mode = 0, i, group, freq, group_size, group_bits;
431     int amp2, phase2, pos2, off;
432
433     for (group = 0; group < 5; group++) {
434         group_size = 1 << (s->frame_bits - group - 1);
435         group_bits = 4 - group;
436         pos2 = 0;
437         off  = 0;
438
439         for (i = 1; ; i = freq + 1) {
440             int v;
441
442             v = qdmc_get_vlc(gb, &vtable[3], 1);
443             if (v < 0)
444                 return AVERROR_INVALIDDATA;
445
446             freq = i + v;
447             while (freq >= group_size - 1) {
448                 freq += 2 - group_size;
449                 pos2 += group_size;
450                 off  += 1 << group_bits;
451             }
452
453             if (pos2 >= s->frame_size)
454                 break;
455
456             if (s->nb_channels > 1)
457                 stereo_mode = get_bits(gb, 2);
458
459             amp   = qdmc_get_vlc(gb, &vtable[2], 0);
460             if (amp < 0)
461                 return AVERROR_INVALIDDATA;
462             phase = get_bits(gb, 3);
463
464             if (stereo_mode > 1) {
465                 amp2   = qdmc_get_vlc(gb, &vtable[4], 0);
466                 if (amp2 < 0)
467                     return AVERROR_INVALIDDATA;
468                 amp2   = amp - amp2;
469
470                 phase2 = qdmc_get_vlc(gb, &vtable[5], 0);
471                 if (phase2 < 0)
472                     return AVERROR_INVALIDDATA;
473                 phase2 = phase - phase2;
474
475                 if (phase2 < 0)
476                     phase2 += 8;
477             }
478
479             if ((freq >> group_bits) + 1 < s->subframe_size) {
480                 add_tone(s, group, off, freq, stereo_mode & 1, amp, phase);
481                 if (stereo_mode > 1)
482                     add_tone(s, group, off, freq, ~stereo_mode & 1, amp2, phase2);
483             }
484         }
485     }
486
487     return 0;
488 }
489
490 static void lin_calc(QDMCContext *s, float amplitude, int node1, int node2, int index)
491 {
492     int subframe_size, i, j, k, length;
493     float scale, *noise_ptr;
494
495     scale = 0.5 * amplitude;
496     subframe_size = s->subframe_size;
497     if (subframe_size >= node2)
498         subframe_size = node2;
499     length = (subframe_size - node1) & 0xFFFC;
500     j = node1;
501     noise_ptr = &s->noise_buffer[256 * index];
502
503     for (i = 0; i < length; i += 4, j+= 4, noise_ptr += 4) {
504         s->noise2_buffer[j    ] += scale * noise_ptr[0];
505         s->noise2_buffer[j + 1] += scale * noise_ptr[1];
506         s->noise2_buffer[j + 2] += scale * noise_ptr[2];
507         s->noise2_buffer[j + 3] += scale * noise_ptr[3];
508     }
509
510     k = length + node1;
511     noise_ptr = s->noise_buffer + length + (index << 8);
512     for (i = length; i < subframe_size - node1; i++, k++, noise_ptr++)
513         s->noise2_buffer[k] += scale * noise_ptr[0];
514 }
515
516 static void add_noise(QDMCContext *s, int ch, int current_subframe)
517 {
518     int i, j, aindex;
519     float amplitude;
520     float *im = &s->fft_buffer[0 + ch][s->fft_offset + s->subframe_size * current_subframe];
521     float *re = &s->fft_buffer[2 + ch][s->fft_offset + s->subframe_size * current_subframe];
522
523     memset(s->noise2_buffer, 0, 4 * s->subframe_size);
524
525     for (i = 0; i < noise_bands_size[s->band_index]; i++) {
526         if (qdmc_nodes[i + 21 * s->band_index] > s->subframe_size - 1)
527             break;
528
529         aindex = s->noise[ch][i][current_subframe / 2];
530         amplitude = aindex > 0 ? amplitude_tab[aindex & 0x3F] : 0.0f;
531
532         lin_calc(s, amplitude, qdmc_nodes[21 * s->band_index + i],
533                  qdmc_nodes[21 * s->band_index + i + 2], i);
534     }
535
536     for (j = 2; j < s->subframe_size - 1; j++) {
537         float rnd_re, rnd_im;
538
539         s->rndval = 214013U * s->rndval + 2531011;
540         rnd_im = ((s->rndval & 0x7FFF) - 16384.0f) * 0.000030517578f * s->noise2_buffer[j];
541         s->rndval = 214013U * s->rndval + 2531011;
542         rnd_re = ((s->rndval & 0x7FFF) - 16384.0f) * 0.000030517578f * s->noise2_buffer[j];
543         im[j  ] += rnd_im;
544         re[j  ] += rnd_re;
545         im[j+1] -= rnd_im;
546         re[j+1] -= rnd_re;
547     }
548 }
549
550 static void add_wave(QDMCContext *s, int offset, int freqs, int group, int stereo_mode, int amp, int phase)
551 {
552     int j, group_bits, pos, pindex;
553     float im, re, amplitude, level, *imptr, *reptr;
554
555     if (s->nb_channels == 1)
556         stereo_mode = 0;
557
558     group_bits = 4 - group;
559     pos = freqs >> (4 - group);
560     amplitude = amplitude_tab[amp & 0x3F];
561     imptr = &s->fft_buffer[    stereo_mode][s->fft_offset + s->subframe_size * offset + pos];
562     reptr = &s->fft_buffer[2 + stereo_mode][s->fft_offset + s->subframe_size * offset + pos];
563     pindex = (phase << 6) - ((2 * (freqs >> (4 - group)) + 1) << 7);
564     for (j = 0; j < (1 << (group_bits + 1)) - 1; j++) {
565         pindex += (2 * freqs + 1) << (7 - group_bits);
566         level = amplitude * s->alt_sin[group][j];
567         im = level * sin_table[ pindex        & 0x1FF];
568         re = level * sin_table[(pindex + 128) & 0x1FF];
569         imptr[0] += im;
570         imptr[1] -= im;
571         reptr[0] += re;
572         reptr[1] -= re;
573         imptr += s->subframe_size;
574         reptr += s->subframe_size;
575         if (imptr >= &s->fft_buffer[stereo_mode][2 * s->frame_size]) {
576             imptr = &s->fft_buffer[0 + stereo_mode][pos];
577             reptr = &s->fft_buffer[2 + stereo_mode][pos];
578         }
579     }
580 }
581
582 static void add_wave0(QDMCContext *s, int offset, int freqs, int stereo_mode, int amp, int phase)
583 {
584     float level, im, re;
585     int pos;
586
587     if (s->nb_channels == 1)
588         stereo_mode = 0;
589
590     level = amplitude_tab[amp & 0x3F];
591     im = level * sin_table[ (phase << 6)        & 0x1FF];
592     re = level * sin_table[((phase << 6) + 128) & 0x1FF];
593     pos = s->fft_offset + freqs + s->subframe_size * offset;
594     s->fft_buffer[    stereo_mode][pos    ] += im;
595     s->fft_buffer[2 + stereo_mode][pos    ] += re;
596     s->fft_buffer[    stereo_mode][pos + 1] -= im;
597     s->fft_buffer[2 + stereo_mode][pos + 1] -= re;
598 }
599
600 static void add_waves(QDMCContext *s, int current_subframe)
601 {
602     int w, g;
603
604     for (g = 0; g < 4; g++) {
605         for (w = s->cur_tone[g]; w < s->nb_tones[g]; w++) {
606             QDMCTone *t = &s->tones[g][w];
607
608             if (current_subframe < t->offset)
609                 break;
610             add_wave(s, t->offset, t->freq, g, t->mode, t->amplitude, t->phase);
611         }
612         s->cur_tone[g] = w;
613     }
614     for (w = s->cur_tone[4]; w < s->nb_tones[4]; w++) {
615         QDMCTone *t = &s->tones[4][w];
616
617         if (current_subframe < t->offset)
618             break;
619         add_wave0(s, t->offset, t->freq, t->mode, t->amplitude, t->phase);
620     }
621     s->cur_tone[4] = w;
622 }
623
624 static int decode_frame(QDMCContext *s, GetBitContext *gb, int16_t *out)
625 {
626     int ret, ch, i, n;
627
628     if (skip_label(s, gb))
629         return AVERROR_INVALIDDATA;
630
631     s->fft_offset = s->frame_size - s->fft_offset;
632     s->buffer_ptr = &s->buffer[s->nb_channels * s->buffer_offset];
633
634     ret = read_noise_data(s, gb);
635     if (ret < 0)
636         return ret;
637
638     ret = read_wave_data(s, gb);
639     if (ret < 0)
640         return ret;
641
642     for (n = 0; n < 32; n++) {
643         float *r;
644
645         for (ch = 0; ch < s->nb_channels; ch++)
646             add_noise(s, ch, n);
647
648         add_waves(s, n);
649
650         for (ch = 0; ch < s->nb_channels; ch++) {
651             for (i = 0; i < s->subframe_size; i++) {
652                 s->cmplx[ch][i].re = s->fft_buffer[ch + 2][s->fft_offset + n * s->subframe_size + i];
653                 s->cmplx[ch][i].im = s->fft_buffer[ch + 0][s->fft_offset + n * s->subframe_size + i];
654                 s->cmplx[ch][s->subframe_size + i].re = 0;
655                 s->cmplx[ch][s->subframe_size + i].im = 0;
656             }
657         }
658
659         for (ch = 0; ch < s->nb_channels; ch++) {
660             s->fft_ctx.fft_permute(&s->fft_ctx, s->cmplx[ch]);
661             s->fft_ctx.fft_calc(&s->fft_ctx, s->cmplx[ch]);
662         }
663
664         r = &s->buffer_ptr[s->nb_channels * n * s->subframe_size];
665         for (i = 0; i < 2 * s->subframe_size; i++) {
666             for (ch = 0; ch < s->nb_channels; ch++) {
667                 *r++ += s->cmplx[ch][i].re;
668             }
669         }
670
671         r = &s->buffer_ptr[n * s->subframe_size * s->nb_channels];
672         for (i = 0; i < s->nb_channels * s->subframe_size; i++) {
673             out[i] = av_clipf(r[i], INT16_MIN, INT16_MAX);
674         }
675         out += s->subframe_size * s->nb_channels;
676
677         for (ch = 0; ch < s->nb_channels; ch++) {
678             memset(s->fft_buffer[ch+0] + s->fft_offset + n * s->subframe_size, 0, 4 * s->subframe_size);
679             memset(s->fft_buffer[ch+2] + s->fft_offset + n * s->subframe_size, 0, 4 * s->subframe_size);
680         }
681         memset(s->buffer + s->nb_channels * (n * s->subframe_size + s->frame_size + s->buffer_offset), 0, 4 * s->subframe_size * s->nb_channels);
682     }
683
684     s->buffer_offset += s->frame_size;
685     if (s->buffer_offset >= 32768 - s->frame_size) {
686         memcpy(s->buffer, &s->buffer[s->nb_channels * s->buffer_offset], 4 * s->frame_size * s->nb_channels);
687         s->buffer_offset = 0;
688     }
689
690     return 0;
691 }
692
693 static av_cold void qdmc_flush(AVCodecContext *avctx)
694 {
695     QDMCContext *s = avctx->priv_data;
696
697     memset(s->buffer, 0, sizeof(s->buffer));
698     memset(s->fft_buffer, 0, sizeof(s->fft_buffer));
699     s->fft_offset = 0;
700     s->buffer_offset = 0;
701 }
702
703 static int qdmc_decode_frame(AVCodecContext *avctx, void *data,
704                              int *got_frame_ptr, AVPacket *avpkt)
705 {
706     QDMCContext *s = avctx->priv_data;
707     AVFrame *frame = data;
708     GetBitContext gb;
709     int ret;
710
711     if (!avpkt->data)
712         return 0;
713     if (avpkt->size < s->checksum_size)
714         return AVERROR_INVALIDDATA;
715
716     s->avctx = avctx;
717     frame->nb_samples = s->frame_size;
718     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
719         return ret;
720
721     if ((ret = init_get_bits8(&gb, avpkt->data, s->checksum_size)) < 0)
722         return ret;
723
724     memset(s->nb_tones, 0, sizeof(s->nb_tones));
725     memset(s->cur_tone, 0, sizeof(s->cur_tone));
726
727     ret = decode_frame(s, &gb, (int16_t *)frame->data[0]);
728     if (ret >= 0) {
729         *got_frame_ptr = 1;
730         return s->checksum_size;
731     }
732     qdmc_flush(avctx);
733     return ret;
734 }
735
736 AVCodec ff_qdmc_decoder = {
737     .name             = "qdmc",
738     .long_name        = NULL_IF_CONFIG_SMALL("QDesign Music Codec 1"),
739     .type             = AVMEDIA_TYPE_AUDIO,
740     .id               = AV_CODEC_ID_QDMC,
741     .priv_data_size   = sizeof(QDMCContext),
742     .init             = qdmc_decode_init,
743     .close            = qdmc_decode_close,
744     .decode           = qdmc_decode_frame,
745     .flush            = qdmc_flush,
746     .capabilities     = AV_CODEC_CAP_DR1,
747 };