]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
aout: report drift via parameter rather than callback
[vlc] / modules / audio_output / alsa.c
1 /*****************************************************************************
2  * alsa.c : alsa plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2000-2010 the VideoLAN team
5  * Copyright (C) 2009-2011 RĂ©mi Denis-Courmont
6  *
7  * Authors: Henri Fallon <henri@videolan.org> - Original Author
8  *          Jeffrey Baker <jwbaker@acm.org> - Port to ALSA 1.0 API
9  *          John Paul Lorenti <jpl31@columbia.edu> - Device selection
10  *          Arnaud de Bossoreille de Ribou <bozo@via.ecp.fr> - S/PDIF and aout3
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <assert.h>
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_dialog.h>
36 #include <vlc_aout.h>
37 #include <vlc_cpu.h>
38
39 #include <alsa/asoundlib.h>
40 #include <alsa/version.h>
41
42 /** Private data for an ALSA PCM playback stream */
43 struct aout_sys_t
44 {
45     snd_pcm_t *pcm;
46     void (*reorder) (void *, size_t, unsigned);
47     float soft_gain;
48     bool soft_mute;
49 };
50
51 #include "volume.h"
52
53 #define A52_FRAME_NB 1536
54
55 static int Open (vlc_object_t *);
56 static void Close (vlc_object_t *);
57 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
58                                 vlc_value_t newval, vlc_value_t oldval, void *p_unused );
59 static void GetDevices (vlc_object_t *, module_config_t *, const char *);
60
61 #define AUDIO_DEV_TEXT N_("Audio output device")
62 #define AUDIO_DEV_LONGTEXT N_("Audio output device (using ALSA syntax).")
63 static const char *const devices[] = {
64     "default",
65 };
66 static const char *const devices_text[] = {
67     N_("Default"),
68 };
69
70 #define AUDIO_CHAN_TEXT N_("Audio output channels")
71 #define AUDIO_CHAN_LONGTEXT N_("Channels available for audio output." \
72     "If the input has more channels than the output, it will be down-mixed." \
73     "This parameter is ignored when digital pass-through is active.")
74 static const int channels[] = {
75     AOUT_CHAN_CENTER, AOUT_CHANS_STEREO, AOUT_CHANS_4_0, AOUT_CHANS_4_1,
76     AOUT_CHANS_5_0, AOUT_CHANS_5_1, AOUT_CHANS_7_1,
77 };
78 static const char *const channels_text[] = {
79     N_("Mono"), N_("Stereo"), N_("Surround 4.0"), N_("Surround 4.1"),
80     N_("Surround 5.0"), N_("Surround 5.1"), N_("Surround 7.1"),
81 };
82
83 vlc_module_begin ()
84     set_shortname( "ALSA" )
85     set_description( N_("ALSA audio output") )
86     set_category( CAT_AUDIO )
87     set_subcategory( SUBCAT_AUDIO_AOUT )
88     add_string ("alsa-audio-device", "default",
89                 AUDIO_DEV_TEXT, AUDIO_DEV_LONGTEXT, false)
90         change_string_list( devices, devices_text, FindDevicesCallback )
91         change_action_add( FindDevicesCallback, N_("Refresh list") )
92     add_integer ("alsa-audio-channels", AOUT_CHANS_FRONT,
93                  AUDIO_CHAN_TEXT, AUDIO_CHAN_LONGTEXT, false)
94         change_integer_list (channels, channels_text)
95     add_sw_gain ()
96     set_capability( "audio output", 150 )
97     set_callbacks( Open, Close )
98 vlc_module_end ()
99
100
101 /** Helper for ALSA -> VLC debugging output */
102 static void Dump (vlc_object_t *obj, const char *msg,
103                   int (*cb)(void *, snd_output_t *), void *p)
104 {
105     snd_output_t *output;
106     char *str;
107
108     if (unlikely(snd_output_buffer_open (&output)))
109         return;
110
111     int val = cb (p, output);
112     if (val)
113     {
114         msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
115         return;
116     }
117
118     size_t len = snd_output_buffer_string (output, &str);
119     if (len > 0 && str[len - 1])
120         len--; /* strip trailing newline */
121     msg_Dbg (obj, "%s%.*s", msg, (int)len, str);
122     snd_output_close (output);
123 }
124 #define Dump(o, m, cb, p) \
125         Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
126
127 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
128 {
129     snd_pcm_info_t *info;
130
131     Dump (obj, " ", snd_pcm_dump, pcm);
132     snd_pcm_info_alloca (&info);
133     if (snd_pcm_info (pcm, info) == 0)
134     {
135         msg_Dbg (obj, " device name   : %s", snd_pcm_info_get_name (info));
136         msg_Dbg (obj, " device ID     : %s", snd_pcm_info_get_id (info));
137         msg_Dbg (obj, " subdevice name: %s",
138                 snd_pcm_info_get_subdevice_name (info));
139     }
140 }
141
142 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
143 {
144     snd_pcm_status_t *status;
145
146     snd_pcm_status_alloca (&status);
147     snd_pcm_status (pcm, status);
148     Dump (obj, "current status:\n", snd_pcm_status_dump, status);
149 }
150 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
151
152 static int DeviceChanged (vlc_object_t *obj, const char *varname,
153                           vlc_value_t prev, vlc_value_t cur, void *data)
154 {
155     aout_ChannelsRestart (obj, varname, prev, cur, data);
156
157     if (!var_Type (obj, "alsa-audio-device"))
158         var_Create (obj, "alsa-audio-device", VLC_VAR_STRING);
159     var_SetString (obj, "alsa-audio-device", cur.psz_string);
160     return VLC_SUCCESS;
161 }
162
163 static void Play (audio_output_t *, block_t *, mtime_t *);
164 static void Pause (audio_output_t *, bool, mtime_t);
165 static void PauseDummy (audio_output_t *, bool, mtime_t);
166 static void Flush (audio_output_t *, bool);
167 static void Reorder71 (void *, size_t, unsigned);
168
169 /** Initializes an ALSA playback stream */
170 static int Open (vlc_object_t *obj)
171 {
172     audio_output_t *aout = (audio_output_t *)obj;
173
174     /* Get device name */
175     char *device = var_InheritString (aout, "alsa-audio-device");
176     if (unlikely(device == NULL))
177         return VLC_ENOMEM;
178
179     snd_pcm_format_t pcm_format; /* ALSA sample format */
180     vlc_fourcc_t fourcc = aout->format.i_format;
181     bool spdif = false;
182
183     switch (fourcc)
184     {
185         case VLC_CODEC_F64B:
186             pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
187             break;
188         case VLC_CODEC_F64L:
189             pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
190             break;
191         case VLC_CODEC_F32B:
192             pcm_format = SND_PCM_FORMAT_FLOAT_BE;
193             break;
194         case VLC_CODEC_F32L:
195             pcm_format = SND_PCM_FORMAT_FLOAT_LE;
196             break;
197         case VLC_CODEC_S32B:
198             pcm_format = SND_PCM_FORMAT_S32_BE;
199             break;
200         case VLC_CODEC_S32L:
201             pcm_format = SND_PCM_FORMAT_S32_LE;
202             break;
203         case VLC_CODEC_S24B:
204             pcm_format = SND_PCM_FORMAT_S24_3BE;
205             break;
206         case VLC_CODEC_S24L:
207             pcm_format = SND_PCM_FORMAT_S24_3LE;
208             break;
209         case VLC_CODEC_U24B:
210             pcm_format = SND_PCM_FORMAT_U24_3BE;
211             break;
212         case VLC_CODEC_U24L:
213             pcm_format = SND_PCM_FORMAT_U24_3LE;
214             break;
215         case VLC_CODEC_S16B:
216             pcm_format = SND_PCM_FORMAT_S16_BE;
217             break;
218         case VLC_CODEC_S16L:
219             pcm_format = SND_PCM_FORMAT_S16_LE;
220             break;
221         case VLC_CODEC_U16B:
222             pcm_format = SND_PCM_FORMAT_U16_BE;
223             break;
224         case VLC_CODEC_U16L:
225             pcm_format = SND_PCM_FORMAT_U16_LE;
226             break;
227         case VLC_CODEC_S8:
228             pcm_format = SND_PCM_FORMAT_S8;
229             break;
230         case VLC_CODEC_U8:
231             pcm_format = SND_PCM_FORMAT_U8;
232             break;
233         default:
234             if (AOUT_FMT_SPDIF(&aout->format))
235                 spdif = var_InheritBool (aout, "spdif");
236             if (spdif)
237             {
238                 fourcc = VLC_CODEC_SPDIFL;
239                 pcm_format = SND_PCM_FORMAT_S16;
240             }
241             else
242             if (HAVE_FPU)
243             {
244                 fourcc = VLC_CODEC_FL32;
245                 pcm_format = SND_PCM_FORMAT_FLOAT;
246             }
247             else
248             {
249                 fourcc = VLC_CODEC_S16N;
250                 pcm_format = SND_PCM_FORMAT_S16;
251             }
252     }
253
254     /* ALSA channels */
255     /* XXX: maybe this should be shared with other dumb outputs */
256     uint32_t map = var_InheritInteger (aout, "alsa-audio-channels");
257     map &= aout->format.i_physical_channels;
258     if (unlikely(map == 0)) /* WTH? */
259         map = AOUT_CHANS_STEREO;
260
261     unsigned channels = popcount (map);
262     if (channels < aout_FormatNbChannels (&aout->format))
263         msg_Dbg (aout, "downmixing from %u to %u channels",
264                  aout_FormatNbChannels (&aout->format), channels);
265     else
266         msg_Dbg (aout, "keeping %u channels", channels);
267
268     /* Choose the IEC device for S/PDIF output:
269        if the device is overridden by the user then it will be the one.
270        Otherwise we compute the default device based on the output format. */
271     if (spdif && !strcmp (device, "default"))
272     {
273         unsigned aes3;
274
275         switch (aout->format.i_rate)
276         {
277 #define FS(freq) \
278             case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
279             FS( 44100) /* def. */ FS( 48000) FS( 32000)
280             FS( 22050)            FS( 24000)
281             FS( 88200) FS(768000) FS( 96000)
282             FS(176400)            FS(192000)
283 #undef FS
284             default:
285                 aes3 = IEC958_AES3_CON_FS_NOTID;
286                 break;
287         }
288
289         free (device);
290         if (asprintf (&device,
291                       "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
292                       IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
293                       IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
294                       0, aes3) == -1)
295             return VLC_ENOMEM;
296     }
297
298     /* Allocate structures */
299     aout_sys_t *sys = malloc (sizeof (*sys));
300     if (unlikely(sys == NULL))
301     {
302         free (device);
303         return VLC_ENOMEM;
304     }
305     aout->sys = sys;
306
307     /* Open the device */
308     snd_pcm_t *pcm;
309     /* VLC always has a resampler. No need for ALSA's. */
310     const int mode = SND_PCM_NO_AUTO_RESAMPLE;
311
312     int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
313 #if (SND_LIB_VERSION <= 0x010015)
314 # warning Please update alsa-lib to version > 1.0.21a.
315     var_Create (aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
316     if (val != 0 && var_GetBool (aout->p_libvlc, "alsa-working"))
317         dialog_Fatal (aout, "ALSA version problem",
318             "VLC failed to re-initialize your audio output device.\n"
319             "Please update alsa-lib to version 1.0.22 or higher "
320             "to fix this issue.");
321     var_SetBool (aout->p_libvlc, "alsa-working", !val);
322 #endif
323     if (val != 0)
324     {
325 #if (SND_LIB_VERSION <= 0x010017)
326 # warning Please update alsa-lib to version > 1.0.23.
327         var_Create (aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
328         if (!var_GetBool (aout->p_libvlc, "alsa-broken"))
329         {
330             var_SetBool (aout->p_libvlc, "alsa-broken", true);
331             dialog_Fatal (aout, "Potential ALSA version problem",
332                 "VLC failed to initialize your audio output device (if any).\n"
333                 "Please update alsa-lib to version 1.0.24 or higher "
334                 "to try to fix this issue.");
335         }
336 #endif
337         msg_Err (aout, "cannot open ALSA device \"%s\": %s", device,
338                  snd_strerror (val));
339         dialog_Fatal (aout, _("Audio output failed"),
340                       _("The audio device \"%s\" could not be used:\n%s."),
341                       device, snd_strerror (val));
342         free (device);
343         free (sys);
344         return VLC_EGENERIC;
345     }
346     sys->pcm = pcm;
347
348     /* Print some potentially useful debug */
349     msg_Dbg (aout, "using ALSA device: %s", device);
350     DumpDevice (VLC_OBJECT(aout), pcm);
351
352     /* Get Initial hardware parameters */
353     snd_pcm_hw_params_t *hw;
354     unsigned param;
355
356     snd_pcm_hw_params_alloca (&hw);
357     snd_pcm_hw_params_any (pcm, hw);
358     Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
359
360     val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
361     if (val)
362     {
363         msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
364         goto error;
365     }
366
367     val = snd_pcm_hw_params_set_access (pcm, hw,
368                                         SND_PCM_ACCESS_RW_INTERLEAVED);
369     if (val)
370     {
371         msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
372         goto error;
373     }
374
375     /* Set sample format */
376     if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
377         ;
378     else
379     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
380     {
381         fourcc = VLC_CODEC_FL32;
382         pcm_format = SND_PCM_FORMAT_FLOAT;
383     }
384     else
385     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
386     {
387         fourcc = VLC_CODEC_S32N;
388         pcm_format = SND_PCM_FORMAT_S32;
389     }
390     else
391     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
392     {
393         fourcc = VLC_CODEC_S16N;
394         pcm_format = SND_PCM_FORMAT_S16;
395     }
396     else
397     {
398         msg_Err (aout, "no supported sample format");
399         goto error;
400     }
401
402     val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
403     if (val)
404     {
405         msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
406         goto error;
407     }
408
409     /* Set channels count */
410     /* By default, ALSA plug will pad missing channels with zeroes, which is
411      * usually fine. However, it will also discard extraneous channels, which
412      * is not acceptable. Thus the user must configure the physically
413      * available channels, and VLC will downmix if needed. */
414     val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
415     if (val)
416     {
417         msg_Err (aout, "cannot set %u channels: %s", channels,
418                  snd_strerror (val));
419         goto error;
420     }
421
422     /* Set sample rate */
423     unsigned rate = aout->format.i_rate;
424     val = snd_pcm_hw_params_set_rate_near (pcm, hw, &rate, NULL);
425     if (val)
426     {
427         msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
428         goto error;
429     }
430     if (aout->format.i_rate != rate)
431         msg_Dbg (aout, "resampling from %d Hz to %d Hz",
432                  aout->format.i_rate, rate);
433
434     /* Set buffer size */
435     param = AOUT_MAX_ADVANCE_TIME;
436     val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, &param, NULL);
437     if (val)
438     {
439         msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
440         goto error;
441     }
442 #if 0
443     val = snd_pcm_hw_params_get_buffer_time (hw, &param, NULL);
444     if (val)
445     {
446         msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
447         param = AOUT_MIN_PREPARE_TIME;
448     }
449     else
450         param /= 2;
451 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
452     param = AOUT_MIN_PREPARE_TIME;
453 #endif
454     val = snd_pcm_hw_params_set_period_time_near (pcm, hw, &param, NULL);
455     if (val)
456     {
457         msg_Err (aout, "cannot set period: %s", snd_strerror (val));
458         goto error;
459     }
460
461     /* Commit hardware parameters */
462     val = snd_pcm_hw_params (pcm, hw);
463     if (val < 0)
464     {
465         msg_Err (aout, "cannot commit hardware parameters: %s",
466                  snd_strerror (val));
467         goto error;
468     }
469     Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
470
471     /* Get Initial software parameters */
472     snd_pcm_sw_params_t *sw;
473
474     snd_pcm_sw_params_alloca (&sw);
475     snd_pcm_sw_params_current (pcm, sw);
476     Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
477
478     /* START REVISIT */
479     //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
480     // FIXME: useful?
481     val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
482     if( val < 0 )
483     {
484         msg_Err( aout, "unable to set start threshold (%s)",
485                  snd_strerror( val ) );
486         goto error;
487     }
488     /* END REVISIT */
489
490     /* Commit software parameters. */
491     val = snd_pcm_sw_params (pcm, sw);
492     if (val)
493     {
494         msg_Err (aout, "cannot commit software parameters: %s",
495                  snd_strerror (val));
496         goto error;
497     }
498     Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
499
500     val = snd_pcm_prepare (pcm);
501     if (val)
502     {
503         msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
504         goto error;
505     }
506
507     /* Setup audio_output_t */
508     aout->format.i_format = fourcc;
509     aout->format.i_rate = rate;
510     sys->reorder = NULL;
511     if (spdif)
512     {
513         aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
514         aout->format.i_frame_length = A52_FRAME_NB;
515         aout->volume_set = NULL;
516         aout->mute_set = NULL;
517     }
518     else
519     {
520         aout->format.i_original_channels =
521         aout->format.i_physical_channels = map;
522         switch (popcount (map))
523         {
524             case 8:
525                 sys->reorder = Reorder71;
526                 break;
527         }
528
529         aout_SoftVolumeInit (aout);
530     }
531
532     aout->pf_play = Play;
533     if (snd_pcm_hw_params_can_pause (hw))
534         aout->pf_pause = Pause;
535     else
536     {
537         aout->pf_pause = PauseDummy;
538         msg_Warn (aout, "device cannot be paused");
539     }
540     aout->pf_flush = Flush;
541
542     /* Setup audio-device choices */
543     {
544         vlc_value_t text;
545
546         var_Create (obj, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
547         text.psz_string = _("Audio Device");
548         var_Change (obj, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
549
550         GetDevices (obj, NULL, device);
551     }
552     var_AddCallback (obj, "audio-device", DeviceChanged, NULL);
553
554     free (device);
555     return 0;
556
557 error:
558     snd_pcm_close (pcm);
559     free (device);
560     free (sys);
561     return VLC_EGENERIC;
562 }
563
564 /**
565  * Queues one audio buffer to the hardware.
566  */
567 static void Play (audio_output_t *aout, block_t *block,
568                   mtime_t *restrict drift)
569 {
570     aout_sys_t *sys = aout->sys;
571
572     if (sys->reorder != NULL)
573         sys->reorder (block->p_buffer, block->i_nb_samples,
574                       aout->format.i_bitspersample / 8);
575
576     snd_pcm_t *pcm = sys->pcm;
577     snd_pcm_sframes_t frames;
578     snd_pcm_state_t state = snd_pcm_state (pcm);
579
580     if (snd_pcm_delay (pcm, &frames) == 0)
581     {
582         mtime_t delay = frames * CLOCK_FREQ / aout->format.i_rate;
583         delay += mdate () - block->i_pts;
584
585         if (state != SND_PCM_STATE_RUNNING)
586         {
587             if (delay < 0)
588             {
589                 if (aout->format.i_format != VLC_CODEC_SPDIFL)
590                 {
591                     frames = (delay * aout->format.i_rate) / -CLOCK_FREQ;
592                     msg_Dbg (aout, "prepending %ld zeroes", frames);
593
594                     void *z = calloc (frames, aout->format.i_bytes_per_frame);
595                     if (likely(z != NULL))
596                     {
597                         snd_pcm_writei (pcm, z, frames);
598                         free (z);
599                         delay = 0;
600                     }
601                 }
602                 /* Lame fallback if zero padding does not work */
603                 if (delay < 0)
604                 {
605                     msg_Dbg (aout, "deferring start (%"PRId64" us)", -delay);
606                     msleep (-delay);
607                 }
608             }
609             else
610                 msg_Dbg (aout, "starting late (%"PRId64" us)", delay);
611         }
612         else
613             *drift = delay;
614     }
615
616     /* TODO: better overflow handling */
617     /* TODO: no period wake ups */
618
619     while (block->i_nb_samples > 0)
620     {
621         frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
622         if (frames >= 0)
623         {
624             size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
625             block->i_nb_samples -= frames;
626             block->p_buffer += bytes;
627             block->i_buffer -= bytes;
628             // pts, length
629         }
630         else  
631         {
632             int val = snd_pcm_recover (pcm, frames, 1);
633             if (val)
634             {
635                 msg_Err (aout, "cannot recover playback stream: %s",
636                          snd_strerror (val));
637                 DumpDeviceStatus (aout, pcm);
638                 break;
639             }
640             msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
641         }
642     }
643     block_Release (block);
644 }
645
646 /**
647  * Pauses/resumes the audio playback.
648  */
649 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
650 {
651     snd_pcm_t *pcm = aout->sys->pcm;
652
653     int val = snd_pcm_pause (pcm, pause);
654     if (unlikely(val))
655         PauseDummy (aout, pause, date);
656 }
657
658 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
659 {
660     snd_pcm_t *pcm = aout->sys->pcm;
661
662     /* Stupid device cannot pause. Discard samples. */
663     if (pause)
664         snd_pcm_drop (pcm);
665     else
666         snd_pcm_prepare (pcm);
667     (void) date;
668 }
669
670 /**
671  * Flushes/drains the audio playback buffer.
672  */
673 static void Flush (audio_output_t *aout, bool wait)
674 {
675     snd_pcm_t *pcm = aout->sys->pcm;
676
677     if (wait)
678         snd_pcm_drain (pcm);
679     else
680         snd_pcm_drop (pcm);
681     snd_pcm_prepare (pcm);
682 }
683
684
685 /**
686  * Releases the audio output.
687  */
688 static void Close (vlc_object_t *obj)
689 {
690     audio_output_t *aout = (audio_output_t *)obj;
691     aout_sys_t *sys = aout->sys;
692     snd_pcm_t *pcm = aout->sys->pcm;
693
694     var_DelCallback (obj, "audio-device", DeviceChanged, NULL);
695     var_Destroy (obj, "audio-device");
696
697     snd_pcm_drop (pcm);
698     snd_pcm_close (pcm);
699     free (sys);
700 }
701
702 /**
703  * Converts from VLC to ALSA order for 7.1.
704  * VLC has middle channels in position 2 and 3, ALSA in position 6 and 7.
705  */
706 static void Reorder71 (void *p, size_t n, unsigned size)
707 {
708     switch (size)
709     {
710         case 4:
711             for (uint64_t *ptr = p; n > 0; ptr += 4, n--)
712             {
713                 uint64_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
714                 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
715             }
716             break;
717         case 2:
718             for (uint32_t *ptr = p; n > 0; ptr += 4, n--)
719             {
720                 uint32_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
721                 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
722             }
723             break;
724
725         default:
726             for (uint16_t *ptr = p; n > 0; n--)
727             {
728                 uint16_t middle[size];
729                 memcpy (middle, ptr + size, size * 2);
730                 ptr += size;
731                 memcpy (ptr, ptr + size, size * 2);
732                 ptr += size;
733                 memcpy (ptr, ptr + size, size * 2);
734                 ptr += size;
735                 memcpy (ptr, middle, size * 2);
736                 ptr += size;
737             }
738             break;
739     }
740 }
741
742
743 /*****************************************************************************
744  * config variable callback
745  *****************************************************************************/
746 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
747                                vlc_value_t newval, vlc_value_t oldval, void *p_unused )
748 {
749     module_config_t *p_item;
750     (void)newval;
751     (void)oldval;
752     (void)p_unused;
753
754     p_item = config_FindConfig( p_this, psz_name );
755     if( !p_item ) return VLC_SUCCESS;
756
757     /* Clear-up the current list */
758     if( p_item->i_list )
759     {
760         int i;
761
762         /* Keep the first entrie */
763         for( i = 1; i < p_item->i_list; i++ )
764         {
765             free( (char *)p_item->ppsz_list[i] );
766             free( (char *)p_item->ppsz_list_text[i] );
767         }
768         /* TODO: Remove when no more needed */
769         p_item->ppsz_list[i] = NULL;
770         p_item->ppsz_list_text[i] = NULL;
771     }
772     p_item->i_list = 1;
773
774     GetDevices (p_this, p_item, "default");
775
776     return VLC_SUCCESS;
777 }
778
779
780 static void GetDevices (vlc_object_t *obj, module_config_t *item,
781                         const char *prefs_dev)
782 {
783     void **hints;
784     bool hinted_default = false;
785     bool hinted_prefs = !strcmp (prefs_dev, "default");
786
787     msg_Dbg(obj, "Available ALSA PCM devices:");
788
789     if (snd_device_name_hint(-1, "pcm", &hints) < 0)
790         return;
791
792     for (size_t i = 0; hints[i] != NULL; i++)
793     {
794         void *hint = hints[i];
795
796         char *name = snd_device_name_get_hint(hint, "NAME");
797         if (unlikely(name == NULL))
798             continue;
799
800         char *desc = snd_device_name_get_hint(hint, "DESC");
801         if (desc != NULL)
802             for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
803                  *lf = ' ';
804         msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
805
806         if (!strcmp (name, "default"))
807             hinted_default = true;
808         if (!strcmp (name, prefs_dev))
809             hinted_prefs = true;
810
811         if (item != NULL)
812         {
813             item->ppsz_list = xrealloc(item->ppsz_list,
814                                        (item->i_list + 2) * sizeof(char *));
815             item->ppsz_list_text = xrealloc(item->ppsz_list_text,
816                                           (item->i_list + 2) * sizeof(char *));
817             item->ppsz_list[item->i_list] = name;
818             if (desc == NULL)
819                 desc = strdup(name);
820             item->ppsz_list_text[item->i_list] = desc;
821             item->i_list++;
822         }
823         else
824         {
825             vlc_value_t val, text;
826
827             val.psz_string = name;
828             text.psz_string = desc;
829             var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
830             free(desc);
831             free(name);
832         }
833     }
834
835     snd_device_name_free_hint(hints);
836
837     if (item != NULL)
838     {
839         item->ppsz_list[item->i_list] = NULL;
840         item->ppsz_list_text[item->i_list] = NULL;
841     }
842     else
843     {
844         vlc_value_t val, text;
845
846         if (!hinted_default)
847         {
848             val.psz_string = (char *)"default";
849             text.psz_string = (char *)N_("Default");
850             var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
851         }
852
853         val.psz_string = (char *)prefs_dev;
854         if (!hinted_prefs)
855         {
856             text.psz_string = (char *)N_("VLC preferences");
857             var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
858         }
859         var_Change(obj, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
860     }
861 }