audio: add af_lavrresample, remove old resampling filters
[mplayer.git] / libaf / af.c
blob434943bd6ac793e7e19748e4749f012717cf680e
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_volume;
33 extern af_info_t af_info_equalizer;
34 extern af_info_t af_info_gate;
35 extern af_info_t af_info_comp;
36 extern af_info_t af_info_pan;
37 extern af_info_t af_info_surround;
38 extern af_info_t af_info_sub;
39 extern af_info_t af_info_export;
40 extern af_info_t af_info_volnorm;
41 extern af_info_t af_info_extrastereo;
42 extern af_info_t af_info_lavcac3enc;
43 extern af_info_t af_info_lavrresample;
44 extern af_info_t af_info_sweep;
45 extern af_info_t af_info_hrtf;
46 extern af_info_t af_info_ladspa;
47 extern af_info_t af_info_center;
48 extern af_info_t af_info_sinesuppress;
49 extern af_info_t af_info_karaoke;
50 extern af_info_t af_info_scaletempo;
51 extern af_info_t af_info_stats;
52 extern af_info_t af_info_bs2b;
54 static af_info_t* filter_list[]={
55 &af_info_dummy,
56 &af_info_delay,
57 &af_info_channels,
58 &af_info_format,
59 &af_info_volume,
60 &af_info_equalizer,
61 &af_info_gate,
62 &af_info_comp,
63 &af_info_pan,
64 &af_info_surround,
65 &af_info_sub,
66 #ifdef HAVE_SYS_MMAN_H
67 &af_info_export,
68 #endif
69 &af_info_volnorm,
70 &af_info_extrastereo,
71 &af_info_lavcac3enc,
72 &af_info_lavrresample,
73 &af_info_sweep,
74 &af_info_hrtf,
75 #ifdef CONFIG_LADSPA
76 &af_info_ladspa,
77 #endif
78 &af_info_center,
79 &af_info_sinesuppress,
80 &af_info_karaoke,
81 &af_info_scaletempo,
82 &af_info_stats,
83 #ifdef CONFIG_LIBBS2B
84 &af_info_bs2b,
85 #endif
86 NULL
89 // CPU speed
90 int* af_cpu_speed = NULL;
92 /* Find a filter in the static list of filters using it's name. This
93 function is used internally */
94 static af_info_t* af_find(char*name)
96 int i=0;
97 while(filter_list[i]){
98 if(!strcmp(filter_list[i]->name,name))
99 return filter_list[i];
100 i++;
102 mp_msg(MSGT_AFILTER, MSGL_ERR, "Couldn't find audio filter '%s'\n",name);
103 return NULL;
106 /* Find filter in the dynamic filter list using it's name This
107 function is used for finding already initialized filters */
108 af_instance_t* af_get(af_stream_t* s, char* name)
110 af_instance_t* af=s->first;
111 // Find the filter
112 while(af != NULL){
113 if(!strcmp(af->info->name,name))
114 return af;
115 af=af->next;
117 return NULL;
120 /*/ Function for creating a new filter of type name. The name may
121 contain the commandline parameters for the filter */
122 static af_instance_t* af_create(af_stream_t* s, const char* name_with_cmd)
124 char* name = strdup(name_with_cmd);
125 char* cmdline = name;
127 // Allocate space for the new filter and reset all pointers
128 af_instance_t* new=malloc(sizeof(af_instance_t));
129 if (!name || !new) {
130 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Could not allocate memory\n");
131 goto err_out;
133 memset(new,0,sizeof(af_instance_t));
135 // Check for commandline parameters
136 strsep(&cmdline, "=");
138 // Find filter from name
139 if(NULL == (new->info=af_find(name)))
140 goto err_out;
142 /* Make sure that the filter is not already in the list if it is
143 non-reentrant */
144 if(new->info->flags & AF_FLAGS_NOT_REENTRANT){
145 if(af_get(s,name)){
146 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] There can only be one instance of"
147 " the filter '%s' in each stream\n",name);
148 goto err_out;
152 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Adding filter %s \n",name);
154 // Initialize the new filter
155 if(AF_OK == new->info->open(new) &&
156 AF_ERROR < new->control(new,AF_CONTROL_POST_CREATE,&s->cfg)){
157 if(cmdline){
158 if(AF_ERROR>=new->control(new,AF_CONTROL_COMMAND_LINE,cmdline))
159 goto err_out;
161 free(name);
162 return new;
165 err_out:
166 free(new);
167 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Couldn't create or open audio filter '%s'\n",
168 name);
169 free(name);
170 return NULL;
173 /* Create and insert a new filter of type name before the filter in the
174 argument. This function can be called during runtime, the return
175 value is the new filter */
176 static af_instance_t* af_prepend(af_stream_t* s, af_instance_t* af, const char* name)
178 // Create the new filter and make sure it is OK
179 af_instance_t* new=af_create(s,name);
180 if(!new)
181 return NULL;
182 // Update pointers
183 new->next=af;
184 if(af){
185 new->prev=af->prev;
186 af->prev=new;
188 else
189 s->last=new;
190 if(new->prev)
191 new->prev->next=new;
192 else
193 s->first=new;
194 return new;
197 /* Create and insert a new filter of type name after the filter in the
198 argument. This function can be called during runtime, the return
199 value is the new filter */
200 static af_instance_t* af_append(af_stream_t* s, af_instance_t* af, const char* name)
202 // Create the new filter and make sure it is OK
203 af_instance_t* new=af_create(s,name);
204 if(!new)
205 return NULL;
206 // Update pointers
207 new->prev=af;
208 if(af){
209 new->next=af->next;
210 af->next=new;
212 else
213 s->first=new;
214 if(new->next)
215 new->next->prev=new;
216 else
217 s->last=new;
218 return new;
221 // Uninit and remove the filter "af"
222 void af_remove(af_stream_t* s, af_instance_t* af)
224 if(!af) return;
226 // Print friendly message
227 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Removing filter %s \n",af->info->name);
229 // Notify filter before changing anything
230 af->control(af,AF_CONTROL_PRE_DESTROY,0);
232 // Detach pointers
233 if(af->prev)
234 af->prev->next=af->next;
235 else
236 s->first=af->next;
237 if(af->next)
238 af->next->prev=af->prev;
239 else
240 s->last=af->prev;
242 // Uninitialize af and free memory
243 af->uninit(af);
244 free(af);
247 static void print_fmt(af_data_t *d)
249 if (d) {
250 mp_msg(MSGT_AFILTER, MSGL_V, "%dHz/%dch/%s", d->rate, d->nch,
251 af_fmt2str_short(d->format));
252 } else {
253 mp_msg(MSGT_AFILTER, MSGL_V, "(?)");
257 static void af_print_filter_chain(af_stream_t* s)
259 mp_msg(MSGT_AFILTER, MSGL_V, "Audio filter chain:\n");
261 mp_msg(MSGT_AFILTER, MSGL_V, " [in] ");
262 print_fmt(&s->input);
263 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
265 af_instance_t *af = s->first;
266 while (af) {
267 mp_msg(MSGT_AFILTER, MSGL_V, " [%s] ", af->info->name);
268 print_fmt(af->data);
269 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
271 af = af->next;
274 mp_msg(MSGT_AFILTER, MSGL_V, " [out] ");
275 print_fmt(&s->output);
276 mp_msg(MSGT_AFILTER, MSGL_V, "\n");
279 // Warning:
280 // A failed af_reinit() leaves the audio chain behind in a useless, broken
281 // state (for example, format filters that were tentatively inserted stay
282 // inserted).
283 // In that case, you should always rebuild the filter chain, or abort.
284 int af_reinit(af_stream_t* s, af_instance_t* af)
287 af_data_t in; // Format of the input to current filter
288 int rv=0; // Return value
290 // Check if there are any filters left in the list
291 if(NULL == af){
292 if(!(af=af_append(s,s->first,"dummy")))
293 return AF_UNKNOWN;
294 else
295 return AF_ERROR;
298 // Check if this is the first filter
299 if(!af->prev)
300 memcpy(&in,&(s->input),sizeof(af_data_t));
301 else
302 memcpy(&in,af->prev->data,sizeof(af_data_t));
303 // Reset just in case...
304 in.audio=NULL;
305 in.len=0;
307 rv = af->control(af,AF_CONTROL_REINIT,&in);
308 switch(rv){
309 case AF_OK:
310 af = af->next;
311 break;
312 case AF_FALSE:{ // Configuration filter is needed
313 // Do auto insertion only if force is not specified
314 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
315 af_instance_t* new = NULL;
316 // Insert channels filter
317 if((af->prev?af->prev->data->nch:s->input.nch) != in.nch){
318 // Create channels filter
319 if(NULL == (new = af_prepend(s,af,"channels")))
320 return AF_ERROR;
321 // Set number of output channels
322 if(AF_OK != (rv = new->control(new,AF_CONTROL_CHANNELS,&in.nch)))
323 return rv;
324 // Initialize channels filter
325 if(!new->prev)
326 memcpy(&in,&(s->input),sizeof(af_data_t));
327 else
328 memcpy(&in,new->prev->data,sizeof(af_data_t));
329 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
330 return rv;
332 // Insert format filter
333 if((af->prev?af->prev->data->format:s->input.format) != in.format){
334 // Create format filter
335 if(NULL == (new = af_prepend(s,af,"format")))
336 return AF_ERROR;
337 // Set output bits per sample
338 in.format |= af_bits2fmt(in.bps*8);
339 if(AF_OK != (rv = new->control(new,AF_CONTROL_FORMAT_FMT,&in.format)))
340 return rv;
341 // Initialize format filter
342 if(!new->prev)
343 memcpy(&in,&(s->input),sizeof(af_data_t));
344 else
345 memcpy(&in,new->prev->data,sizeof(af_data_t));
346 if(AF_OK != (rv = new->control(new,AF_CONTROL_REINIT,&in)))
347 return rv;
349 if(!new){ // Should _never_ happen
350 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Unable to correct audio format. "
351 "This error should never uccur, please send bugreport.\n");
352 return AF_ERROR;
354 af=new->next;
356 else {
357 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Automatic filter insertion disabled "
358 "but formats do not match. Giving up.\n");
359 return AF_ERROR;
361 break;
363 case AF_DETACH:{ // Filter is redundant and wants to be unloaded
364 // Do auto remove only if force is not specified
365 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
366 af_instance_t* aft=af->prev;
367 af_remove(s,af);
368 if(aft)
369 af=aft->next;
370 else
371 af=s->first; // Restart configuration
373 break;
375 default:
376 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Reinitialization did not work, audio"
377 " filter '%s' returned error code %i\n",af->info->name,rv);
378 return AF_ERROR;
380 }while(af);
382 af_print_filter_chain(s);
384 return AF_OK;
387 // Uninit and remove all filters
388 void af_uninit(af_stream_t* s)
390 while(s->first)
391 af_remove(s,s->first);
395 * Extend the filter chain so we get the required output format at the end.
396 * \return AF_ERROR on error, AF_OK if successful.
398 static int fixup_output_format(af_stream_t* s)
400 af_instance_t* af = NULL;
401 // Check number of output channels fix if not OK
402 // If needed always inserted last -> easy to screw up other filters
403 if(s->output.nch && s->last->data->nch!=s->output.nch){
404 if(!strcmp(s->last->info->name,"format"))
405 af = af_prepend(s,s->last,"channels");
406 else
407 af = af_append(s,s->last,"channels");
408 // Init the new filter
409 if(!af || (AF_OK != af->control(af,AF_CONTROL_CHANNELS,&(s->output.nch))))
410 return AF_ERROR;
411 if(AF_OK != af_reinit(s,af))
412 return AF_ERROR;
415 // Check output format fix if not OK
416 if(s->output.format != AF_FORMAT_UNKNOWN &&
417 s->last->data->format != s->output.format){
418 if(strcmp(s->last->info->name,"format"))
419 af = af_append(s,s->last,"format");
420 else
421 af = s->last;
422 // Init the new filter
423 s->output.format |= af_bits2fmt(s->output.bps*8);
424 if(!af || (AF_OK != af->control(af,AF_CONTROL_FORMAT_FMT,&(s->output.format))))
425 return AF_ERROR;
426 if(AF_OK != af_reinit(s,af))
427 return AF_ERROR;
430 // Re init again just in case
431 if(AF_OK != af_reinit(s,s->first))
432 return AF_ERROR;
434 if (s->output.format == AF_FORMAT_UNKNOWN)
435 s->output.format = s->last->data->format;
436 if (!s->output.nch) s->output.nch = s->last->data->nch;
437 if (!s->output.rate) s->output.rate = s->last->data->rate;
438 if((s->last->data->format != s->output.format) ||
439 (s->last->data->nch != s->output.nch) ||
440 (s->last->data->rate != s->output.rate)) {
441 return AF_ERROR;
443 return AF_OK;
447 * Automatic downmix to stereo in case the codec does not implement it.
449 static void af_downmix(af_stream_t* s)
451 static const char * const downmix_strs[AF_NCH + 1] = {
452 /* FL FR RL RR FC LF AL AR */
453 [3] = "pan=2:" "0.6:0:" "0:0.6:" "0.4:0.4",
454 [4] = "pan=2:" "0.6:0:" "0:0.6:" "0.4:0:" "0:0.4",
455 [5] = "pan=2:" "0.5:0:" "0:0.5:" "0.2:0:" "0:0.2:" "0.3:0.3",
456 [6] = "pan=2:" "0.4:0:" "0:0.4:" "0.2:0:" "0:0.2:" "0.3:0.3:" "0.1:0.1",
457 [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",
458 [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",
460 const char *af_pan_str = downmix_strs[s->input.nch];
462 if (af_pan_str)
463 af_append(s, s->first, af_pan_str);
466 /* Initialize the stream "s". This function creates a new filter list
467 if necessary according to the values set in input and output. Input
468 and output should contain the format of the current movie and the
469 formate of the preferred output respectively. The function is
470 reentrant i.e. if called with an already initialized stream the
471 stream will be reinitialized.
472 If one of the prefered output parameters is 0 the one that needs
473 no conversion is used (i.e. the output format in the last filter).
474 The return value is 0 if success and -1 if failure */
475 int af_init(af_stream_t* s)
477 struct MPOpts *opts = s->opts;
478 int i=0;
480 // Sanity check
481 if(!s) return -1;
483 // Precaution in case caller is misbehaving
484 s->input.audio = s->output.audio = NULL;
485 s->input.len = s->output.len = 0;
487 // Figure out how fast the machine is
488 if(AF_INIT_AUTO == (AF_INIT_TYPE_MASK & s->cfg.force))
489 s->cfg.force = (s->cfg.force & ~AF_INIT_TYPE_MASK) | AF_INIT_TYPE;
491 // Check if this is the first call
492 if(!s->first){
493 // Append a downmix pan filter at the beginning of the chain if needed
494 if (s->input.nch != opts->audio_output_channels
495 && opts->audio_output_channels == 2)
496 af_downmix(s);
497 // Add all filters in the list (if there are any)
498 if (s->cfg.list) {
499 while(s->cfg.list[i]){
500 if(!af_append(s,s->last,s->cfg.list[i++]))
501 return -1;
506 // If we do not have any filters otherwise
507 // add dummy to make automatic format conversion work
508 if (!s->first && !af_append(s, s->first, "dummy"))
509 return -1;
511 // Init filters
512 if(AF_OK != af_reinit(s,s->first))
513 return -1;
515 // make sure the chain is not empty and valid (e.g. because of AF_DETACH)
516 if (!s->first)
517 if (!af_append(s,s->first,"dummy") || AF_OK != af_reinit(s,s->first))
518 return -1;
520 // Check output format
521 if((AF_INIT_TYPE_MASK & s->cfg.force) != AF_INIT_FORCE){
522 af_instance_t* af = NULL; // New filter
523 // Check output frequency if not OK fix with resample
524 if(s->output.rate && s->last->data->rate!=s->output.rate){
525 // try to find a filter that can change samplrate
526 af = af_control_any_rev(s, AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
527 &(s->output.rate));
528 if (!af) {
529 char *resampler = "lavrresample";
530 if((AF_INIT_TYPE_MASK & s->cfg.force) == AF_INIT_SLOW){
531 if(!strcmp(s->first->info->name,"format"))
532 af = af_append(s,s->first,resampler);
533 else
534 af = af_prepend(s,s->first,resampler);
536 else{
537 if(!strcmp(s->last->info->name,"format"))
538 af = af_prepend(s,s->last,resampler);
539 else
540 af = af_append(s,s->last,resampler);
542 // Init the new filter
543 if(!af || (AF_OK != af->control(af,AF_CONTROL_RESAMPLE_RATE | AF_CONTROL_SET,
544 &(s->output.rate))))
545 return -1;
547 if(AF_OK != af_reinit(s,af))
548 return -1;
550 if (AF_OK != fixup_output_format(s)) {
551 // Something is stuffed audio out will not work
552 mp_msg(MSGT_AFILTER, MSGL_ERR, "[libaf] Unable to setup filter system can not"
553 " meet sound-card demands, please send bugreport. \n");
554 af_uninit(s);
555 return -1;
558 return 0;
561 /* Add filter during execution. This function adds the filter "name"
562 to the stream s. The filter will be inserted somewhere nice in the
563 list of filters. The return value is a pointer to the new filter,
564 If the filter couldn't be added the return value is NULL. */
565 af_instance_t* af_add(af_stream_t* s, char* name){
566 af_instance_t* new;
567 // Sanity check
568 if(!s || !s->first || !name)
569 return NULL;
570 // Insert the filter somwhere nice
571 if(!strcmp(s->first->info->name,"format"))
572 new = af_append(s, s->first, name);
573 else
574 new = af_prepend(s, s->first, name);
575 if(!new)
576 return NULL;
578 // Reinitalize the filter list
579 if(AF_OK != af_reinit(s, s->first) ||
580 AF_OK != fixup_output_format(s)){
581 while (s->first)
582 af_remove(s, s->first);
583 af_init(s);
584 return NULL;
586 return new;
589 // Filter data chunk through the filters in the list
590 af_data_t* af_play(af_stream_t* s, af_data_t* data)
592 af_instance_t* af=s->first;
593 // Iterate through all filters
595 if (data->len <= 0) break;
596 data=af->play(af,data);
597 af=af->next;
598 }while(af && data);
599 return data;
602 /* Calculate the minimum output buffer size for given input data d
603 * when using the RESIZE_LOCAL_BUFFER macro. The +t+1 part ensures the
604 * value is >= len*mul rounded upwards to whole samples even if the
605 * double 'mul' is inexact. */
606 int af_lencalc(double mul, af_data_t* d)
608 int t = d->bps * d->nch;
609 return d->len * mul + t + 1;
612 // Calculate average ratio of filter output size to input size
613 double af_calc_filter_multiplier(af_stream_t* s)
615 af_instance_t* af=s->first;
616 double mul = 1;
617 // Iterate through all filters and calculate total multiplication factor
619 mul *= af->mul;
620 af=af->next;
621 }while(af);
623 return mul;
626 /* Calculate the total delay [bytes output] caused by the filters */
627 double af_calc_delay(af_stream_t* s)
629 af_instance_t* af=s->first;
630 register double delay = 0.0;
631 // Iterate through all filters
632 while(af){
633 delay += af->delay;
634 delay *= af->mul;
635 af=af->next;
637 return delay;
640 /* Helper function called by the macro with the same name this
641 function should not be called directly */
642 int af_resize_local_buffer(af_instance_t* af, af_data_t* data)
644 // Calculate new length
645 register int len = af_lencalc(af->mul,data);
646 mp_msg(MSGT_AFILTER, MSGL_V, "[libaf] Reallocating memory in module %s, "
647 "old len = %i, new len = %i\n",af->info->name,af->data->len,len);
648 // If there is a buffer free it
649 free(af->data->audio);
650 // Create new buffer and check that it is OK
651 af->data->audio = malloc(len);
652 if(!af->data->audio){
653 mp_msg(MSGT_AFILTER, MSGL_FATAL, "[libaf] Could not allocate memory \n");
654 return AF_ERROR;
656 af->data->len=len;
657 return AF_OK;
660 // documentation in af.h
661 af_instance_t *af_control_any_rev (af_stream_t* s, int cmd, void* arg) {
662 int res = AF_UNKNOWN;
663 af_instance_t* filt = s->last;
664 while (filt) {
665 res = filt->control(filt, cmd, arg);
666 if (res == AF_OK)
667 return filt;
668 filt = filt->prev;
670 return NULL;
673 void af_help (void) {
674 int i = 0;
675 mp_msg(MSGT_AFILTER, MSGL_INFO, "Available audio filters:\n");
676 while (filter_list[i]) {
677 if (filter_list[i]->comment && filter_list[i]->comment[0])
678 mp_msg(MSGT_AFILTER, MSGL_INFO, " %-15s: %s (%s)\n", filter_list[i]->name, filter_list[i]->info, filter_list[i]->comment);
679 else
680 mp_msg(MSGT_AFILTER, MSGL_INFO, " %-15s: %s\n", filter_list[i]->name, filter_list[i]->info);
681 i++;
685 void af_fix_parameters(af_data_t *data)
687 data->bps = af_fmt2bits(data->format)/8;