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 #define A52_FRAME_NB 1536
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 *);
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[] = {
62 static const char *const devices_text[] = {
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,
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"),
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 )
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)
100 snd_output_t *output;
103 if (unlikely(snd_output_buffer_open (&output)))
106 int val = cb (p, output);
109 msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
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);
119 #define Dump(o, m, cb, p) \
120 Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
122 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
124 snd_pcm_info_t *info;
126 Dump (obj, " ", snd_pcm_dump, pcm);
127 snd_pcm_info_alloca (&info);
128 if (snd_pcm_info (pcm, info) == 0)
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));
137 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
139 snd_pcm_status_t *status;
141 snd_pcm_status_alloca (&status);
142 snd_pcm_status (pcm, status);
143 Dump (obj, "current status:\n", snd_pcm_status_dump, status);
145 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
148 * Initializes list of devices.
150 static void Probe (vlc_object_t *obj, const char *dev)
152 /* Due to design bug in audio output core, this hack is required: */
153 if (var_Type (obj, "audio-device") == 0)
155 /* The variable does not exist - first call. */
158 var_Create (obj, "audio-device", VLC_VAR_STRING | VLC_VAR_HASCHOICE);
159 text.psz_string = _("Audio Device");
160 var_Change (obj, "audio-device", VLC_VAR_SETTEXT, &text, NULL);
162 GetDevices (obj, NULL, dev);
164 var_AddCallback (obj, "audio-device", aout_ChannelsRestart, NULL);
165 var_TriggerCallback (obj, "intf-change");
169 static void Play (audio_output_t *, block_t *);
170 static void Pause (audio_output_t *, bool, mtime_t);
171 static void PauseDummy (audio_output_t *, bool, mtime_t);
172 static void Flush (audio_output_t *, bool);
173 static void Reorder71 (void *, size_t, unsigned);
175 /** Initializes an ALSA playback stream */
176 static int Open (vlc_object_t *obj)
178 audio_output_t *aout = (audio_output_t *)obj;
180 /* Get device name */
183 if (var_Type (aout, "audio-device"))
184 device = var_GetString (aout, "audio-device");
186 device = var_InheritString (aout, "alsa-audio-device");
187 if (unlikely(device == NULL))
190 snd_pcm_format_t pcm_format; /* ALSA sample format */
191 vlc_fourcc_t fourcc = aout->format.i_format;
197 pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
200 pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
203 pcm_format = SND_PCM_FORMAT_FLOAT_BE;
206 pcm_format = SND_PCM_FORMAT_FLOAT_LE;
209 fourcc = VLC_CODEC_FL32;
210 pcm_format = SND_PCM_FORMAT_FLOAT;
213 pcm_format = SND_PCM_FORMAT_S32_BE;
216 pcm_format = SND_PCM_FORMAT_S32_LE;
219 pcm_format = SND_PCM_FORMAT_S24_3BE;
222 pcm_format = SND_PCM_FORMAT_S24_3LE;
225 pcm_format = SND_PCM_FORMAT_U24_3BE;
228 pcm_format = SND_PCM_FORMAT_U24_3LE;
231 pcm_format = SND_PCM_FORMAT_S16_BE;
234 pcm_format = SND_PCM_FORMAT_S16_LE;
237 pcm_format = SND_PCM_FORMAT_U16_BE;
240 pcm_format = SND_PCM_FORMAT_U16_LE;
243 pcm_format = SND_PCM_FORMAT_S8;
246 pcm_format = SND_PCM_FORMAT_U8;
249 if (AOUT_FMT_SPDIF(&aout->format))
250 spdif = var_InheritBool (aout, "spdif");
253 fourcc = VLC_CODEC_SPDIFL;
254 pcm_format = SND_PCM_FORMAT_S16;
259 fourcc = VLC_CODEC_FL32;
260 pcm_format = SND_PCM_FORMAT_FLOAT;
264 fourcc = VLC_CODEC_S16N;
265 pcm_format = SND_PCM_FORMAT_S16;
270 /* XXX: maybe this should be shared with other dumb outputs */
271 uint32_t map = var_InheritInteger (aout, "alsa-audio-channels");
272 map &= aout->format.i_physical_channels;
273 if (unlikely(map == 0)) /* WTH? */
274 map = AOUT_CHANS_STEREO;
276 unsigned channels = popcount (map);
277 if (channels < aout_FormatNbChannels (&aout->format))
278 msg_Dbg (aout, "downmixing from %u to %u channels",
279 aout_FormatNbChannels (&aout->format), channels);
281 msg_Dbg (aout, "keeping %u channels", channels);
283 /* Choose the IEC device for S/PDIF output:
284 if the device is overridden by the user then it will be the one.
285 Otherwise we compute the default device based on the output format. */
286 if (spdif && !strcmp (device, "default"))
290 switch (aout->format.i_rate)
293 case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
294 FS( 44100) /* def. */ FS( 48000) FS( 32000)
295 FS( 22050) FS( 24000)
296 FS( 88200) FS(768000) FS( 96000)
297 FS(176400) FS(192000)
300 aes3 = IEC958_AES3_CON_FS_NOTID;
305 if (asprintf (&device,
306 "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
307 IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
308 IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
313 /* Allocate structures */
314 aout_sys_t *sys = malloc (sizeof (*sys));
315 if (unlikely(sys == NULL))
322 /* Open the device */
324 /* VLC always has a resampler. No need for ALSA's. */
325 const int mode = SND_PCM_NO_AUTO_RESAMPLE;
327 int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
328 #if (SND_LIB_VERSION <= 0x010015)
329 # warning Please update alsa-lib to version > 1.0.21a.
330 var_Create (aout->p_libvlc, "alsa-working", VLC_VAR_BOOL);
331 if (val != 0 && var_GetBool (aout->p_libvlc, "alsa-working"))
332 dialog_Fatal (aout, "ALSA version problem",
333 "VLC failed to re-initialize your audio output device.\n"
334 "Please update alsa-lib to version 1.0.22 or higher "
335 "to fix this issue.");
336 var_SetBool (aout->p_libvlc, "alsa-working", !val);
340 #if (SND_LIB_VERSION <= 0x010017)
341 # warning Please update alsa-lib to version > 1.0.23.
342 var_Create (aout->p_libvlc, "alsa-broken", VLC_VAR_BOOL);
343 if (!var_GetBool (aout->p_libvlc, "alsa-broken"))
345 var_SetBool (aout->p_libvlc, "alsa-broken", true);
346 dialog_Fatal (aout, "Potential ALSA version problem",
347 "VLC failed to initialize your audio output device (if any).\n"
348 "Please update alsa-lib to version 1.0.24 or higher "
349 "to try to fix this issue.");
352 msg_Err (aout, "cannot open ALSA device \"%s\": %s", device,
354 dialog_Fatal (aout, _("Audio output failed"),
355 _("The audio device \"%s\" could not be used:\n%s."),
356 device, snd_strerror (val));
363 /* Print some potentially useful debug */
364 msg_Dbg (aout, "using ALSA device: %s", device);
365 DumpDevice (VLC_OBJECT(aout), pcm);
367 /* Get Initial hardware parameters */
368 snd_pcm_hw_params_t *hw;
371 snd_pcm_hw_params_alloca (&hw);
372 snd_pcm_hw_params_any (pcm, hw);
373 Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
375 val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
378 msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
382 val = snd_pcm_hw_params_set_access (pcm, hw,
383 SND_PCM_ACCESS_RW_INTERLEAVED);
386 msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
390 /* Set sample format */
391 if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
394 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
396 fourcc = VLC_CODEC_FL32;
397 pcm_format = SND_PCM_FORMAT_FLOAT;
400 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
402 fourcc = VLC_CODEC_S32N;
403 pcm_format = SND_PCM_FORMAT_S32;
406 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
408 fourcc = VLC_CODEC_S16N;
409 pcm_format = SND_PCM_FORMAT_S16;
413 msg_Err (aout, "no supported sample format");
417 val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
420 msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
424 /* Set channels count */
425 /* By default, ALSA plug will pad missing channels with zeroes, which is
426 * usually fine. However, it will also discard extraneous channels, which
427 * is not acceptable. Thus the user must configure the physically
428 * available channels, and VLC will downmix if needed. */
429 val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
432 msg_Err (aout, "cannot set %u channels: %s", channels,
437 /* Set sample rate */
438 unsigned rate = aout->format.i_rate;
439 val = snd_pcm_hw_params_set_rate_near (pcm, hw, &rate, NULL);
442 msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
445 if (aout->format.i_rate != rate)
446 msg_Dbg (aout, "resampling from %d Hz to %d Hz",
447 aout->format.i_rate, rate);
449 /* Set buffer size */
450 param = AOUT_MAX_ADVANCE_TIME;
451 val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, ¶m, NULL);
454 msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
458 val = snd_pcm_hw_params_get_buffer_time (hw, ¶m, NULL);
461 msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
462 param = AOUT_MIN_PREPARE_TIME;
466 #else /* work-around for PulseAudio: */
467 param = AOUT_MIN_PREPARE_TIME;
469 val = snd_pcm_hw_params_set_period_time_near (pcm, hw, ¶m, NULL);
472 msg_Err (aout, "cannot set period: %s", snd_strerror (val));
476 /* Commit hardware parameters */
477 val = snd_pcm_hw_params (pcm, hw);
480 msg_Err (aout, "cannot commit hardware parameters: %s",
484 Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
486 /* Get Initial software parameters */
487 snd_pcm_sw_params_t *sw;
489 snd_pcm_sw_params_alloca (&sw);
490 snd_pcm_sw_params_current (pcm, sw);
491 Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
494 //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
496 val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
499 msg_Err( aout, "unable to set start threshold (%s)",
500 snd_strerror( val ) );
505 /* Commit software parameters. */
506 val = snd_pcm_sw_params (pcm, sw);
509 msg_Err (aout, "cannot commit software parameters: %s",
513 Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
515 val = snd_pcm_prepare (pcm);
518 msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
522 /* Setup audio_output_t */
523 aout->format.i_format = fourcc;
524 aout->format.i_rate = rate;
527 aout->format.i_bytes_per_frame = AOUT_SPDIF_SIZE;
528 aout->format.i_frame_length = A52_FRAME_NB;
529 aout_VolumeNoneInit (aout);
533 aout->format.i_original_channels =
534 aout->format.i_physical_channels = map;
535 switch (popcount (map))
538 sys->reorder = Reorder71;
544 aout_VolumeSoftInit (aout);
547 aout->pf_play = Play;
548 if (snd_pcm_hw_params_can_pause (hw))
549 aout->pf_pause = Pause;
552 aout->pf_pause = PauseDummy;
553 msg_Warn (aout, "device cannot be paused");
555 aout->pf_flush = Flush;
569 * Queues one audio buffer to the hardware.
571 static void Play (audio_output_t *aout, block_t *block)
573 aout_sys_t *sys = aout->sys;
575 if (sys->reorder != NULL)
576 sys->reorder (block->p_buffer, block->i_nb_samples,
577 aout->format.i_bitspersample / 8);
579 snd_pcm_t *pcm = sys->pcm;
580 snd_pcm_sframes_t frames;
581 snd_pcm_state_t state = snd_pcm_state (pcm);
583 if (snd_pcm_delay (pcm, &frames) == 0)
585 mtime_t delay = frames * CLOCK_FREQ / aout->format.i_rate;
587 if (state != SND_PCM_STATE_RUNNING)
589 delay = block->i_pts - (mdate () + delay);
592 if (aout->format.i_format != VLC_CODEC_SPDIFL)
594 frames = (delay * aout->format.i_rate) / CLOCK_FREQ;
595 msg_Dbg (aout, "prepending %ld zeroes", frames);
597 void *z = calloc (frames, aout->format.i_bytes_per_frame);
598 if (likely(z != NULL))
600 snd_pcm_writei (pcm, z, frames);
605 /* Lame fallback if zero padding does not work */
608 msg_Dbg (aout, "deferring start (%"PRId64" us)", delay);
613 msg_Dbg (aout, "starting late (%"PRId64" us)", delay);
616 aout_TimeReport (aout, block->i_pts - delay);
619 /* TODO: better overflow handling */
620 /* TODO: no period wake ups */
622 while (block->i_nb_samples > 0)
624 frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
627 size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
628 block->i_nb_samples -= frames;
629 block->p_buffer += bytes;
630 block->i_buffer -= bytes;
635 int val = snd_pcm_recover (pcm, frames, 1);
638 msg_Err (aout, "cannot recover playback stream: %s",
640 DumpDeviceStatus (aout, pcm);
643 msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
646 block_Release (block);
650 * Pauses/resumes the audio playback.
652 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
654 snd_pcm_t *pcm = aout->sys->pcm;
656 int val = snd_pcm_pause (pcm, pause);
658 PauseDummy (aout, pause, date);
661 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
663 snd_pcm_t *pcm = aout->sys->pcm;
665 /* Stupid device cannot pause. Discard samples. */
669 snd_pcm_prepare (pcm);
674 * Flushes/drains the audio playback buffer.
676 static void Flush (audio_output_t *aout, bool wait)
678 snd_pcm_t *pcm = aout->sys->pcm;
684 snd_pcm_prepare (pcm);
689 * Releases the audio output.
691 static void Close (vlc_object_t *obj)
693 audio_output_t *aout = (audio_output_t *)obj;
694 aout_sys_t *sys = aout->sys;
695 snd_pcm_t *pcm = aout->sys->pcm;
697 var_DelCallback (obj, "audio-device", aout_ChannelsRestart, NULL);
704 * Converts from VLC to ALSA order for 7.1.
705 * VLC has middle channels in position 2 and 3, ALSA in position 6 and 7.
707 static void Reorder71 (void *p, size_t n, unsigned size)
712 for (uint64_t *ptr = p; n > 0; ptr += 4, n--)
714 uint64_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
715 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
719 for (uint32_t *ptr = p; n > 0; ptr += 4, n--)
721 uint32_t middle = ptr[1], c_lfe = ptr[2], rear = ptr[3];
722 ptr[1] = c_lfe; ptr[2] = rear; ptr[3] = middle;
727 for (uint16_t *ptr = p; n > 0; n--)
729 uint16_t middle[size];
730 memcpy (middle, ptr + size, size * 2);
732 memcpy (ptr, ptr + size, size * 2);
734 memcpy (ptr, ptr + size, size * 2);
736 memcpy (ptr, middle, size * 2);
744 /*****************************************************************************
745 * config variable callback
746 *****************************************************************************/
747 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
748 vlc_value_t newval, vlc_value_t oldval, void *p_unused )
750 module_config_t *p_item;
755 p_item = config_FindConfig( p_this, psz_name );
756 if( !p_item ) return VLC_SUCCESS;
758 /* Clear-up the current list */
763 /* Keep the first entrie */
764 for( i = 1; i < p_item->i_list; i++ )
766 free( (char *)p_item->ppsz_list[i] );
767 free( (char *)p_item->ppsz_list_text[i] );
769 /* TODO: Remove when no more needed */
770 p_item->ppsz_list[i] = NULL;
771 p_item->ppsz_list_text[i] = NULL;
775 GetDevices (p_this, p_item, "default");
781 static void GetDevices (vlc_object_t *obj, module_config_t *item,
782 const char *prefs_dev)
785 bool hinted_default = false;
786 bool hinted_prefs = !strcmp (prefs_dev, "default");
788 msg_Dbg(obj, "Available ALSA PCM devices:");
790 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
793 for (size_t i = 0; hints[i] != NULL; i++)
795 void *hint = hints[i];
797 char *name = snd_device_name_get_hint(hint, "NAME");
798 if (unlikely(name == NULL))
801 char *desc = snd_device_name_get_hint(hint, "DESC");
803 for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
805 msg_Dbg(obj, "%s (%s)", (desc != NULL) ? desc : name, name);
807 if (!strcmp (name, "default"))
808 hinted_default = true;
809 if (!strcmp (name, prefs_dev))
814 item->ppsz_list = xrealloc(item->ppsz_list,
815 (item->i_list + 2) * sizeof(char *));
816 item->ppsz_list_text = xrealloc(item->ppsz_list_text,
817 (item->i_list + 2) * sizeof(char *));
818 item->ppsz_list[item->i_list] = name;
821 item->ppsz_list_text[item->i_list] = desc;
826 vlc_value_t val, text;
828 val.psz_string = name;
829 text.psz_string = desc;
830 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
836 snd_device_name_free_hint(hints);
840 item->ppsz_list[item->i_list] = NULL;
841 item->ppsz_list_text[item->i_list] = NULL;
845 vlc_value_t val, text;
849 val.psz_string = (char *)"default";
850 text.psz_string = (char *)N_("Default");
851 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
854 val.psz_string = (char *)prefs_dev;
857 text.psz_string = (char *)N_("VLC preferences");
858 var_Change(obj, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
860 var_Change(obj, "audio-device", VLC_VAR_SETVALUE, &val, NULL);