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