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