fix nasty warnings, and some non-ansi constructs. increase portability.
[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-2001             *
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.30 2001/12/21 14:52:36 segher Exp $
15
16  ********************************************************************/
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <math.h>
21 #include <stdarg.h>
22
23 #include "vorbis/codec.h"
24 #include "vorbis/vorbisenc.h"
25
26 #include "codec_internal.h"
27 #include "registry-api.h"
28
29 #include "os.h"
30 #include "misc.h"
31
32 /* careful with this; it's using static array sizing to make managing
33    all the modes a little less annoying.  If we use a residue backend
34    with > 10 partition types, or a different division of iteration,
35    this needs to be updated. */
36 typedef struct {
37   vorbis_info_residue0 *res[2];
38   static_codebook *book_aux[2];
39   static_codebook *books_base[5][10][3];
40   static_codebook *books_stereo_backfill[5][10];
41   static_codebook *books_residue_backfill[5][10][2];
42 } vorbis_residue_template;
43
44 static double stereo_threshholds[]={0.0, 2.5, 4.5, 8.5, 16.5};
45
46 typedef struct vp_adjblock{
47   int block[P_BANDS][P_LEVELS];
48 } vp_adjblock;
49
50 #include "modes/residue_44.h"
51 #include "modes/psych_44.h"
52 #include "modes/floor_44.h"
53
54 /* a few static coder conventions */
55 static vorbis_info_time0 _time_dummy={0};
56 static vorbis_info_mode _mode_set_short={0,0,0,0};
57 static vorbis_info_mode _mode_set_long={1,0,0,1};
58
59 /* mapping conventions:
60    only one submap (this would change for efficient 5.1 support for example)*/
61 /* Four psychoacoustic profiles are used, one for each blocktype */
62 static vorbis_info_mapping0 _mapping_set_short={
63   1, {0,0}, {0}, {0}, {0}, {0,1}, 0,{0},{0}};
64 static vorbis_info_mapping0 _mapping_set_long={
65   1, {0,0}, {0}, {1}, {1}, {2,3}, 0,{0},{0}};
66
67 static int vorbis_encode_toplevel_setup(vorbis_info *vi,int small,int large,int ch,long rate){
68   if(vi && vi->codec_setup){
69     codec_setup_info *ci=vi->codec_setup;
70
71     vi->version=0;
72     vi->channels=ch;
73     vi->rate=rate;
74     
75     ci->blocksizes[0]=small;
76     ci->blocksizes[1]=large;
77
78     /* time mapping hooks are unused in vorbis I */
79     ci->times=1;
80     ci->time_type[0]=0;
81     ci->time_param[0]=calloc(1,sizeof(_time_dummy));
82     memcpy(ci->time_param[0],&_time_dummy,sizeof(_time_dummy));
83
84     /* by convention, two modes: one for short, one for long blocks.
85        short block mode uses mapping sero, long block uses mapping 1 */
86     ci->modes=2;
87     ci->mode_param[0]=calloc(1,sizeof(_mode_set_short));
88     memcpy(ci->mode_param[0],&_mode_set_short,sizeof(_mode_set_short));
89     ci->mode_param[1]=calloc(1,sizeof(_mode_set_long));
90     memcpy(ci->mode_param[1],&_mode_set_long,sizeof(_mode_set_long));
91
92     /* by convention two mappings, both mapping type zero (polyphonic
93        PCM), first for short, second for long blocks */
94     ci->maps=2;
95     ci->map_type[0]=0;
96     ci->map_param[0]=calloc(1,sizeof(_mapping_set_short));
97     memcpy(ci->map_param[0],&_mapping_set_short,sizeof(_mapping_set_short));
98     ci->map_type[1]=0;
99     ci->map_param[1]=calloc(1,sizeof(_mapping_set_long));
100     memcpy(ci->map_param[1],&_mapping_set_long,sizeof(_mapping_set_long));
101
102     return(0);
103   }
104   return(OV_EINVAL);
105 }
106
107 static int vorbis_encode_floor_setup(vorbis_info *vi,double q,int block,
108                                     static_codebook    ***books, 
109                                     vorbis_info_floor1 *in, 
110                                     ...){
111   int x[11],i,k,iq=rint(q*10);
112   vorbis_info_floor1 *f=calloc(1,sizeof(*f));
113   codec_setup_info *ci=vi->codec_setup;
114   va_list ap;
115
116   va_start(ap,in);
117   for(i=0;i<11;i++)
118     x[i]=va_arg(ap,int);
119   va_end(ap);
120
121   memcpy(f,in+x[iq],sizeof(*f));
122   /* fill in the lowpass field, even if it's temporary */
123   f->n=ci->blocksizes[block]>>1;
124
125   /* books */
126   {
127     int partitions=f->partitions;
128     int maxclass=-1;
129     int maxbook=-1;
130     for(i=0;i<partitions;i++)
131       if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
132     for(i=0;i<=maxclass;i++){
133       if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
134       f->class_book[i]+=ci->books;
135       for(k=0;k<(1<<f->class_subs[i]);k++){
136         if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
137         if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
138       }
139     }
140
141     for(i=0;i<=maxbook;i++)
142       ci->book_param[ci->books++]=books[x[iq]][i];
143   }
144
145   /* for now, we're only using floor 1 */
146   ci->floor_type[ci->floors]=1;
147   ci->floor_param[ci->floors]=f;
148   ci->floors++;
149
150   return(0);
151 }
152
153 static int vorbis_encode_global_psych_setup(vorbis_info *vi,double q,
154                                            vorbis_info_psy_global *in, ...){
155   int i,iq=q*10;
156   double x[11],dq;
157   codec_setup_info *ci=vi->codec_setup;
158   vorbis_info_psy_global *g=&ci->psy_g_param;
159   va_list ap;
160   
161   va_start(ap,in);
162   for(i=0;i<11;i++)
163     x[i]=va_arg(ap,double);
164   va_end(ap);
165
166   if(iq==10){
167     iq=9;
168     dq=1.;
169   }else{
170     dq=q*10.-iq;
171   }
172
173   memcpy(g,in+(int)x[iq],sizeof(*g));
174
175   dq=x[iq]*(1.-dq)+x[iq+1]*dq;
176   iq=(int)dq;
177   dq-=iq;
178   if(dq==0 && iq>0){
179     iq--;
180     dq=1.;
181   }
182
183   /* interpolate the trigger threshholds */
184   for(i=0;i<4;i++){
185     g->preecho_thresh[i]=in[iq].preecho_thresh[i]*(1.-dq)+in[iq+1].preecho_thresh[i]*dq;
186     g->postecho_thresh[i]=in[iq].postecho_thresh[i]*(1.-dq)+in[iq+1].postecho_thresh[i]*dq;
187   }
188   g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
189   return(0);
190 }
191
192 static int vorbis_encode_psyset_setup(vorbis_info *vi,int block){
193   codec_setup_info *ci=vi->codec_setup;
194   vorbis_info_psy *p=ci->psy_param[block];
195
196   if(block>=ci->psys)
197     ci->psys=block+1;
198   if(!p){
199     p=calloc(1,sizeof(*p));
200     ci->psy_param[block]=p;
201   }
202
203   memcpy(p,&_psy_info_template,sizeof(*p));
204
205   return 0;
206 }
207
208 static int vorbis_encode_tonemask_setup(vorbis_info *vi,double q,int block,
209                                        double *att,
210                                        double *max,
211                                        int *peaklimit_bands,
212                                        vp_adjblock *in){
213   int i,j,iq;
214   double dq;
215   codec_setup_info *ci=vi->codec_setup;
216   vorbis_info_psy *p=ci->psy_param[block];
217
218   iq=q*10;
219   if(iq==10){
220     iq=9;
221     dq=1.;
222   }else{
223     dq=q*10.-iq;
224   }
225
226   p->tone_masteratt=att[iq]*(1.-dq)+att[iq+1]*dq;
227   p->max_curve_dB=max[iq];
228   p->curvelimitp=peaklimit_bands[iq];
229
230   iq=q*5.;
231   if(iq==5){
232     iq=5;
233     dq=1.;
234   }else{
235     dq=q*5.-iq;
236   }
237   
238   for(i=0;i<P_BANDS;i++)
239     for(j=0;j<P_LEVELS;j++)
240       p->toneatt.block[i][j]=(j<4?4:j)*-10.+
241         in[iq].block[i][j]*(1.-dq)+in[iq+1].block[i][j]*dq;
242   return(0);
243 }
244
245
246 static int vorbis_encode_compand_setup(vorbis_info *vi,double q,int block,
247                                       float in[][NOISE_COMPAND_LEVELS], ...){
248   int i,iq=q*10;
249   double x[11],dq;
250   codec_setup_info *ci=vi->codec_setup;
251   vorbis_info_psy *p=ci->psy_param[block];
252   va_list ap;
253   
254   va_start(ap,in);
255   for(i=0;i<11;i++)
256     x[i]=va_arg(ap,double);
257   va_end(ap);
258
259   if(iq==10){
260     iq=9;
261     dq=1.;
262   }else{
263     dq=q*10.-iq;
264   }
265
266   dq=x[iq]*(1.-dq)+x[iq+1]*dq;
267   iq=(int)dq;
268   dq-=iq;
269   if(dq==0 && iq>0){
270     iq--;
271     dq=1.;
272   }
273
274   /* interpolate the compander settings */
275   for(i=0;i<NOISE_COMPAND_LEVELS;i++)
276     p->noisecompand[i]=in[iq][i]*(1.-dq)+in[iq+1][i]*dq;
277   return(0);
278 }
279
280 static int vorbis_encode_peak_setup(vorbis_info *vi,double q,int block,
281                                     double *guard,
282                                     double *suppress,
283                                     vp_adjblock *in){
284   int i,j,iq;
285   double dq;
286   codec_setup_info *ci=vi->codec_setup;
287   vorbis_info_psy *p=ci->psy_param[block];
288
289   iq=q*10;
290   if(iq==10){
291     iq=9;
292     dq=1.;
293   }else{
294     dq=q*10.-iq;
295   }
296
297   p->peakattp=1;
298   p->tone_guard=guard[iq]*(1.-dq)+guard[iq+1]*dq;
299   p->tone_abs_limit=suppress[iq]*(1.-dq)+suppress[iq+1]*dq;
300
301   iq=q*5.;
302   if(iq==5){
303     iq=5;
304     dq=1.;
305   }else{
306     dq=q*5.-iq;
307   }
308
309   for(i=0;i<P_BANDS;i++)
310     for(j=0;j<P_LEVELS;j++)
311       p->peakatt.block[i][j]=(j<4?4:j)*-10.+
312         in[iq].block[i][j]*(1.-dq)+in[iq+1].block[i][j]*dq;
313   return(0);
314 }
315
316 static int vorbis_encode_noisebias_setup(vorbis_info *vi,double q,int block,
317                                          double *suppress,
318                                          int in[][17],int guard[33]){
319   int i,iq=q*10;
320   double dq;
321   codec_setup_info *ci=vi->codec_setup;
322   vorbis_info_psy *p=ci->psy_param[block];
323
324   if(iq==10){
325     iq=9;
326     dq=1.;
327   }else{
328     dq=q*10.-iq;
329   }
330
331   p->noisemaxsupp=suppress[iq]*(1.-dq)+suppress[iq+1]*dq;
332   p->noisewindowlomin=guard[iq*3];
333   p->noisewindowhimin=guard[iq*3+1];
334   p->noisewindowfixed=guard[iq*3+2];
335   
336   for(i=0;i<P_BANDS;i++)
337     p->noiseoff[i]=in[iq][i]*(1.-dq)+in[iq+1][i]*dq;
338   return(0);
339 }
340
341 static int vorbis_encode_ath_setup(vorbis_info *vi,double q,int block,
342                                    float in[][27], ...){
343   int i,iq=q*10;
344   double x[11],dq;
345   codec_setup_info *ci=vi->codec_setup;
346   vorbis_info_psy *p=ci->psy_param[block];
347   va_list ap;
348   
349   va_start(ap,in);
350   for(i=0;i<11;i++)
351     x[i]=va_arg(ap,double);
352   va_end(ap);
353
354   p->ath_adjatt=ci->hi.ath_floating_dB;
355   p->ath_maxatt=ci->hi.ath_absolute_dB;
356
357   if(iq==10){
358     iq=9;
359     dq=1.;
360   }else{
361     dq=q*10.-iq;
362   }
363
364   dq=x[iq]*(1.-dq)+x[iq+1]*dq;
365   iq=(int)dq;
366   dq-=iq;
367   if(dq==0 && iq>0){
368     iq--;
369     dq=1.;
370   }
371
372   for(i=0;i<27;i++)
373     p->ath[i]=in[iq][i]*(1.-dq)+in[iq+1][i]*dq;
374   return(0);
375 }
376
377
378 static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
379   int i;
380   for(i=0;i<ci->books;i++)
381     if(ci->book_param[i]==book)return(i);
382   
383   return(ci->books++);
384 }
385
386 static int vorbis_encode_residue_setup(vorbis_info *vi,double q,int block,
387                                        int coupled_p,
388                                        int stereo_backfill_p,
389                                        int residue_backfill_p,
390                                        vorbis_residue_template *in,
391                                        int point_dB,
392                                        double point_kHz){
393
394   int i,iq=q*10;
395   int n,k;
396   int partition_position=0;
397   int res_position=0;
398   int iterations=1;
399   int amplitude_select=0;
400
401   codec_setup_info *ci=vi->codec_setup;
402   vorbis_info_residue0 *r;
403   vorbis_info_psy *psy=ci->psy_param[block*2];
404   
405   /* may be re-called due to ctl */
406   if(ci->residue_param[block])
407     /* free preexisting instance */
408     residue_free_info(ci->residue_param[block],ci->residue_type[block]);
409
410   r=ci->residue_param[block]=malloc(sizeof(*r));
411   memcpy(r,in[iq].res[block],sizeof(*r));
412   if(ci->residues<=block)ci->residues=block+1;
413
414   if(block){
415     r->grouping=32;
416   }else{
417     r->grouping=16;
418   }
419
420   /* for uncoupled, we use type 1, else type 2 */
421   if(coupled_p){
422     ci->residue_type[block]=2;
423   }else{
424     ci->residue_type[block]=1;
425   }
426
427   switch(ci->residue_type[block]){
428   case 1:
429     n=r->end=ci->blocksizes[block?1:0]>>1; /* to be adjusted by lowpass later */
430     partition_position=rint(point_kHz*1000./(vi->rate/2)*n/r->grouping);
431     res_position=partition_position*r->grouping;
432     break;
433   case 2:
434     n=r->end=(ci->blocksizes[block?1:0]>>1)*vi->channels; /* to be adjusted by lowpass later */
435     partition_position=rint(point_kHz*1000./(vi->rate/2)*n/r->grouping);
436     res_position=partition_position*r->grouping/vi->channels;
437     break;
438   }
439
440   for(i=0;i<r->partitions;i++)
441     if(r->blimit[i]<0)r->blimit[i]=partition_position;
442
443   for(i=0;i<r->partitions;i++)
444     for(k=0;k<3;k++)
445       if(in[iq].books_base[point_dB][i][k])
446         r->secondstages[i]|=(1<<k);
447   
448   ci->passlimit[0]=3;
449     
450   if(coupled_p){
451     vorbis_info_mapping0 *map=ci->map_param[block];
452
453     map->coupling_steps=1;
454     map->coupling_mag[0]=0;
455     map->coupling_ang[0]=1;
456
457     psy->couple_pass[0].granulem=1.;
458     psy->couple_pass[0].igranulem=1.;
459
460     psy->couple_pass[0].couple_pass[0].limit=res_position;
461     psy->couple_pass[0].couple_pass[0].outofphase_redundant_flip_p=1;
462     psy->couple_pass[0].couple_pass[0].outofphase_requant_limit=9e10;
463     psy->couple_pass[0].couple_pass[0].amppost_point=0;
464     psy->couple_pass[0].couple_pass[1].limit=9999;
465     psy->couple_pass[0].couple_pass[1].outofphase_redundant_flip_p=1;
466     psy->couple_pass[0].couple_pass[1].outofphase_requant_limit=9e10;
467     psy->couple_pass[0].couple_pass[1].amppost_point=
468       stereo_threshholds[point_dB];
469     amplitude_select=point_dB;
470
471     if(stereo_backfill_p && amplitude_select){
472       memcpy(psy->couple_pass+iterations,psy->couple_pass+iterations-1,
473              sizeof(*psy->couple_pass));
474       psy->couple_pass[1].couple_pass[1].amppost_point=stereo_threshholds[amplitude_select-1];
475       ci->passlimit[1]=4;
476       for(i=0;i<r->partitions;i++)
477         if(in[iq].books_stereo_backfill[amplitude_select][i])
478           r->secondstages[i]|=8;
479       amplitude_select=amplitude_select-1;
480       iterations++;
481     }
482     
483     if(residue_backfill_p){
484       memcpy(psy->couple_pass+iterations,psy->couple_pass+iterations-1,
485              sizeof(*psy->couple_pass));
486       psy->couple_pass[iterations].granulem=.333333333;
487       psy->couple_pass[iterations].igranulem=3.;
488       psy->couple_pass[iterations].couple_pass[0].outofphase_requant_limit=1.;
489       psy->couple_pass[iterations].couple_pass[1].outofphase_requant_limit=1.;
490       for(i=0;i<r->partitions;i++)
491         if(in[iq].books_residue_backfill[amplitude_select][i][0])
492           r->secondstages[i]|=(1<<(iterations+2));
493       ci->passlimit[iterations]=ci->passlimit[iterations-1]+1;
494       iterations++;
495       
496       memcpy(psy->couple_pass+iterations,psy->couple_pass+iterations-1,
497              sizeof(*psy->couple_pass));
498       psy->couple_pass[iterations].granulem=.1111111111;
499       psy->couple_pass[iterations].igranulem=9.;
500       psy->couple_pass[iterations].couple_pass[0].outofphase_requant_limit=.3;
501       psy->couple_pass[iterations].couple_pass[1].outofphase_requant_limit=.3;
502       for(i=0;i<r->partitions;i++)
503         if(in[iq].books_residue_backfill[amplitude_select][i][1])
504           r->secondstages[i]|=(1<<(iterations+2));
505       ci->passlimit[iterations]=ci->passlimit[iterations-1]+1;
506       iterations++;
507     }
508     ci->coupling_passes=iterations;
509
510   }else{
511
512     if(residue_backfill_p){
513       for(i=0;i<r->partitions;i++){
514         if(in[iq].books_residue_backfill[0][i][0])
515           r->secondstages[i]|=8;
516         if(in[iq].books_residue_backfill[0][i][1])
517           r->secondstages[i]|=16;
518       }
519       ci->passlimit[1]=4;
520       ci->passlimit[2]=5;
521       ci->coupling_passes=3;
522     }else
523       ci->coupling_passes=1;
524   }
525   
526   memcpy(&ci->psy_param[block*2+1]->couple_pass,
527          &ci->psy_param[block*2]->couple_pass,
528          sizeof(psy->couple_pass));
529   
530   /* fill in all the books */
531   {
532     int booklist=0,k;
533     r->groupbook=ci->books;
534     ci->book_param[ci->books++]=in[iq].book_aux[block];
535     for(i=0;i<r->partitions;i++){
536       for(k=0;k<3;k++){
537         if(in[iq].books_base[point_dB][i][k]){
538           int bookid=book_dup_or_new(ci,in[iq].books_base[point_dB][i][k]);
539           r->booklist[booklist++]=bookid;
540           ci->book_param[bookid]=in[iq].books_base[point_dB][i][k];
541         }
542       }
543       if(coupled_p && stereo_backfill_p && point_dB &&
544          in[iq].books_stereo_backfill[point_dB][i]){
545         int bookid=book_dup_or_new(ci,in[iq].books_stereo_backfill[point_dB][i]);
546         r->booklist[booklist++]=bookid;
547         ci->book_param[bookid]=in[iq].books_stereo_backfill[point_dB][i];
548       }
549       if(residue_backfill_p){
550         for(k=0;k<2;k++){
551           if(in[iq].books_residue_backfill[amplitude_select][i][k]){
552             int bookid=book_dup_or_new(ci,in[iq].books_residue_backfill[amplitude_select][i][k]);
553             r->booklist[booklist++]=bookid;
554             ci->book_param[bookid]=in[iq].books_residue_backfill[amplitude_select][i][k];
555           }
556         }
557       }
558     }
559   }
560
561   return(0);
562 }      
563
564 static int vorbis_encode_lowpass_setup(vorbis_info *vi,double q,int block){
565   int iq=q*10;
566   double dq;
567   double freq;
568   codec_setup_info *ci=vi->codec_setup;
569   vorbis_info_floor1 *f=ci->floor_param[block];
570   vorbis_info_residue0 *r=ci->residue_param[block];
571   int blocksize=ci->blocksizes[block]>>1;
572   double nyq=vi->rate/2.;
573
574   if(iq==10){
575     iq=9;
576     dq=1.;
577   }else{
578     dq=q*10.-iq;
579   }
580   
581   freq=ci->hi.lowpass_kHz[block]*1000.;
582   if(freq>vi->rate/2)freq=vi->rate/2;
583   /* lowpass needs to be set in the floor and the residue. */
584
585   /* in the floor, the granularity can be very fine; it doesn't alter
586      the encoding structure, only the samples used to fit the floor
587      approximation */
588   f->n=freq/nyq*blocksize;
589
590   /* in the residue, we're constrained, physically, by partition
591      boundaries.  We still lowpass 'wherever', but we have to round up
592      here to next boundary, or the vorbis spec will round it *down* to
593      previous boundary in encode/decode */
594   if(ci->residue_type[block]==2)
595     r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
596       r->grouping;
597   else
598     r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
599       r->grouping;
600   return(0);
601 }
602
603 /* encoders will need to use vorbis_info_init beforehand and call
604    vorbis_info clear when all done */
605
606 /* two interfaces; this, more detailed one, and later a convenience
607    layer on top */
608
609 /* the final setup call */
610 int vorbis_encode_setup_init(vorbis_info *vi){
611   int ret=0;
612   /*long rate=vi->rate;*/
613   long channels=vi->channels;
614   codec_setup_info *ci=vi->codec_setup;
615   highlevel_encode_setup *hi=&ci->hi;
616
617   ret|=vorbis_encode_floor_setup(vi,hi->base_quality_short,0,
618                                 _floor_44_128_books,_floor_44_128,
619                                 0,1,1,2,2,2,2,2,2,2,2);
620   ret|=vorbis_encode_floor_setup(vi,hi->base_quality_long,1,
621                                 _floor_44_1024_books,_floor_44_1024,
622                                 0,0,0,0,0,0,0,0,0,0,0);
623   
624   ret|=vorbis_encode_global_psych_setup(vi,hi->trigger_quality,_psy_global_44,
625                                        0., 1., 1.5, 2., 2., 2., 2., 2., 2., 2., 2.);
626
627   ret|=vorbis_encode_psyset_setup(vi,0);
628   ret|=vorbis_encode_psyset_setup(vi,1);
629   ret|=vorbis_encode_psyset_setup(vi,2);
630   ret|=vorbis_encode_psyset_setup(vi,3);
631   
632   ret|=vorbis_encode_tonemask_setup(vi,hi->blocktype[0].tone_mask_quality,0,
633                                     _psy_tone_masteratt,_psy_tone_0dB,_psy_ehmer_bandlimit,
634                                     _vp_tonemask_adj_otherblock);
635   ret|=vorbis_encode_tonemask_setup(vi,hi->blocktype[1].tone_mask_quality,1,
636                                     _psy_tone_masteratt,_psy_tone_0dB,_psy_ehmer_bandlimit,
637                                     _vp_tonemask_adj_otherblock);
638   ret|=vorbis_encode_tonemask_setup(vi,hi->blocktype[2].tone_mask_quality,2,
639                                     _psy_tone_masteratt,_psy_tone_0dB,_psy_ehmer_bandlimit,
640                                     _vp_tonemask_adj_otherblock);
641   ret|=vorbis_encode_tonemask_setup(vi,hi->blocktype[3].tone_mask_quality,3,
642                                     _psy_tone_masteratt,_psy_tone_0dB,_psy_ehmer_bandlimit,
643                                     _vp_tonemask_adj_longblock);
644   
645   ret|=vorbis_encode_compand_setup(vi,hi->blocktype[0].noise_compand_quality,
646                                   0,_psy_compand_44_short,
647                                   1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.);
648   ret|=vorbis_encode_compand_setup(vi,hi->blocktype[1].noise_compand_quality,
649                                   1,_psy_compand_44_short,
650                                   1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.);
651   ret|=vorbis_encode_compand_setup(vi,hi->blocktype[2].noise_compand_quality,
652                                   2,_psy_compand_44,
653                                   1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.);
654   ret|=vorbis_encode_compand_setup(vi,hi->blocktype[3].noise_compand_quality,
655                                   3,_psy_compand_44,
656                                   1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.);
657   ret|=vorbis_encode_peak_setup(vi,hi->blocktype[0].tone_peaklimit_quality,
658                                 0,_psy_tone_masterguard,_psy_tone_suppress,
659                                 _vp_peakguard);
660   ret|=vorbis_encode_peak_setup(vi,hi->blocktype[1].tone_peaklimit_quality,
661                                 1,_psy_tone_masterguard,_psy_tone_suppress,
662                                 _vp_peakguard);
663   ret|=vorbis_encode_peak_setup(vi,hi->blocktype[2].tone_peaklimit_quality,
664                                 2,_psy_tone_masterguard,_psy_tone_suppress,
665                                 _vp_peakguard);
666   ret|=vorbis_encode_peak_setup(vi,hi->blocktype[3].tone_peaklimit_quality,
667                                 3,_psy_tone_masterguard,_psy_tone_suppress,
668                                 _vp_peakguard);
669
670   if(hi->impulse_block_p){
671     ret|=vorbis_encode_noisebias_setup(vi,hi->blocktype[0].noise_bias_quality,
672                                        0,_psy_noise_suppress,_psy_noisebias_impulse,
673                                        _psy_noiseguards_short);
674   }else{
675     ret|=vorbis_encode_noisebias_setup(vi,hi->blocktype[0].noise_bias_quality,
676                                        0,_psy_noise_suppress,_psy_noisebias_other,
677                                        _psy_noiseguards_short);
678   }
679
680   ret|=vorbis_encode_noisebias_setup(vi,hi->blocktype[1].noise_bias_quality,
681                                     1,_psy_noise_suppress,_psy_noisebias_other,
682                                       _psy_noiseguards_short);
683   ret|=vorbis_encode_noisebias_setup(vi,hi->blocktype[2].noise_bias_quality,
684                                       2,_psy_noise_suppress,_psy_noisebias_other,
685                                     _psy_noiseguards_long);
686   ret|=vorbis_encode_noisebias_setup(vi,hi->blocktype[3].noise_bias_quality,
687                                     3,_psy_noise_suppress,_psy_noisebias_long,
688                                     _psy_noiseguards_long);
689
690   ret|=vorbis_encode_ath_setup(vi,hi->blocktype[0].ath_quality,0,ATH_Bark_dB,
691                               0., 0., 0., 0., .2, .5, 1., 1., 1.5, 2., 2.);
692   ret|=vorbis_encode_ath_setup(vi,hi->blocktype[1].ath_quality,1,ATH_Bark_dB,
693                               0., 0., 0., 0., .2, .5, 1., 1., 1.5, 2., 2.);
694   ret|=vorbis_encode_ath_setup(vi,hi->blocktype[2].ath_quality,2,ATH_Bark_dB,
695                               0., 0., 0., 0., .2, .5, 1., 1., 1.5, 2., 2.);
696   ret|=vorbis_encode_ath_setup(vi,hi->blocktype[3].ath_quality,3,ATH_Bark_dB,
697                               0., 0., 0., 0., .2, .5, 1., 1., 1.5, 2., 2.);
698
699   if(ret){
700     vorbis_info_clear(vi);
701     return ret; 
702   }
703
704   if(channels==2 && hi->stereo_couple_p){
705     /* setup specific to stereo coupling */
706     
707     ret|=vorbis_encode_residue_setup(vi,hi->base_quality_short,0,
708                                     1, /* coupled */
709                                     hi->stereo_backfill_p,
710                                     hi->residue_backfill_p, 
711                                     _residue_template_44_stereo,
712                                     hi->stereo_point_dB,
713                                     hi->stereo_point_kHz[0]);
714       
715     ret|=vorbis_encode_residue_setup(vi,hi->base_quality_long,1,
716                                     1, /* coupled */
717                                     hi->stereo_backfill_p,
718                                     hi->residue_backfill_p, 
719                                     _residue_template_44_stereo,
720                                     hi->stereo_point_dB,
721                                     hi->stereo_point_kHz[1]);
722
723   }else{
724     /* setup specific to non-stereo (mono or uncoupled polyphonic)
725        coupling */
726     ret|=vorbis_encode_residue_setup(vi,hi->base_quality_short,0,
727                                     0, /* uncoupled */
728                                     0,
729                                     hi->residue_backfill_p, 
730                                     _residue_template_44_uncoupled,
731                                     0,
732                                     hi->stereo_point_kHz[0]); /* just
733                                     used as an encoding partitioning
734                                     point */
735       
736     ret|=vorbis_encode_residue_setup(vi,hi->base_quality_long,1,
737                                     0, /* uncoupled */
738                                     0,
739                                     hi->residue_backfill_p, 
740                                     _residue_template_44_uncoupled,
741                                     0,
742                                     hi->stereo_point_kHz[1]); /* just
743                                     used as an encoding partitioning
744                                     point */
745   }
746   ret|=vorbis_encode_lowpass_setup(vi,hi->lowpass_kHz[0],0);
747   ret|=vorbis_encode_lowpass_setup(vi,hi->lowpass_kHz[1],1);
748     
749   if(ret)
750     vorbis_info_clear(vi);
751   return(ret);
752
753 }
754
755 /* this is only tuned for 44.1kHz right now.  S'ok, for other rates it
756    just doesn't guess */
757 static double ratepch_un44[11]=
758     {40000.,50000.,60000.,70000.,75000.,85000.,105000.,
759      115000.,135000.,160000.,250000.};
760 static double ratepch_st44[11]=
761     {32000.,40000.,48000.,56000.,64000.,
762      80000.,96000.,112000.,128000.,160000.,250000.};
763
764 static double vbr_to_approx_bitrate(int ch,int coupled,
765                                     double q,long srate){
766   int iq=q*10.;
767   double dq;
768   double *r=NULL;
769
770   if(iq==10){
771     iq=9;
772     dq=1.;
773   }else{
774     dq=q*10.-iq;
775   }
776
777   if(srate>42000 && srate<46000){
778     if(coupled)
779       r=ratepch_st44;
780     else
781       r=ratepch_un44;
782   }
783   
784   if(r==NULL)
785     return(-1);
786   
787   return((r[iq]*(1.-dq)+r[iq+1]*dq)*ch);  
788 }
789
790 static double approx_bitrate_to_vbr(int ch,int coupled,
791                                     double bitrate,long srate){
792   double *r=NULL,del;
793   int i;
794
795   if(srate>42000 && srate<46000){
796     if(coupled)
797       r=ratepch_st44;
798     else
799       r=ratepch_un44;
800   }
801   
802   if(r==NULL)
803     return(-1.);
804
805   bitrate/=ch;
806
807   if(bitrate<=r[0])return(0.);
808   for(i=0;i<10;i++)
809     if(r[i]<bitrate && r[i+1]>=bitrate)break;
810   if(i==10)return(10.);
811
812   del=(bitrate-r[i])/(r[i+1]-r[i]);
813   
814   return((i+del)*.1);
815 }
816
817 /* only populates the high-level settings so that we can tweak with ctl before final setup */
818 int vorbis_encode_setup_vbr(vorbis_info *vi,
819                             long channels,
820                             long rate,
821                             
822                             float base_quality){
823   int ret=0,i,iq;
824   double dq;
825   codec_setup_info *ci=vi->codec_setup;
826   highlevel_encode_setup *hi=&ci->hi;
827   
828   base_quality+=.0001;
829   if(base_quality<0.)base_quality=0.;
830   if(base_quality>.999)base_quality=.999;
831
832   iq=base_quality*10;
833   if(iq==10){
834     iq=9;
835     dq=1.;
836   }else{
837     dq=base_quality*10.-iq;
838   }
839
840   ret|=vorbis_encode_toplevel_setup(vi,256,2048,channels,rate);
841   hi->base_quality=base_quality;
842   hi->base_quality_short=base_quality;
843   hi->base_quality_long=base_quality;
844   hi->trigger_quality=base_quality;
845
846   for(i=0;i<4;i++){
847     hi->blocktype[i].tone_mask_quality=base_quality;
848     hi->blocktype[i].tone_peaklimit_quality=base_quality;
849     hi->blocktype[i].noise_bias_quality=base_quality;
850     hi->blocktype[i].noise_compand_quality=base_quality;
851     hi->blocktype[i].ath_quality=base_quality;
852   }
853
854   hi->short_block_p=1;
855   hi->long_block_p=1;
856   hi->impulse_block_p=1;
857   hi->amplitude_track_dBpersec=-6.;
858
859   hi->stereo_couple_p=1; /* only relevant if a two channel input */
860   hi->stereo_backfill_p=0;
861   hi->residue_backfill_p=0;
862
863   /* set the ATH floaters */
864   hi->ath_floating_dB=_psy_ath_floater[iq]*(1.-dq)+_psy_ath_floater[iq+1]*dq;
865   hi->ath_absolute_dB=_psy_ath_abs[iq]*(1.-dq)+_psy_ath_abs[iq+1]*dq;
866
867   /* set stereo dB and Hz */
868   hi->stereo_point_dB=_psy_stereo_point_dB_44[iq];
869   hi->stereo_point_kHz[0]=_psy_stereo_point_kHz_44[0][iq]*(1.-dq)+
870     _psy_stereo_point_kHz_44[0][iq+1]*dq;
871   hi->stereo_point_kHz[1]=_psy_stereo_point_kHz_44[1][iq]*(1.-dq)+
872     _psy_stereo_point_kHz_44[1][iq+1]*dq;
873   
874   /* set lowpass */
875   hi->lowpass_kHz[0]=
876     hi->lowpass_kHz[1]=
877     _psy_lowpass_44[iq]*(1.-dq)+_psy_lowpass_44[iq+1]*dq;
878
879   /* set bitrate approximation */
880   vi->bitrate_nominal=vbr_to_approx_bitrate(vi->channels,hi->stereo_couple_p,
881                                             base_quality,vi->rate);
882   vi->bitrate_lower=-1;
883   vi->bitrate_upper=-1;
884   vi->bitrate_window=-1;
885
886   return(ret);
887 }
888
889 int vorbis_encode_init_vbr(vorbis_info *vi,
890                            long channels,
891                            long rate,
892                            
893                            float base_quality /* 0. to 1. */
894                            ){
895   int ret=0;
896
897   ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
898   
899   if(ret){
900     vorbis_info_clear(vi);
901     return ret; 
902   }
903   ret=vorbis_encode_setup_init(vi);
904   if(ret)
905     vorbis_info_clear(vi);
906   return(ret);
907 }
908
909 int vorbis_encode_setup_managed(vorbis_info *vi,
910                                 long channels,
911                                 long rate,
912                                 
913                                 long max_bitrate,
914                                 long nominal_bitrate,
915                                 long min_bitrate){
916
917   double approx_vbr=approx_bitrate_to_vbr(channels,(channels==2), 
918                                           (float)nominal_bitrate,rate);
919   int ret=0;
920   if(approx_vbr<0)return(OV_EIMPL);
921
922   if(nominal_bitrate<=0.){
923     if(max_bitrate>0.){
924       nominal_bitrate=max_bitrate*.875;
925     }else{
926       if(min_bitrate>0.){
927         nominal_bitrate=min_bitrate;
928       }else{
929         return(OV_EINVAL);
930       }
931     }
932   }
933
934   ret=vorbis_encode_setup_vbr(vi,channels,rate,approx_vbr);
935   if(ret){
936     vorbis_info_clear(vi);
937     return ret; 
938   }
939
940   /* adjust to make management's life easier.  Use the ctl() interface
941      once it's implemented */
942   {
943     codec_setup_info *ci=vi->codec_setup;
944     highlevel_encode_setup *hi=&ci->hi;
945
946     /* backfills */
947     hi->stereo_backfill_p=1;
948     hi->residue_backfill_p=1;
949
950     /* no impulse blocks */
951     hi->impulse_block_p=0;
952     /* de-rate stereo */
953     if(hi->stereo_point_dB && hi->stereo_couple_p && channels==2){
954       hi->stereo_point_dB++;
955       if(hi->stereo_point_dB>3)hi->stereo_point_dB=3;
956     }      
957     /* slug the vbr noise setting*/
958     hi->blocktype[0].noise_bias_quality-=.1;
959     if(hi->blocktype[0].noise_bias_quality<0.)
960       hi->blocktype[0].noise_bias_quality=0.;
961     hi->blocktype[1].noise_bias_quality-=.1;
962     if(hi->blocktype[1].noise_bias_quality<0.)
963       hi->blocktype[1].noise_bias_quality=0.;
964     hi->blocktype[2].noise_bias_quality-=.05;
965     if(hi->blocktype[2].noise_bias_quality<0.)
966       hi->blocktype[2].noise_bias_quality=0.;
967     hi->blocktype[3].noise_bias_quality-=.05;
968     if(hi->blocktype[3].noise_bias_quality<0.)
969       hi->blocktype[3].noise_bias_quality=0.;
970    
971     /* initialize management.  Currently hardcoded for 44, but so is above. */
972     memcpy(&ci->bi,&_bm_44_default,sizeof(ci->bi));
973     ci->bi.queue_hardmin=min_bitrate;
974     ci->bi.queue_hardmax=max_bitrate;
975     
976     ci->bi.queue_avgmin=nominal_bitrate;
977     ci->bi.queue_avgmax=nominal_bitrate;
978
979     /* adjust management */
980     if(max_bitrate<=0. && min_bitrate<=0.){
981       /* just an average tracker; no reason for the window to be as small as 2s. */
982       ci->bi.queue_avg_time=4.;
983     }
984     ci->bi.avgfloat_noise_maxval=_bm_max_noise_offset[(int)approx_vbr];
985     /*if(max_bitrate>0.){
986       ci->bi.avgfloat_minimum=0.;
987       }*/
988
989   }
990   return(ret);
991 }
992
993 int vorbis_encode_init(vorbis_info *vi,
994                        long channels,
995                        long rate,
996
997                        long max_bitrate,
998                        long nominal_bitrate,
999                        long min_bitrate){
1000
1001   int ret=vorbis_encode_setup_managed(vi,channels,rate,
1002                                       max_bitrate,
1003                                       nominal_bitrate,
1004                                       min_bitrate);
1005   if(ret){
1006     vorbis_info_clear(vi);
1007     return(ret);
1008   }
1009
1010   ret=vorbis_encode_setup_init(vi);
1011   if(ret)
1012     vorbis_info_clear(vi);
1013   return(ret);
1014 }
1015
1016 int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
1017   return(OV_EIMPL);
1018 }
1019                        
1020
1021
1022
1023
1024
1025
1026