summaryrefslogtreecommitdiffstats
path: root/libmpcodecs/ad_twin.c
blob: 395567128a35ce55601ecb3feeb1fd7332858471 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "config.h"

#include "ad_internal.h"
#include "vqf.h"
#include "loader/ldt_keeper.h"
#include "loader/wine/windef.h"
#include "libaf/af_format.h"

#include "help_mp.h"

static const ad_info_t info =
{
    "TWinVQ decoder",
    "vqf",
    "Roberto Togni",
    "Nick Kurshev",
    "Ported from MPlayerXP"
};

LIBAD_EXTERN(twin)

void* WINAPI LoadLibraryA(char* name);
void*  WINAPI GetProcAddress(void* handle, char* func);
int WINAPI FreeLibrary(void* handle);

static int (*TvqInitialize)( headerInfo *setupInfo, INDEX *index, int dispErrorMessageBox );
static void (*TvqTerminate)( INDEX *index );
static void (*TvqGetVectorInfo)(int *bits0[], int *bits1[]);

static void (*TvqDecodeFrame)(INDEX  *indexp, float out[]);
static int  (*TvqWtypeToBtype)( int w_type, int *btype );
static void (*TvqUpdateVectorInfo)(int varbits, int *ndiv, int bits0[], int bits1[]);

static int   (*TvqCheckVersion)(char *versionID);
static void  (*TvqGetConfInfo)(tvqConfInfo *cf);
static int   (*TvqGetFrameSize)();
static int   (*TvqGetNumFixedBitsPerFrame)();

#define BYTE_BIT    8
#define BBUFSIZ     1024        /* Bit buffer size (bytes) */
#define BBUFLEN     (BBUFSIZ*BYTE_BIT)  /* Bit buffer length (bits) */
typedef struct vqf_priv_s
{
  float pts;
  WAVEFORMATEX o_wf;   // out format
  INDEX index;
  tvqConfInfo cf;
  headerInfo hi;
  int *bits_0[N_INTR_TYPE], *bits_1[N_INTR_TYPE];
  unsigned framesize;
  /* stream related */
  int readable;
  int ptr;           /* current point in the bit buffer */
  int nbuf;          /* bit buffer size */
  char buf[BBUFSIZ];  /* the bit buffer */
  int skip_cnt;
}vqf_priv_t;

static void* vqf_dll;

static int load_dll( char *libname )
{
#ifdef WIN32_LOADER
    Setup_LDT_Keeper();
#endif
    vqf_dll = LoadLibraryA(libname);
    if( vqf_dll == NULL )
    {
        mp_msg(MSGT_DECAUDIO, MSGL_ERR, "failed loading dll\n" );
    return 0;
    }
  TvqInitialize = GetProcAddress(vqf_dll,"TvqInitialize");
  TvqTerminate = GetProcAddress(vqf_dll,"TvqTerminate");
  TvqGetVectorInfo = GetProcAddress(vqf_dll,"TvqGetVectorInfo");
  TvqDecodeFrame = GetProcAddress(vqf_dll,"TvqDecodeFrame");
  TvqWtypeToBtype = GetProcAddress(vqf_dll,"TvqWtypeToBtype");
  TvqUpdateVectorInfo = GetProcAddress(vqf_dll,"TvqUpdateVectorInfo");
  TvqCheckVersion = GetProcAddress(vqf_dll,"TvqCheckVersion");
  TvqGetConfInfo = GetProcAddress(vqf_dll,"TvqGetConfInfo");
  TvqGetFrameSize = GetProcAddress(vqf_dll,"TvqGetFrameSize");
  TvqGetNumFixedBitsPerFrame = GetProcAddress(vqf_dll,"TvqGetNumFixedBitsPerFrame");
  return TvqInitialize && TvqTerminate && TvqGetVectorInfo &&
     TvqDecodeFrame && TvqWtypeToBtype && TvqUpdateVectorInfo &&
     TvqCheckVersion && TvqGetConfInfo && TvqGetFrameSize &&
     TvqGetNumFixedBitsPerFrame;
}

