synced with r22428
[mplayer/greg.git] / libaf / af.c
blobe76af0821e3ccec7e26d5b3282cb31e507b9f3a3
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
5 #ifdef HAVE_MALLOC_H
6 #include <malloc.h>
7 #endif
9 #include "af.h"
11 // Static list of filters
12 extern af_info_t af_info_dummy;
13 extern af_info_t af_info_delay;
14 extern af_info_t af_info_channels;
15 extern af_info_t af_info_format;
16 extern af_info_t af_info_resample;
17 extern af_info_t af_info_volume;
18 extern af_info_t af_info_equalizer;
19 extern af_info_t af_info_gate;
20 extern af_info_t af_info_comp;
21 extern af_info_t af_info_pan;
22 extern af_info_t af_info_surround;
23 extern af_info_t af_info_sub;
24 extern af_info_t af_info_export;
25 extern af_info_t af_info_volnorm;
26 extern af_info_t af_info_extrastereo;
27 extern af_info_t af_info_lavcresample;
28 extern af_info_t af_info_sweep;
29 extern af_info_t af_info_hrtf;
30 extern af_info_t af_info_ladspa;
31 extern af_info_t af_info_center;
32 extern af_info_t af_info_sinesuppress;
33 extern af_info_t af_info_karaoke;
35 static af_info_t* filter_list[]={
36 &af_info_dummy,
37 &af_info_delay,
38 &af_info_channels,
39 &af_info_format,
40 &af_info_resample,
41 &af_info_volume,
42 &af_info_equalizer,
43 &af_info_gate,
44 &af_info_comp,
45 &af_info_pan,
46 &af_info_surround,
47 &af_info_sub,
48 #ifdef HAVE_SYS_MMAN_H
49 &af_info_export,
50 #endif
51 &af_info_volnorm,
52 &af_info_extrastereo,
53 #ifdef USE_LIBAVCODEC
54 &af_info_lavcresample,
55 #endif
56 &af_info_sweep,
57 &af_info_hrtf,
58 #ifdef HAVE_LADSPA
59 &af_info_ladspa,
60 #endif
61 &af_info_center,
62 &af_info_sinesuppress,
63 &af_info_karaoke,
64 NULL
67 // Message printing
68 af_msg_cfg_t af_msg_cfg={0,NULL,NULL};
70 // CPU speed
71 int* af_cpu_speed = NULL;
73 /* Find a filter in the static list of filters using it's name. This
74 function is used internally */
75 static af_info_t* af_find(char*name)
77 int i=0;
78 while(filter_list[i]){
79 if(!strcmp(filter_list[i]->name,name))
80 return filter_list[i];
81 i++;
83 af_msg(AF_MSG_ERROR,"Couldn't find audio filter '%s'\n",name);
84 return NULL;
87 /* Find filter in the dynamic filter list using it's name This
88 function is used for finding already initialized filters */
89 af_instance_t* af_get(af_stream_t* s, char* name)
91 af_instance_t* af=s->first;
92 // Find the filter
93 while(af != NULL){
94 if(!strcmp(af->info->name,name))
95 return af;
96 af=af->next;
98 return NULL;
101 /*/ Function for creating a new filter of type name. The name may
102 contain the commandline parameters for the filter */
103 static af_instance_t* af_create(af_stream_t* s, char* name)
105 char* cmdline = name;
107 // Allocate space for the new filter and reset all pointers
108 af_instance_t* new=malloc(sizeof(af_instance_t));
109 if(!new){
110 af_msg(AF_MSG_ERROR,"[libaf] Could not allocate memory\n");
111 goto err_out;
113 memset(new,0,sizeof(af_instance_t));
115 // Check for commandline parameters
116 strsep(&cmdline, "=");
118 // Find filter from name
119 if(NULL == (new->info=af_find(name)))
120 goto err_out;
122 /* Make sure that the filter is not already in the list if it is
123 non-reentrant */
124 if(new->info->flags & AF_FLAGS_NOT_REENTRANT){
125 if(af_get(s,name)){
126 af_msg(AF_MSG_ERROR,"[libaf] There can only be one instance of"
127 " the filter '%s' in each stream\n",name);
128 goto err_out;
132 af_msg(AF_MSG_VERBOSE,"[libaf] Adding filter %s \n",name);
134 // Initialize the new filter
135 if(AF_OK == new->info->open(new) &&
136 AF_ERROR < new->control(new,AF_CONTROL_POST_CREATE,&s->cfg)){
137 if(cmdline){
138 if(AF_ERROR<new->control(new,AF_CONTROL_COMMAND_LINE,cmdline))
139 return new;
141 else
142 return new;
145 err_out:
146 free(new);
147 af_msg(AF_MSG_ERROR,"[libaf] Couldn't create or open audio filter '%s'\n",
148 name);
149 return NULL;
152 /* Create and insert a new filter of type name before the filter in the
153 argument. This function can be called during runtime, the return
154 value is the new filter */
155 static af_instance_t* af_prepend(af_stream_t* s, af_instance_t* af, char* name)
157 // Create the new filter and make sure it is OK
158 af_instance_t* new=af_create(s,name);
159 if(!new)
160 return NULL;
161 // Update pointers
162 new->next=af;
163 if(af){
164 new->prev=af->prev;
165 af->prev=new;
167 else
168 s->last=new;
169 if(new->prev)
170 new->prev->next=new;
171 else
172 s->first=new;
173 return new;
176 /* Create and insert a new filter of type name after the filter in the
177 argument. This function can be called during runtime, the return
178 value is the new filter */
179 static af_instance_t* af_append(af_stream_t* s, af_instance_t* af, char* name)
181 // Create the new filter and make sure it is OK
182 af_instance_t* new=af_create(s,name);
183 if(!new)
184 return NULL;
185 // Update pointers
186 new->prev=af;
187 if(af){
188 new->next=af->next;
189 af->next=new;
191 else
192 s->first=new;
193 if(new->next)
194 new->next->prev=new;
195 else
196 s->last=new;
197 return new;
200 // Uninit and remove the filter "af"
201 void af_remove(af_stream_t* s, af_instance_t* af)
203 if(!af) return;
205 // Print friendly message
206 af_msg(AF_MSG_VERBOSE,"[libaf] Removing filter %s \n",af->info->name);
208 // Notify filter before changing anything
209 af->control(af,AF_CONTROL_PRE_DESTROY,0);
211 // Detach pointers
212 if(af->prev)
213 af->prev->next=af->next;
214 else
215 s->first=af->next;
216 if(af->next)
217 af->next->prev=af->prev;
218 else
219 s->last=af->prev;
221 // Uninitialize af and free memory
222 af->uninit(af);
223 free(af);
226 /* Reinitializes all filters downstream from the filter given in the
227 argument the return value is AF_OK if success and AF_ERROR if
228 failure */
229 static int af_reinit(af_stream_t* s, af_instance_t* af)
232 af_data_t in; // Format of the input to current filter
233 int rv=0; // Return value
235 // Check if there are any filters left in the list
236 if(NULL == af){
237 if(!(af=af_append(s,s->first,"dummy")))
238 return AF_UNKNOWN;
239 else
240 return AF_ERROR;
243 // Check if this is the first filter
244 if(!af->prev)
245 memcpy(&in,&(s->input),sizeof(af_data_t));
246 else
247 memcpy(&in,af->prev->data,sizeof(af_data_t));
248 // Reset just in case...
249 in.audio=NULL;
250 in.len=0;
252 rv = af->control(af,AF_CONTROL_REINIT,&in);
253 switch(rv){
254 case AF_OK:
255 af = af->next;
256 break;
257 case AF_FALSE:{ // Configuration filter is needed
258 // Do auto insertion only if force is not specified
259 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
260 af_instance_t* new = NULL;
261 // Insert channels filter
262 if((af->prev?af->prev->data->nch:s->input.nch) != in.nch){
263 // Create channels filter
264 if(NULL == (new = af_prepend(s,af,"channels")))
265 return AF_ERROR;
266 // Set number of output channels
267 if(AF_OK != (rv = new->control(new,AF_CONTROL_CHANNELS,&in.nch)))
268 return rv;
269 // Initialize channels filter
270 if(!new->prev)
271 memcpy(&in,&(s->input),sizeof(af_data_t));
272 else
273 memcpy(&in,new->prev->data,sizeof(af_data_t));
274 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
275 return rv;
277 // Insert format filter
278 if((af->prev?af->prev->data->format:s->input.format) != in.format){
279 // Create format filter
280 if(NULL == (new = af_prepend(s,af,"format")))
281 return AF_ERROR;
282 // Set output bits per sample
283 in.format |= af_bits2fmt(in.bps*8);
284 if(AF_OK != (rv = new->control(new,AF_CONTROL_FORMAT_FMT,&in.format)))
285 return rv;
286 // Initialize format filter
287 if(!new->prev)
288 memcpy(&in,&(s->input),sizeof(af_data_t));
289 else
290 memcpy(&in,new->prev->data,sizeof(af_data_t));
291 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
292 return rv;
294 if(!new){ // Should _never_ happen
295 af_msg(AF_MSG_ERROR,"[libaf] Unable to correct audio format. "
296 "This error should never uccur, please send bugreport.\n");
297 return AF_ERROR;
299 af=new->next;
301 else {
302 af_msg(AF_MSG_ERROR, "[libaf] Automatic filter insertion disabled "
303 "but formats do not match. Giving up.\n");
304 return AF_ERROR;
306 break;
308 case AF_DETACH:{ // Filter is redundant and wants to be unloaded
309 // Do auto remove only if force is not specified
310 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
311 af_instance_t* aft=af->prev;
312 af_remove(s,af);
313 if(aft)
314 af=aft->next;
315 else
316 af=s->first; // Restart configuration
318 break;
320 default:
321 af_msg(AF_MSG_ERROR,"[libaf] Reinitialization did not work, audio"
322 " filter '%s' returned error code %i\n",af->info->name,rv);
323 return AF_ERROR;
325 }while(af);
326 return AF_OK;
329 // Uninit and remove all filters
330 void af_uninit(af_stream_t* s)
332 while(s->first)
333 af_remove(s,s->first);
336 /* Initialize the stream "s". This function creates a new filter list
337 if necessary according to the values set in input and output. Input
338 and output should contain the format of the current movie and the
339 formate of the preferred output respectively. The function is
340 reentrant i.e. if called with an already initialized stream the
341 stream will be reinitialized.
342 If one of the prefered output parameters is 0 the one that needs
343 no conversion is used (i.e. the output format in the last filter).
344 The return value is 0 if success and -1 if failure */
345 int af_init(af_stream_t* s)
347 int i=0;
349 // Sanity check
350 if(!s) return -1;
352 // Precaution in case caller is misbehaving
353 s->input.audio = s->output.audio = NULL;
354 s->input.len = s->output.len = 0;
356 // Figure out how fast the machine is
357 if(AF_INIT_AUTO == (AF_INIT_TYPE_MASK & s->cfg.force))
358 s->cfg.force = (s->cfg.force & ~AF_INIT_TYPE_MASK) | AF_INIT_TYPE;
360 // Check if this is the first call
361 if(!s->first){
362 // Add all filters in the list (if there are any)
363 if(!s->cfg.list){ // To make automatic format conversion work
364 if(!af_append(s,s->first,"dummy"))
365 return -1;
367 else{
368 while(s->cfg.list[i]){
369 if(!af_append(s,s->last,s->cfg.list[i++]))
370 return -1;
375 // Init filters
376 if(AF_OK != af_reinit(s,s->first))
377 return -1;
379 // make sure the chain is not empty and valid (e.g. because of AF_DETACH)
380 if (!s->first)
381 if (!af_append(s,s->first,"dummy") || AF_OK != af_reinit(s,s->first))
382 return -1;
384 // Check output format
385 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
386 af_instance_t* af = NULL; // New filter
387 // Check output frequency if not OK fix with resample
388 if(s->output.rate && s->last->data->rate!=s->output.rate){
389 // try to find a filter that can change samplrate
390 af = af_control_any_rev(s, AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
391 &(s->output.rate));
392 if (!af) {
393 char *resampler = "resample";
394 #ifdef USE_LIBAVCODEC
395 if ((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_SLOW)
396 resampler = "lavcresample";
397 #endif
398 if((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_SLOW){
399 if(!strcmp(s->first->info->name,"format"))
400 af = af_append(s,s->first,resampler);
401 else
402 af = af_prepend(s,s->first,resampler);
404 else{
405 if(!strcmp(s->last->info->name,"format"))
406 af = af_prepend(s,s->last,resampler);
407 else
408 af = af_append(s,s->last,resampler);
410 // Init the new filter
411 if(!af || (AF_OK != af->control(af,AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
412 &(s->output.rate))))
413 return -1;
414 // Use lin int if the user wants fast
415 if ((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_FAST) {
416 char args[32];
417 sprintf(args, "%d", s->output.rate);
418 #ifdef USE_LIBAVCODEC
419 if (strcmp(resampler, "lavcresample") == 0)
420 strcat(args, ":1");
421 else
422 #endif
423 strcat(args, ":0:0");
424 af->control(af, AF_CONTROL_COMMAND_LINE, args);
427 if(AF_OK != af_reinit(s,af))
428 return -1;
431 // Check number of output channels fix if not OK
432 // If needed always inserted last -> easy to screw up other filters
433 if(s->output.nch && s->last->data->nch!=s->output.nch){
434 if(!strcmp(s->last->info->name,"format"))
435 af = af_prepend(s,s->last,"channels");
436 else
437 af = af_append(s,s->last,"channels");
438 // Init the new filter
439 if(!af || (AF_OK != af->control(af,AF_CONTROL_CHANNELS,&(s->output.nch))))
440 return -1;
441 if(AF_OK != af_reinit(s,af))
442 return -1;
445 // Check output format fix if not OK
446 if(s->output.format != AF_FORMAT_UNKNOWN &&
447 s->last->data->format != s->output.format){
448 if(strcmp(s->last->info->name,"format"))
449 af = af_append(s,s->last,"format");
450 else
451 af = s->last;
452 // Init the new filter
453 s->output.format |= af_bits2fmt(s->output.bps*8);
454 if(!af || (AF_OK != af->control(af,AF_CONTROL_FORMAT_FMT,&(s->output.format))))
455 return -1;
456 if(AF_OK != af_reinit(s,af))
457 return -1;
460 // Re init again just in case
461 if(AF_OK != af_reinit(s,s->first))
462 return -1;
464 if (s->output.format == AF_FORMAT_UNKNOWN)
465 s->output.format = s->last->data->format;
466 if (!s->output.nch) s->output.nch = s->last->data->nch;
467 if (!s->output.rate) s->output.rate = s->last->data->rate;
468 if((s->last->data->format != s->output.format) ||
469 (s->last->data->nch != s->output.nch) ||
470 (s->last->data->rate != s->output.rate)) {
471 // Something is stuffed audio out will not work
472 af_msg(AF_MSG_ERROR,"[libaf] Unable to setup filter system can not"
473 " meet sound-card demands, please send bugreport. \n");
474 af_uninit(s);
475 return -1;
478 return 0;
481 /* Add filter during execution. This function adds the filter "name"
482 to the stream s. The filter will be inserted somewhere nice in the
483 list of filters. The return value is a pointer to the new filter,
484 If the filter couldn't be added the return value is NULL. */
485 af_instance_t* af_add(af_stream_t* s, char* name){
486 af_instance_t* new;
487 // Sanity check
488 if(!s || !s->first || !name)
489 return NULL;
490 // Insert the filter somwhere nice
491 if(!strcmp(s->first->info->name,"format"))
492 new = af_append(s, s->first, name);
493 else
494 new = af_prepend(s, s->first, name);
495 if(!new)
496 return NULL;
498 // Reinitalize the filter list
499 if(AF_OK != af_reinit(s, s->first)){
500 free(new);
501 return NULL;
503 return new;
506 // Filter data chunk through the filters in the list
507 af_data_t* af_play(af_stream_t* s, af_data_t* data)
509 af_instance_t* af=s->first;
510 // Iterate through all filters
512 if (data->len <= 0) break;
513 data=af->play(af,data);
514 af=af->next;
515 }while(af);
516 return data;
519 /* Helper function used to calculate the exact buffer length needed
520 when buffers are resized. The returned length is >= than what is
521 needed */
522 inline int af_lencalc(frac_t mul, af_data_t* d){
523 register int t = d->bps*d->nch;
524 return t*(((d->len/t)*mul.n)/mul.d + 1);
527 /* Calculate how long the output from the filters will be given the
528 input length "len". The calculated length is >= the actual
529 length. */
530 int af_outputlen(af_stream_t* s, int len)
532 int t = s->input.bps*s->input.nch;
533 af_instance_t* af=s->first;
534 frac_t mul = {1,1};
535 // Iterate through all filters
537 af_frac_mul(&mul, &af->mul);
538 af=af->next;
539 }while(af);
540 return t * (((len/t)*mul.n + 1)/mul.d);
543 /* Calculate how long the input to the filters should be to produce a
544 certain output length, i.e. the return value of this function is
545 the input length required to produce the output length "len". The
546 calculated length is <= the actual length */
547 int af_inputlen(af_stream_t* s, int len)
549 int t = s->input.bps*s->input.nch;
550 af_instance_t* af=s->first;
551 frac_t mul = {1,1};
552 // Iterate through all filters
554 af_frac_mul(&mul, &af->mul);
555 af=af->next;
556 }while(af);
557 return t * (((len/t) * mul.d - 1)/mul.n);
560 /* Calculate how long the input IN to the filters should be to produce
561 a certain output length OUT but with the following three constraints:
562 1. IN <= max_insize, where max_insize is the maximum possible input
563 block length
564 2. OUT <= max_outsize, where max_outsize is the maximum possible
565 output block length
566 3. If possible OUT >= len.
567 Return -1 in case of error */
568 int af_calc_insize_constrained(af_stream_t* s, int len,
569 int max_outsize,int max_insize)
571 int t = s->input.bps*s->input.nch;
572 int in = 0;
573 int out = 0;
574 af_instance_t* af=s->first;
575 frac_t mul = {1,1};
576 // Iterate through all filters and calculate total multiplication factor
578 af_frac_mul(&mul, &af->mul);
579 af=af->next;
580 }while(af);
581 // Sanity check
582 if(!mul.n || !mul.d)
583 return -1;
585 in = t * (((len/t) * mul.d - 1)/mul.n);
587 if(in>max_insize) in=t*(max_insize/t);
589 // Try to meet constraint nr 3.
590 while((out=t * (((in/t+1)*mul.n - 1)/mul.d)) <= max_outsize && in<=max_insize){
591 if( (t * (((in/t)*mul.n))/mul.d) >= len) return in;
592 in+=t;
595 // Could no meet constraint nr 3.
596 while(out > max_outsize || in > max_insize){
597 in-=t;
598 if(in<t) return -1; // Input parameters are probably incorrect
599 out = t * (((in/t)*mul.n + 1)/mul.d);
601 return in;
604 /* Calculate the total delay [ms] caused by the filters */
605 double af_calc_delay(af_stream_t* s)
607 af_instance_t* af=s->first;
608 register double delay = 0.0;
609 // Iterate through all filters
610 while(af){
611 delay += af->delay;
612 af=af->next;
614 return delay;
617 /* Helper function called by the macro with the same name this
618 function should not be called directly */
619 inline int af_resize_local_buffer(af_instance_t* af, af_data_t* data)
621 // Calculate new length
622 register int len = af_lencalc(af->mul,data);
623 af_msg(AF_MSG_VERBOSE,"[libaf] Reallocating memory in module %s, "
624 "old len = %i, new len = %i\n",af->info->name,af->data->len,len);
625 // If there is a buffer free it
626 if(af->data->audio)
627 free(af->data->audio);
628 // Create new buffer and check that it is OK
629 af->data->audio = malloc(len);
630 if(!af->data->audio){
631 af_msg(AF_MSG_FATAL,"[libaf] Could not allocate memory \n");
632 return AF_ERROR;
634 af->data->len=len;
635 return AF_OK;
638 // documentation in af.h
639 af_instance_t *af_control_any_rev (af_stream_t* s, int cmd, void* arg) {
640 int res = AF_UNKNOWN;
641 af_instance_t* filt = s->last;
642 while (filt) {
643 res = filt->control(filt, cmd, arg);
644 if (res == AF_OK)
645 return filt;
646 filt = filt->prev;
648 return NULL;
652 * \brief calculate greatest common divisior of a and b.
653 * \ingroup af_filter
655 * If both are 0 the result is 1.
657 int af_gcd(register int a, register int b) {
658 while (b != 0) {
659 a %= b;
660 if (a == 0)
661 break;
662 b %= a;
664 // the result is either in a or b. As the other one is 0 just add them.
665 a += b;
666 if (!a)
667 return 1;
668 return a;
672 * \brief cancel down a fraction f
673 * \param f fraction to cancel down
674 * \ingroup af_filter
676 void af_frac_cancel(frac_t *f) {
677 int gcd = af_gcd(f->n, f->d);
678 f->n /= gcd;
679 f->d /= gcd;
683 * \brief multiply out by in and store result in out.
684 * \param out [inout] fraction to multiply by in
685 * \param in [in] fraction to multiply out by
686 * \ingroup af_filter
688 * the resulting fraction will be cancelled down
689 * if in and out were.
691 void af_frac_mul(frac_t *out, const frac_t *in) {
692 int gcd1 = af_gcd(out->n, in->d);
693 int gcd2 = af_gcd(in->n, out->d);
694 out->n = (out->n / gcd1) * (in->n / gcd2);
695 out->d = (out->d / gcd2) * (in->d / gcd1);
698 void af_help (void) {
699 int i = 0;
700 af_msg(AF_MSG_INFO, "Available audio filters:\n");
701 while (filter_list[i]) {
702 if (filter_list[i]->comment && filter_list[i]->comment[0])
703 af_msg(AF_MSG_INFO, " %-15s: %s (%s)\n", filter_list[i]->name, filter_list[i]->info, filter_list[i]->comment);
704 else
705 af_msg(AF_MSG_INFO, " %-15s: %s\n", filter_list[i]->name, filter_list[i]->info);
706 i++;
710 void af_fix_parameters(af_data_t *data)
712 data->bps = af_fmt2bits(data->format)/8;