CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/ext/at3_standalone/atrac3.cpp
Views: 1401
/*1* ATRAC3 compatible decoder2* Copyright (c) 2006-2008 Maxim Poliakovski3* Copyright (c) 2006-2008 Benjamin Larsson4*5* This file is part of FFmpeg.6*7* FFmpeg is free software; you can redistribute it and/or8* modify it under the terms of the GNU Lesser General Public9* License as published by the Free Software Foundation; either10* version 2.1 of the License, or (at your option) any later version.11*12* FFmpeg is distributed in the hope that it will be useful,13* but WITHOUT ANY WARRANTY; without even the implied warranty of14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU15* Lesser General Public License for more details.16*17* You should have received a copy of the GNU Lesser General Public18* License along with FFmpeg; if not, write to the Free Software19* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA20*/2122/**23* @file24* ATRAC3 compatible decoder.25* This decoder handles Sony's ATRAC3 data.26*27* Container formats used to store ATRAC3 data:28* RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3).29*30* To use this decoder, a calling application must supply the extradata31* bytes provided in the containers above.32*/33#define _USE_MATH_DEFINES3435#include <math.h>36#include <stddef.h>37#include <stdio.h>38#include <string.h>3940#include "float_dsp.h"41#include "fft.h"42#include "mem.h"43#include "compat.h"44#include "get_bits.h"4546#include "atrac.h"47#include "atrac3data.h"4849#define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1))5051#define JOINT_STEREO 0x1252#define STEREO 0x25354#define SAMPLES_PER_FRAME 102455#define MDCT_SIZE 5125657typedef struct GainBlock {58AtracGainInfo g_block[4];59} GainBlock;6061typedef struct TonalComponent {62int pos;63int num_coefs;64float coef[8];65} TonalComponent;6667typedef struct ChannelUnit {68int bands_coded;69int num_components;70float prev_frame[SAMPLES_PER_FRAME];71int gc_blk_switch;72TonalComponent components[64];73GainBlock gain_block[2];7475DECLARE_ALIGNED(32, float, spectrum)[SAMPLES_PER_FRAME];76DECLARE_ALIGNED(32, float, imdct_buf)[SAMPLES_PER_FRAME];7778float delay_buf1[46]; ///<qmf delay buffers79float delay_buf2[46];80float delay_buf3[46];81} ChannelUnit;8283typedef struct ATRAC3Context {84GetBitContext gb;85//@{86/** stream data */87int coding_mode;8889ChannelUnit *units;90//@}91//@{92/** joint-stereo related variables */93int matrix_coeff_index_prev[4];94int matrix_coeff_index_now[4];95int matrix_coeff_index_next[4];96int weighting_delay[6];97//@}98//@{99/** data buffers */100uint8_t *decoded_bytes_buffer;101float temp_buf[1070];102//@}103//@{104/** extradata */105int scrambled_stream;106//@}107108AtracGCContext gainc_ctx;109FFTContext mdct_ctx;110111int block_align;112int channels;113} ATRAC3Context;114115static DECLARE_ALIGNED(32, float, mdct_window)[MDCT_SIZE];116static VLC_TYPE atrac3_vlc_table[4096][2];117static VLC spectral_coeff_tab[7];118119/**120* Regular 512 points IMDCT without overlapping, with the exception of the121* swapping of odd bands caused by the reverse spectra of the QMF.122*123* @param odd_band 1 if the band is an odd band124*/125static void imlt(ATRAC3Context *q, float *input, float *output, int odd_band)126{127int i;128129if (odd_band) {130/**131* Reverse the odd bands before IMDCT, this is an effect of the QMF132* transform or it gives better compression to do it this way.133* FIXME: It should be possible to handle this in imdct_calc134* for that to happen a modification of the prerotation step of135* all SIMD code and C code is needed.136* Or fix the functions before so they generate a pre reversed spectrum.137*/138for (i = 0; i < 128; i++)139FFSWAP(float, input[i], input[255 - i]);140}141142imdct_calc(&q->mdct_ctx, output, input);143144/* Perform windowing on the output. */145vector_fmul(output, mdct_window, MDCT_SIZE);146}147148/*149* indata descrambling, only used for data coming from the rm container150*/151static int decode_bytes(const uint8_t *input, uint8_t *out, int bytes)152{153int i, off;154uint32_t c;155const uint32_t *buf;156uint32_t *output = (uint32_t *)out;157158off = (intptr_t)input & 3;159buf = (const uint32_t *)(input - off);160if (off)161c = av_be2ne32((0x537F6103U >> (off * 8)) | (0x537F6103U << (32 - (off * 8))));162else163c = av_be2ne32(0x537F6103U);164bytes += 3 + off;165for (i = 0; i < bytes / 4; i++)166output[i] = c ^ buf[i];167168//if (off)169// avpriv_request_sample(NULL, "Offset of %d", off);170171return off;172}173174static void init_imdct_window(void)175{176int i, j;177178/* generate the mdct window, for details see179* http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */180for (i = 0, j = 255; i < 128; i++, j--) {181float wi = sin(((i + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;182float wj = sin(((j + 0.5) / 256.0 - 0.5) * M_PI) + 1.0;183float w = 0.5 * (wi * wi + wj * wj);184mdct_window[i] = mdct_window[511 - i] = wi / w;185mdct_window[j] = mdct_window[511 - j] = wj / w;186}187}188189void atrac3_free(ATRAC3Context *ctx)190{191av_freep(&ctx->units);192av_freep(&ctx->decoded_bytes_buffer);193194ff_mdct_end(&ctx->mdct_ctx);195av_freep(&ctx);196}197198/**199* Mantissa decoding200*201* @param selector which table the output values are coded with202* @param coding_flag constant length coding or variable length coding203* @param mantissas mantissa output table204* @param num_codes number of values to get205*/206static void read_quant_spectral_coeffs(GetBitContext *gb, int selector,207int coding_flag, int *mantissas,208int num_codes)209{210int i, code, huff_symb;211212if (selector == 1)213num_codes /= 2;214215if (coding_flag != 0) {216/* constant length coding (CLC) */217int num_bits = clc_length_tab[selector];218219if (selector > 1) {220for (i = 0; i < num_codes; i++) {221if (num_bits)222code = get_sbits(gb, num_bits);223else224code = 0;225mantissas[i] = code;226}227} else {228for (i = 0; i < num_codes; i++) {229if (num_bits)230code = get_bits(gb, num_bits); // num_bits is always 4 in this case231else232code = 0;233mantissas[i * 2 ] = mantissa_clc_tab[code >> 2];234mantissas[i * 2 + 1] = mantissa_clc_tab[code & 3];235}236}237} else {238/* variable length coding (VLC) */239if (selector != 1) {240for (i = 0; i < num_codes; i++) {241huff_symb = get_vlc2(gb, spectral_coeff_tab[selector-1].table,242spectral_coeff_tab[selector-1].bits, 3);243huff_symb += 1;244code = huff_symb >> 1;245if (huff_symb & 1)246code = -code;247mantissas[i] = code;248}249} else {250for (i = 0; i < num_codes; i++) {251huff_symb = get_vlc2(gb, spectral_coeff_tab[selector - 1].table,252spectral_coeff_tab[selector - 1].bits, 3);253mantissas[i * 2 ] = mantissa_vlc_tab[huff_symb * 2 ];254mantissas[i * 2 + 1] = mantissa_vlc_tab[huff_symb * 2 + 1];255}256}257}258}259260/**261* Restore the quantized band spectrum coefficients262*263* @return subband count, fix for broken specification/files264*/265static int decode_spectrum(GetBitContext *gb, float *output)266{267int num_subbands, coding_mode, i, j, first, last, subband_size;268int subband_vlc_index[32], sf_index[32];269int mantissas[128];270float scale_factor;271272num_subbands = get_bits(gb, 5); // number of coded subbands273coding_mode = get_bits1(gb); // coding Mode: 0 - VLC/ 1-CLC274275/* get the VLC selector table for the subbands, 0 means not coded */276for (i = 0; i <= num_subbands; i++)277subband_vlc_index[i] = get_bits(gb, 3);278279/* read the scale factor indexes from the stream */280for (i = 0; i <= num_subbands; i++) {281if (subband_vlc_index[i] != 0)282sf_index[i] = get_bits(gb, 6);283}284285for (i = 0; i <= num_subbands; i++) {286first = subband_tab[i ];287last = subband_tab[i + 1];288289subband_size = last - first;290291if (subband_vlc_index[i] != 0) {292/* decode spectral coefficients for this subband */293/* TODO: This can be done faster is several blocks share the294* same VLC selector (subband_vlc_index) */295read_quant_spectral_coeffs(gb, subband_vlc_index[i], coding_mode,296mantissas, subband_size);297298/* decode the scale factor for this subband */299scale_factor = av_atrac_sf_table[sf_index[i]] *300inv_max_quant[subband_vlc_index[i]];301302/* inverse quantize the coefficients */303for (j = 0; first < last; first++, j++)304output[first] = mantissas[j] * scale_factor;305} else {306/* this subband was not coded, so zero the entire subband */307memset(output + first, 0, subband_size * sizeof(*output));308}309}310311/* clear the subbands that were not coded */312first = subband_tab[i];313memset(output + first, 0, (SAMPLES_PER_FRAME - first) * sizeof(*output));314return num_subbands;315}316317/**318* Restore the quantized tonal components319*320* @param components tonal components321* @param num_bands number of coded bands322*/323static int decode_tonal_components(GetBitContext *gb,324TonalComponent *components, int num_bands)325{326int i, b, c, m;327int nb_components, coding_mode_selector, coding_mode;328int band_flags[4], mantissa[8];329int component_count = 0;330331nb_components = get_bits(gb, 5);332333/* no tonal components */334if (nb_components == 0)335return 0;336337coding_mode_selector = get_bits(gb, 2);338if (coding_mode_selector == 2)339return AVERROR_INVALIDDATA;340341coding_mode = coding_mode_selector & 1;342343for (i = 0; i < nb_components; i++) {344int coded_values_per_component, quant_step_index;345346for (b = 0; b <= num_bands; b++)347band_flags[b] = get_bits1(gb);348349coded_values_per_component = get_bits(gb, 3);350351quant_step_index = get_bits(gb, 3);352if (quant_step_index <= 1)353return AVERROR_INVALIDDATA;354355if (coding_mode_selector == 3)356coding_mode = get_bits1(gb);357358for (b = 0; b < (num_bands + 1) * 4; b++) {359int coded_components;360361if (band_flags[b >> 2] == 0)362continue;363364coded_components = get_bits(gb, 3);365366for (c = 0; c < coded_components; c++) {367TonalComponent *cmp = &components[component_count];368int sf_index, coded_values, max_coded_values;369float scale_factor;370371sf_index = get_bits(gb, 6);372if (component_count >= 64)373return AVERROR_INVALIDDATA;374375cmp->pos = b * 64 + get_bits(gb, 6);376377max_coded_values = SAMPLES_PER_FRAME - cmp->pos;378coded_values = coded_values_per_component + 1;379coded_values = FFMIN(max_coded_values, coded_values);380381scale_factor = av_atrac_sf_table[sf_index] *382inv_max_quant[quant_step_index];383384read_quant_spectral_coeffs(gb, quant_step_index, coding_mode,385mantissa, coded_values);386387cmp->num_coefs = coded_values;388389/* inverse quant */390for (m = 0; m < coded_values; m++)391cmp->coef[m] = mantissa[m] * scale_factor;392393component_count++;394}395}396}397398return component_count;399}400401/**402* Decode gain parameters for the coded bands403*404* @param block the gainblock for the current band405* @param num_bands amount of coded bands406*/407static int decode_gain_control(GetBitContext *gb, GainBlock *block,408int num_bands)409{410int b, j;411int *level, *loc;412413AtracGainInfo *gain = block->g_block;414415for (b = 0; b <= num_bands; b++) {416gain[b].num_points = get_bits(gb, 3);417level = gain[b].lev_code;418loc = gain[b].loc_code;419420for (j = 0; j < gain[b].num_points; j++) {421level[j] = get_bits(gb, 4);422loc[j] = get_bits(gb, 5);423if (j && loc[j] <= loc[j - 1])424return AVERROR_INVALIDDATA;425}426}427428/* Clear the unused blocks. */429for (; b < 4 ; b++)430gain[b].num_points = 0;431432return 0;433}434435/**436* Combine the tonal band spectrum and regular band spectrum437*438* @param spectrum output spectrum buffer439* @param num_components number of tonal components440* @param components tonal components for this band441* @return position of the last tonal coefficient442*/443static int add_tonal_components(float *spectrum, int num_components,444TonalComponent *components)445{446int i, j, last_pos = -1;447float *input, *output;448449for (i = 0; i < num_components; i++) {450last_pos = FFMAX(components[i].pos + components[i].num_coefs, last_pos);451input = components[i].coef;452output = &spectrum[components[i].pos];453454for (j = 0; j < components[i].num_coefs; j++)455output[j] += input[j];456}457458return last_pos;459}460461#define INTERPOLATE(old, new, nsample) \462((old) + (nsample) * 0.125 * ((new) - (old)))463464static void reverse_matrixing(float *su1, float *su2, int *prev_code,465int *curr_code)466{467int i, nsample, band;468float mc1_l, mc1_r, mc2_l, mc2_r;469470for (i = 0, band = 0; band < 4 * 256; band += 256, i++) {471int s1 = prev_code[i];472int s2 = curr_code[i];473nsample = band;474475if (s1 != s2) {476/* Selector value changed, interpolation needed. */477mc1_l = matrix_coeffs[s1 * 2 ];478mc1_r = matrix_coeffs[s1 * 2 + 1];479mc2_l = matrix_coeffs[s2 * 2 ];480mc2_r = matrix_coeffs[s2 * 2 + 1];481482/* Interpolation is done over the first eight samples. */483for (; nsample < band + 8; nsample++) {484float c1 = su1[nsample];485float c2 = su2[nsample];486c2 = c1 * INTERPOLATE(mc1_l, mc2_l, nsample - band) +487c2 * INTERPOLATE(mc1_r, mc2_r, nsample - band);488su1[nsample] = c2;489su2[nsample] = c1 * 2.0 - c2;490}491}492493/* Apply the matrix without interpolation. */494switch (s2) {495case 0: /* M/S decoding */496for (; nsample < band + 256; nsample++) {497float c1 = su1[nsample];498float c2 = su2[nsample];499su1[nsample] = c2 * 2.0;500su2[nsample] = (c1 - c2) * 2.0;501}502break;503case 1:504for (; nsample < band + 256; nsample++) {505float c1 = su1[nsample];506float c2 = su2[nsample];507su1[nsample] = (c1 + c2) * 2.0;508su2[nsample] = c2 * -2.0;509}510break;511case 2:512case 3:513for (; nsample < band + 256; nsample++) {514float c1 = su1[nsample];515float c2 = su2[nsample];516su1[nsample] = c1 + c2;517su2[nsample] = c1 - c2;518}519break;520default:521av_assert1(0);522}523}524}525526static void get_channel_weights(int index, int flag, float ch[2])527{528if (index == 7) {529ch[0] = 1.0;530ch[1] = 1.0;531} else {532ch[0] = (index & 7) / 7.0;533ch[1] = sqrt(2 - ch[0] * ch[0]);534if (flag)535FFSWAP(float, ch[0], ch[1]);536}537}538539static void channel_weighting(float *su1, float *su2, int *p3)540{541int band, nsample;542/* w[x][y] y=0 is left y=1 is right */543float w[2][2];544545if (p3[1] != 7 || p3[3] != 7) {546get_channel_weights(p3[1], p3[0], w[0]);547get_channel_weights(p3[3], p3[2], w[1]);548549for (band = 256; band < 4 * 256; band += 256) {550for (nsample = band; nsample < band + 8; nsample++) {551su1[nsample] *= INTERPOLATE(w[0][0], w[0][1], nsample - band);552su2[nsample] *= INTERPOLATE(w[1][0], w[1][1], nsample - band);553}554for(; nsample < band + 256; nsample++) {555su1[nsample] *= w[1][0];556su2[nsample] *= w[1][1];557}558}559}560}561562/**563* Decode a Sound Unit564*565* @param snd the channel unit to be used566* @param output the decoded samples before IQMF in float representation567* @param channel_num channel number568* @param coding_mode the coding mode (JOINT_STEREO or regular stereo/mono)569*/570static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,571ChannelUnit *snd, float *output,572int channel_num, int coding_mode)573{574int band, ret, num_subbands, last_tonal, num_bands;575GainBlock *gain1 = &snd->gain_block[ snd->gc_blk_switch];576GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];577578if (coding_mode == JOINT_STEREO && channel_num == 1) {579if (get_bits(gb, 2) != 3) {580av_log(AV_LOG_ERROR,"JS mono Sound Unit id != 3.");581return AVERROR_INVALIDDATA;582}583} else {584if (get_bits(gb, 6) != 0x28) {585av_log(AV_LOG_ERROR,"Sound Unit id != 0x28.");586return AVERROR_INVALIDDATA;587}588}589590/* number of coded QMF bands */591snd->bands_coded = get_bits(gb, 2);592593ret = decode_gain_control(gb, gain2, snd->bands_coded);594if (ret)595return ret;596597snd->num_components = decode_tonal_components(gb, snd->components,598snd->bands_coded);599if (snd->num_components < 0)600return snd->num_components;601602num_subbands = decode_spectrum(gb, snd->spectrum);603604/* Merge the decoded spectrum and tonal components. */605last_tonal = add_tonal_components(snd->spectrum, snd->num_components,606snd->components);607608609/* calculate number of used MLT/QMF bands according to the amount of coded610spectral lines */611num_bands = (subband_tab[num_subbands] - 1) >> 8;612if (last_tonal >= 0)613num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);614615616/* Reconstruct time domain samples. */617for (band = 0; band < 4; band++) {618/* Perform the IMDCT step without overlapping. */619if (band <= num_bands)620imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);621else622memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));623624/* gain compensation and overlapping */625ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,626&snd->prev_frame[band * 256],627&gain1->g_block[band], &gain2->g_block[band],628256, &output[band * 256]);629}630631/* Swap the gain control buffers for the next frame. */632snd->gc_blk_switch ^= 1;633634return 0;635}636637static int decode_frame(ATRAC3Context *q, int block_align, int channels, const uint8_t *databuf,638float **out_samples)639{640int ret, i;641uint8_t *ptr1;642643if (q->coding_mode == JOINT_STEREO) {644/* channel coupling mode */645/* decode Sound Unit 1 */646init_get_bits(&q->gb, databuf, block_align * 8);647648ret = decode_channel_sound_unit(q, &q->gb, q->units, out_samples[0], 0,649JOINT_STEREO);650if (ret != 0)651return ret;652653/* Framedata of the su2 in the joint-stereo mode is encoded in654* reverse byte order so we need to swap it first. */655if (databuf == q->decoded_bytes_buffer) {656uint8_t *ptr2 = q->decoded_bytes_buffer + block_align - 1;657ptr1 = q->decoded_bytes_buffer;658for (i = 0; i < block_align / 2; i++, ptr1++, ptr2--)659FFSWAP(uint8_t, *ptr1, *ptr2);660} else {661const uint8_t *ptr2 = databuf + block_align - 1;662for (i = 0; i < block_align; i++)663q->decoded_bytes_buffer[i] = *ptr2--;664}665666/* Skip the sync codes (0xF8). */667ptr1 = q->decoded_bytes_buffer;668for (i = 4; *ptr1 == 0xF8; i++, ptr1++) {669if (i >= block_align)670return AVERROR_INVALIDDATA;671}672673674/* set the bitstream reader at the start of the second Sound Unit*/675init_get_bits8(&q->gb, ptr1, q->decoded_bytes_buffer + block_align - ptr1);676677/* Fill the Weighting coeffs delay buffer */678memmove(q->weighting_delay, &q->weighting_delay[2],6794 * sizeof(*q->weighting_delay));680q->weighting_delay[4] = get_bits1(&q->gb);681q->weighting_delay[5] = get_bits(&q->gb, 3);682683for (i = 0; i < 4; i++) {684q->matrix_coeff_index_prev[i] = q->matrix_coeff_index_now[i];685q->matrix_coeff_index_now[i] = q->matrix_coeff_index_next[i];686q->matrix_coeff_index_next[i] = get_bits(&q->gb, 2);687}688689/* Decode Sound Unit 2. */690ret = decode_channel_sound_unit(q, &q->gb, &q->units[1],691out_samples[1], 1, JOINT_STEREO);692if (ret != 0)693return ret;694695/* Reconstruct the channel coefficients. */696reverse_matrixing(out_samples[0], out_samples[1],697q->matrix_coeff_index_prev,698q->matrix_coeff_index_now);699700channel_weighting(out_samples[0], out_samples[1], q->weighting_delay);701} else {702/* normal stereo mode or mono */703/* Decode the channel sound units. */704for (i = 0; i < channels; i++) {705/* Set the bitstream reader at the start of a channel sound unit. */706init_get_bits(&q->gb,707databuf + i * block_align / channels,708block_align * 8 / channels);709710ret = decode_channel_sound_unit(q, &q->gb, &q->units[i],711out_samples[i], i, q->coding_mode);712if (ret != 0)713return ret;714}715}716717/* Apply the iQMF synthesis filter. */718for (i = 0; i < channels; i++) {719float *p1 = out_samples[i];720float *p2 = p1 + 256;721float *p3 = p2 + 256;722float *p4 = p3 + 256;723ff_atrac_iqmf(p1, p2, 256, p1, q->units[i].delay_buf1, q->temp_buf);724ff_atrac_iqmf(p4, p3, 256, p3, q->units[i].delay_buf2, q->temp_buf);725ff_atrac_iqmf(p1, p3, 512, p1, q->units[i].delay_buf3, q->temp_buf);726}727728return 0;729}730731int atrac3_decode_frame(ATRAC3Context *ctx, float *out_data[2], int *nb_samples, const uint8_t *buf, int buf_size)732{733int ret;734const uint8_t *databuf;735736const int block_align = ctx->block_align;737const int channels = ctx->channels;738739*nb_samples = 0;740741if (buf_size < block_align) {742av_log(AV_LOG_ERROR,743"Frame too small (%d bytes). Truncated file?", buf_size);744return AVERROR_INVALIDDATA;745}746747/* Check if we need to descramble and what buffer to pass on. */748if (ctx->scrambled_stream) {749decode_bytes(buf, ctx->decoded_bytes_buffer, block_align);750databuf = ctx->decoded_bytes_buffer;751} else {752databuf = buf;753}754755ret = decode_frame(ctx, block_align, channels, databuf, out_data);756if (ret) {757av_log(AV_LOG_ERROR, "Frame decoding error!");758return ret;759}760761*nb_samples = SAMPLES_PER_FRAME;762return block_align;763}764765void atrac3_flush_buffers(ATRAC3Context *c) {766// There's no known correct way to do this, so let's just reset some stuff.767memset(c->temp_buf, 0, sizeof(c->temp_buf));768}769770static void atrac3_init_static_data(void)771{772int i;773774init_imdct_window();775ff_atrac_generate_tables();776777/* Initialize the VLC tables. */778for (i = 0; i < 7; i++) {779spectral_coeff_tab[i].table = &atrac3_vlc_table[atrac3_vlc_offs[i]];780spectral_coeff_tab[i].table_allocated = atrac3_vlc_offs[i + 1] -781atrac3_vlc_offs[i ];782init_vlc(&spectral_coeff_tab[i], 9, huff_tab_sizes[i],783huff_bits[i], 1, 1,784huff_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);785}786}787788static int static_init_done;789790ATRAC3Context *atrac3_alloc(int channels, int *block_align, const uint8_t *extra_data, int extra_data_size) {791int i, ret;792int version, delay, samples_per_frame, frame_factor;793794const uint8_t *edata_ptr = extra_data;795796if (channels <= 0 || channels > 2) {797av_log(AV_LOG_ERROR, "Channel configuration error!");798return nullptr;799}800801ATRAC3Context *q = (ATRAC3Context *)av_mallocz(sizeof(ATRAC3Context));802q->channels = channels;803if (*block_align) {804q->block_align = *block_align;805} else {806// Atrac3 (unlike Atrac3+) requires a specified block align.807atrac3_free(q);808return nullptr;809}810811if (!static_init_done)812atrac3_init_static_data();813static_init_done = 1;814815/* Take care of the codec-specific extradata. */816if (extra_data_size == 14) {817/* Parse the extradata, WAV format */818av_log(AV_LOG_DEBUG, "[0-1] %d",819bytestream_get_le16(&edata_ptr)); // Unknown value always 1820edata_ptr += 4; // samples per channel821q->coding_mode = bytestream_get_le16(&edata_ptr);822av_log(AV_LOG_DEBUG,"[8-9] %d",823bytestream_get_le16(&edata_ptr)); //Dupe of coding mode824frame_factor = bytestream_get_le16(&edata_ptr); // Unknown always 1825av_log(AV_LOG_DEBUG,"[12-13] %d",826bytestream_get_le16(&edata_ptr)); // Unknown always 0827828/* setup */829samples_per_frame = SAMPLES_PER_FRAME * channels;830version = 4;831delay = 0x88E;832q->coding_mode = q->coding_mode ? JOINT_STEREO : STEREO;833q->scrambled_stream = 0;834835if (q->block_align != 96 * channels * frame_factor &&836q->block_align != 152 * channels * frame_factor &&837q->block_align != 192 * channels * frame_factor) {838av_log(AV_LOG_ERROR, "Unknown frame/channel/frame_factor "839"configuration %d/%d/%d", block_align,840channels, frame_factor);841atrac3_free(q);842return nullptr;843}844} else if (extra_data_size == 12 || extra_data_size == 10) {845/* Parse the extradata, RM format. */846version = bytestream_get_be32(&edata_ptr);847samples_per_frame = bytestream_get_be16(&edata_ptr);848delay = bytestream_get_be16(&edata_ptr);849q->coding_mode = bytestream_get_be16(&edata_ptr);850q->scrambled_stream = 1;851852} else {853av_log(AV_LOG_ERROR, "Unknown extradata size %d.",854extra_data_size);855atrac3_free(q);856return nullptr;857}858859/* Check the extradata */860861if (version != 4) {862av_log(AV_LOG_ERROR, "Version %d != 4.", version);863atrac3_free(q);864return nullptr;865}866867if (samples_per_frame != SAMPLES_PER_FRAME &&868samples_per_frame != SAMPLES_PER_FRAME * 2) {869av_log(AV_LOG_ERROR, "Unknown amount of samples per frame %d.",870samples_per_frame);871atrac3_free(q);872return nullptr;873}874875if (delay != 0x88E) {876av_log(AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.",877delay);878atrac3_free(q);879return nullptr;880}881882if (q->coding_mode == STEREO)883av_log(AV_LOG_DEBUG, "Normal stereo detected.");884else if (q->coding_mode == JOINT_STEREO) {885if (channels != 2) {886av_log(AV_LOG_ERROR, "Invalid coding mode");887atrac3_free(q);888return nullptr;889}890av_log(AV_LOG_DEBUG, "Joint stereo detected.");891} else {892av_log(AV_LOG_ERROR, "Unknown channel coding mode %x!",893q->coding_mode);894atrac3_free(q);895return nullptr;896}897898q->decoded_bytes_buffer = (uint8_t *)av_mallocz(FFALIGN(q->block_align, 4) + AV_INPUT_BUFFER_PADDING_SIZE);899900/* initialize the MDCT transform */901if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {902av_log(AV_LOG_ERROR, "Error initializing MDCT");903av_freep(&q->decoded_bytes_buffer);904905return nullptr;906}907908/* init the joint-stereo decoding data */909q->weighting_delay[0] = 0;910q->weighting_delay[1] = 7;911q->weighting_delay[2] = 0;912q->weighting_delay[3] = 7;913q->weighting_delay[4] = 0;914q->weighting_delay[5] = 7;915916for (i = 0; i < 4; i++) {917q->matrix_coeff_index_prev[i] = 3;918q->matrix_coeff_index_now[i] = 3;919q->matrix_coeff_index_next[i] = 3;920}921922ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);923924q->units = (ChannelUnit *)av_mallocz_array(channels, sizeof(*q->units));925return q;926}927928929