]> git.sesse.net Git - vlc/blob - src/audio_output/output.c
aout: privatize some attributes
[vlc] / src / audio_output / output.c
1 /*****************************************************************************
2  * output.c : internal management of output streams for the audio output
3  *****************************************************************************
4  * Copyright (C) 2002-2004 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 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <assert.h>
32 #include <vlc_common.h>
33 #include <vlc_aout.h>
34 #include <vlc_aout_intf.h>
35 #include <vlc_cpu.h>
36 #include <vlc_modules.h>
37
38 #include "libvlc.h"
39 #include "aout_internal.h"
40
41 /*****************************************************************************
42  * aout_OutputNew : allocate a new output and rework the filter pipeline
43  *****************************************************************************
44  * This function is entered with the mixer lock.
45  *****************************************************************************/
46 int aout_OutputNew( audio_output_t *p_aout,
47                     const audio_sample_format_t * p_format )
48 {
49     aout_owner_t *owner = aout_owner (p_aout);
50
51     vlc_assert_locked( &p_aout->lock );
52     p_aout->format = *p_format;
53
54     /* Retrieve user defaults. */
55     int i_rate = var_InheritInteger( p_aout, "aout-rate" );
56     if ( i_rate != 0 )
57         p_aout->format.i_rate = i_rate;
58     aout_FormatPrepare( &p_aout->format );
59
60     /* Find the best output plug-in. */
61     owner->module = module_need (p_aout, "audio output", "$aout", false);
62     if (owner->module == NULL)
63     {
64         msg_Err( p_aout, "no suitable audio output module" );
65         return -1;
66     }
67
68     if ( var_Type( p_aout, "audio-channels" ) ==
69              (VLC_VAR_INTEGER | VLC_VAR_HASCHOICE) )
70     {
71         /* The user may have selected a different channels configuration. */
72         switch( var_InheritInteger( p_aout, "audio-channels" ) )
73         {
74             case AOUT_VAR_CHAN_RSTEREO:
75                 p_aout->format.i_original_channels |= AOUT_CHAN_REVERSESTEREO;
76                 break;
77             case AOUT_VAR_CHAN_STEREO:
78                 p_aout->format.i_original_channels =
79                                               AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
80                 break;
81             case AOUT_VAR_CHAN_LEFT:
82                 p_aout->format.i_original_channels = AOUT_CHAN_LEFT;
83                 break;
84             case AOUT_VAR_CHAN_RIGHT:
85                 p_aout->format.i_original_channels = AOUT_CHAN_RIGHT;
86                 break;
87             case AOUT_VAR_CHAN_DOLBYS:
88                 p_aout->format.i_original_channels =
89                       AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_DOLBYSTEREO;
90                 break;
91         }
92     }
93     else if ( p_aout->format.i_physical_channels == AOUT_CHAN_CENTER
94               && (p_aout->format.i_original_channels
95                    & AOUT_CHAN_PHYSMASK) == (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT) )
96     {
97         vlc_value_t val, text;
98
99         /* Mono - create the audio-channels variable. */
100         var_Create( p_aout, "audio-channels",
101                     VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
102         text.psz_string = _("Audio Channels");
103         var_Change( p_aout, "audio-channels", VLC_VAR_SETTEXT, &text, NULL );
104
105         val.i_int = AOUT_VAR_CHAN_STEREO; text.psz_string = _("Stereo");
106         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
107         val.i_int = AOUT_VAR_CHAN_LEFT; text.psz_string = _("Left");
108         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
109         val.i_int = AOUT_VAR_CHAN_RIGHT; text.psz_string = _("Right");
110         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
111         if ( p_aout->format.i_original_channels & AOUT_CHAN_DUALMONO )
112         {
113             /* Go directly to the left channel. */
114             p_aout->format.i_original_channels = AOUT_CHAN_LEFT;
115             var_SetInteger( p_aout, "audio-channels", AOUT_VAR_CHAN_LEFT );
116         }
117         var_AddCallback( p_aout, "audio-channels", aout_ChannelsRestart,
118                          NULL );
119     }
120     else if ( p_aout->format.i_physical_channels ==
121                (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT)
122                 && (p_aout->format.i_original_channels &
123                      (AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT)) )
124     {
125         vlc_value_t val, text;
126
127         /* Stereo - create the audio-channels variable. */
128         var_Create( p_aout, "audio-channels",
129                     VLC_VAR_INTEGER | VLC_VAR_HASCHOICE );
130         text.psz_string = _("Audio Channels");
131         var_Change( p_aout, "audio-channels", VLC_VAR_SETTEXT, &text, NULL );
132
133         if ( p_aout->format.i_original_channels & AOUT_CHAN_DOLBYSTEREO )
134         {
135             val.i_int = AOUT_VAR_CHAN_DOLBYS;
136             text.psz_string = _("Dolby Surround");
137         }
138         else
139         {
140             val.i_int = AOUT_VAR_CHAN_STEREO;
141             text.psz_string = _("Stereo");
142         }
143         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
144         val.i_int = AOUT_VAR_CHAN_LEFT; text.psz_string = _("Left");
145         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
146         val.i_int = AOUT_VAR_CHAN_RIGHT; text.psz_string = _("Right");
147         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
148         val.i_int = AOUT_VAR_CHAN_RSTEREO; text.psz_string=_("Reverse stereo");
149         var_Change( p_aout, "audio-channels", VLC_VAR_ADDCHOICE, &val, &text );
150         if ( p_aout->format.i_original_channels & AOUT_CHAN_DUALMONO )
151         {
152             /* Go directly to the left channel. */
153             p_aout->format.i_original_channels = AOUT_CHAN_LEFT;
154             var_SetInteger( p_aout, "audio-channels", AOUT_VAR_CHAN_LEFT );
155         }
156         var_AddCallback( p_aout, "audio-channels", aout_ChannelsRestart,
157                          NULL );
158     }
159     var_TriggerCallback( p_aout, "intf-change" );
160
161     aout_FormatPrepare( &p_aout->format );
162
163     /* Prepare FIFO. */
164     aout_FifoInit( p_aout, &p_aout->fifo, p_aout->format.i_rate );
165     aout_FormatPrint( p_aout, "output", &p_aout->format );
166
167     /* Choose the mixer format. */
168     owner->mixer_format = p_aout->format;
169     if (AOUT_FMT_NON_LINEAR(&p_aout->format))
170         owner->mixer_format.i_format = p_format->i_format;
171     else
172     /* Most audio filters can only deal with single-precision,
173      * so lets always use that when hardware supports floating point. */
174     if( HAVE_FPU )
175         owner->mixer_format.i_format = VLC_CODEC_FL32;
176     else
177     /* Otherwise, audio filters will not work. Use fixed-point if the input has
178      * more than 16-bits depth. */
179     if( p_format->i_bitspersample > 16 )
180         owner->mixer_format.i_format = VLC_CODEC_FI32;
181     else
182     /* Fallback to 16-bits. This avoids pointless conversion to and from
183      * 32-bits samples for the sole purpose of software mixing. */
184         owner->mixer_format.i_format = VLC_CODEC_S16N;
185
186     aout_FormatPrepare (&owner->mixer_format);
187     aout_FormatPrint (p_aout, "mixer", &owner->mixer_format);
188
189     /* Create filters. */
190     owner->nb_filters = 0;
191     if (aout_FiltersCreatePipeline (p_aout, owner->filters,
192                                     &owner->nb_filters, &owner->mixer_format,
193                                     &p_aout->format) < 0)
194     {
195         msg_Err( p_aout, "couldn't create audio output pipeline" );
196         module_unneed (p_aout, owner->module);
197         owner->module = NULL;
198         return -1;
199     }
200     return 0;
201 }
202
203 /*****************************************************************************
204  * aout_OutputDelete : delete the output
205  *****************************************************************************
206  * This function is entered with the mixer lock.
207  *****************************************************************************/
208 void aout_OutputDelete( audio_output_t * p_aout )
209 {
210     aout_owner_t *owner = aout_owner (p_aout);
211
212     vlc_assert_locked( &p_aout->lock );
213
214     if (owner->module == NULL)
215         return;
216
217     module_unneed (p_aout, owner->module);
218     aout_VolumeNoneInit( p_aout ); /* clear volume callback */
219     owner->module = NULL;
220     aout_FiltersDestroyPipeline (owner->filters, owner->nb_filters);
221     aout_FifoDestroy( &p_aout->fifo );
222 }
223
224 static block_t *aout_OutputSlice( audio_output_t *, aout_fifo_t * );
225
226 /*****************************************************************************
227  * aout_OutputPlay : play a buffer
228  *****************************************************************************
229  * This function is entered with the mixer lock.
230  *****************************************************************************/
231 void aout_OutputPlay( audio_output_t * p_aout, aout_buffer_t * p_buffer )
232 {
233     aout_owner_t *owner = aout_owner (p_aout);
234
235     vlc_assert_locked( &p_aout->lock );
236
237     aout_FiltersPlay (owner->filters, owner->nb_filters, &p_buffer);
238     if( !p_buffer )
239         return;
240     if( p_buffer->i_buffer == 0 )
241     {
242         block_Release( p_buffer );
243         return;
244     }
245
246     aout_fifo_t *fifo = &owner->input->fifo;
247     /* XXX: cleanup */
248     aout_FifoPush( fifo, p_buffer );
249
250     while( (p_buffer = aout_OutputSlice( p_aout, fifo ) ) != NULL )
251     {
252         aout_FifoPush( &p_aout->fifo, p_buffer );
253         p_aout->pf_play( p_aout );
254     }
255 }
256
257 /**
258  * Notifies the audio output (if any) of pause/resume events.
259  * This enables the output to expedite pause, instead of waiting for its
260  * buffers to drain.
261  */
262 void aout_OutputPause( audio_output_t *aout, bool pause, mtime_t date )
263 {
264     aout_owner_t *owner = aout_owner (aout);
265
266     vlc_assert_locked( &aout->lock );
267
268     if( aout->pf_pause != NULL )
269         aout->pf_pause( aout, pause, date );
270     if( !pause )
271     {
272         mtime_t duration = date - owner->input->i_pause_date;
273         /* XXX: ^ onk onk! gruik! ^ */
274         aout_FifoMoveDates( &aout->fifo, duration );
275     }
276 }
277
278 /**
279  * Flushes or drains the audio output buffers.
280  * This enables the output to expedite seek and stop.
281  * @param wait if true, wait for buffer playback (i.e. drain),
282  *             if false, discard the buffers immediately (i.e. flush)
283  */
284 void aout_OutputFlush( audio_output_t *aout, bool wait )
285 {
286     vlc_assert_locked( &aout->lock );
287
288     if( aout->pf_flush != NULL )
289         aout->pf_flush( aout, wait );
290     aout_FifoReset( &aout->fifo );
291 }
292
293
294 /*** Volume handling ***/
295
296 /**
297  * Dummy volume setter. This is the default volume setter.
298  */
299 static int aout_VolumeNoneSet (audio_output_t *aout, float volume, bool mute)
300 {
301     (void)aout; (void)volume; (void)mute;
302     return -1;
303 }
304
305 /**
306  * Configures the dummy volume setter.
307  * @note Audio output plugins for which volume is irrelevant
308  * should call this function during activation.
309  */
310 void aout_VolumeNoneInit (audio_output_t *aout)
311 {
312     /* aout_New() -safely- calls this function without the lock, before any
313      * other thread knows of this audio output instance.
314     vlc_assert_locked (&aout->lock); */
315     aout->pf_volume_set = aout_VolumeNoneSet;
316 }
317
318 /**
319  * Volume setter for software volume.
320  */
321 static int aout_VolumeSoftSet (audio_output_t *aout, float volume, bool mute)
322 {
323     aout_owner_t *owner = aout_owner (aout);
324
325     vlc_assert_locked (&aout->lock);
326
327     /* Cubic mapping from software volume to amplification factor.
328      * This provides a good tradeoff between low and high volume ranges.
329      *
330      * This code is only used for the VLC software mixer. If you change this
331      * formula, be sure to update the aout_VolumeHardInit()-based plugins also.
332      */
333     if (!mute)
334         volume = volume * volume * volume;
335     else
336         volume = 0.;
337
338     owner->volume.multiplier = volume;
339     return 0;
340 }
341
342 /**
343  * Configures the volume setter for software mixing
344  * and apply the default volume.
345  * @note Audio output plugins that cannot apply the volume
346  * should call this function during activation.
347  */
348 void aout_VolumeSoftInit (audio_output_t *aout)
349 {
350     audio_volume_t volume = var_InheritInteger (aout, "volume");
351     bool mute = var_InheritBool (aout, "mute");
352
353     vlc_assert_locked (&aout->lock);
354     aout->pf_volume_set = aout_VolumeSoftSet;
355     aout_VolumeSoftSet (aout, volume / (float)AOUT_VOLUME_DEFAULT, mute);
356 }
357
358 /**
359  * Configures a custom volume setter. This is used by audio outputs that can
360  * control the hardware volume directly and/or emulate it internally.
361  * @param setter volume setter callback
362  */
363 void aout_VolumeHardInit (audio_output_t *aout, aout_volume_cb setter)
364 {
365     vlc_assert_locked (&aout->lock);
366     aout->pf_volume_set = setter;
367 }
368
369 /**
370  * Supply or update the current custom ("hardware") volume.
371  * @note This only makes sense after calling aout_VolumeHardInit().
372  * @param setter volume setter callback
373  * @param volume current custom volume
374  * @param mute current mute flag
375  * @note Audio output plugins that cannot apply the volume
376  * should call this function during activation.
377  */
378 void aout_VolumeHardSet (audio_output_t *aout, float volume, bool mute)
379 {
380 #warning FIXME
381     /* REVISIT: This is tricky. We cannot acquire the volume lock as this gets
382      * called from the audio output (it would cause a lock inversion).
383      * We also should not override the input manager volume, but only the
384      * volume of the current audio output... FIXME */
385     msg_Err (aout, "%s(%f, %u)", __func__, volume, (unsigned)mute);
386 }
387
388
389 /*** Buffer management ***/
390
391 /**
392  * Rearranges audio blocks in correct number of samples.
393  * @note (FIXME) This is left here for historical reasons. It belongs in the
394  * output code. Besides, this operation should be avoided if possible.
395  */
396 static block_t *aout_OutputSlice (audio_output_t *p_aout, aout_fifo_t *p_fifo)
397 {
398     const unsigned samples = p_aout->i_nb_samples;
399     /* FIXME: Remove this silly constraint. Just pass buffers as they come to
400      * "smart" audio outputs. */
401     assert( samples > 0 );
402
403     vlc_assert_locked( &p_aout->lock );
404
405     /* Retrieve the date of the next buffer. */
406     date_t exact_start_date = p_aout->fifo.end_date;
407     mtime_t start_date = date_Get( &exact_start_date );
408
409     /* See if we have enough data to prepare a new buffer for the audio output. */
410     aout_buffer_t *p_buffer = p_fifo->p_first;
411     if( p_buffer == NULL )
412         return NULL;
413
414     /* Find the earliest start date available. */
415     if ( start_date == VLC_TS_INVALID )
416     {
417         start_date = p_buffer->i_pts;
418         date_Set( &exact_start_date, start_date );
419     }
420     /* Compute the end date for the new buffer. */
421     mtime_t end_date = date_Increment( &exact_start_date, samples );
422
423     /* Check that start_date is available. */
424     mtime_t prev_date;
425     for( ;; )
426     {
427         /* Check for the continuity of start_date */
428         prev_date = p_buffer->i_pts + p_buffer->i_length;
429         if( prev_date >= start_date - 1 )
430             break;
431         /* We authorize a +-1 because rounding errors get compensated
432          * regularly. */
433         msg_Warn( p_aout, "got a packet in the past (%"PRId64")",
434                   start_date - prev_date );
435         aout_BufferFree( aout_FifoPop( p_fifo ) );
436
437         p_buffer = p_fifo->p_first;
438         if( p_buffer == NULL )
439             return NULL;
440     }
441
442     /* Check that we have enough samples. */
443     while( prev_date < end_date )
444     {
445         p_buffer = p_buffer->p_next;
446         if( p_buffer == NULL )
447             return NULL;
448
449         /* Check that all buffers are contiguous. */
450         if( prev_date != p_buffer->i_pts )
451         {
452             msg_Warn( p_aout,
453                       "buffer hole, dropping packets (%"PRId64")",
454                       p_buffer->i_pts - prev_date );
455
456             aout_buffer_t *p_deleted;
457             while( (p_deleted = p_fifo->p_first) != p_buffer )
458                 aout_BufferFree( aout_FifoPop( p_fifo ) );
459         }
460
461         prev_date = p_buffer->i_pts + p_buffer->i_length;
462     }
463
464     if( !AOUT_FMT_NON_LINEAR( &p_aout->format ) )
465     {
466         p_buffer = p_fifo->p_first;
467
468         /* Additionally check that p_first_byte_to_mix is well located. */
469         const unsigned framesize = p_aout->format.i_bytes_per_frame;
470         ssize_t delta = (start_date - p_buffer->i_pts)
471                       * p_aout->format.i_rate / CLOCK_FREQ;
472         if( delta != 0 )
473             msg_Warn( p_aout, "input start is not output end (%zd)", delta );
474         if( delta < 0 )
475         {
476             /* Is it really the best way to do it ? */
477             aout_FifoReset( &p_aout->fifo );
478             return NULL;
479         }
480         if( delta > 0 )
481         {
482             mtime_t t = delta * CLOCK_FREQ / p_aout->format.i_rate;
483             p_buffer->i_nb_samples -= delta;
484             p_buffer->i_pts += t;
485             p_buffer->i_length -= t;
486             delta *= framesize;
487             p_buffer->p_buffer += delta;
488             p_buffer->i_buffer -= delta;
489         }
490
491         /* Build packet with adequate number of samples */
492         unsigned needed = samples * framesize;
493         p_buffer = block_Alloc( needed );
494         if( unlikely(p_buffer == NULL) )
495             /* XXX: should free input buffers */
496             return NULL;
497         p_buffer->i_nb_samples = samples;
498
499         for( uint8_t *p_out = p_buffer->p_buffer; needed > 0; )
500         {
501             aout_buffer_t *p_inbuf = p_fifo->p_first;
502             if( unlikely(p_inbuf == NULL) )
503             {
504                 msg_Err( p_aout, "packetization error" );
505                 vlc_memset( p_out, 0, needed );
506                 break;
507             }
508
509             const uint8_t *p_in = p_inbuf->p_buffer;
510             size_t avail = p_inbuf->i_nb_samples * framesize;
511             if( avail > needed )
512             {
513                 vlc_memcpy( p_out, p_in, needed );
514                 p_fifo->p_first->p_buffer += needed;
515                 p_fifo->p_first->i_buffer -= needed;
516                 needed /= framesize;
517                 p_fifo->p_first->i_nb_samples -= needed;
518
519                 mtime_t t = needed * CLOCK_FREQ / p_aout->format.i_rate;
520                 p_fifo->p_first->i_pts += t;
521                 p_fifo->p_first->i_length -= t;
522                 break;
523             }
524
525             vlc_memcpy( p_out, p_in, avail );
526             needed -= avail;
527             p_out += avail;
528             /* Next buffer */
529             aout_BufferFree( aout_FifoPop( p_fifo ) );
530         }
531     }
532     else
533         p_buffer = aout_FifoPop( p_fifo );
534
535     p_buffer->i_pts = start_date;
536     p_buffer->i_length = end_date - start_date;
537
538     return p_buffer;
539 }
540
541 /*****************************************************************************
542  * aout_OutputNextBuffer : give the audio output plug-in the right buffer
543  *****************************************************************************
544  * If b_can_sleek is 1, the aout core functions won't try to resample
545  * new buffers to catch up - that is we suppose that the output plug-in can
546  * compensate it by itself. S/PDIF outputs should always set b_can_sleek = 1.
547  * This function is entered with no lock at all :-).
548  *****************************************************************************/
549 aout_buffer_t * aout_OutputNextBuffer( audio_output_t * p_aout,
550                                        mtime_t start_date,
551                                        bool b_can_sleek )
552 {
553     aout_owner_t *owner = aout_owner (p_aout);
554     aout_fifo_t *p_fifo = &p_aout->fifo;
555     aout_buffer_t * p_buffer;
556     mtime_t now = mdate();
557
558     aout_lock( p_aout );
559
560     /* Drop the audio sample if the audio output is really late.
561      * In the case of b_can_sleek, we don't use a resampler so we need to be
562      * a lot more severe. */
563     while( ((p_buffer = p_fifo->p_first) != NULL)
564      && p_buffer->i_pts < (b_can_sleek ? start_date : now) - AOUT_MAX_PTS_DELAY )
565     {
566         msg_Dbg( p_aout, "audio output is too slow (%"PRId64"), "
567                  "trashing %"PRId64"us", now - p_buffer->i_pts,
568                  p_buffer->i_length );
569         aout_BufferFree( aout_FifoPop( p_fifo ) );
570     }
571
572     if( p_buffer == NULL )
573     {
574 #if 0 /* This is bad because the audio output might just be trying to fill
575        * in its internal buffers. And anyway, it's up to the audio output
576        * to deal with this kind of starvation. */
577
578         /* Set date to 0, to allow the mixer to send a new buffer ASAP */
579         aout_FifoReset( &p_aout->fifo );
580         if ( !p_aout->b_starving )
581             msg_Dbg( p_aout,
582                  "audio output is starving (no input), playing silence" );
583         p_aout->b_starving = true;
584 #endif
585         goto out;
586     }
587
588     mtime_t delta = start_date - p_buffer->i_pts;
589     /* Here we suppose that all buffers have the same duration - this is
590      * generally true, and anyway if it's wrong it won't be a disaster.
591      */
592     if ( 0 > delta + p_buffer->i_length )
593     {
594         if (!owner->b_starving)
595             msg_Dbg( p_aout, "audio output is starving (%"PRId64"), "
596                      "playing silence", -delta );
597         owner->b_starving = true;
598         p_buffer = NULL;
599         goto out;
600     }
601
602     owner->b_starving = false;
603     p_buffer = aout_FifoPop( p_fifo );
604
605     if( !b_can_sleek
606      && ( delta > AOUT_MAX_PTS_DELAY || delta < -AOUT_MAX_PTS_ADVANCE ) )
607     {
608         /* Try to compensate the drift by doing some resampling. */
609         msg_Warn( p_aout, "output date isn't PTS date, requesting "
610                   "resampling (%"PRId64")", delta );
611
612         aout_FifoMoveDates (&owner->input->fifo, delta);
613         aout_FifoMoveDates( p_fifo, delta );
614     }
615 out:
616     aout_unlock( p_aout );
617     return p_buffer;
618 }