void print_wave_header(WAVEFORMATEX *h, int verbose_level);
static int init_vqf_audio_codec(sh_audio_t *sh_audio){
    WAVEFORMATEX *in_fmt=sh_audio->wf;
    vqf_priv_t*priv=sh_audio->context;
    int ver;
    mp_msg(MSGT_DECAUDIO, MSGL_INFO, "======= Win32 (TWinVQ) AUDIO Codec init =======\n");

    sh_audio->channels=in_fmt->nChannels;
    sh_audio->samplerate=in_fmt->nSamplesPerSec;
    sh_audio->sample_format=AF_FORMAT_S16_NE;
//    sh_audio->sample_format=AF_FORMAT_FLOAT_NE;
    sh_audio->samplesize=af_fmt2bits(sh_audio->sample_format)/8;
    priv->o_wf.nChannels=in_fmt->nChannels;
    priv->o_wf.nSamplesPerSec=in_fmt->nSamplesPerSec;
    priv->o_wf.nBlockAlign=sh_audio->samplesize*in_fmt->nChannels;
    priv->o_wf.nAvgBytesPerSec=in_fmt->nBlockAlign*in_fmt->nChannels;
    priv->o_wf.wFormatTag=0x01;
    priv->o_wf.wBitsPerSample=in_fmt->wBitsPerSample;
    priv->o_wf.cbSize=0;

    if( mp_msg_test(MSGT_DECAUDIO,MSGL_V) )
    {
    mp_msg(MSGT_DECAUDIO, MSGL_V, "Input format:\n");
    print_wave_header(in_fmt, MSGL_V);
    mp_msg(MSGT_DECAUDIO, MSGL_V, "Output fmt:\n");
    print_wave_header(&priv->o_wf, MSGL_V);
    }
    memcpy(&priv->hi,&in_fmt[1],sizeof(headerInfo));
    if((ver=TvqInitialize(&priv->hi,&priv->index,0))){
    const char *tvqe[]={
    "No errors",
    "General error",
    "Wrong version",
    "Channel setting error",
    "Wrong coding mode",
    "Inner parameter setting error",
    "Wrong number of VQ pre-selection candidates, used only in encoder" };
    mp_msg(MSGT_DECAUDIO, MSGL_ERR, "Tvq initialization error: %s\n",ver>=0&&ver<7?tvqe[ver]:"Unknown");
    return 0;
    }
    ver=TvqCheckVersion(priv->hi.ID);
    if(ver==TVQ_UNKNOWN_VERSION){
    mp_msg(MSGT_DECAUDIO, MSGL_ERR, "Tvq unknown version of stream\n" );
    return 0;
    }
    TvqGetConfInfo(&priv->cf);
    TvqGetVectorInfo(priv->bits_0,priv->bits_1);
    priv->framesize=TvqGetFrameSize();
    sh_audio->audio_in_minsize=priv->framesize*in_fmt->nChannels;
    sh_audio->a_in_buffer_size=4*sh_audio->audio_in_minsize;
    sh_audio->a_in_buffer=av_malloc(sh_audio->a_in_buffer_size);
    sh_audio->a_in_buffer_len=0;


    return 1;
}

static int close_vqf_audio_codec(sh_audio_t *sh_audio)
{
    vqf_priv_t*priv=sh_audio->context;
    TvqTerminate(&priv->index);
    return 1;
}

int init(sh_audio_t *sh_audio)
{
    return 1;
}

int preinit(sh_audio_t *sh_audio)
{
  /* Win32 VQF audio codec: */
  vqf_priv_t *priv;
  if(!(sh_audio->context=malloc(sizeof(vqf_priv_t)))) return 0;
  priv=sh_audio->context;
  if(!load_dll(sh_audio->codec->dll))
  {
    mp_msg(MSGT_DECAUDIO, MSGL_ERR, "win32.dll looks broken :(\n");
    return 0;
  }
  if(!init_vqf_audio_codec(sh_audio)){
    mp_msg(MSGT_DECAUDIO, MSGL_ERR, "TWinVQ initialization fail\n");
    return 0;
  }
  mp_msg(MSGT_DECAUDIO, MSGL_INFO, "INFO: TWinVQ (%s) audio codec init OK!\n",sh_audio->codec->dll);
  priv->skip_cnt = 2;
  return 1;
}

void uninit(sh_audio_t *sh)
{
  close_vqf_audio_codec(sh);
  free(sh->context);
  FreeLibrary(vqf_dll);
}

