]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/sound/OggVorbis/vorbissrc/vorbisenc.c
Various Mac OS X tweaks to get this to build. Probably breaking things.
[icculus/iodoom3.git] / neo / sound / OggVorbis / vorbissrc / vorbisenc.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
5  * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
7  *                                                                  *
8  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002             *
9  * by the XIPHOPHORUS Company http://www.xiph.org/                  *
10  *                                                                  *
11  ********************************************************************
12
13  function: simple programmatic interface for encoder mode setup
14  last mod: $Id: vorbisenc.c,v 1.47 2002/07/11 06:40:50 xiphmont Exp $
15
16  ********************************************************************/
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <math.h>
21
22 #include "../vorbis/codec.h"
23 #include "../vorbis/vorbisenc.h"
24
25 #include "codec_internal.h"
26
27 #include "os.h"
28 #include "misc.h"
29
30 /* careful with this; it's using static array sizing to make managing
31    all the modes a little less annoying.  If we use a residue backend
32    with > 12 partition types, or a different division of iteration,
33    this needs to be updated. */
34 typedef struct {
35   static_codebook *books[12][3];
36 } static_bookblock;
37
38 typedef struct {
39   int res_type;
40   int limit_type; /* 0 lowpass limited, 1 point stereo limited */
41   vorbis_info_residue0 *res;
42   static_codebook  *book_aux;
43   static_codebook  *book_aux_managed;
44   static_bookblock *books_base;
45   static_bookblock *books_base_managed;
46 } vorbis_residue_template;
47
48 typedef struct {
49   vorbis_info_mapping0    *map;
50   vorbis_residue_template *res;
51 } vorbis_mapping_template;
52
53 typedef struct vp_adjblock{
54   int block[P_BANDS];
55 } vp_adjblock;
56
57 typedef struct {
58   int data[NOISE_COMPAND_LEVELS];
59 } compandblock;
60
61 /* high level configuration information for setting things up
62    step-by-step with the detailed vorbis_encode_ctl interface.
63    There's a fair amount of redundancy such that interactive setup
64    does not directly deal with any vorbis_info or codec_setup_info
65    initialization; it's all stored (until full init) in this highlevel
66    setup, then flushed out to the real codec setup structs later. */
67
68 typedef struct {
69   int att[P_NOISECURVES];
70   float boost;
71   float decay;
72 } att3;
73 typedef struct { int data[P_NOISECURVES]; } adj3; 
74
75 typedef struct {
76   int   pre[PACKETBLOBS];
77   int   post[PACKETBLOBS];
78   float kHz[PACKETBLOBS];
79   float lowpasskHz[PACKETBLOBS];
80 } adj_stereo;
81
82 typedef struct {
83   int lo;
84   int hi;
85   int fixed;
86 } noiseguard;
87 typedef struct {
88   int data[P_NOISECURVES][17];
89 } noise3;
90
91 typedef struct {
92   int      mappings;
93   double  *rate_mapping;
94   double  *quality_mapping;
95   int      coupling_restriction;
96   long     samplerate_min_restriction;
97   long     samplerate_max_restriction;
98
99
100   int     *blocksize_short;
101   int     *blocksize_long;
102
103   att3    *psy_tone_masteratt;
104   int     *psy_tone_0dB;
105   int     *psy_tone_dBsuppress;
106
107   vp_adjblock *psy_tone_adj_impulse;
108   vp_adjblock *psy_tone_adj_long;
109   vp_adjblock *psy_tone_adj_other;
110
111   noiseguard  *psy_noiseguards;
112   noise3      *psy_noise_bias_impulse;
113   noise3      *psy_noise_bias_padding;
114   noise3      *psy_noise_bias_trans;
115   noise3      *psy_noise_bias_long;
116   int         *psy_noise_dBsuppress;
117
118   compandblock  *psy_noise_compand;
119   double        *psy_noise_compand_short_mapping;
120   double        *psy_noise_compand_long_mapping;
121
122   int      *psy_noise_normal_start[2];
123   int      *psy_noise_normal_partition[2];
124   double   *psy_noise_normal_thresh;
125
126   int      *psy_ath_float;
127   int      *psy_ath_abs;
128
129   double   *psy_lowpass;
130
131   vorbis_info_psy_global *global_params;
132   double     *global_mapping;
133   adj_stereo *stereo_modes;
134
135   static_codebook ***floor_books;
136   vorbis_info_floor1 *floor_params;
137   int *floor_short_mapping;
138   int *floor_long_mapping;
139
140   vorbis_mapping_template *maps;
141 } ve_setup_data_template;
142
143 /* a few static coder conventions */
144 static vorbis_info_mode _mode_template[2]={
145   {0,0,0,0},
146   {1,0,0,1}
147 };
148
149 static 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 ve_setup_data_template *setup_list[]={
164   &ve_setup_44_stereo,
165   &ve_setup_44_stereo_low,
166   &ve_setup_44_uncoupled,
167   &ve_setup_44_uncoupled_low,
168
169   &ve_setup_32_stereo,
170   &ve_setup_32_stereo_low,
171   &ve_setup_32_uncoupled,
172   &ve_setup_32_uncoupled_low,
173
174   &ve_setup_22_stereo,
175   &ve_setup_22_uncoupled,
176   &ve_setup_16_stereo,
177   &ve_setup_16_uncoupled,
178
179   &ve_setup_11_stereo,
180   &ve_setup_11_uncoupled,
181   &ve_setup_8_stereo,
182   &ve_setup_8_uncoupled,
183
184   &ve_setup_X_stereo,
185   &ve_setup_X_uncoupled,
186   &ve_setup_X_stereo_low,
187   &ve_setup_X_uncoupled_low,
188   &ve_setup_XX_stereo,
189   &ve_setup_XX_uncoupled,
190   0
191 };
192
193 static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
194   if(vi && vi->codec_setup){
195
196     vi->version=0;
197     vi->channels=ch;
198     vi->rate=rate;
199
200     return(0);
201   }
202   return(OV_EINVAL);
203 }
204
205 static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
206                                      static_codebook    ***books, 
207                                      vorbis_info_floor1 *in, 
208                                      int *x){
209   int i,k,is=s;
210   vorbis_info_floor1 *f=_ogg_calloc(1,sizeof(*f));
211   codec_setup_info *ci=vi->codec_setup;
212
213   memcpy(f,in+x[is],sizeof(*f));
214   /* fill in the lowpass field, even if it's temporary */
215   f->n=ci->blocksizes[block]>>1;
216
217   /* books */
218   {
219     int partitions=f->partitions;
220     int maxclass=-1;
221     int maxbook=-1;
222     for(i=0;i<partitions;i++)
223       if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
224     for(i=0;i<=maxclass;i++){
225       if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
226       f->class_book[i]+=ci->books;
227       for(k=0;k<(1<<f->class_subs[i]);k++){
228         if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
229         if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
230       }
231     }
232
233     for(i=0;i<=maxbook;i++)
234       ci->book_param[ci->books++]=books[x[is]][i];
235   }
236
237   /* for now, we're only using floor 1 */
238   ci->floor_type[ci->floors]=1;
239   ci->floor_param[ci->floors]=f;
240   ci->floors++;
241
242   return;
243 }
244
245 static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
246                                             vorbis_info_psy_global *in, 
247                                             double *x){
248   int i,is=s;
249   double ds=s-is;
250   codec_setup_info *ci=vi->codec_setup;
251   vorbis_info_psy_global *g=&ci->psy_g_param;
252   
253   memcpy(g,in+(int)x[is],sizeof(*g));
254   
255   ds=x[is]*(1.-ds)+x[is+1]*ds;
256   is=(int)ds;
257   ds-=is;
258   if(ds==0 && is>0){
259     is--;
260     ds=1.;
261   }
262   
263   /* interpolate the trigger threshholds */
264   for(i=0;i<4;i++){
265     g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
266     g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
267   }
268   g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
269   return;
270 }
271
272 static void vorbis_encode_global_stereo(vorbis_info *vi,
273                                        highlevel_encode_setup *hi,
274                                        adj_stereo *p){
275   float s=hi->stereo_point_setting;
276   int i,is=s;
277   double ds=s-is;
278   codec_setup_info *ci=vi->codec_setup;
279   vorbis_info_psy_global *g=&ci->psy_g_param;
280
281   if(p){
282     memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
283     memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
284
285     if(hi->managed){
286       /* interpolate the kHz threshholds */
287       for(i=0;i<PACKETBLOBS;i++){
288         float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
289         g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
290         g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
291         g->coupling_pkHz[i]=kHz;
292         
293         kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
294         g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
295         g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
296         
297       }
298     }else{
299       float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
300       for(i=0;i<PACKETBLOBS;i++){
301         g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
302         g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
303         g->coupling_pkHz[i]=kHz;
304       }
305       
306       kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
307       for(i=0;i<PACKETBLOBS;i++){
308         g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
309         g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
310       }
311     }
312   }else{
313     for(i=0;i<PACKETBLOBS;i++){
314       g->sliding_lowpass[0][i]=ci->blocksizes[0];
315       g->sliding_lowpass[1][i]=ci->blocksizes[1];
316     }
317   }
318   return;
319 }
320
321 static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
322                                       int *nn_start,
323                                       int *nn_partition,
324                                       double *nn_thresh,
325                                       int block){
326   codec_setup_info *ci=vi->codec_setup;
327   vorbis_info_psy *p=ci->psy_param[block];
328   highlevel_encode_setup *hi=&ci->hi;
329   int is=s;
330   
331   if(block>=ci->psys)
332     ci->psys=block+1;
333   if(!p){
334     p=_ogg_calloc(1,sizeof(*p));
335     ci->psy_param[block]=p;
336   }
337   
338   memcpy(p,&_psy_info_template,sizeof(*p));
339   p->blockflag=block>>1;
340
341   if(hi->noise_normalize_p){
342     p->normal_channel_p=1;
343     p->normal_point_p=1;
344     p->normal_start=nn_start[is];
345     p->normal_partition=nn_partition[is];
346     p->normal_thresh=nn_thresh[is];
347   }
348     
349   return;
350 }
351
352 static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
353                                          att3 *att,
354                                          int  *max,
355                                          vp_adjblock *in){
356   int i,is=s;
357   double ds=s-is;
358   codec_setup_info *ci=vi->codec_setup;
359   vorbis_info_psy *p=ci->psy_param[block];
360
361   /* 0 and 2 are only used by bitmanagement, but there's no harm to always
362      filling the values in here */
363   p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
364   p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
365   p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
366   p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
367   p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
368
369   p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
370
371   for(i=0;i<P_BANDS;i++)
372     p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
373   return;
374 }
375
376
377 static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
378                                        compandblock *in, double *x){
379   int i,is=s;
380   double ds=s-is;
381   codec_setup_info *ci=vi->codec_setup;
382   vorbis_info_psy *p=ci->psy_param[block];
383
384   ds=x[is]*(1.-ds)+x[is+1]*ds;
385   is=(int)ds;
386   ds-=is;
387   if(ds==0 && is>0){
388     is--;
389     ds=1.;
390   }
391
392   /* interpolate the compander settings */
393   for(i=0;i<NOISE_COMPAND_LEVELS;i++)
394     p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
395   return;
396 }
397
398 static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
399                                     int *suppress){
400   int is=s;
401   double ds=s-is;
402   codec_setup_info *ci=vi->codec_setup;
403   vorbis_info_psy *p=ci->psy_param[block];
404
405   p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
406
407   return;
408 }
409
410 static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
411                                          int *suppress,
412                                          noise3 *in,
413                                          noiseguard *guard,
414                                          double userbias){
415   int i,is=s,j;
416   double ds=s-is;
417   codec_setup_info *ci=vi->codec_setup;
418   vorbis_info_psy *p=ci->psy_param[block];
419
420   p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
421   p->noisewindowlomin=guard[block].lo;
422   p->noisewindowhimin=guard[block].hi;
423   p->noisewindowfixed=guard[block].fixed;
424
425   for(j=0;j<P_NOISECURVES;j++)
426     for(i=0;i<P_BANDS;i++)
427       p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
428
429   /* impulse blocks may take a user specified bias to boost the
430      nominal/high noise encoding depth */
431   for(j=0;j<P_NOISECURVES;j++){
432     float min=p->noiseoff[j][0]+6; /* the lowest it can go */
433     for(i=0;i<P_BANDS;i++){
434       p->noiseoff[j][i]+=userbias;
435       if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
436     }
437   }
438
439   return;
440 }
441
442 static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
443   codec_setup_info *ci=vi->codec_setup;
444   vorbis_info_psy *p=ci->psy_param[block];
445
446   p->ath_adjatt=ci->hi.ath_floating_dB;
447   p->ath_maxatt=ci->hi.ath_absolute_dB;
448   return;
449 }
450
451
452 static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
453   int i;
454   for(i=0;i<ci->books;i++)
455     if(ci->book_param[i]==book)return(i);
456   
457   return(ci->books++);
458 }
459
460 static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
461                                          int *shortb,int *longb){
462
463   codec_setup_info *ci=vi->codec_setup;
464   int is=s;
465   
466   int blockshort=shortb[is];
467   int blocklong=longb[is];
468   ci->blocksizes[0]=blockshort;
469   ci->blocksizes[1]=blocklong;
470
471 }
472
473 static void vorbis_encode_residue_setup(vorbis_info *vi,
474                                        int number, int block,
475                                        vorbis_residue_template *res){
476
477   codec_setup_info *ci=vi->codec_setup;
478   int i,n;
479   
480   vorbis_info_residue0 *r=ci->residue_param[number]=
481     _ogg_malloc(sizeof(*r));
482   
483   memcpy(r,res->res,sizeof(*r));
484   if(ci->residues<=number)ci->residues=number+1;
485
486   switch(ci->blocksizes[block]){
487   case 64:case 128:case 256:
488     r->grouping=16;
489     break;
490   default:
491     r->grouping=32;
492     break;
493   }
494   ci->residue_type[number]=res->res_type;
495
496   /* to be adjusted by lowpass/pointlimit later */
497   n=r->end=ci->blocksizes[block]>>1; 
498   if(res->res_type==2)
499     n=r->end*=vi->channels;
500   
501   /* fill in all the books */
502   {
503     int booklist=0,k;
504     
505     if(ci->hi.managed){
506       for(i=0;i<r->partitions;i++)
507         for(k=0;k<3;k++)
508           if(res->books_base_managed->books[i][k])
509             r->secondstages[i]|=(1<<k);
510
511       r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
512       ci->book_param[r->groupbook]=res->book_aux_managed;      
513     
514       for(i=0;i<r->partitions;i++){
515         for(k=0;k<3;k++){
516           if(res->books_base_managed->books[i][k]){
517             int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
518             r->booklist[booklist++]=bookid;
519             ci->book_param[bookid]=res->books_base_managed->books[i][k];
520           }
521         }
522       }
523
524     }else{
525
526       for(i=0;i<r->partitions;i++)
527         for(k=0;k<3;k++)
528           if(res->books_base->books[i][k])
529             r->secondstages[i]|=(1<<k);
530   
531       r->groupbook=book_dup_or_new(ci,res->book_aux);
532       ci->book_param[r->groupbook]=res->book_aux;
533       
534       for(i=0;i<r->partitions;i++){
535         for(k=0;k<3;k++){
536           if(res->books_base->books[i][k]){
537             int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
538             r->booklist[booklist++]=bookid;
539             ci->book_param[bookid]=res->books_base->books[i][k];
540           }
541         }
542       }
543     }
544   }
545   
546   /* lowpass setup/pointlimit */
547   {
548     double freq=ci->hi.lowpass_kHz*1000.;
549     vorbis_info_floor1 *f=ci->floor_param[block]; /* by convention */
550     double nyq=vi->rate/2.;
551     long blocksize=ci->blocksizes[block]>>1;
552
553     /* lowpass needs to be set in the floor and the residue. */    
554     if(freq>nyq)freq=nyq;
555     /* in the floor, the granularity can be very fine; it doesn't alter
556        the encoding structure, only the samples used to fit the floor
557        approximation */
558     f->n=freq/nyq*blocksize; 
559
560     /* this res may by limited by the maximum pointlimit of the mode,
561        not the lowpass. the floor is always lowpass limited. */
562     if(res->limit_type){
563       if(ci->hi.managed)
564         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
565       else
566         freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
567       if(freq>nyq)freq=nyq;
568     }
569     
570     /* in the residue, we're constrained, physically, by partition
571        boundaries.  We still lowpass 'wherever', but we have to round up
572        here to next boundary, or the vorbis spec will round it *down* to
573        previous boundary in encode/decode */
574     if(ci->residue_type[block]==2)
575       r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
576         r->grouping;
577     else
578       r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
579         r->grouping;
580   }
581 }      
582
583 /* we assume two maps in this encoder */
584 static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
585                                           vorbis_mapping_template *maps){
586
587   codec_setup_info *ci=vi->codec_setup;
588   int i,j,is=s,modes=2;
589   vorbis_info_mapping0 *map=maps[is].map;
590   vorbis_info_mode *mode=_mode_template;
591   vorbis_residue_template *res=maps[is].res;
592
593   if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
594
595   for(i=0;i<modes;i++){
596
597     ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
598     ci->mode_param[i]=_ogg_calloc(1,sizeof(*mode));
599   
600     memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
601     if(i>=ci->modes)ci->modes=i+1;
602
603     ci->map_type[i]=0;
604     memcpy(ci->map_param[i],map+i,sizeof(*map));
605     if(i>=ci->maps)ci->maps=i+1;
606     
607     for(j=0;j<map[i].submaps;j++)
608       vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
609                                   ,res+map[i].residuesubmap[j]);
610   }
611 }
612
613 static double setting_to_approx_bitrate(vorbis_info *vi){
614   codec_setup_info *ci=vi->codec_setup;
615   highlevel_encode_setup *hi=&ci->hi;
616   ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
617   int is=hi->base_setting;
618   double ds=hi->base_setting-is;
619   int ch=vi->channels;
620   double *r=setup->rate_mapping;
621
622   if(r==NULL)
623     return(-1);
624   
625   return((r[is]*(1.-ds)+r[is+1]*ds)*ch);  
626 }
627
628 static void get_setup_template(vorbis_info *vi,
629                                long ch,long srate,
630                                double req,int q_or_bitrate){
631   int i=0,j;
632   codec_setup_info *ci=vi->codec_setup;
633   highlevel_encode_setup *hi=&ci->hi;
634   if(q_or_bitrate)req/=ch;
635
636   while(setup_list[i]){
637     if(setup_list[i]->coupling_restriction==-1 ||
638        setup_list[i]->coupling_restriction==ch){
639       if(srate>=setup_list[i]->samplerate_min_restriction &&
640          srate<=setup_list[i]->samplerate_max_restriction){
641         int mappings=setup_list[i]->mappings;
642         double *map=(q_or_bitrate?
643                      setup_list[i]->rate_mapping:
644                      setup_list[i]->quality_mapping);
645
646         /* the template matches.  Does the requested quality mode
647            fall within this template's modes? */
648         if(req<map[0]){++i;continue;}
649         if(req>map[setup_list[i]->mappings]){++i;continue;}
650         for(j=0;j<mappings;j++)
651           if(req>=map[j] && req<map[j+1])break;
652         /* an all-points match */
653         hi->setup=setup_list[i];
654         if(j==mappings)
655           hi->base_setting=j-.001;
656         else{
657           float low=map[j];
658           float high=map[j+1];
659           float del=(req-low)/(high-low);
660           hi->base_setting=j+del;
661         }
662         return;
663       }
664     }
665     i++;
666   }
667   
668   hi->setup=NULL;
669 }
670
671 /* encoders will need to use vorbis_info_init beforehand and call
672    vorbis_info clear when all done */
673
674 /* two interfaces; this, more detailed one, and later a convenience
675    layer on top */
676
677 /* the final setup call */
678 int vorbis_encode_setup_init(vorbis_info *vi){
679   int i0=0,singleblock=0;
680   codec_setup_info *ci=vi->codec_setup;
681   ve_setup_data_template *setup=NULL;
682   highlevel_encode_setup *hi=&ci->hi;
683
684   if(ci==NULL)return(OV_EINVAL);
685   if(!hi->impulse_block_p)i0=1;
686
687   /* too low/high an ATH floater is nonsensical, but doesn't break anything */
688   if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
689   if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
690
691   /* again, bound this to avoid the app shooting itself int he foot
692      too badly */
693   if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
694   if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
695   
696   /* get the appropriate setup template; matches the fetch in previous
697      stages */
698   setup=(ve_setup_data_template *)hi->setup;
699   if(setup==NULL)return(OV_EINVAL);
700
701   hi->set_in_stone=1;
702   /* choose block sizes from configured sizes as well as paying
703      attention to long_block_p and short_block_p.  If the configured
704      short and long blocks are the same length, we set long_block_p
705      and unset short_block_p */
706   vorbis_encode_blocksize_setup(vi,hi->base_setting,
707                                 setup->blocksize_short,
708                                 setup->blocksize_long);
709   if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
710   
711   /* floor setup; choose proper floor params.  Allocated on the floor
712      stack in order; if we alloc only long floor, it's 0 */
713   vorbis_encode_floor_setup(vi,hi->short_setting,0,
714                             setup->floor_books,
715                             setup->floor_params,
716                             setup->floor_short_mapping);
717   if(!singleblock)
718     vorbis_encode_floor_setup(vi,hi->long_setting,1,
719                               setup->floor_books,
720                               setup->floor_params,
721                               setup->floor_long_mapping);
722   
723   /* setup of [mostly] short block detection and stereo*/
724   vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
725                                    setup->global_params,
726                                    setup->global_mapping);
727   vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
728
729   /* basic psych setup and noise normalization */
730   vorbis_encode_psyset_setup(vi,hi->short_setting,
731                              setup->psy_noise_normal_start[0],
732                              setup->psy_noise_normal_partition[0],  
733                              setup->psy_noise_normal_thresh,  
734                              0);
735   vorbis_encode_psyset_setup(vi,hi->short_setting,
736                              setup->psy_noise_normal_start[0],
737                              setup->psy_noise_normal_partition[0],  
738                              setup->psy_noise_normal_thresh,  
739                              1);
740   if(!singleblock){
741     vorbis_encode_psyset_setup(vi,hi->long_setting,
742                                setup->psy_noise_normal_start[1],
743                                setup->psy_noise_normal_partition[1],  
744                                     setup->psy_noise_normal_thresh,  
745                                2);
746     vorbis_encode_psyset_setup(vi,hi->long_setting,
747                                setup->psy_noise_normal_start[1],
748                                setup->psy_noise_normal_partition[1],  
749                                setup->psy_noise_normal_thresh,  
750                                3);
751   }
752
753   /* tone masking setup */
754   vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
755                                setup->psy_tone_masteratt,
756                                setup->psy_tone_0dB,
757                                setup->psy_tone_adj_impulse);
758   vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
759                                setup->psy_tone_masteratt,
760                                setup->psy_tone_0dB,
761                                setup->psy_tone_adj_other);
762   if(!singleblock){
763     vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
764                                  setup->psy_tone_masteratt,
765                                  setup->psy_tone_0dB,
766                                  setup->psy_tone_adj_other);
767     vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
768                                  setup->psy_tone_masteratt,
769                                  setup->psy_tone_0dB,
770                                  setup->psy_tone_adj_long);
771   }
772
773   /* noise companding setup */
774   vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
775                               setup->psy_noise_compand,
776                               setup->psy_noise_compand_short_mapping);
777   vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
778                               setup->psy_noise_compand,
779                               setup->psy_noise_compand_short_mapping);
780   if(!singleblock){
781     vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
782                                 setup->psy_noise_compand,
783                                 setup->psy_noise_compand_long_mapping);
784     vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
785                                 setup->psy_noise_compand,
786                                 setup->psy_noise_compand_long_mapping);
787   }
788
789   /* peak guarding setup  */
790   vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
791                            setup->psy_tone_dBsuppress);
792   vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
793                            setup->psy_tone_dBsuppress);
794   if(!singleblock){
795     vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
796                              setup->psy_tone_dBsuppress);
797     vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
798                              setup->psy_tone_dBsuppress);
799   }
800
801   /* noise bias setup */
802   vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
803                                 setup->psy_noise_dBsuppress,
804                                 setup->psy_noise_bias_impulse,
805                                 setup->psy_noiseguards,
806                                 (i0==0?hi->impulse_noisetune:0.));
807   vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
808                                 setup->psy_noise_dBsuppress,
809                                 setup->psy_noise_bias_padding,
810                                 setup->psy_noiseguards,0.);
811   if(!singleblock){
812     vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
813                                   setup->psy_noise_dBsuppress,
814                                   setup->psy_noise_bias_trans,
815                                   setup->psy_noiseguards,0.);
816     vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
817                                   setup->psy_noise_dBsuppress,
818                                   setup->psy_noise_bias_long,
819                                   setup->psy_noiseguards,0.);
820   }
821
822   vorbis_encode_ath_setup(vi,0);
823   vorbis_encode_ath_setup(vi,1);
824   if(!singleblock){
825     vorbis_encode_ath_setup(vi,2);
826     vorbis_encode_ath_setup(vi,3);
827   }
828
829   vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
830
831   /* set bitrate readonlies and management */
832   vi->bitrate_nominal=setting_to_approx_bitrate(vi);
833   vi->bitrate_lower=hi->bitrate_min;
834   vi->bitrate_upper=hi->bitrate_max;
835   vi->bitrate_window=hi->bitrate_limit_window;
836
837   if(hi->managed){
838     ci->bi.queue_avg_time=hi->bitrate_av_window;
839     ci->bi.queue_avg_center=hi->bitrate_av_window_center;
840     ci->bi.queue_minmax_time=hi->bitrate_limit_window;
841     ci->bi.queue_hardmin=hi->bitrate_min;
842     ci->bi.queue_hardmax=hi->bitrate_max;
843     ci->bi.queue_avgmin=hi->bitrate_av_lo;
844     ci->bi.queue_avgmax=hi->bitrate_av_hi;
845     ci->bi.avgfloat_downslew_max=-999999.f;
846     ci->bi.avgfloat_upslew_max=999999.f;
847   }
848
849   return(0);
850   
851 }
852
853 static int vorbis_encode_setup_setting(vorbis_info *vi,
854                                        long  channels,
855                                        long  rate){
856   int ret=0,i,is;
857   codec_setup_info *ci=vi->codec_setup;
858   highlevel_encode_setup *hi=&ci->hi;
859   ve_setup_data_template *setup=hi->setup;
860   double ds;
861
862   ret=vorbis_encode_toplevel_setup(vi,channels,rate);
863   if(ret)return(ret);
864
865   is=hi->base_setting;
866   ds=hi->base_setting-is;
867
868   hi->short_setting=hi->base_setting;
869   hi->long_setting=hi->base_setting;
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+=.00001;
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       nominal_bitrate=max_bitrate*.875;
950     }else{
951       if(min_bitrate>0.){
952         nominal_bitrate=min_bitrate;
953       }else{
954         return(OV_EINVAL);
955       }
956     }
957   }
958
959   get_setup_template(vi,channels,rate,nominal_bitrate,1);
960   if(!hi->setup)return OV_EIMPL;
961   
962   ret=vorbis_encode_setup_setting(vi,channels,rate);
963   if(ret){
964     vorbis_info_clear(vi);
965     return ret; 
966   }
967
968   /* initialize management with sane defaults */
969       /* initialize management with sane defaults */
970   hi->managed=1;
971   hi->bitrate_av_window=4.;
972   hi->bitrate_av_window_center=.5;
973   hi->bitrate_limit_window=2.;
974   hi->bitrate_min=min_bitrate;
975   hi->bitrate_max=max_bitrate;
976   hi->bitrate_av_lo=tnominal;
977   hi->bitrate_av_hi=tnominal;
978
979   return(ret);
980
981 }
982
983 int vorbis_encode_init(vorbis_info *vi,
984                        long channels,
985                        long rate,
986
987                        long max_bitrate,
988                        long nominal_bitrate,
989                        long min_bitrate){
990
991   int ret=vorbis_encode_setup_managed(vi,channels,rate,
992                                       max_bitrate,
993                                       nominal_bitrate,
994                                       min_bitrate);
995   if(ret){
996     vorbis_info_clear(vi);
997     return(ret);
998   }
999
1000   ret=vorbis_encode_setup_init(vi);
1001   if(ret)
1002     vorbis_info_clear(vi);
1003   return(ret);
1004 }
1005
1006 int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
1007   if(vi){
1008     codec_setup_info *ci=vi->codec_setup;
1009     highlevel_encode_setup *hi=&ci->hi;
1010     int setp=(number&0xf); /* a read request has a low nibble of 0 */
1011
1012     if(setp && hi->set_in_stone)return(OV_EINVAL);
1013
1014     switch(number){
1015     case OV_ECTL_RATEMANAGE_GET:
1016       {
1017         
1018         struct ovectl_ratemanage_arg *ai=
1019           (struct ovectl_ratemanage_arg *)arg;
1020         
1021         ai->management_active=hi->managed;
1022         ai->bitrate_av_window=hi->bitrate_av_window;
1023         ai->bitrate_av_window_center=hi->bitrate_av_window_center;
1024         ai->bitrate_hard_window=hi->bitrate_limit_window;
1025         ai->bitrate_hard_min=hi->bitrate_min;
1026         ai->bitrate_hard_max=hi->bitrate_max;
1027         ai->bitrate_av_lo=hi->bitrate_av_lo;
1028         ai->bitrate_av_hi=hi->bitrate_av_hi;
1029         
1030       }
1031       return(0);
1032     
1033     case OV_ECTL_RATEMANAGE_SET:
1034       {
1035         struct ovectl_ratemanage_arg *ai=
1036           (struct ovectl_ratemanage_arg *)arg;
1037         if(ai==NULL){
1038           hi->managed=0;
1039         }else{
1040           hi->managed=ai->management_active;
1041           vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
1042           vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
1043         }
1044       }
1045       return 0;
1046
1047     case OV_ECTL_RATEMANAGE_AVG:
1048       {
1049         struct ovectl_ratemanage_arg *ai=
1050           (struct ovectl_ratemanage_arg *)arg;
1051         if(ai==NULL){
1052           hi->bitrate_av_lo=0;
1053           hi->bitrate_av_hi=0;
1054           hi->bitrate_av_window=0;
1055         }else{
1056           hi->bitrate_av_window=ai->bitrate_av_window;
1057           hi->bitrate_av_window_center=ai->bitrate_av_window_center;
1058           hi->bitrate_av_lo=ai->bitrate_av_lo;
1059           hi->bitrate_av_hi=ai->bitrate_av_hi;
1060         }
1061
1062         if(hi->bitrate_av_window<.25)hi->bitrate_av_window=.25;
1063         if(hi->bitrate_av_window>10.)hi->bitrate_av_window=10.;
1064         if(hi->bitrate_av_window_center<0.)hi->bitrate_av_window=0.;
1065         if(hi->bitrate_av_window_center>1.)hi->bitrate_av_window=1.;
1066         
1067         if( ( (hi->bitrate_av_lo<=0 && hi->bitrate_av_hi<=0)||
1068               (hi->bitrate_av_window<=0) ) &&
1069             ( (hi->bitrate_min<=0 && hi->bitrate_max<=0)||
1070               (hi->bitrate_limit_window<=0) ))
1071           hi->managed=0;
1072       }
1073       return(0);
1074     case OV_ECTL_RATEMANAGE_HARD:
1075       {
1076         struct ovectl_ratemanage_arg *ai=
1077           (struct ovectl_ratemanage_arg *)arg;
1078         if(ai==NULL){
1079           hi->bitrate_min=0;
1080           hi->bitrate_max=0;
1081           hi->bitrate_limit_window=0;
1082         }else{
1083           hi->bitrate_limit_window=ai->bitrate_hard_window;
1084           hi->bitrate_min=ai->bitrate_hard_min;
1085           hi->bitrate_max=ai->bitrate_hard_max;
1086         }
1087         if(hi->bitrate_limit_window<0.)hi->bitrate_limit_window=0.;
1088         if(hi->bitrate_limit_window>10.)hi->bitrate_limit_window=10.;
1089         
1090         if( ( (hi->bitrate_av_lo<=0 && hi->bitrate_av_hi<=0)||
1091               (hi->bitrate_av_window<=0) ) &&
1092             ( (hi->bitrate_min<=0 && hi->bitrate_max<=0)||
1093               (hi->bitrate_limit_window<=0) ))
1094           hi->managed=0;
1095       }
1096       return(0);
1097
1098     case OV_ECTL_LOWPASS_GET:
1099       {
1100         double *farg=(double *)arg;
1101         *farg=hi->lowpass_kHz;
1102       }
1103       return(0);
1104     case OV_ECTL_LOWPASS_SET:
1105       {
1106         double *farg=(double *)arg;
1107         hi->lowpass_kHz=*farg;
1108
1109         if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
1110         if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
1111       }
1112       return(0);
1113     case OV_ECTL_IBLOCK_GET:
1114       {
1115         double *farg=(double *)arg;
1116         *farg=hi->impulse_noisetune;
1117       }
1118       return(0);
1119     case OV_ECTL_IBLOCK_SET:
1120       {
1121         double *farg=(double *)arg;
1122         hi->impulse_noisetune=*farg;
1123
1124         if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
1125         if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
1126       }
1127       return(0);      
1128     }
1129
1130
1131     return(OV_EIMPL);
1132   }
1133   return(OV_EINVAL);
1134 }