cd3cd8cc33f66fdab6f4a599603a69dce9b33205
[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.40 2002/06/28 22:19:37 xiphmont 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
148
149   0
150 };
151
152
153 /* a few static coder conventions */
154 static vorbis_info_mode _mode_template[2]={
155   {0,0,0,0},
156   {1,0,0,1}
157 };
158
159
160 static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
161   if(vi && vi->codec_setup){
162
163     vi->version=0;
164     vi->channels=ch;
165     vi->rate=rate;
166
167     return(0);
168   }
169   return(OV_EINVAL);
170 }
171
172 static int vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
173                                      static_codebook    ***books, 
174                                      vorbis_info_floor1 *in, 
175                                      int *x){
176   int i,k,is=rint(s);
177   vorbis_info_floor1 *f=_ogg_calloc(1,sizeof(*f));
178   codec_setup_info *ci=vi->codec_setup;
179
180   memcpy(f,in+x[is],sizeof(*f));
181   /* fill in the lowpass field, even if it's temporary */
182   f->n=ci->blocksizes[block]>>1;
183
184   /* books */
185   {
186     int partitions=f->partitions;
187     int maxclass=-1;
188     int maxbook=-1;
189     for(i=0;i<partitions;i++)
190       if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
191     for(i=0;i<=maxclass;i++){
192       if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
193       f->class_book[i]+=ci->books;
194       for(k=0;k<(1<<f->class_subs[i]);k++){
195         if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
196         if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
197       }
198     }
199
200     for(i=0;i<=maxbook;i++)
201       ci->book_param[ci->books++]=books[x[is]][i];
202   }
203
204   /* for now, we're only using floor 1 */
205   ci->floor_type[ci->floors]=1;
206   ci->floor_param[ci->floors]=f;
207   ci->floors++;
208
209   return(0);
210 }
211
212 static int vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
213                                             vorbis_info_psy_global *in, 
214                                             double *x){
215   int i,is=s;
216   double ds=s-is;
217   codec_setup_info *ci=vi->codec_setup;
218   vorbis_info_psy_global *g=&ci->psy_g_param;
219   
220   memcpy(g,in+(int)x[is],sizeof(*g));
221   
222   ds=x[is]*(1.-ds)+x[is+1]*ds;
223   is=(int)ds;
224   ds-=is;
225   if(ds==0 && is>0){
226     is--;
227     ds=1.;
228   }
229   
230   /* interpolate the trigger threshholds */
231   for(i=0;i<4;i++){
232     g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
233     g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
234   }
235   g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
236   return(0);
237 }
238
239 static int vorbis_encode_global_stereo(vorbis_info *vi,
240                                        highlevel_encode_setup *hi,
241                                        adj_stereo *p){
242   float s=hi->stereo_point_setting;
243   int i,is=s;
244   double ds=s-is;
245   codec_setup_info *ci=vi->codec_setup;
246   vorbis_info_psy_global *g=&ci->psy_g_param;
247
248   memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
249   memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
250
251   if(hi->managed){
252     /* interpolate the kHz threshholds */
253     for(i=0;i<PACKETBLOBS;i++){
254       float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
255       g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
256       g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
257       g->coupling_pkHz[i]=kHz;
258
259       kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
260       g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
261       g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
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
582   while(setup_list[i]){
583     if(setup_list[i]->coupling_restriction==-1 ||
584        setup_list[i]->coupling_restriction==ch){
585       if(srate>=setup_list[i]->bitrate_min_restriction &&
586          srate<=setup_list[i]->bitrate_max_restriction){
587         int mappings=setup_list[i]->mappings;
588         double *map=(q_or_bitrate?
589                      setup_list[i]->rate_mapping:
590                      setup_list[i]->quality_mapping);
591         if(q_or_bitrate)req/=ch;
592
593         /* the template matches.  Does the requested quality mode
594            fall within this template's modes? */
595         if(req<map[0])continue;
596         if(req>map[setup_list[i]->mappings])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   }
613   
614   hi->setup=NULL;
615 }
616
617 /* encoders will need to use vorbis_info_init beforehand and call
618    vorbis_info clear when all done */
619
620 /* two interfaces; this, more detailed one, and later a convenience
621    layer on top */
622
623 /* the final setup call */
624 int vorbis_encode_setup_init(vorbis_info *vi){
625   int ret=0,i0=0;
626   codec_setup_info *ci=vi->codec_setup;
627   ve_setup_data_template *setup=NULL;
628   highlevel_encode_setup *hi=&ci->hi;
629
630   if(ci==NULL)return(OV_EINVAL);
631   if(!hi->impulse_block_p)i0=1;
632
633   /* too low/high an ATH floater is nonsensical, but doesn't break anything */
634   if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
635   if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
636
637   /* again, bound this to avoid the app shooting itself int he foot
638      too badly */
639   if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
640   if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
641   
642   /* get the appropriate setup template; matches the fetch in previous
643      stages */
644   setup=(ve_setup_data_template *)hi->setup;
645   if(setup==NULL)return(OV_EINVAL);
646
647   /* choose block sizes from configured sizes as well as paying
648      attention to long_block_p and short_block_p.  If the configured
649      short and long blocks are the same length, we set long_block_p
650      and unset short_block_p */
651   vorbis_encode_blocksize_setup(vi,hi->base_setting,
652                                 setup->blocksize_short,
653                                 setup->blocksize_long);
654   
655   /* floor setup; choose proper floor params.  Allocated on the floor
656      stack in order; if we alloc only long floor, it's 0 */
657   ret|=vorbis_encode_floor_setup(vi,hi->short_setting,0,
658                                  setup->floor_books,
659                                  setup->floor_params,
660                                  setup->floor_short_mapping);
661   ret|=vorbis_encode_floor_setup(vi,hi->long_setting,1,
662                                  setup->floor_books,
663                                  setup->floor_params,
664                                  setup->floor_long_mapping);
665   
666   /* setup of [mostly] short block detection and stereo*/
667   ret|=vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
668                                         setup->global_params,
669                                         setup->global_mapping);
670   ret|=vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
671
672   /* basic psych setup and noise normalization */
673   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
674                                   setup->psy_noise_normal_start[0],
675                                   setup->psy_noise_normal_partition[0],  
676                                   setup->psy_noise_normal_thresh,  
677                                   0);
678   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
679                                   setup->psy_noise_normal_start[0],
680                                   setup->psy_noise_normal_partition[0],  
681                                   setup->psy_noise_normal_thresh,  
682                                   1);
683   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
684                                   setup->psy_noise_normal_start[1],
685                                   setup->psy_noise_normal_partition[1],  
686                                   setup->psy_noise_normal_thresh,  
687                                   2);
688   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
689                                   setup->psy_noise_normal_start[1],
690                                   setup->psy_noise_normal_partition[1],  
691                                   setup->psy_noise_normal_thresh,  
692                                   3);
693
694   /* tone masking setup */
695   ret|=vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
696                                     setup->psy_tone_masteratt,
697                                     setup->psy_tone_0dB,
698                                     setup->psy_tone_adj_impulse);
699   ret|=vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
700                                     setup->psy_tone_masteratt,
701                                     setup->psy_tone_0dB,
702                                     setup->psy_tone_adj_other);
703   ret|=vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
704                                     setup->psy_tone_masteratt,
705                                     setup->psy_tone_0dB,
706                                     setup->psy_tone_adj_other);
707   ret|=vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
708                                     setup->psy_tone_masteratt,
709                                     setup->psy_tone_0dB,
710                                     setup->psy_tone_adj_long);
711
712   /* noise companding setup */
713   ret|=vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
714                                    setup->psy_noise_compand,
715                                    setup->psy_noise_compand_short_mapping);
716   ret|=vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
717                                    setup->psy_noise_compand,
718                                    setup->psy_noise_compand_short_mapping);
719   ret|=vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
720                                    setup->psy_noise_compand,
721                                    setup->psy_noise_compand_long_mapping);
722   ret|=vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
723                                    setup->psy_noise_compand,
724                                    setup->psy_noise_compand_long_mapping);
725
726   /* peak guarding setup  */
727   ret|=vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
728                                 setup->psy_tone_dBsuppress);
729   ret|=vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
730                                 setup->psy_tone_dBsuppress);
731   ret|=vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
732                                 setup->psy_tone_dBsuppress);
733   ret|=vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
734                                 setup->psy_tone_dBsuppress);
735
736   /* noise bias setup */
737   ret|=vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
738                                      setup->psy_noise_dBsuppress,
739                                      setup->psy_noise_bias_impulse,
740                                      setup->psy_noiseguards);
741   ret|=vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
742                                      setup->psy_noise_dBsuppress,
743                                      setup->psy_noise_bias_padding,
744                                      setup->psy_noiseguards);
745   ret|=vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
746                                      setup->psy_noise_dBsuppress,
747                                      setup->psy_noise_bias_trans,
748                                      setup->psy_noiseguards);
749   ret|=vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
750                                      setup->psy_noise_dBsuppress,
751                                      setup->psy_noise_bias_long,
752                                      setup->psy_noiseguards);
753
754   ret|=vorbis_encode_ath_setup(vi,0);
755   ret|=vorbis_encode_ath_setup(vi,1);
756   ret|=vorbis_encode_ath_setup(vi,2);
757   ret|=vorbis_encode_ath_setup(vi,3);
758
759   if(ret){
760     vorbis_info_clear(vi);
761     return ret; 
762   }
763
764   vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
765
766   /* set bitrate readonlies and management */
767   vi->bitrate_nominal=setting_to_approx_bitrate(vi);
768   vi->bitrate_lower=hi->bitrate_min;
769   vi->bitrate_upper=hi->bitrate_max;
770   vi->bitrate_window=hi->bitrate_limit_window;
771
772   if(hi->managed){
773     ci->bi.queue_avg_time=hi->bitrate_av_window;
774     ci->bi.queue_avg_center=hi->bitrate_av_window_center;
775     ci->bi.queue_minmax_time=hi->bitrate_limit_window;
776     ci->bi.queue_hardmin=hi->bitrate_min;
777     ci->bi.queue_hardmax=hi->bitrate_max;
778     ci->bi.queue_avgmin=hi->bitrate_av_lo;
779     ci->bi.queue_avgmax=hi->bitrate_av_hi;
780     ci->bi.avgfloat_downslew_max=-999999.f;
781     ci->bi.avgfloat_upslew_max=999999.f;
782   }
783
784   return(ret);
785   
786 }
787
788 static int vorbis_encode_setup_setting(vorbis_info *vi,
789                                        long  channels,
790                                        long  rate){
791   int ret=0,i,is;
792   codec_setup_info *ci=vi->codec_setup;
793   highlevel_encode_setup *hi=&ci->hi;
794   ve_setup_data_template *setup=hi->setup;
795   double ds;
796
797   ret=vorbis_encode_toplevel_setup(vi,channels,rate);
798   if(ret)return(ret);
799
800   is=hi->base_setting;
801   ds=hi->base_setting-is;
802
803   hi->short_setting=hi->base_setting;
804   hi->long_setting=hi->base_setting;
805
806   hi->managed=0;
807
808   hi->impulse_block_p=1;
809   hi->noise_normalize_p=1;
810
811   hi->stereo_point_setting=hi->base_setting;
812   hi->lowpass_kHz=
813     setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;  
814   
815   hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
816     setup->psy_ath_float[is+1]*ds;
817   hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
818     setup->psy_ath_abs[is+1]*ds;
819
820   hi->amplitude_track_dBpersec=-6.;
821   hi->trigger_setting=hi->base_setting;
822
823   for(i=0;i<4;i++){
824     hi->block[i].tone_mask_setting=hi->base_setting;
825     hi->block[i].tone_peaklimit_setting=hi->base_setting;
826     hi->block[i].noise_bias_setting=hi->base_setting;
827     hi->block[i].noise_compand_setting=hi->base_setting;
828   }
829
830   return(ret);
831 }
832
833 int vorbis_encode_setup_vbr(vorbis_info *vi,
834                             long  channels,
835                             long  rate,                     
836                             float quality){
837   codec_setup_info *ci=vi->codec_setup;
838   highlevel_encode_setup *hi=&ci->hi;
839
840   get_setup_template(vi,channels,rate,quality,0);
841   if(!hi->setup)return OV_EIMPL;
842   
843   return vorbis_encode_setup_setting(vi,channels,rate);
844 }
845
846 int vorbis_encode_init_vbr(vorbis_info *vi,
847                            long channels,
848                            long rate,
849                            
850                            float base_quality /* 0. to 1. */
851                            ){
852   int ret=0;
853
854   ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
855   
856   if(ret){
857     vorbis_info_clear(vi);
858     return ret; 
859   }
860   ret=vorbis_encode_setup_init(vi);
861   if(ret)
862     vorbis_info_clear(vi);
863   return(ret);
864 }
865
866 int vorbis_encode_setup_managed(vorbis_info *vi,
867                                 long channels,
868                                 long rate,
869                                 
870                                 long max_bitrate,
871                                 long nominal_bitrate,
872                                 long min_bitrate){
873
874   codec_setup_info *ci=vi->codec_setup;
875   highlevel_encode_setup *hi=&ci->hi;
876   double tnominal=nominal_bitrate;
877   int ret=0;
878
879   if(nominal_bitrate<=0.){
880     if(max_bitrate>0.){
881       nominal_bitrate=max_bitrate*.875;
882     }else{
883       if(min_bitrate>0.){
884         nominal_bitrate=min_bitrate;
885       }else{
886         return(OV_EINVAL);
887       }
888     }
889   }
890
891   get_setup_template(vi,channels,rate,nominal_bitrate,1);
892   if(!hi->setup)return OV_EIMPL;
893   
894   ret=vorbis_encode_setup_setting(vi,channels,rate);
895   if(ret){
896     vorbis_info_clear(vi);
897     return ret; 
898   }
899
900   /* initialize management with sane defaults */
901   ci->hi.managed=1;
902
903   ci->hi.bitrate_av_window=4.;
904   ci->hi.bitrate_av_window_center=.5;
905   ci->hi.bitrate_limit_window=2.;
906   ci->hi.bitrate_min=min_bitrate;
907   ci->hi.bitrate_max=max_bitrate;
908   ci->hi.bitrate_av_lo=tnominal;
909   ci->hi.bitrate_av_hi=tnominal;
910
911   return(ret);
912 }
913
914 int vorbis_encode_init(vorbis_info *vi,
915                        long channels,
916                        long rate,
917
918                        long max_bitrate,
919                        long nominal_bitrate,
920                        long min_bitrate){
921
922   int ret=vorbis_encode_setup_managed(vi,channels,rate,
923                                       max_bitrate,
924                                       nominal_bitrate,
925                                       min_bitrate);
926   if(ret){
927     vorbis_info_clear(vi);
928     return(ret);
929   }
930
931   ret=vorbis_encode_setup_init(vi);
932   if(ret)
933     vorbis_info_clear(vi);
934   return(ret);
935 }
936
937 int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
938   return(OV_EIMPL);
939 }