Memory use reduction:
[platform/upstream/libvorbis.git] / lib / block.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
5  * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
7  *                                                                  *
8  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002             *
9  * by the XIPHOPHORUS Company http://www.xiph.org/                  *
10  *                                                                  *
11  ********************************************************************
12
13  function: PCM data vector blocking, windowing and dis/reassembly
14  last mod: $Id: block.c,v 1.56 2002/01/19 04:52:39 xiphmont Exp $
15
16  Handle windowing, overlap-add, etc of the PCM vectors.  This is made
17  more amusing by Vorbis' current two allowed block sizes.
18  
19  ********************************************************************/
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <ogg/ogg.h>
25 #include "vorbis/codec.h"
26 #include "codec_internal.h"
27
28 #include "window.h"
29 #include "mdct.h"
30 #include "lpc.h"
31 #include "registry.h"
32 #include "misc.h"
33
34 static int ilog2(unsigned int v){
35   int ret=0;
36   while(v>1){
37     ret++;
38     v>>=1;
39   }
40   return(ret);
41 }
42
43 /* pcm accumulator examples (not exhaustive):
44
45  <-------------- lW ---------------->
46                    <--------------- W ---------------->
47 :            .....|.....       _______________         |
48 :        .'''     |     '''_---      |       |\        |
49 :.....'''         |_____--- '''......|       | \_______|
50 :.................|__________________|_______|__|______|
51                   |<------ Sl ------>|      > Sr <     |endW
52                   |beginSl           |endSl  |  |endSr   
53                   |beginW            |endlW  |beginSr
54
55
56                       |< lW >|       
57                    <--------------- W ---------------->
58                   |   |  ..  ______________            |
59                   |   | '  `/        |     ---_        |
60                   |___.'___/`.       |         ---_____| 
61                   |_______|__|_______|_________________|
62                   |      >|Sl|<      |<------ Sr ----->|endW
63                   |       |  |endSl  |beginSr          |endSr
64                   |beginW |  |endlW                     
65                   mult[0] |beginSl                     mult[n]
66
67  <-------------- lW ----------------->
68                           |<--W-->|                               
69 :            ..............  ___  |   |                    
70 :        .'''             |`/   \ |   |                       
71 :.....'''                 |/`....\|...|                    
72 :.........................|___|___|___|                  
73                           |Sl |Sr |endW    
74                           |   |   |endSr
75                           |   |beginSr
76                           |   |endSl
77                           |beginSl
78                           |beginW
79 */
80
81 /* block abstraction setup *********************************************/
82
83 #ifndef WORD_ALIGN
84 #define WORD_ALIGN 8
85 #endif
86
87 int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
88   memset(vb,0,sizeof(*vb));
89   vb->vd=v;
90   vb->localalloc=0;
91   vb->localstore=NULL;
92   if(v->analysisp){
93     vorbis_block_internal *vbi=
94       vb->internal=_ogg_calloc(1,sizeof(vorbis_block_internal));
95     oggpack_writeinit(&vb->opb);
96     vbi->ampmax=-9999;
97     vbi->packet_markers=_ogg_malloc(vorbis_bitrate_maxmarkers()*
98                                sizeof(*vbi->packet_markers));
99   }
100   
101   return(0);
102 }
103
104 void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
105   bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
106   if(bytes+vb->localtop>vb->localalloc){
107     /* can't just _ogg_realloc... there are outstanding pointers */
108     if(vb->localstore){
109       struct alloc_chain *link=_ogg_malloc(sizeof(*link));
110       vb->totaluse+=vb->localtop;
111       link->next=vb->reap;
112       link->ptr=vb->localstore;
113       vb->reap=link;
114     }
115     /* highly conservative */
116     vb->localalloc=bytes;
117     vb->localstore=_ogg_malloc(vb->localalloc);
118     vb->localtop=0;
119   }
120   {
121     void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
122     vb->localtop+=bytes;
123     return ret;
124   }
125 }
126
127 /* reap the chain, pull the ripcord */
128 void _vorbis_block_ripcord(vorbis_block *vb){
129   /* reap the chain */
130   struct alloc_chain *reap=vb->reap;
131   while(reap){
132     struct alloc_chain *next=reap->next;
133     _ogg_free(reap->ptr);
134     memset(reap,0,sizeof(*reap));
135     _ogg_free(reap);
136     reap=next;
137   }
138   /* consolidate storage */
139   if(vb->totaluse){
140     vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
141     vb->localalloc+=vb->totaluse;
142     vb->totaluse=0;
143   }
144
145   /* pull the ripcord */
146   vb->localtop=0;
147   vb->reap=NULL;
148 }
149
150 int vorbis_block_clear(vorbis_block *vb){
151   if(vb->vd)
152     if(vb->vd->analysisp)
153       oggpack_writeclear(&vb->opb);
154   _vorbis_block_ripcord(vb);
155   if(vb->localstore)_ogg_free(vb->localstore);
156
157   if(vb->internal){
158     vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
159     if(vbi->packet_markers)_ogg_free(vbi->packet_markers);
160
161     _ogg_free(vb->internal);
162   }
163
164   memset(vb,0,sizeof(*vb));
165   return(0);
166 }
167
168 /* Analysis side code, but directly related to blocking.  Thus it's
169    here and not in analysis.c (which is for analysis transforms only).
170    The init is here because some of it is shared */
171
172 static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
173   int i;
174   codec_setup_info *ci=vi->codec_setup;
175   backend_lookup_state *b=NULL;
176
177   memset(v,0,sizeof(*v));
178   b=v->backend_state=_ogg_calloc(1,sizeof(*b));
179
180   v->vi=vi;
181   b->modebits=ilog2(ci->modes);
182
183   b->transform[0]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
184   b->transform[1]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
185
186   /* MDCT is tranform 0 */
187
188   b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
189   b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
190   mdct_init(b->transform[0][0],ci->blocksizes[0]);
191   mdct_init(b->transform[1][0],ci->blocksizes[1]);
192
193   b->window[0][0][0]=_ogg_calloc(VI_WINDOWB,sizeof(*b->window[0][0][0]));
194   b->window[0][0][1]=b->window[0][0][0];
195   b->window[0][1][0]=b->window[0][0][0];
196   b->window[0][1][1]=b->window[0][0][0];
197   b->window[1][0][0]=_ogg_calloc(VI_WINDOWB,sizeof(*b->window[1][0][0]));
198   b->window[1][0][1]=_ogg_calloc(VI_WINDOWB,sizeof(*b->window[1][0][1]));
199   b->window[1][1][0]=_ogg_calloc(VI_WINDOWB,sizeof(*b->window[1][1][0]));
200   b->window[1][1][1]=_ogg_calloc(VI_WINDOWB,sizeof(*b->window[1][1][1]));
201
202   for(i=0;i<VI_WINDOWB;i++){
203     b->window[0][0][0][i]=
204       _vorbis_window(i,ci->blocksizes[0],ci->blocksizes[0]/2,ci->blocksizes[0]/2);
205     b->window[1][0][0][i]=
206       _vorbis_window(i,ci->blocksizes[1],ci->blocksizes[0]/2,ci->blocksizes[0]/2);
207     b->window[1][0][1][i]=
208       _vorbis_window(i,ci->blocksizes[1],ci->blocksizes[0]/2,ci->blocksizes[1]/2);
209     b->window[1][1][0][i]=
210       _vorbis_window(i,ci->blocksizes[1],ci->blocksizes[1]/2,ci->blocksizes[0]/2);
211     b->window[1][1][1][i]=
212       _vorbis_window(i,ci->blocksizes[1],ci->blocksizes[1]/2,ci->blocksizes[1]/2);
213   }
214
215   if(encp){ /* encode/decode differ here */
216     /* finish the codebooks */
217     b->fullbooks=_ogg_calloc(ci->books,sizeof(*b->fullbooks));
218     for(i=0;i<ci->books;i++)
219       vorbis_book_init_encode(b->fullbooks+i,ci->book_param[i]);
220     v->analysisp=1;
221   }else{
222     /* finish the codebooks */
223     b->fullbooks=_ogg_calloc(ci->books,sizeof(*b->fullbooks));
224     for(i=0;i<ci->books;i++){
225       vorbis_book_init_decode(b->fullbooks+i,ci->book_param[i]);
226       /* decode codebooks are now standalone after init */
227       vorbis_staticbook_destroy(ci->book_param[i]);
228       ci->book_param[i]=NULL;
229     }
230   }
231
232   /* initialize the storage vectors to a decent size greater than the
233      minimum */
234   
235   v->pcm_storage=8192; /* we'll assume later that we have
236                           a minimum of twice the blocksize of
237                           accumulated samples in analysis */
238   v->pcm=_ogg_malloc(vi->channels*sizeof(*v->pcm));
239   v->pcmret=_ogg_malloc(vi->channels*sizeof(*v->pcmret));
240   {
241     int i;
242     for(i=0;i<vi->channels;i++)
243       v->pcm[i]=_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
244   }
245
246   /* all 1 (large block) or 0 (small block) */
247   /* explicitly set for the sake of clarity */
248   v->lW=0; /* previous window size */
249   v->W=0;  /* current window size */
250
251   /* all vector indexes */
252   v->centerW=ci->blocksizes[1]/2;
253
254   v->pcm_current=v->centerW;
255
256   /* initialize all the mapping/backend lookups */
257   b->mode=_ogg_calloc(ci->modes,sizeof(*b->mode));
258   for(i=0;i<ci->modes;i++){
259     int mapnum=ci->mode_param[i]->mapping;
260     int maptype=ci->map_type[mapnum];
261     b->mode[i]=_mapping_P[maptype]->look(v,ci->mode_param[i],
262                                          ci->map_param[mapnum]);
263   }
264
265   return(0);
266 }
267
268 /* arbitrary settings and spec-mandated numbers get filled in here */
269 int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
270   backend_lookup_state *b=NULL;
271
272   _vds_shared_init(v,vi,1);
273   b=v->backend_state;
274   b->psy_g_look=_vp_global_look(vi);
275
276   /* Initialize the envelope state storage */
277   b->ve=_ogg_calloc(1,sizeof(*b->ve));
278   _ve_envelope_init(b->ve,vi);
279
280   vorbis_bitrate_init(vi,&b->bms);
281
282   return(0);
283 }
284
285 void vorbis_dsp_clear(vorbis_dsp_state *v){
286   int i,j,k;
287   if(v){
288     vorbis_info *vi=v->vi;
289     codec_setup_info *ci=(vi?vi->codec_setup:NULL);
290     backend_lookup_state *b=v->backend_state;
291
292     if(b){
293       if(b->window[0][0][0]){
294         for(i=0;i<VI_WINDOWB;i++)
295           if(b->window[0][0][0][i])_ogg_free(b->window[0][0][0][i]);
296         _ogg_free(b->window[0][0][0]);
297         
298         for(j=0;j<2;j++)
299           for(k=0;k<2;k++){
300             for(i=0;i<VI_WINDOWB;i++)
301               if(b->window[1][j][k][i])_ogg_free(b->window[1][j][k][i]);
302             _ogg_free(b->window[1][j][k]);
303           }
304       }
305
306       if(b->ve){
307         _ve_envelope_clear(b->ve);
308         _ogg_free(b->ve);
309       }
310
311       if(b->transform[0]){
312         mdct_clear(b->transform[0][0]);
313         _ogg_free(b->transform[0][0]);
314         _ogg_free(b->transform[0]);
315       }
316       if(b->transform[1]){
317         mdct_clear(b->transform[1][0]);
318         _ogg_free(b->transform[1][0]);
319         _ogg_free(b->transform[1]);
320       }
321       if(b->psy_g_look)_vp_global_free(b->psy_g_look);
322       vorbis_bitrate_clear(&b->bms);
323     }
324     
325     if(v->pcm){
326       for(i=0;i<vi->channels;i++)
327         if(v->pcm[i])_ogg_free(v->pcm[i]);
328       _ogg_free(v->pcm);
329       if(v->pcmret)_ogg_free(v->pcmret);
330     }
331
332     /* free mode lookups; these are actually vorbis_look_mapping structs */
333     if(ci){
334       for(i=0;i<ci->modes;i++){
335         int mapnum=ci->mode_param[i]->mapping;
336         int maptype=ci->map_type[mapnum];
337         if(b && b->mode)_mapping_P[maptype]->free_look(b->mode[i]);
338       }
339       /* free codebooks */
340       for(i=0;i<ci->books;i++)
341         if(b && b->fullbooks)vorbis_book_clear(b->fullbooks+i);
342     }
343
344     if(b){
345       if(b->mode)_ogg_free(b->mode);    
346       if(b->fullbooks)_ogg_free(b->fullbooks);
347       
348       /* free header, header1, header2 */
349       if(b->header)_ogg_free(b->header);
350       if(b->header1)_ogg_free(b->header1);
351       if(b->header2)_ogg_free(b->header2);
352       _ogg_free(b);
353     }
354     
355     memset(v,0,sizeof(*v));
356   }
357 }
358
359 float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
360   int i;
361   vorbis_info *vi=v->vi;
362   backend_lookup_state *b=v->backend_state;
363
364   /* free header, header1, header2 */
365   if(b->header)_ogg_free(b->header);b->header=NULL;
366   if(b->header1)_ogg_free(b->header1);b->header1=NULL;
367   if(b->header2)_ogg_free(b->header2);b->header2=NULL;
368
369   /* Do we have enough storage space for the requested buffer? If not,
370      expand the PCM (and envelope) storage */
371     
372   if(v->pcm_current+vals>=v->pcm_storage){
373     v->pcm_storage=v->pcm_current+vals*2;
374    
375     for(i=0;i<vi->channels;i++){
376       v->pcm[i]=_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
377     }
378   }
379
380   for(i=0;i<vi->channels;i++)
381     v->pcmret[i]=v->pcm[i]+v->pcm_current;
382     
383   return(v->pcmret);
384 }
385
386 static void _preextrapolate_helper(vorbis_dsp_state *v){
387   int i;
388   int order=32;
389   float *lpc=alloca(order*sizeof(*lpc));
390   float *work=alloca(v->pcm_current*sizeof(*work));
391   long j;
392   v->preextrapolate=1;
393
394   if(v->pcm_current-v->centerW>order*2){ /* safety */
395     for(i=0;i<v->vi->channels;i++){
396       /* need to run the extrapolation in reverse! */
397       for(j=0;j<v->pcm_current;j++)
398         work[j]=v->pcm[i][v->pcm_current-j-1];
399       
400       /* prime as above */
401       vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
402       
403       /* run the predictor filter */
404       vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
405                          order,
406                          work+v->pcm_current-v->centerW,
407                          v->centerW);
408
409       for(j=0;j<v->pcm_current;j++)
410         v->pcm[i][v->pcm_current-j-1]=work[j];
411
412     }
413   }
414 }
415
416
417 /* call with val<=0 to set eof */
418
419 int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
420   vorbis_info *vi=v->vi;
421   codec_setup_info *ci=vi->codec_setup;
422   /*backend_lookup_state *b=v->backend_state;*/
423
424   if(vals<=0){
425     int order=32;
426     int i;
427     float *lpc=alloca(order*sizeof(*lpc));
428
429     /* if it wasn't done earlier (very short sample) */
430     if(!v->preextrapolate)
431       _preextrapolate_helper(v);
432
433     /* We're encoding the end of the stream.  Just make sure we have
434        [at least] a full block of zeroes at the end. */
435     /* actually, we don't want zeroes; that could drop a large
436        amplitude off a cliff, creating spread spectrum noise that will
437        suck to encode.  Extrapolate for the sake of cleanliness. */
438
439     vorbis_analysis_buffer(v,ci->blocksizes[1]*2);
440     v->eofflag=v->pcm_current;
441     v->pcm_current+=ci->blocksizes[1]*2;
442
443     for(i=0;i<vi->channels;i++){
444       if(v->eofflag>order*2){
445         /* extrapolate with LPC to fill in */
446         long n;
447
448         /* make a predictor filter */
449         n=v->eofflag;
450         if(n>ci->blocksizes[1])n=ci->blocksizes[1];
451         vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
452
453         /* run the predictor filter */
454         vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
455                            v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
456       }else{
457         /* not enough data to extrapolate (unlikely to happen due to
458            guarding the overlap, but bulletproof in case that
459            assumtion goes away). zeroes will do. */
460         memset(v->pcm[i]+v->eofflag,0,
461                (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
462
463       }
464     }
465   }else{
466
467     if(v->pcm_current+vals>v->pcm_storage)
468       return(OV_EINVAL);
469
470     v->pcm_current+=vals;
471
472     /* we may want to reverse extrapolate the beginning of a stream
473        too... in case we're beginning on a cliff! */
474     /* clumsy, but simple.  It only runs once, so simple is good. */
475     if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
476       _preextrapolate_helper(v);
477
478   }
479   return(0);
480 }
481
482 /* do the deltas, envelope shaping, pre-echo and determine the size of
483    the next block on which to continue analysis */
484 int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
485   int i;
486   vorbis_info *vi=v->vi;
487   codec_setup_info *ci=vi->codec_setup;
488   backend_lookup_state *b=v->backend_state;
489   vorbis_look_psy_global *g=b->psy_g_look;
490   vorbis_info_psy_global *gi=&ci->psy_g_param;
491   long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
492   vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
493
494   /* check to see if we're started... */
495   if(!v->preextrapolate)return(0);
496
497   /* check to see if we're done... */
498   if(v->eofflag==-1)return(0);
499
500   /* By our invariant, we have lW, W and centerW set.  Search for
501      the next boundary so we can determine nW (the next window size)
502      which lets us compute the shape of the current block's window */
503   
504   if(ci->blocksizes[0]<ci->blocksizes[1]){
505     long bp=_ve_envelope_search(v);
506     if(bp==-1)return(0); /* not enough data currently to search for a
507                             full long block */
508     v->nW=bp;
509
510   }else
511     v->nW=0;
512   
513   centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
514
515   {
516     /* center of next block + next block maximum right side. */
517
518     long blockbound=centerNext+ci->blocksizes[v->nW]/2;
519     if(v->pcm_current<blockbound)return(0); /* not enough data yet;
520                                                although this check is
521                                                less strict that the
522                                                _ve_envelope_search,
523                                                the search is not run
524                                                if we only use one
525                                                block size */
526
527
528   }
529   
530   /* fill in the block.  Note that for a short window, lW and nW are *short*
531      regardless of actual settings in the stream */
532
533   _vorbis_block_ripcord(vb);
534   if(v->W){
535     vb->lW=v->lW;
536     vb->W=v->W;
537     vb->nW=v->nW;
538   }else{
539     vb->lW=0;
540     vb->W=v->W;
541     vb->nW=0;
542   }
543
544   if(v->W){
545     if(!v->lW || !v->nW)
546       vbi->blocktype=BLOCKTYPE_TRANSITION;
547     else
548       vbi->blocktype=BLOCKTYPE_LONG;
549   }else{
550     if(_ve_envelope_mark(v))
551       vbi->blocktype=BLOCKTYPE_IMPULSE;
552     else
553       vbi->blocktype=BLOCKTYPE_PADDING;
554   }
555  
556   vb->vd=v;
557   vb->sequence=v->sequence++;
558   vb->granulepos=v->granulepos;
559   vb->pcmend=ci->blocksizes[v->W];
560   
561   /* copy the vectors; this uses the local storage in vb */
562
563   /* this tracks 'strongest peak' for later psychoacoustics */
564   /* moved to the global psy state; clean this mess up */
565   if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
566   g->ampmax=_vp_ampmax_decay(g->ampmax,v);
567   vbi->ampmax=g->ampmax;
568   
569   vb->pcm=_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
570   vbi->pcmdelay=_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
571   for(i=0;i<vi->channels;i++){
572     vbi->pcmdelay[i]=
573       _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
574     memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
575     vb->pcm[i]=vbi->pcmdelay[i]+beginW;
576     
577     /* before we added the delay 
578        vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
579        memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
580     */
581     
582   }
583   
584   /* handle eof detection: eof==0 means that we've not yet received EOF
585                            eof>0  marks the last 'real' sample in pcm[]
586                            eof<0  'no more to do'; doesn't get here */
587
588   if(v->eofflag){
589     if(v->centerW>=v->eofflag){
590       v->eofflag=-1;
591       vb->eofflag=1;
592       return(1);
593     }
594   }
595
596   /* advance storage vectors and clean up */
597   {
598     int new_centerNext=ci->blocksizes[1]/2+gi->delaycache;
599     int movementW=centerNext-new_centerNext;
600
601     if(movementW>0){
602
603       _ve_envelope_shift(b->ve,movementW);
604       v->pcm_current-=movementW;
605       
606       for(i=0;i<vi->channels;i++)
607         memmove(v->pcm[i],v->pcm[i]+movementW,
608                 v->pcm_current*sizeof(*v->pcm[i]));
609       
610       
611       v->lW=v->W;
612       v->W=v->nW;
613       v->centerW=new_centerNext;
614       
615       if(v->eofflag){
616         v->eofflag-=movementW;
617         /* do not add padding to end of stream! */
618         if(v->centerW>=v->eofflag){
619           v->granulepos+=movementW-(v->centerW-v->eofflag);
620         }else{
621           v->granulepos+=movementW;
622         }
623       }else{
624         v->granulepos+=movementW;
625       }
626     }
627   }
628
629   /* done */
630   return(1);
631 }
632
633 int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
634   _vds_shared_init(v,vi,0);
635
636   v->pcm_returned=-1;
637   v->granulepos=-1;
638   v->sequence=-1;
639
640   return(0);
641 }
642
643 /* Unlike in analysis, the window is only partially applied for each
644    block.  The time domain envelope is not yet handled at the point of
645    calling (as it relies on the previous block). */
646
647 int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
648   vorbis_info *vi=v->vi;
649   codec_setup_info *ci=vi->codec_setup;
650
651   /* Shift out any PCM that we returned previously */
652   /* centerW is currently the center of the last block added */
653
654   if(v->centerW>ci->blocksizes[1]/2 &&
655   /* Quick additional hack; to avoid *alot* of shifts, use an
656      oversized buffer.  This increases memory usage, but doesn't make
657      much difference wrt L1/L2 cache pressure. */
658      v->pcm_returned>8192){
659
660     /* don't shift too much; we need to have a minimum PCM buffer of
661        1/2 long block */
662
663     int shiftPCM=v->centerW-ci->blocksizes[1]/2;
664     shiftPCM=(v->pcm_returned<shiftPCM?v->pcm_returned:shiftPCM);
665
666     v->pcm_current-=shiftPCM;
667     v->centerW-=shiftPCM;
668     v->pcm_returned-=shiftPCM;
669     
670     if(shiftPCM){
671       int i;
672       for(i=0;i<vi->channels;i++)
673         memmove(v->pcm[i],v->pcm[i]+shiftPCM,
674                 v->pcm_current*sizeof(*v->pcm[i]));
675     }
676   }
677
678   v->lW=v->W;
679   v->W=vb->W;
680   v->nW=-1;
681
682   v->glue_bits+=vb->glue_bits;
683   v->time_bits+=vb->time_bits;
684   v->floor_bits+=vb->floor_bits;
685   v->res_bits+=vb->res_bits;
686
687   if(v->sequence+1 != vb->sequence)v->granulepos=-1; /* out of sequence;
688                                                      lose count */
689
690   v->sequence=vb->sequence;
691
692   {
693     int sizeW=ci->blocksizes[v->W];
694     int centerW=v->centerW+ci->blocksizes[v->lW]/4+sizeW/4;
695     int beginW=centerW-sizeW/2;
696     int endW=beginW+sizeW;
697     int beginSl;
698     int endSl;
699     int i,j;
700
701     /* Do we have enough PCM/mult storage for the block? */
702     if(endW>v->pcm_storage){
703       /* expand the storage */
704       v->pcm_storage=endW+ci->blocksizes[1];
705    
706       for(i=0;i<vi->channels;i++)
707         v->pcm[i]=_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i])); 
708     }
709
710     /* overlap/add PCM */
711
712     switch((int)v->W){
713     case 0:
714       beginSl=0;
715       endSl=ci->blocksizes[0]/2;
716       break;
717     case 1:
718       beginSl=ci->blocksizes[1]/4-ci->blocksizes[v->lW]/4;
719       endSl=beginSl+ci->blocksizes[v->lW]/2;
720       break;
721     default:
722       return(-1);
723     }
724
725     for(j=0;j<vi->channels;j++){
726       float *pcm=v->pcm[j]+beginW;
727       float *p=vb->pcm[j];
728
729       /* the overlap/add section */
730       for(i=beginSl;i<endSl;i++)
731         pcm[i]+=p[i];
732       /* the remaining section */
733       for(;i<sizeW;i++)
734         pcm[i]=p[i];
735
736     }
737
738     /* deal with initial packet state; we do this using the explicit
739        pcm_returned==-1 flag otherwise we're sensitive to first block
740        being short or long */
741
742     if(v->pcm_returned==-1)
743       v->pcm_returned=centerW;
744
745     /* track the frame number... This is for convenience, but also
746        making sure our last packet doesn't end with added padding.  If
747        the last packet is partial, the number of samples we'll have to
748        return will be past the vb->granulepos.
749        
750        This is not foolproof!  It will be confused if we begin
751        decoding at the last page after a seek or hole.  In that case,
752        we don't have a starting point to judge where the last frame
753        is.  For this reason, vorbisfile will always try to make sure
754        it reads the last two marked pages in proper sequence */
755
756     if(v->granulepos==-1)
757       if(vb->granulepos==-1){
758         v->granulepos=0;
759       }else{
760         v->granulepos=vb->granulepos;
761       }
762     else{
763       v->granulepos+=(centerW-v->centerW);
764       if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
765
766         if(v->granulepos>vb->granulepos){
767           long extra=v->granulepos-vb->granulepos;
768
769           if(vb->eofflag){
770             /* partial last frame.  Strip the extra samples off */
771             centerW-=extra;
772           }else if(vb->sequence == 1){
773             /* ^^^ argh, this can be 1 from seeking! */
774
775
776             /* partial first frame.  Discard extra leading samples */
777             v->pcm_returned+=extra;
778             if(v->pcm_returned>centerW)v->pcm_returned=centerW;
779             
780           }
781           
782         }/* else{ Shouldn't happen *unless* the bitstream is out of
783             spec.  Either way, believe the bitstream } */
784         v->granulepos=vb->granulepos;
785       }
786     }
787
788     /* Update, cleanup */
789
790     v->centerW=centerW;
791     v->pcm_current=endW;
792
793     if(vb->eofflag)v->eofflag=1;
794   }
795
796   return(0);
797 }
798
799 /* pcm==NULL indicates we just want the pending samples, no more */
800 int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
801   vorbis_info *vi=v->vi;
802   if(v->pcm_returned>-1 && v->pcm_returned<v->centerW){
803     if(pcm){
804       int i;
805       for(i=0;i<vi->channels;i++)
806         v->pcmret[i]=v->pcm[i]+v->pcm_returned;
807       *pcm=v->pcmret;
808     }
809     return(v->centerW-v->pcm_returned);
810   }
811   return(0);
812 }
813
814 int vorbis_synthesis_read(vorbis_dsp_state *v,int bytes){
815   if(bytes && v->pcm_returned+bytes>v->centerW)return(OV_EINVAL);
816   v->pcm_returned+=bytes;
817   return(0);
818 }
819