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 FFmpeg.
10 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 BITS_LEFT(length,gb) ((length) - get_bits_count ((gb)))
74 #define SAMPLES_NEEDED \
75 av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
77 #define SAMPLES_NEEDED_2(why) \
78 av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
80 #define QDM2_MAX_FRAME_SIZE 512
82 typedef int8_t sb_int8_array[2][30][64];
88 int type; ///< subpacket type
89 unsigned int size; ///< subpacket size
90 const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
94 * A node in the subpacket list
96 typedef struct QDM2SubPNode {
97 QDM2SubPacket *packet; ///< packet
98 struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
108 QDM2Complex *complex;
126 DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
130 * QDM2 decoder context
135 /// Parameters from codec header, do not change during playback
136 int nb_channels; ///< number of channels
137 int channels; ///< number of channels
138 int group_size; ///< size of frame group (16 frames per group)
139 int fft_size; ///< size of FFT, in complex numbers
140 int checksum_size; ///< size of data block, used also for checksum
142 /// Parameters built from header parameters, do not change during playback
143 int group_order; ///< order of frame group
144 int fft_order; ///< order of FFT (actually fftorder+1)
145 int fft_frame_size; ///< size of fft frame, in components (1 comples = re + im)
146 int frame_size; ///< size of data frame
148 int sub_sampling; ///< subsampling: 0=25%, 1=50%, 2=100% */
149 int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
150 int cm_table_select; ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
152 /// Packets and packet lists
153 QDM2SubPacket sub_packets[16]; ///< the packets themselves
154 QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
155 QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
156 int sub_packets_B; ///< number of packets on 'B' list
157 QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
158 QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
161 FFTTone fft_tones[1000];
164 FFTCoefficient fft_coefs[1000];
166 int fft_coefs_min_index[5];
167 int fft_coefs_max_index[5];
168 int fft_level_exp[6];
169 RDFTContext rdft_ctx;
173 const uint8_t *compressed_data;
175 float output_buffer[QDM2_MAX_FRAME_SIZE * MPA_MAX_CHANNELS * 2];
178 MPADSPContext mpadsp;
179 DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
180 int synth_buf_offset[MPA_MAX_CHANNELS];
181 DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
182 DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
184 /// Mixed temporary data used in decoding
185 float tone_level[MPA_MAX_CHANNELS][30][64];
186 int8_t coding_method[MPA_MAX_CHANNELS][30][64];
187 int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
188 int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
189 int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
190 int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
191 int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
192 int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
193 int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
196 int has_errors; ///< packet has errors
197 int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
198 int do_synth_filter; ///< used to perform or skip synthesis filter
201 int noise_idx; ///< index for dithering noise table
205 static uint8_t empty_buffer[FF_INPUT_BUFFER_PADDING_SIZE];
207 static VLC vlc_tab_level;
208 static VLC vlc_tab_diff;
209 static VLC vlc_tab_run;
210 static VLC fft_level_exp_alt_vlc;
211 static VLC fft_level_exp_vlc;
212 static VLC fft_stereo_exp_vlc;
213 static VLC fft_stereo_phase_vlc;
214 static VLC vlc_tab_tone_level_idx_hi1;
215 static VLC vlc_tab_tone_level_idx_mid;
216 static VLC vlc_tab_tone_level_idx_hi2;
217 static VLC vlc_tab_type30;
218 static VLC vlc_tab_type34;
219 static VLC vlc_tab_fft_tone_offset[5];
221 static const uint16_t qdm2_vlc_offs[] = {
222 0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
225 static av_cold void qdm2_init_vlc(void)
227 static int vlcs_initialized = 0;
228 static VLC_TYPE qdm2_table[3838][2];
230 if (!vlcs_initialized) {
232 vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
233 vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
234 init_vlc (&vlc_tab_level, 8, 24,
235 vlc_tab_level_huffbits, 1, 1,
236 vlc_tab_level_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
238 vlc_tab_diff.table = &qdm2_table[qdm2_vlc_offs[1]];
239 vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
240 init_vlc (&vlc_tab_diff, 8, 37,
241 vlc_tab_diff_huffbits, 1, 1,
242 vlc_tab_diff_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
244 vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
245 vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
246 init_vlc (&vlc_tab_run, 5, 6,
247 vlc_tab_run_huffbits, 1, 1,
248 vlc_tab_run_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
250 fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
251 fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
252 init_vlc (&fft_level_exp_alt_vlc, 8, 28,
253 fft_level_exp_alt_huffbits, 1, 1,
254 fft_level_exp_alt_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
257 fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
258 fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
259 init_vlc (&fft_level_exp_vlc, 8, 20,
260 fft_level_exp_huffbits, 1, 1,
261 fft_level_exp_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
263 fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
264 fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
265 init_vlc (&fft_stereo_exp_vlc, 6, 7,
266 fft_stereo_exp_huffbits, 1, 1,
267 fft_stereo_exp_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
269 fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
270 fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
271 init_vlc (&fft_stereo_phase_vlc, 6, 9,
272 fft_stereo_phase_huffbits, 1, 1,
273 fft_stereo_phase_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
275 vlc_tab_tone_level_idx_hi1.table = &qdm2_table[qdm2_vlc_offs[7]];
276 vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
277 init_vlc (&vlc_tab_tone_level_idx_hi1, 8, 20,
278 vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
279 vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
281 vlc_tab_tone_level_idx_mid.table = &qdm2_table[qdm2_vlc_offs[8]];
282 vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
283 init_vlc (&vlc_tab_tone_level_idx_mid, 8, 24,
284 vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
285 vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
287 vlc_tab_tone_level_idx_hi2.table = &qdm2_table[qdm2_vlc_offs[9]];
288 vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
289 init_vlc (&vlc_tab_tone_level_idx_hi2, 8, 24,
290 vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
291 vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
293 vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
294 vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
295 init_vlc (&vlc_tab_type30, 6, 9,
296 vlc_tab_type30_huffbits, 1, 1,
297 vlc_tab_type30_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
299 vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
300 vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
301 init_vlc (&vlc_tab_type34, 5, 10,
302 vlc_tab_type34_huffbits, 1, 1,
303 vlc_tab_type34_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
305 vlc_tab_fft_tone_offset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
306 vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
307 init_vlc (&vlc_tab_fft_tone_offset[0], 8, 23,
308 vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
309 vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
311 vlc_tab_fft_tone_offset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
312 vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
313 init_vlc (&vlc_tab_fft_tone_offset[1], 8, 28,
314 vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
315 vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
317 vlc_tab_fft_tone_offset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
318 vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
319 init_vlc (&vlc_tab_fft_tone_offset[2], 8, 32,
320 vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
321 vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
323 vlc_tab_fft_tone_offset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
324 vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
325 init_vlc (&vlc_tab_fft_tone_offset[3], 8, 35,
326 vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
327 vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
329 vlc_tab_fft_tone_offset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
330 vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
331 init_vlc (&vlc_tab_fft_tone_offset[4], 8, 38,
332 vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
333 vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
339 static int qdm2_get_vlc (GetBitContext *gb, VLC *vlc, int flag, int depth)
343 value = get_vlc2(gb, vlc->table, vlc->bits, depth);
345 /* stage-2, 3 bits exponent escape sequence */
347 value = get_bits (gb, get_bits (gb, 3) + 1);
349 /* stage-3, optional */
351 int tmp = vlc_stage3_values[value];
353 if ((value & ~3) > 0)
354 tmp += get_bits (gb, (value >> 2));
362 static int qdm2_get_se_vlc (VLC *vlc, GetBitContext *gb, int depth)
364 int value = qdm2_get_vlc (gb, vlc, 0, depth);
366 return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
373 * @param data pointer to data to be checksum'ed
374 * @param length data length
375 * @param value checksum value
377 * @return 0 if checksum is OK
379 static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value) {
382 for (i=0; i < length; i++)
385 return (uint16_t)(value & 0xffff);
390 * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
392 * @param gb bitreader context
393 * @param sub_packet packet under analysis
395 static void qdm2_decode_sub_packet_header (GetBitContext *gb, QDM2SubPacket *sub_packet)
397 sub_packet->type = get_bits (gb, 8);
399 if (sub_packet->type == 0) {
400 sub_packet->size = 0;
401 sub_packet->data = NULL;
403 sub_packet->size = get_bits (gb, 8);
405 if (sub_packet->type & 0x80) {
406 sub_packet->size <<= 8;
407 sub_packet->size |= get_bits (gb, 8);
408 sub_packet->type &= 0x7f;
411 if (sub_packet->type == 0x7f)
412 sub_packet->type |= (get_bits (gb, 8) << 8);
414 sub_packet->data = &gb->buffer[get_bits_count(gb) / 8]; // FIXME: this depends on bitreader internal data
417 av_log(NULL,AV_LOG_DEBUG,"Subpacket: type=%d size=%d start_offs=%x\n",
418 sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
423 * Return node pointer to first packet of requested type in list.
425 * @param list list of subpackets to be scanned
426 * @param type type of searched subpacket
427 * @return node pointer for subpacket if found, else NULL
429 static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int type)
431 while (list != NULL && list->packet != NULL) {
432 if (list->packet->type == type)
441 * Replace 8 elements with their average value.
442 * Called by qdm2_decode_superblock before starting subblock decoding.
446 static void average_quantized_coeffs (QDM2Context *q)
448 int i, j, n, ch, sum;
450 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
452 for (ch = 0; ch < q->nb_channels; ch++)
453 for (i = 0; i < n; i++) {
456 for (j = 0; j < 8; j++)
457 sum += q->quantized_coeffs[ch][i][j];
463 for (j=0; j < 8; j++)
464 q->quantized_coeffs[ch][i][j] = sum;
470 * Build subband samples with noise weighted by q->tone_level.
471 * Called by synthfilt_build_sb_samples.
474 * @param sb subband index
476 static void build_sb_samples_from_noise (QDM2Context *q, int sb)
480 FIX_NOISE_IDX(q->noise_idx);
485 for (ch = 0; ch < q->nb_channels; ch++)
486 for (j = 0; j < 64; j++) {
487 q->sb_samples[ch][j * 2][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
488 q->sb_samples[ch][j * 2 + 1][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
494 * Called while processing data from subpackets 11 and 12.
495 * Used after making changes to coding_method array.
497 * @param sb subband index
498 * @param channels number of channels
499 * @param coding_method q->coding_method[0][0][0]
501 static void fix_coding_method_array (int sb, int channels, sb_int8_array coding_method)
506 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};
508 for (ch = 0; ch < channels; ch++) {
509 for (j = 0; j < 64; ) {
510 if((coding_method[ch][sb][j] - 8) > 22) {
514 switch (switchtable[coding_method[ch][sb][j]-8]) {
515 case 0: run = 10; case_val = 10; break;
516 case 1: run = 1; case_val = 16; break;
517 case 2: run = 5; case_val = 24; break;
518 case 3: run = 3; case_val = 30; break;
519 case 4: run = 1; case_val = 30; break;
520 case 5: run = 1; case_val = 8; break;
521 default: run = 1; case_val = 8; break;
524 for (k = 0; k < run; k++)
526 if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
529 //not debugged, almost never used
530 memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8_t));
531 memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8_t));
540 * Related to synthesis filter
541 * Called by process_subpacket_10
544 * @param flag 1 if called after getting data from subpacket 10, 0 if no subpacket 10
546 static void fill_tone_level_array (QDM2Context *q, int flag)
548 int i, sb, ch, sb_used;
551 // This should never happen
552 if (q->nb_channels <= 0)
555 for (ch = 0; ch < q->nb_channels; ch++)
556 for (sb = 0; sb < 30; sb++)
557 for (i = 0; i < 8; i++) {
558 if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
559 tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
560 q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
562 tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
565 q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
568 sb_used = QDM2_SB_USED(q->sub_sampling);
570 if ((q->superblocktype_2_3 != 0) && !flag) {
571 for (sb = 0; sb < sb_used; sb++)
572 for (ch = 0; ch < q->nb_channels; ch++)
573 for (i = 0; i < 64; i++) {
574 q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
575 if (q->tone_level_idx[ch][sb][i] < 0)
576 q->tone_level[ch][sb][i] = 0;
578 q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
581 tab = q->superblocktype_2_3 ? 0 : 1;
582 for (sb = 0; sb < sb_used; sb++) {
583 if ((sb >= 4) && (sb <= 23)) {
584 for (ch = 0; ch < q->nb_channels; ch++)
585 for (i = 0; i < 64; i++) {
586 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
587 q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
588 q->tone_level_idx_mid[ch][sb - 4][i / 8] -
589 q->tone_level_idx_hi2[ch][sb - 4];
590 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
591 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
592 q->tone_level[ch][sb][i] = 0;
594 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
598 for (ch = 0; ch < q->nb_channels; ch++)
599 for (i = 0; i < 64; i++) {
600 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
601 q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
602 q->tone_level_idx_hi2[ch][sb - 4];
603 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
604 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
605 q->tone_level[ch][sb][i] = 0;
607 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
610 for (ch = 0; ch < q->nb_channels; ch++)
611 for (i = 0; i < 64; i++) {
612 tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
613 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
614 q->tone_level[ch][sb][i] = 0;
616 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
628 * Related to synthesis filter
629 * Called by process_subpacket_11
630 * c is built with data from subpacket 11
631 * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
633 * @param tone_level_idx
634 * @param tone_level_idx_temp
635 * @param coding_method q->coding_method[0][0][0]
636 * @param nb_channels number of channels
637 * @param c coming from subpacket 11, passed as 8*c
638 * @param superblocktype_2_3 flag based on superblock packet type
639 * @param cm_table_select q->cm_table_select
641 static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
642 sb_int8_array coding_method, int nb_channels,
643 int c, int superblocktype_2_3, int cm_table_select)
646 int tmp, acc, esp_40, comp;
647 int add1, add2, add3, add4;
650 // This should never happen
651 if (nb_channels <= 0)
654 if (!superblocktype_2_3) {
655 /* This case is untested, no samples available */
657 for (ch = 0; ch < nb_channels; ch++)
658 for (sb = 0; sb < 30; sb++) {
659 for (j = 1; j < 63; j++) { // The loop only iterates to 63 so the code doesn't overflow the buffer
660 add1 = tone_level_idx[ch][sb][j] - 10;
663 add2 = add3 = add4 = 0;
665 add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
670 add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
675 add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
679 tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
682 tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
684 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
687 for (ch = 0; ch < nb_channels; ch++)
688 for (sb = 0; sb < 30; sb++)
689 for (j = 0; j < 64; j++)
690 acc += tone_level_idx_temp[ch][sb][j];
692 multres = 0x66666667 * (acc * 10);
693 esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
694 for (ch = 0; ch < nb_channels; ch++)
695 for (sb = 0; sb < 30; sb++)
696 for (j = 0; j < 64; j++) {
697 comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
700 comp /= 256; // signed shift
728 coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
730 for (sb = 0; sb < 30; sb++)
731 fix_coding_method_array(sb, nb_channels, coding_method);
732 for (ch = 0; ch < nb_channels; ch++)
733 for (sb = 0; sb < 30; sb++)
734 for (j = 0; j < 64; j++)
736 if (coding_method[ch][sb][j] < 10)
737 coding_method[ch][sb][j] = 10;
740 if (coding_method[ch][sb][j] < 16)
741 coding_method[ch][sb][j] = 16;
743 if (coding_method[ch][sb][j] < 30)
744 coding_method[ch][sb][j] = 30;
747 } else { // superblocktype_2_3 != 0
748 for (ch = 0; ch < nb_channels; ch++)
749 for (sb = 0; sb < 30; sb++)
750 for (j = 0; j < 64; j++)
751 coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
760 * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
761 * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
764 * @param gb bitreader context
765 * @param length packet length in bits
766 * @param sb_min lower subband processed (sb_min included)
767 * @param sb_max higher subband processed (sb_max excluded)
769 static int synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)
771 int sb, j, k, n, ch, run, channels;
772 int joined_stereo, zero_encoding, chs;
774 float type34_div = 0;
775 float type34_predictor;
776 float samples[10], sign_bits[16];
779 // If no data use noise
780 for (sb=sb_min; sb < sb_max; sb++)
781 build_sb_samples_from_noise (q, sb);
786 for (sb = sb_min; sb < sb_max; sb++) {
787 FIX_NOISE_IDX(q->noise_idx);
789 channels = q->nb_channels;
791 if (q->nb_channels <= 1 || sb < 12)
796 joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;
799 if (BITS_LEFT(length,gb) >= 16)
800 for (j = 0; j < 16; j++)
801 sign_bits[j] = get_bits1 (gb);
803 for (j = 0; j < 64; j++)
804 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
805 q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
807 fix_coding_method_array(sb, q->nb_channels, q->coding_method);
811 for (ch = 0; ch < channels; ch++) {
812 zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;
813 type34_predictor = 0.0;
816 for (j = 0; j < 128; ) {
817 switch (q->coding_method[ch][sb][j / 2]) {
819 if (BITS_LEFT(length,gb) >= 10) {
821 for (k = 0; k < 5; k++) {
822 if ((j + 2 * k) >= 128)
824 samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
828 for (k = 0; k < 5; k++)
829 samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
831 for (k = 0; k < 5; k++)
832 samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
834 for (k = 0; k < 10; k++)
835 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
841 if (BITS_LEFT(length,gb) >= 1) {
846 f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
849 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
855 if (BITS_LEFT(length,gb) >= 10) {
857 for (k = 0; k < 5; k++) {
860 samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
863 n = get_bits (gb, 8);
864 for (k = 0; k < 5; k++)
865 samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
868 for (k = 0; k < 5; k++)
869 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
875 if (BITS_LEFT(length,gb) >= 7) {
877 for (k = 0; k < 3; k++)
878 samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
880 for (k = 0; k < 3; k++)
881 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
887 if (BITS_LEFT(length,gb) >= 4) {
888 unsigned v = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);
889 if (v >= FF_ARRAY_ELEMS(type30_dequant))
890 return AVERROR_INVALIDDATA;
891 samples[0] = type30_dequant[v];
893 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
899 if (BITS_LEFT(length,gb) >= 7) {
901 type34_div = (float)(1 << get_bits(gb, 2));
902 samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
903 type34_predictor = samples[0];
906 unsigned v = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);
907 if (v >= FF_ARRAY_ELEMS(type34_delta))
908 return AVERROR_INVALIDDATA;
909 samples[0] = type34_delta[v] / type34_div + type34_predictor;
910 type34_predictor = samples[0];
913 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
919 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
925 float tmp[10][MPA_MAX_CHANNELS];
927 for (k = 0; k < run; k++) {
928 tmp[k][0] = samples[k];
929 tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
931 for (chs = 0; chs < q->nb_channels; chs++)
932 for (k = 0; k < run; k++)
934 q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];
936 for (k = 0; k < run; k++)
938 q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
950 * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
951 * This is similar to process_subpacket_9, but for a single channel and for element [0]
952 * same VLC tables as process_subpacket_9 are used.
954 * @param quantized_coeffs pointer to quantized_coeffs[ch][0]
955 * @param gb bitreader context
956 * @param length packet length in bits
958 static int init_quantized_coeffs_elem0 (int8_t *quantized_coeffs, GetBitContext *gb, int length)
960 int i, k, run, level, diff;
962 if (BITS_LEFT(length,gb) < 16)
964 level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
966 quantized_coeffs[0] = level;
968 for (i = 0; i < 7; ) {
969 if (BITS_LEFT(length,gb) < 16)
971 run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
976 if (BITS_LEFT(length,gb) < 16)
978 diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
980 for (k = 1; k <= run; k++)
981 quantized_coeffs[i + k] = (level + ((k * diff) / run));
991 * Related to synthesis filter, process data from packet 10
992 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
993 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
996 * @param gb bitreader context
997 * @param length packet length in bits
999 static void init_tone_level_dequantization (QDM2Context *q, GetBitContext *gb, int length)
1001 int sb, j, k, n, ch;
1003 for (ch = 0; ch < q->nb_channels; ch++) {
1004 init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb, length);
1006 if (BITS_LEFT(length,gb) < 16) {
1007 memset(q->quantized_coeffs[ch][0], 0, 8);
1012 n = q->sub_sampling + 1;
1014 for (sb = 0; sb < n; sb++)
1015 for (ch = 0; ch < q->nb_channels; ch++)
1016 for (j = 0; j < 8; j++) {
1017 if (BITS_LEFT(length,gb) < 1)
1019 if (get_bits1(gb)) {
1020 for (k=0; k < 8; k++) {
1021 if (BITS_LEFT(length,gb) < 16)
1023 q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1026 for (k=0; k < 8; k++)
1027 q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1031 n = QDM2_SB_USED(q->sub_sampling) - 4;
1033 for (sb = 0; sb < n; sb++)
1034 for (ch = 0; ch < q->nb_channels; ch++) {
1035 if (BITS_LEFT(length,gb) < 16)
1037 q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1039 q->tone_level_idx_hi2[ch][sb] -= 16;
1041 for (j = 0; j < 8; j++)
1042 q->tone_level_idx_mid[ch][sb][j] = -16;
1045 n = QDM2_SB_USED(q->sub_sampling) - 5;
1047 for (sb = 0; sb < n; sb++)
1048 for (ch = 0; ch < q->nb_channels; ch++)
1049 for (j = 0; j < 8; j++) {
1050 if (BITS_LEFT(length,gb) < 16)
1052 q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1057 * Process subpacket 9, init quantized_coeffs with data from it
1060 * @param node pointer to node with packet
1062 static int process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
1065 int i, j, k, n, ch, run, level, diff;
1067 init_get_bits(&gb, node->packet->data, node->packet->size*8);
1069 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1; // same as averagesomething function
1071 for (i = 1; i < n; i++)
1072 for (ch=0; ch < q->nb_channels; ch++) {
1073 level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1074 q->quantized_coeffs[ch][i][0] = level;
1076 for (j = 0; j < (8 - 1); ) {
1077 run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1078 diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1083 for (k = 1; k <= run; k++)
1084 q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
1091 for (ch = 0; ch < q->nb_channels; ch++)
1092 for (i = 0; i < 8; i++)
1093 q->quantized_coeffs[ch][0][i] = 0;
1100 * Process subpacket 10 if not null, else
1103 * @param node pointer to node with packet
1104 * @param length packet length in bits
1106 static void process_subpacket_10 (QDM2Context *q, QDM2SubPNode *node, int length)
1110 init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1113 init_tone_level_dequantization(q, &gb, length);
1114 fill_tone_level_array(q, 1);
1116 fill_tone_level_array(q, 0);
1122 * Process subpacket 11
1125 * @param node pointer to node with packet
1126 * @param length packet length in bit
1128 static void process_subpacket_11 (QDM2Context *q, QDM2SubPNode *node, int length)
1132 init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1134 int c = get_bits (&gb, 13);
1137 fill_coding_method_array (q->tone_level_idx, q->tone_level_idx_temp, q->coding_method,
1138 q->nb_channels, 8*c, q->superblocktype_2_3, q->cm_table_select);
1141 synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1146 * Process subpacket 12
1149 * @param node pointer to node with packet
1150 * @param length packet length in bits
1152 static void process_subpacket_12 (QDM2Context *q, QDM2SubPNode *node, int length)
1156 init_get_bits(&gb, ((node == NULL) ? empty_buffer : node->packet->data), ((node == NULL) ? 0 : node->packet->size*8));
1157 synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1161 * Process new subpackets for synthesis filter
1164 * @param list list with synthesis filter packets (list D)
1166 static void process_synthesis_subpackets (QDM2Context *q, QDM2SubPNode *list)
1168 QDM2SubPNode *nodes[4];
1170 nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1171 if (nodes[0] != NULL)
1172 process_subpacket_9(q, nodes[0]);
1174 nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1175 if (nodes[1] != NULL)
1176 process_subpacket_10(q, nodes[1], nodes[1]->packet->size << 3);
1178 process_subpacket_10(q, NULL, 0);
1180 nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1181 if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1182 process_subpacket_11(q, nodes[2], (nodes[2]->packet->size << 3));
1184 process_subpacket_11(q, NULL, 0);
1186 nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1187 if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1188 process_subpacket_12(q, nodes[3], (nodes[3]->packet->size << 3));
1190 process_subpacket_12(q, NULL, 0);
1195 * Decode superblock, fill packet lists.
1199 static void qdm2_decode_super_block (QDM2Context *q)
1202 QDM2SubPacket header, *packet;
1203 int i, packet_bytes, sub_packet_size, sub_packets_D;
1204 unsigned int next_index = 0;
1206 memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1207 memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1208 memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1210 q->sub_packets_B = 0;
1213 average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1215 init_get_bits(&gb, q->compressed_data, q->compressed_size*8);
1216 qdm2_decode_sub_packet_header(&gb, &header);
1218 if (header.type < 2 || header.type >= 8) {
1220 av_log(NULL,AV_LOG_ERROR,"bad superblock type\n");
1224 q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1225 packet_bytes = (q->compressed_size - get_bits_count(&gb) / 8);
1227 init_get_bits(&gb, header.data, header.size*8);
1229 if (header.type == 2 || header.type == 4 || header.type == 5) {
1230 int csum = 257 * get_bits(&gb, 8);
1231 csum += 2 * get_bits(&gb, 8);
1233 csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1237 av_log(NULL,AV_LOG_ERROR,"bad packet checksum\n");
1242 q->sub_packet_list_B[0].packet = NULL;
1243 q->sub_packet_list_D[0].packet = NULL;
1245 for (i = 0; i < 6; i++)
1246 if (--q->fft_level_exp[i] < 0)
1247 q->fft_level_exp[i] = 0;
1249 for (i = 0; packet_bytes > 0; i++) {
1252 q->sub_packet_list_A[i].next = NULL;
1255 q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1257 /* seek to next block */
1258 init_get_bits(&gb, header.data, header.size*8);
1259 skip_bits(&gb, next_index*8);
1261 if (next_index >= header.size)
1265 /* decode subpacket */
1266 packet = &q->sub_packets[i];
1267 qdm2_decode_sub_packet_header(&gb, packet);
1268 next_index = packet->size + get_bits_count(&gb) / 8;
1269 sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1271 if (packet->type == 0)
1274 if (sub_packet_size > packet_bytes) {
1275 if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1277 packet->size += packet_bytes - sub_packet_size;
1280 packet_bytes -= sub_packet_size;
1282 /* add subpacket to 'all subpackets' list */
1283 q->sub_packet_list_A[i].packet = packet;
1285 /* add subpacket to related list */
1286 if (packet->type == 8) {
1287 SAMPLES_NEEDED_2("packet type 8");
1289 } else if (packet->type >= 9 && packet->type <= 12) {
1290 /* packets for MPEG Audio like Synthesis Filter */
1291 QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1292 } else if (packet->type == 13) {
1293 for (j = 0; j < 6; j++)
1294 q->fft_level_exp[j] = get_bits(&gb, 6);
1295 } else if (packet->type == 14) {
1296 for (j = 0; j < 6; j++)
1297 q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1298 } else if (packet->type == 15) {
1299 SAMPLES_NEEDED_2("packet type 15")
1301 } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
1302 /* packets for FFT */
1303 QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1305 } // Packet bytes loop
1307 /* **************************************************************** */
1308 if (q->sub_packet_list_D[0].packet != NULL) {
1309 process_synthesis_subpackets(q, q->sub_packet_list_D);
1310 q->do_synth_filter = 1;
1311 } else if (q->do_synth_filter) {
1312 process_subpacket_10(q, NULL, 0);
1313 process_subpacket_11(q, NULL, 0);
1314 process_subpacket_12(q, NULL, 0);
1316 /* **************************************************************** */
1320 static void qdm2_fft_init_coefficient (QDM2Context *q, int sub_packet,
1321 int offset, int duration, int channel,
1324 if (q->fft_coefs_min_index[duration] < 0)
1325 q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1327 q->fft_coefs[q->fft_coefs_index].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1328 q->fft_coefs[q->fft_coefs_index].channel = channel;
1329 q->fft_coefs[q->fft_coefs_index].offset = offset;
1330 q->fft_coefs[q->fft_coefs_index].exp = exp;
1331 q->fft_coefs[q->fft_coefs_index].phase = phase;
1332 q->fft_coefs_index++;
1336 static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)
1338 int channel, stereo, phase, exp;
1339 int local_int_4, local_int_8, stereo_phase, local_int_10;
1340 int local_int_14, stereo_exp, local_int_20, local_int_28;
1346 local_int_8 = (4 - duration);
1347 local_int_10 = 1 << (q->group_order - duration - 1);
1350 while (get_bits_left(gb)>0) {
1351 if (q->superblocktype_2_3) {
1352 while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1355 local_int_4 += local_int_10;
1356 local_int_28 += (1 << local_int_8);
1358 local_int_4 += 8*local_int_10;
1359 local_int_28 += (8 << local_int_8);
1364 offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1365 while (offset >= (local_int_10 - 1)) {
1366 offset += (1 - (local_int_10 - 1));
1367 local_int_4 += local_int_10;
1368 local_int_28 += (1 << local_int_8);
1372 if (local_int_4 >= q->group_size)
1375 local_int_14 = (offset >> local_int_8);
1376 if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1379 if (q->nb_channels > 1) {
1380 channel = get_bits1(gb);
1381 stereo = get_bits1(gb);
1387 exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1388 exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1389 exp = (exp < 0) ? 0 : exp;
1391 phase = get_bits(gb, 3);
1396 stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1397 stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1398 if (stereo_phase < 0)
1402 if (q->frequency_range > (local_int_14 + 1)) {
1403 int sub_packet = (local_int_20 + local_int_28);
1405 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);
1407 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
1415 static void qdm2_decode_fft_packets (QDM2Context *q)
1417 int i, j, min, max, value, type, unknown_flag;
1420 if (q->sub_packet_list_B[0].packet == NULL)
1423 /* reset minimum indexes for FFT coefficients */
1424 q->fft_coefs_index = 0;
1425 for (i=0; i < 5; i++)
1426 q->fft_coefs_min_index[i] = -1;
1428 /* process subpackets ordered by type, largest type first */
1429 for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1430 QDM2SubPacket *packet= NULL;
1432 /* find subpacket with largest type less than max */
1433 for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1434 value = q->sub_packet_list_B[j].packet->type;
1435 if (value > min && value < max) {
1437 packet = q->sub_packet_list_B[j].packet;
1443 /* check for errors (?) */
1447 if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
1450 /* decode FFT tones */
1451 init_get_bits (&gb, packet->data, packet->size*8);
1453 if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1458 type = packet->type;
1460 if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1461 int duration = q->sub_sampling + 5 - (type & 15);
1463 if (duration >= 0 && duration < 4)
1464 qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1465 } else if (type == 31) {
1466 for (j=0; j < 4; j++)
1467 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1468 } else if (type == 46) {
1469 for (j=0; j < 6; j++)
1470 q->fft_level_exp[j] = get_bits(&gb, 6);
1471 for (j=0; j < 4; j++)
1472 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1474 } // Loop on B packets
1476 /* calculate maximum indexes for FFT coefficients */
1477 for (i = 0, j = -1; i < 5; i++)
1478 if (q->fft_coefs_min_index[i] >= 0) {
1480 q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1484 q->fft_coefs_max_index[j] = q->fft_coefs_index;
1488 static void qdm2_fft_generate_tone (QDM2Context *q, FFTTone *tone)
1493 const double iscale = 2.0*M_PI / 512.0;
1495 tone->phase += tone->phase_shift;
1497 /* calculate current level (maximum amplitude) of tone */
1498 level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1499 c.im = level * sin(tone->phase*iscale);
1500 c.re = level * cos(tone->phase*iscale);
1502 /* generate FFT coefficients for tone */
1503 if (tone->duration >= 3 || tone->cutoff >= 3) {
1504 tone->complex[0].im += c.im;
1505 tone->complex[0].re += c.re;
1506 tone->complex[1].im -= c.im;
1507 tone->complex[1].re -= c.re;
1509 f[1] = -tone->table[4];
1510 f[0] = tone->table[3] - tone->table[0];
1511 f[2] = 1.0 - tone->table[2] - tone->table[3];
1512 f[3] = tone->table[1] + tone->table[4] - 1.0;
1513 f[4] = tone->table[0] - tone->table[1];
1514 f[5] = tone->table[2];
1515 for (i = 0; i < 2; i++) {
1516 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
1517 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
1519 for (i = 0; i < 4; i++) {
1520 tone->complex[i].re += c.re * f[i+2];
1521 tone->complex[i].im += c.im * f[i+2];
1525 /* copy the tone if it has not yet died out */
1526 if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1527 memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1528 q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1533 static void qdm2_fft_tone_synthesizer (QDM2Context *q, int sub_packet)
1536 const double iscale = 0.25 * M_PI;
1538 for (ch = 0; ch < q->channels; ch++) {
1539 memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1543 /* apply FFT tones with duration 4 (1 FFT period) */
1544 if (q->fft_coefs_min_index[4] >= 0)
1545 for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1549 if (q->fft_coefs[i].sub_packet != sub_packet)
1552 ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1553 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];
1555 c.re = level * cos(q->fft_coefs[i].phase * iscale);
1556 c.im = level * sin(q->fft_coefs[i].phase * iscale);
1557 q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1558 q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1559 q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1560 q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1563 /* generate existing FFT tones */
1564 for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1565 qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1566 q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1569 /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1570 for (i = 0; i < 4; i++)
1571 if (q->fft_coefs_min_index[i] >= 0) {
1572 for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1576 if (q->fft_coefs[j].sub_packet != sub_packet)
1580 offset = q->fft_coefs[j].offset >> four_i;
1581 ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1583 if (offset < q->frequency_range) {
1585 tone.cutoff = offset;
1587 tone.cutoff = (offset >= 60) ? 3 : 2;
1589 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];
1590 tone.complex = &q->fft.complex[ch][offset];
1591 tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1592 tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1593 tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1595 tone.time_index = 0;
1597 qdm2_fft_generate_tone(q, &tone);
1600 q->fft_coefs_min_index[i] = j;
1605 static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
1607 const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1609 q->fft.complex[channel][0].re *= 2.0f;
1610 q->fft.complex[channel][0].im = 0.0f;
1611 q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1612 /* add samples to output buffer */
1613 for (i = 0; i < ((q->fft_frame_size + 15) & ~15); i++)
1614 q->output_buffer[q->channels * i + channel] += ((float *) q->fft.complex[channel])[i] * gain;
1620 * @param index subpacket number
1622 static void qdm2_synthesis_filter (QDM2Context *q, int index)
1624 int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1626 /* copy sb_samples */
1627 sb_used = QDM2_SB_USED(q->sub_sampling);
1629 for (ch = 0; ch < q->channels; ch++)
1630 for (i = 0; i < 8; i++)
1631 for (k=sb_used; k < SBLIMIT; k++)
1632 q->sb_samples[ch][(8 * index) + i][k] = 0;
1634 for (ch = 0; ch < q->nb_channels; ch++) {
1635 float *samples_ptr = q->samples + ch;
1637 for (i = 0; i < 8; i++) {
1638 ff_mpa_synth_filter_float(&q->mpadsp,
1639 q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1640 ff_mpa_synth_window_float, &dither_state,
1641 samples_ptr, q->nb_channels,
1642 q->sb_samples[ch][(8 * index) + i]);
1643 samples_ptr += 32 * q->nb_channels;
1647 /* add samples to output buffer */
1648 sub_sampling = (4 >> q->sub_sampling);
1650 for (ch = 0; ch < q->channels; ch++)
1651 for (i = 0; i < q->frame_size; i++)
1652 q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
1657 * Init static data (does not depend on specific file)
1661 static av_cold void qdm2_init(QDM2Context *q) {
1662 static int initialized = 0;
1664 if (initialized != 0)
1669 ff_mpa_synth_init_float(ff_mpa_synth_window_float);
1670 softclip_table_init();
1672 init_noise_samples();
1674 av_log(NULL, AV_LOG_DEBUG, "init done\n");
1679 static void dump_context(QDM2Context *q)
1682 #define PRINT(a,b) av_log(NULL,AV_LOG_DEBUG," %s = %d\n", a, b);
1683 PRINT("compressed_data",q->compressed_data);
1684 PRINT("compressed_size",q->compressed_size);
1685 PRINT("frame_size",q->frame_size);
1686 PRINT("checksum_size",q->checksum_size);
1687 PRINT("channels",q->channels);
1688 PRINT("nb_channels",q->nb_channels);
1689 PRINT("fft_frame_size",q->fft_frame_size);
1690 PRINT("fft_size",q->fft_size);
1691 PRINT("sub_sampling",q->sub_sampling);
1692 PRINT("fft_order",q->fft_order);
1693 PRINT("group_order",q->group_order);
1694 PRINT("group_size",q->group_size);
1695 PRINT("sub_packet",q->sub_packet);
1696 PRINT("frequency_range",q->frequency_range);
1697 PRINT("has_errors",q->has_errors);
1698 PRINT("fft_tone_end",q->fft_tone_end);
1699 PRINT("fft_tone_start",q->fft_tone_start);
1700 PRINT("fft_coefs_index",q->fft_coefs_index);
1701 PRINT("coeff_per_sb_select",q->coeff_per_sb_select);
1702 PRINT("cm_table_select",q->cm_table_select);
1703 PRINT("noise_idx",q->noise_idx);
1705 for (i = q->fft_tone_start; i < q->fft_tone_end; i++)
1707 FFTTone *t = &q->fft_tones[i];
1709 av_log(NULL,AV_LOG_DEBUG,"Tone (%d) dump:\n", i);
1710 av_log(NULL,AV_LOG_DEBUG," level = %f\n", t->level);
1711 // PRINT(" level", t->level);
1712 PRINT(" phase", t->phase);
1713 PRINT(" phase_shift", t->phase_shift);
1714 PRINT(" duration", t->duration);
1715 PRINT(" samples_im", t->samples_im);
1716 PRINT(" samples_re", t->samples_re);
1717 PRINT(" table", t->table);
1725 * Init parameters from codec extradata
1727 static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1729 QDM2Context *s = avctx->priv_data;
1732 int tmp_val, tmp, size;
1734 /* extradata parsing
1743 32 size (including this field)
1745 32 type (=QDM2 or QDMC)
1747 32 size (including this field, in bytes)
1748 32 tag (=QDCA) // maybe mandatory parameters
1751 32 samplerate (=44100)
1753 32 block size (=4096)
1754 32 frame size (=256) (for one channel)
1755 32 packet size (=1300)
1757 32 size (including this field, in bytes)
1758 32 tag (=QDCP) // maybe some tuneable parameters
1768 if (!avctx->extradata || (avctx->extradata_size < 48)) {
1769 av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1773 extradata = avctx->extradata;
1774 extradata_size = avctx->extradata_size;
1776 while (extradata_size > 7) {
1777 if (!memcmp(extradata, "frmaQDM", 7))
1783 if (extradata_size < 12) {
1784 av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1789 if (memcmp(extradata, "frmaQDM", 7)) {
1790 av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1794 if (extradata[7] == 'C') {
1796 av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1801 extradata_size -= 8;
1803 size = AV_RB32(extradata);
1805 if(size > extradata_size){
1806 av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1807 extradata_size, size);
1812 av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1813 if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1814 av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1820 avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1822 if (s->channels > MPA_MAX_CHANNELS)
1823 return AVERROR_INVALIDDATA;
1825 avctx->sample_rate = AV_RB32(extradata);
1828 avctx->bit_rate = AV_RB32(extradata);
1831 s->group_size = AV_RB32(extradata);
1834 s->fft_size = AV_RB32(extradata);
1837 s->checksum_size = AV_RB32(extradata);
1838 if (s->checksum_size >= 1U << 28) {
1839 av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
1840 return AVERROR_INVALIDDATA;
1843 s->fft_order = av_log2(s->fft_size) + 1;
1844 s->fft_frame_size = 2 * s->fft_size; // complex has two floats
1846 // something like max decodable tones
1847 s->group_order = av_log2(s->group_size) + 1;
1848 s->frame_size = s->group_size / 16; // 16 iterations per super block
1850 if (s->frame_size > QDM2_MAX_FRAME_SIZE)
1851 return AVERROR_INVALIDDATA;
1853 s->sub_sampling = s->fft_order - 7;
1854 s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1856 switch ((s->sub_sampling * 2 + s->channels - 1)) {
1857 case 0: tmp = 40; break;
1858 case 1: tmp = 48; break;
1859 case 2: tmp = 56; break;
1860 case 3: tmp = 72; break;
1861 case 4: tmp = 80; break;
1862 case 5: tmp = 100;break;
1863 default: tmp=s->sub_sampling; break;
1866 if ((tmp * 1000) < avctx->bit_rate) tmp_val = 1;
1867 if ((tmp * 1440) < avctx->bit_rate) tmp_val = 2;
1868 if ((tmp * 1760) < avctx->bit_rate) tmp_val = 3;
1869 if ((tmp * 2240) < avctx->bit_rate) tmp_val = 4;
1870 s->cm_table_select = tmp_val;
1872 if (s->sub_sampling == 0)
1875 tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1882 s->coeff_per_sb_select = 0;
1883 else if (tmp <= 16000)
1884 s->coeff_per_sb_select = 1;
1886 s->coeff_per_sb_select = 2;
1888 // Fail on unknown fft order
1889 if ((s->fft_order < 7) || (s->fft_order > 9)) {
1890 av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1894 ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
1895 ff_mpadsp_init(&s->mpadsp);
1899 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1901 avcodec_get_frame_defaults(&s->frame);
1902 avctx->coded_frame = &s->frame;
1909 static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1911 QDM2Context *s = avctx->priv_data;
1913 ff_rdft_end(&s->rdft_ctx);
1919 static int qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
1922 const int frame_size = (q->frame_size * q->channels);
1924 if((unsigned)frame_size > FF_ARRAY_ELEMS(q->output_buffer)/2)
1927 /* select input buffer */
1928 q->compressed_data = in;
1929 q->compressed_size = q->checksum_size;
1933 /* copy old block, clear new block of output samples */
1934 memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1935 memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1937 /* decode block of QDM2 compressed data */
1938 if (q->sub_packet == 0) {
1939 q->has_errors = 0; // zero it for a new super block
1940 av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1941 qdm2_decode_super_block(q);
1944 /* parse subpackets */
1945 if (!q->has_errors) {
1946 if (q->sub_packet == 2)
1947 qdm2_decode_fft_packets(q);
1949 qdm2_fft_tone_synthesizer(q, q->sub_packet);
1952 /* sound synthesis stage 1 (FFT) */
1953 for (ch = 0; ch < q->channels; ch++) {
1954 qdm2_calculate_fft(q, ch, q->sub_packet);
1956 if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1957 SAMPLES_NEEDED_2("has errors, and C list is not empty")
1962 /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1963 if (!q->has_errors && q->do_synth_filter)
1964 qdm2_synthesis_filter(q, q->sub_packet);
1966 q->sub_packet = (q->sub_packet + 1) % 16;
1968 /* clip and convert output float[] to 16bit signed samples */
1969 for (i = 0; i < frame_size; i++) {
1970 int value = (int)q->output_buffer[i];
1972 if (value > SOFTCLIP_THRESHOLD)
1973 value = (value > HARDCLIP_THRESHOLD) ? 32767 : softclip_table[ value - SOFTCLIP_THRESHOLD];
1974 else if (value < -SOFTCLIP_THRESHOLD)
1975 value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1984 static int qdm2_decode_frame(AVCodecContext *avctx, void *data,
1985 int *got_frame_ptr, AVPacket *avpkt)
1987 const uint8_t *buf = avpkt->data;
1988 int buf_size = avpkt->size;
1989 QDM2Context *s = avctx->priv_data;
1995 if(buf_size < s->checksum_size)
1998 /* get output buffer */
1999 s->frame.nb_samples = 16 * s->frame_size;
2000 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
2001 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
2004 out = (int16_t *)s->frame.data[0];
2006 for (i = 0; i < 16; i++) {
2007 if (qdm2_decode(s, buf, out) < 0)
2009 out += s->channels * s->frame_size;
2013 *(AVFrame *)data = s->frame;
2015 return s->checksum_size;
2018 AVCodec ff_qdm2_decoder =
2021 .type = AVMEDIA_TYPE_AUDIO,
2022 .id = CODEC_ID_QDM2,
2023 .priv_data_size = sizeof(QDM2Context),
2024 .init = qdm2_decode_init,
2025 .close = qdm2_decode_close,
2026 .decode = qdm2_decode_frame,
2027 .capabilities = CODEC_CAP_DR1,
2028 .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),