summaryrefslogtreecommitdiffstats
path: root/apps/codecs/libtremor/codebook.c
blob: f86b762f3c39cb6f803b8f23a8a3f0bd9fd97a3f (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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/********************************************************************
 *                                                                  *
 * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE.   *
 *                                                                  *
 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
 *                                                                  *
 * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002    *
 * BY THE Xiph.Org FOUNDATION http://www.xiph.org/                  *
 *                                                                  *
 ********************************************************************

 function: basic codebook pack/unpack/code/decode operations

 ********************************************************************/

#include "config-tremor.h"
#include <string.h>
#include <math.h>
#include "ogg.h"
#include "ivorbiscodec.h"
#include "codebook.h"
#include "misc.h"
#include "os.h"

/* unpacks a codebook from the packet buffer into the codebook struct,
   readies the codebook auxiliary structures for decode *************/
int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  long i,j;
  memset(s,0,sizeof(*s));

  /* make sure alignment is correct */
  if(oggpack_read(opb,24)!=0x564342)goto _eofout;

  /* first the basic parameters */
  s->dim=oggpack_read(opb,16);
  s->entries=oggpack_read(opb,24);
  if(s->entries==-1)goto _eofout;

  if(_ilog(s->dim)+_ilog(s->entries)>24)goto _eofout;

  /* codeword ordering.... length ordered or unordered? */
  switch((int)oggpack_read(opb,1)){
  case 0:
    /* unordered */
    s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);

    /* allocated but unused entries? */
    if(oggpack_read(opb,1)){
      /* yes, unused entries */

      for(i=0;i<s->entries;i++){
        if(oggpack_read(opb,1)){
          long num=oggpack_read(opb,5);
          if(num==-1)goto _eofout;
          s->lengthlist[i]=num+1;
        }else
          s->lengthlist[i]=0;
      }
    }else{
      /* all entries used; no tagging */
      for(i=0;i<s->entries;i++){
        long num=oggpack_read(opb,5);
        if(num==-1)goto _eofout;
        s->lengthlist[i]=num+1;
      }
    }
    
    break;
  case 1:
    /* ordered */
    {
      long length=oggpack_read(opb,5)+1;
      s->lengthlist=(long *)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);

      for(i=0;i<s->entries;){
        long num=oggpack_read(opb,_ilog(s->entries-i));
        if(num==-1)goto _eofout;
        for(j=0;j<num && i<s->entries;j++,i++)
          s->lengthlist[i]=length;
        length++;
      }
    }
    break;
  default:
    /* EOF */
    return(-1);
  }
  
  /* Do we have a mapping to unpack? */
  switch((s->maptype=oggpack_read(opb,4))){
  case 0:
    /* no mapping */
    break;
  case 1: case 2:
    /* implicitly populated value mapping */
    /* explicitly populated value mapping */

    s->q_min=oggpack_read(opb,32);
    s->q_delta=oggpack_read(opb,32);
    s->q_quant=oggpack_read(opb,4)+1;
    s->q_sequencep=oggpack_read(opb,1);

    {
      int quantvals=0;
      switch(s->maptype){
      case 1:
        quantvals=(s->dim==0?0:_book_maptype1_quantvals(s));
        break;
      case 2:
        quantvals=s->entries*s->dim;
        break;
      }
      
      /* quantized values */
      s->quantlist=(long *)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
      for(i=0;i<quantvals;i++)
        s->quantlist[i]=oggpack_read(opb,s->q_quant);
      
      if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
    }
    break;
  default:
    goto _errout;
  }

  /* all set */
  return(0);
  
 _errout:
 _eofout:
  vorbis_staticbook_clear(s);
  return(-1); 
}

/* the 'eliminate the decode tree' optimization actually requires the
   codewords to be MSb first, not LSb.  This is an annoying inelegancy
   (and one of the first places where carefully thought out design
   turned out to be wrong; Vorbis II and future Ogg codecs should go
   to an MSb bitpacker), but not actually the huge hit it appears to
   be.  The first-stage decode table catches most words so that
   bitreverse is not in the main execution path. */