int control(sh_audio_t *sh_audio,int cmd,void* arg, ...)
{
  switch(cmd) {
      case ADCTRL_QUERY_FORMAT:
          return CONTROL_TRUE;
      default:
          return CONTROL_UNKNOWN;
  }
}

static int bread(char   *data,    /* Output: Output data array */
          int   size,     /* Input:  Length of each data */
          int   nbits,    /* Input:  Number of bits to write */
          sh_audio_t *sh)  /* Input:  File pointer */
{
    /*--- Variables ---*/
    int  ibits, iptr, idata, ibufadr, ibufbit, icl;
    unsigned char mask, tmpdat;
    int  retval;
    vqf_priv_t *priv=sh->context;

    /*--- Main operation ---*/
    retval = 0;
    mask = 0x1;
    for ( ibits=0; ibits<nbits; ibits++ ){
        if ( priv->readable == 0 ){  /* when the file data buffer is empty */
            priv->nbuf = demux_read_data(sh->ds, priv->buf, BBUFSIZ);
            priv->nbuf *= 8;
            priv->readable = 1;
        }
        iptr = priv->ptr;           /* current file data buffer pointer */
        if ( iptr >= priv->nbuf )   /* If data file is empty then return */
            return retval;
        ibufadr = iptr/BYTE_BIT;      /* current file data buffer address */
        ibufbit = iptr%BYTE_BIT;      /* current file data buffer bit */
        /*  tmpdat = stream->buf[ibufadr] >> (BYTE_BIT-ibufbit-1); */
        tmpdat = (unsigned char)priv->buf[ibufadr];
        tmpdat >>= (BYTE_BIT-ibufbit-1);
        /* current data bit */

        idata = ibits*size;                   /* output data address */
        data[idata] = (char)(tmpdat & mask);  /* set output data */
        for (icl=1; icl<size; icl++)
            data[idata+icl] = 0; /* clear the rest output data buffer */
        priv->ptr += 1;       /* update data buffer pointer */
        if (priv->ptr == BBUFLEN){
            priv->ptr = 0;
            priv->readable = 0;
        }
        ++retval;
    }
    return retval;
}

#define BITS_INT    (sizeof(int)*8)

static int get_bstm(int *data,          /* Input: input data */
            unsigned nbits,         /* Input: number of bits */
            sh_audio_t *sh)          /* Input: bit file pointer */
{
    unsigned    ibit;
    unsigned    mask;
    unsigned    work;
    char    tmpbit[BITS_INT];
    int     retval;

    if ( nbits > BITS_INT ){
        mp_msg(MSGT_DECAUDIO, MSGL_ERR, "get_bstm(): %d: %d Error.\n",
            nbits, BITS_INT);
        exit(1);
    }
    retval = bread(tmpbit, sizeof(*tmpbit), nbits, sh);
    for (ibit=retval; ibit<nbits; ibit++){
        tmpbit[ibit] = 0;
    }
    mask = 0x1<<(nbits-1);
    work=0;
    for ( ibit=0; ibit<nbits; ibit++ ){
        work += mask*tmpbit[ibit];
        mask >>= 1;
    }
    *data = work;
    return retval;
}

static int GetVqInfo( tvqConfInfoSubBlock *cfg,
            int bits0[],
            int bits1[],
            int variableBits,
            INDEX *index,
            sh_audio_t *sh)
{
    int idiv;
    int bitcount = 0;

    if ( index->btype == BLK_LONG ){
        TvqUpdateVectorInfo( variableBits, &cfg->ndiv, bits0, bits1 ); // re-calculate VQ bits
    }
    for ( idiv=0; idiv<cfg->ndiv; idiv++ ){
        bitcount += get_bstm(&index->wvq[idiv],bits0[idiv],sh); /* CB 0 */
        bitcount += get_bstm(&index->wvq[idiv+cfg->ndiv],bits1[idiv],sh); /* CB 1 */
    }
    return bitcount;
}

