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