static inline ogg_uint32_t bitreverse(register ogg_uint32_t x)
{
  unsigned tmp, ret;
#ifdef _ARM_ASSEM_
#if ARM_ARCH >= 6
  unsigned mask = 0x0f0f0f0f;
#else
  unsigned mask = 0x00ff00ff;
#endif
  asm (
#if ARM_ARCH >= 6
    "rev     %[r], %[x]              \n"  /* swap halfwords and bytes */
    "and     %[t], %[m], %[r]        \n"  /* Sequence is one instruction */
    "eor     %[r], %[t], %[r]        \n"  /*   longer than on <= ARMv5, but */
    "mov     %[t], %[t], lsl #4      \n"  /*   interlock free */
    "orr     %[r], %[t], %[r], lsr #4\n"  /* nibbles swapped */
    "eor     %[m], %[m], %[m], lsl #2\n"  /* mask = 0x33333333 */
    "and     %[t], %[m], %[r]        \n"
    "eor     %[r], %[t], %[r]        \n"
    "mov     %[t], %[t], lsl #2      \n"
    "orr     %[r], %[t], %[r], lsr #2\n"  /* dibits swapped */
    "eor     %[m], %[m], %[m], lsl #1\n"  /* mask = 0x55555555 */
    "and     %[t], %[m], %[r]        \n"
    "eor     %[r], %[t], %[r]        \n"
    "mov     %[t], %[t], lsl #1      \n"
    "orr     %[r], %[t], %[r], lsr #1\n"  /* bits swapped */
#else /* ARM_ARCH <= 5 */
    "mov     %[r], %[x], ror #16     \n"  /* swap halfwords */
    "and     %[t], %[m], %[r], lsr #8\n"
    "eor     %[r], %[r], %[t], lsl #8\n"
    "orr     %[r], %[t], %[r], lsl #8\n"  /* bytes swapped */
    "eor     %[m], %[m], %[m], lsl #4\n"  /* mask = 0x0f0f0f0f */
    "and     %[t], %[m], %[r], lsr #4\n"
    "eor     %[r], %[r], %[t], lsl #4\n"
    "orr     %[r], %[t], %[r], lsl #4\n"  /* nibbles swapped */
    "eor     %[m], %[m], %[m], lsl #2\n"  /* mask = 0x33333333 */
    "and     %[t], %[m], %[r], lsr #2\n"
    "eor     %[r], %[r], %[t], lsl #2\n"
    "orr     %[r], %[t], %[r], lsl #2\n"  /* dibits swapped */
    "eor     %[m], %[m], %[m], lsl #1\n"  /* mask = 0x55555555 */
    "and     %[t], %[m], %[r], lsr #1\n"
    "eor     %[r], %[r], %[t], lsl #1\n"
    "orr     %[r], %[t], %[r], lsl #1\n"  /* bits swapped */
#endif /* ARM_ARCH */
    : /* outputs */
    [m]"+r"(mask),
    [r]"=r"(ret),
    [t]"=r"(tmp)
    : /* inputs */
    [x]"r"(x)
  );
#else /* !_ARM_ASSEM_ */

#ifdef CPU_COLDFIRE
  ret = x;
  asm ("swap  %[r]" : [r] "+d" (ret));   /* swap halfwords */
#else
  ret = (x>>16) | (x<<16);
#endif
  tmp = ret & 0x00ff00ff;
  ret ^= tmp;
  ret = (ret >> 8) | (tmp << 8);         /* bytes swapped */
  tmp = ret & 0x0f0f0f0f;
  ret ^= tmp;
  ret = (ret >> 4) | (tmp << 4);         /* 4-bit units swapped */
  tmp = ret & 0x33333333;
  ret ^= tmp;
  ret = (ret >> 2) | (tmp << 2);         /* 2-bit units swapped */
  tmp = ret & 0x55555555;
  ret ^= tmp;
  ret = (ret >> 1) | (tmp << 1);         /* done */
#endif /* !_ARM_ASSEM_ */
  return ret;
}

static inline long bisect_codelist(long lo, long hi, ogg_uint32_t cache,
                                   const ogg_uint32_t *codelist)
{
  ogg_uint32_t testword=bitreverse(cache);
  long p;
  while(LIKELY(p = (hi-lo) >> 1) > 0){
    if(codelist[lo+p] > testword)
      hi -= p;
    else
      lo += p;
  }
  return lo;
}

STIN long decode_packed_entry_number(codebook *book, 
                                              oggpack_buffer *b){
  int  read=book->dec_maxlength;
  long lo,hi;
  long lok = oggpack_look(b,book->dec_firsttablen);
 
  if (LIKELY(lok >= 0)) {
    ogg_int32_t entry = book->dec_firsttable[lok];
    if(UNLIKELY(entry < 0)){
      lo=(entry>>15)&0x7fff;
      hi=book->used_entries-(entry&0x7fff);
    }else{
      oggpack_adv(b, book->dec_codelengths[entry-1]);
      return(entry-1);
    }
  }else{
    lo=0;
    hi=book->used_entries;
  }

  lok = oggpack_look(b, read);

  while(lok<0 && read>1)
    lok = oggpack_look(b, --read);

  if(lok<0){
    oggpack_adv(b,1); /* force eop */
    return -1;
  }

  /* bisect search for the codeword in the ordered list */
  {
    lo = bisect_codelist(lo, hi, lok, book->codelist);

    if(book->dec_codelengths[lo]<=read){
      oggpack_adv(b, book->dec_codelengths[lo]);
      return(lo);
    }
  }
  
  oggpack_adv(b, read+1);
  return(-1);
}

