2 * QDM2 compatible decoder
3 * Copyright (c) 2003 Ewald Snel
4 * Copyright (c) 2005 Benjamin Larsson
5 * Copyright (c) 2005 Alex Beregszaszi
6 * Copyright (c) 2005 Roberto Togni
8 * This file is part of Libav.
10 * Libav is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * Libav is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with Libav; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
30 * The decoder is not perfect yet, there are still some distortions
31 * especially on files encoded with 16 or 8 subbands.
38 #define BITSTREAM_READER_LE
43 #include "mpegaudiodsp.h"
44 #include "mpegaudio.h"
47 #include "qdm2_tablegen.h"
53 #define QDM2_LIST_ADD(list, size, packet) \
56 list[size - 1].next = &list[size]; \
58 list[size].packet = packet; \
59 list[size].next = NULL; \
63 // Result is 8, 16 or 30
64 #define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
66 #define FIX_NOISE_IDX(noise_idx) \
67 if ((noise_idx) >= 3840) \
68 (noise_idx) -= 3840; \
70 #define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
72 #define SAMPLES_NEEDED \
73 av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
75 #define SAMPLES_NEEDED_2(why) \
76 av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
78 #define QDM2_MAX_FRAME_SIZE 512
80 typedef int8_t sb_int8_array[2][30][64];
86 int type; ///< subpacket type
87 unsigned int size; ///< subpacket size
88 const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
92 * A node in the subpacket list
94 typedef struct QDM2SubPNode {
95 QDM2SubPacket *packet; ///< packet
96 struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
106 QDM2Complex *complex;
124 DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
128 * QDM2 decoder context
133 /// Parameters from codec header, do not change during playback
134 int nb_channels; ///< number of channels
135 int channels; ///< number of channels
136 int group_size; ///< size of frame group (16 frames per group)
137 int fft_size; ///< size of FFT, in complex numbers
138 int checksum_size; ///< size of data block, used also for checksum
140 /// Parameters built from header parameters, do not change during playback
141 int group_order; ///< order of frame group
142 int fft_order; ///< order of FFT (actually fftorder+1)
143 int frame_size; ///< size of data frame
145 int sub_sampling; ///< subsampling: 0=25%, 1=50%, 2=100% */
146 int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
147 int cm_table_select; ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
149 /// Packets and packet lists
150 QDM2SubPacket sub_packets[16]; ///< the packets themselves
151 QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
152 QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
153 int sub_packets_B; ///< number of packets on 'B' list
154 QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
155 QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
158 FFTTone fft_tones[1000];
161 FFTCoefficient fft_coefs[1000];
163 int fft_coefs_min_index[5];
164 int fft_coefs_max_index[5];
165 int fft_level_exp[6];
166 RDFTContext rdft_ctx;
170 const uint8_t *compressed_data;
172 float output_buffer[QDM2_MAX_FRAME_SIZE * 2];
175 MPADSPContext mpadsp;
176 DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
177 int synth_buf_offset[MPA_MAX_CHANNELS];
178 DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
179 DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
181 /// Mixed temporary data used in decoding
182 float tone_level[MPA_MAX_CHANNELS][30][64];
183 int8_t coding_method[MPA_MAX_CHANNELS][30][64];
184 int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
185 int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
186 int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
187 int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
188 int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
189 int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
190 int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
193 int has_errors; ///< packet has errors
194 int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
195 int do_synth_filter; ///< used to perform or skip synthesis filter
198 int noise_idx; ///< index for dithering noise table
202 static VLC vlc_tab_level;
203 static VLC vlc_tab_diff;
204 static VLC vlc_tab_run;
205 static VLC fft_level_exp_alt_vlc;
206 static VLC fft_level_exp_vlc;
207 static VLC fft_stereo_exp_vlc;
208 static VLC fft_stereo_phase_vlc;
209 static VLC vlc_tab_tone_level_idx_hi1;
210 static VLC vlc_tab_tone_level_idx_mid;
211 static VLC vlc_tab_tone_level_idx_hi2;
212 static VLC vlc_tab_type30;
213 static VLC vlc_tab_type34;
214 static VLC vlc_tab_fft_tone_offset[5];
216 static const uint16_t qdm2_vlc_offs[] = {
217 0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
220 static av_cold void qdm2_init_vlc(void)
222 static int vlcs_initialized = 0;
223 static VLC_TYPE qdm2_table[3838][2];
225 if (!vlcs_initialized) {
227 vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
228 vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
229 init_vlc (&vlc_tab_level, 8, 24,
230 vlc_tab_level_huffbits, 1, 1,
231 vlc_tab_level_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
233 vlc_tab_diff.table = &qdm2_table[qdm2_vlc_offs[1]];
234 vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
235 init_vlc (&vlc_tab_diff, 8, 37,
236 vlc_tab_diff_huffbits, 1, 1,
237 vlc_tab_diff_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
239 vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
240 vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
241 init_vlc (&vlc_tab_run, 5, 6,
242 vlc_tab_run_huffbits, 1, 1,
243 vlc_tab_run_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
245 fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
246 fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
247 init_vlc (&fft_level_exp_alt_vlc, 8, 28,
248 fft_level_exp_alt_huffbits, 1, 1,
249 fft_level_exp_alt_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
252 fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
253 fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
254 init_vlc (&fft_level_exp_vlc, 8, 20,
255 fft_level_exp_huffbits, 1, 1,
256 fft_level_exp_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
258 fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
259 fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
260 init_vlc (&fft_stereo_exp_vlc, 6, 7,
261 fft_stereo_exp_huffbits, 1, 1,
262 fft_stereo_exp_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
264 fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
265 fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
266 init_vlc (&fft_stereo_phase_vlc, 6, 9,
267 fft_stereo_phase_huffbits, 1, 1,
268 fft_stereo_phase_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
270 vlc_tab_tone_level_idx_hi1.table = &qdm2_table[qdm2_vlc_offs[7]];
271 vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
272 init_vlc (&vlc_tab_tone_level_idx_hi1, 8, 20,
273 vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
274 vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
276 vlc_tab_tone_level_idx_mid.table = &qdm2_table[qdm2_vlc_offs[8]];
277 vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
278 init_vlc (&vlc_tab_tone_level_idx_mid, 8, 24,
279 vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
280 vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
282 vlc_tab_tone_level_idx_hi2.table = &qdm2_table[qdm2_vlc_offs[9]];
283 vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
284 init_vlc (&vlc_tab_tone_level_idx_hi2, 8, 24,
285 vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
286 vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
288 vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
289 vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
290 init_vlc (&vlc_tab_type30, 6, 9,
291 vlc_tab_type30_huffbits, 1, 1,
292 vlc_tab_type30_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
294 vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
295 vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
296 init_vlc (&vlc_tab_type34, 5, 10,
297 vlc_tab_type34_huffbits, 1, 1,
298 vlc_tab_type34_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
300 vlc_tab_fft_tone_offset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
301 vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
302 init_vlc (&vlc_tab_fft_tone_offset[0], 8, 23,
303 vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
304 vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
306 vlc_tab_fft_tone_offset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
307 vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
308 init_vlc (&vlc_tab_fft_tone_offset[1], 8, 28,
309 vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
310 vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
312 vlc_tab_fft_tone_offset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
313 vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
314 init_vlc (&vlc_tab_fft_tone_offset[2], 8, 32,
315 vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
316 vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
318 vlc_tab_fft_tone_offset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
319 vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
320 init_vlc (&vlc_tab_fft_tone_offset[3], 8, 35,
321 vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
322 vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
324 vlc_tab_fft_tone_offset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
325 vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
326 init_vlc (&vlc_tab_fft_tone_offset[4], 8, 38,
327 vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
328 vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
334 static int qdm2_get_vlc (GetBitContext *gb, VLC *vlc, int flag, int depth)
338 value = get_vlc2(gb, vlc->table, vlc->bits, depth);
340 /* stage-2, 3 bits exponent escape sequence */
342 value = get_bits (gb, get_bits (gb, 3) + 1);
344 /* stage-3, optional */
346 int tmp = vlc_stage3_values[value];
348 if ((value & ~3) > 0)
349 tmp += get_bits (gb, (value >> 2));
357 static int qdm2_get_se_vlc (VLC *vlc, GetBitContext *gb, int depth)
359 int value = qdm2_get_vlc (gb, vlc, 0, depth);
361 return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
368 * @param data pointer to data to be checksum'ed
369 * @param length data length
370 * @param value checksum value
372 * @return 0 if checksum is OK
374 static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value) {
377 for (i=0; i < length; i++)
380 return (uint16_t)(value & 0xffff);
385 * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
387 * @param gb bitreader context
388 * @param sub_packet packet under analysis
390 static void qdm2_decode_sub_packet_header (GetBitContext *gb, QDM2SubPacket *sub_packet)
392 sub_packet->type = get_bits (gb, 8);
394 if (sub_packet->type == 0) {
395 sub_packet->size = 0;
396 sub_packet->data = NULL;
398 sub_packet->size = get_bits (gb, 8);
400 if (sub_packet->type & 0x80) {
401 sub_packet->size <<= 8;
402 sub_packet->size |= get_bits (gb, 8);
403 sub_packet->type &= 0x7f;
406 if (sub_packet->type == 0x7f)
407 sub_packet->type |= (get_bits (gb, 8) << 8);
409 sub_packet->data = &gb->buffer[get_bits_count(gb) / 8]; // FIXME: this depends on bitreader internal data
412 av_log(NULL,AV_LOG_DEBUG,"Subpacket: type=%d size=%d start_offs=%x\n",
413 sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
418 * Return node pointer to first packet of requested type in list.
420 * @param list list of subpackets to be scanned
421 * @param type type of searched subpacket
422 * @return node pointer for subpacket if found, else NULL
424 static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int type)
426 while (list != NULL && list->packet != NULL) {
427 if (list->packet->type == type)
436 * Replace 8 elements with their average value.
437 * Called by qdm2_decode_superblock before starting subblock decoding.
441 static void average_quantized_coeffs (QDM2Context *q)
443 int i, j, n, ch, sum;
445 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
447 for (ch = 0; ch < q->nb_channels; ch++)
448 for (i = 0; i < n; i++) {
451 for (j = 0; j < 8; j++)
452 sum += q->quantized_coeffs[ch][i][j];
458 for (j=0; j < 8; j++)
459 q->quantized_coeffs[ch][i][j] = sum;
465 * Build subband samples with noise weighted by q->tone_level.
466 * Called by synthfilt_build_sb_samples.
469 * @param sb subband index
471 static void build_sb_samples_from_noise (QDM2Context *q, int sb)
475 FIX_NOISE_IDX(q->noise_idx);
480 for (ch = 0; ch < q->nb_channels; ch++)
481 for (j = 0; j < 64; j++) {
482 q->sb_samples[ch][j * 2][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
483 q->sb_samples[ch][j * 2 + 1][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
489 * Called while processing data from subpackets 11 and 12.
490 * Used after making changes to coding_method array.
492 * @param sb subband index
493 * @param channels number of channels
494 * @param coding_method q->coding_method[0][0][0]
496 static void fix_coding_method_array (int sb, int channels, sb_int8_array coding_method)
501 static const int switchtable[23] = {0,5,1,5,5,5,5,5,2,5,5,5,5,5,5,5,3,5,5,5,5,5,4};
503 for (ch = 0; ch < channels; ch++) {
504 for (j = 0; j < 64; ) {
505 if((coding_method[ch][sb][j] - 8) > 22) {
509 switch (switchtable[coding_method[ch][sb][j]-8]) {
510 case 0: run = 10; case_val = 10; break;
511 case 1: run = 1; case_val = 16; break;
512 case 2: run = 5; case_val = 24; break;
513 case 3: run = 3; case_val = 30; break;
514 case 4: run = 1; case_val = 30; break;
515 case 5: run = 1; case_val = 8; break;
516 default: run = 1; case_val = 8; break;
519 for (k = 0; k < run; k++)
521 if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
524 //not debugged, almost never used
525 memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8_t));
526 memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8_t));
535 * Related to synthesis filter
536 * Called by process_subpacket_10
539 * @param flag 1 if called after getting data from subpacket 10, 0 if no subpacket 10
541 static void fill_tone_level_array (QDM2Context *q, int flag)
543 int i, sb, ch, sb_used;
546 // This should never happen
547 if (q->nb_channels <= 0)
550 for (ch = 0; ch < q->nb_channels; ch++)
551 for (sb = 0; sb < 30; sb++)
552 for (i = 0; i < 8; i++) {
553 if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
554 tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
555 q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
557 tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
560 q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
563 sb_used = QDM2_SB_USED(q->sub_sampling);
565 if ((q->superblocktype_2_3 != 0) && !flag) {
566 for (sb = 0; sb < sb_used; sb++)
567 for (ch = 0; ch < q->nb_channels; ch++)
568 for (i = 0; i < 64; i++) {
569 q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
570 if (q->tone_level_idx[ch][sb][i] < 0)
571 q->tone_level[ch][sb][i] = 0;
573 q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
576 tab = q->superblocktype_2_3 ? 0 : 1;
577 for (sb = 0; sb < sb_used; sb++) {
578 if ((sb >= 4) && (sb <= 23)) {
579 for (ch = 0; ch < q->nb_channels; ch++)
580 for (i = 0; i < 64; i++) {
581 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
582 q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
583 q->tone_level_idx_mid[ch][sb - 4][i / 8] -
584 q->tone_level_idx_hi2[ch][sb - 4];
585 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
586 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
587 q->tone_level[ch][sb][i] = 0;
589 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
593 for (ch = 0; ch < q->nb_channels; ch++)
594 for (i = 0; i < 64; i++) {
595 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
596 q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
597 q->tone_level_idx_hi2[ch][sb - 4];
598 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
599 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
600 q->tone_level[ch][sb][i] = 0;
602 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
605 for (ch = 0; ch < q->nb_channels; ch++)
606 for (i = 0; i < 64; i++) {
607 tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
608 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
609 q->tone_level[ch][sb][i] = 0;
611 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
623 * Related to synthesis filter
624 * Called by process_subpacket_11
625 * c is built with data from subpacket 11
626 * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
628 * @param tone_level_idx
629 * @param tone_level_idx_temp
630 * @param coding_method q->coding_method[0][0][0]
631 * @param nb_channels number of channels
632 * @param c coming from subpacket 11, passed as 8*c
633 * @param superblocktype_2_3 flag based on superblock packet type
634 * @param cm_table_select q->cm_table_select
636 static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
637 sb_int8_array coding_method, int nb_channels,
638 int c, int superblocktype_2_3, int cm_table_select)
641 int tmp, acc, esp_40, comp;
642 int add1, add2, add3, add4;
645 // This should never happen
646 if (nb_channels <= 0)
649 if (!superblocktype_2_3) {
650 /* This case is untested, no samples available */
652 for (ch = 0; ch < nb_channels; ch++)
653 for (sb = 0; sb < 30; sb++) {
654 for (j = 1; j < 63; j++) { // The loop only iterates to 63 so the code doesn't overflow the buffer
655 add1 = tone_level_idx[ch][sb][j] - 10;
658 add2 = add3 = add4 = 0;
660 add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
665 add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
670 add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
674 tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
677 tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
679 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
682 for (ch = 0; ch < nb_channels; ch++)
683 for (sb = 0; sb < 30; sb++)
684 for (j = 0; j < 64; j++)
685 acc += tone_level_idx_temp[ch][sb][j];
687 multres = 0x66666667 * (acc * 10);
688 esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
689 for (ch = 0; ch < nb_channels; ch++)
690 for (sb = 0; sb < 30; sb++)
691 for (j = 0; j < 64; j++) {
692 comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
695 comp /= 256; // signed shift
723 coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
725 for (sb = 0; sb < 30; sb++)
726 fix_coding_method_array(sb, nb_channels, coding_method);
727 for (ch = 0; ch < nb_channels; ch++)
728 for (sb = 0; sb < 30; sb++)
729 for (j = 0; j < 64; j++)
731 if (coding_method[ch][sb][j] < 10)
732 coding_method[ch][sb][j] = 10;
735 if (coding_method[ch][sb][j] < 16)
736 coding_method[ch][sb][j] = 16;
738 if (coding_method[ch][sb][j] < 30)
739 coding_method[ch][sb][j] = 30;
742 } else { // superblocktype_2_3 != 0
743 for (ch = 0; ch < nb_channels; ch++)
744 for (sb = 0; sb < 30; sb++)
745 for (j = 0; j < 64; j++)
746 coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
755 * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
756 * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
759 * @param gb bitreader context
760 * @param length packet length in bits
761 * @param sb_min lower subband processed (sb_min included)
762 * @param sb_max higher subband processed (sb_max excluded)
764 static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)
766 int sb, j, k, n, ch, run, channels;
767 int joined_stereo, zero_encoding, chs;
769 float type34_div = 0;
770 float type34_predictor;
771 float samples[10], sign_bits[16];
774 // If no data use noise
775 for (sb=sb_min; sb < sb_max; sb++)
776 build_sb_samples_from_noise (q, sb);
781 for (sb = sb_min; sb < sb_max; sb++) {
782 FIX_NOISE_IDX(q->noise_idx);
784 channels = q->nb_channels;
786 if (q->nb_channels <= 1 || sb < 12)
791 joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1 (gb) : 0;
794 if (get_bits_left(gb) >= 16)
795 for (j = 0; j < 16; j++)
796 sign_bits[j] = get_bits1 (gb);
798 for (j = 0; j < 64; j++)
799 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
800 q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
802 fix_coding_method_array(sb, q->nb_channels, q->coding_method);
806 for (ch = 0; ch < channels; ch++) {
807 zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
808 type34_predictor = 0.0;
811 for (j = 0; j < 128; ) {
812 switch (q->coding_method[ch][sb][j / 2]) {
814 if (get_bits_left(gb) >= 10) {
816 for (k = 0; k < 5; k++) {
817 if ((j + 2 * k) >= 128)
819 samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
823 for (k = 0; k < 5; k++)
824 samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
826 for (k = 0; k < 5; k++)
827 samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
829 for (k = 0; k < 10; k++)
830 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
836 if (get_bits_left(gb) >= 1) {
841 f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
844 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
850 if (get_bits_left(gb) >= 10) {
852 for (k = 0; k < 5; k++) {
855 samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
858 n = get_bits (gb, 8);
859 for (k = 0; k < 5; k++)
860 samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
863 for (k = 0; k < 5; k++)
864 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
870 if (get_bits_left(gb) >= 7) {
872 for (k = 0; k < 3; k++)
873 samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
875 for (k = 0; k < 3; k++)
876 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
882 if (get_bits_left(gb) >= 4)
883 samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];
885 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
891 if (get_bits_left(gb) >= 7) {
893 type34_div = (float)(1 << get_bits(gb, 2));
894 samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
895 type34_predictor = samples[0];
898 samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;
899 type34_predictor = samples[0];
902 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
908 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
914 float tmp[10][MPA_MAX_CHANNELS];
916 for (k = 0; k < run; k++) {
917 tmp[k][0] = samples[k];
918 tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
920 for (chs = 0; chs < q->nb_channels; chs++)
921 for (k = 0; k < run; k++)
923 q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];
925 for (k = 0; k < run; k++)
927 q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
938 * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
939 * This is similar to process_subpacket_9, but for a single channel and for element [0]
940 * same VLC tables as process_subpacket_9 are used.
942 * @param quantized_coeffs pointer to quantized_coeffs[ch][0]
943 * @param gb bitreader context
945 static void init_quantized_coeffs_elem0 (int8_t *quantized_coeffs, GetBitContext *gb)
947 int i, k, run, level, diff;
949 if (get_bits_left(gb) < 16)
951 level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
953 quantized_coeffs[0] = level;
955 for (i = 0; i < 7; ) {
956 if (get_bits_left(gb) < 16)
958 run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
960 if (get_bits_left(gb) < 16)
962 diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
964 for (k = 1; k <= run; k++)
965 quantized_coeffs[i + k] = (level + ((k * diff) / run));
974 * Related to synthesis filter, process data from packet 10
975 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
976 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
979 * @param gb bitreader context
981 static void init_tone_level_dequantization (QDM2Context *q, GetBitContext *gb)
985 for (ch = 0; ch < q->nb_channels; ch++) {
986 init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb);
988 if (get_bits_left(gb) < 16) {
989 memset(q->quantized_coeffs[ch][0], 0, 8);
994 n = q->sub_sampling + 1;
996 for (sb = 0; sb < n; sb++)
997 for (ch = 0; ch < q->nb_channels; ch++)
998 for (j = 0; j < 8; j++) {
999 if (get_bits_left(gb) < 1)
1001 if (get_bits1(gb)) {
1002 for (k=0; k < 8; k++) {
1003 if (get_bits_left(gb) < 16)
1005 q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1008 for (k=0; k < 8; k++)
1009 q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1013 n = QDM2_SB_USED(q->sub_sampling) - 4;
1015 for (sb = 0; sb < n; sb++)
1016 for (ch = 0; ch < q->nb_channels; ch++) {
1017 if (get_bits_left(gb) < 16)
1019 q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1021 q->tone_level_idx_hi2[ch][sb] -= 16;
1023 for (j = 0; j < 8; j++)
1024 q->tone_level_idx_mid[ch][sb][j] = -16;
1027 n = QDM2_SB_USED(q->sub_sampling) - 5;
1029 for (sb = 0; sb < n; sb++)
1030 for (ch = 0; ch < q->nb_channels; ch++)
1031 for (j = 0; j < 8; j++) {
1032 if (get_bits_left(gb) < 16)
1034 q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1039 * Process subpacket 9, init quantized_coeffs with data from it
1042 * @param node pointer to node with packet
1044 static void process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
1047 int i, j, k, n, ch, run, level, diff;
1049 init_get_bits(&gb, node->packet->data, node->packet->size*8);
1051 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1; // same as averagesomething function
1053 for (i = 1; i < n; i++)
1054 for (ch=0; ch < q->nb_channels; ch++) {
1055 level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1056 q->quantized_coeffs[ch][i][0] = level;
1058 for (j = 0; j < (8 - 1); ) {
1059 run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1060 diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1062 for (k = 1; k <= run; k++)
1063 q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
1070 for (ch = 0; ch < q->nb_channels; ch++)
1071 for (i = 0; i < 8; i++)
1072 q->quantized_coeffs[ch][0][i] = 0;
1077 * Process subpacket 10 if not null, else
1080 * @param node pointer to node with packet
1081 * @param length packet length in bits
1083 static void process_subpacket_10 (QDM2Context *q, QDM2SubPNode *node)
1088 init_get_bits(&gb, node->packet->data, node->packet->size * 8);
1089 init_tone_level_dequantization(q, &gb);
1090 fill_tone_level_array(q, 1);
1092 fill_tone_level_array(q, 0);
1098 * Process subpacket 11
1101 * @param node pointer to node with packet
1103 static void process_subpacket_11 (QDM2Context *q, QDM2SubPNode *node)
1109 length = node->packet->size * 8;
1110 init_get_bits(&gb, node->packet->data, length);
1114 int c = get_bits (&gb, 13);
1117 fill_coding_method_array (q->tone_level_idx, q->tone_level_idx_temp, q->coding_method,
1118 q->nb_channels, 8*c, q->superblocktype_2_3, q->cm_table_select);
1121 synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1126 * Process subpacket 12
1129 * @param node pointer to node with packet
1130 * @param length packet length in bits
1132 static void process_subpacket_12 (QDM2Context *q, QDM2SubPNode *node)
1138 length = node->packet->size * 8;
1139 init_get_bits(&gb, node->packet->data, length);
1142 synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1146 * Process new subpackets for synthesis filter
1149 * @param list list with synthesis filter packets (list D)
1151 static void process_synthesis_subpackets (QDM2Context *q, QDM2SubPNode *list)
1153 QDM2SubPNode *nodes[4];
1155 nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1156 if (nodes[0] != NULL)
1157 process_subpacket_9(q, nodes[0]);
1159 nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1160 if (nodes[1] != NULL)
1161 process_subpacket_10(q, nodes[1]);
1163 process_subpacket_10(q, NULL);
1165 nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1166 if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1167 process_subpacket_11(q, nodes[2]);
1169 process_subpacket_11(q, NULL);
1171 nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1172 if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1173 process_subpacket_12(q, nodes[3]);
1175 process_subpacket_12(q, NULL);
1180 * Decode superblock, fill packet lists.
1184 static void qdm2_decode_super_block (QDM2Context *q)
1187 QDM2SubPacket header, *packet;
1188 int i, packet_bytes, sub_packet_size, sub_packets_D;
1189 unsigned int next_index = 0;
1191 memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1192 memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1193 memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1195 q->sub_packets_B = 0;
1198 average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1200 init_get_bits(&gb, q->compressed_data, q->compressed_size*8);
1201 qdm2_decode_sub_packet_header(&gb, &header);
1203 if (header.type < 2 || header.type >= 8) {
1205 av_log(NULL,AV_LOG_ERROR,"bad superblock type\n");
1209 q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1210 packet_bytes = (q->compressed_size - get_bits_count(&gb) / 8);
1212 init_get_bits(&gb, header.data, header.size*8);
1214 if (header.type == 2 || header.type == 4 || header.type == 5) {
1215 int csum = 257 * get_bits(&gb, 8);
1216 csum += 2 * get_bits(&gb, 8);
1218 csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1222 av_log(NULL,AV_LOG_ERROR,"bad packet checksum\n");
1227 q->sub_packet_list_B[0].packet = NULL;
1228 q->sub_packet_list_D[0].packet = NULL;
1230 for (i = 0; i < 6; i++)
1231 if (--q->fft_level_exp[i] < 0)
1232 q->fft_level_exp[i] = 0;
1234 for (i = 0; packet_bytes > 0; i++) {
1237 q->sub_packet_list_A[i].next = NULL;
1240 q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1242 /* seek to next block */
1243 init_get_bits(&gb, header.data, header.size*8);
1244 skip_bits(&gb, next_index*8);
1246 if (next_index >= header.size)
1250 /* decode subpacket */
1251 packet = &q->sub_packets[i];
1252 qdm2_decode_sub_packet_header(&gb, packet);
1253 next_index = packet->size + get_bits_count(&gb) / 8;
1254 sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1256 if (packet->type == 0)
1259 if (sub_packet_size > packet_bytes) {
1260 if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1262 packet->size += packet_bytes - sub_packet_size;
1265 packet_bytes -= sub_packet_size;
1267 /* add subpacket to 'all subpackets' list */
1268 q->sub_packet_list_A[i].packet = packet;
1270 /* add subpacket to related list */
1271 if (packet->type == 8) {
1272 SAMPLES_NEEDED_2("packet type 8");
1274 } else if (packet->type >= 9 && packet->type <= 12) {
1275 /* packets for MPEG Audio like Synthesis Filter */
1276 QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1277 } else if (packet->type == 13) {
1278 for (j = 0; j < 6; j++)
1279 q->fft_level_exp[j] = get_bits(&gb, 6);
1280 } else if (packet->type == 14) {
1281 for (j = 0; j < 6; j++)
1282 q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1283 } else if (packet->type == 15) {
1284 SAMPLES_NEEDED_2("packet type 15")
1286 } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
1287 /* packets for FFT */
1288 QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1290 } // Packet bytes loop
1292 /* **************************************************************** */
1293 if (q->sub_packet_list_D[0].packet != NULL) {
1294 process_synthesis_subpackets(q, q->sub_packet_list_D);
1295 q->do_synth_filter = 1;
1296 } else if (q->do_synth_filter) {
1297 process_subpacket_10(q, NULL);
1298 process_subpacket_11(q, NULL);
1299 process_subpacket_12(q, NULL);
1301 /* **************************************************************** */
1305 static void qdm2_fft_init_coefficient (QDM2Context *q, int sub_packet,
1306 int offset, int duration, int channel,
1309 if (q->fft_coefs_min_index[duration] < 0)
1310 q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1312 q->fft_coefs[q->fft_coefs_index].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1313 q->fft_coefs[q->fft_coefs_index].channel = channel;
1314 q->fft_coefs[q->fft_coefs_index].offset = offset;
1315 q->fft_coefs[q->fft_coefs_index].exp = exp;
1316 q->fft_coefs[q->fft_coefs_index].phase = phase;
1317 q->fft_coefs_index++;
1321 static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)
1323 int channel, stereo, phase, exp;
1324 int local_int_4, local_int_8, stereo_phase, local_int_10;
1325 int local_int_14, stereo_exp, local_int_20, local_int_28;
1331 local_int_8 = (4 - duration);
1332 local_int_10 = 1 << (q->group_order - duration - 1);
1336 if (q->superblocktype_2_3) {
1337 while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1340 local_int_4 += local_int_10;
1341 local_int_28 += (1 << local_int_8);
1343 local_int_4 += 8*local_int_10;
1344 local_int_28 += (8 << local_int_8);
1349 offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1350 while (offset >= (local_int_10 - 1)) {
1351 offset += (1 - (local_int_10 - 1));
1352 local_int_4 += local_int_10;
1353 local_int_28 += (1 << local_int_8);
1357 if (local_int_4 >= q->group_size)
1360 local_int_14 = (offset >> local_int_8);
1361 if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1364 if (q->nb_channels > 1) {
1365 channel = get_bits1(gb);
1366 stereo = get_bits1(gb);
1372 exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1373 exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1374 exp = (exp < 0) ? 0 : exp;
1376 phase = get_bits(gb, 3);
1381 stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1382 stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1383 if (stereo_phase < 0)
1387 if (q->frequency_range > (local_int_14 + 1)) {
1388 int sub_packet = (local_int_20 + local_int_28);
1390 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);
1392 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
1400 static void qdm2_decode_fft_packets (QDM2Context *q)
1402 int i, j, min, max, value, type, unknown_flag;
1405 if (q->sub_packet_list_B[0].packet == NULL)
1408 /* reset minimum indexes for FFT coefficients */
1409 q->fft_coefs_index = 0;
1410 for (i=0; i < 5; i++)
1411 q->fft_coefs_min_index[i] = -1;
1413 /* process subpackets ordered by type, largest type first */
1414 for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1415 QDM2SubPacket *packet= NULL;
1417 /* find subpacket with largest type less than max */
1418 for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1419 value = q->sub_packet_list_B[j].packet->type;
1420 if (value > min && value < max) {
1422 packet = q->sub_packet_list_B[j].packet;
1428 /* check for errors (?) */
1432 if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
1435 /* decode FFT tones */
1436 init_get_bits (&gb, packet->data, packet->size*8);
1438 if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1443 type = packet->type;
1445 if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1446 int duration = q->sub_sampling + 5 - (type & 15);
1448 if (duration >= 0 && duration < 4)
1449 qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1450 } else if (type == 31) {
1451 for (j=0; j < 4; j++)
1452 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1453 } else if (type == 46) {
1454 for (j=0; j < 6; j++)
1455 q->fft_level_exp[j] = get_bits(&gb, 6);
1456 for (j=0; j < 4; j++)
1457 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1459 } // Loop on B packets
1461 /* calculate maximum indexes for FFT coefficients */
1462 for (i = 0, j = -1; i < 5; i++)
1463 if (q->fft_coefs_min_index[i] >= 0) {
1465 q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1469 q->fft_coefs_max_index[j] = q->fft_coefs_index;
1473 static void qdm2_fft_generate_tone (QDM2Context *q, FFTTone *tone)
1478 const double iscale = 2.0*M_PI / 512.0;
1480 tone->phase += tone->phase_shift;
1482 /* calculate current level (maximum amplitude) of tone */
1483 level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1484 c.im = level * sin(tone->phase*iscale);
1485 c.re = level * cos(tone->phase*iscale);
1487 /* generate FFT coefficients for tone */
1488 if (tone->duration >= 3 || tone->cutoff >= 3) {
1489 tone->complex[0].im += c.im;
1490 tone->complex[0].re += c.re;
1491 tone->complex[1].im -= c.im;
1492 tone->complex[1].re -= c.re;
1494 f[1] = -tone->table[4];
1495 f[0] = tone->table[3] - tone->table[0];
1496 f[2] = 1.0 - tone->table[2] - tone->table[3];
1497 f[3] = tone->table[1] + tone->table[4] - 1.0;
1498 f[4] = tone->table[0] - tone->table[1];
1499 f[5] = tone->table[2];
1500 for (i = 0; i < 2; i++) {
1501 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
1502 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
1504 for (i = 0; i < 4; i++) {
1505 tone->complex[i].re += c.re * f[i+2];
1506 tone->complex[i].im += c.im * f[i+2];
1510 /* copy the tone if it has not yet died out */
1511 if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1512 memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1513 q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1518 static void qdm2_fft_tone_synthesizer (QDM2Context *q, int sub_packet)
1521 const double iscale = 0.25 * M_PI;
1523 for (ch = 0; ch < q->channels; ch++) {
1524 memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1528 /* apply FFT tones with duration 4 (1 FFT period) */
1529 if (q->fft_coefs_min_index[4] >= 0)
1530 for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1534 if (q->fft_coefs[i].sub_packet != sub_packet)
1537 ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1538 level = (q->fft_coefs[i].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[i].exp & 63];
1540 c.re = level * cos(q->fft_coefs[i].phase * iscale);
1541 c.im = level * sin(q->fft_coefs[i].phase * iscale);
1542 q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1543 q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1544 q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1545 q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1548 /* generate existing FFT tones */
1549 for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1550 qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1551 q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1554 /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1555 for (i = 0; i < 4; i++)
1556 if (q->fft_coefs_min_index[i] >= 0) {
1557 for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1561 if (q->fft_coefs[j].sub_packet != sub_packet)
1565 offset = q->fft_coefs[j].offset >> four_i;
1566 ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1568 if (offset < q->frequency_range) {
1570 tone.cutoff = offset;
1572 tone.cutoff = (offset >= 60) ? 3 : 2;
1574 tone.level = (q->fft_coefs[j].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[j].exp & 63];
1575 tone.complex = &q->fft.complex[ch][offset];
1576 tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1577 tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1578 tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1580 tone.time_index = 0;
1582 qdm2_fft_generate_tone(q, &tone);
1585 q->fft_coefs_min_index[i] = j;
1590 static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
1592 const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1593 float *out = q->output_buffer + channel;
1595 q->fft.complex[channel][0].re *= 2.0f;
1596 q->fft.complex[channel][0].im = 0.0f;
1597 q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1598 /* add samples to output buffer */
1599 for (i = 0; i < FFALIGN(q->fft_size, 8); i++) {
1600 out[0] += q->fft.complex[channel][i].re * gain;
1601 out[q->channels] += q->fft.complex[channel][i].im * gain;
1602 out += 2 * q->channels;
1609 * @param index subpacket number
1611 static void qdm2_synthesis_filter (QDM2Context *q, int index)
1613 int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1615 /* copy sb_samples */
1616 sb_used = QDM2_SB_USED(q->sub_sampling);
1618 for (ch = 0; ch < q->channels; ch++)
1619 for (i = 0; i < 8; i++)
1620 for (k=sb_used; k < SBLIMIT; k++)
1621 q->sb_samples[ch][(8 * index) + i][k] = 0;
1623 for (ch = 0; ch < q->nb_channels; ch++) {
1624 float *samples_ptr = q->samples + ch;
1626 for (i = 0; i < 8; i++) {
1627 ff_mpa_synth_filter_float(&q->mpadsp,
1628 q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1629 ff_mpa_synth_window_float, &dither_state,
1630 samples_ptr, q->nb_channels,
1631 q->sb_samples[ch][(8 * index) + i]);
1632 samples_ptr += 32 * q->nb_channels;
1636 /* add samples to output buffer */
1637 sub_sampling = (4 >> q->sub_sampling);
1639 for (ch = 0; ch < q->channels; ch++)
1640 for (i = 0; i < q->frame_size; i++)
1641 q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
1646 * Init static data (does not depend on specific file)
1650 static av_cold void qdm2_init(QDM2Context *q) {
1651 static int initialized = 0;
1653 if (initialized != 0)
1658 ff_mpa_synth_init_float(ff_mpa_synth_window_float);
1659 softclip_table_init();
1661 init_noise_samples();
1663 av_log(NULL, AV_LOG_DEBUG, "init done\n");
1668 static void dump_context(QDM2Context *q)
1671 #define PRINT(a,b) av_log(NULL,AV_LOG_DEBUG," %s = %d\n", a, b);
1672 PRINT("compressed_data",q->compressed_data);
1673 PRINT("compressed_size",q->compressed_size);
1674 PRINT("frame_size",q->frame_size);
1675 PRINT("checksum_size",q->checksum_size);
1676 PRINT("channels",q->channels);
1677 PRINT("nb_channels",q->nb_channels);
1678 PRINT("fft_size",q->fft_size);
1679 PRINT("sub_sampling",q->sub_sampling);
1680 PRINT("fft_order",q->fft_order);
1681 PRINT("group_order",q->group_order);
1682 PRINT("group_size",q->group_size);
1683 PRINT("sub_packet",q->sub_packet);
1684 PRINT("frequency_range",q->frequency_range);
1685 PRINT("has_errors",q->has_errors);
1686 PRINT("fft_tone_end",q->fft_tone_end);
1687 PRINT("fft_tone_start",q->fft_tone_start);
1688 PRINT("fft_coefs_index",q->fft_coefs_index);
1689 PRINT("coeff_per_sb_select",q->coeff_per_sb_select);
1690 PRINT("cm_table_select",q->cm_table_select);
1691 PRINT("noise_idx",q->noise_idx);
1693 for (i = q->fft_tone_start; i < q->fft_tone_end; i++)
1695 FFTTone *t = &q->fft_tones[i];
1697 av_log(NULL,AV_LOG_DEBUG,"Tone (%d) dump:\n", i);
1698 av_log(NULL,AV_LOG_DEBUG," level = %f\n", t->level);
1699 // PRINT(" level", t->level);
1700 PRINT(" phase", t->phase);
1701 PRINT(" phase_shift", t->phase_shift);
1702 PRINT(" duration", t->duration);
1703 PRINT(" samples_im", t->samples_im);
1704 PRINT(" samples_re", t->samples_re);
1705 PRINT(" table", t->table);
1713 * Init parameters from codec extradata
1715 static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1717 QDM2Context *s = avctx->priv_data;
1720 int tmp_val, tmp, size;
1722 /* extradata parsing
1731 32 size (including this field)
1733 32 type (=QDM2 or QDMC)
1735 32 size (including this field, in bytes)
1736 32 tag (=QDCA) // maybe mandatory parameters
1739 32 samplerate (=44100)
1741 32 block size (=4096)
1742 32 frame size (=256) (for one channel)
1743 32 packet size (=1300)
1745 32 size (including this field, in bytes)
1746 32 tag (=QDCP) // maybe some tuneable parameters
1756 if (!avctx->extradata || (avctx->extradata_size < 48)) {
1757 av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1761 extradata = avctx->extradata;
1762 extradata_size = avctx->extradata_size;
1764 while (extradata_size > 7) {
1765 if (!memcmp(extradata, "frmaQDM", 7))
1771 if (extradata_size < 12) {
1772 av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1777 if (memcmp(extradata, "frmaQDM", 7)) {
1778 av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1782 if (extradata[7] == 'C') {
1784 av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1789 extradata_size -= 8;
1791 size = AV_RB32(extradata);
1793 if(size > extradata_size){
1794 av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1795 extradata_size, size);
1800 av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1801 if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1802 av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1808 avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1810 if (s->channels > MPA_MAX_CHANNELS)
1811 return AVERROR_INVALIDDATA;
1813 avctx->sample_rate = AV_RB32(extradata);
1816 avctx->bit_rate = AV_RB32(extradata);
1819 s->group_size = AV_RB32(extradata);
1822 s->fft_size = AV_RB32(extradata);
1825 s->checksum_size = AV_RB32(extradata);
1826 if (s->checksum_size >= 1U << 28) {
1827 av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
1828 return AVERROR_INVALIDDATA;
1831 s->fft_order = av_log2(s->fft_size) + 1;
1833 // something like max decodable tones
1834 s->group_order = av_log2(s->group_size) + 1;
1835 s->frame_size = s->group_size / 16; // 16 iterations per super block
1836 if (s->frame_size > QDM2_MAX_FRAME_SIZE)
1837 return AVERROR_INVALIDDATA;
1839 s->sub_sampling = s->fft_order - 7;
1840 s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1842 switch ((s->sub_sampling * 2 + s->channels - 1)) {
1843 case 0: tmp = 40; break;
1844 case 1: tmp = 48; break;
1845 case 2: tmp = 56; break;
1846 case 3: tmp = 72; break;
1847 case 4: tmp = 80; break;
1848 case 5: tmp = 100;break;
1849 default: tmp=s->sub_sampling; break;
1852 if ((tmp * 1000) < avctx->bit_rate) tmp_val = 1;
1853 if ((tmp * 1440) < avctx->bit_rate) tmp_val = 2;
1854 if ((tmp * 1760) < avctx->bit_rate) tmp_val = 3;
1855 if ((tmp * 2240) < avctx->bit_rate) tmp_val = 4;
1856 s->cm_table_select = tmp_val;
1858 if (s->sub_sampling == 0)
1861 tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1868 s->coeff_per_sb_select = 0;
1869 else if (tmp <= 16000)
1870 s->coeff_per_sb_select = 1;
1872 s->coeff_per_sb_select = 2;
1874 // Fail on unknown fft order
1875 if ((s->fft_order < 7) || (s->fft_order > 9)) {
1876 av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1880 ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
1881 ff_mpadsp_init(&s->mpadsp);
1885 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1887 avcodec_get_frame_defaults(&s->frame);
1888 avctx->coded_frame = &s->frame;
1895 static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1897 QDM2Context *s = avctx->priv_data;
1899 ff_rdft_end(&s->rdft_ctx);
1905 static int qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
1908 const int frame_size = (q->frame_size * q->channels);
1910 /* select input buffer */
1911 q->compressed_data = in;
1912 q->compressed_size = q->checksum_size;
1916 /* copy old block, clear new block of output samples */
1917 memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1918 memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1920 /* decode block of QDM2 compressed data */
1921 if (q->sub_packet == 0) {
1922 q->has_errors = 0; // zero it for a new super block
1923 av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1924 qdm2_decode_super_block(q);
1927 /* parse subpackets */
1928 if (!q->has_errors) {
1929 if (q->sub_packet == 2)
1930 qdm2_decode_fft_packets(q);
1932 qdm2_fft_tone_synthesizer(q, q->sub_packet);
1935 /* sound synthesis stage 1 (FFT) */
1936 for (ch = 0; ch < q->channels; ch++) {
1937 qdm2_calculate_fft(q, ch, q->sub_packet);
1939 if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1940 SAMPLES_NEEDED_2("has errors, and C list is not empty")
1945 /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1946 if (!q->has_errors && q->do_synth_filter)
1947 qdm2_synthesis_filter(q, q->sub_packet);
1949 q->sub_packet = (q->sub_packet + 1) % 16;
1951 /* clip and convert output float[] to 16bit signed samples */
1952 for (i = 0; i < frame_size; i++) {
1953 int value = (int)q->output_buffer[i];
1955 if (value > SOFTCLIP_THRESHOLD)
1956 value = (value > HARDCLIP_THRESHOLD) ? 32767 : softclip_table[ value - SOFTCLIP_THRESHOLD];
1957 else if (value < -SOFTCLIP_THRESHOLD)
1958 value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1967 static int qdm2_decode_frame(AVCodecContext *avctx, void *data,
1968 int *got_frame_ptr, AVPacket *avpkt)
1970 const uint8_t *buf = avpkt->data;
1971 int buf_size = avpkt->size;
1972 QDM2Context *s = avctx->priv_data;
1978 if(buf_size < s->checksum_size)
1981 /* get output buffer */
1982 s->frame.nb_samples = 16 * s->frame_size;
1983 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
1984 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1987 out = (int16_t *)s->frame.data[0];
1989 for (i = 0; i < 16; i++) {
1990 if (qdm2_decode(s, buf, out) < 0)
1992 out += s->channels * s->frame_size;
1996 *(AVFrame *)data = s->frame;
1998 return s->checksum_size;
2001 AVCodec ff_qdm2_decoder =
2004 .type = AVMEDIA_TYPE_AUDIO,
2005 .id = CODEC_ID_QDM2,
2006 .priv_data_size = sizeof(QDM2Context),
2007 .init = qdm2_decode_init,
2008 .close = qdm2_decode_close,
2009 .decode = qdm2_decode_frame,
2010 .capabilities = CODEC_CAP_DR1,
2011 .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),