]> git.sesse.net Git - vlc/blob - modules/audio_output/alsa.c
aout: drop support for non-native float
[vlc] / modules / audio_output / alsa.c
1 /*****************************************************************************
2  * alsa.c : alsa plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2000-2010 VLC authors and VideoLAN
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 it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * 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     unsigned rate; /**< Sample rate */
47     uint8_t chans_table[AOUT_CHAN_MAX]; /**< Channels order table */
48     uint8_t chans_to_reorder; /**< Number of channels to reorder */
49     uint8_t bits; /**< Bits per sample per channel */
50
51     bool soft_mute;
52     float soft_gain;
53     char *device;
54 };
55
56 #include "volume.h"
57
58 #define A52_FRAME_NB 1536
59
60 static int Open (vlc_object_t *);
61 static void Close (vlc_object_t *);
62 static int EnumDevices (vlc_object_t *, char const *, char ***, char ***);
63
64 #define AUDIO_DEV_TEXT N_("Audio output device")
65 #define AUDIO_DEV_LONGTEXT N_("Audio output device (using ALSA syntax).")
66
67 #define AUDIO_CHAN_TEXT N_("Audio output channels")
68 #define AUDIO_CHAN_LONGTEXT N_("Channels available for audio output. " \
69     "If the input has more channels than the output, it will be down-mixed. " \
70     "This parameter is ignored when digital pass-through is active.")
71 static const int channels[] = {
72     AOUT_CHAN_CENTER, AOUT_CHANS_STEREO, AOUT_CHANS_4_0, AOUT_CHANS_4_1,
73     AOUT_CHANS_5_0, AOUT_CHANS_5_1, AOUT_CHANS_7_1,
74 };
75 static const char *const channels_text[] = {
76     N_("Mono"), N_("Stereo"), N_("Surround 4.0"), N_("Surround 4.1"),
77     N_("Surround 5.0"), N_("Surround 5.1"), N_("Surround 7.1"),
78 };
79
80 vlc_module_begin ()
81     set_shortname( "ALSA" )
82     set_description( N_("ALSA audio output") )
83     set_category( CAT_AUDIO )
84     set_subcategory( SUBCAT_AUDIO_AOUT )
85     add_string ("alsa-audio-device", "default",
86                 AUDIO_DEV_TEXT, AUDIO_DEV_LONGTEXT, false)
87         change_string_cb (EnumDevices)
88     add_integer ("alsa-audio-channels", AOUT_CHANS_FRONT,
89                  AUDIO_CHAN_TEXT, AUDIO_CHAN_LONGTEXT, false)
90         change_integer_list (channels, channels_text)
91     add_sw_gain ()
92     set_capability( "audio output", 150 )
93     set_callbacks( Open, Close )
94 vlc_module_end ()
95
96
97 /** Helper for ALSA -> VLC debugging output */
98 static void Dump (vlc_object_t *obj, const char *msg,
99                   int (*cb)(void *, snd_output_t *), void *p)
100 {
101     snd_output_t *output;
102     char *str;
103
104     if (unlikely(snd_output_buffer_open (&output)))
105         return;
106
107     int val = cb (p, output);
108     if (val)
109     {
110         msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
111         return;
112     }
113
114     size_t len = snd_output_buffer_string (output, &str);
115     if (len > 0 && str[len - 1])
116         len--; /* strip trailing newline */
117     msg_Dbg (obj, "%s%.*s", msg, (int)len, str);
118     snd_output_close (output);
119 }
120 #define Dump(o, m, cb, p) \
121         Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
122
123 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
124 {
125     snd_pcm_info_t *info;
126
127     Dump (obj, " ", snd_pcm_dump, pcm);
128     snd_pcm_info_alloca (&info);
129     if (snd_pcm_info (pcm, info) == 0)
130     {
131         msg_Dbg (obj, " device name   : %s", snd_pcm_info_get_name (info));
132         msg_Dbg (obj, " device ID     : %s", snd_pcm_info_get_id (info));
133         msg_Dbg (obj, " subdevice name: %s",
134                 snd_pcm_info_get_subdevice_name (info));
135     }
136 }
137
138 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
139 {
140     snd_pcm_status_t *status;
141
142     snd_pcm_status_alloca (&status);
143     snd_pcm_status (pcm, status);
144     Dump (obj, "current status:\n", snd_pcm_status_dump, status);
145 }
146 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
147
148 static unsigned SetupChannelsUnknown (vlc_object_t *obj,
149                                       uint16_t *restrict mask)
150 {
151     uint16_t map = var_InheritInteger (obj, "alsa-audio-channels");
152     uint16_t chans = *mask & map;
153
154     if (unlikely(chans == 0)) /* WTH? */
155         chans = AOUT_CHANS_STEREO;
156
157     if (popcount (chans) < popcount (*mask))
158         msg_Dbg (obj, "downmixing from %u to %u channels",
159                  popcount (*mask), popcount (chans));
160     else
161         msg_Dbg (obj, "keeping %u channels", popcount (chans));
162     *mask = chans;
163     return 0;
164 }
165
166 #if (SND_LIB_VERSION >= 0x01001B)
167 static const uint16_t vlc_chans[] = {
168     [SND_CHMAP_MONO] = AOUT_CHAN_CENTER,
169     [SND_CHMAP_FL]   = AOUT_CHAN_LEFT,
170     [SND_CHMAP_FR]   = AOUT_CHAN_RIGHT,
171     [SND_CHMAP_RL]   = AOUT_CHAN_REARLEFT,
172     [SND_CHMAP_RR]   = AOUT_CHAN_REARRIGHT,
173     [SND_CHMAP_FC]   = AOUT_CHAN_CENTER,
174     [SND_CHMAP_LFE]  = AOUT_CHAN_LFE,
175     [SND_CHMAP_SL]   = AOUT_CHAN_MIDDLELEFT,
176     [SND_CHMAP_SR]   = AOUT_CHAN_MIDDLERIGHT,
177     [SND_CHMAP_RC]   = AOUT_CHAN_REARCENTER,
178 };
179
180 static int Map2Mask (vlc_object_t *obj, const snd_pcm_chmap_t *restrict map)
181 {
182     uint16_t mask = 0;
183
184     for (unsigned i = 0; i < map->channels; i++)
185     {
186         const unsigned pos = map->pos[i];
187         uint_fast16_t vlc_chan = 0;
188
189         if (pos < sizeof (vlc_chans) / sizeof (vlc_chans[0]))
190             vlc_chan = vlc_chans[pos];
191         if (vlc_chan == 0)
192         {
193             msg_Dbg (obj, " %s channel %u position %u", "unsupported", i, pos);
194             return -1;
195         }
196         if (mask & vlc_chan)
197         {
198             msg_Dbg (obj, " %s channel %u position %u", "duplicate", i, pos);
199             return -1;
200         }
201         mask |= vlc_chan;
202     }
203     return mask;
204 }
205
206 /**
207  * Compares a fixed ALSA channels map with the VLC channels order.
208  */
209 static unsigned SetupChannelsFixed(const snd_pcm_chmap_t *restrict map,
210                                 uint16_t *restrict mask, uint8_t *restrict tab)
211 {
212     uint32_t chans_out[AOUT_CHAN_MAX];
213
214     for (unsigned i = 0; i < map->channels; i++)
215     {
216         uint_fast16_t vlc_chan = vlc_chans[map->pos[i]];
217
218         chans_out[i] = vlc_chan;
219         *mask |= vlc_chan;
220     }
221
222     return aout_CheckChannelReorder(NULL, chans_out, *mask, tab);
223 }
224
225 /**
226  * Negotiate channels mapping.
227  */
228 static unsigned SetupChannels (vlc_object_t *obj, snd_pcm_t *pcm,
229                                 uint16_t *restrict mask, uint8_t *restrict tab)
230 {
231     snd_pcm_chmap_query_t **maps = snd_pcm_query_chmaps (pcm);
232     if (tab == NULL)
233     {   /* Fallback to manual configuration */
234         msg_Dbg(obj, "channels map not provided");
235         return SetupChannelsUnknown (obj, mask);
236     }
237
238     /* Find most appropriate available channels map */
239     unsigned best_offset;
240     unsigned best_score = 0;
241
242     for (snd_pcm_chmap_query_t *const *p = maps; *p != NULL; p++)
243     {
244         snd_pcm_chmap_query_t *map = *p;
245
246         switch (map->type)
247         {
248             case SND_CHMAP_TYPE_FIXED:
249             case SND_CHMAP_TYPE_PAIRED:
250             case SND_CHMAP_TYPE_VAR:
251                 break;
252             default:
253                 msg_Err (obj, "unknown channels map type %u", map->type);
254                 continue;
255         }
256
257         int chans = Map2Mask (obj, &map->map);
258         if (chans == -1)
259             continue;
260
261         unsigned score = popcount (chans & *mask);
262         if (score > best_score)
263         {
264             best_offset = p - maps;
265             best_score = score;
266         }
267     }
268
269     if (best_score == 0)
270     {
271         msg_Err (obj, "cannot find supported channels map");
272         snd_pcm_free_chmaps (maps);
273         return SetupChannelsUnknown (obj, mask);
274     }
275
276     const snd_pcm_chmap_t *map = &maps[best_offset]->map;
277     msg_Dbg (obj, "using channels map %u, type %u, %u channel(s)", best_offset,
278              maps[best_offset]->type, best_score);
279
280     /* Setup channels map */
281     unsigned to_reorder = SetupChannelsFixed(map, mask, tab);
282
283     /* TODO: avoid reordering for PAIRED and VAR types */
284     //snd_pcm_set_chmap (pcm, ...)
285
286     snd_pcm_free_chmaps (maps);
287     return to_reorder;
288 }
289 #else /* (SND_LIB_VERSION < 0x01001B) */
290 # define SetupChannels(obj, pcm, mask, tab) \
291          SetupChannelsUnknown(obj, mask)
292 #endif
293
294 static int TimeGet (audio_output_t *aout, mtime_t *);
295 static void Play (audio_output_t *, block_t *);
296 static void Pause (audio_output_t *, bool, mtime_t);
297 static void PauseDummy (audio_output_t *, bool, mtime_t);
298 static void Flush (audio_output_t *, bool);
299
300 /** Initializes an ALSA playback stream */
301 static int Start (audio_output_t *aout, audio_sample_format_t *restrict fmt)
302 {
303     aout_sys_t *sys = aout->sys;
304     snd_pcm_format_t pcm_format; /* ALSA sample format */
305     bool spdif = false;
306
307     switch (fmt->i_format)
308     {
309         case VLC_CODEC_FL64:
310             pcm_format = SND_PCM_FORMAT_FLOAT64;
311             break;
312         case VLC_CODEC_FL32:
313             pcm_format = SND_PCM_FORMAT_FLOAT;
314             break;
315         case VLC_CODEC_S32N:
316             pcm_format = SND_PCM_FORMAT_S32;
317             break;
318         case VLC_CODEC_S24B:
319             pcm_format = SND_PCM_FORMAT_S24_3BE;
320             break;
321         case VLC_CODEC_S24L:
322             pcm_format = SND_PCM_FORMAT_S24_3LE;
323             break;
324         case VLC_CODEC_U24B:
325             pcm_format = SND_PCM_FORMAT_U24_3BE;
326             break;
327         case VLC_CODEC_U24L:
328             pcm_format = SND_PCM_FORMAT_U24_3LE;
329             break;
330         case VLC_CODEC_S16N:
331             pcm_format = SND_PCM_FORMAT_S16;
332             break;
333         case VLC_CODEC_U8:
334             pcm_format = SND_PCM_FORMAT_U8;
335             break;
336         default:
337             if (AOUT_FMT_SPDIF(fmt))
338                 spdif = var_InheritBool (aout, "spdif");
339             if (spdif)
340             {
341                 fmt->i_format = VLC_CODEC_SPDIFL;
342                 pcm_format = SND_PCM_FORMAT_S16;
343             }
344             else
345             if (HAVE_FPU)
346             {
347                 fmt->i_format = VLC_CODEC_FL32;
348                 pcm_format = SND_PCM_FORMAT_FLOAT;
349             }
350             else
351             {
352                 fmt->i_format = VLC_CODEC_S16N;
353                 pcm_format = SND_PCM_FORMAT_S16;
354             }
355     }
356
357     const char *device = sys->device;
358     char *devbuf = NULL;
359     /* Choose the IEC device for S/PDIF output */
360     if (spdif && !strcmp (device, "default"))
361     {
362         unsigned aes3;
363
364         switch (fmt->i_rate)
365         {
366 #define FS(freq) \
367             case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
368             FS( 44100) /* def. */ FS( 48000) FS( 32000)
369             FS( 22050)            FS( 24000)
370             FS( 88200) FS(768000) FS( 96000)
371             FS(176400)            FS(192000)
372 #undef FS
373             default:
374                 aes3 = IEC958_AES3_CON_FS_NOTID;
375                 break;
376         }
377
378         if (asprintf (&devbuf,
379                       "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
380                       IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
381                       IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
382                       0, aes3) == -1)
383             return VLC_ENOMEM;
384         device = devbuf;
385     }
386
387     /* Open the device */
388     snd_pcm_t *pcm;
389     /* VLC always has a resampler. No need for ALSA's. */
390     const int mode = SND_PCM_NO_AUTO_RESAMPLE;
391
392     int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
393     free (devbuf);
394     if (val != 0)
395     {
396         msg_Err (aout, "cannot open ALSA device \"%s\": %s", sys->device,
397                  snd_strerror (val));
398         dialog_Fatal (aout, _("Audio output failed"),
399                       _("The audio device \"%s\" could not be used:\n%s."),
400                       sys->device, snd_strerror (val));
401         return VLC_EGENERIC;
402     }
403     sys->pcm = pcm;
404
405     /* Print some potentially useful debug */
406     msg_Dbg (aout, "using ALSA device: %s", sys->device);
407     DumpDevice (VLC_OBJECT(aout), pcm);
408
409     /* Get Initial hardware parameters */
410     snd_pcm_hw_params_t *hw;
411     unsigned param;
412
413     snd_pcm_hw_params_alloca (&hw);
414     snd_pcm_hw_params_any (pcm, hw);
415     Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
416
417     val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
418     if (val)
419     {
420         msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
421         goto error;
422     }
423
424     val = snd_pcm_hw_params_set_access (pcm, hw,
425                                         SND_PCM_ACCESS_RW_INTERLEAVED);
426     if (val)
427     {
428         msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
429         goto error;
430     }
431
432     /* Set sample format */
433     if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
434         ;
435     else
436     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
437     {
438         fmt->i_format = VLC_CODEC_FL32;
439         pcm_format = SND_PCM_FORMAT_FLOAT;
440     }
441     else
442     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
443     {
444         fmt->i_format = VLC_CODEC_S32N;
445         pcm_format = SND_PCM_FORMAT_S32;
446     }
447     else
448     if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
449     {
450         fmt->i_format = VLC_CODEC_S16N;
451         pcm_format = SND_PCM_FORMAT_S16;
452     }
453     else
454     {
455         msg_Err (aout, "no supported sample format");
456         goto error;
457     }
458
459     val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
460     if (val)
461     {
462         msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
463         goto error;
464     }
465
466     /* Set channels count */
467     unsigned channels;
468     if (!spdif)
469     {
470         sys->chans_to_reorder = SetupChannels (VLC_OBJECT(aout), pcm,
471                                   &fmt->i_physical_channels, sys->chans_table);
472         channels = popcount (fmt->i_physical_channels);
473     }
474     else
475         channels = 2;
476     fmt->i_original_channels = fmt->i_physical_channels;
477
478     /* By default, ALSA plug will pad missing channels with zeroes, which is
479      * usually fine. However, it will also discard extraneous channels, which
480      * is not acceptable. Thus the user must configure the physically
481      * available channels, and VLC will downmix if needed. */
482     val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
483     if (val)
484     {
485         msg_Err (aout, "cannot set %u channels: %s", channels,
486                  snd_strerror (val));
487         goto error;
488     }
489
490     /* Set sample rate */
491     val = snd_pcm_hw_params_set_rate_near (pcm, hw, &fmt->i_rate, NULL);
492     if (val)
493     {
494         msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
495         goto error;
496     }
497     sys->rate = fmt->i_rate;
498
499     /* Set buffer size */
500     param = AOUT_MAX_ADVANCE_TIME;
501     val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, &param, NULL);
502     if (val)
503     {
504         msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
505         goto error;
506     }
507 #if 0
508     val = snd_pcm_hw_params_get_buffer_time (hw, &param, NULL);
509     if (val)
510     {
511         msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
512         param = AOUT_MIN_PREPARE_TIME;
513     }
514     else
515         param /= 2;
516 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
517     param = AOUT_MIN_PREPARE_TIME;
518 #endif
519     val = snd_pcm_hw_params_set_period_time_near (pcm, hw, &param, NULL);
520     if (val)
521     {
522         msg_Err (aout, "cannot set period: %s", snd_strerror (val));
523         goto error;
524     }
525
526     /* Commit hardware parameters */
527     val = snd_pcm_hw_params (pcm, hw);
528     if (val < 0)
529     {
530         msg_Err (aout, "cannot commit hardware parameters: %s",
531                  snd_strerror (val));
532         goto error;
533     }
534     Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
535
536     /* Get Initial software parameters */
537     snd_pcm_sw_params_t *sw;
538
539     snd_pcm_sw_params_alloca (&sw);
540     snd_pcm_sw_params_current (pcm, sw);
541     Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
542
543     /* START REVISIT */
544     //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
545     // FIXME: useful?
546     val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
547     if( val < 0 )
548     {
549         msg_Err( aout, "unable to set start threshold (%s)",
550                  snd_strerror( val ) );
551         goto error;
552     }
553     /* END REVISIT */
554
555     /* Commit software parameters. */
556     val = snd_pcm_sw_params (pcm, sw);
557     if (val)
558     {
559         msg_Err (aout, "cannot commit software parameters: %s",
560                  snd_strerror (val));
561         goto error;
562     }
563     Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
564
565     val = snd_pcm_prepare (pcm);
566     if (val)
567     {
568         msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
569         goto error;
570     }
571
572     /* Setup audio_output_t */
573     if (spdif)
574     {
575         fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
576         fmt->i_frame_length = A52_FRAME_NB;
577     }
578     else
579     {
580         aout_FormatPrepare (fmt);
581         sys->bits = fmt->i_bitspersample;
582     }
583
584     aout->time_get = TimeGet;
585     aout->play = Play;
586     if (snd_pcm_hw_params_can_pause (hw))
587         aout->pause = Pause;
588     else
589     {
590         aout->pause = PauseDummy;
591         msg_Warn (aout, "device cannot be paused");
592     }
593     aout->flush = Flush;
594     aout_SoftVolumeStart (aout);
595     return 0;
596
597 error:
598     snd_pcm_close (pcm);
599     return VLC_EGENERIC;
600 }
601
602 static int TimeGet (audio_output_t *aout, mtime_t *restrict delay)
603 {
604     aout_sys_t *sys = aout->sys;
605     snd_pcm_sframes_t frames;
606
607     int val = snd_pcm_delay (sys->pcm, &frames);
608     if (val)
609     {
610         msg_Err (aout, "cannot estimate delay: %s", snd_strerror (val));
611         return -1;
612     }
613     *delay = frames * CLOCK_FREQ / sys->rate;
614     return 0;
615 }
616
617 /**
618  * Queues one audio buffer to the hardware.
619  */
620 static void Play (audio_output_t *aout, block_t *block)
621 {
622     aout_sys_t *sys = aout->sys;
623
624     if (sys->chans_to_reorder != 0)
625         aout_ChannelReorder(block->p_buffer, block->i_buffer,
626                            sys->chans_to_reorder, sys->chans_table, sys->bits);
627
628     snd_pcm_t *pcm = sys->pcm;
629
630     /* TODO: better overflow handling */
631     /* TODO: no period wake ups */
632
633     while (block->i_nb_samples > 0)
634     {
635         snd_pcm_sframes_t frames;
636
637         frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
638         if (frames >= 0)
639         {
640             size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
641             block->i_nb_samples -= frames;
642             block->p_buffer += bytes;
643             block->i_buffer -= bytes;
644             // pts, length
645         }
646         else  
647         {
648             int val = snd_pcm_recover (pcm, frames, 1);
649             if (val)
650             {
651                 msg_Err (aout, "cannot recover playback stream: %s",
652                          snd_strerror (val));
653                 DumpDeviceStatus (aout, pcm);
654                 break;
655             }
656             msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
657         }
658     }
659     block_Release (block);
660 }
661
662 /**
663  * Pauses/resumes the audio playback.
664  */
665 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
666 {
667     snd_pcm_t *pcm = aout->sys->pcm;
668
669     int val = snd_pcm_pause (pcm, pause);
670     if (unlikely(val))
671         PauseDummy (aout, pause, date);
672 }
673
674 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
675 {
676     snd_pcm_t *pcm = aout->sys->pcm;
677
678     /* Stupid device cannot pause. Discard samples. */
679     if (pause)
680         snd_pcm_drop (pcm);
681     else
682         snd_pcm_prepare (pcm);
683     (void) date;
684 }
685
686 /**
687  * Flushes/drains the audio playback buffer.
688  */
689 static void Flush (audio_output_t *aout, bool wait)
690 {
691     snd_pcm_t *pcm = aout->sys->pcm;
692
693     if (wait)
694         snd_pcm_drain (pcm);
695     else
696         snd_pcm_drop (pcm);
697     snd_pcm_prepare (pcm);
698 }
699
700
701 /**
702  * Releases the audio output.
703  */
704 static void Stop (audio_output_t *aout)
705 {
706     aout_sys_t *sys = aout->sys;
707     snd_pcm_t *pcm = sys->pcm;
708
709     snd_pcm_drop (pcm);
710     snd_pcm_close (pcm);
711 }
712
713 /**
714  * Enumerates ALSA output devices.
715  */
716 static int EnumDevices(vlc_object_t *obj, char const *varname,
717                        char ***restrict idp, char ***restrict namep)
718 {
719     void **hints;
720
721     msg_Dbg (obj, "Available ALSA PCM devices:");
722     if (snd_device_name_hint(-1, "pcm", &hints) < 0)
723         return -1;
724
725     char **ids = NULL, **names = NULL;
726     unsigned n = 0;
727
728     for (size_t i = 0; hints[i] != NULL; i++)
729     {
730         void *hint = hints[i];
731
732         char *name = snd_device_name_get_hint(hint, "NAME");
733         if (unlikely(name == NULL))
734             continue;
735
736         char *desc = snd_device_name_get_hint(hint, "DESC");
737         if (desc != NULL)
738             for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
739                  *lf = ' ';
740         msg_Dbg (obj, "%s (%s)", (desc != NULL) ? desc : name, name);
741
742         ids = xrealloc (ids, (n + 1) * sizeof (*ids));
743         names = xrealloc (names, (n + 1) * sizeof (*names));
744         ids[n] = name;
745         names[n] = desc;
746         n++;
747     }
748
749     snd_device_name_free_hint(hints);
750     *idp = ids;
751     *namep = names;
752     (void) varname;
753     return n;
754 }
755
756 static int DevicesEnum (audio_output_t *aout, char ***idp, char ***namep)
757 {
758     return EnumDevices (VLC_OBJECT(aout), NULL, idp, namep);
759 }
760
761 static int DeviceSelect (audio_output_t *aout, const char *id)
762 {
763     aout_sys_t *sys = aout->sys;
764
765     char *device = strdup (id ? id : "default");
766     if (unlikely(device == NULL))
767         return -1;
768
769     free (sys->device);
770     sys->device = device;
771     aout_DeviceReport (aout, device);
772     aout_RestartRequest (aout, AOUT_RESTART_OUTPUT);
773     return 0;
774 }
775
776 static int Open(vlc_object_t *obj)
777 {
778     audio_output_t *aout = (audio_output_t *)obj;
779     aout_sys_t *sys = malloc (sizeof (*sys));
780
781     if (unlikely(sys == NULL))
782         return VLC_ENOMEM;
783     sys->device = var_InheritString (aout, "alsa-audio-device");
784     if (unlikely(sys->device == NULL))
785         goto error;
786
787     aout->sys = sys;
788     aout->start = Start;
789     aout->stop = Stop;
790     aout_SoftVolumeInit (aout);
791     aout->device_enum = DevicesEnum;
792     aout->device_select = DeviceSelect;
793     aout_DeviceReport (aout, sys->device);
794     return VLC_SUCCESS;
795 error:
796     free (sys);
797     return VLC_ENOMEM;
798 }
799
800 static void Close(vlc_object_t *obj)
801 {
802     audio_output_t *aout = (audio_output_t *)obj;
803     aout_sys_t *sys = aout->sys;
804
805     free (sys->device);
806     free (sys);
807 }