make infinite loop finite in mode setup.
[platform/upstream/libvorbis.git] / lib / vorbisenc.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: simple programmatic interface for encoder mode setup
14  last mod: $Id: vorbisenc.c,v 1.42 2002/06/29 13:24:37 msmith Exp $
15
16  ********************************************************************/
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <math.h>
21
22 #include "vorbis/codec.h"
23 #include "vorbis/vorbisenc.h"
24
25 #include "codec_internal.h"
26
27 #include "os.h"
28 #include "misc.h"
29
30 /* careful with this; it's using static array sizing to make managing
31    all the modes a little less annoying.  If we use a residue backend
32    with > 12 partition types, or a different division of iteration,
33    this needs to be updated. */
34 typedef struct {
35   static_codebook *books[12][3];
36 } static_bookblock;
37
38 typedef struct {
39   int res_type;
40   int limit_type; /* 0 lowpass limited, 1 point stereo limited */
41   vorbis_info_residue0 *res;
42   static_codebook  *book_aux;
43   static_codebook  *book_aux_managed;
44   static_bookblock *books_base;
45   static_bookblock *books_base_managed;
46 } vorbis_residue_template;
47
48 typedef struct {
49   vorbis_info_mapping0    *map;
50   vorbis_residue_template *res;
51 } vorbis_mapping_template;
52
53 typedef struct vp_adjblock{
54   int block[P_BANDS];
55 } vp_adjblock;
56
57 typedef struct {
58   int data[NOISE_COMPAND_LEVELS];
59 } compandblock;
60
61 /* high level configuration information for setting things up
62    step-by-step with the detailed vorbis_encode_ctl interface.
63    There's a fair amount of redundancy such that interactive setup
64    does not directly deal with any vorbis_info or codec_setup_info
65    initialization; it's all stored (until full init) in this highlevel
66    setup, then flushed out to the real codec setup structs later. */
67
68 typedef struct {
69   int att[P_NOISECURVES];
70   float boost;
71   float decay;
72 } att3;
73 typedef struct { int data[P_NOISECURVES]; } adj3; 
74
75 typedef struct {
76   int   pre[PACKETBLOBS];
77   int   post[PACKETBLOBS];
78   float kHz[PACKETBLOBS];
79   float lowpasskHz[PACKETBLOBS];
80 } adj_stereo;
81
82 typedef struct {
83   int lo;
84   int hi;
85   int fixed;
86 } noiseguard;
87 typedef struct {
88   int data[P_NOISECURVES][17];
89 } noise3;
90
91 typedef struct {
92   int      mappings;
93   double  *rate_mapping;
94   double  *quality_mapping;
95   int      coupling_restriction;
96   long     bitrate_min_restriction;
97   long     bitrate_max_restriction;
98
99
100   int     *blocksize_short;
101   int     *blocksize_long;
102
103   att3    *psy_tone_masteratt;
104   int     *psy_tone_0dB;
105   int     *psy_tone_dBsuppress;
106
107   vp_adjblock *psy_tone_adj_impulse;
108   vp_adjblock *psy_tone_adj_long;
109   vp_adjblock *psy_tone_adj_other;
110
111   noiseguard  *psy_noiseguards;
112   noise3      *psy_noise_bias_impulse;
113   noise3      *psy_noise_bias_padding;
114   noise3      *psy_noise_bias_trans;
115   noise3      *psy_noise_bias_long;
116   int         *psy_noise_dBsuppress;
117
118   compandblock  *psy_noise_compand;
119   double        *psy_noise_compand_short_mapping;
120   double        *psy_noise_compand_long_mapping;
121
122   int      *psy_noise_normal_start[2];
123   int      *psy_noise_normal_partition[2];
124   double   *psy_noise_normal_thresh;
125
126   int      *psy_ath_float;
127   int      *psy_ath_abs;
128
129   double   *psy_lowpass;
130
131   vorbis_info_psy_global *global_params;
132   double     *global_mapping;
133   adj_stereo *stereo_modes;
134
135   static_codebook ***floor_books;
136   vorbis_info_floor1 *floor_params;
137   int *floor_short_mapping;
138   int *floor_long_mapping;
139
140   vorbis_mapping_template *maps;
141 } ve_setup_data_template;
142
143 #include "modes/setup_44.h"
144
145 static ve_setup_data_template *setup_list[]={
146   &ve_setup_44_stereo,
147   &ve_setup_44_stereo_low,
148   0
149 };
150
151
152 /* a few static coder conventions */
153 static vorbis_info_mode _mode_template[2]={
154   {0,0,0,0},
155   {1,0,0,1}
156 };
157
158
159 static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
160   if(vi && vi->codec_setup){
161
162     vi->version=0;
163     vi->channels=ch;
164     vi->rate=rate;
165
166     return(0);
167   }
168   return(OV_EINVAL);
169 }
170
171 static int vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
172                                      static_codebook    ***books, 
173                                      vorbis_info_floor1 *in, 
174                                      int *x){
175   int i,k,is=rint(s);
176   vorbis_info_floor1 *f=_ogg_calloc(1,sizeof(*f));
177   codec_setup_info *ci=vi->codec_setup;
178
179   memcpy(f,in+x[is],sizeof(*f));
180   /* fill in the lowpass field, even if it's temporary */
181   f->n=ci->blocksizes[block]>>1;
182
183   /* books */
184   {
185     int partitions=f->partitions;
186     int maxclass=-1;
187     int maxbook=-1;
188     for(i=0;i<partitions;i++)
189       if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
190     for(i=0;i<=maxclass;i++){
191       if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
192       f->class_book[i]+=ci->books;
193       for(k=0;k<(1<<f->class_subs[i]);k++){
194         if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
195         if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
196       }
197     }
198
199     for(i=0;i<=maxbook;i++)
200       ci->book_param[ci->books++]=books[x[is]][i];
201   }
202
203   /* for now, we're only using floor 1 */
204   ci->floor_type[ci->floors]=1;
205   ci->floor_param[ci->floors]=f;
206   ci->floors++;
207
208   return(0);
209 }
210
211 static int vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
212                                             vorbis_info_psy_global *in, 
213                                             double *x){
214   int i,is=s;
215   double ds=s-is;
216   codec_setup_info *ci=vi->codec_setup;
217   vorbis_info_psy_global *g=&ci->psy_g_param;
218   
219   memcpy(g,in+(int)x[is],sizeof(*g));
220   
221   ds=x[is]*(1.-ds)+x[is+1]*ds;
222   is=(int)ds;
223   ds-=is;
224   if(ds==0 && is>0){
225     is--;
226     ds=1.;
227   }
228   
229   /* interpolate the trigger threshholds */
230   for(i=0;i<4;i++){
231     g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
232     g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
233   }
234   g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
235   return(0);
236 }
237
238 static int vorbis_encode_global_stereo(vorbis_info *vi,
239                                        highlevel_encode_setup *hi,
240                                        adj_stereo *p){
241   float s=hi->stereo_point_setting;
242   int i,is=s;
243   double ds=s-is;
244   codec_setup_info *ci=vi->codec_setup;
245   vorbis_info_psy_global *g=&ci->psy_g_param;
246
247   memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
248   memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
249
250   if(hi->managed){
251     /* interpolate the kHz threshholds */
252     for(i=0;i<PACKETBLOBS;i++){
253       float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
254       g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
255       g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
256       g->coupling_pkHz[i]=kHz;
257
258       kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
259       g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
260       g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
261
262     }
263   }else{
264     float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
265     for(i=0;i<PACKETBLOBS;i++){
266       g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
267       g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
268       g->coupling_pkHz[i]=kHz;
269     }
270
271     kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
272     for(i=0;i<PACKETBLOBS;i++){
273       g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
274       g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
275     }
276   }
277
278   return(0);
279 }
280
281 static int vorbis_encode_psyset_setup(vorbis_info *vi,double s,
282                                       int *nn_start,
283                                       int *nn_partition,
284                                       double *nn_thresh,
285                                       int block){
286   codec_setup_info *ci=vi->codec_setup;
287   vorbis_info_psy *p=ci->psy_param[block];
288   highlevel_encode_setup *hi=&ci->hi;
289   int is=s;
290   
291   if(block>=ci->psys)
292     ci->psys=block+1;
293   if(!p){
294     p=_ogg_calloc(1,sizeof(*p));
295     ci->psy_param[block]=p;
296   }
297   
298   memcpy(p,&_psy_info_template,sizeof(*p));
299   p->blockflag=block>>1;
300
301   if(hi->noise_normalize_p){
302     p->normal_channel_p=1;
303     p->normal_point_p=1;
304     p->normal_start=nn_start[is];
305     p->normal_partition=nn_partition[is];
306     p->normal_thresh=nn_thresh[is];
307   }
308     
309   return 0;
310 }
311
312 static int vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
313                                         att3 *att,
314                                         int  *max,
315                                         vp_adjblock *in){
316   int i,is=s;
317   double ds=s-is;
318   codec_setup_info *ci=vi->codec_setup;
319   vorbis_info_psy *p=ci->psy_param[block];
320
321   /* 0 and 2 are only used by bitmanagement, but there's no harm to always
322      filling the values in here */
323   p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
324   p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
325   p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
326   p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
327   p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
328
329   p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
330
331   for(i=0;i<P_BANDS;i++)
332     p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
333   return(0);
334 }
335
336
337 static int vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
338                                        compandblock *in, double *x){
339   int i,is=s;
340   double ds=s-is;
341   codec_setup_info *ci=vi->codec_setup;
342   vorbis_info_psy *p=ci->psy_param[block];
343
344   ds=x[is]*(1.-ds)+x[is+1]*ds;
345   is=(int)ds;
346   ds-=is;
347   if(ds==0 && is>0){
348     is--;
349     ds=1.;
350   }
351
352   /* interpolate the compander settings */
353   for(i=0;i<NOISE_COMPAND_LEVELS;i++)
354     p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
355   return(0);
356 }
357
358 static int vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
359                                     int *suppress){
360   int is=s;
361   double ds=s-is;
362   codec_setup_info *ci=vi->codec_setup;
363   vorbis_info_psy *p=ci->psy_param[block];
364
365   p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
366
367   return(0);
368 }
369
370 static int vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
371                                          int *suppress,
372                                          noise3 *in,
373                                          noiseguard *guard){
374   int i,is=s,j;
375   double ds=s-is;
376   codec_setup_info *ci=vi->codec_setup;
377   vorbis_info_psy *p=ci->psy_param[block];
378
379   p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
380   p->noisewindowlomin=guard[block].lo;
381   p->noisewindowhimin=guard[block].hi;
382   p->noisewindowfixed=guard[block].fixed;
383
384   for(j=0;j<P_NOISECURVES;j++)
385     for(i=0;i<P_BANDS;i++)
386       p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
387
388   return(0);
389 }
390
391 static int vorbis_encode_ath_setup(vorbis_info *vi,int block){
392   codec_setup_info *ci=vi->codec_setup;
393   vorbis_info_psy *p=ci->psy_param[block];
394
395   p->ath_adjatt=ci->hi.ath_floating_dB;
396   p->ath_maxatt=ci->hi.ath_absolute_dB;
397   return(0);
398 }
399
400
401 static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
402   int i;
403   for(i=0;i<ci->books;i++)
404     if(ci->book_param[i]==book)return(i);
405   
406   return(ci->books++);
407 }
408
409 static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
410                                          int *shortb,int *longb){
411
412   codec_setup_info *ci=vi->codec_setup;
413   int is=s;
414   
415   int blockshort=shortb[is];
416   int blocklong=longb[is];
417   ci->blocksizes[0]=blockshort;
418   ci->blocksizes[1]=blocklong;
419
420 }
421
422 static void vorbis_encode_residue_setup(vorbis_info *vi,
423                                        int number, int block,
424                                        vorbis_residue_template *res){
425
426   codec_setup_info *ci=vi->codec_setup;
427   int i,n;
428   
429   vorbis_info_residue0 *r=ci->residue_param[number]=
430     _ogg_malloc(sizeof(*r));
431   
432   memcpy(r,res->res,sizeof(*r));
433   if(ci->residues<=number)ci->residues=number+1;
434
435   switch(ci->blocksizes[block]){
436   case 64:case 128:case 256:case 512:
437     r->grouping=16;
438     break;
439   default:
440     r->grouping=32;
441     break;
442   }
443   ci->residue_type[number]=res->res_type;
444
445   /* to be adjusted by lowpass/pointlimit later */
446   n=r->end=ci->blocksizes[block]>>1; 
447   if(res->res_type==2)
448     n=r->end*=vi->channels;
449   
450   /* fill in all the books */
451   {
452     int booklist=0,k;
453     
454     if(ci->hi.managed){
455       for(i=0;i<r->partitions;i++)
456         for(k=0;k<3;k++)
457           if(res->books_base_managed->books[i][k])
458             r->secondstages[i]|=(1<<k);
459
460       r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
461       ci->book_param[r->groupbook]=res->book_aux_managed;      
462     
463       for(i=0;i<r->partitions;i++){
464         for(k=0;k<3;k++){
465           if(res->books_base_managed->books[i][k]){
466             int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
467             r->booklist[booklist++]=bookid;
468             ci->book_param[bookid]=res->books_base_managed->books[i][k];
469           }
470         }
471       }
472
473     }else{
474
475       for(i=0;i<r->partitions;i++)
476         for(k=0;k<3;k++)
477           if(res->books_base->books[i][k])
478             r->secondstages[i]|=(1<<k);
479   
480       r->groupbook=book_dup_or_new(ci,res->book_aux);
481       ci->book_param[r->groupbook]=res->book_aux;
482       
483       for(i=0;i<r->partitions;i++){
484         for(k=0;k<3;k++){
485           if(res->books_base->books[i][k]){
486             int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
487             r->booklist[booklist++]=bookid;
488             ci->book_param[bookid]=res->books_base->books[i][k];
489           }
490         }
491       }
492     }
493   }
494   
495   /* lowpass setup/pointlimit */
496   {
497     double freq=ci->hi.lowpass_kHz*1000.;
498     vorbis_info_floor1 *f=ci->floor_param[block]; /* by convention */
499     double nyq=vi->rate/2.;
500     long blocksize=ci->blocksizes[block]>>1;
501
502     /* lowpass needs to be set in the floor and the residue. */    
503     if(freq>nyq)freq=nyq;
504     /* in the floor, the granularity can be very fine; it doesn't alter
505        the encoding structure, only the samples used to fit the floor
506        approximation */
507     f->n=freq/nyq*blocksize; 
508
509     /* this res may by limited by the maximum pointlimit of the mode,
510        not the lowpass. the floor is always lowpass limited. */
511     if(res->limit_type){
512       if(ci->hi.managed)
513         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
514       else
515         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
516       if(freq>nyq)freq=nyq;
517     }
518     
519     /* in the residue, we're constrained, physically, by partition
520        boundaries.  We still lowpass 'wherever', but we have to round up
521        here to next boundary, or the vorbis spec will round it *down* to
522        previous boundary in encode/decode */
523     if(ci->residue_type[block]==2)
524       r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
525         r->grouping;
526     else
527       r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
528         r->grouping;
529   }
530 }      
531
532 /* we assume two maps in this encoder */
533 static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
534                                           vorbis_mapping_template *maps){
535
536   codec_setup_info *ci=vi->codec_setup;
537   int i,j,is=s;
538   vorbis_info_mapping0 *map=maps[is].map;
539   vorbis_info_mode *mode=_mode_template;
540   vorbis_residue_template *res=maps[is].res;
541
542   for(i=0;i<2;i++){
543
544     ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
545     ci->mode_param[i]=_ogg_calloc(1,sizeof(*mode));
546   
547     memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
548     if(i>=ci->modes)ci->modes=i+1;
549
550     ci->map_type[i]=0;
551     memcpy(ci->map_param[i],map+i,sizeof(*map));
552     if(i>=ci->maps)ci->maps=i+1;
553     
554     for(j=0;j<map[i].submaps;j++)
555       vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
556                                   ,res+map[i].residuesubmap[j]);
557   }
558 }
559
560 static double setting_to_approx_bitrate(vorbis_info *vi){
561   codec_setup_info *ci=vi->codec_setup;
562   highlevel_encode_setup *hi=&ci->hi;
563   ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
564   int is=hi->base_setting;
565   double ds=hi->base_setting-is;
566   int ch=vi->channels;
567   double *r=setup->rate_mapping;
568
569   if(r==NULL)
570     return(-1);
571   
572   return((r[is]*(1.-ds)+r[is+1]*ds)*ch);  
573 }
574
575 static void get_setup_template(vorbis_info *vi,
576                                long ch,long srate,
577                                double req,int q_or_bitrate){
578   int i=0,j;
579   codec_setup_info *ci=vi->codec_setup;
580   highlevel_encode_setup *hi=&ci->hi;
581   if(q_or_bitrate)req/=ch;
582
583   while(setup_list[i]){
584     if(setup_list[i]->coupling_restriction==-1 ||
585        setup_list[i]->coupling_restriction==ch){
586       if(srate>=setup_list[i]->bitrate_min_restriction &&
587          srate<=setup_list[i]->bitrate_max_restriction){
588         int mappings=setup_list[i]->mappings;
589         double *map=(q_or_bitrate?
590                      setup_list[i]->rate_mapping:
591                      setup_list[i]->quality_mapping);
592
593         /* the template matches.  Does the requested quality mode
594            fall within this template's modes? */
595         if(req<map[0]){++i;continue;}
596         if(req>map[setup_list[i]->mappings]){++i;continue;}
597         for(j=0;j<mappings;j++)
598           if(req>=map[j] && req<map[j+1])break;
599         /* an all-points match */
600         hi->setup=setup_list[i];
601         if(j==mappings)
602           hi->base_setting=j-.001;
603         else{
604           float low=map[j];
605           float high=map[j+1];
606           float del=(req-low)/(high-low);
607           hi->base_setting=j+del;
608         }
609         return;
610       }
611     }
612     i++;
613   }
614   
615   hi->setup=NULL;
616 }
617
618 /* encoders will need to use vorbis_info_init beforehand and call
619    vorbis_info clear when all done */
620
621 /* two interfaces; this, more detailed one, and later a convenience
622    layer on top */
623
624 /* the final setup call */
625 int vorbis_encode_setup_init(vorbis_info *vi){
626   int ret=0,i0=0;
627   codec_setup_info *ci=vi->codec_setup;
628   ve_setup_data_template *setup=NULL;
629   highlevel_encode_setup *hi=&ci->hi;
630
631   if(ci==NULL)return(OV_EINVAL);
632   if(!hi->impulse_block_p)i0=1;
633
634   /* too low/high an ATH floater is nonsensical, but doesn't break anything */
635   if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
636   if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
637
638   /* again, bound this to avoid the app shooting itself int he foot
639      too badly */
640   if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
641   if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
642   
643   /* get the appropriate setup template; matches the fetch in previous
644      stages */
645   setup=(ve_setup_data_template *)hi->setup;
646   if(setup==NULL)return(OV_EINVAL);
647
648   /* choose block sizes from configured sizes as well as paying
649      attention to long_block_p and short_block_p.  If the configured
650      short and long blocks are the same length, we set long_block_p
651      and unset short_block_p */
652   vorbis_encode_blocksize_setup(vi,hi->base_setting,
653                                 setup->blocksize_short,
654                                 setup->blocksize_long);
655   
656   /* floor setup; choose proper floor params.  Allocated on the floor
657      stack in order; if we alloc only long floor, it's 0 */
658   ret|=vorbis_encode_floor_setup(vi,hi->short_setting,0,
659                                  setup->floor_books,
660                                  setup->floor_params,
661                                  setup->floor_short_mapping);
662   ret|=vorbis_encode_floor_setup(vi,hi->long_setting,1,
663                                  setup->floor_books,
664                                  setup->floor_params,
665                                  setup->floor_long_mapping);
666   
667   /* setup of [mostly] short block detection and stereo*/
668   ret|=vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
669                                         setup->global_params,
670                                         setup->global_mapping);
671   ret|=vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
672
673   /* basic psych setup and noise normalization */
674   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
675                                   setup->psy_noise_normal_start[0],
676                                   setup->psy_noise_normal_partition[0],  
677                                   setup->psy_noise_normal_thresh,  
678                                   0);
679   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
680                                   setup->psy_noise_normal_start[0],
681                                   setup->psy_noise_normal_partition[0],  
682                                   setup->psy_noise_normal_thresh,  
683                                   1);
684   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
685                                   setup->psy_noise_normal_start[1],
686                                   setup->psy_noise_normal_partition[1],  
687                                   setup->psy_noise_normal_thresh,  
688                                   2);
689   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
690                                   setup->psy_noise_normal_start[1],
691                                   setup->psy_noise_normal_partition[1],  
692                                   setup->psy_noise_normal_thresh,  
693                                   3);
694
695   /* tone masking setup */
696   ret|=vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
697                                     setup->psy_tone_masteratt,
698                                     setup->psy_tone_0dB,
699                                     setup->psy_tone_adj_impulse);
700   ret|=vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
701                                     setup->psy_tone_masteratt,
702                                     setup->psy_tone_0dB,
703                                     setup->psy_tone_adj_other);
704   ret|=vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
705                                     setup->psy_tone_masteratt,
706                                     setup->psy_tone_0dB,
707                                     setup->psy_tone_adj_other);
708   ret|=vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
709                                     setup->psy_tone_masteratt,
710                                     setup->psy_tone_0dB,
711                                     setup->psy_tone_adj_long);
712
713   /* noise companding setup */
714   ret|=vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
715                                    setup->psy_noise_compand,
716                                    setup->psy_noise_compand_short_mapping);
717   ret|=vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
718                                    setup->psy_noise_compand,
719                                    setup->psy_noise_compand_short_mapping);
720   ret|=vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
721                                    setup->psy_noise_compand,
722                                    setup->psy_noise_compand_long_mapping);
723   ret|=vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
724                                    setup->psy_noise_compand,
725                                    setup->psy_noise_compand_long_mapping);
726
727   /* peak guarding setup  */
728   ret|=vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
729                                 setup->psy_tone_dBsuppress);
730   ret|=vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
731                                 setup->psy_tone_dBsuppress);
732   ret|=vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
733                                 setup->psy_tone_dBsuppress);
734   ret|=vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
735                                 setup->psy_tone_dBsuppress);
736
737   /* noise bias setup */
738   ret|=vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
739                                      setup->psy_noise_dBsuppress,
740                                      setup->psy_noise_bias_impulse,
741                                      setup->psy_noiseguards);
742   ret|=vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
743                                      setup->psy_noise_dBsuppress,
744                                      setup->psy_noise_bias_padding,
745                                      setup->psy_noiseguards);
746   ret|=vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
747                                      setup->psy_noise_dBsuppress,
748                                      setup->psy_noise_bias_trans,
749                                      setup->psy_noiseguards);
750   ret|=vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
751                                      setup->psy_noise_dBsuppress,
752                                      setup->psy_noise_bias_long,
753                                      setup->psy_noiseguards);
754
755   ret|=vorbis_encode_ath_setup(vi,0);
756   ret|=vorbis_encode_ath_setup(vi,1);
757   ret|=vorbis_encode_ath_setup(vi,2);
758   ret|=vorbis_encode_ath_setup(vi,3);
759
760   if(ret){
761     vorbis_info_clear(vi);
762     return ret; 
763   }
764
765   vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
766
767   /* set bitrate readonlies and management */
768   vi->bitrate_nominal=setting_to_approx_bitrate(vi);
769   vi->bitrate_lower=hi->bitrate_min;
770   vi->bitrate_upper=hi->bitrate_max;
771   vi->bitrate_window=hi->bitrate_limit_window;
772
773   if(hi->managed){
774     ci->bi.queue_avg_time=hi->bitrate_av_window;
775     ci->bi.queue_avg_center=hi->bitrate_av_window_center;
776     ci->bi.queue_minmax_time=hi->bitrate_limit_window;
777     ci->bi.queue_hardmin=hi->bitrate_min;
778     ci->bi.queue_hardmax=hi->bitrate_max;
779     ci->bi.queue_avgmin=hi->bitrate_av_lo;
780     ci->bi.queue_avgmax=hi->bitrate_av_hi;
781     ci->bi.avgfloat_downslew_max=-999999.f;
782     ci->bi.avgfloat_upslew_max=999999.f;
783   }
784
785   return(ret);
786   
787 }
788
789 static int vorbis_encode_setup_setting(vorbis_info *vi,
790                                        long  channels,
791                                        long  rate){
792   int ret=0,i,is;
793   codec_setup_info *ci=vi->codec_setup;
794   highlevel_encode_setup *hi=&ci->hi;
795   ve_setup_data_template *setup=hi->setup;
796   double ds;
797
798   ret=vorbis_encode_toplevel_setup(vi,channels,rate);
799   if(ret)return(ret);
800
801   is=hi->base_setting;
802   ds=hi->base_setting-is;
803
804   hi->short_setting=hi->base_setting;
805   hi->long_setting=hi->base_setting;
806
807   hi->managed=0;
808
809   hi->impulse_block_p=1;
810   hi->noise_normalize_p=1;
811
812   hi->stereo_point_setting=hi->base_setting;
813   hi->lowpass_kHz=
814     setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;  
815   
816   hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
817     setup->psy_ath_float[is+1]*ds;
818   hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
819     setup->psy_ath_abs[is+1]*ds;
820
821   hi->amplitude_track_dBpersec=-6.;
822   hi->trigger_setting=hi->base_setting;
823
824   for(i=0;i<4;i++){
825     hi->block[i].tone_mask_setting=hi->base_setting;
826     hi->block[i].tone_peaklimit_setting=hi->base_setting;
827     hi->block[i].noise_bias_setting=hi->base_setting;
828     hi->block[i].noise_compand_setting=hi->base_setting;
829   }
830
831   return(ret);
832 }
833
834 int vorbis_encode_setup_vbr(vorbis_info *vi,
835                             long  channels,
836                             long  rate,                     
837                             float quality){
838   codec_setup_info *ci=vi->codec_setup;
839   highlevel_encode_setup *hi=&ci->hi;
840
841   get_setup_template(vi,channels,rate,quality,0);
842   if(!hi->setup)return OV_EIMPL;
843   
844   return vorbis_encode_setup_setting(vi,channels,rate);
845 }
846
847 int vorbis_encode_init_vbr(vorbis_info *vi,
848                            long channels,
849                            long rate,
850                            
851                            float base_quality /* 0. to 1. */
852                            ){
853   int ret=0;
854
855   ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
856   
857   if(ret){
858     vorbis_info_clear(vi);
859     return ret; 
860   }
861   ret=vorbis_encode_setup_init(vi);
862   if(ret)
863     vorbis_info_clear(vi);
864   return(ret);
865 }
866
867 int vorbis_encode_setup_managed(vorbis_info *vi,
868                                 long channels,
869                                 long rate,
870                                 
871                                 long max_bitrate,
872                                 long nominal_bitrate,
873                                 long min_bitrate){
874
875   codec_setup_info *ci=vi->codec_setup;
876   highlevel_encode_setup *hi=&ci->hi;
877   double tnominal=nominal_bitrate;
878   int ret=0;
879
880   if(nominal_bitrate<=0.){
881     if(max_bitrate>0.){
882       nominal_bitrate=max_bitrate*.875;
883     }else{
884       if(min_bitrate>0.){
885         nominal_bitrate=min_bitrate;
886       }else{
887         return(OV_EINVAL);
888       }
889     }
890   }
891
892   get_setup_template(vi,channels,rate,nominal_bitrate,1);
893   if(!hi->setup)return OV_EIMPL;
894   
895   ret=vorbis_encode_setup_setting(vi,channels,rate);
896   if(ret){
897     vorbis_info_clear(vi);
898     return ret; 
899   }
900
901   /* initialize management with sane defaults */
902   ci->hi.managed=1;
903
904   ci->hi.bitrate_av_window=4.;
905   ci->hi.bitrate_av_window_center=.5;
906   ci->hi.bitrate_limit_window=2.;
907   ci->hi.bitrate_min=min_bitrate;
908   ci->hi.bitrate_max=max_bitrate;
909   ci->hi.bitrate_av_lo=tnominal;
910   ci->hi.bitrate_av_hi=tnominal;
911
912   return(ret);
913 }
914
915 int vorbis_encode_init(vorbis_info *vi,
916                        long channels,
917                        long rate,
918
919                        long max_bitrate,
920                        long nominal_bitrate,
921                        long min_bitrate){
922
923   int ret=vorbis_encode_setup_managed(vi,channels,rate,
924                                       max_bitrate,
925                                       nominal_bitrate,
926                                       min_bitrate);
927   if(ret){
928     vorbis_info_clear(vi);
929     return(ret);
930   }
931
932   ret=vorbis_encode_setup_init(vi);
933   if(ret)
934     vorbis_info_clear(vi);
935   return(ret);
936 }
937
938 int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
939   return(OV_EIMPL);
940 }