static int GetBseInfo( tvqConfInfo *cf, tvqConfInfoSubBlock *cfg, INDEX *index, sh_audio_t *sh)
{
    int i_sup, isf, itmp, idiv;
    int bitcount = 0;

    for ( i_sup=0; i_sup<cf->N_CH; i_sup++ ){
        for ( isf=0; isf<cfg->nsf; isf++ ){
            for ( idiv=0; idiv<cfg->fw_ndiv; idiv++ ){
                itmp = idiv + ( isf + i_sup * cfg->nsf ) * cfg->fw_ndiv;
                bitcount += get_bstm(&index->fw[itmp],cfg->fw_nbit,sh);
            }
        }
    }
    for ( i_sup=0; i_sup<cf->N_CH; i_sup++ ){
        for ( isf=0; isf<cfg->nsf; isf++ ){
            bitcount += get_bstm(&index->fw_alf[i_sup * cfg->nsf + isf],cf->FW_ARSW_BITS,sh);
        }
    }
    return bitcount;
}

static int GetGainInfo(tvqConfInfo *cf, tvqConfInfoSubBlock *cfg, INDEX *index, sh_audio_t *sh )
{
    int i_sup, iptop, isf;
    int bitcount = 0;

    for ( i_sup=0; i_sup<cf->N_CH; i_sup++ ){
        iptop = ( cfg->nsubg + 1 ) * i_sup;
        bitcount += get_bstm(&index->pow[iptop], cf->GAIN_BITS,sh);
        for ( isf=0; isf<cfg->nsubg; isf++ ){
            bitcount += get_bstm(&index->pow[iptop+isf+1], cf->SUB_GAIN_BITS,sh);
        }
    }
    return bitcount;
}

static int GetLspInfo( tvqConfInfo *cf, INDEX *index, sh_audio_t *sh )
{
    int i_sup, itmp;
    int bitcount = 0;

    for ( i_sup=0; i_sup<cf->N_CH; i_sup++ ){
        bitcount += get_bstm(&index->lsp[i_sup][0], cf->LSP_BIT0,sh); /* pred. switch */
        bitcount += get_bstm(&index->lsp[i_sup][1], cf->LSP_BIT1,sh); /* first stage */
        for ( itmp=0; itmp<cf->LSP_SPLIT; itmp++ ){         /* second stage */
            bitcount += get_bstm(&index->lsp[i_sup][itmp+2], cf->LSP_BIT2,sh);
        }
    }

    return bitcount;
}

static int GetPpcInfo( tvqConfInfo *cf, INDEX *index, sh_audio_t *sh)
{
    int idiv, i_sup;
    int bitcount = 0;
    vqf_priv_t*priv=sh->context;

    for ( idiv=0; idiv<cf->N_DIV_P; idiv++ ){
        bitcount += get_bstm(&(index->pls[idiv]), priv->bits_0[BLK_PPC][idiv],sh);       /*CB0*/
        bitcount += get_bstm(&(index->pls[idiv+cf->N_DIV_P]), priv->bits_1[BLK_PPC][idiv],sh);/*CB1*/
    }
    for (i_sup=0; i_sup<cf->N_CH; i_sup++){
        bitcount += get_bstm(&(index->pit[i_sup]), cf->BASF_BIT,sh);
        bitcount += get_bstm(&(index->pgain[i_sup]), cf->PGAIN_BIT,sh);
    }

    return bitcount;
}

static int GetEbcInfo( tvqConfInfo *cf, tvqConfInfoSubBlock *cfg, INDEX *index, sh_audio_t *sh)
{
    int i_sup, isf, itmp;
    int bitcount = 0;

    for ( i_sup=0; i_sup<cf->N_CH; i_sup++ ){
        for ( isf=0; isf<cfg->nsf; isf++){
            int indexSfOffset = isf * ( cfg->ncrb - cfg->ebc_crb_base ) - cfg->ebc_crb_base;
            for ( itmp=cfg->ebc_crb_base; itmp<cfg->ncrb; itmp++ ){
                bitcount += get_bstm(&index->bc[i_sup][itmp+indexSfOffset], cfg->ebc_bits,sh);
            }
        }
    }

    return bitcount;
}

