Complete crosslap API for Vorbisfile
[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.72 2003/03/06 22:05:26 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   if(v)--v;
37   while(v){
38     ret++;
39     v>>=1;
40   }
41   return(ret);
42 }
43
44 /* pcm accumulator examples (not exhaustive):
45
46  <-------------- lW ---------------->
47                    <--------------- W ---------------->
48 :            .....|.....       _______________         |
49 :        .'''     |     '''_---      |       |\        |
50 :.....'''         |_____--- '''......|       | \_______|
51 :.................|__________________|_______|__|______|
52                   |<------ Sl ------>|      > Sr <     |endW
53                   |beginSl           |endSl  |  |endSr   
54                   |beginW            |endlW  |beginSr
55
56
57                       |< lW >|       
58                    <--------------- W ---------------->
59                   |   |  ..  ______________            |
60                   |   | '  `/        |     ---_        |
61                   |___.'___/`.       |         ---_____| 
62                   |_______|__|_______|_________________|
63                   |      >|Sl|<      |<------ Sr ----->|endW
64                   |       |  |endSl  |beginSr          |endSr
65                   |beginW |  |endlW                     
66                   mult[0] |beginSl                     mult[n]
67
68  <-------------- lW ----------------->
69                           |<--W-->|                               
70 :            ..............  ___  |   |                    
71 :        .'''             |`/   \ |   |                       
72 :.....'''                 |/`....\|...|                    
73 :.........................|___|___|___|                  
74                           |Sl |Sr |endW    
75                           |   |   |endSr
76                           |   |beginSr
77                           |   |endSl
78                           |beginSl
79                           |beginW
80 */
81
82 /* block abstraction setup *********************************************/
83
84 #ifndef WORD_ALIGN
85 #define WORD_ALIGN 8
86 #endif
87
88 int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
89   memset(vb,0,sizeof(*vb));
90   vb->vd=v;
91   vb->localalloc=0;
92   vb->localstore=NULL;
93   if(v->analysisp){
94     vorbis_block_internal *vbi=
95       vb->internal=_ogg_calloc(1,sizeof(vorbis_block_internal));
96     oggpack_writeinit(&vb->opb);
97     vbi->ampmax=-9999;
98   }
99   
100   return(0);
101 }
102
103 void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
104   bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
105   if(bytes+vb->localtop>vb->localalloc){
106     /* can't just _ogg_realloc... there are outstanding pointers */
107     if(vb->localstore){
108       struct alloc_chain *link=_ogg_malloc(sizeof(*link));
109       vb->totaluse+=vb->localtop;
110       link->next=vb->reap;
111       link->ptr=vb->localstore;
112       vb->reap=link;
113     }
114     /* highly conservative */
115     vb->localalloc=bytes;
116     vb->localstore=_ogg_malloc(vb->localalloc);
117     vb->localtop=0;
118   }
119   {
120     void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
121     vb->localtop+=bytes;
122     return ret;
123   }
124 }
125
126 /* reap the chain, pull the ripcord */
127 void _vorbis_block_ripcord(vorbis_block *vb){
128   /* reap the chain */
129   struct alloc_chain *reap=vb->reap;
130   while(reap){
131     struct alloc_chain *next=reap->next;
132     _ogg_free(reap->ptr);
133     memset(reap,0,sizeof(*reap));
134     _ogg_free(reap);
135     reap=next;
136   }
137   /* consolidate storage */
138   if(vb->totaluse){
139     vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
140     vb->localalloc+=vb->totaluse;
141     vb->totaluse=0;
142   }
143
144   /* pull the ripcord */
145   vb->localtop=0;
146   vb->reap=NULL;
147 }
148
149 int vorbis_block_clear(vorbis_block *vb){
150   if(vb->vd)
151     if(vb->vd->analysisp)
152       oggpack_writeclear(&vb->opb);
153   _vorbis_block_ripcord(vb);
154   if(vb->localstore)_ogg_free(vb->localstore);
155
156   if(vb->internal)
157     _ogg_free(vb->internal);
158
159   memset(vb,0,sizeof(*vb));
160   return(0);
161 }
162
163 /* Analysis side code, but directly related to blocking.  Thus it's
164    here and not in analysis.c (which is for analysis transforms only).
165    The init is here because some of it is shared */
166
167 static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
168   int i;
169   codec_setup_info *ci=vi->codec_setup;
170   private_state *b=NULL;
171
172   memset(v,0,sizeof(*v));
173   b=v->backend_state=_ogg_calloc(1,sizeof(*b));
174
175   v->vi=vi;
176   b->modebits=ilog2(ci->modes);
177
178   b->transform[0]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
179   b->transform[1]=_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
180
181   /* MDCT is tranform 0 */
182
183   b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
184   b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
185   mdct_init(b->transform[0][0],ci->blocksizes[0]);
186   mdct_init(b->transform[1][0],ci->blocksizes[1]);
187
188   /* Vorbis I uses only window type 0 */
189   b->window[0]=_vorbis_window_get(0,ci->blocksizes[0]/2);
190   b->window[1]=_vorbis_window_get(0,ci->blocksizes[1]/2);
191
192   if(encp){ /* encode/decode differ here */
193
194     /* analysis always needs an fft */
195     drft_init(&b->fft_look[0],ci->blocksizes[0]);
196     drft_init(&b->fft_look[1],ci->blocksizes[1]);
197
198     /* finish the codebooks */
199     if(!ci->fullbooks){
200       ci->fullbooks=_ogg_calloc(ci->books,sizeof(*ci->fullbooks));
201       for(i=0;i<ci->books;i++)
202         vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
203     }
204
205     b->psy=_ogg_calloc(ci->psys,sizeof(*b->psy));
206     for(i=0;i<ci->psys;i++){
207       _vp_psy_init(b->psy+i,
208                    ci->psy_param[i],
209                    &ci->psy_g_param,
210                    ci->blocksizes[ci->psy_param[i]->blockflag]/2,
211                    vi->rate);
212     }
213
214     v->analysisp=1;
215   }else{
216     /* finish the codebooks */
217     if(!ci->fullbooks){
218       ci->fullbooks=_ogg_calloc(ci->books,sizeof(*ci->fullbooks));
219       for(i=0;i<ci->books;i++){
220         vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
221         /* decode codebooks are now standalone after init */
222         vorbis_staticbook_destroy(ci->book_param[i]);
223         ci->book_param[i]=NULL;
224       }
225     }
226   }
227
228   /* initialize the storage vectors. blocksize[1] is small for encode,
229      but the correct size for decode */
230   v->pcm_storage=ci->blocksizes[1];
231   v->pcm=_ogg_malloc(vi->channels*sizeof(*v->pcm));
232   v->pcmret=_ogg_malloc(vi->channels*sizeof(*v->pcmret));
233   {
234     int i;
235     for(i=0;i<vi->channels;i++)
236       v->pcm[i]=_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
237   }
238
239   /* all 1 (large block) or 0 (small block) */
240   /* explicitly set for the sake of clarity */
241   v->lW=0; /* previous window size */
242   v->W=0;  /* current window size */
243
244   /* all vector indexes */
245   v->centerW=ci->blocksizes[1]/2;
246
247   v->pcm_current=v->centerW;
248
249   /* initialize all the backend lookups */
250   b->flr=_ogg_calloc(ci->floors,sizeof(*b->flr));
251   b->residue=_ogg_calloc(ci->residues,sizeof(*b->residue));
252
253   for(i=0;i<ci->floors;i++)
254     b->flr[i]=_floor_P[ci->floor_type[i]]->
255       look(v,ci->floor_param[i]);
256
257   for(i=0;i<ci->residues;i++)
258     b->residue[i]=_residue_P[ci->residue_type[i]]->
259       look(v,ci->residue_param[i]);    
260
261   return(0);
262 }
263
264 /* arbitrary settings and spec-mandated numbers get filled in here */
265 int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
266   private_state *b=NULL;
267
268   _vds_shared_init(v,vi,1);
269   b=v->backend_state;
270   b->psy_g_look=_vp_global_look(vi);
271
272   /* Initialize the envelope state storage */
273   b->ve=_ogg_calloc(1,sizeof(*b->ve));
274   _ve_envelope_init(b->ve,vi);
275
276   vorbis_bitrate_init(vi,&b->bms);
277
278   return(0);
279 }
280
281 void vorbis_dsp_clear(vorbis_dsp_state *v){
282   int i;
283   if(v){
284     vorbis_info *vi=v->vi;
285     codec_setup_info *ci=(vi?vi->codec_setup:NULL);
286     private_state *b=v->backend_state;
287
288     if(b){
289         
290       if(b->ve){
291         _ve_envelope_clear(b->ve);
292         _ogg_free(b->ve);
293       }
294
295       if(b->transform[0]){
296         mdct_clear(b->transform[0][0]);
297         _ogg_free(b->transform[0][0]);
298         _ogg_free(b->transform[0]);
299       }
300       if(b->transform[1]){
301         mdct_clear(b->transform[1][0]);
302         _ogg_free(b->transform[1][0]);
303         _ogg_free(b->transform[1]);
304       }
305
306       if(b->flr){
307         for(i=0;i<ci->floors;i++)
308           _floor_P[ci->floor_type[i]]->
309             free_look(b->flr[i]);
310         _ogg_free(b->flr);
311       }
312       if(b->residue){
313         for(i=0;i<ci->residues;i++)
314           _residue_P[ci->residue_type[i]]->
315             free_look(b->residue[i]);
316         _ogg_free(b->residue);
317       }
318       if(b->psy){
319         for(i=0;i<ci->psys;i++)
320           _vp_psy_clear(b->psy+i);
321         _ogg_free(b->psy);
322       }
323
324       if(b->psy_g_look)_vp_global_free(b->psy_g_look);
325       vorbis_bitrate_clear(&b->bms);
326
327       drft_clear(&b->fft_look[0]);
328       drft_clear(&b->fft_look[1]);
329
330     }
331     
332     if(v->pcm){
333       for(i=0;i<vi->channels;i++)
334         if(v->pcm[i])_ogg_free(v->pcm[i]);
335       _ogg_free(v->pcm);
336       if(v->pcmret)_ogg_free(v->pcmret);
337     }
338
339     if(b){
340       /* free header, header1, header2 */
341       if(b->header)_ogg_free(b->header);
342       if(b->header1)_ogg_free(b->header1);
343       if(b->header2)_ogg_free(b->header2);
344       _ogg_free(b);
345     }
346     
347     memset(v,0,sizeof(*v));
348   }
349 }
350
351 float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
352   int i;
353   vorbis_info *vi=v->vi;
354   private_state *b=v->backend_state;
355
356   /* free header, header1, header2 */
357   if(b->header)_ogg_free(b->header);b->header=NULL;
358   if(b->header1)_ogg_free(b->header1);b->header1=NULL;
359   if(b->header2)_ogg_free(b->header2);b->header2=NULL;
360
361   /* Do we have enough storage space for the requested buffer? If not,
362      expand the PCM (and envelope) storage */
363     
364   if(v->pcm_current+vals>=v->pcm_storage){
365     v->pcm_storage=v->pcm_current+vals*2;
366    
367     for(i=0;i<vi->channels;i++){
368       v->pcm[i]=_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
369     }
370   }
371
372   for(i=0;i<vi->channels;i++)
373     v->pcmret[i]=v->pcm[i]+v->pcm_current;
374     
375   return(v->pcmret);
376 }
377
378 static void _preextrapolate_helper(vorbis_dsp_state *v){
379   int i;
380   int order=32;
381   float *lpc=alloca(order*sizeof(*lpc));
382   float *work=alloca(v->pcm_current*sizeof(*work));
383   long j;
384   v->preextrapolate=1;
385
386   if(v->pcm_current-v->centerW>order*2){ /* safety */
387     for(i=0;i<v->vi->channels;i++){
388       /* need to run the extrapolation in reverse! */
389       for(j=0;j<v->pcm_current;j++)
390         work[j]=v->pcm[i][v->pcm_current-j-1];
391       
392       /* prime as above */
393       vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
394       
395       /* run the predictor filter */
396       vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
397                          order,
398                          work+v->pcm_current-v->centerW,
399                          v->centerW);
400
401       for(j=0;j<v->pcm_current;j++)
402         v->pcm[i][v->pcm_current-j-1]=work[j];
403
404     }
405   }
406 }
407
408
409 /* call with val<=0 to set eof */
410
411 int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
412   vorbis_info *vi=v->vi;
413   codec_setup_info *ci=vi->codec_setup;
414
415   if(vals<=0){
416     int order=32;
417     int i;
418     float *lpc=alloca(order*sizeof(*lpc));
419
420     /* if it wasn't done earlier (very short sample) */
421     if(!v->preextrapolate)
422       _preextrapolate_helper(v);
423
424     /* We're encoding the end of the stream.  Just make sure we have
425        [at least] a few full blocks of zeroes at the end. */
426     /* actually, we don't want zeroes; that could drop a large
427        amplitude off a cliff, creating spread spectrum noise that will
428        suck to encode.  Extrapolate for the sake of cleanliness. */
429
430     vorbis_analysis_buffer(v,ci->blocksizes[1]*3); 
431     v->eofflag=v->pcm_current;
432     v->pcm_current+=ci->blocksizes[1]*3;
433
434     for(i=0;i<vi->channels;i++){
435       if(v->eofflag>order*2){
436         /* extrapolate with LPC to fill in */
437         long n;
438
439         /* make a predictor filter */
440         n=v->eofflag;
441         if(n>ci->blocksizes[1])n=ci->blocksizes[1];
442         vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
443
444         /* run the predictor filter */
445         vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
446                            v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
447       }else{
448         /* not enough data to extrapolate (unlikely to happen due to
449            guarding the overlap, but bulletproof in case that
450            assumtion goes away). zeroes will do. */
451         memset(v->pcm[i]+v->eofflag,0,
452                (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
453
454       }
455     }
456   }else{
457
458     if(v->pcm_current+vals>v->pcm_storage)
459       return(OV_EINVAL);
460
461     v->pcm_current+=vals;
462
463     /* we may want to reverse extrapolate the beginning of a stream
464        too... in case we're beginning on a cliff! */
465     /* clumsy, but simple.  It only runs once, so simple is good. */
466     if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
467       _preextrapolate_helper(v);
468
469   }
470   return(0);
471 }
472
473 /* do the deltas, envelope shaping, pre-echo and determine the size of
474    the next block on which to continue analysis */
475 int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
476   int i;
477   vorbis_info *vi=v->vi;
478   codec_setup_info *ci=vi->codec_setup;
479   private_state *b=v->backend_state;
480   vorbis_look_psy_global *g=b->psy_g_look;
481   long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
482   vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
483
484   /* check to see if we're started... */
485   if(!v->preextrapolate)return(0);
486
487   /* check to see if we're done... */
488   if(v->eofflag==-1)return(0);
489
490   /* By our invariant, we have lW, W and centerW set.  Search for
491      the next boundary so we can determine nW (the next window size)
492      which lets us compute the shape of the current block's window */
493
494   /* we do an envelope search even on a single blocksize; we may still
495      be throwing more bits at impulses, and envelope search handles
496      marking impulses too. */
497   {  
498     long bp=_ve_envelope_search(v);
499     if(bp==-1){
500
501       if(v->eofflag==0)return(0); /* not enough data currently to search for a
502                                      full long block */
503       v->nW=0;
504     }else{
505
506       if(ci->blocksizes[0]==ci->blocksizes[1])
507         v->nW=0;
508       else
509         v->nW=bp;
510     }
511   }
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   vb->lW=v->lW;
535   vb->W=v->W;
536   vb->nW=v->nW;
537
538   if(v->W){
539     if(!v->lW || !v->nW){
540       vbi->blocktype=BLOCKTYPE_TRANSITION;
541       /*fprintf(stderr,"-");*/
542     }else{
543       vbi->blocktype=BLOCKTYPE_LONG;
544       /*fprintf(stderr,"_");*/
545     }
546   }else{
547     if(_ve_envelope_mark(v)){
548       vbi->blocktype=BLOCKTYPE_IMPULSE;
549       /*fprintf(stderr,"|");*/
550
551     }else{
552       vbi->blocktype=BLOCKTYPE_PADDING;
553       /*fprintf(stderr,".");*/
554
555     }
556   }
557  
558   vb->vd=v;
559   vb->sequence=v->sequence++;
560   vb->granulepos=v->granulepos;
561   vb->pcmend=ci->blocksizes[v->W];
562   
563   /* copy the vectors; this uses the local storage in vb */
564
565   /* this tracks 'strongest peak' for later psychoacoustics */
566   /* moved to the global psy state; clean this mess up */
567   if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
568   g->ampmax=_vp_ampmax_decay(g->ampmax,v);
569   vbi->ampmax=g->ampmax;
570   
571   vb->pcm=_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
572   vbi->pcmdelay=_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
573   for(i=0;i<vi->channels;i++){
574     vbi->pcmdelay[i]=
575       _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
576     memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
577     vb->pcm[i]=vbi->pcmdelay[i]+beginW;
578     
579     /* before we added the delay 
580        vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
581        memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
582     */
583     
584   }
585   
586   /* handle eof detection: eof==0 means that we've not yet received EOF
587                            eof>0  marks the last 'real' sample in pcm[]
588                            eof<0  'no more to do'; doesn't get here */
589
590   if(v->eofflag){
591     if(v->centerW>=v->eofflag){
592       v->eofflag=-1;
593       vb->eofflag=1;
594       return(1);
595     }
596   }
597
598   /* advance storage vectors and clean up */
599   {
600     int new_centerNext=ci->blocksizes[1]/2;
601     int movementW=centerNext-new_centerNext;
602
603     if(movementW>0){
604
605       _ve_envelope_shift(b->ve,movementW);
606       v->pcm_current-=movementW;
607       
608       for(i=0;i<vi->channels;i++)
609         memmove(v->pcm[i],v->pcm[i]+movementW,
610                 v->pcm_current*sizeof(*v->pcm[i]));
611       
612       
613       v->lW=v->W;
614       v->W=v->nW;
615       v->centerW=new_centerNext;
616       
617       if(v->eofflag){
618         v->eofflag-=movementW;
619         if(v->eofflag<=0)v->eofflag=-1;
620         /* do not add padding to end of stream! */
621         if(v->centerW>=v->eofflag){
622           v->granulepos+=movementW-(v->centerW-v->eofflag);
623         }else{
624           v->granulepos+=movementW;
625         }
626       }else{
627         v->granulepos+=movementW;
628       }
629     }
630   }
631
632   /* done */
633   return(1);
634 }
635
636 int vorbis_synthesis_restart(vorbis_dsp_state *v){
637   vorbis_info *vi=v->vi;
638   codec_setup_info *ci;
639
640   if(!v->backend_state)return -1;
641   if(!vi)return -1;
642   ci=vi->codec_setup;
643   if(!ci)return -1;
644
645   v->centerW=ci->blocksizes[1]/2;
646   v->pcm_current=v->centerW;
647   
648   v->pcm_returned=-1;
649   v->granulepos=-1;
650   v->sequence=-1;
651   v->eofflag=0;
652   ((private_state *)(v->backend_state))->sample_count=-1;
653
654   return(0);
655 }
656
657 int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
658   _vds_shared_init(v,vi,0);
659   vorbis_synthesis_restart(v);
660
661   return(0);
662 }
663
664 /* Unlike in analysis, the window is only partially applied for each
665    block.  The time domain envelope is not yet handled at the point of
666    calling (as it relies on the previous block). */
667
668 int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
669   vorbis_info *vi=v->vi;
670   codec_setup_info *ci=vi->codec_setup;
671   private_state *b=v->backend_state;
672   int i,j;
673
674   if(!vb)return(OV_EINVAL);
675   if(v->pcm_current>v->pcm_returned  && v->pcm_returned!=-1)return(OV_EINVAL);
676     
677   v->lW=v->W;
678   v->W=vb->W;
679   v->nW=-1;
680   
681   if((v->sequence==-1)||
682      (v->sequence+1 != vb->sequence)){
683     v->granulepos=-1; /* out of sequence; lose count */
684     b->sample_count=-1;
685   }
686
687   v->sequence=vb->sequence;
688   
689   if(vb->pcm){  /* no pcm to process if vorbis_synthesis_trackonly 
690                    was called on block */
691     int n=ci->blocksizes[v->W]/2;
692     int n0=ci->blocksizes[0]/2;
693     int n1=ci->blocksizes[1]/2;
694     
695     int thisCenter;
696     int prevCenter;
697     
698     v->glue_bits+=vb->glue_bits;
699     v->time_bits+=vb->time_bits;
700     v->floor_bits+=vb->floor_bits;
701     v->res_bits+=vb->res_bits;
702     
703     if(v->centerW){
704       thisCenter=n1;
705       prevCenter=0;
706     }else{
707       thisCenter=0;
708       prevCenter=n1;
709     }
710     
711     /* v->pcm is now used like a two-stage double buffer.  We don't want
712        to have to constantly shift *or* adjust memory usage.  Don't
713        accept a new block until the old is shifted out */
714     
715     /* overlap/add PCM */
716     
717     for(j=0;j<vi->channels;j++){
718       /* the overlap/add section */
719       if(v->lW){
720         if(v->W){
721           /* large/large */
722           float *w=b->window[1];
723           float *pcm=v->pcm[j]+prevCenter;
724           float *p=vb->pcm[j];
725           for(i=0;i<n1;i++)
726             pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
727         }else{
728           /* large/small */
729           float *w=b->window[0];
730           float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
731           float *p=vb->pcm[j];
732           for(i=0;i<n0;i++)
733             pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
734         }
735       }else{
736         if(v->W){
737           /* small/large */
738           float *w=b->window[0];
739           float *pcm=v->pcm[j]+prevCenter;
740           float *p=vb->pcm[j]+n1/2-n0/2;
741           for(i=0;i<n0;i++)
742             pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
743           for(;i<n1/2+n0/2;i++)
744             pcm[i]=p[i];
745         }else{
746           /* small/small */
747           float *w=b->window[0];
748           float *pcm=v->pcm[j]+prevCenter;
749           float *p=vb->pcm[j];
750           for(i=0;i<n0;i++)
751             pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
752         }
753       }
754       
755       /* the copy section */
756       {
757         float *pcm=v->pcm[j]+thisCenter;
758         float *p=vb->pcm[j]+n;
759         for(i=0;i<n;i++)
760           pcm[i]=p[i];
761       }
762     }
763     
764     if(v->centerW)
765       v->centerW=0;
766     else
767       v->centerW=n1;
768     
769     /* deal with initial packet state; we do this using the explicit
770        pcm_returned==-1 flag otherwise we're sensitive to first block
771        being short or long */
772     
773     if(v->pcm_returned==-1){
774       v->pcm_returned=thisCenter;
775       v->pcm_current=thisCenter;
776     }else{
777       v->pcm_returned=prevCenter;
778       v->pcm_current=prevCenter+
779         ci->blocksizes[v->lW]/4+
780         ci->blocksizes[v->W]/4;
781     }
782     
783   }
784
785   /* track the frame number... This is for convenience, but also
786      making sure our last packet doesn't end with added padding.  If
787      the last packet is partial, the number of samples we'll have to
788      return will be past the vb->granulepos.
789      
790      This is not foolproof!  It will be confused if we begin
791      decoding at the last page after a seek or hole.  In that case,
792      we don't have a starting point to judge where the last frame
793      is.  For this reason, vorbisfile will always try to make sure
794      it reads the last two marked pages in proper sequence */
795
796   if(b->sample_count==-1){
797     b->sample_count=0;
798   }else{
799     b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
800   }
801   
802   if(v->granulepos==-1){
803     if(vb->granulepos!=-1){ /* only set if we have a position to set to */
804
805       v->granulepos=vb->granulepos;
806
807       /* is this a short page? */
808       if(b->sample_count>v->granulepos){
809         /* corner case; if this is both the first and last audio page,
810            then spec says the end is cut, not beginning */
811         if(vb->eofflag){
812           /* trim the end */
813           /* no preceeding granulepos; assume we started at zero (we'd
814              have to in a short single-page stream) */
815           /* granulepos could be -1 due to a seek, but that would result
816              in a long count, not short count */
817           
818           v->pcm_current-=(b->sample_count-v->granulepos);
819         }else{
820           /* trim the beginning */
821           v->pcm_returned+=(b->sample_count-v->granulepos);
822           if(v->pcm_returned>v->pcm_current)
823             v->pcm_returned=v->pcm_current;
824         }
825
826       }
827
828     }
829   }else{
830     v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
831     if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
832       
833       if(v->granulepos>vb->granulepos){
834         long extra=v->granulepos-vb->granulepos;
835
836         if(extra)
837           if(vb->eofflag){
838             /* partial last frame.  Strip the extra samples off */
839             v->pcm_current-=extra;
840           } /* else {Shouldn't happen *unless* the bitstream is out of
841                spec.  Either way, believe the bitstream } */
842       } /* else {Shouldn't happen *unless* the bitstream is out of
843            spec.  Either way, believe the bitstream } */
844       v->granulepos=vb->granulepos;
845     }
846   }
847   
848   /* Update, cleanup */
849   
850   if(vb->eofflag)v->eofflag=1;
851   return(0);
852   
853 }
854
855 /* pcm==NULL indicates we just want the pending samples, no more */
856 int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
857   vorbis_info *vi=v->vi;
858   if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
859     if(pcm){
860       int i;
861       for(i=0;i<vi->channels;i++)
862         v->pcmret[i]=v->pcm[i]+v->pcm_returned;
863       *pcm=v->pcmret;
864     }
865     return(v->pcm_current-v->pcm_returned);
866   }
867   return(0);
868 }
869
870 int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
871   if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
872   v->pcm_returned+=n;
873   return(0);
874 }
875
876 /* intended for use with a specific vorbisfile feature; we want access
877    to the [usually synthetic/postextrapolated] buffer and lapping at
878    the end of a decode cycle, specifically, a half-short-block worth.
879    This funtion works like pcmout above, except it will also expose
880    this implicit buffer data not normally decoded. */
881 int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
882   vorbis_info *vi=v->vi;
883   codec_setup_info *ci=vi->codec_setup;
884   
885   int n=ci->blocksizes[v->W]/2;
886   int n0=ci->blocksizes[0]/2;
887   int n1=ci->blocksizes[1]/2;
888   int i,j;
889
890   if(v->pcm_returned<0)return 0;
891
892   /* our returned data ends at pcm_returned; because the synthesis pcm
893      buffer is a two-fragment ring, that means our data block may be
894      fragmented by buffering, wrapping or a short block not filling
895      out a buffer.  To simplify things, we unfragment if it's at all
896      possibly needed. Otherwise, we'd need to call lapout more than
897      once as well as hold additional dsp state.  Opt for
898      simplicity. */
899
900   /* centerW was advanced by blockin; it would be the center of the
901      *next* block */
902   if(v->centerW==n1){
903     /* the data buffer wraps; swap the halves */
904     /* slow, sure, small */
905     for(j=0;j<vi->channels;j++){
906       float *p=v->pcm[j];
907       for(i=0;i<n1;i++){
908         float temp=p[i];
909         p[i]=p[i+n1];
910         p[i+n1]=temp;
911       }
912     }
913
914     v->pcm_current-=n1;
915     v->pcm_returned-=n1;
916     v->centerW=0;
917   }
918   
919   if((v->lW^v->W)==1){
920     /* long/short or short/long */
921     for(j=0;j<vi->channels;j++){
922       float *s=v->pcm[j];
923       float *d=v->pcm[j]+(n1-n0)/2;
924       for(i=(n1+n0)/2-1;i>=0;--i)
925         d[i]=s[i];
926     }
927     v->pcm_returned+=(n1-n0)/2;
928     v->pcm_current+=(n1-n0)/2;
929   }else{
930     if(v->lW==0){
931       /* short/short */
932       for(j=0;j<vi->channels;j++){
933         float *s=v->pcm[j];
934         float *d=v->pcm[j]+n1-n0;
935         for(i=n0-1;i>=0;--i)
936           d[i]=s[i];
937       }
938       v->pcm_returned+=n1-n0;
939       v->pcm_current+=n1-n0;
940     }
941   }
942     
943   if(pcm){
944     int i;
945     for(i=0;i<vi->channels;i++)
946       v->pcmret[i]=v->pcm[i]+v->pcm_returned;
947     *pcm=v->pcmret;
948   }
949
950   return(n1+n-v->pcm_returned);
951
952 }
953
954 float *vorbis_window(vorbis_dsp_state *v,int W){
955   private_state *b=v->backend_state;
956   return b->window[W];
957 }
958