gl_common: minor cleanup/refactor
[mplayer.git] / libaf / af.c
blobe4015727acd3396f85577865d1e0ec1ba5ee6000
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "config.h"
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include "osdep/strsep.h"
25 #include "af.h"
27 // Static list of filters
28 extern af_info_t af_info_dummy;
29 extern af_info_t af_info_delay;
30 extern af_info_t af_info_channels;
31 extern af_info_t af_info_format;
32 extern af_info_t af_info_resample;
33 extern af_info_t af_info_volume;
34 extern af_info_t af_info_equalizer;
35 extern af_info_t af_info_gate;
36 extern af_info_t af_info_comp;
37 extern af_info_t af_info_pan;
38 extern af_info_t af_info_surround;
39 extern af_info_t af_info_sub;
40 extern af_info_t af_info_export;
41 extern af_info_t af_info_volnorm;
42 extern af_info_t af_info_extrastereo;
43 extern af_info_t af_info_lavcac3enc;
44 extern af_info_t af_info_lavcresample;
45 extern af_info_t af_info_sweep;
46 extern af_info_t af_info_hrtf;
47 extern af_info_t af_info_ladspa;
48 extern af_info_t af_info_center;
49 extern af_info_t af_info_sinesuppress;
50 extern af_info_t af_info_karaoke;
51 extern af_info_t af_info_scaletempo;
52 extern af_info_t af_info_stats;
53 extern af_info_t af_info_bs2b;
55 static af_info_t* filter_list[]={
56 &af_info_dummy,
57 &af_info_delay,
58 &af_info_channels,
59 &af_info_format,
60 &af_info_resample,
61 &af_info_volume,
62 &af_info_equalizer,
63 &af_info_gate,
64 &af_info_comp,
65 &af_info_pan,
66 &af_info_surround,
67 &af_info_sub,
68 #ifdef HAVE_SYS_MMAN_H
69 &af_info_export,
70 #endif
71 &af_info_volnorm,
72 &af_info_extrastereo,
73 &af_info_lavcac3enc,
74 &af_info_lavcresample,
75 &af_info_sweep,
76 &af_info_hrtf,
77 #ifdef CONFIG_LADSPA
78 &af_info_ladspa,
79 #endif
80 &af_info_center,
81 &af_info_sinesuppress,
82 &af_info_karaoke,
83 &af_info_scaletempo,
84 &af_info_stats,
85 #ifdef CONFIG_LIBBS2B
86 &af_info_bs2b,
87 #endif
88 NULL
91 // CPU speed
92 int* af_cpu_speed = NULL;
94 /* Find a filter in the static list of filters using it's name. This
95 function is used internally */
96 static af_info_t* af_find(char*name)
98 int i=0;
99 while(filter_list[i]){
100 if(!strcmp(filter_list[i]->name,name))
101 return filter_list[i];
102 i++;
104 mp_msg(MSGT_AFILTER, MSGL_ERR, "Couldn't find audio filter '%s'\n",name);
105 return NULL;
108 /* Find filter in the dynamic filter list using it's name This
109 function is used for finding already initialized filters */
110 af_instance_t* af_get(af_stream_t* s, char* name)
112 af_instance_t* af=s->first;
113 // Find the filter
114 while(af != NULL){
115 if(!strcmp(af->info->name,name))
116 return af;
117 af=af->next;
119 return NULL;
122 /*/ Function for creating a new filter of type name. The name may
123 contain the commandline parameters for the filter */
124 static af_instance_t* af_create(af_stream_t* s, const char* name_with_cmd)
126 char* name = strdup(name_with_cmd);
127 char* cmdline = name;
129 // Allocate space for the new filter and reset all pointers
130 af_instance_t* new=malloc(sizeof(af_instance_t));
131 if (!name || !new) {
132 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Could not allocate memory\n");
133 goto err_out;
135 memset(new,0,sizeof(af_instance_t));
137 // Check for commandline parameters
138 strsep(&cmdline, "=");
140 // Find filter from name
141 if(NULL == (new->info=af_find(name)))
142 goto err_out;
144 /* Make sure that the filter is not already in the list if it is
145 non-reentrant */
146 if(new->info->flags & AF_FLAGS_NOT_REENTRANT){
147 if(af_get(s,name)){
148 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] There can only be one instance of"
149 " the filter '%s' in each stream\n",name);
150 goto err_out;
154 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Adding filter %s \n",name);
156 // Initialize the new filter
157 if(AF_OK == new->info->open(new) &&
158 AF_ERROR < new->control(new,AF_CONTROL_POST_CREATE,&s->cfg)){
159 if(cmdline){
160 if(AF_ERROR>=new->control(new,AF_CONTROL_COMMAND_LINE,cmdline))
161 goto err_out;
163 free(name);
164 return new;
167 err_out:
168 free(new);
169 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Couldn't create or open audio filter '%s'\n",
170 name);
171 free(name);
172 return NULL;
175 /* Create and insert a new filter of type name before the filter in the
176 argument. This function can be called during runtime, the return
177 value is the new filter */
178 static af_instance_t* af_prepend(af_stream_t* s, af_instance_t* af, const char* name)
180 // Create the new filter and make sure it is OK
181 af_instance_t* new=af_create(s,name);
182 if(!new)
183 return NULL;
184 // Update pointers
185 new->next=af;
186 if(af){
187 new->prev=af->prev;
188 af->prev=new;
190 else
191 s->last=new;
192 if(new->prev)
193 new->prev->next=new;
194 else
195 s->first=new;
196 return new;
199 /* Create and insert a new filter of type name after the filter in the
200 argument. This function can be called during runtime, the return
201 value is the new filter */
202 static af_instance_t* af_append(af_stream_t* s, af_instance_t* af, const char* name)
204 // Create the new filter and make sure it is OK
205 af_instance_t* new=af_create(s,name);
206 if(!new)
207 return NULL;
208 // Update pointers
209 new->prev=af;
210 if(af){
211 new->next=af->next;
212 af->next=new;
214 else
215 s->first=new;
216 if(new->next)
217 new->next->prev=new;
218 else
219 s->last=new;
220 return new;
223 // Uninit and remove the filter "af"
224 void af_remove(af_stream_t* s, af_instance_t* af)
226 if(!af) return;
228 // Print friendly message
229 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Removing filter %s \n",af->info->name);
231 // Notify filter before changing anything
232 af->control(af,AF_CONTROL_PRE_DESTROY,0);
234 // Detach pointers
235 if(af->prev)
236 af->prev->next=af->next;
237 else
238 s->first=af->next;
239 if(af->next)
240 af->next->prev=af->prev;
241 else
242 s->last=af->prev;
244 // Uninitialize af and free memory
245 af->uninit(af);
246 free(af);
249 static void print_fmt(af_data_t *d)
251 if (d) {
252 mp_msg(MSGT_AFILTER, MSGL_V, "%dHz/%dch/%s", d->rate, d->nch,
253 af_fmt2str_short(d->format));
254 } else {
255 mp_msg(MSGT_AFILTER, MSGL_V, "(?)");
259 static void af_print_filter_chain(af_stream_t* s)
261 mp_msg(MSGT_AFILTER, MSGL_V, "Audio filter chain:\n");
263 mp_msg(MSGT_AFILTER, MSGL_V, " [in] ");
264 print_fmt(&s->input);
265 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
267 af_instance_t *af = s->first;
268 while (af) {
269 mp_msg(MSGT_AFILTER, MSGL_V, " [%s] ", af->info->name);
270 print_fmt(af->data);
271 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
273 af = af->next;
276 mp_msg(MSGT_AFILTER, MSGL_V, " [out] ");
277 print_fmt(&s->output);
278 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
281 // Warning:
282 // A failed af_reinit() leaves the audio chain behind in a useless, broken
283 // state (for example, format filters that were tentatively inserted stay
284 // inserted).
285 // In that case, you should always rebuild the filter chain, or abort.
286 int af_reinit(af_stream_t* s, af_instance_t* af)
289 af_data_t in; // Format of the input to current filter
290 int rv=0; // Return value
292 // Check if there are any filters left in the list
293 if(NULL == af){
294 if(!(af=af_append(s,s->first,"dummy")))
295 return AF_UNKNOWN;
296 else
297 return AF_ERROR;
300 // Check if this is the first filter
301 if(!af->prev)
302 memcpy(&in,&(s->input),sizeof(af_data_t));
303 else
304 memcpy(&in,af->prev->data,sizeof(af_data_t));
305 // Reset just in case...
306 in.audio=NULL;
307 in.len=0;
309 rv = af->control(af,AF_CONTROL_REINIT,&in);
310 switch(rv){
311 case AF_OK:
312 af = af->next;
313 break;
314 case AF_FALSE:{ // Configuration filter is needed
315 // Do auto insertion only if force is not specified
316 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
317 af_instance_t* new = NULL;
318 // Insert channels filter
319 if((af->prev?af->prev->data->nch:s->input.nch) != in.nch){
320 // Create channels filter
321 if(NULL == (new = af_prepend(s,af,"channels")))
322 return AF_ERROR;
323 // Set number of output channels
324 if(AF_OK != (rv = new->control(new,AF_CONTROL_CHANNELS,&in.nch)))
325 return rv;
326 // Initialize channels filter
327 if(!new->prev)
328 memcpy(&in,&(s->input),sizeof(af_data_t));
329 else
330 memcpy(&in,new->prev->data,sizeof(af_data_t));
331 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
332 return rv;
334 // Insert format filter
335 if((af->prev?af->prev->data->format:s->input.format) != in.format){
336 // Create format filter
337 if(NULL == (new = af_prepend(s,af,"format")))
338 return AF_ERROR;
339 // Set output bits per sample
340 in.format |= af_bits2fmt(in.bps*8);
341 if(AF_OK != (rv = new->control(new,AF_CONTROL_FORMAT_FMT,&in.format)))
342 return rv;
343 // Initialize format filter
344 if(!new->prev)
345 memcpy(&in,&(s->input),sizeof(af_data_t));
346 else
347 memcpy(&in,new->prev->data,sizeof(af_data_t));
348 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
349 return rv;
351 if(!new){ // Should _never_ happen
352 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Unable to correct audio format. "
353 "This error should never uccur, please send bugreport.\n");
354 return AF_ERROR;
356 af=new->next;
358 else {
359 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Automatic filter insertion disabled "
360 "but formats do not match. Giving up.\n");
361 return AF_ERROR;
363 break;
365 case AF_DETACH:{ // Filter is redundant and wants to be unloaded
366 // Do auto remove only if force is not specified
367 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
368 af_instance_t* aft=af->prev;
369 af_remove(s,af);
370 if(aft)
371 af=aft->next;
372 else
373 af=s->first; // Restart configuration
375 break;
377 default:
378 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Reinitialization did not work, audio"
379 " filter '%s' returned error code %i\n",af->info->name,rv);
380 return AF_ERROR;
382 }while(af);
384 af_print_filter_chain(s);
386 return AF_OK;
389 // Uninit and remove all filters
390 void af_uninit(af_stream_t* s)
392 while(s->first)
393 af_remove(s,s->first);
397 * Extend the filter chain so we get the required output format at the end.
398 * \return AF_ERROR on error, AF_OK if successful.
400 static int fixup_output_format(af_stream_t* s)
402 af_instance_t* af = NULL;
403 // Check number of output channels fix if not OK
404 // If needed always inserted last -> easy to screw up other filters
405 if(s->output.nch && s->last->data->nch!=s->output.nch){
406 if(!strcmp(s->last->info->name,"format"))
407 af = af_prepend(s,s->last,"channels");
408 else
409 af = af_append(s,s->last,"channels");
410 // Init the new filter
411 if(!af || (AF_OK != af->control(af,AF_CONTROL_CHANNELS,&(s->output.nch))))
412 return AF_ERROR;
413 if(AF_OK != af_reinit(s,af))
414 return AF_ERROR;
417 // Check output format fix if not OK
418 if(s->output.format != AF_FORMAT_UNKNOWN &&
419 s->last->data->format != s->output.format){
420 if(strcmp(s->last->info->name,"format"))
421 af = af_append(s,s->last,"format");
422 else
423 af = s->last;
424 // Init the new filter
425 s->output.format |= af_bits2fmt(s->output.bps*8);
426 if(!af || (AF_OK != af->control(af,AF_CONTROL_FORMAT_FMT,&(s->output.format))))
427 return AF_ERROR;
428 if(AF_OK != af_reinit(s,af))
429 return AF_ERROR;
432 // Re init again just in case
433 if(AF_OK != af_reinit(s,s->first))
434 return AF_ERROR;
436 if (s->output.format == AF_FORMAT_UNKNOWN)
437 s->output.format = s->last->data->format;
438 if (!s->output.nch) s->output.nch = s->last->data->nch;
439 if (!s->output.rate) s->output.rate = s->last->data->rate;
440 if((s->last->data->format != s->output.format) ||
441 (s->last->data->nch != s->output.nch) ||
442 (s->last->data->rate != s->output.rate)) {
443 return AF_ERROR;
445 return AF_OK;
449 * Automatic downmix to stereo in case the codec does not implement it.
451 static void af_downmix(af_stream_t* s)
453 static const char * const downmix_strs[AF_NCH + 1] = {
454 /* FL FR RL RR FC LF AL AR */
455 [3] = "pan=2:" "0.6:0:" "0:0.6:" "0.4:0.4",
456 [4] = "pan=2:" "0.6:0:" "0:0.6:" "0.4:0:" "0:0.4",
457 [5] = "pan=2:" "0.5:0:" "0:0.5:" "0.2:0:" "0:0.2:" "0.3:0.3",
458 [6] = "pan=2:" "0.4:0:" "0:0.4:" "0.2:0:" "0:0.2:" "0.3:0.3:" "0.1:0.1",
459 [7] = "pan=2:" "0.4:0:" "0:0.4:" "0.2:0:" "0:0.2:" "0.3:0.3:" "0.1:0:" "0:0.1",
460 [8] = "pan=2:" "0.4:0:" "0:0.4:" "0.15:0:" "0:0.15:" "0.25:0.25:" "0.1:0.1:" "0.1:0:" "0:0.1",
462 const char *af_pan_str = downmix_strs[s->input.nch];
464 if (af_pan_str)
465 af_append(s, s->first, af_pan_str);
468 /* Initialize the stream "s". This function creates a new filter list
469 if necessary according to the values set in input and output. Input
470 and output should contain the format of the current movie and the
471 formate of the preferred output respectively. The function is
472 reentrant i.e. if called with an already initialized stream the
473 stream will be reinitialized.
474 If one of the prefered output parameters is 0 the one that needs
475 no conversion is used (i.e. the output format in the last filter).
476 The return value is 0 if success and -1 if failure */
477 int af_init(af_stream_t* s)
479 struct MPOpts *opts = s->opts;
480 int i=0;
482 // Sanity check
483 if(!s) return -1;
485 // Precaution in case caller is misbehaving
486 s->input.audio = s->output.audio = NULL;
487 s->input.len = s->output.len = 0;
489 // Figure out how fast the machine is
490 if(AF_INIT_AUTO == (AF_INIT_TYPE_MASK & s->cfg.force))
491 s->cfg.force = (s->cfg.force & ~AF_INIT_TYPE_MASK) | AF_INIT_TYPE;
493 // Check if this is the first call
494 if(!s->first){
495 // Append a downmix pan filter at the beginning of the chain if needed
496 if (s->input.nch != opts->audio_output_channels
497 && opts->audio_output_channels == 2)
498 af_downmix(s);
499 // Add all filters in the list (if there are any)
500 if (s->cfg.list) {
501 while(s->cfg.list[i]){
502 if(!af_append(s,s->last,s->cfg.list[i++]))
503 return -1;
508 // If we do not have any filters otherwise
509 // add dummy to make automatic format conversion work
510 if (!s->first && !af_append(s, s->first, "dummy"))
511 return -1;
513 // Init filters
514 if(AF_OK != af_reinit(s,s->first))
515 return -1;
517 // make sure the chain is not empty and valid (e.g. because of AF_DETACH)
518 if (!s->first)
519 if (!af_append(s,s->first,"dummy") || AF_OK != af_reinit(s,s->first))
520 return -1;
522 // Check output format
523 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
524 af_instance_t* af = NULL; // New filter
525 // Check output frequency if not OK fix with resample
526 if(s->output.rate && s->last->data->rate!=s->output.rate){
527 // try to find a filter that can change samplrate
528 af = af_control_any_rev(s, AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
529 &(s->output.rate));
530 if (!af) {
531 char *resampler = "resample";
532 if ((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_SLOW)
533 resampler = "lavcresample";
534 if((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_SLOW){
535 if(!strcmp(s->first->info->name,"format"))
536 af = af_append(s,s->first,resampler);
537 else
538 af = af_prepend(s,s->first,resampler);
540 else{
541 if(!strcmp(s->last->info->name,"format"))
542 af = af_prepend(s,s->last,resampler);
543 else
544 af = af_append(s,s->last,resampler);
546 // Init the new filter
547 if(!af || (AF_OK != af->control(af,AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
548 &(s->output.rate))))
549 return -1;
550 // Use lin int if the user wants fast
551 if ((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_FAST) {
552 char args[32];
553 sprintf(args, "%d", s->output.rate);
554 if (strcmp(resampler, "lavcresample") == 0)
555 strcat(args, ":1");
556 else
557 strcat(args, ":0:0");
558 af->control(af, AF_CONTROL_COMMAND_LINE, args);
561 if(AF_OK != af_reinit(s,af))
562 return -1;
564 if (AF_OK != fixup_output_format(s)) {
565 // Something is stuffed audio out will not work
566 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Unable to setup filter system can not"
567 " meet sound-card demands, please send bugreport. \n");
568 af_uninit(s);
569 return -1;
572 return 0;
575 /* Add filter during execution. This function adds the filter "name"
576 to the stream s. The filter will be inserted somewhere nice in the
577 list of filters. The return value is a pointer to the new filter,
578 If the filter couldn't be added the return value is NULL. */
579 af_instance_t* af_add(af_stream_t* s, char* name){
580 af_instance_t* new;
581 // Sanity check
582 if(!s || !s->first || !name)
583 return NULL;
584 // Insert the filter somwhere nice
585 if(!strcmp(s->first->info->name,"format"))
586 new = af_append(s, s->first, name);
587 else
588 new = af_prepend(s, s->first, name);
589 if(!new)
590 return NULL;
592 // Reinitalize the filter list
593 if(AF_OK != af_reinit(s, s->first) ||
594 AF_OK != fixup_output_format(s)){
595 while (s->first)
596 af_remove(s, s->first);
597 af_init(s);
598 return NULL;
600 return new;
603 // Filter data chunk through the filters in the list
604 af_data_t* af_play(af_stream_t* s, af_data_t* data)
606 af_instance_t* af=s->first;
607 // Iterate through all filters
609 if (data->len <= 0) break;
610 data=af->play(af,data);
611 af=af->next;
612 }while(af && data);
613 return data;
616 /* Calculate the minimum output buffer size for given input data d
617 * when using the RESIZE_LOCAL_BUFFER macro. The +t+1 part ensures the
618 * value is >= len*mul rounded upwards to whole samples even if the
619 * double 'mul' is inexact. */
620 int af_lencalc(double mul, af_data_t* d)
622 int t = d->bps * d->nch;
623 return d->len * mul + t + 1;
626 // Calculate average ratio of filter output size to input size
627 double af_calc_filter_multiplier(af_stream_t* s)
629 af_instance_t* af=s->first;
630 double mul = 1;
631 // Iterate through all filters and calculate total multiplication factor
633 mul *= af->mul;
634 af=af->next;
635 }while(af);
637 return mul;
640 /* Calculate the total delay [bytes output] caused by the filters */
641 double af_calc_delay(af_stream_t* s)
643 af_instance_t* af=s->first;
644 register double delay = 0.0;
645 // Iterate through all filters
646 while(af){
647 delay += af->delay;
648 delay *= af->mul;
649 af=af->next;
651 return delay;
654 /* Helper function called by the macro with the same name this
655 function should not be called directly */
656 int af_resize_local_buffer(af_instance_t* af, af_data_t* data)
658 // Calculate new length
659 register int len = af_lencalc(af->mul,data);
660 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Reallocating memory in module %s, "
661 "old len = %i, new len = %i\n",af->info->name,af->data->len,len);
662 // If there is a buffer free it
663 free(af->data->audio);
664 // Create new buffer and check that it is OK
665 af->data->audio = malloc(len);
666 if(!af->data->audio){
667 mp_msg(MSGT_AFILTER, MSGL_FATAL, "[libaf] Could not allocate memory \n");
668 return AF_ERROR;
670 af->data->len=len;
671 return AF_OK;
674 // documentation in af.h
675 af_instance_t *af_control_any_rev (af_stream_t* s, int cmd, void* arg) {
676 int res = AF_UNKNOWN;
677 af_instance_t* filt = s->last;
678 while (filt) {
679 res = filt->control(filt, cmd, arg);
680 if (res == AF_OK)
681 return filt;
682 filt = filt->prev;
684 return NULL;
687 void af_help (void) {
688 int i = 0;
689 mp_msg(MSGT_AFILTER, MSGL_INFO, "Available audio filters:\n");
690 while (filter_list[i]) {
691 if (filter_list[i]->comment && filter_list[i]->comment[0])
692 mp_msg(MSGT_AFILTER, MSGL_INFO, " %-15s: %s (%s)\n", filter_list[i]->name, filter_list[i]->info, filter_list[i]->comment);
693 else
694 mp_msg(MSGT_AFILTER, MSGL_INFO, " %-15s: %s\n", filter_list[i]->name, filter_list[i]->info);
695 i++;
699 void af_fix_parameters(af_data_t *data)
701 data->bps = af_fmt2bits(data->format)/8;