]> git.sesse.net Git - vlc/blob - src/audio_output/input.c
Allow scaletempo to be toggled without restarting VLC
[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
44 #include <vlc_aout.h>
45 #include <vlc_filter.h>
46 #include <libvlc.h>
47
48 #include "aout_internal.h"
49
50 #define AOUT_ASSERT_MIXER_LOCKED vlc_assert_locked( &p_aout->mixer_lock )
51 #define AOUT_ASSERT_INPUT_LOCKED vlc_assert_locked( &p_input->lock )
52
53 static void inputFailure( aout_instance_t *, aout_input_t *, const char * );
54 static void inputDrop( aout_input_t *, aout_buffer_t * );
55 static void inputResamplingStop( aout_input_t *p_input );
56
57 static int VisualizationCallback( vlc_object_t *, char const *,
58                                   vlc_value_t, vlc_value_t, void * );
59 static int EqualizerCallback( vlc_object_t *, char const *,
60                               vlc_value_t, vlc_value_t, void * );
61 static int ReplayGainCallback( vlc_object_t *, char const *,
62                                vlc_value_t, vlc_value_t, void * );
63 static void ReplayGainSelect( aout_instance_t *, aout_input_t * );
64
65 static vout_thread_t *RequestVout( void *,
66                                    vout_thread_t *, video_format_t *, bool );
67
68 /*****************************************************************************
69  * aout_InputNew : allocate a new input and rework the filter pipeline
70  *****************************************************************************/
71 int aout_InputNew( aout_instance_t * p_aout, aout_input_t * p_input, const aout_request_vout_t *p_request_vout )
72 {
73     audio_sample_format_t chain_input_format;
74     audio_sample_format_t chain_output_format;
75     vlc_value_t val, text;
76     char *psz_filters, *psz_visual, *psz_scaletempo;
77     int i_visual;
78
79     aout_FormatPrint( p_aout, "input", &p_input->input );
80
81     p_input->i_nb_resamplers = p_input->i_nb_filters = 0;
82
83     /* Prepare FIFO. */
84     aout_FifoInit( p_aout, &p_input->mixer.fifo, p_aout->mixer_format.i_rate );
85     p_input->mixer.begin = NULL;
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             vlc_object_attach( p_filter , p_aout );
281
282             p_filter->p_owner = malloc( sizeof(*p_filter->p_owner) );
283             p_filter->p_owner->p_aout  = p_aout;
284             p_filter->p_owner->p_input = p_input;
285
286             /* request format */
287             memcpy( &p_filter->fmt_in.audio, &chain_output_format,
288                     sizeof(audio_sample_format_t) );
289             p_filter->fmt_in.i_codec = chain_output_format.i_format;
290             memcpy( &p_filter->fmt_out.audio, &chain_output_format,
291                     sizeof(audio_sample_format_t) );
292             p_filter->fmt_out.i_codec = chain_output_format.i_format;
293             p_filter->pf_audio_buffer_new = aout_FilterBufferNew;
294
295             /* try to find the requested filter */
296             if( i_visual == 2 ) /* this can only be a visualization module */
297             {
298                 p_filter->p_module = module_need( p_filter, "visualization2",
299                                                   psz_parser, true );
300             }
301             else /* this can be a audio filter module as well as a visualization module */
302             {
303                 p_filter->p_module = module_need( p_filter, "audio filter",
304                                               psz_parser, true );
305
306                 if ( p_filter->p_module == NULL )
307                 {
308                     /* if the filter requested a special format, retry */
309                     if ( !( AOUT_FMTS_IDENTICAL( &p_filter->fmt_in.audio,
310                                                  &chain_input_format )
311                             && AOUT_FMTS_IDENTICAL( &p_filter->fmt_out.audio,
312                                                     &chain_output_format ) ) )
313                     {
314                         aout_FormatPrepare( &p_filter->fmt_in.audio );
315                         aout_FormatPrepare( &p_filter->fmt_out.audio );
316                         p_filter->p_module = module_need( p_filter,
317                                                           "audio filter",
318                                                           psz_parser, true );
319                     }
320                     /* try visual filters */
321                     else
322                     {
323                         memcpy( &p_filter->fmt_in.audio, &chain_output_format,
324                                 sizeof(audio_sample_format_t) );
325                         memcpy( &p_filter->fmt_out.audio, &chain_output_format,
326                                 sizeof(audio_sample_format_t) );
327                         p_filter->p_module = module_need( p_filter,
328                                                           "visualization2",
329                                                           psz_parser, true );
330                     }
331                 }
332             }
333
334             /* failure */
335             if ( p_filter->p_module == NULL )
336             {
337                 msg_Err( p_aout, "cannot add user filter %s (skipped)",
338                          psz_parser );
339
340                 free( p_filter->p_owner );
341                 vlc_object_release( p_filter );
342
343                 psz_parser = psz_next;
344                 continue;
345             }
346
347             /* complete the filter chain if necessary */
348             if ( !AOUT_FMTS_IDENTICAL( &chain_input_format,
349                                        &p_filter->fmt_in.audio ) )
350             {
351                 if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_filters,
352                                                  &p_input->i_nb_filters,
353                                                  &chain_input_format,
354                                                  &p_filter->fmt_in.audio ) < 0 )
355                 {
356                     msg_Err( p_aout, "cannot add user filter %s (skipped)",
357                              psz_parser );
358
359                     module_unneed( p_filter, p_filter->p_module );
360                     free( p_filter->p_owner );
361                     vlc_object_release( p_filter );
362
363                     psz_parser = psz_next;
364                     continue;
365                 }
366             }
367
368             /* success */
369             p_input->pp_filters[p_input->i_nb_filters++] = p_filter;
370             memcpy( &chain_input_format, &p_filter->fmt_out.audio,
371                     sizeof( audio_sample_format_t ) );
372
373             if( i_visual == 0 ) /* scaletempo */
374                 p_input->p_playback_rate_filter = p_filter;
375
376             /* next filter if any */
377             psz_parser = psz_next;
378         }
379     }
380     free( psz_visual );
381     free( psz_filters );
382     free( psz_scaletempo );
383
384     /* complete the filter chain if necessary */
385     if ( !AOUT_FMTS_IDENTICAL( &chain_input_format, &chain_output_format ) )
386     {
387         if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_filters,
388                                          &p_input->i_nb_filters,
389                                          &chain_input_format,
390                                          &chain_output_format ) < 0 )
391         {
392             inputFailure( p_aout, p_input, "couldn't set an input pipeline" );
393             return -1;
394         }
395     }
396
397     /* Prepare hints for the buffer allocator. */
398     p_input->input_alloc.b_alloc = true;
399     p_input->input_alloc.i_bytes_per_sec = -1;
400
401     /* Create resamplers. */
402     if ( !AOUT_FMT_NON_LINEAR( &p_aout->mixer_format ) )
403     {
404         chain_output_format.i_rate = (__MAX(p_input->input.i_rate,
405                                             p_aout->mixer_format.i_rate)
406                                  * (100 + AOUT_MAX_RESAMPLING)) / 100;
407         if ( chain_output_format.i_rate == p_aout->mixer_format.i_rate )
408         {
409             /* Just in case... */
410             chain_output_format.i_rate++;
411         }
412         if ( aout_FiltersCreatePipeline( p_aout, p_input->pp_resamplers,
413                                          &p_input->i_nb_resamplers,
414                                          &chain_output_format,
415                                          &p_aout->mixer_format ) < 0 )
416         {
417             inputFailure( p_aout, p_input, "couldn't set a resampler pipeline");
418             return -1;
419         }
420
421         aout_FiltersHintBuffers( p_aout, p_input->pp_resamplers,
422                                  p_input->i_nb_resamplers,
423                                  &p_input->input_alloc );
424         p_input->input_alloc.b_alloc = true;
425
426         /* Setup the initial rate of the resampler */
427         p_input->pp_resamplers[0]->fmt_in.audio.i_rate = p_input->input.i_rate;
428     }
429     p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
430
431     if( ! p_input->p_playback_rate_filter && p_input->i_nb_resamplers > 0 )
432     {
433         p_input->p_playback_rate_filter = p_input->pp_resamplers[0];
434     }
435
436     aout_FiltersHintBuffers( p_aout, p_input->pp_filters,
437                              p_input->i_nb_filters,
438                              &p_input->input_alloc );
439     p_input->input_alloc.b_alloc = true;
440
441     /* i_bytes_per_sec is still == -1 if no filters */
442     p_input->input_alloc.i_bytes_per_sec = __MAX(
443                                     p_input->input_alloc.i_bytes_per_sec,
444                                     (int)(p_input->input.i_bytes_per_frame
445                                      * p_input->input.i_rate
446                                      / p_input->input.i_frame_length) );
447
448     ReplayGainSelect( p_aout, p_input );
449
450     /* Success */
451     p_input->b_error = false;
452     p_input->i_last_input_rate = INPUT_RATE_DEFAULT;
453
454     return 0;
455 }
456
457 /*****************************************************************************
458  * aout_InputDelete : delete an input
459  *****************************************************************************
460  * This function must be entered with the mixer lock.
461  *****************************************************************************/
462 int aout_InputDelete( aout_instance_t * p_aout, aout_input_t * p_input )
463 {
464     AOUT_ASSERT_MIXER_LOCKED;
465     if ( p_input->b_error )
466         return 0;
467
468     /* XXX We need to update b_recycle_vout before calling aout_FiltersDestroyPipeline.
469      * FIXME They can be a race condition if audio-visual is updated between
470      * aout_InputDelete and aout_InputNew.
471      */
472     char *psz_visual = var_GetString( p_aout, "audio-visual");
473     p_input->b_recycle_vout = psz_visual && *psz_visual;
474     free( psz_visual );
475
476     aout_FiltersDestroyPipeline( p_aout, p_input->pp_filters,
477                                  p_input->i_nb_filters );
478     p_input->i_nb_filters = 0;
479     aout_FiltersDestroyPipeline( p_aout, p_input->pp_resamplers,
480                                  p_input->i_nb_resamplers );
481     p_input->i_nb_resamplers = 0;
482     aout_FifoDestroy( p_aout, &p_input->mixer.fifo );
483
484     return 0;
485 }
486
487 /*****************************************************************************
488  * aout_InputCheckAndRestart : restart an input
489  *****************************************************************************
490  * This function must be entered with the input and mixer lock.
491  *****************************************************************************/
492 void aout_InputCheckAndRestart( aout_instance_t * p_aout, aout_input_t * p_input )
493 {
494     AOUT_ASSERT_MIXER_LOCKED;
495     AOUT_ASSERT_INPUT_LOCKED;
496
497     if( !p_input->b_restart )
498         return;
499
500     aout_lock_input_fifos( p_aout );
501
502     /* A little trick to avoid loosing our input fifo and properties */
503
504     uint8_t *p_first_byte_to_mix = p_input->mixer.begin;
505     aout_fifo_t fifo = p_input->mixer.fifo;
506     bool b_paused = p_input->b_paused;
507     mtime_t i_pause_date = p_input->i_pause_date;
508
509     aout_FifoInit( p_aout, &p_input->mixer.fifo, p_aout->mixer_format.i_rate );
510
511     aout_InputDelete( p_aout, p_input );
512
513     aout_InputNew( p_aout, p_input, &p_input->request_vout );
514     p_input->mixer.begin = p_first_byte_to_mix;
515     p_input->mixer.fifo = fifo;
516     p_input->b_paused = b_paused;
517     p_input->i_pause_date = i_pause_date;
518
519     p_input->b_restart = false;
520
521     aout_unlock_input_fifos( p_aout );
522 }
523 /*****************************************************************************
524  * aout_InputPlay : play a buffer
525  *****************************************************************************
526  * This function must be entered with the input lock.
527  *****************************************************************************/
528 /* XXX Do not activate it !! */
529 //#define AOUT_PROCESS_BEFORE_CHEKS
530 int aout_InputPlay( aout_instance_t * p_aout, aout_input_t * p_input,
531                     aout_buffer_t * p_buffer, int i_input_rate )
532 {
533     mtime_t start_date;
534     AOUT_ASSERT_INPUT_LOCKED;
535
536     if( i_input_rate != INPUT_RATE_DEFAULT && p_input->p_playback_rate_filter == NULL )
537     {
538         inputDrop( p_input, p_buffer );
539         return 0;
540     }
541
542 #ifdef AOUT_PROCESS_BEFORE_CHEKS
543     /* Run pre-filters. */
544     aout_FiltersPlay( p_aout, p_input->pp_filters, p_input->i_nb_filters,
545                       &p_buffer );
546     if( !p_buffer )
547         return 0;
548
549     /* Actually run the resampler now. */
550     if ( p_input->i_nb_resamplers > 0 )
551     {
552         const mtime_t i_date = p_buffer->i_pts;
553         aout_FiltersPlay( p_aout, p_input->pp_resamplers,
554                           p_input->i_nb_resamplers,
555                           &p_buffer );
556     }
557
558     if( !p_buffer )
559         return 0;
560     if( p_buffer->i_nb_samples <= 0 )
561     {
562         block_Release( p_buffer );
563         return 0;
564     }
565 #endif
566
567     /* Handle input rate change, but keep drift correction */
568     if( i_input_rate != p_input->i_last_input_rate )
569     {
570         unsigned int * const pi_rate = &p_input->p_playback_rate_filter->fmt_in.audio.i_rate;
571 #define F(r,ir) ( INPUT_RATE_DEFAULT * (r) / (ir) )
572         const int i_delta = *pi_rate - F(p_input->input.i_rate,p_input->i_last_input_rate);
573         *pi_rate = F(p_input->input.i_rate + i_delta, i_input_rate);
574 #undef F
575         p_input->i_last_input_rate = i_input_rate;
576     }
577
578     /* We don't care if someone changes the start date behind our back after
579      * this. We'll deal with that when pushing the buffer, and compensate
580      * with the next incoming buffer. */
581     aout_lock_input_fifos( p_aout );
582     start_date = aout_FifoNextStart( p_aout, &p_input->mixer.fifo );
583     aout_unlock_input_fifos( p_aout );
584
585     if ( start_date != 0 && start_date < mdate() )
586     {
587         /* The decoder is _very_ late. This can only happen if the user
588          * pauses the stream (or if the decoder is buggy, which cannot
589          * happen :). */
590         msg_Warn( p_aout, "computed PTS is out of range (%"PRId64"), "
591                   "clearing out", mdate() - start_date );
592         aout_lock_input_fifos( p_aout );
593         aout_FifoSet( p_aout, &p_input->mixer.fifo, 0 );
594         p_input->mixer.begin = NULL;
595         aout_unlock_input_fifos( p_aout );
596         if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
597             msg_Warn( p_aout, "timing screwed, stopping resampling" );
598         inputResamplingStop( p_input );
599         p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
600         start_date = 0;
601     }
602
603     if ( p_buffer->i_pts < mdate() + AOUT_MIN_PREPARE_TIME )
604     {
605         /* The decoder gives us f*cked up PTS. It's its business, but we
606          * can't present it anyway, so drop the buffer. */
607         msg_Warn( p_aout, "PTS is out of range (%"PRId64"), dropping buffer",
608                   mdate() - p_buffer->i_pts );
609
610         inputDrop( p_input, p_buffer );
611         inputResamplingStop( p_input );
612         return 0;
613     }
614
615     /* If the audio drift is too big then it's not worth trying to resample
616      * the audio. */
617     mtime_t i_pts_tolerance = 3 * AOUT_PTS_TOLERANCE * i_input_rate / INPUT_RATE_DEFAULT;
618     if ( start_date != 0 &&
619          ( start_date < p_buffer->i_pts - i_pts_tolerance ) )
620     {
621         msg_Warn( p_aout, "audio drift is too big (%"PRId64"), clearing out",
622                   start_date - p_buffer->i_pts );
623         aout_lock_input_fifos( p_aout );
624         aout_FifoSet( p_aout, &p_input->mixer.fifo, 0 );
625         p_input->mixer.begin = NULL;
626         aout_unlock_input_fifos( p_aout );
627         if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
628             msg_Warn( p_aout, "timing screwed, stopping resampling" );
629         inputResamplingStop( p_input );
630         p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
631         start_date = 0;
632     }
633     else if ( start_date != 0 &&
634               ( start_date > p_buffer->i_pts + i_pts_tolerance) )
635     {
636         msg_Warn( p_aout, "audio drift is too big (%"PRId64"), dropping buffer",
637                   start_date - p_buffer->i_pts );
638         inputDrop( p_input, p_buffer );
639         return 0;
640     }
641
642     if ( start_date == 0 ) start_date = p_buffer->i_pts;
643
644 #ifndef AOUT_PROCESS_BEFORE_CHEKS
645     /* Run pre-filters. */
646     aout_FiltersPlay( p_input->pp_filters, p_input->i_nb_filters, &p_buffer );
647     if( !p_buffer )
648         return 0;
649 #endif
650
651     /* Run the resampler if needed.
652      * We first need to calculate the output rate of this resampler. */
653     if ( ( p_input->i_resampling_type == AOUT_RESAMPLING_NONE ) &&
654          ( start_date < p_buffer->i_pts - AOUT_PTS_TOLERANCE
655            || start_date > p_buffer->i_pts + AOUT_PTS_TOLERANCE ) &&
656          p_input->i_nb_resamplers > 0 )
657     {
658         /* Can happen in several circumstances :
659          * 1. A problem at the input (clock drift)
660          * 2. A small pause triggered by the user
661          * 3. Some delay in the output stage, causing a loss of lip
662          *    synchronization
663          * Solution : resample the buffer to avoid a scratch.
664          */
665         mtime_t drift = p_buffer->i_pts - start_date;
666
667         p_input->i_resamp_start_date = mdate();
668         p_input->i_resamp_start_drift = (int)drift;
669
670         if ( drift > 0 )
671             p_input->i_resampling_type = AOUT_RESAMPLING_DOWN;
672         else
673             p_input->i_resampling_type = AOUT_RESAMPLING_UP;
674
675         msg_Warn( p_aout, "buffer is %"PRId64" %s, triggering %ssampling",
676                           drift > 0 ? drift : -drift,
677                           drift > 0 ? "in advance" : "late",
678                           drift > 0 ? "down" : "up");
679     }
680
681     if ( p_input->i_resampling_type != AOUT_RESAMPLING_NONE )
682     {
683         /* Resampling has been triggered previously (because of dates
684          * mismatch). We want the resampling to happen progressively so
685          * it isn't too audible to the listener. */
686
687         if( p_input->i_resampling_type == AOUT_RESAMPLING_UP )
688         {
689             p_input->pp_resamplers[0]->fmt_in.audio.i_rate += 2; /* Hz */
690         }
691         else
692         {
693             p_input->pp_resamplers[0]->fmt_in.audio.i_rate -= 2; /* Hz */
694         }
695
696         /* Check if everything is back to normal, in which case we can stop the
697          * resampling */
698         unsigned int i_nominal_rate =
699           (p_input->pp_resamplers[0] == p_input->p_playback_rate_filter)
700           ? INPUT_RATE_DEFAULT * p_input->input.i_rate / i_input_rate
701           : p_input->input.i_rate;
702         if( p_input->pp_resamplers[0]->fmt_in.audio.i_rate == i_nominal_rate )
703         {
704             p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
705             msg_Warn( p_aout, "resampling stopped after %"PRIi64" usec "
706                       "(drift: %"PRIi64")",
707                       mdate() - p_input->i_resamp_start_date,
708                       p_buffer->i_pts - start_date);
709         }
710         else if( abs( (int)(p_buffer->i_pts - start_date) ) <
711                  abs( p_input->i_resamp_start_drift ) / 2 )
712         {
713             /* if we reduced the drift from half, then it is time to switch
714              * back the resampling direction. */
715             if( p_input->i_resampling_type == AOUT_RESAMPLING_UP )
716                 p_input->i_resampling_type = AOUT_RESAMPLING_DOWN;
717             else
718                 p_input->i_resampling_type = AOUT_RESAMPLING_UP;
719             p_input->i_resamp_start_drift = 0;
720         }
721         else if( p_input->i_resamp_start_drift &&
722                  ( abs( (int)(p_buffer->i_pts - start_date) ) >
723                    abs( p_input->i_resamp_start_drift ) * 3 / 2 ) )
724         {
725             /* If the drift is increasing and not decreasing, than something
726              * is bad. We'd better stop the resampling right now. */
727             msg_Warn( p_aout, "timing screwed, stopping resampling" );
728             inputResamplingStop( p_input );
729             p_buffer->i_flags |= BLOCK_FLAG_DISCONTINUITY;
730         }
731     }
732
733 #ifndef AOUT_PROCESS_BEFORE_CHEKS
734     /* Actually run the resampler now. */
735     if ( p_input->i_nb_resamplers > 0 )
736     {
737         aout_FiltersPlay( p_input->pp_resamplers, p_input->i_nb_resamplers,
738                           &p_buffer );
739     }
740
741     if( !p_buffer )
742         return 0;
743     if( p_buffer->i_nb_samples <= 0 )
744     {
745         block_Release( p_buffer );
746         return 0;
747     }
748 #endif
749
750     /* Adding the start date will be managed by aout_FifoPush(). */
751     p_buffer->i_pts = start_date;
752
753     aout_lock_input_fifos( p_aout );
754     aout_FifoPush( p_aout, &p_input->mixer.fifo, p_buffer );
755     aout_unlock_input_fifos( p_aout );
756     return 0;
757 }
758
759 /*****************************************************************************
760  * static functions
761  *****************************************************************************/
762
763 static void inputFailure( aout_instance_t * p_aout, aout_input_t * p_input,
764                           const char * psz_error_message )
765 {
766     /* error message */
767     msg_Err( p_aout, "%s", psz_error_message );
768
769     /* clean up */
770     aout_FiltersDestroyPipeline( p_aout, p_input->pp_filters,
771                                  p_input->i_nb_filters );
772     aout_FiltersDestroyPipeline( p_aout, p_input->pp_resamplers,
773                                  p_input->i_nb_resamplers );
774     aout_FifoDestroy( p_aout, &p_input->mixer.fifo );
775     var_Destroy( p_aout, "visual" );
776     var_Destroy( p_aout, "equalizer" );
777     var_Destroy( p_aout, "audio-filter" );
778     var_Destroy( p_aout, "audio-visual" );
779
780     var_Destroy( p_aout, "audio-replay-gain-mode" );
781     var_Destroy( p_aout, "audio-replay-gain-default" );
782     var_Destroy( p_aout, "audio-replay-gain-preamp" );
783     var_Destroy( p_aout, "audio-replay-gain-peak-protection" );
784
785     /* error flag */
786     p_input->b_error = 1;
787 }
788
789 static void inputDrop( aout_input_t *p_input, aout_buffer_t *p_buffer )
790 {
791     aout_BufferFree( p_buffer );
792
793     p_input->i_buffer_lost++;
794 }
795
796 static void inputResamplingStop( aout_input_t *p_input )
797 {
798     p_input->i_resampling_type = AOUT_RESAMPLING_NONE;
799     if( p_input->i_nb_resamplers != 0 )
800     {
801         p_input->pp_resamplers[0]->fmt_in.audio.i_rate =
802             ( p_input->pp_resamplers[0] == p_input->p_playback_rate_filter )
803             ? INPUT_RATE_DEFAULT * p_input->input.i_rate / p_input->i_last_input_rate
804             : p_input->input.i_rate;
805     }
806 }
807
808 static vout_thread_t *RequestVout( void *p_private,
809                                    vout_thread_t *p_vout, video_format_t *p_fmt, bool b_recycle )
810 {
811     aout_instance_t *p_aout = p_private;
812     VLC_UNUSED(b_recycle);
813     vout_configuration_t cfg = {
814         .vout       = p_vout,
815         .input      = NULL,
816         .change_fmt = true,
817         .fmt        = p_fmt,
818         .dpb_size   = 1,
819     };
820     return vout_Request( p_aout, &cfg );
821 }
822
823 vout_thread_t *aout_filter_RequestVout( filter_t *p_filter,
824                                         vout_thread_t *p_vout, video_format_t *p_fmt )
825 {
826     aout_input_t *p_input = p_filter->p_owner->p_input;
827     aout_request_vout_t *p_request = &p_input->request_vout;
828
829     /* XXX: this only works from audio input */
830     /* If you want to use visualization filters from another place, you will
831      * need to add a new pf_aout_request_vout callback or store a pointer
832      * to aout_request_vout_t inside filter_t (i.e. a level of indirection). */
833
834     return p_request->pf_request_vout( p_request->p_private,
835                                        p_vout, p_fmt, p_input->b_recycle_vout );
836 }
837
838 static int ChangeFiltersString( aout_instance_t * p_aout, const char* psz_variable,
839                                  const char *psz_name, bool b_add )
840 {
841     return aout_ChangeFilterString( VLC_OBJECT(p_aout), p_aout,
842                                     psz_variable, psz_name, b_add ) ? 1 : 0;
843 }
844
845 static int VisualizationCallback( 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     (void)psz_cmd; (void)oldval; (void)p_data;
851
852     if( !psz_mode || !*psz_mode )
853     {
854         ChangeFiltersString( p_aout, "audio-visual", "goom", false );
855         ChangeFiltersString( p_aout, "audio-visual", "visual", false );
856         ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
857     }
858     else
859     {
860         if( !strcmp( "goom", psz_mode ) )
861         {
862             ChangeFiltersString( p_aout, "audio-visual", "visual", false );
863             ChangeFiltersString( p_aout, "audio-visual", "goom", true );
864             ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
865         }
866         else if( !strcmp( "projectm", psz_mode ) )
867         {
868             ChangeFiltersString( p_aout, "audio-visual", "visual", false );
869             ChangeFiltersString( p_aout, "audio-visual", "goom", false );
870             ChangeFiltersString( p_aout, "audio-visual", "projectm", true );
871         }
872         else
873         {
874             var_Create( p_aout, "effect-list", VLC_VAR_STRING );
875             var_SetString( p_aout, "effect-list", psz_mode );
876
877             ChangeFiltersString( p_aout, "audio-visual", "goom", false );
878             ChangeFiltersString( p_aout, "audio-visual", "visual", true );
879             ChangeFiltersString( p_aout, "audio-visual", "projectm", false );
880         }
881     }
882
883     /* That sucks */
884     AoutInputsMarkToRestart( p_aout );
885
886     return VLC_SUCCESS;
887 }
888
889 static int EqualizerCallback( vlc_object_t *p_this, char const *psz_cmd,
890                        vlc_value_t oldval, vlc_value_t newval, void *p_data )
891 {
892     aout_instance_t *p_aout = (aout_instance_t *)p_this;
893     char *psz_mode = newval.psz_string;
894     int i_ret;
895     (void)psz_cmd; (void)oldval; (void)p_data;
896
897     if( !psz_mode || !*psz_mode )
898     {
899         i_ret = ChangeFiltersString( p_aout, "audio-filter", "equalizer",
900                                      false );
901     }
902     else
903     {
904         var_Create( p_aout, "equalizer-preset", VLC_VAR_STRING );
905         var_SetString( p_aout, "equalizer-preset", psz_mode );
906         i_ret = ChangeFiltersString( p_aout, "audio-filter", "equalizer",
907                                      true );
908     }
909
910     /* That sucks */
911     if( i_ret == 1 )
912         AoutInputsMarkToRestart( p_aout );
913     return VLC_SUCCESS;
914 }
915
916 static int ReplayGainCallback( vlc_object_t *p_this, char const *psz_cmd,
917                                vlc_value_t oldval, vlc_value_t newval, void *p_data )
918 {
919     VLC_UNUSED(psz_cmd); VLC_UNUSED(oldval);
920     VLC_UNUSED(newval); VLC_UNUSED(p_data);
921     aout_instance_t *p_aout = (aout_instance_t *)p_this;
922     int i;
923
924     aout_lock_mixer( p_aout );
925     for( i = 0; i < p_aout->i_nb_inputs; i++ )
926         ReplayGainSelect( p_aout, p_aout->pp_inputs[i] );
927
928     /* Restart the mixer (a trivial mixer may be in use) */
929     if( p_aout->p_mixer )
930         aout_MixerMultiplierSet( p_aout, p_aout->mixer_multiplier );
931     aout_unlock_mixer( p_aout );
932
933     return VLC_SUCCESS;
934 }
935
936 static void ReplayGainSelect( aout_instance_t *p_aout, aout_input_t *p_input )
937 {
938     char *psz_replay_gain = var_GetNonEmptyString( p_aout,
939                                                    "audio-replay-gain-mode" );
940     int i_mode;
941     int i_use;
942     float f_gain;
943
944     p_input->mixer.multiplier = 1.0;
945
946     if( !psz_replay_gain )
947         return;
948
949     /* Find select mode */
950     if( !strcmp( psz_replay_gain, "track" ) )
951         i_mode = AUDIO_REPLAY_GAIN_TRACK;
952     else if( !strcmp( psz_replay_gain, "album" ) )
953         i_mode = AUDIO_REPLAY_GAIN_ALBUM;
954     else
955         i_mode = AUDIO_REPLAY_GAIN_MAX;
956
957     /* If the select mode is not available, prefer the other one */
958     i_use = i_mode;
959     if( i_use != AUDIO_REPLAY_GAIN_MAX && !p_input->replay_gain.pb_gain[i_use] )
960     {
961         for( i_use = 0; i_use < AUDIO_REPLAY_GAIN_MAX; i_use++ )
962         {
963             if( p_input->replay_gain.pb_gain[i_use] )
964                 break;
965         }
966     }
967
968     /* */
969     if( i_use != AUDIO_REPLAY_GAIN_MAX )
970         f_gain = p_input->replay_gain.pf_gain[i_use] + var_GetFloat( p_aout, "audio-replay-gain-preamp" );
971     else if( i_mode != AUDIO_REPLAY_GAIN_MAX )
972         f_gain = var_GetFloat( p_aout, "audio-replay-gain-default" );
973     else
974         f_gain = 0.0;
975     p_input->mixer.multiplier = pow( 10.0, f_gain / 20.0 );
976
977     /* */
978     if( p_input->replay_gain.pb_peak[i_use] &&
979         var_GetBool( p_aout, "audio-replay-gain-peak-protection" ) &&
980         p_input->replay_gain.pf_peak[i_use] * p_input->mixer.multiplier > 1.0 )
981     {
982         p_input->mixer.multiplier = 1.0f / p_input->replay_gain.pf_peak[i_use];
983     }
984
985     free( psz_replay_gain );
986 }
987