static int vqf_read_frame(sh_audio_t *sh,INDEX *index)
{
    /*--- Variables ---*/
    tvqConfInfoSubBlock *cfg;
    int variableBits;
    int bitcount;
    int numFixedBitsPerFrame = TvqGetNumFixedBitsPerFrame();
    int btype;
    vqf_priv_t *priv=sh->context;

    /*--- Initialization ---*/
    variableBits = 0;
    bitcount = 0;

    /*--- read block independent factors ---*/
    /* Window type */
    bitcount += get_bstm( &index->w_type, priv->cf.BITS_WTYPE, sh );
    if ( TvqWtypeToBtype( index->w_type, &index->btype ) ) {
        mp_msg(MSGT_DECAUDIO, MSGL_ERR, "Error: unknown window type: %d\n", index->w_type);
        return 0;
    }
    btype = index->btype;

    /*--- read block dependent factors ---*/
    cfg = &priv->cf.cfg[btype]; // set the block dependent paremeters table

    bitcount += variableBits;

    /* Interleaved vector quantization */
    bitcount += GetVqInfo( cfg, priv->bits_0[btype], priv->bits_1[btype], variableBits, index, sh );

    /* Bark-scale envelope */
    bitcount += GetBseInfo( &priv->cf, cfg, index, sh );
    /* Gain */
    bitcount += GetGainInfo( &priv->cf, cfg, index, sh );
    /* LSP */
    bitcount += GetLspInfo( &priv->cf, index, sh );
    /* PPC */
    if ( cfg->ppc_enable ){
        bitcount += GetPpcInfo( &priv->cf, index, sh );
    }
    /* Energy Balance Calibration */
    if ( cfg->ebc_enable ){
        bitcount += GetEbcInfo( &priv->cf, cfg, index, sh );
    }

    return bitcount == numFixedBitsPerFrame ? bitcount/8 : 0;
}

static void frtobuf_s16(float out[],       /* Input  --- input data frame */
        short bufout[],    /* Output --- output data buffer array */
        unsigned frameSize,   /* Input  --- frame size */
        unsigned numChannels) /* Input  --- number of channels */
{
    /*--- Variables ---*/
    unsigned ismp, ich;
    float *ptr;
    float dtmp;

    for ( ich=0; ich<numChannels; ich++ ){
        ptr = out+ich*frameSize;
        for ( ismp=0; ismp<frameSize; ismp++ ){
            dtmp = ptr[ismp];
            if ( dtmp >= 0. ) {
                if ( dtmp > 32700. )
                dtmp = 32700.;
                bufout[ismp*numChannels+ich] = (short)(dtmp+0.5);
            } else {
                if ( dtmp < -32700. )
                dtmp = -32700.;
                bufout[ismp*numChannels+ich] = (short)(dtmp-0.5);
            }
        }
    }
}

static void frtobuf_float(float out[],       /* Input  --- input data frame */
        float bufout[],    /* Output --- output data buffer array */
        unsigned frameSize,   /* Input  --- frame size */
        unsigned numChannels) /* Input  --- number of channels */
{
    /*--- Variables ---*/
    unsigned ismp, ich;
    float *ptr;
    float dtmp;

    for ( ich=0; ich<numChannels; ich++ ){
        ptr = out+ich*frameSize;
        for ( ismp=0; ismp<frameSize; ismp++ ){
            dtmp = ptr[ismp];
            if ( dtmp >= 0. ) {
                if ( dtmp > 32700. )
                dtmp = 32700.;
                bufout[ismp*numChannels+ich] = dtmp/32767.;
            } else {
                if ( dtmp < -32700. )
                dtmp = -32700.;
                bufout[ismp*numChannels+ich] = dtmp/32767.;
            }
        }
    }
}

int decode_audio(sh_audio_t *sh_audio,unsigned char *buf,int minlen,int maxlen)
{
    int l, len=0;
    vqf_priv_t *priv=sh_audio->context;
    while(len<minlen)
    {
        float out[priv->framesize*sh_audio->channels];
        l=vqf_read_frame(sh_audio,&priv->index);
        if(!l) break;
        TvqDecodeFrame(&priv->index, out);
        if (priv->skip_cnt) {
            // Ingnore first two frames, replace them with silence
            priv->skip_cnt--;
            memset(buf, 0, priv->framesize*sh_audio->channels*sh_audio->samplesize);
        } else {
           if (sh_audio->sample_format == AF_FORMAT_S16_NE)
               frtobuf_s16(out, (short *)buf, priv->framesize, sh_audio->channels);
           else
               frtobuf_float(out, (float *)buf, priv->framesize, sh_audio->channels);
        }
        len += priv->framesize*sh_audio->channels*sh_audio->samplesize;
        buf += priv->framesize*sh_audio->channels*sh_audio->samplesize;
    }
    return len;
}