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
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
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.
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.
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 *****************************************************************************/
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_dialog.h>
39 #include <alsa/asoundlib.h>
40 #include <alsa/version.h>
42 /** Private data for an ALSA PCM playback stream */
46 void (*reorder) (void *, size_t, unsigned);
49 audio_sample_format_t format;
54 #define A52_FRAME_NB 1536
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 *);
61 #define AUDIO_DEV_TEXT N_("Audio output device")
62 #define AUDIO_DEV_LONGTEXT N_("Audio output device (using ALSA syntax).")
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,
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"),
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)
89 set_capability( "audio output", 150 )
90 set_callbacks( Open, Close )
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)
101 if (unlikely(snd_output_buffer_open (&output)))
104 int val = cb (p, output);
107 msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
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);
117 #define Dump(o, m, cb, p) \
118 Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
120 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
122 snd_pcm_info_t *info;
124 Dump (obj, " ", snd_pcm_dump, pcm);
125 snd_pcm_info_alloca (&info);
126 if (snd_pcm_info (pcm, info) == 0)
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));
135 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
137 snd_pcm_status_t *status;
139 snd_pcm_status_alloca (&status);
140 snd_pcm_status (pcm, status);
141 Dump (obj, "current status:\n", snd_pcm_status_dump, status);
143 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
145 static int DeviceChanged (vlc_object_t *obj, const char *varname,
146 vlc_value_t prev, vlc_value_t cur, void *data)
148 aout_ChannelsRestart (obj, varname, prev, cur, data);
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);
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);
163 /** Initializes an ALSA playback stream */
164 static int Start (audio_output_t *aout, audio_sample_format_t *restrict fmt)
166 aout_sys_t *sys = aout->sys;
168 /* Get device name */
169 char *device = var_InheritString (aout, "alsa-audio-device");
170 if (unlikely(device == NULL))
173 snd_pcm_format_t pcm_format; /* ALSA sample format */
174 vlc_fourcc_t fourcc = fmt->i_format;
180 pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
183 pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
186 pcm_format = SND_PCM_FORMAT_FLOAT_BE;
189 pcm_format = SND_PCM_FORMAT_FLOAT_LE;
192 pcm_format = SND_PCM_FORMAT_S32_BE;
195 pcm_format = SND_PCM_FORMAT_S32_LE;
198 pcm_format = SND_PCM_FORMAT_S24_3BE;
201 pcm_format = SND_PCM_FORMAT_S24_3LE;
204 pcm_format = SND_PCM_FORMAT_U24_3BE;
207 pcm_format = SND_PCM_FORMAT_U24_3LE;
210 pcm_format = SND_PCM_FORMAT_S16_BE;
213 pcm_format = SND_PCM_FORMAT_S16_LE;
216 pcm_format = SND_PCM_FORMAT_U16_BE;
219 pcm_format = SND_PCM_FORMAT_U16_LE;
222 pcm_format = SND_PCM_FORMAT_S8;
225 pcm_format = SND_PCM_FORMAT_U8;
228 if (AOUT_FMT_SPDIF(fmt))
229 spdif = var_InheritBool (aout, "spdif");
232 fourcc = VLC_CODEC_SPDIFL;
233 pcm_format = SND_PCM_FORMAT_S16;
238 fourcc = VLC_CODEC_FL32;
239 pcm_format = SND_PCM_FORMAT_FLOAT;
243 fourcc = VLC_CODEC_S16N;
244 pcm_format = SND_PCM_FORMAT_S16;
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;
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);
260 msg_Dbg (aout, "keeping %u channels", channels);
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"))
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)
279 aes3 = IEC958_AES3_CON_FS_NOTID;
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,
292 /* Open the device */
294 /* VLC always has a resampler. No need for ALSA's. */
295 const int mode = SND_PCM_NO_AUTO_RESAMPLE;
297 int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
300 msg_Err (aout, "cannot open ALSA device \"%s\": %s", device,
302 dialog_Fatal (aout, _("Audio output failed"),
303 _("The audio device \"%s\" could not be used:\n%s."),
304 device, snd_strerror (val));
310 /* Print some potentially useful debug */
311 msg_Dbg (aout, "using ALSA device: %s", device);
312 DumpDevice (VLC_OBJECT(aout), pcm);
314 /* Get Initial hardware parameters */
315 snd_pcm_hw_params_t *hw;
318 snd_pcm_hw_params_alloca (&hw);
319 snd_pcm_hw_params_any (pcm, hw);
320 Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
322 val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
325 msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
329 val = snd_pcm_hw_params_set_access (pcm, hw,
330 SND_PCM_ACCESS_RW_INTERLEAVED);
333 msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
337 /* Set sample format */
338 if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
341 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
343 fourcc = VLC_CODEC_FL32;
344 pcm_format = SND_PCM_FORMAT_FLOAT;
347 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
349 fourcc = VLC_CODEC_S32N;
350 pcm_format = SND_PCM_FORMAT_S32;
353 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
355 fourcc = VLC_CODEC_S16N;
356 pcm_format = SND_PCM_FORMAT_S16;
360 msg_Err (aout, "no supported sample format");
364 val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
367 msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
371 /* Set channels count */
372 /* By default, ALSA plug will pad missing channels with zeroes, which is
373 * usually fine. However, it will also discard extraneous channels, which
374 * is not acceptable. Thus the user must configure the physically
375 * available channels, and VLC will downmix if needed. */
376 val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
379 msg_Err (aout, "cannot set %u channels: %s", channels,
384 /* Set sample rate */
385 unsigned rate = fmt->i_rate;
386 val = snd_pcm_hw_params_set_rate_near (pcm, hw, &rate, NULL);
389 msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
392 if (fmt->i_rate != rate)
393 msg_Dbg (aout, "resampling from %d Hz to %d Hz", fmt->i_rate, rate);
395 /* Set buffer size */
396 param = AOUT_MAX_ADVANCE_TIME;
397 val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, ¶m, NULL);
400 msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
404 val = snd_pcm_hw_params_get_buffer_time (hw, ¶m, NULL);
407 msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
408 param = AOUT_MIN_PREPARE_TIME;
412 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
413 param = AOUT_MIN_PREPARE_TIME;
415 val = snd_pcm_hw_params_set_period_time_near (pcm, hw, ¶m, NULL);
418 msg_Err (aout, "cannot set period: %s", snd_strerror (val));
422 /* Commit hardware parameters */
423 val = snd_pcm_hw_params (pcm, hw);
426 msg_Err (aout, "cannot commit hardware parameters: %s",
430 Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
432 /* Get Initial software parameters */
433 snd_pcm_sw_params_t *sw;
435 snd_pcm_sw_params_alloca (&sw);
436 snd_pcm_sw_params_current (pcm, sw);
437 Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
440 //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
442 val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
445 msg_Err( aout, "unable to set start threshold (%s)",
446 snd_strerror( val ) );
451 /* Commit software parameters. */
452 val = snd_pcm_sw_params (pcm, sw);
455 msg_Err (aout, "cannot commit software parameters: %s",
459 Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
461 val = snd_pcm_prepare (pcm);
464 msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
468 /* Setup audio_output_t */
469 fmt->i_format = fourcc;
474 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
475 fmt->i_frame_length = A52_FRAME_NB;
479 fmt->i_original_channels =
480 fmt->i_physical_channels = map;
481 switch (popcount (map))
484 sys->reorder = Reorder71;
490 aout->time_get = TimeGet;
492 if (snd_pcm_hw_params_can_pause (hw))
496 aout->pause = PauseDummy;
497 msg_Warn (aout, "device cannot be paused");
501 /* Setup audio-device choices */
505 var_Create (aout, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
506 text.psz_string = _("Audio Device");
507 var_Change (aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
509 GetDevices (VLC_OBJECT(aout), device);
511 var_AddCallback (aout, "audio-device", DeviceChanged, NULL);
514 aout_SoftVolumeStart (aout);
523 static int TimeGet (audio_output_t *aout, mtime_t *restrict pts)
525 aout_sys_t *sys = aout->sys;
526 snd_pcm_sframes_t frames;
528 int val = snd_pcm_delay (sys->pcm, &frames);
531 msg_Err (aout, "cannot estimate delay: %s", snd_strerror (val));
534 *pts = mdate () + (frames * CLOCK_FREQ / sys->format.i_rate);
539 * Queues one audio buffer to the hardware.
541 static void Play (audio_output_t *aout, block_t *block)
543 aout_sys_t *sys = aout->sys;
545 if (sys->reorder != NULL)
546 sys->reorder (block->p_buffer, block->i_nb_samples,
547 sys->format.i_bitspersample / 8);
549 snd_pcm_t *pcm = sys->pcm;
551 /* TODO: better overflow handling */
552 /* TODO: no period wake ups */
554 while (block->i_nb_samples > 0)
556 snd_pcm_sframes_t frames;
558 frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
561 size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
562 block->i_nb_samples -= frames;
563 block->p_buffer += bytes;
564 block->i_buffer -= bytes;
569 int val = snd_pcm_recover (pcm, frames, 1);
572 msg_Err (aout, "cannot recover playback stream: %s",
574 DumpDeviceStatus (aout, pcm);
577 msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
580 block_Release (block);
584 * Pauses/resumes the audio playback.
586 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
588 snd_pcm_t *pcm = aout->sys->pcm;
590 int val = snd_pcm_pause (pcm, pause);
592 PauseDummy (aout, pause, date);
595 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
597 snd_pcm_t *pcm = aout->sys->pcm;
599 /* Stupid device cannot pause. Discard samples. */
603 snd_pcm_prepare (pcm);
608 * Flushes/drains the audio playback buffer.
610 static void Flush (audio_output_t *aout, bool wait)
612 snd_pcm_t *pcm = aout->sys->pcm;
618 snd_pcm_prepare (pcm);
623 * Releases the audio output.
625 static void Stop (audio_output_t *aout)
627 aout_sys_t *sys = aout->sys;
628 snd_pcm_t *pcm = sys->pcm;
630 var_DelCallback (aout, "audio-device", DeviceChanged, NULL);
631 var_Destroy (aout, "audio-device");
638 * Converts from VLC to ALSA order for 7.1.
639 * VLC has middle channels in position 2 and 3, ALSA in position 6 and 7.
641 static void Reorder71 (void *p, size_t n, unsigned size)
646 for (uint64_t *ptr = p; n > 0; ptr += 4, n--)
648 uint64_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
649 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
653 for (uint32_t *ptr = p; n > 0; ptr += 4, n--)
655 uint32_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
656 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
661 for (uint16_t *ptr = p; n > 0; n--)
663 uint16_t middle[size];
664 memcpy (middle, ptr + size, size * 2);
666 memcpy (ptr, ptr + size, size * 2);
668 memcpy (ptr, ptr + size, size * 2);
670 memcpy (ptr, middle, size * 2);
679 * Enumerates ALSA output devices.
681 static int EnumDevices(vlc_object_t *obj, char const *varname,
682 char ***restrict vp, char ***restrict tp)
686 char **names = xmalloc(sizeof (*names));
687 char **descs = xmalloc(sizeof (*names));
688 names[0] = strdup ("default");
689 descs[0] = strdup (N_("Default"));
691 if (unlikely(names[0] == NULL || descs[0] == NULL))
695 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
698 for (size_t i = 0; hints[i] != NULL; i++)
700 void *hint = hints[i];
702 char *name = snd_device_name_get_hint(hint, "NAME");
703 if (unlikely(name == NULL))
706 char *desc = snd_device_name_get_hint(hint, "DESC");
713 names = xrealloc (names, (n + 1) * sizeof (*names));
714 descs = xrealloc (descs, (n + 1) * sizeof (*descs));
719 snd_device_name_free_hint(hints);
721 (void) obj; (void) varname;
728 static void GetDevices(vlc_object_t *obj, const char *prefs_dev)
732 msg_Dbg(obj, "Available ALSA PCM devices:");
733 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
736 vlc_value_t val, text;
737 bool hinted_default = false;
738 bool hinted_prefs = !strcmp (prefs_dev, "default");
740 for (size_t i = 0; hints[i] != NULL; i++)
742 void *hint = hints[i];
744 char *name = snd_device_name_get_hint(hint, "NAME");
745 if (unlikely(name == NULL))
748 char *desc = snd_device_name_get_hint(hint, "DESC");
750 for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
752 msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
754 if (!strcmp (name, "default"))
755 hinted_default = true;
756 if (!strcmp (name, prefs_dev))
759 val.psz_string = name;
760 text.psz_string = desc;
761 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
766 snd_device_name_free_hint(hints);
770 val.psz_string = (char *)"default";
771 text.psz_string = (char *)N_("Default");
772 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
775 val.psz_string = (char *)prefs_dev;
778 text.psz_string = (char *)N_("VLC preferences");
779 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
781 var_Change(obj, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
784 static int Open(vlc_object_t *obj)
786 audio_output_t *aout = (audio_output_t *)obj;
787 aout_sys_t *sys = malloc (sizeof (*sys));
789 if (unlikely(sys == NULL))
794 aout_SoftVolumeInit (aout);
798 static void Close(vlc_object_t *obj)
800 audio_output_t *aout = (audio_output_t *)obj;
801 aout_sys_t *sys = aout->sys;