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