2 * COOK compatible decoder
3 * Copyright (c) 2003 Sascha Sommer
4 * Copyright (c) 2005 Benjamin Larsson
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * Cook compatible decoder. Bastardization of the G.722.1 standard.
26 * This decoder handles RealNetworks, RealAudio G2 data.
27 * Cook is identified by the codec name cook in RM files.
29 * To use this decoder, a calling application must supply the extradata
30 * bytes provided from the RM container; 8+ bytes for mono streams and
31 * 16+ for stereo streams (maybe more).
33 * Codec technicalities (all this assume a buffer length of 1024):
34 * Cook works with several different techniques to achieve its compression.
35 * In the timedomain the buffer is divided into 8 pieces and quantized. If
36 * two neighboring pieces have different quantization index a smooth
37 * quantization curve is used to get a smooth overlap between the different
39 * To get to the transformdomain Cook uses a modulated lapped transform.
40 * The transform domain has 50 subbands with 20 elements each. This
41 * means only a maximum of 50*20=1000 coefficients are used out of the 1024
45 #include "libavutil/channel_layout.h"
46 #include "libavutil/lfg.h"
47 #include "libavutil/mem.h"
48 #include "libavutil/mem_internal.h"
49 #include "libavutil/thread.h"
50 #include "libavutil/tx.h"
55 #include "bytestream.h"
56 #include "codec_internal.h"
63 /* the different Cook versions */
64 #define MONO 0x1000001
65 #define STEREO 0x1000002
66 #define JOINT_STEREO 0x1000003
67 #define MC_COOK 0x2000000
69 #define SUBBAND_SIZE 20
70 #define MAX_SUBPACKETS 5
72 #define QUANT_VLC_BITS 9
73 #define COUPLING_VLC_BITS 6
75 typedef struct cook_gains
{
80 typedef struct COOKSubpacket
{
88 int samples_per_channel
;
89 int log2_numvector_size
;
90 unsigned int channel_mask
;
93 int bits_per_subpacket
;
96 int numvector_size
; // 1 << log2_numvector_size;
98 float mono_previous_buffer1
[1024];
99 float mono_previous_buffer2
[1024];
109 typedef struct cook
{
111 * The following 5 functions provide the lowlevel arithmetic on
112 * the internal audio buffers.
114 void (*scalar_dequant
)(struct cook
*q
, int index
, int quant_index
,
115 int *subband_coef_index
, int *subband_coef_sign
,
118 void (*decouple
)(struct cook
*q
,
122 float *decode_buffer
,
123 float *mlt_buffer1
, float *mlt_buffer2
);
125 void (*imlt_window
)(struct cook
*q
, float *buffer1
,
126 cook_gains
*gains_ptr
, float *previous_buffer
);
128 void (*interpolate
)(struct cook
*q
, float *buffer
,
129 int gain_index
, int gain_index_next
);
131 void (*saturate_output
)(struct cook
*q
, float *out
);
133 AVCodecContext
* avctx
;
134 AudioDSPContext adsp
;
138 int samples_per_channel
;
141 int discarded_packets
;
144 AVTXContext
*mdct_ctx
;
149 VLC envelope_quant_index
[13];
150 VLC sqvh
[7]; // scalar quantization
152 /* generate tables and related variables */
153 int gain_size_factor
;
154 float gain_table
[31];
158 uint8_t* decoded_bytes_buffer
;
159 DECLARE_ALIGNED(32, float, mono_mdct_output
)[2048];
160 float decode_buffer_1
[1024];
161 float decode_buffer_2
[1024];
162 float decode_buffer_0
[1060]; /* static allocation for joint decode */
164 const float *cplscales
[5];
166 COOKSubpacket subpacket
[MAX_SUBPACKETS
];
169 static float pow2tab
[127];
170 static float rootpow2tab
[127];
172 /*************** init functions ***************/
174 /* table generator */
175 static av_cold
void init_pow2table(void)
177 /* fast way of computing 2^i and 2^(0.5*i) for -63 <= i < 64 */
179 static const float exp2_tab
[2] = {1, M_SQRT2
};
180 float exp2_val
= powf(2, -63);
181 float root_val
= powf(2, -32);
182 for (i
= -63; i
< 64; i
++) {
185 pow2tab
[63 + i
] = exp2_val
;
186 rootpow2tab
[63 + i
] = root_val
* exp2_tab
[i
& 1];
191 /* table generator */
192 static av_cold
void init_gain_table(COOKContext
*q
)
195 q
->gain_size_factor
= q
->samples_per_channel
/ 8;
196 for (i
= 0; i
< 31; i
++)
197 q
->gain_table
[i
] = pow(pow2tab
[i
+ 48],
198 (1.0 / (double) q
->gain_size_factor
));
201 static av_cold
int build_vlc(VLC
*vlc
, int nb_bits
, const uint8_t counts
[16],
202 const void *syms
, int symbol_size
, int offset
,
205 uint8_t lens
[MAX_COOK_VLC_ENTRIES
];
208 for (int i
= 0; i
< 16; i
++)
209 for (unsigned count
= num
+ counts
[i
]; num
< count
; num
++)
212 return ff_vlc_init_from_lengths(vlc
, nb_bits
, num
, lens
, 1,
213 syms
, symbol_size
, symbol_size
,
217 static av_cold
int init_cook_vlc_tables(COOKContext
*q
)
222 for (i
= 0; i
< 13; i
++) {
223 result
|= build_vlc(&q
->envelope_quant_index
[i
], QUANT_VLC_BITS
,
224 envelope_quant_index_huffcounts
[i
],
225 envelope_quant_index_huffsyms
[i
], 1, -12, q
->avctx
);
227 av_log(q
->avctx
, AV_LOG_DEBUG
, "sqvh VLC init\n");
228 for (i
= 0; i
< 7; i
++) {
229 int sym_size
= 1 + (i
== 3);
230 result
|= build_vlc(&q
->sqvh
[i
], vhvlcsize_tab
[i
],
232 cvh_huffsyms
[i
], sym_size
, 0, q
->avctx
);
235 for (i
= 0; i
< q
->num_subpackets
; i
++) {
236 if (q
->subpacket
[i
].joint_stereo
== 1) {
237 result
|= build_vlc(&q
->subpacket
[i
].channel_coupling
, COUPLING_VLC_BITS
,
238 ccpl_huffcounts
[q
->subpacket
[i
].js_vlc_bits
- 2],
239 ccpl_huffsyms
[q
->subpacket
[i
].js_vlc_bits
- 2], 1,
241 av_log(q
->avctx
, AV_LOG_DEBUG
, "subpacket %i Joint-stereo VLC used.\n", i
);
245 av_log(q
->avctx
, AV_LOG_DEBUG
, "VLC tables initialized.\n");
249 static av_cold
int init_cook_mlt(COOKContext
*q
)
252 int mlt_size
= q
->samples_per_channel
;
253 const float scale
= 1.0 / 32768.0;
255 if (!(q
->mlt_window
= av_malloc_array(mlt_size
, sizeof(*q
->mlt_window
))))
256 return AVERROR(ENOMEM
);
258 /* Initialize the MLT window: simple sine window. */
259 ff_sine_window_init(q
->mlt_window
, mlt_size
);
260 for (j
= 0; j
< mlt_size
; j
++)
261 q
->mlt_window
[j
] *= sqrt(2.0 / q
->samples_per_channel
);
263 /* Initialize the MDCT. */
264 ret
= av_tx_init(&q
->mdct_ctx
, &q
->mdct_fn
, AV_TX_FLOAT_MDCT
,
265 1, mlt_size
, &scale
, AV_TX_FULL_IMDCT
);
272 static av_cold
void init_cplscales_table(COOKContext
*q
)
275 for (i
= 0; i
< 5; i
++)
276 q
->cplscales
[i
] = cplscales
[i
];
279 /*************** init functions end ***********/
281 #define DECODE_BYTES_PAD1(bytes) (3 - ((bytes) + 3) % 4)
282 #define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
285 * Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
286 * Why? No idea, some checksum/error detection method maybe.
288 * Out buffer size: extra bytes are needed to cope with
289 * padding/misalignment.
290 * Subpackets passed to the decoder can contain two, consecutive
291 * half-subpackets, of identical but arbitrary size.
292 * 1234 1234 1234 1234 extraA extraB
293 * Case 1: AAAA BBBB 0 0
294 * Case 2: AAAA ABBB BB-- 3 3
295 * Case 3: AAAA AABB BBBB 2 2
296 * Case 4: AAAA AAAB BBBB BB-- 1 5
298 * Nice way to waste CPU cycles.
300 * @param inbuffer pointer to byte array of indata
301 * @param out pointer to byte array of outdata
302 * @param bytes number of bytes
304 static inline int decode_bytes(const uint8_t *inbuffer
, uint8_t *out
, int bytes
)
306 static const uint32_t tab
[4] = {
307 AV_BE2NE32C(0x37c511f2u
), AV_BE2NE32C(0xf237c511u
),
308 AV_BE2NE32C(0x11f237c5u
), AV_BE2NE32C(0xc511f237u
),
313 uint32_t *obuf
= (uint32_t *) out
;
314 /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
315 * I'm too lazy though, should be something like
316 * for (i = 0; i < bitamount / 64; i++)
317 * (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);
318 * Buffer alignment needs to be checked. */
320 off
= (intptr_t) inbuffer
& 3;
321 buf
= (const uint32_t *) (inbuffer
- off
);
324 for (i
= 0; i
< bytes
/ 4; i
++)
325 obuf
[i
] = c
^ buf
[i
];
330 static av_cold
int cook_decode_close(AVCodecContext
*avctx
)
333 COOKContext
*q
= avctx
->priv_data
;
334 av_log(avctx
, AV_LOG_DEBUG
, "Deallocating memory.\n");
336 /* Free allocated memory buffers. */
337 av_freep(&q
->mlt_window
);
338 av_freep(&q
->decoded_bytes_buffer
);
340 /* Free the transform. */
341 av_tx_uninit(&q
->mdct_ctx
);
343 /* Free the VLC tables. */
344 for (i
= 0; i
< 13; i
++)
345 ff_vlc_free(&q
->envelope_quant_index
[i
]);
346 for (i
= 0; i
< 7; i
++)
347 ff_vlc_free(&q
->sqvh
[i
]);
348 for (i
= 0; i
< q
->num_subpackets
; i
++)
349 ff_vlc_free(&q
->subpacket
[i
].channel_coupling
);
351 av_log(avctx
, AV_LOG_DEBUG
, "Memory deallocated.\n");
357 * Fill the gain array for the timedomain quantization.
359 * @param gb pointer to the GetBitContext
360 * @param gaininfo array[9] of gain indexes
362 static void decode_gain_info(GetBitContext
*gb
, int *gaininfo
)
366 n
= get_unary(gb
, 0, get_bits_left(gb
)); // amount of elements*2 to update
370 int index
= get_bits(gb
, 3);
371 int gain
= get_bits1(gb
) ? get_bits(gb
, 4) - 7 : -1;
374 gaininfo
[i
++] = gain
;
381 * Create the quant index table needed for the envelope.
383 * @param q pointer to the COOKContext
384 * @param quant_index_table pointer to the array
386 static int decode_envelope(COOKContext
*q
, COOKSubpacket
*p
,
387 int *quant_index_table
)
391 quant_index_table
[0] = get_bits(&q
->gb
, 6) - 6; // This is used later in categorize
393 for (i
= 1; i
< p
->total_subbands
; i
++) {
395 if (i
>= p
->js_subband_start
* 2) {
396 vlc_index
-= p
->js_subband_start
;
403 vlc_index
= 13; // the VLC tables >13 are identical to No. 13
405 j
= get_vlc2(&q
->gb
, q
->envelope_quant_index
[vlc_index
- 1].table
,
407 quant_index_table
[i
] = quant_index_table
[i
- 1] + j
; // differential encoding
408 if (quant_index_table
[i
] > 63 || quant_index_table
[i
] < -63) {
409 av_log(q
->avctx
, AV_LOG_ERROR
,
410 "Invalid quantizer %d at position %d, outside [-63, 63] range\n",
411 quant_index_table
[i
], i
);
412 return AVERROR_INVALIDDATA
;
420 * Calculate the category and category_index vector.
422 * @param q pointer to the COOKContext
423 * @param quant_index_table pointer to the array
424 * @param category pointer to the category array
425 * @param category_index pointer to the category_index array
427 static void categorize(COOKContext
*q
, COOKSubpacket
*p
, const int *quant_index_table
,
428 int *category
, int *category_index
)
430 int exp_idx
, bias
, tmpbias1
, tmpbias2
, bits_left
, num_bits
, index
, v
, i
, j
;
431 int exp_index2
[102] = { 0 };
432 int exp_index1
[102] = { 0 };
434 int tmp_categorize_array
[128 * 2] = { 0 };
435 int tmp_categorize_array1_idx
= p
->numvector_size
;
436 int tmp_categorize_array2_idx
= p
->numvector_size
;
438 bits_left
= p
->bits_per_subpacket
- get_bits_count(&q
->gb
);
440 if (bits_left
> q
->samples_per_channel
)
441 bits_left
= q
->samples_per_channel
+
442 ((bits_left
- q
->samples_per_channel
) * 5) / 8;
447 for (i
= 32; i
> 0; i
= i
/ 2) {
450 for (j
= p
->total_subbands
; j
> 0; j
--) {
451 exp_idx
= av_clip_uintp2((i
- quant_index_table
[index
] + bias
) / 2, 3);
453 num_bits
+= expbits_tab
[exp_idx
];
455 if (num_bits
>= bits_left
- 32)
459 /* Calculate total number of bits. */
461 for (i
= 0; i
< p
->total_subbands
; i
++) {
462 exp_idx
= av_clip_uintp2((bias
- quant_index_table
[i
]) / 2, 3);
463 num_bits
+= expbits_tab
[exp_idx
];
464 exp_index1
[i
] = exp_idx
;
465 exp_index2
[i
] = exp_idx
;
467 tmpbias1
= tmpbias2
= num_bits
;
469 for (j
= 1; j
< p
->numvector_size
; j
++) {
470 if (tmpbias1
+ tmpbias2
> 2 * bits_left
) { /* ---> */
473 for (i
= 0; i
< p
->total_subbands
; i
++) {
474 if (exp_index1
[i
] < 7) {
475 v
= (-2 * exp_index1
[i
]) - quant_index_table
[i
] + bias
;
484 tmp_categorize_array
[tmp_categorize_array1_idx
++] = index
;
485 tmpbias1
-= expbits_tab
[exp_index1
[index
]] -
486 expbits_tab
[exp_index1
[index
] + 1];
491 for (i
= 0; i
< p
->total_subbands
; i
++) {
492 if (exp_index2
[i
] > 0) {
493 v
= (-2 * exp_index2
[i
]) - quant_index_table
[i
] + bias
;
502 tmp_categorize_array
[--tmp_categorize_array2_idx
] = index
;
503 tmpbias2
-= expbits_tab
[exp_index2
[index
]] -
504 expbits_tab
[exp_index2
[index
] - 1];
509 for (i
= 0; i
< p
->total_subbands
; i
++)
510 category
[i
] = exp_index2
[i
];
512 for (i
= 0; i
< p
->numvector_size
- 1; i
++)
513 category_index
[i
] = tmp_categorize_array
[tmp_categorize_array2_idx
++];
518 * Expand the category vector.
520 * @param q pointer to the COOKContext
521 * @param category pointer to the category array
522 * @param category_index pointer to the category_index array
524 static inline void expand_category(COOKContext
*q
, int *category
,
528 for (i
= 0; i
< q
->num_vectors
; i
++)
530 int idx
= category_index
[i
];
531 if (++category
[idx
] >= FF_ARRAY_ELEMS(dither_tab
))
537 * The real requantization of the mltcoefs
539 * @param q pointer to the COOKContext
541 * @param quant_index quantisation index
542 * @param subband_coef_index array of indexes to quant_centroid_tab
543 * @param subband_coef_sign signs of coefficients
544 * @param mlt_p pointer into the mlt buffer
546 static void scalar_dequant_float(COOKContext
*q
, int index
, int quant_index
,
547 int *subband_coef_index
, int *subband_coef_sign
,
553 for (i
= 0; i
< SUBBAND_SIZE
; i
++) {
554 if (subband_coef_index
[i
]) {
555 f1
= quant_centroid_tab
[index
][subband_coef_index
[i
]];
556 if (subband_coef_sign
[i
])
559 /* noise coding if subband_coef_index[i] == 0 */
560 f1
= dither_tab
[index
];
561 if (av_lfg_get(&q
->random_state
) < 0x80000000)
564 mlt_p
[i
] = f1
* rootpow2tab
[quant_index
+ 63];
568 * Unpack the subband_coef_index and subband_coef_sign vectors.
570 * @param q pointer to the COOKContext
571 * @param category pointer to the category array
572 * @param subband_coef_index array of indexes to quant_centroid_tab
573 * @param subband_coef_sign signs of coefficients
575 static int unpack_SQVH(COOKContext
*q
, COOKSubpacket
*p
, int category
,
576 int *subband_coef_index
, int *subband_coef_sign
)
579 int vlc
, vd
, tmp
, result
;
581 vd
= vd_tab
[category
];
583 for (i
= 0; i
< vpr_tab
[category
]; i
++) {
584 vlc
= get_vlc2(&q
->gb
, q
->sqvh
[category
].table
, q
->sqvh
[category
].bits
, 3);
585 if (p
->bits_per_subpacket
< get_bits_count(&q
->gb
)) {
589 for (j
= vd
- 1; j
>= 0; j
--) {
590 tmp
= (vlc
* invradix_tab
[category
]) / 0x100000;
591 subband_coef_index
[vd
* i
+ j
] = vlc
- tmp
* (kmax_tab
[category
] + 1);
594 for (j
= 0; j
< vd
; j
++) {
595 if (subband_coef_index
[i
* vd
+ j
]) {
596 if (get_bits_count(&q
->gb
) < p
->bits_per_subpacket
) {
597 subband_coef_sign
[i
* vd
+ j
] = get_bits1(&q
->gb
);
600 subband_coef_sign
[i
* vd
+ j
] = 0;
603 subband_coef_sign
[i
* vd
+ j
] = 0;
612 * Fill the mlt_buffer with mlt coefficients.
614 * @param q pointer to the COOKContext
615 * @param category pointer to the category array
616 * @param quant_index_table pointer to the array
617 * @param mlt_buffer pointer to mlt coefficients
619 static void decode_vectors(COOKContext
*q
, COOKSubpacket
*p
, int *category
,
620 int *quant_index_table
, float *mlt_buffer
)
622 /* A zero in this table means that the subband coefficient is
623 random noise coded. */
624 int subband_coef_index
[SUBBAND_SIZE
];
625 /* A zero in this table means that the subband coefficient is a
626 positive multiplicator. */
627 int subband_coef_sign
[SUBBAND_SIZE
];
631 for (band
= 0; band
< p
->total_subbands
; band
++) {
632 index
= category
[band
];
633 if (category
[band
] < 7) {
634 if (unpack_SQVH(q
, p
, category
[band
], subband_coef_index
, subband_coef_sign
)) {
636 for (j
= 0; j
< p
->total_subbands
; j
++)
637 category
[band
+ j
] = 7;
641 memset(subband_coef_index
, 0, sizeof(subband_coef_index
));
642 memset(subband_coef_sign
, 0, sizeof(subband_coef_sign
));
644 q
->scalar_dequant(q
, index
, quant_index_table
[band
],
645 subband_coef_index
, subband_coef_sign
,
646 &mlt_buffer
[band
* SUBBAND_SIZE
]);
649 /* FIXME: should this be removed, or moved into loop above? */
650 if (p
->total_subbands
* SUBBAND_SIZE
>= q
->samples_per_channel
)
655 static int mono_decode(COOKContext
*q
, COOKSubpacket
*p
, float *mlt_buffer
)
657 int category_index
[128] = { 0 };
658 int category
[128] = { 0 };
659 int quant_index_table
[102];
662 if ((res
= decode_envelope(q
, p
, quant_index_table
)) < 0)
664 q
->num_vectors
= get_bits(&q
->gb
, p
->log2_numvector_size
);
665 categorize(q
, p
, quant_index_table
, category
, category_index
);
666 expand_category(q
, category
, category_index
);
667 for (i
=0; i
<p
->total_subbands
; i
++) {
669 return AVERROR_INVALIDDATA
;
671 decode_vectors(q
, p
, category
, quant_index_table
, mlt_buffer
);
678 * the actual requantization of the timedomain samples
680 * @param q pointer to the COOKContext
681 * @param buffer pointer to the timedomain buffer
682 * @param gain_index index for the block multiplier
683 * @param gain_index_next index for the next block multiplier
685 static void interpolate_float(COOKContext
*q
, float *buffer
,
686 int gain_index
, int gain_index_next
)
690 fc1
= pow2tab
[gain_index
+ 63];
692 if (gain_index
== gain_index_next
) { // static gain
693 for (i
= 0; i
< q
->gain_size_factor
; i
++)
695 } else { // smooth gain
696 fc2
= q
->gain_table
[15 + (gain_index_next
- gain_index
)];
697 for (i
= 0; i
< q
->gain_size_factor
; i
++) {
705 * Apply transform window, overlap buffers.
707 * @param q pointer to the COOKContext
708 * @param inbuffer pointer to the mltcoefficients
709 * @param gains_ptr current and previous gains
710 * @param previous_buffer pointer to the previous buffer to be used for overlapping
712 static void imlt_window_float(COOKContext
*q
, float *inbuffer
,
713 cook_gains
*gains_ptr
, float *previous_buffer
)
715 const float fc
= pow2tab
[gains_ptr
->previous
[0] + 63];
717 /* The weird thing here, is that the two halves of the time domain
718 * buffer are swapped. Also, the newest data, that we save away for
719 * next frame, has the wrong sign. Hence the subtraction below.
720 * Almost sounds like a complex conjugate/reverse data/FFT effect.
723 /* Apply window and overlap */
724 for (i
= 0; i
< q
->samples_per_channel
; i
++)
725 inbuffer
[i
] = inbuffer
[i
] * fc
* q
->mlt_window
[i
] -
726 previous_buffer
[i
] * q
->mlt_window
[q
->samples_per_channel
- 1 - i
];
730 * The modulated lapped transform, this takes transform coefficients
731 * and transforms them into timedomain samples.
732 * Apply transform window, overlap buffers, apply gain profile
733 * and buffer management.
735 * @param q pointer to the COOKContext
736 * @param inbuffer pointer to the mltcoefficients
737 * @param gains_ptr current and previous gains
738 * @param previous_buffer pointer to the previous buffer to be used for overlapping
740 static void imlt_gain(COOKContext
*q
, float *inbuffer
,
741 cook_gains
*gains_ptr
, float *previous_buffer
)
743 float *buffer0
= q
->mono_mdct_output
;
744 float *buffer1
= q
->mono_mdct_output
+ q
->samples_per_channel
;
747 /* Inverse modified discrete cosine transform */
748 q
->mdct_fn(q
->mdct_ctx
, q
->mono_mdct_output
, inbuffer
, sizeof(float));
750 q
->imlt_window(q
, buffer1
, gains_ptr
, previous_buffer
);
752 /* Apply gain profile */
753 for (i
= 0; i
< 8; i
++)
754 if (gains_ptr
->now
[i
] || gains_ptr
->now
[i
+ 1])
755 q
->interpolate(q
, &buffer1
[q
->gain_size_factor
* i
],
756 gains_ptr
->now
[i
], gains_ptr
->now
[i
+ 1]);
758 /* Save away the current to be previous block. */
759 memcpy(previous_buffer
, buffer0
,
760 q
->samples_per_channel
* sizeof(*previous_buffer
));
765 * function for getting the jointstereo coupling information
767 * @param q pointer to the COOKContext
768 * @param decouple_tab decoupling array
770 static int decouple_info(COOKContext
*q
, COOKSubpacket
*p
, int *decouple_tab
)
773 int vlc
= get_bits1(&q
->gb
);
774 int start
= cplband
[p
->js_subband_start
];
775 int end
= cplband
[p
->subbands
- 1];
776 int length
= end
- start
+ 1;
782 for (i
= 0; i
< length
; i
++)
783 decouple_tab
[start
+ i
] = get_vlc2(&q
->gb
,
784 p
->channel_coupling
.table
,
785 COUPLING_VLC_BITS
, 3);
787 for (i
= 0; i
< length
; i
++) {
788 int v
= get_bits(&q
->gb
, p
->js_vlc_bits
);
789 if (v
== (1<<p
->js_vlc_bits
)-1) {
790 av_log(q
->avctx
, AV_LOG_ERROR
, "decouple value too large\n");
791 return AVERROR_INVALIDDATA
;
793 decouple_tab
[start
+ i
] = v
;
799 * function decouples a pair of signals from a single signal via multiplication.
801 * @param q pointer to the COOKContext
802 * @param subband index of the current subband
803 * @param f1 multiplier for channel 1 extraction
804 * @param f2 multiplier for channel 2 extraction
805 * @param decode_buffer input buffer
806 * @param mlt_buffer1 pointer to left channel mlt coefficients
807 * @param mlt_buffer2 pointer to right channel mlt coefficients
809 static void decouple_float(COOKContext
*q
,
813 float *decode_buffer
,
814 float *mlt_buffer1
, float *mlt_buffer2
)
817 for (j
= 0; j
< SUBBAND_SIZE
; j
++) {
818 tmp_idx
= ((p
->js_subband_start
+ subband
) * SUBBAND_SIZE
) + j
;
819 mlt_buffer1
[SUBBAND_SIZE
* subband
+ j
] = f1
* decode_buffer
[tmp_idx
];
820 mlt_buffer2
[SUBBAND_SIZE
* subband
+ j
] = f2
* decode_buffer
[tmp_idx
];
825 * function for decoding joint stereo data
827 * @param q pointer to the COOKContext
828 * @param mlt_buffer1 pointer to left channel mlt coefficients
829 * @param mlt_buffer2 pointer to right channel mlt coefficients
831 static int joint_decode(COOKContext
*q
, COOKSubpacket
*p
,
832 float *mlt_buffer_left
, float *mlt_buffer_right
)
835 int decouple_tab
[SUBBAND_SIZE
] = { 0 };
836 float *decode_buffer
= q
->decode_buffer_0
;
839 const float *cplscale
;
841 memset(decode_buffer
, 0, sizeof(q
->decode_buffer_0
));
843 /* Make sure the buffers are zeroed out. */
844 memset(mlt_buffer_left
, 0, 1024 * sizeof(*mlt_buffer_left
));
845 memset(mlt_buffer_right
, 0, 1024 * sizeof(*mlt_buffer_right
));
846 if ((res
= decouple_info(q
, p
, decouple_tab
)) < 0)
848 if ((res
= mono_decode(q
, p
, decode_buffer
)) < 0)
850 /* The two channels are stored interleaved in decode_buffer. */
851 for (i
= 0; i
< p
->js_subband_start
; i
++) {
852 for (j
= 0; j
< SUBBAND_SIZE
; j
++) {
853 mlt_buffer_left
[i
* 20 + j
] = decode_buffer
[i
* 40 + j
];
854 mlt_buffer_right
[i
* 20 + j
] = decode_buffer
[i
* 40 + 20 + j
];
858 /* When we reach js_subband_start (the higher frequencies)
859 the coefficients are stored in a coupling scheme. */
860 idx
= (1 << p
->js_vlc_bits
) - 1;
861 for (i
= p
->js_subband_start
; i
< p
->subbands
; i
++) {
862 cpl_tmp
= cplband
[i
];
863 idx
-= decouple_tab
[cpl_tmp
];
864 cplscale
= q
->cplscales
[p
->js_vlc_bits
- 2]; // choose decoupler table
865 f1
= cplscale
[decouple_tab
[cpl_tmp
] + 1];
867 q
->decouple(q
, p
, i
, f1
, f2
, decode_buffer
,
868 mlt_buffer_left
, mlt_buffer_right
);
869 idx
= (1 << p
->js_vlc_bits
) - 1;
876 * First part of subpacket decoding:
877 * decode raw stream bytes and read gain info.
879 * @param q pointer to the COOKContext
880 * @param inbuffer pointer to raw stream data
881 * @param gains_ptr array of current/prev gain pointers
883 static inline void decode_bytes_and_gain(COOKContext
*q
, COOKSubpacket
*p
,
884 const uint8_t *inbuffer
,
885 cook_gains
*gains_ptr
)
889 offset
= decode_bytes(inbuffer
, q
->decoded_bytes_buffer
,
890 p
->bits_per_subpacket
/ 8);
891 init_get_bits(&q
->gb
, q
->decoded_bytes_buffer
+ offset
,
892 p
->bits_per_subpacket
);
893 decode_gain_info(&q
->gb
, gains_ptr
->now
);
895 /* Swap current and previous gains */
896 FFSWAP(int *, gains_ptr
->now
, gains_ptr
->previous
);
900 * Saturate the output signal and interleave.
902 * @param q pointer to the COOKContext
903 * @param out pointer to the output vector
905 static void saturate_output_float(COOKContext
*q
, float *out
)
907 q
->adsp
.vector_clipf(out
, q
->mono_mdct_output
+ q
->samples_per_channel
,
908 FFALIGN(q
->samples_per_channel
, 8), -1.0f
, 1.0f
);
913 * Final part of subpacket decoding:
914 * Apply modulated lapped transform, gain compensation,
915 * clip and convert to integer.
917 * @param q pointer to the COOKContext
918 * @param decode_buffer pointer to the mlt coefficients
919 * @param gains_ptr array of current/prev gain pointers
920 * @param previous_buffer pointer to the previous buffer to be used for overlapping
921 * @param out pointer to the output buffer
923 static inline void mlt_compensate_output(COOKContext
*q
, float *decode_buffer
,
924 cook_gains
*gains_ptr
, float *previous_buffer
,
927 imlt_gain(q
, decode_buffer
, gains_ptr
, previous_buffer
);
929 q
->saturate_output(q
, out
);
934 * Cook subpacket decoding. This function returns one decoded subpacket,
935 * usually 1024 samples per channel.
937 * @param q pointer to the COOKContext
938 * @param inbuffer pointer to the inbuffer
939 * @param outbuffer pointer to the outbuffer
941 static int decode_subpacket(COOKContext
*q
, COOKSubpacket
*p
,
942 const uint8_t *inbuffer
, float **outbuffer
)
944 int sub_packet_size
= p
->size
;
947 memset(q
->decode_buffer_1
, 0, sizeof(q
->decode_buffer_1
));
948 decode_bytes_and_gain(q
, p
, inbuffer
, &p
->gains1
);
950 if (p
->joint_stereo
) {
951 if ((res
= joint_decode(q
, p
, q
->decode_buffer_1
, q
->decode_buffer_2
)) < 0)
954 if ((res
= mono_decode(q
, p
, q
->decode_buffer_1
)) < 0)
957 if (p
->num_channels
== 2) {
958 decode_bytes_and_gain(q
, p
, inbuffer
+ sub_packet_size
/ 2, &p
->gains2
);
959 if ((res
= mono_decode(q
, p
, q
->decode_buffer_2
)) < 0)
964 mlt_compensate_output(q
, q
->decode_buffer_1
, &p
->gains1
,
965 p
->mono_previous_buffer1
,
966 outbuffer
? outbuffer
[p
->ch_idx
] : NULL
);
968 if (p
->num_channels
== 2) {
970 mlt_compensate_output(q
, q
->decode_buffer_2
, &p
->gains1
,
971 p
->mono_previous_buffer2
,
972 outbuffer
? outbuffer
[p
->ch_idx
+ 1] : NULL
);
974 mlt_compensate_output(q
, q
->decode_buffer_2
, &p
->gains2
,
975 p
->mono_previous_buffer2
,
976 outbuffer
? outbuffer
[p
->ch_idx
+ 1] : NULL
);
983 static int cook_decode_frame(AVCodecContext
*avctx
, AVFrame
*frame
,
984 int *got_frame_ptr
, AVPacket
*avpkt
)
986 const uint8_t *buf
= avpkt
->data
;
987 int buf_size
= avpkt
->size
;
988 COOKContext
*q
= avctx
->priv_data
;
989 float **samples
= NULL
;
994 if (buf_size
< avctx
->block_align
)
997 /* get output buffer */
998 if (q
->discarded_packets
>= 2) {
999 frame
->nb_samples
= q
->samples_per_channel
;
1000 if ((ret
= ff_get_buffer(avctx
, frame
, 0)) < 0)
1002 samples
= (float **)frame
->extended_data
;
1005 /* estimate subpacket sizes */
1006 q
->subpacket
[0].size
= avctx
->block_align
;
1008 for (i
= 1; i
< q
->num_subpackets
; i
++) {
1009 q
->subpacket
[i
].size
= 2 * buf
[avctx
->block_align
- q
->num_subpackets
+ i
];
1010 q
->subpacket
[0].size
-= q
->subpacket
[i
].size
+ 1;
1011 if (q
->subpacket
[0].size
< 0) {
1012 av_log(avctx
, AV_LOG_DEBUG
,
1013 "frame subpacket size total > avctx->block_align!\n");
1014 return AVERROR_INVALIDDATA
;
1018 /* decode supbackets */
1019 for (i
= 0; i
< q
->num_subpackets
; i
++) {
1020 q
->subpacket
[i
].bits_per_subpacket
= (q
->subpacket
[i
].size
* 8) >>
1021 q
->subpacket
[i
].bits_per_subpdiv
;
1022 q
->subpacket
[i
].ch_idx
= chidx
;
1023 av_log(avctx
, AV_LOG_DEBUG
,
1024 "subpacket[%i] size %i js %i %i block_align %i\n",
1025 i
, q
->subpacket
[i
].size
, q
->subpacket
[i
].joint_stereo
, offset
,
1026 avctx
->block_align
);
1028 if ((ret
= decode_subpacket(q
, &q
->subpacket
[i
], buf
+ offset
, samples
)) < 0)
1030 offset
+= q
->subpacket
[i
].size
;
1031 chidx
+= q
->subpacket
[i
].num_channels
;
1032 av_log(avctx
, AV_LOG_DEBUG
, "subpacket[%i] %i %i\n",
1033 i
, q
->subpacket
[i
].size
* 8, get_bits_count(&q
->gb
));
1036 /* Discard the first two frames: no valid audio. */
1037 if (q
->discarded_packets
< 2) {
1038 q
->discarded_packets
++;
1040 return avctx
->block_align
;
1045 return avctx
->block_align
;
1048 static void dump_cook_context(COOKContext
*q
)
1051 #define PRINT(a, b) ff_dlog(q->avctx, " %s = %d\n", a, b);
1052 ff_dlog(q
->avctx
, "COOKextradata\n");
1053 ff_dlog(q
->avctx
, "cookversion=%x\n", q
->subpacket
[0].cookversion
);
1054 if (q
->subpacket
[0].cookversion
> STEREO
) {
1055 PRINT("js_subband_start", q
->subpacket
[0].js_subband_start
);
1056 PRINT("js_vlc_bits", q
->subpacket
[0].js_vlc_bits
);
1058 ff_dlog(q
->avctx
, "COOKContext\n");
1059 PRINT("nb_channels", q
->avctx
->ch_layout
.nb_channels
);
1060 PRINT("bit_rate", (int)q
->avctx
->bit_rate
);
1061 PRINT("sample_rate", q
->avctx
->sample_rate
);
1062 PRINT("samples_per_channel", q
->subpacket
[0].samples_per_channel
);
1063 PRINT("subbands", q
->subpacket
[0].subbands
);
1064 PRINT("js_subband_start", q
->subpacket
[0].js_subband_start
);
1065 PRINT("log2_numvector_size", q
->subpacket
[0].log2_numvector_size
);
1066 PRINT("numvector_size", q
->subpacket
[0].numvector_size
);
1067 PRINT("total_subbands", q
->subpacket
[0].total_subbands
);
1071 * Cook initialization
1073 * @param avctx pointer to the AVCodecContext
1075 static av_cold
int cook_decode_init(AVCodecContext
*avctx
)
1077 static AVOnce init_static_once
= AV_ONCE_INIT
;
1078 COOKContext
*q
= avctx
->priv_data
;
1081 unsigned int channel_mask
= 0;
1082 int samples_per_frame
= 0;
1084 int channels
= avctx
->ch_layout
.nb_channels
;
1088 /* Take care of the codec specific extradata. */
1089 if (avctx
->extradata_size
< 8) {
1090 av_log(avctx
, AV_LOG_ERROR
, "Necessary extradata missing!\n");
1091 return AVERROR_INVALIDDATA
;
1093 av_log(avctx
, AV_LOG_DEBUG
, "codecdata_length=%d\n", avctx
->extradata_size
);
1095 bytestream2_init(&gb
, avctx
->extradata
, avctx
->extradata_size
);
1097 /* Take data from the AVCodecContext (RM container). */
1099 av_log(avctx
, AV_LOG_ERROR
, "Invalid number of channels\n");
1100 return AVERROR_INVALIDDATA
;
1103 if (avctx
->block_align
>= INT_MAX
/ 8)
1104 return AVERROR(EINVAL
);
1106 /* Initialize RNG. */
1107 av_lfg_init(&q
->random_state
, 0);
1109 ff_audiodsp_init(&q
->adsp
);
1111 while (bytestream2_get_bytes_left(&gb
)) {
1112 if (s
>= FFMIN(MAX_SUBPACKETS
, avctx
->block_align
)) {
1113 avpriv_request_sample(avctx
, "subpackets > %d", FFMIN(MAX_SUBPACKETS
, avctx
->block_align
));
1114 return AVERROR_PATCHWELCOME
;
1116 /* 8 for mono, 16 for stereo, ? for multichannel
1117 Swap to right endianness so we don't need to care later on. */
1118 q
->subpacket
[s
].cookversion
= bytestream2_get_be32(&gb
);
1119 samples_per_frame
= bytestream2_get_be16(&gb
);
1120 q
->subpacket
[s
].subbands
= bytestream2_get_be16(&gb
);
1121 bytestream2_get_be32(&gb
); // Unknown unused
1122 q
->subpacket
[s
].js_subband_start
= bytestream2_get_be16(&gb
);
1123 if (q
->subpacket
[s
].js_subband_start
>= 51) {
1124 av_log(avctx
, AV_LOG_ERROR
, "js_subband_start %d is too large\n", q
->subpacket
[s
].js_subband_start
);
1125 return AVERROR_INVALIDDATA
;
1127 q
->subpacket
[s
].js_vlc_bits
= bytestream2_get_be16(&gb
);
1129 /* Initialize extradata related variables. */
1130 q
->subpacket
[s
].samples_per_channel
= samples_per_frame
/ channels
;
1131 q
->subpacket
[s
].bits_per_subpacket
= avctx
->block_align
* 8;
1133 /* Initialize default data states. */
1134 q
->subpacket
[s
].log2_numvector_size
= 5;
1135 q
->subpacket
[s
].total_subbands
= q
->subpacket
[s
].subbands
;
1136 q
->subpacket
[s
].num_channels
= 1;
1138 /* Initialize version-dependent variables */
1140 av_log(avctx
, AV_LOG_DEBUG
, "subpacket[%i].cookversion=%x\n", s
,
1141 q
->subpacket
[s
].cookversion
);
1142 q
->subpacket
[s
].joint_stereo
= 0;
1143 switch (q
->subpacket
[s
].cookversion
) {
1145 if (channels
!= 1) {
1146 avpriv_request_sample(avctx
, "Container channels != 1");
1147 return AVERROR_PATCHWELCOME
;
1149 av_log(avctx
, AV_LOG_DEBUG
, "MONO\n");
1152 if (channels
!= 1) {
1153 q
->subpacket
[s
].bits_per_subpdiv
= 1;
1154 q
->subpacket
[s
].num_channels
= 2;
1156 av_log(avctx
, AV_LOG_DEBUG
, "STEREO\n");
1159 if (channels
!= 2) {
1160 avpriv_request_sample(avctx
, "Container channels != 2");
1161 return AVERROR_PATCHWELCOME
;
1163 av_log(avctx
, AV_LOG_DEBUG
, "JOINT_STEREO\n");
1164 if (avctx
->extradata_size
>= 16) {
1165 q
->subpacket
[s
].total_subbands
= q
->subpacket
[s
].subbands
+
1166 q
->subpacket
[s
].js_subband_start
;
1167 q
->subpacket
[s
].joint_stereo
= 1;
1168 q
->subpacket
[s
].num_channels
= 2;
1170 if (q
->subpacket
[s
].samples_per_channel
> 256) {
1171 q
->subpacket
[s
].log2_numvector_size
= 6;
1173 if (q
->subpacket
[s
].samples_per_channel
> 512) {
1174 q
->subpacket
[s
].log2_numvector_size
= 7;
1178 av_log(avctx
, AV_LOG_DEBUG
, "MULTI_CHANNEL\n");
1179 channel_mask
|= q
->subpacket
[s
].channel_mask
= bytestream2_get_be32(&gb
);
1181 if (av_popcount64(q
->subpacket
[s
].channel_mask
) > 1) {
1182 q
->subpacket
[s
].total_subbands
= q
->subpacket
[s
].subbands
+
1183 q
->subpacket
[s
].js_subband_start
;
1184 q
->subpacket
[s
].joint_stereo
= 1;
1185 q
->subpacket
[s
].num_channels
= 2;
1186 q
->subpacket
[s
].samples_per_channel
= samples_per_frame
>> 1;
1188 if (q
->subpacket
[s
].samples_per_channel
> 256) {
1189 q
->subpacket
[s
].log2_numvector_size
= 6;
1191 if (q
->subpacket
[s
].samples_per_channel
> 512) {
1192 q
->subpacket
[s
].log2_numvector_size
= 7;
1195 q
->subpacket
[s
].samples_per_channel
= samples_per_frame
;
1199 avpriv_request_sample(avctx
, "Cook version %d",
1200 q
->subpacket
[s
].cookversion
);
1201 return AVERROR_PATCHWELCOME
;
1204 if (s
> 1 && q
->subpacket
[s
].samples_per_channel
!= q
->samples_per_channel
) {
1205 av_log(avctx
, AV_LOG_ERROR
, "different number of samples per channel!\n");
1206 return AVERROR_INVALIDDATA
;
1208 q
->samples_per_channel
= q
->subpacket
[0].samples_per_channel
;
1211 /* Initialize variable relations */
1212 q
->subpacket
[s
].numvector_size
= (1 << q
->subpacket
[s
].log2_numvector_size
);
1214 /* Try to catch some obviously faulty streams, otherwise it might be exploitable */
1215 if (q
->subpacket
[s
].total_subbands
> 53) {
1216 avpriv_request_sample(avctx
, "total_subbands > 53");
1217 return AVERROR_PATCHWELCOME
;
1220 if ((q
->subpacket
[s
].js_vlc_bits
> 6) ||
1221 (q
->subpacket
[s
].js_vlc_bits
< 2 * q
->subpacket
[s
].joint_stereo
)) {
1222 av_log(avctx
, AV_LOG_ERROR
, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
1223 q
->subpacket
[s
].js_vlc_bits
, 2 * q
->subpacket
[s
].joint_stereo
);
1224 return AVERROR_INVALIDDATA
;
1227 if (q
->subpacket
[s
].subbands
> 50) {
1228 avpriv_request_sample(avctx
, "subbands > 50");
1229 return AVERROR_PATCHWELCOME
;
1231 if (q
->subpacket
[s
].subbands
== 0) {
1232 avpriv_request_sample(avctx
, "subbands = 0");
1233 return AVERROR_PATCHWELCOME
;
1235 q
->subpacket
[s
].gains1
.now
= q
->subpacket
[s
].gain_1
;
1236 q
->subpacket
[s
].gains1
.previous
= q
->subpacket
[s
].gain_2
;
1237 q
->subpacket
[s
].gains2
.now
= q
->subpacket
[s
].gain_3
;
1238 q
->subpacket
[s
].gains2
.previous
= q
->subpacket
[s
].gain_4
;
1240 if (q
->num_subpackets
+ q
->subpacket
[s
].num_channels
> channels
) {
1241 av_log(avctx
, AV_LOG_ERROR
, "Too many subpackets %d for channels %d\n", q
->num_subpackets
, channels
);
1242 return AVERROR_INVALIDDATA
;
1245 q
->num_subpackets
++;
1249 /* Try to catch some obviously faulty streams, otherwise it might be exploitable */
1250 if (q
->samples_per_channel
!= 256 && q
->samples_per_channel
!= 512 &&
1251 q
->samples_per_channel
!= 1024) {
1252 avpriv_request_sample(avctx
, "samples_per_channel = %d",
1253 q
->samples_per_channel
);
1254 return AVERROR_PATCHWELCOME
;
1257 /* Generate tables */
1258 ff_thread_once(&init_static_once
, init_pow2table
);
1260 init_cplscales_table(q
);
1262 if ((ret
= init_cook_vlc_tables(q
)))
1265 /* Pad the databuffer with:
1266 DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
1267 AV_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
1268 q
->decoded_bytes_buffer
=
1269 av_mallocz(avctx
->block_align
1270 + DECODE_BYTES_PAD1(avctx
->block_align
)
1271 + AV_INPUT_BUFFER_PADDING_SIZE
);
1272 if (!q
->decoded_bytes_buffer
)
1273 return AVERROR(ENOMEM
);
1275 /* Initialize transform. */
1276 if ((ret
= init_cook_mlt(q
)))
1279 /* Initialize COOK signal arithmetic handling */
1281 q
->scalar_dequant
= scalar_dequant_float
;
1282 q
->decouple
= decouple_float
;
1283 q
->imlt_window
= imlt_window_float
;
1284 q
->interpolate
= interpolate_float
;
1285 q
->saturate_output
= saturate_output_float
;
1288 avctx
->sample_fmt
= AV_SAMPLE_FMT_FLTP
;
1289 av_channel_layout_uninit(&avctx
->ch_layout
);
1291 av_channel_layout_from_mask(&avctx
->ch_layout
, channel_mask
);
1293 av_channel_layout_default(&avctx
->ch_layout
, channels
);
1296 dump_cook_context(q
);
1301 const FFCodec ff_cook_decoder
= {
1303 CODEC_LONG_NAME("Cook / Cooker / Gecko (RealAudio G2)"),
1304 .p
.type
= AVMEDIA_TYPE_AUDIO
,
1305 .p
.id
= AV_CODEC_ID_COOK
,
1306 .priv_data_size
= sizeof(COOKContext
),
1307 .init
= cook_decode_init
,
1308 .close
= cook_decode_close
,
1309 FF_CODEC_DECODE_CB(cook_decode_frame
),
1310 .p
.capabilities
= AV_CODEC_CAP_DR1
,
1311 .p
.sample_fmts
= (const enum AVSampleFormat
[]) { AV_SAMPLE_FMT_FLTP
,
1312 AV_SAMPLE_FMT_NONE
},
1313 .caps_internal
= FF_CODEC_CAP_INIT_CLEANUP
,