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);
53 #define A52_FRAME_NB 1536
55 static int Open (vlc_object_t *);
56 static void Close (vlc_object_t *);
57 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
58 vlc_value_t newval, vlc_value_t oldval, void *p_unused );
59 static void GetDevices (vlc_object_t *, module_config_t *, const char *);
61 #define AUDIO_DEV_TEXT N_("Audio output device")
62 #define AUDIO_DEV_LONGTEXT N_("Audio output device (using ALSA syntax).")
63 static const char *const devices[] = {
66 static const char *const devices_text[] = {
70 #define AUDIO_CHAN_TEXT N_("Audio output channels")
71 #define AUDIO_CHAN_LONGTEXT N_("Channels available for audio output." \
72 "If the input has more channels than the output, it will be down-mixed." \
73 "This parameter is ignored when digital pass-through is active.")
74 static const int channels[] = {
75 AOUT_CHAN_CENTER, AOUT_CHANS_STEREO, AOUT_CHANS_4_0, AOUT_CHANS_4_1,
76 AOUT_CHANS_5_0, AOUT_CHANS_5_1, AOUT_CHANS_7_1,
78 static const char *const channels_text[] = {
79 N_("Mono"), N_("Stereo"), N_("Surround 4.0"), N_("Surround 4.1"),
80 N_("Surround 5.0"), N_("Surround 5.1"), N_("Surround 7.1"),
84 set_shortname( "ALSA" )
85 set_description( N_("ALSA audio output") )
86 set_category( CAT_AUDIO )
87 set_subcategory( SUBCAT_AUDIO_AOUT )
88 add_string ("alsa-audio-device", "default",
89 AUDIO_DEV_TEXT, AUDIO_DEV_LONGTEXT, false)
90 change_string_list( devices, devices_text, FindDevicesCallback )
91 change_action_add( FindDevicesCallback, N_("Refresh list") )
92 add_integer ("alsa-audio-channels", AOUT_CHANS_FRONT,
93 AUDIO_CHAN_TEXT, AUDIO_CHAN_LONGTEXT, false)
94 change_integer_list (channels, channels_text)
96 set_capability( "audio output", 150 )
97 set_callbacks( Open, Close )
101 /** Helper for ALSA -> VLC debugging output */
102 static void Dump (vlc_object_t *obj, const char *msg,
103 int (*cb)(void *, snd_output_t *), void *p)
105 snd_output_t *output;
108 if (unlikely(snd_output_buffer_open (&output)))
111 int val = cb (p, output);
114 msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
118 size_t len = snd_output_buffer_string (output, &str);
119 if (len > 0 && str[len - 1])
120 len--; /* strip trailing newline */
121 msg_Dbg (obj, "%s%.*s", msg, (int)len, str);
122 snd_output_close (output);
124 #define Dump(o, m, cb, p) \
125 Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
127 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
129 snd_pcm_info_t *info;
131 Dump (obj, " ", snd_pcm_dump, pcm);
132 snd_pcm_info_alloca (&info);
133 if (snd_pcm_info (pcm, info) == 0)
135 msg_Dbg (obj, " device name : %s", snd_pcm_info_get_name (info));
136 msg_Dbg (obj, " device ID : %s", snd_pcm_info_get_id (info));
137 msg_Dbg (obj, " subdevice name: %s",
138 snd_pcm_info_get_subdevice_name (info));
142 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
144 snd_pcm_status_t *status;
146 snd_pcm_status_alloca (&status);
147 snd_pcm_status (pcm, status);
148 Dump (obj, "current status:\n", snd_pcm_status_dump, status);
150 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
152 static int DeviceChanged (vlc_object_t *obj, const char *varname,
153 vlc_value_t prev, vlc_value_t cur, void *data)
155 aout_ChannelsRestart (obj, varname, prev, cur, data);
157 if (!var_Type (obj, "alsa-audio-device"))
158 var_Create (obj, "alsa-audio-device", VLC_VAR_STRING);
159 var_SetString (obj, "alsa-audio-device", cur.psz_string);
163 static void Play (audio_output_t *, block_t *, mtime_t *);
164 static void Pause (audio_output_t *, bool, mtime_t);
165 static void PauseDummy (audio_output_t *, bool, mtime_t);
166 static void Flush (audio_output_t *, bool);
167 static void Reorder71 (void *, size_t, unsigned);
169 /** Initializes an ALSA playback stream */
170 static int Open (vlc_object_t *obj)
172 audio_output_t *aout = (audio_output_t *)obj;
174 /* Get device name */
175 char *device = var_InheritString (aout, "alsa-audio-device");
176 if (unlikely(device == NULL))
179 snd_pcm_format_t pcm_format; /* ALSA sample format */
180 vlc_fourcc_t fourcc = aout->format.i_format;
186 pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
189 pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
192 pcm_format = SND_PCM_FORMAT_FLOAT_BE;
195 pcm_format = SND_PCM_FORMAT_FLOAT_LE;
198 pcm_format = SND_PCM_FORMAT_S32_BE;
201 pcm_format = SND_PCM_FORMAT_S32_LE;
204 pcm_format = SND_PCM_FORMAT_S24_3BE;
207 pcm_format = SND_PCM_FORMAT_S24_3LE;
210 pcm_format = SND_PCM_FORMAT_U24_3BE;
213 pcm_format = SND_PCM_FORMAT_U24_3LE;
216 pcm_format = SND_PCM_FORMAT_S16_BE;
219 pcm_format = SND_PCM_FORMAT_S16_LE;
222 pcm_format = SND_PCM_FORMAT_U16_BE;
225 pcm_format = SND_PCM_FORMAT_U16_LE;
228 pcm_format = SND_PCM_FORMAT_S8;
231 pcm_format = SND_PCM_FORMAT_U8;
234 if (AOUT_FMT_SPDIF(&aout->format))
235 spdif = var_InheritBool (aout, "spdif");
238 fourcc = VLC_CODEC_SPDIFL;
239 pcm_format = SND_PCM_FORMAT_S16;
244 fourcc = VLC_CODEC_FL32;
245 pcm_format = SND_PCM_FORMAT_FLOAT;
249 fourcc = VLC_CODEC_S16N;
250 pcm_format = SND_PCM_FORMAT_S16;
255 /* XXX: maybe this should be shared with other dumb outputs */
256 uint32_t map = var_InheritInteger (aout, "alsa-audio-channels");
257 map &= aout->format.i_physical_channels;
258 if (unlikely(map == 0)) /* WTH? */
259 map = AOUT_CHANS_STEREO;
261 unsigned channels = popcount (map);
262 if (channels < aout_FormatNbChannels (&aout->format))
263 msg_Dbg (aout, "downmixing from %u to %u channels",
264 aout_FormatNbChannels (&aout->format), channels);
266 msg_Dbg (aout, "keeping %u channels", channels);
268 /* Choose the IEC device for S/PDIF output:
269 if the device is overridden by the user then it will be the one.
270 Otherwise we compute the default device based on the output format. */
271 if (spdif && !strcmp (device, "default"))
275 switch (aout->format.i_rate)
278 case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
279 FS( 44100) /* def. */ FS( 48000) FS( 32000)
280 FS( 22050) FS( 24000)
281 FS( 88200) FS(768000) FS( 96000)
282 FS(176400) FS(192000)
285 aes3 = IEC958_AES3_CON_FS_NOTID;
290 if (asprintf (&device,
291 "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
292 IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
293 IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
298 /* Allocate structures */
299 aout_sys_t *sys = malloc (sizeof (*sys));
300 if (unlikely(sys == NULL))
307 /* Open the device */
309 /* VLC always has a resampler. No need for ALSA's. */
310 const int mode = SND_PCM_NO_AUTO_RESAMPLE;
312 int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
313 #if (SND_LIB_VERSION <= 0x010015)
314 # warning Please update alsa-lib to version > 1.0.21a.
315 var_Create (aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
316 if (val != 0 && var_GetBool (aout->p_libvlc, "alsa-working"))
317 dialog_Fatal (aout, "ALSA version problem",
318 "VLC failed to re-initialize your audio output device.\n"
319 "Please update alsa-lib to version 1.0.22 or higher "
320 "to fix this issue.");
321 var_SetBool (aout->p_libvlc, "alsa-working", !val);
325 #if (SND_LIB_VERSION <= 0x010017)
326 # warning Please update alsa-lib to version > 1.0.23.
327 var_Create (aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
328 if (!var_GetBool (aout->p_libvlc, "alsa-broken"))
330 var_SetBool (aout->p_libvlc, "alsa-broken", true);
331 dialog_Fatal (aout, "Potential ALSA version problem",
332 "VLC failed to initialize your audio output device (if any).\n"
333 "Please update alsa-lib to version 1.0.24 or higher "
334 "to try to fix this issue.");
337 msg_Err (aout, "cannot open ALSA device \"%s\": %s", device,
339 dialog_Fatal (aout, _("Audio output failed"),
340 _("The audio device \"%s\" could not be used:\n%s."),
341 device, snd_strerror (val));
348 /* Print some potentially useful debug */
349 msg_Dbg (aout, "using ALSA device: %s", device);
350 DumpDevice (VLC_OBJECT(aout), pcm);
352 /* Get Initial hardware parameters */
353 snd_pcm_hw_params_t *hw;
356 snd_pcm_hw_params_alloca (&hw);
357 snd_pcm_hw_params_any (pcm, hw);
358 Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
360 val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
363 msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
367 val = snd_pcm_hw_params_set_access (pcm, hw,
368 SND_PCM_ACCESS_RW_INTERLEAVED);
371 msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
375 /* Set sample format */
376 if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
379 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
381 fourcc = VLC_CODEC_FL32;
382 pcm_format = SND_PCM_FORMAT_FLOAT;
385 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
387 fourcc = VLC_CODEC_S32N;
388 pcm_format = SND_PCM_FORMAT_S32;
391 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
393 fourcc = VLC_CODEC_S16N;
394 pcm_format = SND_PCM_FORMAT_S16;
398 msg_Err (aout, "no supported sample format");
402 val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
405 msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
409 /* Set channels count */
410 /* By default, ALSA plug will pad missing channels with zeroes, which is
411 * usually fine. However, it will also discard extraneous channels, which
412 * is not acceptable. Thus the user must configure the physically
413 * available channels, and VLC will downmix if needed. */
414 val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
417 msg_Err (aout, "cannot set %u channels: %s", channels,
422 /* Set sample rate */
423 unsigned rate = aout->format.i_rate;
424 val = snd_pcm_hw_params_set_rate_near (pcm, hw, &rate, NULL);
427 msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
430 if (aout->format.i_rate != rate)
431 msg_Dbg (aout, "resampling from %d Hz to %d Hz",
432 aout->format.i_rate, rate);
434 /* Set buffer size */
435 param = AOUT_MAX_ADVANCE_TIME;
436 val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, ¶m, NULL);
439 msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
443 val = snd_pcm_hw_params_get_buffer_time (hw, ¶m, NULL);
446 msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
447 param = AOUT_MIN_PREPARE_TIME;
451 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
452 param = AOUT_MIN_PREPARE_TIME;
454 val = snd_pcm_hw_params_set_period_time_near (pcm, hw, ¶m, NULL);
457 msg_Err (aout, "cannot set period: %s", snd_strerror (val));
461 /* Commit hardware parameters */
462 val = snd_pcm_hw_params (pcm, hw);
465 msg_Err (aout, "cannot commit hardware parameters: %s",
469 Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
471 /* Get Initial software parameters */
472 snd_pcm_sw_params_t *sw;
474 snd_pcm_sw_params_alloca (&sw);
475 snd_pcm_sw_params_current (pcm, sw);
476 Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
479 //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
481 val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
484 msg_Err( aout, "unable to set start threshold (%s)",
485 snd_strerror( val ) );
490 /* Commit software parameters. */
491 val = snd_pcm_sw_params (pcm, sw);
494 msg_Err (aout, "cannot commit software parameters: %s",
498 Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
500 val = snd_pcm_prepare (pcm);
503 msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
507 /* Setup audio_output_t */
508 aout->format.i_format = fourcc;
509 aout->format.i_rate = rate;
513 aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
514 aout->format.i_frame_length = A52_FRAME_NB;
515 aout->volume_set = NULL;
516 aout->mute_set = NULL;
520 aout->format.i_original_channels =
521 aout->format.i_physical_channels = map;
522 switch (popcount (map))
525 sys->reorder = Reorder71;
529 aout_SoftVolumeInit (aout);
532 aout->pf_play = Play;
533 if (snd_pcm_hw_params_can_pause (hw))
534 aout->pf_pause = Pause;
537 aout->pf_pause = PauseDummy;
538 msg_Warn (aout, "device cannot be paused");
540 aout->pf_flush = Flush;
542 /* Setup audio-device choices */
546 var_Create (obj, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
547 text.psz_string = _("Audio Device");
548 var_Change (obj, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
550 GetDevices (obj, NULL, device);
552 var_AddCallback (obj, "audio-device", DeviceChanged, NULL);
565 * Queues one audio buffer to the hardware.
567 static void Play (audio_output_t *aout, block_t *block,
568 mtime_t *restrict drift)
570 aout_sys_t *sys = aout->sys;
572 if (sys->reorder != NULL)
573 sys->reorder (block->p_buffer, block->i_nb_samples,
574 aout->format.i_bitspersample / 8);
576 snd_pcm_t *pcm = sys->pcm;
577 snd_pcm_sframes_t frames;
578 snd_pcm_state_t state = snd_pcm_state (pcm);
580 if (snd_pcm_delay (pcm, &frames) == 0)
582 mtime_t delay = frames * CLOCK_FREQ / aout->format.i_rate;
583 delay += mdate () - block->i_pts;
585 if (state != SND_PCM_STATE_RUNNING)
589 if (aout->format.i_format != VLC_CODEC_SPDIFL)
591 frames = (delay * aout->format.i_rate) / -CLOCK_FREQ;
592 msg_Dbg (aout, "prepending %ld zeroes", frames);
594 void *z = calloc (frames, aout->format.i_bytes_per_frame);
595 if (likely(z != NULL))
597 snd_pcm_writei (pcm, z, frames);
602 /* Lame fallback if zero padding does not work */
605 msg_Dbg (aout, "deferring start (%"PRId64" us)", -delay);
610 msg_Dbg (aout, "starting late (%"PRId64" us)", delay);
616 /* TODO: better overflow handling */
617 /* TODO: no period wake ups */
619 while (block->i_nb_samples > 0)
621 frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
624 size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
625 block->i_nb_samples -= frames;
626 block->p_buffer += bytes;
627 block->i_buffer -= bytes;
632 int val = snd_pcm_recover (pcm, frames, 1);
635 msg_Err (aout, "cannot recover playback stream: %s",
637 DumpDeviceStatus (aout, pcm);
640 msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
643 block_Release (block);
647 * Pauses/resumes the audio playback.
649 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
651 snd_pcm_t *pcm = aout->sys->pcm;
653 int val = snd_pcm_pause (pcm, pause);
655 PauseDummy (aout, pause, date);
658 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
660 snd_pcm_t *pcm = aout->sys->pcm;
662 /* Stupid device cannot pause. Discard samples. */
666 snd_pcm_prepare (pcm);
671 * Flushes/drains the audio playback buffer.
673 static void Flush (audio_output_t *aout, bool wait)
675 snd_pcm_t *pcm = aout->sys->pcm;
681 snd_pcm_prepare (pcm);
686 * Releases the audio output.
688 static void Close (vlc_object_t *obj)
690 audio_output_t *aout = (audio_output_t *)obj;
691 aout_sys_t *sys = aout->sys;
692 snd_pcm_t *pcm = aout->sys->pcm;
694 var_DelCallback (obj, "audio-device", DeviceChanged, NULL);
695 var_Destroy (obj, "audio-device");
703 * Converts from VLC to ALSA order for 7.1.
704 * VLC has middle channels in position 2 and 3, ALSA in position 6 and 7.
706 static void Reorder71 (void *p, size_t n, unsigned size)
711 for (uint64_t *ptr = p; n > 0; ptr += 4, n--)
713 uint64_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
714 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
718 for (uint32_t *ptr = p; n > 0; ptr += 4, n--)
720 uint32_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
721 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
726 for (uint16_t *ptr = p; n > 0; n--)
728 uint16_t middle[size];
729 memcpy (middle, ptr + size, size * 2);
731 memcpy (ptr, ptr + size, size * 2);
733 memcpy (ptr, ptr + size, size * 2);
735 memcpy (ptr, middle, size * 2);
743 /*****************************************************************************
744 * config variable callback
745 *****************************************************************************/
746 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
747 vlc_value_t newval, vlc_value_t oldval, void *p_unused )
749 module_config_t *p_item;
754 p_item = config_FindConfig( p_this, psz_name );
755 if( !p_item ) return VLC_SUCCESS;
757 /* Clear-up the current list */
762 /* Keep the first entrie */
763 for( i = 1; i < p_item->i_list; i++ )
765 free( (char *)p_item->ppsz_list[i] );
766 free( (char *)p_item->ppsz_list_text[i] );
768 /* TODO: Remove when no more needed */
769 p_item->ppsz_list[i] = NULL;
770 p_item->ppsz_list_text[i] = NULL;
774 GetDevices (p_this, p_item, "default");
780 static void GetDevices (vlc_object_t *obj, module_config_t *item,
781 const char *prefs_dev)
784 bool hinted_default = false;
785 bool hinted_prefs = !strcmp (prefs_dev, "default");
787 msg_Dbg(obj, "Available ALSA PCM devices:");
789 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
792 for (size_t i = 0; hints[i] != NULL; i++)
794 void *hint = hints[i];
796 char *name = snd_device_name_get_hint(hint, "NAME");
797 if (unlikely(name == NULL))
800 char *desc = snd_device_name_get_hint(hint, "DESC");
802 for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
804 msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
806 if (!strcmp (name, "default"))
807 hinted_default = true;
808 if (!strcmp (name, prefs_dev))
813 item->ppsz_list = xrealloc(item->ppsz_list,
814 (item->i_list + 2) * sizeof(char *));
815 item->ppsz_list_text = xrealloc(item->ppsz_list_text,
816 (item->i_list + 2) * sizeof(char *));
817 item->ppsz_list[item->i_list] = name;
820 item->ppsz_list_text[item->i_list] = desc;
825 vlc_value_t val, text;
827 val.psz_string = name;
828 text.psz_string = desc;
829 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
835 snd_device_name_free_hint(hints);
839 item->ppsz_list[item->i_list] = NULL;
840 item->ppsz_list_text[item->i_list] = NULL;
844 vlc_value_t val, text;
848 val.psz_string = (char *)"default";
849 text.psz_string = (char *)N_("Default");
850 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
853 val.psz_string = (char *)prefs_dev;
856 text.psz_string = (char *)N_("VLC preferences");
857 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
859 var_Change(obj, "audio-device", VLC_VAR_SETVALUE, &val, NULL);