static long decode_packed_block(codebook *book, oggpack_buffer *b,
                                long *buf, int n){
  long *bufptr = buf;
  long *bufend = buf + n;

  while (bufptr<bufend) {
    if(b->endbyte < b->storage - 8) {
      ogg_uint32_t *ptr;
      unsigned long bit, bitend;
      unsigned long adr;
      ogg_uint32_t cache = 0;
      int cachesize = 0;
      const unsigned int cachemask = (1<<book->dec_firsttablen)-1;
      const int          book_dec_maxlength = book->dec_maxlength;
      const ogg_uint32_t *book_dec_firsttable = book->dec_firsttable;
      const long         book_used_entries = book->used_entries;
      const ogg_uint32_t *book_codelist = book->codelist;
      const char         *book_dec_codelengths = book->dec_codelengths;

      adr = (unsigned long)b->ptr;
      bit = (adr&3)*8+b->endbit;
      ptr = (ogg_uint32_t*)(adr&~3);
      bitend = ((adr&3)+(b->storage-b->endbyte))*8;
      while (bufptr<bufend){
        if (UNLIKELY(cachesize<book_dec_maxlength)) {
          if (bit-cachesize+32>=bitend)
            break;
          bit-=cachesize;
          cache = letoh32(ptr[bit>>5]);
          if (bit&31) {
            cache >>= (bit&31);
            cache |= letoh32(ptr[(bit>>5)+1]) << (32-(bit&31));
          }
          cachesize=32;
          bit+=32;
        }

        ogg_int32_t entry = book_dec_firsttable[cache&cachemask];
        if(UNLIKELY(entry < 0)){
          const long lo = (entry>>15)&0x7fff, hi = book_used_entries-(entry&0x7fff);
          entry = bisect_codelist(lo, hi, cache, book_codelist);
        }else
          entry--;

        *bufptr++ = entry;
        int l = book_dec_codelengths[entry];
        cachesize -= l;
        cache >>= l;
      }

      adr=(unsigned long)b->ptr;
      bit-=(adr&3)*8+cachesize;
      b->endbyte+=bit/8;
      b->ptr+=bit/8;
      b->endbit=bit&7;
    } else {
      long r = decode_packed_entry_number(book, b);
      if (r == -1) return bufptr-buf;
      *bufptr++ = r;
    }
  }
  return n;
}

/* Decode side is specced and easier, because we don't need to find
   matches using different criteria; we simply read and map.  There are
   two things we need to do 'depending':
   
   We may need to support interleave.  We don't really, but it's
   convenient to do it here rather than rebuild the vector later.

   Cascades may be additive or multiplicitive; this is not inherent in
   the codebook, but set in the code using the codebook.  Like
   interleaving, it's easiest to do it here.  
   addmul==0 -> declarative (set the value)
   addmul==1 -> additive
   addmul==2 -> multiplicitive */

/* returns the [original, not compacted] entry number or -1 on eof *********/
long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  if(book->used_entries>0){
    long packed_entry=decode_packed_entry_number(book,b);
    if(packed_entry>=0)
      return(book->dec_index[packed_entry]);
  }

  /* if there's no dec_index, the codebook unpacking isn't collapsed */
  return(-1);
}

/* returns 0 on OK or -1 on eof *************************************/
long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
                              oggpack_buffer *b,int n,int point){
  if(book->used_entries>0){  
    int step=n/book->dim;
    long *entry = (long *)alloca(sizeof(*entry)*step);
    ogg_int32_t **t = (ogg_int32_t **)alloca(sizeof(*t)*step);
    int i,j,o;
    int shift=point-book->binarypoint;
    
    if(shift>=0){
      for (i = 0; i < step; i++) {
        entry[i]=decode_packed_entry_number(book,b);
        if(entry[i]==-1)return(-1);
        t[i] = book->valuelist+entry[i]*book->dim;
      }
      for(i=0,o=0;i<book->dim;i++,o+=step)
        for (j=0;j<step;j++)
          a[o+j]+=t[j][i]>>shift;
    }else{
      for (i = 0; i < step; i++) {
        entry[i]=decode_packed_entry_number(book,b);
        if(entry[i]==-1)return(-1);
        t[i] = book->valuelist+entry[i]*book->dim;
      }
      for(i=0,o=0;i<book->dim;i++,o+=step)
        for (j=0;j<step;j++)
          a[o+j]+=t[j][i]<<-shift;
    }
  }
  return(0);
}

