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
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
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.
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.
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 *****************************************************************************/
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 void Play (audio_output_t *, block_t *, mtime_t *);
157 static void Pause (audio_output_t *, bool, mtime_t);
158 static void PauseDummy (audio_output_t *, bool, mtime_t);
159 static void Flush (audio_output_t *, bool);
160 static void Reorder71 (void *, size_t, unsigned);
162 /** Initializes an ALSA playback stream */
163 static int Start (audio_output_t *aout, audio_sample_format_t *restrict fmt)
165 aout_sys_t *sys = aout->sys;
167 /* Get device name */
168 char *device = var_InheritString (aout, "alsa-audio-device");
169 if (unlikely(device == NULL))
172 snd_pcm_format_t pcm_format; /* ALSA sample format */
173 vlc_fourcc_t fourcc = fmt->i_format;
179 pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
182 pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
185 pcm_format = SND_PCM_FORMAT_FLOAT_BE;
188 pcm_format = SND_PCM_FORMAT_FLOAT_LE;
191 pcm_format = SND_PCM_FORMAT_S32_BE;
194 pcm_format = SND_PCM_FORMAT_S32_LE;
197 pcm_format = SND_PCM_FORMAT_S24_3BE;
200 pcm_format = SND_PCM_FORMAT_S24_3LE;
203 pcm_format = SND_PCM_FORMAT_U24_3BE;
206 pcm_format = SND_PCM_FORMAT_U24_3LE;
209 pcm_format = SND_PCM_FORMAT_S16_BE;
212 pcm_format = SND_PCM_FORMAT_S16_LE;
215 pcm_format = SND_PCM_FORMAT_U16_BE;
218 pcm_format = SND_PCM_FORMAT_U16_LE;
221 pcm_format = SND_PCM_FORMAT_S8;
224 pcm_format = SND_PCM_FORMAT_U8;
227 if (AOUT_FMT_SPDIF(fmt))
228 spdif = var_InheritBool (aout, "spdif");
231 fourcc = VLC_CODEC_SPDIFL;
232 pcm_format = SND_PCM_FORMAT_S16;
237 fourcc = VLC_CODEC_FL32;
238 pcm_format = SND_PCM_FORMAT_FLOAT;
242 fourcc = VLC_CODEC_S16N;
243 pcm_format = SND_PCM_FORMAT_S16;
248 /* XXX: maybe this should be shared with other dumb outputs */
249 uint32_t map = var_InheritInteger (aout, "alsa-audio-channels");
250 map &= fmt->i_physical_channels;
251 if (unlikely(map == 0)) /* WTH? */
252 map = AOUT_CHANS_STEREO;
254 unsigned channels = popcount (map);
255 if (channels < aout_FormatNbChannels (fmt))
256 msg_Dbg (aout, "downmixing from %u to %u channels",
257 aout_FormatNbChannels (fmt), channels);
259 msg_Dbg (aout, "keeping %u channels", channels);
261 /* Choose the IEC device for S/PDIF output:
262 if the device is overridden by the user then it will be the one.
263 Otherwise we compute the default device based on the output format. */
264 if (spdif && !strcmp (device, "default"))
271 case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
272 FS( 44100) /* def. */ FS( 48000) FS( 32000)
273 FS( 22050) FS( 24000)
274 FS( 88200) FS(768000) FS( 96000)
275 FS(176400) FS(192000)
278 aes3 = IEC958_AES3_CON_FS_NOTID;
283 if (asprintf (&device,
284 "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
285 IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
286 IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
291 /* Open the device */
293 /* VLC always has a resampler. No need for ALSA's. */
294 const int mode = SND_PCM_NO_AUTO_RESAMPLE;
296 int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
297 #if (SND_LIB_VERSION <= 0x010015)
298 # warning Please update alsa-lib to version > 1.0.21a.
299 var_Create (aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
300 if (val != 0 && var_GetBool (aout->p_libvlc, "alsa-working"))
301 dialog_Fatal (aout, "ALSA version problem",
302 "VLC failed to re-initialize your audio output device.\n"
303 "Please update alsa-lib to version 1.0.22 or higher "
304 "to fix this issue.");
305 var_SetBool (aout->p_libvlc, "alsa-working", !val);
309 #if (SND_LIB_VERSION <= 0x010017)
310 # warning Please update alsa-lib to version > 1.0.23.
311 var_Create (aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
312 if (!var_GetBool (aout->p_libvlc, "alsa-broken"))
314 var_SetBool (aout->p_libvlc, "alsa-broken", true);
315 dialog_Fatal (aout, "Potential ALSA version problem",
316 "VLC failed to initialize your audio output device (if any).\n"
317 "Please update alsa-lib to version 1.0.24 or higher "
318 "to try to fix this issue.");
321 msg_Err (aout, "cannot open ALSA device \"%s\": %s", device,
323 dialog_Fatal (aout, _("Audio output failed"),
324 _("The audio device \"%s\" could not be used:\n%s."),
325 device, snd_strerror (val));
331 /* Print some potentially useful debug */
332 msg_Dbg (aout, "using ALSA device: %s", device);
333 DumpDevice (VLC_OBJECT(aout), pcm);
335 /* Get Initial hardware parameters */
336 snd_pcm_hw_params_t *hw;
339 snd_pcm_hw_params_alloca (&hw);
340 snd_pcm_hw_params_any (pcm, hw);
341 Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
343 val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
346 msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
350 val = snd_pcm_hw_params_set_access (pcm, hw,
351 SND_PCM_ACCESS_RW_INTERLEAVED);
354 msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
358 /* Set sample format */
359 if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
362 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
364 fourcc = VLC_CODEC_FL32;
365 pcm_format = SND_PCM_FORMAT_FLOAT;
368 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
370 fourcc = VLC_CODEC_S32N;
371 pcm_format = SND_PCM_FORMAT_S32;
374 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
376 fourcc = VLC_CODEC_S16N;
377 pcm_format = SND_PCM_FORMAT_S16;
381 msg_Err (aout, "no supported sample format");
385 val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
388 msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
392 /* Set channels count */
393 /* By default, ALSA plug will pad missing channels with zeroes, which is
394 * usually fine. However, it will also discard extraneous channels, which
395 * is not acceptable. Thus the user must configure the physically
396 * available channels, and VLC will downmix if needed. */
397 val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
400 msg_Err (aout, "cannot set %u channels: %s", channels,
405 /* Set sample rate */
406 unsigned rate = fmt->i_rate;
407 val = snd_pcm_hw_params_set_rate_near (pcm, hw, &rate, NULL);
410 msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
413 if (fmt->i_rate != rate)
414 msg_Dbg (aout, "resampling from %d Hz to %d Hz", fmt->i_rate, rate);
416 /* Set buffer size */
417 param = AOUT_MAX_ADVANCE_TIME;
418 val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, ¶m, NULL);
421 msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
425 val = snd_pcm_hw_params_get_buffer_time (hw, ¶m, NULL);
428 msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
429 param = AOUT_MIN_PREPARE_TIME;
433 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
434 param = AOUT_MIN_PREPARE_TIME;
436 val = snd_pcm_hw_params_set_period_time_near (pcm, hw, ¶m, NULL);
439 msg_Err (aout, "cannot set period: %s", snd_strerror (val));
443 /* Commit hardware parameters */
444 val = snd_pcm_hw_params (pcm, hw);
447 msg_Err (aout, "cannot commit hardware parameters: %s",
451 Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
453 /* Get Initial software parameters */
454 snd_pcm_sw_params_t *sw;
456 snd_pcm_sw_params_alloca (&sw);
457 snd_pcm_sw_params_current (pcm, sw);
458 Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
461 //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
463 val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
466 msg_Err( aout, "unable to set start threshold (%s)",
467 snd_strerror( val ) );
472 /* Commit software parameters. */
473 val = snd_pcm_sw_params (pcm, sw);
476 msg_Err (aout, "cannot commit software parameters: %s",
480 Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
482 val = snd_pcm_prepare (pcm);
485 msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
489 /* Setup audio_output_t */
490 fmt->i_format = fourcc;
495 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
496 fmt->i_frame_length = A52_FRAME_NB;
500 fmt->i_original_channels =
501 fmt->i_physical_channels = map;
502 switch (popcount (map))
505 sys->reorder = Reorder71;
512 if (snd_pcm_hw_params_can_pause (hw))
516 aout->pause = PauseDummy;
517 msg_Warn (aout, "device cannot be paused");
521 /* Setup audio-device choices */
525 var_Create (aout, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
526 text.psz_string = _("Audio Device");
527 var_Change (aout, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
529 GetDevices (VLC_OBJECT(aout), device);
531 var_AddCallback (aout, "audio-device", DeviceChanged, NULL);
534 aout_SoftVolumeStart (aout);
544 * Queues one audio buffer to the hardware.
546 static void Play (audio_output_t *aout, block_t *block,
547 mtime_t *restrict drift)
549 aout_sys_t *sys = aout->sys;
551 if (sys->reorder != NULL)
552 sys->reorder (block->p_buffer, block->i_nb_samples,
553 sys->format.i_bitspersample / 8);
555 snd_pcm_t *pcm = sys->pcm;
556 snd_pcm_status_t *status;
559 snd_pcm_status_alloca (&status);
560 val = snd_pcm_status (pcm, status);
562 msg_Err (aout, "cannot get status: %s", snd_strerror (val));
565 snd_pcm_sframes_t frames = snd_pcm_status_get_delay (status);
566 mtime_t delay = frames * CLOCK_FREQ / sys->format.i_rate;
567 delay += mdate () - block->i_pts;
569 if (snd_pcm_status_get_state (status) != SND_PCM_STATE_RUNNING)
573 if (sys->format.i_format != VLC_CODEC_SPDIFL)
575 frames = (delay * sys->format.i_rate) / -CLOCK_FREQ;
576 msg_Dbg (aout, "prepending %ld zeroes", frames);
578 void *z = calloc (frames, sys->format.i_bytes_per_frame);
579 if (likely(z != NULL))
581 snd_pcm_writei (pcm, z, frames);
586 /* Lame fallback if zero padding does not work */
589 msg_Dbg (aout, "deferring start (%"PRId64" us)", -delay);
594 msg_Dbg (aout, "starting late (%"PRId64" us)", delay);
600 /* TODO: better overflow handling */
601 /* TODO: no period wake ups */
603 while (block->i_nb_samples > 0)
605 snd_pcm_sframes_t frames;
607 frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
610 size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
611 block->i_nb_samples -= frames;
612 block->p_buffer += bytes;
613 block->i_buffer -= bytes;
618 int val = snd_pcm_recover (pcm, frames, 1);
621 msg_Err (aout, "cannot recover playback stream: %s",
623 DumpDeviceStatus (aout, pcm);
626 msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
629 block_Release (block);
633 * Pauses/resumes the audio playback.
635 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
637 snd_pcm_t *pcm = aout->sys->pcm;
639 int val = snd_pcm_pause (pcm, pause);
641 PauseDummy (aout, pause, date);
644 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
646 snd_pcm_t *pcm = aout->sys->pcm;
648 /* Stupid device cannot pause. Discard samples. */
652 snd_pcm_prepare (pcm);
657 * Flushes/drains the audio playback buffer.
659 static void Flush (audio_output_t *aout, bool wait)
661 snd_pcm_t *pcm = aout->sys->pcm;
667 snd_pcm_prepare (pcm);
672 * Releases the audio output.
674 static void Stop (audio_output_t *aout)
676 aout_sys_t *sys = aout->sys;
677 snd_pcm_t *pcm = sys->pcm;
679 var_DelCallback (aout, "audio-device", DeviceChanged, NULL);
680 var_Destroy (aout, "audio-device");
687 * Converts from VLC to ALSA order for 7.1.
688 * VLC has middle channels in position 2 and 3, ALSA in position 6 and 7.
690 static void Reorder71 (void *p, size_t n, unsigned size)
695 for (uint64_t *ptr = p; n > 0; ptr += 4, n--)
697 uint64_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
698 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
702 for (uint32_t *ptr = p; n > 0; ptr += 4, n--)
704 uint32_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
705 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
710 for (uint16_t *ptr = p; n > 0; n--)
712 uint16_t middle[size];
713 memcpy (middle, ptr + size, size * 2);
715 memcpy (ptr, ptr + size, size * 2);
717 memcpy (ptr, ptr + size, size * 2);
719 memcpy (ptr, middle, size * 2);
728 * Enumerates ALSA output devices.
730 static int EnumDevices(vlc_object_t *obj, char const *varname,
731 char ***restrict vp, char ***restrict tp)
735 char **names = xmalloc(sizeof (*names));
736 char **descs = xmalloc(sizeof (*names));
737 names[0] = strdup ("default");
738 descs[0] = strdup (N_("Default"));
740 if (unlikely(names[0] == NULL || descs[0] == NULL))
744 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
747 for (size_t i = 0; hints[i] != NULL; i++)
749 void *hint = hints[i];
751 char *name = snd_device_name_get_hint(hint, "NAME");
752 if (unlikely(name == NULL))
755 char *desc = snd_device_name_get_hint(hint, "DESC");
762 names = xrealloc (names, (n + 1) * sizeof (*names));
763 descs = xrealloc (descs, (n + 1) * sizeof (*descs));
768 snd_device_name_free_hint(hints);
770 (void) obj; (void) varname;
777 static void GetDevices(vlc_object_t *obj, const char *prefs_dev)
781 msg_Dbg(obj, "Available ALSA PCM devices:");
782 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
785 vlc_value_t val, text;
786 bool hinted_default = false;
787 bool hinted_prefs = !strcmp (prefs_dev, "default");
789 for (size_t i = 0; hints[i] != NULL; i++)
791 void *hint = hints[i];
793 char *name = snd_device_name_get_hint(hint, "NAME");
794 if (unlikely(name == NULL))
797 char *desc = snd_device_name_get_hint(hint, "DESC");
799 for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
801 msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
803 if (!strcmp (name, "default"))
804 hinted_default = true;
805 if (!strcmp (name, prefs_dev))
808 val.psz_string = name;
809 text.psz_string = desc;
810 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
815 snd_device_name_free_hint(hints);
819 val.psz_string = (char *)"default";
820 text.psz_string = (char *)N_("Default");
821 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
824 val.psz_string = (char *)prefs_dev;
827 text.psz_string = (char *)N_("VLC preferences");
828 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
830 var_Change(obj, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
833 static int Open(vlc_object_t *obj)
835 audio_output_t *aout = (audio_output_t *)obj;
836 aout_sys_t *sys = malloc (sizeof (*sys));
838 if (unlikely(sys == NULL))
843 aout_SoftVolumeInit (aout);
847 static void Close(vlc_object_t *obj)
849 audio_output_t *aout = (audio_output_t *)obj;
850 aout_sys_t *sys = aout->sys;