bugfix. bm->avg_binacc wasn't initialised to known values (and was used without
[platform/upstream/libvorbis.git] / lib / bitrate.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: bitrate tracking and management
14  last mod: $Id: bitrate.c,v 1.12 2002/06/14 17:14:58 msmith Exp $
15
16  ********************************************************************/
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <math.h>
22 #include <ogg/ogg.h>
23 #include "vorbis/codec.h"
24 #include "codec_internal.h"
25 #include "os.h"
26 #include "misc.h"
27 #include "bitrate.h"
28
29
30 static long BINBITS(bitrate_manager_state *bm,long pos,long inbin){
31   int bins=bm->queue_bins;
32   int bin=((inbin&0x7fffffffUL)>>BITTRACK_BPT);
33   ogg_uint32_t lobits=0;
34   ogg_uint32_t hibits=0;
35   ogg_uint32_t bitdel;
36   
37   if(bin>0)lobits=bm->queue_binned[pos*bins+bin-1];
38   if(bin<bins)
39     hibits=bm->queue_binned[pos*bins+bin];
40   else
41     hibits=lobits;
42
43   bitdel=hibits-lobits;
44
45   return(lobits+bitdel*(inbin&((1<<BITTRACK_BPT)-1))/(1<<BITTRACK_BPT));
46
47 }
48
49 #define LIMITBITS(pos,bin) ((bin)>-bins?\
50                  bm->minmax_binstack[(pos)*bins*2+((bin)+bins)-1]:0)
51
52 static long LACING_ADJUST(long bits){
53   int addto=((bits+7)/8+1)/256+1;
54   return( ((bits+7)/8+addto)*8 );
55 }
56
57 static double floater_interpolate(bitrate_manager_state *bm,vorbis_info *vi,
58                                   double desired_rate){
59   int bin=bm->avgfloat*BITTRACK_DIVISOR-1.;
60   double lobitrate;
61   double hibitrate;
62   
63   lobitrate=(double)(bin==0?0:bm->avg_binacc[bin-1])/bm->avg_sampleacc*vi->rate;
64   while(lobitrate>desired_rate && bin>0){
65     bin--;
66     lobitrate=(double)(bin==0?0:bm->avg_binacc[bin-1])/bm->avg_sampleacc*vi->rate;
67   }
68
69   hibitrate=(double)(bin>=bm->queue_bins?bm->avg_binacc[bm->queue_bins-1]:
70                      bm->avg_binacc[bin])/bm->avg_sampleacc*vi->rate;
71   while(hibitrate<desired_rate && bin<bm->queue_bins){
72     bin++;
73     if(bin<bm->queue_bins)
74       hibitrate=(double)bm->avg_binacc[bin]/bm->avg_sampleacc*vi->rate;
75   }
76
77   /* interpolate */
78   if(bin==bm->queue_bins){
79     return bin/(double)BITTRACK_DIVISOR;
80   }else{
81     double delta=(desired_rate-lobitrate)/(hibitrate-lobitrate);
82     return (bin+delta)/BITTRACK_DIVISOR;
83   }
84 }
85
86 /* try out a new limit */
87 static long limit_sum(bitrate_manager_state *bm,int limit){
88   int i=bm->minmax_stackptr;
89   long acc=bm->minmax_acctotal;
90   long bins=bm->queue_bins;
91   
92   acc-=LIMITBITS(i,0);
93   acc+=LIMITBITS(i,limit);
94
95   while(i-->0){
96     if(bm->minmax_limitstack[i]<=limit)break;
97     acc-=LIMITBITS(i,bm->minmax_limitstack[i]);
98     acc+=LIMITBITS(i,limit);
99   }
100   return(acc);
101 }
102
103 /* compute bitrate tracking setup, allocate circular packet size queue */
104 void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
105   int i;
106   codec_setup_info *ci=vi->codec_setup;
107   bitrate_manager_info *bi=&ci->bi;
108   long maxlatency;
109
110   memset(bm,0,sizeof(*bm));
111   
112   if(bi){
113     
114     bm->avg_sampledesired=bi->queue_avg_time*vi->rate;
115     bm->avg_centerdesired=bi->queue_avg_time*vi->rate*bi->queue_avg_center;
116     bm->minmax_sampledesired=bi->queue_minmax_time*vi->rate;
117     
118     /* first find the max possible needed queue size */
119     maxlatency=max(bm->avg_sampledesired-bm->avg_centerdesired,
120                    bm->minmax_sampledesired)+bm->avg_centerdesired;
121     
122     if(maxlatency>0 &&
123        (bi->queue_avgmin>0 || bi->queue_avgmax>0 || bi->queue_hardmax>0 ||
124         bi->queue_hardmin>0)){
125       long maxpackets=maxlatency/(ci->blocksizes[0]>>1)+3;
126       long bins=BITTRACK_DIVISOR*ci->passlimit[ci->coupling_passes-1];
127       
128       bm->queue_size=maxpackets;
129       bm->queue_bins=bins;
130       bm->queue_binned=_ogg_malloc(maxpackets*bins*sizeof(*bm->queue_binned));
131       bm->queue_actual=_ogg_malloc(maxpackets*sizeof(*bm->queue_actual));
132       
133       if((bi->queue_avgmin>0 || bi->queue_avgmax>0) &&
134          bi->queue_avg_time>0){
135         
136         bm->avg_binacc=_ogg_calloc(bins,sizeof(*bm->avg_binacc));
137         bm->avgfloat=bi->avgfloat_initial;
138         
139         
140       }else{
141         bm->avg_tail= -1;
142       }
143       
144       if((bi->queue_hardmin>0 || bi->queue_hardmax>0) &&
145          bi->queue_minmax_time>0){
146         
147         bm->minmax_binstack=_ogg_calloc((bins+1)*bins*2,
148                                         sizeof(bm->minmax_binstack));
149         bm->minmax_posstack=_ogg_calloc((bins+1),
150                                       sizeof(bm->minmax_posstack));
151         bm->minmax_limitstack=_ogg_calloc((bins+1),
152                                           sizeof(bm->minmax_limitstack));
153       }else{
154         bm->minmax_tail= -1;
155       }
156       
157       /* space for the packet queueing */
158       bm->queue_packet_buffers=_ogg_calloc(maxpackets,sizeof(*bm->queue_packet_buffers));
159       bm->queue_packets=_ogg_calloc(maxpackets,sizeof(*bm->queue_packets));
160       for(i=0;i<maxpackets;i++)
161         oggpack_writeinit(bm->queue_packet_buffers+i);
162       
163     }else{
164       bm->queue_packet_buffers=_ogg_calloc(1,sizeof(*bm->queue_packet_buffers));
165       bm->queue_packets=_ogg_calloc(1,sizeof(*bm->queue_packets));
166       oggpack_writeinit(bm->queue_packet_buffers);
167     }      
168   }
169 }
170
171 void vorbis_bitrate_clear(bitrate_manager_state *bm){
172   int i;
173   if(bm){
174     if(bm->queue_binned)_ogg_free(bm->queue_binned);
175     if(bm->queue_actual)_ogg_free(bm->queue_actual);
176     if(bm->avg_binacc)_ogg_free(bm->avg_binacc);
177     if(bm->minmax_binstack)_ogg_free(bm->minmax_binstack);
178     if(bm->minmax_posstack)_ogg_free(bm->minmax_posstack);
179     if(bm->minmax_limitstack)_ogg_free(bm->minmax_limitstack);
180     if(bm->queue_packet_buffers){
181       if(bm->queue_size==0){
182         oggpack_writeclear(bm->queue_packet_buffers);
183         _ogg_free(bm->queue_packet_buffers);
184       }else{
185         for(i=0;i<bm->queue_size;i++)
186           oggpack_writeclear(bm->queue_packet_buffers+i);
187         _ogg_free(bm->queue_packet_buffers);
188       }
189     }
190     if(bm->queue_packets)_ogg_free(bm->queue_packets);
191     memset(bm,0,sizeof(*bm));
192   }
193 }
194
195 int vorbis_bitrate_managed(vorbis_block *vb){
196   vorbis_dsp_state      *vd=vb->vd;
197   backend_lookup_state  *b=vd->backend_state; 
198   bitrate_manager_state *bm=&b->bms;
199
200   if(bm->queue_binned)return(1);
201   return(0);
202 }
203
204 int vorbis_bitrate_maxmarkers(void){
205   return 8*BITTRACK_DIVISOR;
206 }
207
208 /* finish taking in the block we just processed */
209 int vorbis_bitrate_addblock(vorbis_block *vb){
210   int i; 
211   vorbis_block_internal *vbi=vb->internal;
212   vorbis_dsp_state      *vd=vb->vd;
213   backend_lookup_state  *b=vd->backend_state; 
214   bitrate_manager_state *bm=&b->bms;
215   vorbis_info           *vi=vd->vi;
216   codec_setup_info      *ci=vi->codec_setup;
217   bitrate_manager_info  *bi=&ci->bi;
218   int                    eofflag=vb->eofflag;
219   int                    head=bm->queue_head;
220   int                    next_head=head+1;
221   int                    bins=bm->queue_bins;
222   int                    minmax_head,new_minmax_head;
223   
224   ogg_uint32_t           *head_ptr;
225   oggpack_buffer          temp;
226
227   if(!bm->queue_binned){
228     oggpack_buffer temp;
229     /* not a bitrate managed stream, but for API simplicity, we'll
230        buffer one packet to keep the code path clean */
231     
232     if(bm->queue_head)return(-1); /* one has been submitted without
233                                      being claimed */
234     bm->queue_head++;
235
236     bm->queue_packets[0].packet=oggpack_get_buffer(&vb->opb);
237     bm->queue_packets[0].bytes=oggpack_bytes(&vb->opb);
238     bm->queue_packets[0].b_o_s=0;
239     bm->queue_packets[0].e_o_s=vb->eofflag;
240     bm->queue_packets[0].granulepos=vb->granulepos;
241     bm->queue_packets[0].packetno=vb->sequence; /* for sake of completeness */
242
243     memcpy(&temp,bm->queue_packet_buffers,sizeof(vb->opb));
244     memcpy(bm->queue_packet_buffers,&vb->opb,sizeof(vb->opb));
245     memcpy(&vb->opb,&temp,sizeof(vb->opb));
246
247     return(0);
248   }
249
250   /* add encoded packet to head */
251   if(next_head>=bm->queue_size)next_head=0;
252   head_ptr=bm->queue_binned+bins*head;
253
254   /* is there room to add a block? In proper use of the API, this will
255      never come up... but guard it anyway */
256   if(next_head==bm->avg_tail || next_head==bm->minmax_tail)return(-1);
257
258   /* add the block to the toplevel queue */
259   bm->queue_head=next_head;
260   bm->queue_actual[head]=(vb->W?0x80000000UL:0);
261
262   /* buffer packet fields */
263   bm->queue_packets[head].packet=oggpack_get_buffer(&vb->opb);
264   bm->queue_packets[head].bytes=oggpack_bytes(&vb->opb);
265   bm->queue_packets[head].b_o_s=0;
266   bm->queue_packets[head].e_o_s=vb->eofflag;
267   bm->queue_packets[head].granulepos=vb->granulepos;
268   bm->queue_packets[head].packetno=vb->sequence; /* for sake of completeness */
269
270   /* swap packet buffers */
271   memcpy(&temp,bm->queue_packet_buffers+head,sizeof(vb->opb));
272   memcpy(bm->queue_packet_buffers+head,&vb->opb,sizeof(vb->opb));
273   memcpy(&vb->opb,&temp,sizeof(vb->opb));
274
275   /* save markers */
276   memcpy(head_ptr,vbi->packet_markers,sizeof(*head_ptr)*bins);
277
278   if(bm->avg_binacc)
279     new_minmax_head=minmax_head=bm->avg_center;
280   else
281     new_minmax_head=minmax_head=head;
282
283   /* the average tracking queue is updated first; its results (if it's
284      in use) are taken into account by the min/max limiter (if min/max
285      is in use) */
286   if(bm->avg_binacc){
287     unsigned long desired_center=bm->avg_centerdesired;
288     if(eofflag)desired_center=0;
289
290     /* update the avg head */
291     for(i=0;i<bins;i++)
292       bm->avg_binacc[i]+=LACING_ADJUST(head_ptr[i]);
293     bm->avg_sampleacc+=ci->blocksizes[vb->W]>>1;
294     bm->avg_centeracc+=ci->blocksizes[vb->W]>>1;
295
296     if(bm->avg_sampleacc>bm->avg_sampledesired || eofflag){
297
298       /* update the avg center */
299       if(bm->avg_centeracc>desired_center){
300         /* choose the new average floater */
301         int samples=ci->blocksizes[vb->W]>>1;
302         double upper=floater_interpolate(bm,vi,bi->queue_avgmax);
303         double lower=floater_interpolate(bm,vi,bi->queue_avgmin);
304         double new=bi->avgfloat_initial,slew;
305         int bin;
306         
307         if(upper>0. && upper<new)new=upper;
308         if(lower<bi->avgfloat_minimum)
309           lower=bi->avgfloat_minimum;
310         if(lower>new)new=lower;
311         
312         slew=(new-bm->avgfloat)/samples*vi->rate;
313         
314         if(slew<bi->avgfloat_downslew_max)
315           new=bm->avgfloat+bi->avgfloat_downslew_max/vi->rate*samples;
316         if(slew>bi->avgfloat_upslew_max)
317           new=bm->avgfloat+bi->avgfloat_upslew_max/vi->rate*samples;
318         
319         bm->avgfloat=new;
320
321         /* apply the average floater to new blocks */
322         bin=bm->avgfloat*(BITTRACK_DIVISOR<<BITTRACK_BPT);
323         
324         while(bm->avg_centeracc>desired_center){
325           samples=ci->blocksizes[bm->queue_actual[bm->avg_center]&
326                                 0x80000000UL?1:0]>>1;
327           
328           bm->queue_actual[bm->avg_center]|=bin;
329           
330           bm->avg_centeracc-=samples;
331           bm->avg_center++;
332           if(bm->noisetrigger_postpone)bm->noisetrigger_postpone-=samples;
333           if(bm->avg_center>=bm->queue_size)bm->avg_center=0;
334         }
335         new_minmax_head=bm->avg_center;
336         
337         /* track noise bias triggers and noise bias */
338         if(bm->avgfloat<bi->avgfloat_noise_lowtrigger)
339           bm->noisetrigger_request+=1.f;
340         else
341           if(bm->noisetrigger_request>0. && bm->avgnoise>0.)
342             bm->noisetrigger_request-=.2f;
343         
344         if(bm->avgfloat>bi->avgfloat_noise_hightrigger)
345           bm->noisetrigger_request-=1.f;
346         else
347           if(bm->noisetrigger_request<0 && bm->avgnoise<0.)
348             bm->noisetrigger_request+=.2f;
349         
350         if(bm->noisetrigger_postpone<=0){
351           if(bm->noisetrigger_request<0.){
352             bm->avgnoise-=1.f;
353             if(-bm->noisetrigger_request>(signed long)(bm->avg_sampleacc)/2)
354               bm->avgnoise-=1.f;
355             bm->noisetrigger_postpone=bm->avg_sampleacc/2;
356           }
357           if(bm->noisetrigger_request>0.){
358             bm->avgnoise+=1.f;
359             if(bm->noisetrigger_request>(signed long)(bm->avg_sampleacc)/2)
360               bm->avgnoise+=1.f;
361             bm->noisetrigger_postpone=bm->avg_sampleacc/2;
362           }
363           
364           /* we generally want the noise bias to drift back to zero */
365           bm->noisetrigger_request=0.f;
366           if(bm->avgnoise>0)
367             bm->noisetrigger_request= -1.;
368           if(bm->avgnoise<0)
369             bm->noisetrigger_request= +1.;
370           
371           if(bm->avgnoise<bi->avgfloat_noise_minval)
372             bm->avgnoise=bi->avgfloat_noise_minval;
373           if(bm->avgnoise>bi->avgfloat_noise_maxval)
374             bm->avgnoise=bi->avgfloat_noise_maxval;
375         }
376       }
377       
378       /* update the avg tail if needed */
379       while(bm->avg_sampleacc>bm->avg_sampledesired){
380         int samples=
381           ci->blocksizes[bm->queue_actual[bm->avg_tail]&0x80000000UL?1:0]>>1;
382         for(i=0;i<bm->queue_bins;i++)
383           bm->avg_binacc[i]-=LACING_ADJUST(bm->queue_binned[bins*bm->avg_tail+i]);
384         bm->avg_sampleacc-=samples;
385         bm->avg_tail++;
386         if(bm->avg_tail>=bm->queue_size)bm->avg_tail=0;
387       }
388       
389       
390     }
391   }else{
392     /* if we're not using an average tracker, the 'float' is nailed to
393        the avgfloat_initial value.  It needs to be set for the min/max
394        to deal properly */
395     long bin=bi->avgfloat_initial*(BITTRACK_DIVISOR<<BITTRACK_BPT);
396     bm->queue_actual[head]|=bin;
397     new_minmax_head=next_head;
398   }     
399   
400   /* update the min/max queues and enforce limits */
401   if(bm->minmax_binstack){
402     unsigned long sampledesired=eofflag?0:bm->minmax_sampledesired;
403     
404     /* add to stack recent */
405     while(minmax_head!=new_minmax_head){
406       unsigned int i;
407       int samples=ci->blocksizes[bm->queue_actual[minmax_head]&
408                                 0x80000000UL?1:0]>>1;
409       
410         /* the construction here is not parallel to the floater's
411            stack.  
412
413            floater[bin-1]  <-> floater supported at bin
414            ...
415            floater[0]      <-> floater supported at 1
416            supported at zero is implicit.  
417            the BINBITS macro performs offsetting
418
419      
420       bin  minmax[bin*2-1] <-> floater supported at bin
421            ...
422         1  minmax[bin]     <-> floater supported at 1
423         0  minmax[bin-1]   <-> no limit/support (limited to/supported at bin 0,
424                                                  ie, no effect)
425        -1  minmax[bin-2]   <-> floater limited to bin-1
426            ...
427     -bin+1  minmax[0]       <-> floater limited to 1
428             limited to zero (val= -bin) is implicit
429         */
430       for(i=0;i<(unsigned int)bins;i++){
431         bm->minmax_binstack[bm->minmax_stackptr*bins*2+bins+i]+=
432           LACING_ADJUST(
433           BINBITS(bm,minmax_head,
434                   (bm->queue_actual[minmax_head]&0x7fffffffUL)>
435                   ((i+1)<<BITTRACK_BPT)?
436                   bm->queue_actual[minmax_head]:
437                   ((i+1)<<BITTRACK_BPT)));
438         
439         bm->minmax_binstack[bm->minmax_stackptr*bins*2+i]+=
440           LACING_ADJUST(
441           BINBITS(bm,minmax_head,
442                   (bm->queue_actual[minmax_head]&0x7fffffffUL)<
443                   ((i+1)<<BITTRACK_BPT)?
444                   bm->queue_actual[minmax_head]:
445                   ((i+1)<<BITTRACK_BPT)));
446       }
447       
448       bm->minmax_posstack[bm->minmax_stackptr]=minmax_head; /* not one
449                                                                past
450                                                                like
451                                                                typical */
452       bm->minmax_limitstack[bm->minmax_stackptr]=0;
453       bm->minmax_sampleacc+=samples;
454       bm->minmax_acctotal+=
455         LACING_ADJUST(BINBITS(bm,minmax_head,bm->queue_actual[minmax_head]));
456       
457       minmax_head++;
458       if(minmax_head>=bm->queue_size)minmax_head=0;
459     }
460     
461     /* check limits, enforce changes */
462     if(bm->minmax_sampleacc>sampledesired){
463       double bitrate=(double)bm->minmax_acctotal/bm->minmax_sampleacc*vi->rate;
464       int limit=0;
465       
466       if((bi->queue_hardmax>0 && bitrate>bi->queue_hardmax) || 
467          (bi->queue_hardmin>0 && bitrate<bi->queue_hardmin)){
468         int newstack;
469         int stackctr;
470         long bitsum=limit_sum(bm,0);
471
472         bitrate=(double)bitsum/bm->minmax_sampleacc*vi->rate;
473
474         /* we're off rate.  Iteratively try out new hard floater
475            limits until we find one that brings us inside.  Here's
476            where we see the whole point of the limit stacks.  */
477         if(bi->queue_hardmax>0 && bitrate>bi->queue_hardmax){
478           for(limit=-1;limit>-bins;limit--){
479             long bitsum=limit_sum(bm,limit);
480             bitrate=(double)bitsum/bm->minmax_sampleacc*vi->rate;
481             if(bitrate<=bi->queue_hardmax)break;
482           }
483         }else if(bitrate<bi->queue_hardmin){
484           for(limit=1;limit<bins;limit++){
485             long bitsum=limit_sum(bm,limit);
486             bitrate=(double)bitsum/bm->minmax_sampleacc*vi->rate;
487             if(bitrate>=bi->queue_hardmin)break;
488           }
489           if(bitrate>bi->queue_hardmax)limit--;
490         }
491
492         for(i=limit-1;i>-bins;i--){
493           long bitsum=limit_sum(bm,i);
494           bitrate=(double)bitsum/bm->minmax_sampleacc*vi->rate;
495         }
496
497         bitsum=limit_sum(bm,limit);
498         bitrate=(double)bitsum/bm->minmax_sampleacc*vi->rate;
499
500         /* trace the limit backward, stop when we see a lower limit */
501         newstack=bm->minmax_stackptr-1;
502         while(newstack>=0){
503           if(bm->minmax_limitstack[newstack]<limit)break;
504           newstack--;
505         }
506         
507         /* update bit counter with new limit and replace any stack
508            limits that have been replaced by our new lower limit */
509         stackctr=bm->minmax_stackptr;
510         while(stackctr>newstack){
511           bm->minmax_acctotal-=
512             LIMITBITS(stackctr,bm->minmax_limitstack[stackctr]);
513           bm->minmax_acctotal+=LIMITBITS(stackctr,limit);
514
515           if(stackctr<bm->minmax_stackptr)
516             for(i=0;i<bins*2;i++)
517               bm->minmax_binstack[stackctr*bins*2+i]+=
518               bm->minmax_binstack[(stackctr+1)*bins*2+i];
519
520           stackctr--;
521         }
522         stackctr++;
523         bm->minmax_posstack[stackctr]=bm->minmax_posstack[bm->minmax_stackptr];
524         bm->minmax_limitstack[stackctr]=limit;
525
526         /* set up new blank stack entry */
527         stackctr++;
528         bm->minmax_stackptr=stackctr;
529         memset(&bm->minmax_binstack[stackctr*bins*2],
530                0,
531                sizeof(*bm->minmax_binstack)*bins*2);
532         bm->minmax_limitstack[stackctr]=0;
533         bm->minmax_posstack[stackctr]=-1;
534         
535       }
536     }
537     
538     /* remove from tail */
539     while(bm->minmax_sampleacc>sampledesired){
540       int samples=
541         ci->blocksizes[bm->queue_actual[bm->minmax_tail]&0x80000000UL?1:0]>>1;
542       int actual=bm->queue_actual[bm->minmax_tail]&0x7fffffffUL;
543
544       for(i=0;i<bins;i++){
545         bm->minmax_binstack[bins+i]-= /* always comes off the stack bottom */
546           LACING_ADJUST(BINBITS(bm,bm->minmax_tail,
547                                 actual>((i+1)<<BITTRACK_BPT)?
548                                 actual:((i+1)<<BITTRACK_BPT)));
549         bm->minmax_binstack[i]-= 
550           LACING_ADJUST(BINBITS(bm,bm->minmax_tail,
551                                 actual<((i+1)<<BITTRACK_BPT)?
552                                 actual:((i+1)<<BITTRACK_BPT)));
553       }
554
555       /* always perform in this order; max overrules min */
556       if((bm->minmax_limitstack[0]<<BITTRACK_BPT)>actual)
557         actual=(bm->minmax_limitstack[0]<<BITTRACK_BPT);
558       if(((bins+bm->minmax_limitstack[0])<<BITTRACK_BPT)<actual)
559         actual=(bins+bm->minmax_limitstack[0])<<BITTRACK_BPT;
560
561       bm->minmax_acctotal-=LACING_ADJUST(BINBITS(bm,bm->minmax_tail,actual));
562       bm->minmax_sampleacc-=samples;
563      
564       /* revise queue_actual to reflect the limit */
565       bm->queue_actual[bm->minmax_tail]&=0x80000000UL;
566       bm->queue_actual[bm->minmax_tail]|=actual;
567       
568       if(bm->minmax_tail==bm->minmax_posstack[0]){
569         /* the stack becomes a FIFO; the first data has fallen off */
570         memmove(bm->minmax_binstack,bm->minmax_binstack+bins*2,
571                 sizeof(*bm->minmax_binstack)*bins*2*bm->minmax_stackptr);
572         memmove(bm->minmax_posstack,bm->minmax_posstack+1,
573                 sizeof(*bm->minmax_posstack)*bm->minmax_stackptr);
574         memmove(bm->minmax_limitstack,bm->minmax_limitstack+1,
575                 sizeof(*bm->minmax_limitstack)*bm->minmax_stackptr);
576         bm->minmax_stackptr--;
577       }
578       
579       bm->minmax_tail++;
580       if(bm->minmax_tail>=bm->queue_size)bm->minmax_tail=0;
581     }
582     
583     
584     bm->last_to_flush=bm->minmax_tail;
585   }else{
586     bm->last_to_flush=bm->avg_center;
587   }
588   if(eofflag)
589     bm->last_to_flush=bm->queue_head;
590   return(0);
591 }
592
593 int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
594   backend_lookup_state  *b=vd->backend_state;
595   bitrate_manager_state *bm=&b->bms;
596
597   if(bm->queue_size==0){
598     if(bm->queue_head==0)return(0);
599
600     memcpy(op,bm->queue_packets,sizeof(*op));
601     bm->queue_head=0;
602
603   }else{
604     long bin;
605     long bytes;
606
607     if(bm->next_to_flush==bm->last_to_flush)return(0);
608
609     bin=bm->queue_actual[bm->next_to_flush];
610     bytes=(BINBITS(bm,bm->next_to_flush,bin)+7)/8;
611     
612     memcpy(op,bm->queue_packets+bm->next_to_flush,sizeof(*op));
613
614     if(bytes<op->bytes)op->bytes=bytes;
615
616     bm->next_to_flush++;
617     if(bm->next_to_flush>=bm->queue_size)bm->next_to_flush=0;
618
619   }
620
621   return(1);
622 }