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