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