]> git.sesse.net Git - vlc/blob - src/audio_output/input.c
0ae5f532cca403221e0dadbf15d4b64b6df09012
[vlc] / src / audio_output / input.c
1 /*****************************************************************************
2  * input.c : internal management of input streams for the audio output
3  *****************************************************************************
4  * Copyright (C) 2002-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Christophe Massiot <massiot@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <assert.h>
33
34 #include <vlc_common.h>
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <math.h>
39 #include <assert.h>
40
41 #include <vlc_input.h>
42 #include <vlc_vout.h>                  /* for vout_Request */
43 #include <vlc_modules.h>
44
45 #include <vlc_aout.h>
46 #include <vlc_filter.h>
47 #include <libvlc.h>
48
49 #include "aout_internal.h"
50
51 #define AOUT_ASSERT_MIXER_LOCKED vlc_assert_locked( &p_aout->mixer_lock )
52 #define AOUT_ASSERT_INPUT_LOCKED vlc_assert_locked( &p_input->lock )
53
54 static void inputFailure( aout_instance_t *, aout_input_t *, const char * );
55 static void inputDrop( aout_input_t *, aout_buffer_t * );
56 static void inputResamplingStop( aout_input_t *p_input );
57
58 static int VisualizationCallback( vlc_object_t *, char const *,
59                                   vlc_value_t, vlc_value_t, void * );
60 static int EqualizerCallback( vlc_object_t *, char const *,
61                               vlc_value_t, vlc_value_t, void * );
62 static int ReplayGainCallback( vlc_object_t *, char const *,
63                                vlc_value_t, vlc_value_t, void * );
64 static void ReplayGainSelect( aout_instance_t *, aout_input_t * );
65
66 static vout_thread_t *RequestVout( void *,
67                                    vout_thread_t *, video_format_t *, bool );
68
69 /*****************************************************************************
70  * aout_InputNew : allocate a new input and rework the filter pipeline
71  *****************************************************************************/
72 int aout_InputNew( aout_instance_t * p_aout, aout_input_t * p_input, const aout_request_vout_t *p_request_vout )
73 {
74     audio_sample_format_t chain_input_format;
75     audio_sample_format_t chain_output_format;
76     vlc_value_t val, text;
77     char *psz_filters, *psz_visual, *psz_scaletempo;
78     int i_visual;
79
80     aout_FormatPrint( p_aout, "input", &p_input->input );
81
82     p_input->i_nb_resamplers = p_input->i_nb_filters = 0;
83
84     /* Prepare FIFO. */
85     aout_FifoInit( p_aout, &p_input->mixer.fifo, p_aout->mixer_format.i_rate );
86
87     /* */
88     if( p_request_vout )
89     {
90         p_input->request_vout = *p_request_vout;
91     }
92     else
93     {
94         p_input->request_vout.pf_request_vout = RequestVout;
95         p_input->request_vout.p_private = p_aout;
96     }
97
98     /* Prepare format structure */
99     chain_input_format  = p_input->input;
100     chain_output_format = p_aout->mixer_format;
101     chain_output_format.i_rate = p_input->input.i_rate;
102     aout_FormatPrepare( &chain_output_format );
103
104     /* Now add user filters */
105     if( var_Type( p_aout, "visual" ) == 0 )
106     {
107         var_Create( p_aout, "visual", VLC_VAR_STRING | VLC_VAR_HASCHOICE );
108         text.psz_string = _("Visualizations");
109         var_Change( p_aout, "visual", VLC_VAR_SETTEXT, &text, NULL );
110         val.psz_string = (char*)""; text.psz_string = _("Disable");
111         var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
112         val.psz_string = (char*)"spectrometer"; text.psz_string = _("Spectrometer");
113         var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
114         val.psz_string = (char*)"scope"; text.psz_string = _("Scope");
115         var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
116         val.psz_string = (char*)"spectrum"; text.psz_string = _("Spectrum");
117         var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
118         val.psz_string = (char*)"vuMeter"; text.psz_string = _("Vu meter");
119         var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
120
121         /* Look for goom plugin */
122         if( module_exists( "goom" ) )
123         {
124             val.psz_string = (char*)"goom"; text.psz_string = (char*)"Goom";
125             var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
126         }
127
128         /* Look for libprojectM plugin */
129         if( module_exists( "projectm" ) )
130         {
131             val.psz_string = (char*)"projectm"; text.psz_string = (char*)"projectM";
132             var_Change( p_aout, "visual", VLC_VAR_ADDCHOICE, &val, &text );
133         }
134
135         if( var_Get( p_aout, "effect-list", &val ) == VLC_SUCCESS )
136         {
137             var_SetString( p_aout, "visual", val.psz_string );
138             free( val.psz_string );
139         }
140         var_AddCallback( p_aout, "visual", VisualizationCallback, NULL );
141     }
142
143     if( var_Type( p_aout, "equalizer" ) == 0 )
144     {
145         module_config_t *p_config;
146         int i;
147
148         p_config = config_FindConfig( VLC_OBJECT(p_aout), "equalizer-preset" );
149         if( p_config && p_config->i_list )
150         {
151                var_Create( p_aout, "equalizer",
152                            VLC_VAR_STRING | VLC_VAR_HASCHOICE );
153             text.psz_string = _("Equalizer");
154             var_Change( p_aout, "equalizer", VLC_VAR_SETTEXT, &text, NULL );
155
156             val.psz_string = (char*)""; text.psz_string = _("Disable");
157             var_Change( p_aout, "equalizer", VLC_VAR_ADDCHOICE, &val, &text );
158
159             for( i = 0; i < p_config->i_list; i++ )
160             {
161                 val.psz_string = (char *)p_config->ppsz_list[i];
162                 text.psz_string = (char *)p_config->ppsz_list_text[i];
163                 var_Change( p_aout, "equalizer", VLC_VAR_ADDCHOICE,
164                             &val, &text );
165             }
166
167             var_AddCallback( p_aout, "equalizer", EqualizerCallback, NULL );
168         }
169     }
170
171     if( var_Type( p_aout, "audio-filter" ) == 0 )
172     {
173         var_Create( p_aout, "audio-filter",
174                     VLC_VAR_STRING | VLC_VAR_DOINHERIT );
175         text.psz_string = _("Audio filters");
176         var_Change( p_aout, "audio-filter", VLC_VAR_SETTEXT, &text, NULL );
177     }
178     if( var_Type( p_aout, "audio-visual" ) == 0 )
179     {
180         var_Create( p_aout, "audio-visual",
181                     VLC_VAR_STRING | VLC_VAR_DOINHERIT );
182         text.psz_string = _("Audio visualizations");
183         var_Change( p_aout, "audio-visual", VLC_VAR_SETTEXT, &text, NULL );
184     }
185
186     if( var_Type( p_aout, "audio-replay-gain-mode" ) == 0 )
187     {
188         module_config_t *p_config;
189         int i;
190
191         p_config = config_FindConfig( VLC_OBJECT(p_aout), "audio-replay-gain-mode" );
192         if( p_config && p_config->i_list )
193         {
194             var_Create( p_aout, "audio-replay-gain-mode",
195                         VLC_VAR_STRING | VLC_VAR_DOINHERIT );
196
197             text.psz_string = _("Replay gain");
198             var_Change( p_aout, "audio-replay-gain-mode", VLC_VAR_SETTEXT, &text, NULL );
199
200             for( i = 0; i < p_config->i_list; i++ )
201             {
202                 val.psz_string = (char *)p_config->ppsz_list[i];
203                 text.psz_string = (char *)p_config->ppsz_list_text[i];
204                 var_Change( p_aout, "audio-replay-gain-mode", VLC_VAR_ADDCHOICE,
205                             &val, &text );
206             }
207
208             var_AddCallback( p_aout, "audio-replay-gain-mode", ReplayGainCallback, NULL );
209         }
210     }
211     if( var_Type( p_aout, "audio-replay-gain-preamp" ) == 0 )
212     {
213         var_Create( p_aout, "audio-replay-gain-preamp",
214                     VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
215     }
216     if( var_Type( p_aout, "audio-replay-gain-default" ) == 0 )
217     {
218         var_Create( p_aout, "audio-replay-gain-default",
219                     VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
220     }
221     if( var_Type( p_aout, "audio-replay-gain-peak-protection" ) == 0 )
222     {
223         var_Create( p_aout, "audio-replay-gain-peak-protection",
224                     VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
225     }
226
227     psz_filters = var_GetString( p_aout, "audio-filter" );
228     psz_visual = var_GetString( p_aout, "audio-visual");
229     psz_scaletempo = var_InheritBool( p_aout, "audio-time-stretch" ) ? strdup( "scaletempo" ) : NULL;
230
231     p_input->b_recycle_vout = psz_visual && *psz_visual;
232
233     /* parse user filter lists */
234     char *const ppsz_array[] = { psz_scaletempo, psz_filters, psz_visual };
235     p_input->p_playback_rate_filter = NULL;
236
237     for( i_visual = 0; i_visual < 3 && !AOUT_FMT_NON_LINEAR(&chain_output_format); i_visual++ )
238     {
239         char *psz_next = NULL;
240         char *psz_parser = ppsz_array[i_visual];
241
242         if( psz_parser == NULL || !*psz_parser )
243             continue;
244
245         while( psz_parser && *psz_parser )
246         {
247             filter_t * p_filter = NULL;
248
249             if( p_input->i_nb_filters >= AOUT_MAX_FILTERS )
250             {
251                 msg_Dbg( p_aout, "max filters reached (%d)", AOUT_MAX_FILTERS );
252                 break;
253             }
254
255             while( *psz_parser == ' ' && *psz_parser == ':' )
256             {
257                 psz_parser++;
258             }
259             if( ( psz_next = strchr( psz_parser , ':'  ) ) )
260             {
261                 *psz_next++ = '\0';
262             }
263             if( *psz_parser =='\0' )
264             {
265                 break;
266             }
267
268             /* Create a VLC object */
269             static const char typename[] = "audio filter";
270             p_filter = vlc_custom_create( p_aout, sizeof(*p_filter),
271                                           VLC_OBJECT_GENERIC, typename );
272             if( p_filter == NULL )
273             {
274                 msg_Err( p_aout, "cannot add user filter %s (skipped)",
275                          psz_parser );
276                 psz_parser = psz_next;
277                 continue;
278             }
279
280             p_filter->p_owner = malloc( sizeof(*p_filter->p_owner) );
281             p_filter->p_owner->p_aout  = p_aout;
282             p_filter->p_owner->p_input = p_input;
283
284             /* request format */
285             memcpy( &p_filter->fmt_in.audio, &chain_output_format,
286                     sizeof(audio_sample_format_t) );
287             p_filter->fmt_in.i_codec = chain_output_format.i_format;
288             memcpy( &p_filter->fmt_out.audio, &chain_output_format,
289                     sizeof(audio_sample_format_t) );
290             p_filter->fmt_out.i_codec = chain_output_format.i_format;
291             p_filter->pf_audio_buffer_new = aout_FilterBufferNew;
292
293             /* try to find the requested filter */
294             if( i_visual == 2 ) /* this can only be a visualization module */
295             {
296                 p_filter->p_module = module_need( p_filter, "visualization2",
297                                                   psz_parser, true );
298             }
299             else /* this can be a audio filter module as well as a visualization module */
300             {
301                 p_filter->p_module = module_need( p_filter, "audio filter",
302                                               psz_parser, true );
303
304                 if ( p_filter->p_module == NULL )
305                 {
306                     /* if the filter requested a special format, retry */
307                     if ( !( AOUT_FMTS_IDENTICAL( &p_filter->fmt_in.audio,
308                                                  &chain_input_format )
309                             && AOUT_FMTS_IDENTICAL( &p_filter->fmt_out.audio,
310                                                     &chain_output_format ) ) )
311                     {
312                         aout_FormatPrepare( &p_filter->fmt_in.audio );
313                         aout_FormatPrepare( &p_filter->fmt_out.audio );
314                         p_filter->p_module = module_need( p_filter,
315                                                           "audio filter",
316                                                           psz_parser, true );
317                     }
318                     /* try visual filters */
319                     else
320                     {
321                         memcpy( &p_filter->fmt_in.audio, &chain_output_format,
322                                 sizeof(audio_sample_format_t) );
323                         memcpy( &p_filter->fmt_out.audio, &chain_output_format,
324                                 sizeof(audio_sample_format_t) );
325                         p_filter->p_module = module_need( p_filter,
326                                                           "visualization2",
327                                                           psz_parser, true );
328                     }
329                 }
330             }
331
332             /* failure */
333             if ( p_filter->p_module == NULL )
334             {
335                 msg_Err( p_aout, "cannot add user filter %s (skipped)",
336                          psz_parser );
337
338                 free( p_filter->p_owner );
339                 vlc_object_release( p_filter );
340
341                 psz_parser = psz_next;
342                 continue;
343             }
344
345             /* complete the filter chain if necessary */
346             if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_filters,
347                                              &p_input->i_nb_filters,
348                                              &chain_input_format,
349                                              &p_filter->fmt_in.audio ) < 0 )
350             {
351                 msg_Err( p_aout, "cannot add user filter %s (skipped)",
352                          psz_parser );
353
354                 module_unneed( p_filter, p_filter->p_module );
355                 free( p_filter->p_owner );
356                 vlc_object_release( p_filter );
357
358                 psz_parser = psz_next;
359                 continue;
360             }
361
362             /* success */
363             p_input->pp_filters[p_input->i_nb_filters++] = p_filter;
364             memcpy( &chain_input_format, &p_filter->fmt_out.audio,
365                     sizeof( audio_sample_format_t ) );
366
367             if( i_visual == 0 ) /* scaletempo */
368                 p_input->p_playback_rate_filter = p_filter;
369
370             /* next filter if any */
371             psz_parser = psz_next;
372         }
373     }
374     free( psz_visual );
375     free( psz_filters );
376     free( psz_scaletempo );
377
378     /* complete the filter chain if necessary */
379     if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_filters,
380                                      &p_input->i_nb_filters,
381                                      &chain_input_format,
382                                      &chain_output_format ) < 0 )
383     {
384         inputFailure( p_aout, p_input, "couldn't set an input pipeline" );
385         return -1;
386     }
387
388     /* Create resamplers. */
389     if ( !AOUT_FMT_NON_LINEAR( &p_aout->mixer_format ) )
390     {
391         chain_output_format.i_rate = (__MAX(p_input->input.i_rate,
392                                             p_aout->mixer_format.i_rate)
393                                  * (100 + AOUT_MAX_RESAMPLING)) / 100;
394         if ( chain_output_format.i_rate == p_aout->mixer_format.i_rate )
395         {
396             /* Just in case... */
397             chain_output_format.i_rate++;
398         }
399         if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_resamplers,
400                                          &p_input->i_nb_resamplers,
401                                          &chain_output_format,
402                                          &p_aout->mixer_format ) < 0 )
403         {
404             inputFailure( p_aout, p_input, "couldn't set a resampler pipeline");
405             return -1;
406         }
407
408         /* Setup the initial rate of the resampler */
409         p_input->pp_resamplers[0]->fmt_in.audio.i_rate = p_input->input.i_rate;
410     }
411     p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
412
413     if( ! p_input->p_playback_rate_filter && p_input->i_nb_resamplers > 0 )
414     {
415         p_input->p_playback_rate_filter = p_input->pp_resamplers[0];
416     }
417
418     ReplayGainSelect( p_aout, p_input );
419
420     /* Success */
421     p_input->b_error = false;
422     p_input->i_last_input_rate = INPUT_RATE_DEFAULT;
423
424     return 0;
425 }
426
427 /*****************************************************************************
428  * aout_InputDelete : delete an input
429  *****************************************************************************
430  * This function must be entered with the mixer lock.
431  *****************************************************************************/
432 int aout_InputDelete( aout_instance_t * p_aout, aout_input_t * p_input )
433 {
434     AOUT_ASSERT_MIXER_LOCKED;
435     if ( p_input->b_error )
436         return 0;
437
438     /* XXX We need to update b_recycle_vout before calling aout_FiltersDestroyPipeline.
439      * FIXME They can be a race condition if audio-visual is updated between
440      * aout_InputDelete and aout_InputNew.
441      */
442     char *psz_visual = var_GetString( p_aout, "audio-visual");
443     p_input->b_recycle_vout = psz_visual && *psz_visual;
444     free( psz_visual );
445
446     aout_FiltersDestroyPipeline( p_input->pp_filters, p_input->i_nb_filters );
447     p_input->i_nb_filters = 0;
448     aout_FiltersDestroyPipeline( p_input->pp_resamplers,
449                                  p_input->i_nb_resamplers );
450     p_input->i_nb_resamplers = 0;
451     aout_FifoDestroy( &p_input->mixer.fifo );
452
453     return 0;
454 }
455
456 /*****************************************************************************
457  * aout_InputCheckAndRestart : restart an input
458  *****************************************************************************
459  * This function must be entered with the input and mixer lock.
460  *****************************************************************************/
461 void aout_InputCheckAndRestart( aout_instance_t * p_aout, aout_input_t * p_input )
462 {
463     AOUT_ASSERT_MIXER_LOCKED;
464     AOUT_ASSERT_INPUT_LOCKED;
465
466     if( !p_input->b_restart )
467         return;
468
469     aout_lock_input_fifos( p_aout );
470
471     /* A little trick to avoid loosing our input fifo and properties */
472
473     aout_fifo_t fifo = p_input->mixer.fifo;
474     bool b_paused = p_input->b_paused;
475     mtime_t i_pause_date = p_input->i_pause_date;
476
477     aout_FifoInit( p_aout, &p_input->mixer.fifo, p_aout->mixer_format.i_rate );
478
479     aout_InputDelete( p_aout, p_input );
480
481     aout_InputNew( p_aout, p_input, &p_input->request_vout );
482     p_input->mixer.fifo = fifo;
483     p_input->b_paused = b_paused;
484     p_input->i_pause_date = i_pause_date;
485
486     p_input->b_restart = false;
487
488     aout_unlock_input_fifos( p_aout );
489 }
490 /*****************************************************************************
491  * aout_InputPlay : play a buffer
492  *****************************************************************************
493  * This function must be entered with the input lock.
494  *****************************************************************************/
495 /* XXX Do not activate it !! */
496 //#define AOUT_PROCESS_BEFORE_CHEKS
497 int aout_InputPlay( aout_instance_t * p_aout, aout_input_t * p_input,
498                     aout_buffer_t * p_buffer, int i_input_rate )
499 {
500     mtime_t start_date;
501     AOUT_ASSERT_INPUT_LOCKED;
502
503     if( i_input_rate != INPUT_RATE_DEFAULT && p_input->p_playback_rate_filter == NULL )
504     {
505         inputDrop( p_input, p_buffer );
506         return 0;
507     }
508
509 #ifdef AOUT_PROCESS_BEFORE_CHEKS
510     /* Run pre-filters. */
511     aout_FiltersPlay( p_aout, p_input->pp_filters, p_input->i_nb_filters,
512                       &p_buffer );
513     if( !p_buffer )
514         return 0;
515
516     /* Actually run the resampler now. */
517     if ( p_input->i_nb_resamplers > 0 )
518     {
519         const mtime_t i_date = p_buffer->i_pts;
520         aout_FiltersPlay( p_aout, p_input->pp_resamplers,
521                           p_input->i_nb_resamplers,
522                           &p_buffer );
523     }
524
525     if( !p_buffer )
526         return 0;
527     if( p_buffer->i_nb_samples <= 0 )
528     {
529         block_Release( p_buffer );
530         return 0;
531     }
532 #endif
533
534     /* Handle input rate change, but keep drift correction */
535     if( i_input_rate != p_input->i_last_input_rate )
536     {
537         unsigned int * const pi_rate = &p_input->p_playback_rate_filter->fmt_in.audio.i_rate;
538 #define F(r,ir) ( INPUT_RATE_DEFAULT * (r) / (ir) )
539         const int i_delta = *pi_rate - F(p_input->input.i_rate,p_input->i_last_input_rate);
540         *pi_rate = F(p_input->input.i_rate + i_delta, i_input_rate);
541 #undef F
542         p_input->i_last_input_rate = i_input_rate;
543     }
544
545     /* We don't care if someone changes the start date behind our back after
546      * this. We'll deal with that when pushing the buffer, and compensate
547      * with the next incoming buffer. */
548     aout_lock_input_fifos( p_aout );
549     start_date = aout_FifoNextStart( &p_input->mixer.fifo );
550     aout_unlock_input_fifos( p_aout );
551
552     mtime_t now = mdate();
553     if ( start_date != 0 && start_date < now )
554     {
555         /* The decoder is _very_ late. This can only happen if the user
556          * pauses the stream (or if the decoder is buggy, which cannot
557          * happen :). */
558         msg_Warn( p_aout, "computed PTS is out of range (%"PRId64"), "
559                   "clearing out", now - start_date );
560         aout_lock_input_fifos( p_aout );
561         aout_FifoSet( &p_input->mixer.fifo, 0 );
562         aout_unlock_input_fifos( p_aout );
563         if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
564             msg_Warn( p_aout, "timing screwed, stopping resampling" );
565         inputResamplingStop( p_input );
566         p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
567         start_date = 0;
568     }
569
570     if ( p_buffer->i_pts < now + AOUT_MIN_PREPARE_TIME )
571     {
572         /* The decoder gives us f*cked up PTS. It's its business, but we
573          * can't present it anyway, so drop the buffer. */
574         msg_Warn( p_aout, "PTS is out of range (%"PRId64"), dropping buffer",
575                   now - p_buffer->i_pts );
576
577         inputDrop( p_input, p_buffer );
578         inputResamplingStop( p_input );
579         return 0;
580     }
581
582     /* If the audio drift is too big then it's not worth trying to resample
583      * the audio. */
584     if( !start_date )
585         start_date = p_buffer->i_pts;
586
587     mtime_t tolerance = 3 * AOUT_PTS_TOLERANCE
588                           * i_input_rate / INPUT_RATE_DEFAULT;
589     mtime_t drift = start_date - p_buffer->i_pts;
590
591     if( drift < -tolerance )
592     {
593         msg_Warn( p_aout, "buffer way too early (%"PRId64"), clearing queue",
594                   drift );
595         aout_lock_input_fifos( p_aout );
596         aout_FifoSet( &p_input->mixer.fifo, 0 );
597         aout_unlock_input_fifos( p_aout );
598         if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
599             msg_Warn( p_aout, "timing screwed, stopping resampling" );
600         inputResamplingStop( p_input );
601         p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
602         start_date = p_buffer->i_pts;
603         drift = 0;
604     }
605     else if( drift > +tolerance )
606     {
607         msg_Warn( p_aout, "buffer way too late (%"PRId64"), dropping buffer",
608                   drift );
609         inputDrop( p_input, p_buffer );
610         return 0;
611     }
612
613 #ifndef AOUT_PROCESS_BEFORE_CHEKS
614     /* Run pre-filters. */
615     aout_FiltersPlay( p_input->pp_filters, p_input->i_nb_filters, &p_buffer );
616     if( !p_buffer )
617         return 0;
618 #endif
619
620     /* Run the resampler if needed.
621      * We first need to calculate the output rate of this resampler. */
622     if ( ( p_input->i_resampling_type == AOUT_RESAMPLING_NONE ) &&
623          ( drift < -AOUT_PTS_TOLERANCE || drift > +AOUT_PTS_TOLERANCE ) &&
624          p_input->i_nb_resamplers > 0 )
625     {
626         /* Can happen in several circumstances :
627          * 1. A problem at the input (clock drift)
628          * 2. A small pause triggered by the user
629          * 3. Some delay in the output stage, causing a loss of lip
630          *    synchronization
631          * Solution : resample the buffer to avoid a scratch.
632          */
633         p_input->i_resamp_start_date = now;
634         p_input->i_resamp_start_drift = (int)-drift;
635         p_input->i_resampling_type = (drift < 0) ? AOUT_RESAMPLING_DOWN
636                                                  : AOUT_RESAMPLING_UP;
637         msg_Warn( p_aout, (drift < 0)
638                   ? "buffer too early (%"PRId64"), down-sampling"
639                   : "buffer too late  (%"PRId64"), up-sampling", drift );
640     }
641
642     if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
643     {
644         /* Resampling has been triggered previously (because of dates
645          * mismatch). We want the resampling to happen progressively so
646          * it isn't too audible to the listener. */
647
648         if( p_input->i_resampling_type == AOUT_RESAMPLING_UP )
649             p_input->pp_resamplers[0]->fmt_in.audio.i_rate += 2; /* Hz */
650         else
651             p_input->pp_resamplers[0]->fmt_in.audio.i_rate -= 2; /* Hz */
652
653         /* Check if everything is back to normal, in which case we can stop the
654          * resampling */
655         unsigned int i_nominal_rate =
656           (p_input->pp_resamplers[0] == p_input->p_playback_rate_filter)
657           ? INPUT_RATE_DEFAULT * p_input->input.i_rate / i_input_rate
658           : p_input->input.i_rate;
659         if( p_input->pp_resamplers[0]->fmt_in.audio.i_rate == i_nominal_rate )
660         {
661             p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
662             msg_Warn( p_aout, "resampling stopped after %"PRIi64" usec "
663                       "(drift: %"PRIi64")",
664                       now - p_input->i_resamp_start_date,
665                       p_buffer->i_pts - start_date);
666         }
667         else if( abs( (int)(p_buffer->i_pts - start_date) ) <
668                  abs( p_input->i_resamp_start_drift ) / 2 )
669         {
670             /* if we reduced the drift from half, then it is time to switch
671              * back the resampling direction. */
672             if( p_input->i_resampling_type == AOUT_RESAMPLING_UP )
673                 p_input->i_resampling_type = AOUT_RESAMPLING_DOWN;
674             else
675                 p_input->i_resampling_type = AOUT_RESAMPLING_UP;
676             p_input->i_resamp_start_drift = 0;
677         }
678         else if( p_input->i_resamp_start_drift &&
679                  ( abs( (int)(p_buffer->i_pts - start_date) ) >
680                    abs( p_input->i_resamp_start_drift ) * 3 / 2 ) )
681         {
682             /* If the drift is increasing and not decreasing, than something
683              * is bad. We'd better stop the resampling right now. */
684             msg_Warn( p_aout, "timing screwed, stopping resampling" );
685             inputResamplingStop( p_input );
686             p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
687         }
688     }
689
690 #ifndef AOUT_PROCESS_BEFORE_CHEKS
691     /* Actually run the resampler now. */
692     if ( p_input->i_nb_resamplers > 0 )
693     {
694         aout_FiltersPlay( p_input->pp_resamplers, p_input->i_nb_resamplers,
695                           &p_buffer );
696     }
697
698     if( !p_buffer )
699         return 0;
700     if( p_buffer->i_nb_samples <= 0 )
701     {
702         block_Release( p_buffer );
703         return 0;
704     }
705 #endif
706
707     /* Adding the start date will be managed by aout_FifoPush(). */
708     p_buffer->i_pts = start_date;
709
710     aout_lock_input_fifos( p_aout );
711     aout_FifoPush( &p_input->mixer.fifo, p_buffer );
712     aout_unlock_input_fifos( p_aout );
713     return 0;
714 }
715
716 /*****************************************************************************
717  * static functions
718  *****************************************************************************/
719
720 static void inputFailure( aout_instance_t * p_aout, aout_input_t * p_input,
721                           const char * psz_error_message )
722 {
723     /* error message */
724     msg_Err( p_aout, "%s", psz_error_message );
725
726     /* clean up */
727     aout_FiltersDestroyPipeline( p_input->pp_filters, p_input->i_nb_filters );
728     aout_FiltersDestroyPipeline( p_input->pp_resamplers,
729                                  p_input->i_nb_resamplers );
730     aout_FifoDestroy( &p_input->mixer.fifo );
731     var_Destroy( p_aout, "visual" );
732     var_Destroy( p_aout, "equalizer" );
733     var_Destroy( p_aout, "audio-filter" );
734     var_Destroy( p_aout, "audio-visual" );
735
736     var_Destroy( p_aout, "audio-replay-gain-mode" );
737     var_Destroy( p_aout, "audio-replay-gain-default" );
738     var_Destroy( p_aout, "audio-replay-gain-preamp" );
739     var_Destroy( p_aout, "audio-replay-gain-peak-protection" );
740
741     /* error flag */
742     p_input->b_error = 1;
743 }
744
745 static void inputDrop( aout_input_t *p_input, aout_buffer_t *p_buffer )
746 {
747     aout_BufferFree( p_buffer );
748
749     p_input->i_buffer_lost++;
750 }
751
752 static void inputResamplingStop( aout_input_t *p_input )
753 {
754     p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
755     if( p_input->i_nb_resamplers != 0 )
756     {
757         p_input->pp_resamplers[0]->fmt_in.audio.i_rate =
758             ( p_input->pp_resamplers[0] == p_input->p_playback_rate_filter )
759             ? INPUT_RATE_DEFAULT * p_input->input.i_rate / p_input->i_last_input_rate
760             : p_input->input.i_rate;
761     }
762 }
763
764 static vout_thread_t *RequestVout( void *p_private,
765                                    vout_thread_t *p_vout, video_format_t *p_fmt, bool b_recycle )
766 {
767     aout_instance_t *p_aout = p_private;
768     VLC_UNUSED(b_recycle);
769     vout_configuration_t cfg = {
770         .vout       = p_vout,
771         .input      = NULL,
772         .change_fmt = true,
773         .fmt        = p_fmt,
774         .dpb_size   = 1,
775     };
776     return vout_Request( p_aout, &cfg );
777 }
778
779 vout_thread_t *aout_filter_RequestVout( filter_t *p_filter,
780                                         vout_thread_t *p_vout, video_format_t *p_fmt )
781 {
782     aout_input_t *p_input = p_filter->p_owner->p_input;
783     aout_request_vout_t *p_request = &p_input->request_vout;
784
785     /* XXX: this only works from audio input */
786     /* If you want to use visualization filters from another place, you will
787      * need to add a new pf_aout_request_vout callback or store a pointer
788      * to aout_request_vout_t inside filter_t (i.e. a level of indirection). */
789
790     return p_request->pf_request_vout( p_request->p_private,
791                                        p_vout, p_fmt, p_input->b_recycle_vout );
792 }
793
794 static int ChangeFiltersString( aout_instance_t * p_aout, const char* psz_variable,
795                                  const char *psz_name, bool b_add )
796 {
797     return aout_ChangeFilterString( VLC_OBJECT(p_aout), p_aout,
798                                     psz_variable, psz_name, b_add ) ? 1 : 0;
799 }
800
801 static int VisualizationCallback( vlc_object_t *p_this, char const *psz_cmd,
802                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
803 {
804     aout_instance_t *p_aout = (aout_instance_t *)p_this;
805     char *psz_mode = newval.psz_string;
806     (void)psz_cmd; (void)oldval; (void)p_data;
807
808     if( !psz_mode || !*psz_mode )
809     {
810         ChangeFiltersString( p_aout, "audio-visual", "goom", false );
811         ChangeFiltersString( p_aout, "audio-visual", "visual", false );
812         ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
813     }
814     else
815     {
816         if( !strcmp( "goom", psz_mode ) )
817         {
818             ChangeFiltersString( p_aout, "audio-visual", "visual", false );
819             ChangeFiltersString( p_aout, "audio-visual", "goom", true );
820             ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
821         }
822         else if( !strcmp( "projectm", psz_mode ) )
823         {
824             ChangeFiltersString( p_aout, "audio-visual", "visual", false );
825             ChangeFiltersString( p_aout, "audio-visual", "goom", false );
826             ChangeFiltersString( p_aout, "audio-visual", "projectm", true );
827         }
828         else
829         {
830             var_Create( p_aout, "effect-list", VLC_VAR_STRING );
831             var_SetString( p_aout, "effect-list", psz_mode );
832
833             ChangeFiltersString( p_aout, "audio-visual", "goom", false );
834             ChangeFiltersString( p_aout, "audio-visual", "visual", true );
835             ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
836         }
837     }
838
839     /* That sucks */
840     AoutInputsMarkToRestart( p_aout );
841
842     return VLC_SUCCESS;
843 }
844
845 static int EqualizerCallback( vlc_object_t *p_this, char const *psz_cmd,
846                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
847 {
848     aout_instance_t *p_aout = (aout_instance_t *)p_this;
849     char *psz_mode = newval.psz_string;
850     int i_ret;
851     (void)psz_cmd; (void)oldval; (void)p_data;
852
853     if( !psz_mode || !*psz_mode )
854     {
855         i_ret = ChangeFiltersString( p_aout, "audio-filter", "equalizer",
856                                      false );
857     }
858     else
859     {
860         var_Create( p_aout, "equalizer-preset", VLC_VAR_STRING );
861         var_SetString( p_aout, "equalizer-preset", psz_mode );
862         i_ret = ChangeFiltersString( p_aout, "audio-filter", "equalizer",
863                                      true );
864     }
865
866     /* That sucks */
867     if( i_ret == 1 )
868         AoutInputsMarkToRestart( p_aout );
869     return VLC_SUCCESS;
870 }
871
872 static int ReplayGainCallback( vlc_object_t *p_this, char const *psz_cmd,
873                                vlc_value_t oldval, vlc_value_t newval, void *p_data )
874 {
875     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
876     VLC_UNUSED(newval); VLC_UNUSED(p_data);
877     aout_instance_t *p_aout = (aout_instance_t *)p_this;
878
879     aout_lock_mixer( p_aout );
880     if( p_aout->p_input != NULL )
881         ReplayGainSelect( p_aout, p_aout->p_input );
882     aout_unlock_mixer( p_aout );
883
884     return VLC_SUCCESS;
885 }
886
887 static void ReplayGainSelect( aout_instance_t *p_aout, aout_input_t *p_input )
888 {
889     char *psz_replay_gain = var_GetNonEmptyString( p_aout,
890                                                    "audio-replay-gain-mode" );
891     int i_mode;
892     int i_use;
893     float f_gain;
894
895     p_input->mixer.multiplier = 1.0;
896
897     if( !psz_replay_gain )
898         return;
899
900     /* Find select mode */
901     if( !strcmp( psz_replay_gain, "track" ) )
902         i_mode = AUDIO_REPLAY_GAIN_TRACK;
903     else if( !strcmp( psz_replay_gain, "album" ) )
904         i_mode = AUDIO_REPLAY_GAIN_ALBUM;
905     else
906         i_mode = AUDIO_REPLAY_GAIN_MAX;
907
908     /* If the select mode is not available, prefer the other one */
909     i_use = i_mode;
910     if( i_use != AUDIO_REPLAY_GAIN_MAX && !p_input->replay_gain.pb_gain[i_use] )
911     {
912         for( i_use = 0; i_use < AUDIO_REPLAY_GAIN_MAX; i_use++ )
913         {
914             if( p_input->replay_gain.pb_gain[i_use] )
915                 break;
916         }
917     }
918
919     /* */
920     if( i_use != AUDIO_REPLAY_GAIN_MAX )
921         f_gain = p_input->replay_gain.pf_gain[i_use] + var_GetFloat( p_aout, "audio-replay-gain-preamp" );
922     else if( i_mode != AUDIO_REPLAY_GAIN_MAX )
923         f_gain = var_GetFloat( p_aout, "audio-replay-gain-default" );
924     else
925         f_gain = 0.0;
926     p_input->mixer.multiplier = pow( 10.0, f_gain / 20.0 );
927
928     /* */
929     if( p_input->replay_gain.pb_peak[i_use] &&
930         var_GetBool( p_aout, "audio-replay-gain-peak-protection" ) &&
931         p_input->replay_gain.pf_peak[i_use] * p_input->mixer.multiplier > 1.0 )
932     {
933         p_input->mixer.multiplier = 1.0f / p_input->replay_gain.pf_peak[i_use];
934     }
935
936     free( psz_replay_gain );
937 }