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