new ectl calls for lowpass and impulse block tweaking
[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.44 2002/07/01 11:20:11 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     samplerate_min_restriction;
97   long     samplerate_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 #include "modes/setup_44u.h"
145
146 static ve_setup_data_template *setup_list[]={
147   &ve_setup_44_stereo,
148   &ve_setup_44_stereo_low,
149   &ve_setup_44_uncoupled,
150   &ve_setup_44_uncoupled_low,
151   0
152 };
153
154
155 /* a few static coder conventions */
156 static vorbis_info_mode _mode_template[2]={
157   {0,0,0,0},
158   {1,0,0,1}
159 };
160
161
162 static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
163   if(vi && vi->codec_setup){
164
165     vi->version=0;
166     vi->channels=ch;
167     vi->rate=rate;
168
169     return(0);
170   }
171   return(OV_EINVAL);
172 }
173
174 static int vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
175                                      static_codebook    ***books, 
176                                      vorbis_info_floor1 *in, 
177                                      int *x){
178   int i,k,is=rint(s);
179   vorbis_info_floor1 *f=_ogg_calloc(1,sizeof(*f));
180   codec_setup_info *ci=vi->codec_setup;
181
182   memcpy(f,in+x[is],sizeof(*f));
183   /* fill in the lowpass field, even if it's temporary */
184   f->n=ci->blocksizes[block]>>1;
185
186   /* books */
187   {
188     int partitions=f->partitions;
189     int maxclass=-1;
190     int maxbook=-1;
191     for(i=0;i<partitions;i++)
192       if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
193     for(i=0;i<=maxclass;i++){
194       if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
195       f->class_book[i]+=ci->books;
196       for(k=0;k<(1<<f->class_subs[i]);k++){
197         if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
198         if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
199       }
200     }
201
202     for(i=0;i<=maxbook;i++)
203       ci->book_param[ci->books++]=books[x[is]][i];
204   }
205
206   /* for now, we're only using floor 1 */
207   ci->floor_type[ci->floors]=1;
208   ci->floor_param[ci->floors]=f;
209   ci->floors++;
210
211   return(0);
212 }
213
214 static int vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
215                                             vorbis_info_psy_global *in, 
216                                             double *x){
217   int i,is=s;
218   double ds=s-is;
219   codec_setup_info *ci=vi->codec_setup;
220   vorbis_info_psy_global *g=&ci->psy_g_param;
221   
222   memcpy(g,in+(int)x[is],sizeof(*g));
223   
224   ds=x[is]*(1.-ds)+x[is+1]*ds;
225   is=(int)ds;
226   ds-=is;
227   if(ds==0 && is>0){
228     is--;
229     ds=1.;
230   }
231   
232   /* interpolate the trigger threshholds */
233   for(i=0;i<4;i++){
234     g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
235     g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
236   }
237   g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
238   return(0);
239 }
240
241 static int vorbis_encode_global_stereo(vorbis_info *vi,
242                                        highlevel_encode_setup *hi,
243                                        adj_stereo *p){
244   float s=hi->stereo_point_setting;
245   int i,is=s;
246   double ds=s-is;
247   codec_setup_info *ci=vi->codec_setup;
248   vorbis_info_psy_global *g=&ci->psy_g_param;
249
250   if(p){
251     memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
252     memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
253
254     if(hi->managed){
255       /* interpolate the kHz threshholds */
256       for(i=0;i<PACKETBLOBS;i++){
257         float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
258         g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
259         g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
260         g->coupling_pkHz[i]=kHz;
261         
262         kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
263         g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
264         g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
265         
266       }
267     }else{
268       float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
269       for(i=0;i<PACKETBLOBS;i++){
270         g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
271         g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
272         g->coupling_pkHz[i]=kHz;
273       }
274       
275       kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
276       for(i=0;i<PACKETBLOBS;i++){
277         g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
278         g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
279       }
280     }
281   }else{
282     for(i=0;i<PACKETBLOBS;i++){
283       g->sliding_lowpass[0][i]=ci->blocksizes[0];
284       g->sliding_lowpass[1][i]=ci->blocksizes[1];
285     }
286   }
287   return(0);
288 }
289
290 static int vorbis_encode_psyset_setup(vorbis_info *vi,double s,
291                                       int *nn_start,
292                                       int *nn_partition,
293                                       double *nn_thresh,
294                                       int block){
295   codec_setup_info *ci=vi->codec_setup;
296   vorbis_info_psy *p=ci->psy_param[block];
297   highlevel_encode_setup *hi=&ci->hi;
298   int is=s;
299   
300   if(block>=ci->psys)
301     ci->psys=block+1;
302   if(!p){
303     p=_ogg_calloc(1,sizeof(*p));
304     ci->psy_param[block]=p;
305   }
306   
307   memcpy(p,&_psy_info_template,sizeof(*p));
308   p->blockflag=block>>1;
309
310   if(hi->noise_normalize_p){
311     p->normal_channel_p=1;
312     p->normal_point_p=1;
313     p->normal_start=nn_start[is];
314     p->normal_partition=nn_partition[is];
315     p->normal_thresh=nn_thresh[is];
316   }
317     
318   return 0;
319 }
320
321 static int vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
322                                         att3 *att,
323                                         int  *max,
324                                         vp_adjblock *in){
325   int i,is=s;
326   double ds=s-is;
327   codec_setup_info *ci=vi->codec_setup;
328   vorbis_info_psy *p=ci->psy_param[block];
329
330   /* 0 and 2 are only used by bitmanagement, but there's no harm to always
331      filling the values in here */
332   p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
333   p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
334   p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
335   p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
336   p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
337
338   p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
339
340   for(i=0;i<P_BANDS;i++)
341     p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
342   return(0);
343 }
344
345
346 static int vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
347                                        compandblock *in, double *x){
348   int i,is=s;
349   double ds=s-is;
350   codec_setup_info *ci=vi->codec_setup;
351   vorbis_info_psy *p=ci->psy_param[block];
352
353   ds=x[is]*(1.-ds)+x[is+1]*ds;
354   is=(int)ds;
355   ds-=is;
356   if(ds==0 && is>0){
357     is--;
358     ds=1.;
359   }
360
361   /* interpolate the compander settings */
362   for(i=0;i<NOISE_COMPAND_LEVELS;i++)
363     p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
364   return(0);
365 }
366
367 static int vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
368                                     int *suppress){
369   int is=s;
370   double ds=s-is;
371   codec_setup_info *ci=vi->codec_setup;
372   vorbis_info_psy *p=ci->psy_param[block];
373
374   p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
375
376   return(0);
377 }
378
379 static int vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
380                                          int *suppress,
381                                          noise3 *in,
382                                          noiseguard *guard,
383                                          double userbias){
384   int i,is=s,j;
385   double ds=s-is;
386   codec_setup_info *ci=vi->codec_setup;
387   vorbis_info_psy *p=ci->psy_param[block];
388
389   p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
390   p->noisewindowlomin=guard[block].lo;
391   p->noisewindowhimin=guard[block].hi;
392   p->noisewindowfixed=guard[block].fixed;
393
394   for(j=0;j<P_NOISECURVES;j++)
395     for(i=0;i<P_BANDS;i++)
396       p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
397
398   /* impulse blocks may take a user specified bias to boost the
399      nominal/high noise encoding depth */
400   for(j=0;j<P_NOISECURVES;j++){
401     float min=p->noiseoff[j][0]+6; /* the lowest it can go */
402     for(i=0;i<P_BANDS;i++){
403       p->noiseoff[j][i]+=userbias;
404       if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
405     }
406   }
407
408   return(0);
409 }
410
411 static int vorbis_encode_ath_setup(vorbis_info *vi,int block){
412   codec_setup_info *ci=vi->codec_setup;
413   vorbis_info_psy *p=ci->psy_param[block];
414
415   p->ath_adjatt=ci->hi.ath_floating_dB;
416   p->ath_maxatt=ci->hi.ath_absolute_dB;
417   return(0);
418 }
419
420
421 static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
422   int i;
423   for(i=0;i<ci->books;i++)
424     if(ci->book_param[i]==book)return(i);
425   
426   return(ci->books++);
427 }
428
429 static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
430                                          int *shortb,int *longb){
431
432   codec_setup_info *ci=vi->codec_setup;
433   int is=s;
434   
435   int blockshort=shortb[is];
436   int blocklong=longb[is];
437   ci->blocksizes[0]=blockshort;
438   ci->blocksizes[1]=blocklong;
439
440 }
441
442 static void vorbis_encode_residue_setup(vorbis_info *vi,
443                                        int number, int block,
444                                        vorbis_residue_template *res){
445
446   codec_setup_info *ci=vi->codec_setup;
447   int i,n;
448   
449   vorbis_info_residue0 *r=ci->residue_param[number]=
450     _ogg_malloc(sizeof(*r));
451   
452   memcpy(r,res->res,sizeof(*r));
453   if(ci->residues<=number)ci->residues=number+1;
454
455   switch(ci->blocksizes[block]){
456   case 64:case 128:case 256:case 512:
457     r->grouping=16;
458     break;
459   default:
460     r->grouping=32;
461     break;
462   }
463   ci->residue_type[number]=res->res_type;
464
465   /* to be adjusted by lowpass/pointlimit later */
466   n=r->end=ci->blocksizes[block]>>1; 
467   if(res->res_type==2)
468     n=r->end*=vi->channels;
469   
470   /* fill in all the books */
471   {
472     int booklist=0,k;
473     
474     if(ci->hi.managed){
475       for(i=0;i<r->partitions;i++)
476         for(k=0;k<3;k++)
477           if(res->books_base_managed->books[i][k])
478             r->secondstages[i]|=(1<<k);
479
480       r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
481       ci->book_param[r->groupbook]=res->book_aux_managed;      
482     
483       for(i=0;i<r->partitions;i++){
484         for(k=0;k<3;k++){
485           if(res->books_base_managed->books[i][k]){
486             int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
487             r->booklist[booklist++]=bookid;
488             ci->book_param[bookid]=res->books_base_managed->books[i][k];
489           }
490         }
491       }
492
493     }else{
494
495       for(i=0;i<r->partitions;i++)
496         for(k=0;k<3;k++)
497           if(res->books_base->books[i][k])
498             r->secondstages[i]|=(1<<k);
499   
500       r->groupbook=book_dup_or_new(ci,res->book_aux);
501       ci->book_param[r->groupbook]=res->book_aux;
502       
503       for(i=0;i<r->partitions;i++){
504         for(k=0;k<3;k++){
505           if(res->books_base->books[i][k]){
506             int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
507             r->booklist[booklist++]=bookid;
508             ci->book_param[bookid]=res->books_base->books[i][k];
509           }
510         }
511       }
512     }
513   }
514   
515   /* lowpass setup/pointlimit */
516   {
517     double freq=ci->hi.lowpass_kHz*1000.;
518     vorbis_info_floor1 *f=ci->floor_param[block]; /* by convention */
519     double nyq=vi->rate/2.;
520     long blocksize=ci->blocksizes[block]>>1;
521
522     /* lowpass needs to be set in the floor and the residue. */    
523     if(freq>nyq)freq=nyq;
524     /* in the floor, the granularity can be very fine; it doesn't alter
525        the encoding structure, only the samples used to fit the floor
526        approximation */
527     f->n=freq/nyq*blocksize; 
528
529     /* this res may by limited by the maximum pointlimit of the mode,
530        not the lowpass. the floor is always lowpass limited. */
531     if(res->limit_type){
532       if(ci->hi.managed)
533         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
534       else
535         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
536       if(freq>nyq)freq=nyq;
537     }
538     
539     /* in the residue, we're constrained, physically, by partition
540        boundaries.  We still lowpass 'wherever', but we have to round up
541        here to next boundary, or the vorbis spec will round it *down* to
542        previous boundary in encode/decode */
543     if(ci->residue_type[block]==2)
544       r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
545         r->grouping;
546     else
547       r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
548         r->grouping;
549   }
550 }      
551
552 /* we assume two maps in this encoder */
553 static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
554                                           vorbis_mapping_template *maps){
555
556   codec_setup_info *ci=vi->codec_setup;
557   int i,j,is=s;
558   vorbis_info_mapping0 *map=maps[is].map;
559   vorbis_info_mode *mode=_mode_template;
560   vorbis_residue_template *res=maps[is].res;
561
562   for(i=0;i<2;i++){
563
564     ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
565     ci->mode_param[i]=_ogg_calloc(1,sizeof(*mode));
566   
567     memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
568     if(i>=ci->modes)ci->modes=i+1;
569
570     ci->map_type[i]=0;
571     memcpy(ci->map_param[i],map+i,sizeof(*map));
572     if(i>=ci->maps)ci->maps=i+1;
573     
574     for(j=0;j<map[i].submaps;j++)
575       vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
576                                   ,res+map[i].residuesubmap[j]);
577   }
578 }
579
580 static double setting_to_approx_bitrate(vorbis_info *vi){
581   codec_setup_info *ci=vi->codec_setup;
582   highlevel_encode_setup *hi=&ci->hi;
583   ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
584   int is=hi->base_setting;
585   double ds=hi->base_setting-is;
586   int ch=vi->channels;
587   double *r=setup->rate_mapping;
588
589   if(r==NULL)
590     return(-1);
591   
592   return((r[is]*(1.-ds)+r[is+1]*ds)*ch);  
593 }
594
595 static void get_setup_template(vorbis_info *vi,
596                                long ch,long srate,
597                                double req,int q_or_bitrate){
598   int i=0,j;
599   codec_setup_info *ci=vi->codec_setup;
600   highlevel_encode_setup *hi=&ci->hi;
601   if(q_or_bitrate)req/=ch;
602
603   while(setup_list[i]){
604     if(setup_list[i]->coupling_restriction==-1 ||
605        setup_list[i]->coupling_restriction==ch){
606       if(srate>=setup_list[i]->samplerate_min_restriction &&
607          srate<=setup_list[i]->samplerate_max_restriction){
608         int mappings=setup_list[i]->mappings;
609         double *map=(q_or_bitrate?
610                      setup_list[i]->rate_mapping:
611                      setup_list[i]->quality_mapping);
612
613         /* the template matches.  Does the requested quality mode
614            fall within this template's modes? */
615         if(req<map[0]){++i;continue;}
616         if(req>map[setup_list[i]->mappings]){++i;continue;}
617         for(j=0;j<mappings;j++)
618           if(req>=map[j] && req<map[j+1])break;
619         /* an all-points match */
620         hi->setup=setup_list[i];
621         if(j==mappings)
622           hi->base_setting=j-.001;
623         else{
624           float low=map[j];
625           float high=map[j+1];
626           float del=(req-low)/(high-low);
627           hi->base_setting=j+del;
628         }
629         return;
630       }
631     }
632     i++;
633   }
634   
635   hi->setup=NULL;
636 }
637
638 /* encoders will need to use vorbis_info_init beforehand and call
639    vorbis_info clear when all done */
640
641 /* two interfaces; this, more detailed one, and later a convenience
642    layer on top */
643
644 /* the final setup call */
645 int vorbis_encode_setup_init(vorbis_info *vi){
646   int ret=0,i0=0;
647   codec_setup_info *ci=vi->codec_setup;
648   ve_setup_data_template *setup=NULL;
649   highlevel_encode_setup *hi=&ci->hi;
650
651   if(ci==NULL)return(OV_EINVAL);
652   if(!hi->impulse_block_p)i0=1;
653
654   /* too low/high an ATH floater is nonsensical, but doesn't break anything */
655   if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
656   if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
657
658   /* again, bound this to avoid the app shooting itself int he foot
659      too badly */
660   if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
661   if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
662   
663   /* get the appropriate setup template; matches the fetch in previous
664      stages */
665   setup=(ve_setup_data_template *)hi->setup;
666   if(setup==NULL)return(OV_EINVAL);
667
668   hi->set_in_stone=1;
669   /* choose block sizes from configured sizes as well as paying
670      attention to long_block_p and short_block_p.  If the configured
671      short and long blocks are the same length, we set long_block_p
672      and unset short_block_p */
673   vorbis_encode_blocksize_setup(vi,hi->base_setting,
674                                 setup->blocksize_short,
675                                 setup->blocksize_long);
676   
677   /* floor setup; choose proper floor params.  Allocated on the floor
678      stack in order; if we alloc only long floor, it's 0 */
679   ret|=vorbis_encode_floor_setup(vi,hi->short_setting,0,
680                                  setup->floor_books,
681                                  setup->floor_params,
682                                  setup->floor_short_mapping);
683   ret|=vorbis_encode_floor_setup(vi,hi->long_setting,1,
684                                  setup->floor_books,
685                                  setup->floor_params,
686                                  setup->floor_long_mapping);
687   
688   /* setup of [mostly] short block detection and stereo*/
689   ret|=vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
690                                         setup->global_params,
691                                         setup->global_mapping);
692   ret|=vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
693
694   /* basic psych setup and noise normalization */
695   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
696                                   setup->psy_noise_normal_start[0],
697                                   setup->psy_noise_normal_partition[0],  
698                                   setup->psy_noise_normal_thresh,  
699                                   0);
700   ret|=vorbis_encode_psyset_setup(vi,hi->short_setting,
701                                   setup->psy_noise_normal_start[0],
702                                   setup->psy_noise_normal_partition[0],  
703                                   setup->psy_noise_normal_thresh,  
704                                   1);
705   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
706                                   setup->psy_noise_normal_start[1],
707                                   setup->psy_noise_normal_partition[1],  
708                                   setup->psy_noise_normal_thresh,  
709                                   2);
710   ret|=vorbis_encode_psyset_setup(vi,hi->long_setting,
711                                   setup->psy_noise_normal_start[1],
712                                   setup->psy_noise_normal_partition[1],  
713                                   setup->psy_noise_normal_thresh,  
714                                   3);
715
716   /* tone masking setup */
717   ret|=vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
718                                     setup->psy_tone_masteratt,
719                                     setup->psy_tone_0dB,
720                                     setup->psy_tone_adj_impulse);
721   ret|=vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
722                                     setup->psy_tone_masteratt,
723                                     setup->psy_tone_0dB,
724                                     setup->psy_tone_adj_other);
725   ret|=vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
726                                     setup->psy_tone_masteratt,
727                                     setup->psy_tone_0dB,
728                                     setup->psy_tone_adj_other);
729   ret|=vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
730                                     setup->psy_tone_masteratt,
731                                     setup->psy_tone_0dB,
732                                     setup->psy_tone_adj_long);
733
734   /* noise companding setup */
735   ret|=vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
736                                    setup->psy_noise_compand,
737                                    setup->psy_noise_compand_short_mapping);
738   ret|=vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
739                                    setup->psy_noise_compand,
740                                    setup->psy_noise_compand_short_mapping);
741   ret|=vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
742                                    setup->psy_noise_compand,
743                                    setup->psy_noise_compand_long_mapping);
744   ret|=vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
745                                    setup->psy_noise_compand,
746                                    setup->psy_noise_compand_long_mapping);
747
748   /* peak guarding setup  */
749   ret|=vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
750                                 setup->psy_tone_dBsuppress);
751   ret|=vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
752                                 setup->psy_tone_dBsuppress);
753   ret|=vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
754                                 setup->psy_tone_dBsuppress);
755   ret|=vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
756                                 setup->psy_tone_dBsuppress);
757
758   /* noise bias setup */
759   ret|=vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
760                                      setup->psy_noise_dBsuppress,
761                                      setup->psy_noise_bias_impulse,
762                                      setup->psy_noiseguards,
763                                      hi->impulse_noisetune);
764   ret|=vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
765                                      setup->psy_noise_dBsuppress,
766                                      setup->psy_noise_bias_padding,
767                                      setup->psy_noiseguards,0.);
768   ret|=vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
769                                      setup->psy_noise_dBsuppress,
770                                      setup->psy_noise_bias_trans,
771                                      setup->psy_noiseguards,0.);
772   ret|=vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
773                                      setup->psy_noise_dBsuppress,
774                                      setup->psy_noise_bias_long,
775                                      setup->psy_noiseguards,0.);
776
777   ret|=vorbis_encode_ath_setup(vi,0);
778   ret|=vorbis_encode_ath_setup(vi,1);
779   ret|=vorbis_encode_ath_setup(vi,2);
780   ret|=vorbis_encode_ath_setup(vi,3);
781
782   if(ret){
783     vorbis_info_clear(vi);
784     return ret; 
785   }
786
787   vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
788
789   /* set bitrate readonlies and management */
790   vi->bitrate_nominal=setting_to_approx_bitrate(vi);
791   vi->bitrate_lower=hi->bitrate_min;
792   vi->bitrate_upper=hi->bitrate_max;
793   vi->bitrate_window=hi->bitrate_limit_window;
794
795   if(hi->managed){
796     ci->bi.queue_avg_time=hi->bitrate_av_window;
797     ci->bi.queue_avg_center=hi->bitrate_av_window_center;
798     ci->bi.queue_minmax_time=hi->bitrate_limit_window;
799     ci->bi.queue_hardmin=hi->bitrate_min;
800     ci->bi.queue_hardmax=hi->bitrate_max;
801     ci->bi.queue_avgmin=hi->bitrate_av_lo;
802     ci->bi.queue_avgmax=hi->bitrate_av_hi;
803     ci->bi.avgfloat_downslew_max=-999999.f;
804     ci->bi.avgfloat_upslew_max=999999.f;
805   }
806
807   return(ret);
808   
809 }
810
811 static int vorbis_encode_setup_setting(vorbis_info *vi,
812                                        long  channels,
813                                        long  rate){
814   int ret=0,i,is;
815   codec_setup_info *ci=vi->codec_setup;
816   highlevel_encode_setup *hi=&ci->hi;
817   ve_setup_data_template *setup=hi->setup;
818   double ds;
819
820   ret=vorbis_encode_toplevel_setup(vi,channels,rate);
821   if(ret)return(ret);
822
823   is=hi->base_setting;
824   ds=hi->base_setting-is;
825
826   hi->short_setting=hi->base_setting;
827   hi->long_setting=hi->base_setting;
828
829   hi->managed=0;
830
831   hi->impulse_block_p=1;
832   hi->noise_normalize_p=1;
833
834   hi->stereo_point_setting=hi->base_setting;
835   hi->lowpass_kHz=
836     setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;  
837   
838   hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
839     setup->psy_ath_float[is+1]*ds;
840   hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
841     setup->psy_ath_abs[is+1]*ds;
842
843   hi->amplitude_track_dBpersec=-6.;
844   hi->trigger_setting=hi->base_setting;
845
846   for(i=0;i<4;i++){
847     hi->block[i].tone_mask_setting=hi->base_setting;
848     hi->block[i].tone_peaklimit_setting=hi->base_setting;
849     hi->block[i].noise_bias_setting=hi->base_setting;
850     hi->block[i].noise_compand_setting=hi->base_setting;
851   }
852
853   return(ret);
854 }
855
856 int vorbis_encode_setup_vbr(vorbis_info *vi,
857                             long  channels,
858                             long  rate,                     
859                             float quality){
860   codec_setup_info *ci=vi->codec_setup;
861   highlevel_encode_setup *hi=&ci->hi;
862
863   quality+=.00001;
864   if(quality>=1.)quality=.9999;
865
866   get_setup_template(vi,channels,rate,quality,0);
867   if(!hi->setup)return OV_EIMPL;
868   
869   return vorbis_encode_setup_setting(vi,channels,rate);
870 }
871
872 int vorbis_encode_init_vbr(vorbis_info *vi,
873                            long channels,
874                            long rate,
875                            
876                            float base_quality /* 0. to 1. */
877                            ){
878   int ret=0;
879
880   ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
881   
882   if(ret){
883     vorbis_info_clear(vi);
884     return ret; 
885   }
886   ret=vorbis_encode_setup_init(vi);
887   if(ret)
888     vorbis_info_clear(vi);
889   return(ret);
890 }
891
892 int vorbis_encode_setup_managed(vorbis_info *vi,
893                                 long channels,
894                                 long rate,
895                                 
896                                 long max_bitrate,
897                                 long nominal_bitrate,
898                                 long min_bitrate){
899
900   codec_setup_info *ci=vi->codec_setup;
901   highlevel_encode_setup *hi=&ci->hi;
902   double tnominal=nominal_bitrate;
903   int ret=0;
904
905   if(nominal_bitrate<=0.){
906     if(max_bitrate>0.){
907       nominal_bitrate=max_bitrate*.875;
908     }else{
909       if(min_bitrate>0.){
910         nominal_bitrate=min_bitrate;
911       }else{
912         return(OV_EINVAL);
913       }
914     }
915   }
916
917   get_setup_template(vi,channels,rate,nominal_bitrate,1);
918   if(!hi->setup)return OV_EIMPL;
919   
920   ret=vorbis_encode_setup_setting(vi,channels,rate);
921   if(ret){
922     vorbis_info_clear(vi);
923     return ret; 
924   }
925
926   /* initialize management with sane defaults */
927       /* initialize management with sane defaults */
928   hi->managed=1;
929   hi->bitrate_av_window=4.;
930   hi->bitrate_av_window_center=.5;
931   hi->bitrate_limit_window=2.;
932   hi->bitrate_min=min_bitrate;
933   hi->bitrate_max=max_bitrate;
934   hi->bitrate_av_lo=tnominal;
935   hi->bitrate_av_hi=tnominal;
936
937   return(ret);
938
939 }
940
941 int vorbis_encode_init(vorbis_info *vi,
942                        long channels,
943                        long rate,
944
945                        long max_bitrate,
946                        long nominal_bitrate,
947                        long min_bitrate){
948
949   int ret=vorbis_encode_setup_managed(vi,channels,rate,
950                                       max_bitrate,
951                                       nominal_bitrate,
952                                       min_bitrate);
953   if(ret){
954     vorbis_info_clear(vi);
955     return(ret);
956   }
957
958   ret=vorbis_encode_setup_init(vi);
959   if(ret)
960     vorbis_info_clear(vi);
961   return(ret);
962 }
963
964 int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
965   if(vi){
966     codec_setup_info *ci=vi->codec_setup;
967     highlevel_encode_setup *hi=&ci->hi;
968     int setp=(number&0xf); /* a read request has a low nibble of 0 */
969
970     if(setp && hi->set_in_stone)return(OV_EINVAL);
971
972     switch(number){
973     case OV_ECTL_RATEMANAGE_GET:
974       {
975         
976         struct ovectl_ratemanage_arg *ai=
977           (struct ovectl_ratemanage_arg *)arg;
978         
979         ai->management_active=hi->managed;
980         ai->bitrate_av_window=hi->bitrate_av_window;
981         ai->bitrate_av_window_center=hi->bitrate_av_window_center;
982         ai->bitrate_hard_window=hi->bitrate_limit_window;
983         ai->bitrate_hard_min=hi->bitrate_min;
984         ai->bitrate_hard_max=hi->bitrate_max;
985         ai->bitrate_av_lo=hi->bitrate_av_lo;
986         ai->bitrate_av_hi=hi->bitrate_av_hi;
987         
988       }
989       return(0);
990     
991     case OV_ECTL_RATEMANAGE_SET:
992       {
993         struct ovectl_ratemanage_arg *ai=
994           (struct ovectl_ratemanage_arg *)arg;
995         if(ai==NULL){
996           hi->managed=0;
997         }else{
998           hi->managed=ai->management_active;
999           vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
1000           vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
1001         }
1002       }
1003       return 0;
1004
1005     case OV_ECTL_RATEMANAGE_AVG:
1006       {
1007         struct ovectl_ratemanage_arg *ai=
1008           (struct ovectl_ratemanage_arg *)arg;
1009         if(ai==NULL){
1010           hi->bitrate_av_lo=0;
1011           hi->bitrate_av_hi=0;
1012           hi->bitrate_av_window=0;
1013         }else{
1014           hi->bitrate_av_window=ai->bitrate_av_window;
1015           hi->bitrate_av_window_center=ai->bitrate_av_window_center;
1016           hi->bitrate_av_lo=ai->bitrate_av_lo;
1017           hi->bitrate_av_hi=ai->bitrate_av_hi;
1018         }
1019
1020         if(hi->bitrate_av_window<.25)hi->bitrate_av_window=.25;
1021         if(hi->bitrate_av_window>10.)hi->bitrate_av_window=10.;
1022         if(hi->bitrate_av_window_center<0.)hi->bitrate_av_window=0.;
1023         if(hi->bitrate_av_window_center>1.)hi->bitrate_av_window=1.;
1024         
1025         if( ( (hi->bitrate_av_lo<=0 && hi->bitrate_av_hi<=0)||
1026               (hi->bitrate_av_window<=0) ) &&
1027             ( (hi->bitrate_min<=0 && hi->bitrate_max<=0)||
1028               (hi->bitrate_limit_window<=0) ))
1029           hi->managed=0;
1030       }
1031       return(0);
1032     case OV_ECTL_RATEMANAGE_HARD:
1033       {
1034         struct ovectl_ratemanage_arg *ai=
1035           (struct ovectl_ratemanage_arg *)arg;
1036         if(ai==NULL){
1037           hi->bitrate_min=0;
1038           hi->bitrate_max=0;
1039           hi->bitrate_limit_window=0;
1040         }else{
1041           hi->bitrate_limit_window=ai->bitrate_hard_window;
1042           hi->bitrate_min=ai->bitrate_hard_min;
1043           hi->bitrate_max=ai->bitrate_hard_max;
1044         }
1045         if(hi->bitrate_limit_window<0.)hi->bitrate_limit_window=0.;
1046         if(hi->bitrate_limit_window>10.)hi->bitrate_limit_window=10.;
1047         
1048         if( ( (hi->bitrate_av_lo<=0 && hi->bitrate_av_hi<=0)||
1049               (hi->bitrate_av_window<=0) ) &&
1050             ( (hi->bitrate_min<=0 && hi->bitrate_max<=0)||
1051               (hi->bitrate_limit_window<=0) ))
1052           hi->managed=0;
1053       }
1054       return(0);
1055
1056     case OV_ECTL_LOWPASS_GET:
1057       {
1058         double *farg=(double *)arg;
1059         *farg=hi->lowpass_kHz;
1060       }
1061       return(0);
1062     case OV_ECTL_LOWPASS_SET:
1063       {
1064         double *farg=(double *)arg;
1065         hi->lowpass_kHz=*farg;
1066
1067         if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
1068         if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
1069       }
1070       return(0);
1071     case OV_ECTL_IBLOCK_GET:
1072       {
1073         double *farg=(double *)arg;
1074         *farg=hi->impulse_noisetune;
1075       }
1076       return(0);
1077     case OV_ECTL_IBLOCK_SET:
1078       {
1079         double *farg=(double *)arg;
1080         hi->impulse_noisetune=*farg;
1081
1082         if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
1083         if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
1084       }
1085       return(0);      
1086     }
1087
1088
1089     return(OV_EIMPL);
1090   }
1091   return(OV_EINVAL);
1092 }