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