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 unsigned rate; /**< Sample rate */
47 uint8_t chans_table[AOUT_CHAN_MAX]; /**< Channels order table */
48 uint8_t chans_to_reorder; /**< Number of channels to reorder */
49 uint8_t bits; /**< Bits per sample per channel */
58 #define A52_FRAME_NB 1536
60 static int Open (vlc_object_t *);
61 static void Close (vlc_object_t *);
62 static int EnumDevices (vlc_object_t *, char const *, char ***, char ***);
64 #define AUDIO_DEV_TEXT N_("Audio output device")
65 #define AUDIO_DEV_LONGTEXT N_("Audio output device (using ALSA syntax).")
67 #define AUDIO_CHAN_TEXT N_("Audio output channels")
68 #define AUDIO_CHAN_LONGTEXT N_("Channels available for audio output. " \
69 "If the input has more channels than the output, it will be down-mixed. " \
70 "This parameter is ignored when digital pass-through is active.")
71 static const int channels[] = {
72 AOUT_CHAN_CENTER, AOUT_CHANS_STEREO, AOUT_CHANS_4_0, AOUT_CHANS_4_1,
73 AOUT_CHANS_5_0, AOUT_CHANS_5_1, AOUT_CHANS_7_1,
75 static const char *const channels_text[] = {
76 N_("Mono"), N_("Stereo"), N_("Surround 4.0"), N_("Surround 4.1"),
77 N_("Surround 5.0"), N_("Surround 5.1"), N_("Surround 7.1"),
81 set_shortname( "ALSA" )
82 set_description( N_("ALSA audio output") )
83 set_category( CAT_AUDIO )
84 set_subcategory( SUBCAT_AUDIO_AOUT )
85 add_string ("alsa-audio-device", "default",
86 AUDIO_DEV_TEXT, AUDIO_DEV_LONGTEXT, false)
87 change_string_cb (EnumDevices)
88 add_integer ("alsa-audio-channels", AOUT_CHANS_FRONT,
89 AUDIO_CHAN_TEXT, AUDIO_CHAN_LONGTEXT, false)
90 change_integer_list (channels, channels_text)
92 set_capability( "audio output", 150 )
93 set_callbacks( Open, Close )
97 /** Helper for ALSA -> VLC debugging output */
98 static void Dump (vlc_object_t *obj, const char *msg,
99 int (*cb)(void *, snd_output_t *), void *p)
101 snd_output_t *output;
104 if (unlikely(snd_output_buffer_open (&output)))
107 int val = cb (p, output);
110 msg_Warn (obj, "cannot get info: %s", snd_strerror (val));
114 size_t len = snd_output_buffer_string (output, &str);
115 if (len > 0 && str[len - 1])
116 len--; /* strip trailing newline */
117 msg_Dbg (obj, "%s%.*s", msg, (int)len, str);
118 snd_output_close (output);
120 #define Dump(o, m, cb, p) \
121 Dump(VLC_OBJECT(o), m, (int (*)(void *, snd_output_t *))(cb), p)
123 static void DumpDevice (vlc_object_t *obj, snd_pcm_t *pcm)
125 snd_pcm_info_t *info;
127 Dump (obj, " ", snd_pcm_dump, pcm);
128 snd_pcm_info_alloca (&info);
129 if (snd_pcm_info (pcm, info) == 0)
131 msg_Dbg (obj, " device name : %s", snd_pcm_info_get_name (info));
132 msg_Dbg (obj, " device ID : %s", snd_pcm_info_get_id (info));
133 msg_Dbg (obj, " subdevice name: %s",
134 snd_pcm_info_get_subdevice_name (info));
138 static void DumpDeviceStatus (vlc_object_t *obj, snd_pcm_t *pcm)
140 snd_pcm_status_t *status;
142 snd_pcm_status_alloca (&status);
143 snd_pcm_status (pcm, status);
144 Dump (obj, "current status:\n", snd_pcm_status_dump, status);
146 #define DumpDeviceStatus(o, p) DumpDeviceStatus(VLC_OBJECT(o), p)
148 static unsigned SetupChannelsUnknown (vlc_object_t *obj,
149 uint16_t *restrict mask)
151 uint16_t map = var_InheritInteger (obj, "alsa-audio-channels");
152 uint16_t chans = *mask & map;
154 if (unlikely(chans == 0)) /* WTH? */
155 chans = AOUT_CHANS_STEREO;
157 if (popcount (chans) < popcount (*mask))
158 msg_Dbg (obj, "downmixing from %u to %u channels",
159 popcount (*mask), popcount (chans));
161 msg_Dbg (obj, "keeping %u channels", popcount (chans));
166 #if (SND_LIB_VERSION >= 0x01001B)
167 static const uint16_t vlc_chans[] = {
168 [SND_CHMAP_MONO] = AOUT_CHAN_CENTER,
169 [SND_CHMAP_FL] = AOUT_CHAN_LEFT,
170 [SND_CHMAP_FR] = AOUT_CHAN_RIGHT,
171 [SND_CHMAP_RL] = AOUT_CHAN_REARLEFT,
172 [SND_CHMAP_RR] = AOUT_CHAN_REARRIGHT,
173 [SND_CHMAP_FC] = AOUT_CHAN_CENTER,
174 [SND_CHMAP_LFE] = AOUT_CHAN_LFE,
175 [SND_CHMAP_SL] = AOUT_CHAN_MIDDLELEFT,
176 [SND_CHMAP_SR] = AOUT_CHAN_MIDDLERIGHT,
177 [SND_CHMAP_RC] = AOUT_CHAN_REARCENTER,
180 static int Map2Mask (vlc_object_t *obj, const snd_pcm_chmap_t *restrict map)
184 for (unsigned i = 0; i < map->channels; i++)
186 const unsigned pos = map->pos[i];
187 uint_fast16_t vlc_chan = 0;
189 if (pos < sizeof (vlc_chans) / sizeof (vlc_chans[0]))
190 vlc_chan = vlc_chans[pos];
193 msg_Dbg (obj, " %s channel %u position %u", "unsupported", i, pos);
198 msg_Dbg (obj, " %s channel %u position %u", "duplicate", i, pos);
207 * Compares a fixed ALSA channels map with the VLC channels order.
209 static unsigned SetupChannelsFixed(const snd_pcm_chmap_t *restrict map,
210 uint16_t *restrict mask, uint8_t *restrict tab)
212 uint32_t chans_out[AOUT_CHAN_MAX];
214 for (unsigned i = 0; i < map->channels; i++)
216 uint_fast16_t vlc_chan = vlc_chans[map->pos[i]];
218 chans_out[i] = vlc_chan;
222 return aout_CheckChannelReorder(NULL, chans_out, *mask, tab);
226 * Negotiate channels mapping.
228 static unsigned SetupChannels (vlc_object_t *obj, snd_pcm_t *pcm,
229 uint16_t *restrict mask, uint8_t *restrict tab)
231 snd_pcm_chmap_query_t **maps = snd_pcm_query_chmaps (pcm);
233 { /* Fallback to manual configuration */
234 msg_Dbg(obj, "channels map not provided");
235 return SetupChannelsUnknown (obj, mask);
238 /* Find most appropriate available channels map */
239 unsigned best_offset;
240 unsigned best_score = 0;
242 for (snd_pcm_chmap_query_t *const *p = maps; *p != NULL; p++)
244 snd_pcm_chmap_query_t *map = *p;
248 case SND_CHMAP_TYPE_FIXED:
249 case SND_CHMAP_TYPE_PAIRED:
250 case SND_CHMAP_TYPE_VAR:
253 msg_Err (obj, "unknown channels map type %u", map->type);
257 int chans = Map2Mask (obj, &map->map);
261 unsigned score = popcount (chans & *mask);
262 if (score > best_score)
264 best_offset = p - maps;
271 msg_Err (obj, "cannot find supported channels map");
272 snd_pcm_free_chmaps (maps);
273 return SetupChannelsUnknown (obj, mask);
276 const snd_pcm_chmap_t *map = &maps[best_offset]->map;
277 msg_Dbg (obj, "using channels map %u, type %u, %u channel(s)", best_offset,
278 maps[best_offset]->type, best_score);
280 /* Setup channels map */
281 unsigned to_reorder = SetupChannelsFixed(map, mask, tab);
283 /* TODO: avoid reordering for PAIRED and VAR types */
284 //snd_pcm_set_chmap (pcm, ...)
286 snd_pcm_free_chmaps (maps);
289 #else /* (SND_LIB_VERSION < 0x01001B) */
290 # define SetupChannels(obj, pcm, mask, tab) \
291 SetupChannelsUnknown(obj, mask)
294 static int TimeGet (audio_output_t *aout, mtime_t *);
295 static void Play (audio_output_t *, block_t *);
296 static void Pause (audio_output_t *, bool, mtime_t);
297 static void PauseDummy (audio_output_t *, bool, mtime_t);
298 static void Flush (audio_output_t *, bool);
300 /** Initializes an ALSA playback stream */
301 static int Start (audio_output_t *aout, audio_sample_format_t *restrict fmt)
303 aout_sys_t *sys = aout->sys;
304 snd_pcm_format_t pcm_format; /* ALSA sample format */
307 switch (fmt->i_format)
310 pcm_format = SND_PCM_FORMAT_FLOAT64_BE;
313 pcm_format = SND_PCM_FORMAT_FLOAT64_LE;
316 pcm_format = SND_PCM_FORMAT_FLOAT_BE;
319 pcm_format = SND_PCM_FORMAT_FLOAT_LE;
322 pcm_format = SND_PCM_FORMAT_S32_BE;
325 pcm_format = SND_PCM_FORMAT_S32_LE;
328 pcm_format = SND_PCM_FORMAT_S24_3BE;
331 pcm_format = SND_PCM_FORMAT_S24_3LE;
334 pcm_format = SND_PCM_FORMAT_U24_3BE;
337 pcm_format = SND_PCM_FORMAT_U24_3LE;
340 pcm_format = SND_PCM_FORMAT_S16_BE;
343 pcm_format = SND_PCM_FORMAT_S16_LE;
346 pcm_format = SND_PCM_FORMAT_U16_BE;
349 pcm_format = SND_PCM_FORMAT_U16_LE;
352 pcm_format = SND_PCM_FORMAT_U8;
355 if (AOUT_FMT_SPDIF(fmt))
356 spdif = var_InheritBool (aout, "spdif");
359 fmt->i_format = VLC_CODEC_SPDIFL;
360 pcm_format = SND_PCM_FORMAT_S16;
365 fmt->i_format = VLC_CODEC_FL32;
366 pcm_format = SND_PCM_FORMAT_FLOAT;
370 fmt->i_format = VLC_CODEC_S16N;
371 pcm_format = SND_PCM_FORMAT_S16;
375 const char *device = sys->device;
377 /* Choose the IEC device for S/PDIF output */
378 if (spdif && !strcmp (device, "default"))
385 case freq: aes3 = IEC958_AES3_CON_FS_ ## freq; break;
386 FS( 44100) /* def. */ FS( 48000) FS( 32000)
387 FS( 22050) FS( 24000)
388 FS( 88200) FS(768000) FS( 96000)
389 FS(176400) FS(192000)
392 aes3 = IEC958_AES3_CON_FS_NOTID;
396 if (asprintf (&devbuf,
397 "iec958:AES0=0x%x,AES1=0x%x,AES2=0x%x,AES3=0x%x",
398 IEC958_AES0_CON_EMPHASIS_NONE | IEC958_AES0_NONAUDIO,
399 IEC958_AES1_CON_ORIGINAL | IEC958_AES1_CON_PCM_CODER,
405 /* Open the device */
407 /* VLC always has a resampler. No need for ALSA's. */
408 const int mode = SND_PCM_NO_AUTO_RESAMPLE;
410 int val = snd_pcm_open (&pcm, device, SND_PCM_STREAM_PLAYBACK, mode);
414 msg_Err (aout, "cannot open ALSA device \"%s\": %s", sys->device,
416 dialog_Fatal (aout, _("Audio output failed"),
417 _("The audio device \"%s\" could not be used:\n%s."),
418 sys->device, snd_strerror (val));
423 /* Print some potentially useful debug */
424 msg_Dbg (aout, "using ALSA device: %s", sys->device);
425 DumpDevice (VLC_OBJECT(aout), pcm);
427 /* Get Initial hardware parameters */
428 snd_pcm_hw_params_t *hw;
431 snd_pcm_hw_params_alloca (&hw);
432 snd_pcm_hw_params_any (pcm, hw);
433 Dump (aout, "initial hardware setup:\n", snd_pcm_hw_params_dump, hw);
435 val = snd_pcm_hw_params_set_rate_resample(pcm, hw, 0);
438 msg_Err (aout, "cannot disable resampling: %s", snd_strerror (val));
442 val = snd_pcm_hw_params_set_access (pcm, hw,
443 SND_PCM_ACCESS_RW_INTERLEAVED);
446 msg_Err (aout, "cannot set access mode: %s", snd_strerror (val));
450 /* Set sample format */
451 if (snd_pcm_hw_params_test_format (pcm, hw, pcm_format) == 0)
454 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_FLOAT) == 0)
456 fmt->i_format = VLC_CODEC_FL32;
457 pcm_format = SND_PCM_FORMAT_FLOAT;
460 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S32) == 0)
462 fmt->i_format = VLC_CODEC_S32N;
463 pcm_format = SND_PCM_FORMAT_S32;
466 if (snd_pcm_hw_params_test_format (pcm, hw, SND_PCM_FORMAT_S16) == 0)
468 fmt->i_format = VLC_CODEC_S16N;
469 pcm_format = SND_PCM_FORMAT_S16;
473 msg_Err (aout, "no supported sample format");
477 val = snd_pcm_hw_params_set_format (pcm, hw, pcm_format);
480 msg_Err (aout, "cannot set sample format: %s", snd_strerror (val));
484 /* Set channels count */
488 sys->chans_to_reorder = SetupChannels (VLC_OBJECT(aout), pcm,
489 &fmt->i_physical_channels, sys->chans_table);
490 channels = popcount (fmt->i_physical_channels);
494 fmt->i_original_channels = fmt->i_physical_channels;
496 /* By default, ALSA plug will pad missing channels with zeroes, which is
497 * usually fine. However, it will also discard extraneous channels, which
498 * is not acceptable. Thus the user must configure the physically
499 * available channels, and VLC will downmix if needed. */
500 val = snd_pcm_hw_params_set_channels (pcm, hw, channels);
503 msg_Err (aout, "cannot set %u channels: %s", channels,
508 /* Set sample rate */
509 val = snd_pcm_hw_params_set_rate_near (pcm, hw, &fmt->i_rate, NULL);
512 msg_Err (aout, "cannot set sample rate: %s", snd_strerror (val));
515 sys->rate = fmt->i_rate;
517 /* Set buffer size */
518 param = AOUT_MAX_ADVANCE_TIME;
519 val = snd_pcm_hw_params_set_buffer_time_near (pcm, hw, ¶m, NULL);
522 msg_Err (aout, "cannot set buffer duration: %s", snd_strerror (val));
526 val = snd_pcm_hw_params_get_buffer_time (hw, ¶m, NULL);
529 msg_Warn (aout, "cannot get buffer time: %s", snd_strerror(val));
530 param = AOUT_MIN_PREPARE_TIME;
534 #else /* work-around for period-long latency outputs (e.g. PulseAudio): */
535 param = AOUT_MIN_PREPARE_TIME;
537 val = snd_pcm_hw_params_set_period_time_near (pcm, hw, ¶m, NULL);
540 msg_Err (aout, "cannot set period: %s", snd_strerror (val));
544 /* Commit hardware parameters */
545 val = snd_pcm_hw_params (pcm, hw);
548 msg_Err (aout, "cannot commit hardware parameters: %s",
552 Dump (aout, "final HW setup:\n", snd_pcm_hw_params_dump, hw);
554 /* Get Initial software parameters */
555 snd_pcm_sw_params_t *sw;
557 snd_pcm_sw_params_alloca (&sw);
558 snd_pcm_sw_params_current (pcm, sw);
559 Dump (aout, "initial software parameters:\n", snd_pcm_sw_params_dump, sw);
562 //snd_pcm_sw_params_set_avail_min( pcm, sw, i_period_size );
564 val = snd_pcm_sw_params_set_start_threshold (pcm, sw, 1);
567 msg_Err( aout, "unable to set start threshold (%s)",
568 snd_strerror( val ) );
573 /* Commit software parameters. */
574 val = snd_pcm_sw_params (pcm, sw);
577 msg_Err (aout, "cannot commit software parameters: %s",
581 Dump (aout, "final software parameters:\n", snd_pcm_sw_params_dump, sw);
583 val = snd_pcm_prepare (pcm);
586 msg_Err (aout, "cannot prepare device: %s", snd_strerror (val));
590 /* Setup audio_output_t */
593 fmt->i_bytes_per_frame = AOUT_SPDIF_SIZE;
594 fmt->i_frame_length = A52_FRAME_NB;
598 aout_FormatPrepare (fmt);
599 sys->bits = fmt->i_bitspersample;
602 aout->time_get = TimeGet;
604 if (snd_pcm_hw_params_can_pause (hw))
608 aout->pause = PauseDummy;
609 msg_Warn (aout, "device cannot be paused");
612 aout_SoftVolumeStart (aout);
620 static int TimeGet (audio_output_t *aout, mtime_t *restrict delay)
622 aout_sys_t *sys = aout->sys;
623 snd_pcm_sframes_t frames;
625 int val = snd_pcm_delay (sys->pcm, &frames);
628 msg_Err (aout, "cannot estimate delay: %s", snd_strerror (val));
631 *delay = frames * CLOCK_FREQ / sys->rate;
636 * Queues one audio buffer to the hardware.
638 static void Play (audio_output_t *aout, block_t *block)
640 aout_sys_t *sys = aout->sys;
642 if (sys->chans_to_reorder != 0)
643 aout_ChannelReorder(block->p_buffer, block->i_buffer,
644 sys->chans_to_reorder, sys->chans_table, sys->bits);
646 snd_pcm_t *pcm = sys->pcm;
648 /* TODO: better overflow handling */
649 /* TODO: no period wake ups */
651 while (block->i_nb_samples > 0)
653 snd_pcm_sframes_t frames;
655 frames = snd_pcm_writei (pcm, block->p_buffer, block->i_nb_samples);
658 size_t bytes = snd_pcm_frames_to_bytes (pcm, frames);
659 block->i_nb_samples -= frames;
660 block->p_buffer += bytes;
661 block->i_buffer -= bytes;
666 int val = snd_pcm_recover (pcm, frames, 1);
669 msg_Err (aout, "cannot recover playback stream: %s",
671 DumpDeviceStatus (aout, pcm);
674 msg_Warn (aout, "cannot write samples: %s", snd_strerror (frames));
677 block_Release (block);
681 * Pauses/resumes the audio playback.
683 static void Pause (audio_output_t *aout, bool pause, mtime_t date)
685 snd_pcm_t *pcm = aout->sys->pcm;
687 int val = snd_pcm_pause (pcm, pause);
689 PauseDummy (aout, pause, date);
692 static void PauseDummy (audio_output_t *aout, bool pause, mtime_t date)
694 snd_pcm_t *pcm = aout->sys->pcm;
696 /* Stupid device cannot pause. Discard samples. */
700 snd_pcm_prepare (pcm);
705 * Flushes/drains the audio playback buffer.
707 static void Flush (audio_output_t *aout, bool wait)
709 snd_pcm_t *pcm = aout->sys->pcm;
715 snd_pcm_prepare (pcm);
720 * Releases the audio output.
722 static void Stop (audio_output_t *aout)
724 aout_sys_t *sys = aout->sys;
725 snd_pcm_t *pcm = sys->pcm;
732 * Enumerates ALSA output devices.
734 static int EnumDevices(vlc_object_t *obj, char const *varname,
735 char ***restrict idp, char ***restrict namep)
739 msg_Dbg (obj, "Available ALSA PCM devices:");
740 if (snd_device_name_hint(-1, "pcm", &hints) < 0)
743 char **ids = NULL, **names = NULL;
746 for (size_t i = 0; hints[i] != NULL; i++)
748 void *hint = hints[i];
750 char *name = snd_device_name_get_hint(hint, "NAME");
751 if (unlikely(name == NULL))
754 char *desc = snd_device_name_get_hint(hint, "DESC");
756 for (char *lf = strchr(desc, '\n'); lf; lf = strchr(lf, '\n'))
758 msg_Dbg (obj, "%s (%s)", (desc != NULL) ? desc : name, name);
760 ids = xrealloc (ids, (n + 1) * sizeof (*ids));
761 names = xrealloc (names, (n + 1) * sizeof (*names));
767 snd_device_name_free_hint(hints);
774 static int DevicesEnum (audio_output_t *aout, char ***idp, char ***namep)
776 return EnumDevices (VLC_OBJECT(aout), NULL, idp, namep);
779 static int DeviceSelect (audio_output_t *aout, const char *id)
781 aout_sys_t *sys = aout->sys;
783 char *device = strdup (id ? id : "default");
784 if (unlikely(device == NULL))
788 sys->device = device;
789 aout_DeviceReport (aout, device);
790 aout_RestartRequest (aout, AOUT_RESTART_OUTPUT);
794 static int Open(vlc_object_t *obj)
796 audio_output_t *aout = (audio_output_t *)obj;
797 aout_sys_t *sys = malloc (sizeof (*sys));
799 if (unlikely(sys == NULL))
801 sys->device = var_InheritString (aout, "alsa-audio-device");
802 if (unlikely(sys->device == NULL))
808 aout_SoftVolumeInit (aout);
809 aout->device_enum = DevicesEnum;
810 aout->device_select = DeviceSelect;
811 aout_DeviceReport (aout, sys->device);
818 static void Close(vlc_object_t *obj)
820 audio_output_t *aout = (audio_output_t *)obj;
821 aout_sys_t *sys = aout->sys;