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