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