long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a,
                             oggpack_buffer *b,int n,int point){
  if(book->used_entries>0){
    int i,j,entry;
    ogg_int32_t *t;
    int shift=point-book->binarypoint;
    
    if(shift>=0){
      for(i=0;i<n;){
        entry = decode_packed_entry_number(book,b);
        if(entry==-1)return(-1);
        t     = book->valuelist+entry*book->dim;
        for (j=0;j<book->dim;)
          a[i++]+=t[j++]>>shift;
      }
    }else{
      shift = -shift;
      for(i=0;i<n;){
        entry = decode_packed_entry_number(book,b);
        if(entry==-1)return(-1);
        t     = book->valuelist+entry*book->dim;
        for (j=0;j<book->dim;)
          a[i++]+=t[j++]<<shift;
      }
    }
  }
  return(0);
}

long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a,
                             oggpack_buffer *b,int n,int point){
  if(book->used_entries>0){
    int i,j,entry;
    ogg_int32_t *t;
    int shift=point-book->binarypoint;
    
    if(shift>=0){
      
      for(i=0;i<n;){
        entry = decode_packed_entry_number(book,b);
        if(entry==-1)return(-1);
        t     = book->valuelist+entry*book->dim;
        for (j=0;j<book->dim;){
          a[i++]=t[j++]>>shift;
        }
      }
    }else{
      shift = -shift;
      for(i=0;i<n;){
        entry = decode_packed_entry_number(book,b);
        if(entry==-1)return(-1);
        t     = book->valuelist+entry*book->dim;
        for (j=0;j<book->dim;){
          a[i++]=t[j++]<<shift;
        }
      }
    }
  }else{

    int i,j;
    for(i=0;i<n;){
      for (j=0;j<book->dim;){
        a[i++]=0;
      }
    }
  }
  return(0);
}

static long vorbis_book_decodevv_add_2ch_even(codebook *book,ogg_int32_t **a,
                                              long offset,oggpack_buffer *b,
                                              unsigned int n,int point){
  long k,chunk,read;
  int shift=point-book->binarypoint;
  long entries[32];
  ogg_int32_t *p0 = &(a[0][offset]);
  ogg_int32_t *p1 = &(a[1][offset]);
  const unsigned long dim = book->dim;
  const ogg_int32_t * const vlist = book->valuelist;

  if(shift>=0){
    while(n>0){
      chunk=32;
      if (16*dim>n)
        chunk=(n*2-1)/dim + 1;
      read = decode_packed_block(book,b,entries,chunk);
      for(k=0;k<read;k++){
        const ogg_int32_t *t = vlist+entries[k]*dim;
        const ogg_int32_t *u = t+dim;
        do{
          *p0++ += *t++>>shift;
          *p1++ += *t++>>shift;
        }while(t<u);
      }
      if (read<chunk)return-1;
      n -= read*dim/2;
    }
  }else{
    shift = -shift;
    while(n>0){
      chunk=32;
      if (16*dim>n)
        chunk=(n*2-1)/dim + 1;
      read = decode_packed_block(book,b,entries,chunk);
      for(k=0;k<read;k++){
        const ogg_int32_t *t = vlist+entries[k]*dim;
        const ogg_int32_t *u = t+dim;
        do{
          *p0++ += *t++<<shift;
          *p1++ += *t++<<shift;
        }while(t<u);
      }
      if (read<chunk)return-1;
      n -= read*dim/2;
    }
  }
  return(0);
}

long vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a,
                              long offset,int ch,
                              oggpack_buffer *b,int n,int point){
  if(LIKELY(book->used_entries>0)){
    long i,j,k,chunk,read;
    int chptr=0;
    int shift=point-book->binarypoint;
    long entries[32];

    if (!(book->dim&1) && ch==2)
      return vorbis_book_decodevv_add_2ch_even(book,a,offset,b,n,point);

    if(shift>=0){
    
      for(i=offset;i<offset+n;){
        chunk=32;
        if (chunk*book->dim>(offset+n-i)*ch)
          chunk=((offset+n-i)*ch+book->dim-1)/book->dim;
        read = decode_packed_block(book,b,entries,chunk);
        for(k=0;k<read;k++){
          const ogg_int32_t *t = book->valuelist+entries[k]*book->dim;
          for (j=0;j<book->dim;j++){
            a[chptr++][i]+=t[j]>>shift;
            if(chptr==ch){
              chptr=0;
              i++;
            }
          }
        }
        if (read<chunk)return-1;
      }
    }else{
      shift = -shift;
      for(i=offset;i<offset+n;){
        chunk=32;
        if (chunk*book->dim>(offset+n-i)*ch)
          chunk=((offset+n-i)*ch+book->dim-1)/book->dim;
        read = decode_packed_block(book,b,entries,chunk);
        for(k=0;k<read;k++){
          const ogg_int32_t *t = book->valuelist+entries[k]*book->dim;
          for (j=0;j<book->dim;j++){
            a[chptr++][i]+=t[j]<<shift;
            if(chptr==ch){
              chptr=0;
              i++;
            }
          }
        }
        if (read<chunk)return-1;
      }
    }
  }
  return(0);
}