AlsaOutputPlugin.cxx 22 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
21
#include "AlsaOutputPlugin.hxx"
22
#include "../OutputAPI.hxx"
23
#include "../Wrapper.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "mixer/MixerList.hxx"
25
#include "pcm/PcmExport.hxx"
26
#include "config/ConfigError.hxx"
27
#include "util/Manual.hxx"
28 29
#include "util/Error.hxx"
#include "util/Domain.hxx"
30
#include "util/ConstBuffer.hxx"
31
#include "Log.hxx"
32

33
#include <alsa/asoundlib.h>
34

35 36
#include <string>

37 38 39 40 41
#if SND_LIB_VERSION >= 0x1001c
/* alsa-lib supports DSD since version 1.0.27.1 */
#define HAVE_ALSA_DSD
#endif

42 43
static const char default_device[] = "default";

44
static constexpr unsigned MPD_ALSA_BUFFER_TIME_US = 500000;
45

46
static constexpr unsigned MPD_ALSA_RETRY_NR = 5;
47

Avuton Olrich's avatar
Avuton Olrich committed
48 49
typedef snd_pcm_sframes_t alsa_writei_t(snd_pcm_t * pcm, const void *buffer,
					snd_pcm_uframes_t size);
50

51
struct AlsaOutput {
52
	AudioOutput base;
53

54
	Manual<PcmExport> pcm_export;
55

56 57 58 59 60
	/**
	 * The configured name of the ALSA device; empty for the
	 * default device
	 */
	std::string device;
61

Max Kellermann's avatar
Max Kellermann committed
62 63 64
	/** use memory mapped I/O? */
	bool use_mmap;

65
	/**
66
	 * Enable DSD over PCM according to the DoP standard standard?
67
	 *
68
	 * @see http://dsd-guide.com/dop-open-standard
69
	 */
70
	bool dop;
71

Max Kellermann's avatar
Max Kellermann committed
72 73 74 75 76 77
	/** libasound's buffer_time setting (in microseconds) */
	unsigned int buffer_time;

	/** libasound's period_time setting (in microseconds) */
	unsigned int period_time;

78 79 80
	/** the mode flags passed to snd_pcm_open */
	int mode;

Max Kellermann's avatar
Max Kellermann committed
81
	/** the libasound PCM device handle */
Max Kellermann's avatar
Max Kellermann committed
82
	snd_pcm_t *pcm;
Max Kellermann's avatar
Max Kellermann committed
83 84 85 86 87 88

	/**
	 * a pointer to the libasound writei() function, which is
	 * snd_pcm_writei() or snd_pcm_mmap_writei(), depending on the
	 * use_mmap configuration
	 */
Avuton Olrich's avatar
Avuton Olrich committed
89
	alsa_writei_t *writei;
Max Kellermann's avatar
Max Kellermann committed
90

91 92 93 94 95 96 97 98 99
	/**
	 * The size of one audio frame passed to method play().
	 */
	size_t in_frame_size;

	/**
	 * The size of one audio frame passed to libasound.
	 */
	size_t out_frame_size;
100 101 102 103 104 105 106 107 108 109

	/**
	 * The size of one period, in number of frames.
	 */
	snd_pcm_uframes_t period_frames;

	/**
	 * The number of frames written in the current period.
	 */
	snd_pcm_uframes_t period_position;
110

111
	/**
112 113 114 115 116 117 118 119
	 * Do we need to call snd_pcm_prepare() before the next write?
	 * It means that we put the device to SND_PCM_STATE_SETUP by
	 * calling snd_pcm_drop().
	 *
	 * Without this flag, we could easily recover after a failed
	 * optimistic write (returning -EBADFD), but the Raspberry Pi
	 * audio driver is infamous for generating ugly artefacts from
	 * this.
120
	 */
121
	bool must_prepare;
122

123 124 125 126 127
	/**
	 * This buffer gets allocated after opening the ALSA device.
	 * It contains silence samples, enough to fill one period (see
	 * #period_frames).
	 */
128
	uint8_t *silence;
129

130 131 132
	AlsaOutput()
		:base(alsa_output_plugin),
		 mode(0), writei(snd_pcm_writei) {
133 134
	}

135 136 137 138 139 140 141 142 143 144
	~AlsaOutput() {
		/* free libasound's config cache */
		snd_config_update_free_global();
	}

	gcc_pure
	const char *GetDevice() {
		return device.empty() ? default_device : device.c_str();
	}

145 146
	bool Configure(const ConfigBlock &block, Error &error);
	static AlsaOutput *Create(const ConfigBlock &block, Error &error);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

	bool Enable(Error &error);
	void Disable();

	bool Open(AudioFormat &audio_format, Error &error);
	void Close();

	size_t Play(const void *chunk, size_t size, Error &error);
	void Drain();
	void Cancel();

private:
	bool SetupDop(AudioFormat audio_format,
		      bool *shift8_r, bool *packed_r, bool *reverse_endian_r,
		      Error &error);
	bool SetupOrDop(AudioFormat &audio_format, Error &error);

	int Recover(int err);

	/**
	 * Write silence to the ALSA device.
	 */
	void WriteSilence(snd_pcm_uframes_t nframes) {
		writei(pcm, silence, nframes);
	}

Max Kellermann's avatar
Max Kellermann committed
173
};
174

175
static constexpr Domain alsa_output_domain("alsa_output");
176

177
inline bool
178
AlsaOutput::Configure(const ConfigBlock &block, Error &error)
179
{
180
	if (!base.Configure(block, error))
181 182
		return false;

183
	device = block.GetBlockValue("device", "");
184

185
	use_mmap = block.GetBlockValue("use_mmap", false);
186

187
	dop = block.GetBlockValue("dop", false) ||
188
		/* legacy name from MPD 0.18 and older: */
189
		block.GetBlockValue("dsd_usb", false);
190

191
	buffer_time = block.GetBlockValue("buffer_time",
192
					      MPD_ALSA_BUFFER_TIME_US);
193
	period_time = block.GetBlockValue("period_time", 0u);
194

195
#ifdef SND_PCM_NO_AUTO_RESAMPLE
196
	if (!block.GetBlockValue("auto_resample", true))
197
		mode |= SND_PCM_NO_AUTO_RESAMPLE;
198
#endif
199

200
#ifdef SND_PCM_NO_AUTO_CHANNELS
201
	if (!block.GetBlockValue("auto_channels", true))
202
		mode |= SND_PCM_NO_AUTO_CHANNELS;
203
#endif
204

205
#ifdef SND_PCM_NO_AUTO_FORMAT
206
	if (!block.GetBlockValue("auto_format", true))
207
		mode |= SND_PCM_NO_AUTO_FORMAT;
208
#endif
209 210

	return true;
211 212
}

213
inline AlsaOutput *
214
AlsaOutput::Create(const ConfigBlock &block, Error &error)
Avuton Olrich's avatar
Avuton Olrich committed
215
{
216
	AlsaOutput *ad = new AlsaOutput();
217

218
	if (!ad->Configure(block, error)) {
219
		delete ad;
220
		return nullptr;
221 222
	}

223
	return ad;
224 225
}

226 227
inline bool
AlsaOutput::Enable(gcc_unused Error &error)
228
{
229
	pcm_export.Construct();
230 231 232
	return true;
}

233 234
inline void
AlsaOutput::Disable()
235
{
236
	pcm_export.Destruct();
237 238
}

Max Kellermann's avatar
Max Kellermann committed
239
static bool
240
alsa_test_default_device()
241
{
Avuton Olrich's avatar
Avuton Olrich committed
242
	snd_pcm_t *handle;
243

244
	int ret = snd_pcm_open(&handle, default_device,
245
			       SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
Avuton Olrich's avatar
Avuton Olrich committed
246
	if (ret) {
247 248 249
		FormatError(alsa_output_domain,
			    "Error opening default ALSA device: %s",
			    snd_strerror(-ret));
250
		return false;
Avuton Olrich's avatar
Avuton Olrich committed
251 252
	} else
		snd_pcm_close(handle);
253

254
	return true;
255 256
}

257 258 259 260 261
/**
 * Convert MPD's #SampleFormat enum to libasound's snd_pcm_format_t
 * enum.  Returns SND_PCM_FORMAT_UNKNOWN if there is no according ALSA
 * PCM format.
 */
Max Kellermann's avatar
Max Kellermann committed
262
static snd_pcm_format_t
263
get_bitformat(SampleFormat sample_format)
264
{
265
	switch (sample_format) {
266
	case SampleFormat::UNDEFINED:
267 268
		return SND_PCM_FORMAT_UNKNOWN;

269
	case SampleFormat::DSD:
270 271 272
#ifdef HAVE_ALSA_DSD
		return SND_PCM_FORMAT_DSD_U8;
#else
273
		return SND_PCM_FORMAT_UNKNOWN;
274
#endif
275

276
	case SampleFormat::S8:
277 278
		return SND_PCM_FORMAT_S8;

279
	case SampleFormat::S16:
280 281
		return SND_PCM_FORMAT_S16;

282
	case SampleFormat::S24_P32:
283 284
		return SND_PCM_FORMAT_S24;

285
	case SampleFormat::S32:
286
		return SND_PCM_FORMAT_S32;
287

288
	case SampleFormat::FLOAT:
289
		return SND_PCM_FORMAT_FLOAT;
290
	}
291 292

	assert(false);
293
	gcc_unreachable();
294 295
}

296 297 298 299
/**
 * Determine the byte-swapped PCM format.  Returns
 * SND_PCM_FORMAT_UNKNOWN if the format cannot be byte-swapped.
 */
300 301 302
static snd_pcm_format_t
byteswap_bitformat(snd_pcm_format_t fmt)
{
303
	switch (fmt) {
304 305 306 307 308
	case SND_PCM_FORMAT_S16_LE: return SND_PCM_FORMAT_S16_BE;
	case SND_PCM_FORMAT_S24_LE: return SND_PCM_FORMAT_S24_BE;
	case SND_PCM_FORMAT_S32_LE: return SND_PCM_FORMAT_S32_BE;
	case SND_PCM_FORMAT_S16_BE: return SND_PCM_FORMAT_S16_LE;
	case SND_PCM_FORMAT_S24_BE: return SND_PCM_FORMAT_S24_LE;
309 310 311 312 313 314 315

	case SND_PCM_FORMAT_S24_3BE:
		return SND_PCM_FORMAT_S24_3LE;

	case SND_PCM_FORMAT_S24_3LE:
		return SND_PCM_FORMAT_S24_3BE;

316 317 318 319
	case SND_PCM_FORMAT_S32_BE: return SND_PCM_FORMAT_S32_LE;
	default: return SND_PCM_FORMAT_UNKNOWN;
	}
}
320

321 322 323 324
/**
 * Check if there is a "packed" version of the give PCM format.
 * Returns SND_PCM_FORMAT_UNKNOWN if not.
 */
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
static snd_pcm_format_t
alsa_to_packed_format(snd_pcm_format_t fmt)
{
	switch (fmt) {
	case SND_PCM_FORMAT_S24_LE:
		return SND_PCM_FORMAT_S24_3LE;

	case SND_PCM_FORMAT_S24_BE:
		return SND_PCM_FORMAT_S24_3BE;

	default:
		return SND_PCM_FORMAT_UNKNOWN;
	}
}

340 341 342 343
/**
 * Attempts to configure the specified sample format.  On failure,
 * fall back to the packed version.
 */
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
static int
alsa_try_format_or_packed(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
			  snd_pcm_format_t fmt, bool *packed_r)
{
	int err = snd_pcm_hw_params_set_format(pcm, hwparams, fmt);
	if (err == 0)
		*packed_r = false;

	if (err != -EINVAL)
		return err;

	fmt = alsa_to_packed_format(fmt);
	if (fmt == SND_PCM_FORMAT_UNKNOWN)
		return -EINVAL;

	err = snd_pcm_hw_params_set_format(pcm, hwparams, fmt);
	if (err == 0)
		*packed_r = true;

	return err;
}

366
/**
367 368
 * Attempts to configure the specified sample format, and tries the
 * reversed host byte order if was not supported.
369 370 371
 */
static int
alsa_output_try_format(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
372
		       SampleFormat sample_format,
373
		       bool *packed_r, bool *reverse_endian_r)
374 375 376 377 378
{
	snd_pcm_format_t alsa_format = get_bitformat(sample_format);
	if (alsa_format == SND_PCM_FORMAT_UNKNOWN)
		return -EINVAL;

379 380
	int err = alsa_try_format_or_packed(pcm, hwparams, alsa_format,
					    packed_r);
381
	if (err == 0)
382
		*reverse_endian_r = false;
383

384 385
	if (err != -EINVAL)
		return err;
386

387
	alsa_format = byteswap_bitformat(alsa_format);
388 389 390
	if (alsa_format == SND_PCM_FORMAT_UNKNOWN)
		return -EINVAL;

391
	err = alsa_try_format_or_packed(pcm, hwparams, alsa_format, packed_r);
392
	if (err == 0)
393
		*reverse_endian_r = true;
394 395 396 397

	return err;
}

398
/**
399
 * Configure a sample format, and probe other formats if that fails.
400
 */
401 402
static int
alsa_output_setup_format(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
403
			 AudioFormat &audio_format,
404
			 bool *packed_r, bool *reverse_endian_r)
405
{
406
	/* try the input format first */
407

408
	int err = alsa_output_try_format(pcm, hwparams,
409
					 audio_format.format,
410
					 packed_r, reverse_endian_r);
411

412
	/* if unsupported by the hardware, try other formats */
413

414
	static constexpr SampleFormat probe_formats[] = {
415 416 417 418 419
		SampleFormat::S24_P32,
		SampleFormat::S32,
		SampleFormat::S16,
		SampleFormat::S8,
		SampleFormat::UNDEFINED,
420
	};
421

422
	for (unsigned i = 0;
423
	     err == -EINVAL && probe_formats[i] != SampleFormat::UNDEFINED;
424
	     ++i) {
425 426
		const SampleFormat mpd_format = probe_formats[i];
		if (mpd_format == audio_format.format)
427
			continue;
428

429
		err = alsa_output_try_format(pcm, hwparams, mpd_format,
430
					     packed_r, reverse_endian_r);
431
		if (err == 0)
432
			audio_format.format = mpd_format;
433
	}
434

435
	return err;
436 437 438 439 440 441 442
}

/**
 * Set up the snd_pcm_t object which was opened by the caller.  Set up
 * the configured settings and the audio format.
 */
static bool
443
alsa_setup(AlsaOutput *ad, AudioFormat &audio_format,
444
	   bool *packed_r, bool *reverse_endian_r, Error &error)
445
{
446 447
	unsigned int sample_rate = audio_format.sample_rate;
	unsigned int channels = audio_format.channels;
448
	int err;
449
	const char *cmd = nullptr;
450
	unsigned retry = MPD_ALSA_RETRY_NR;
451 452 453 454 455 456
	unsigned int period_time, period_time_ro;
	unsigned int buffer_time;

	period_time_ro = period_time = ad->period_time;
configure_hw:
	/* configure HW params */
457
	snd_pcm_hw_params_t *hwparams;
458 459 460 461 462 463 464 465 466 467
	snd_pcm_hw_params_alloca(&hwparams);
	cmd = "snd_pcm_hw_params_any";
	err = snd_pcm_hw_params_any(ad->pcm, hwparams);
	if (err < 0)
		goto error;

	if (ad->use_mmap) {
		err = snd_pcm_hw_params_set_access(ad->pcm, hwparams,
						   SND_PCM_ACCESS_MMAP_INTERLEAVED);
		if (err < 0) {
468 469
			FormatWarning(alsa_output_domain,
				      "Cannot set mmap'ed mode on ALSA device \"%s\": %s",
470
				      ad->GetDevice(), snd_strerror(-err));
471 472
			LogWarning(alsa_output_domain,
				   "Falling back to direct write mode");
473 474 475 476 477 478 479 480 481 482 483 484 485 486
			ad->use_mmap = false;
		} else
			ad->writei = snd_pcm_mmap_writei;
	}

	if (!ad->use_mmap) {
		cmd = "snd_pcm_hw_params_set_access";
		err = snd_pcm_hw_params_set_access(ad->pcm, hwparams,
						   SND_PCM_ACCESS_RW_INTERLEAVED);
		if (err < 0)
			goto error;
		ad->writei = snd_pcm_writei;
	}

487
	err = alsa_output_setup_format(ad->pcm, hwparams, audio_format,
488
				       packed_r, reverse_endian_r);
Avuton Olrich's avatar
Avuton Olrich committed
489
	if (err < 0) {
490 491
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support format %s: %s",
492
			     ad->GetDevice(),
493 494
			     sample_format_to_string(audio_format.format),
			     snd_strerror(-err));
495
		return false;
496 497
	}

498 499
	snd_pcm_format_t format;
	if (snd_pcm_hw_params_get_format(hwparams, &format) == 0)
500 501 502
		FormatDebug(alsa_output_domain,
			    "format=%s (%s)", snd_pcm_format_name(format),
			    snd_pcm_format_description(format));
503

Max Kellermann's avatar
Max Kellermann committed
504
	err = snd_pcm_hw_params_set_channels_near(ad->pcm, hwparams,
Avuton Olrich's avatar
Avuton Olrich committed
505 506
						  &channels);
	if (err < 0) {
507 508
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support %i channels: %s",
509
			     ad->GetDevice(), (int)audio_format.channels,
510
			     snd_strerror(-err));
511
		return false;
512
	}
513
	audio_format.channels = (int8_t)channels;
514

Max Kellermann's avatar
Max Kellermann committed
515
	err = snd_pcm_hw_params_set_rate_near(ad->pcm, hwparams,
516
					      &sample_rate, nullptr);
517
	if (err < 0 || sample_rate == 0) {
518 519
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support %u Hz audio",
520
			     ad->GetDevice(), audio_format.sample_rate);
521
		return false;
522
	}
523
	audio_format.sample_rate = sample_rate;
524

525 526 527 528 529 530
	snd_pcm_uframes_t buffer_size_min, buffer_size_max;
	snd_pcm_hw_params_get_buffer_size_min(hwparams, &buffer_size_min);
	snd_pcm_hw_params_get_buffer_size_max(hwparams, &buffer_size_max);
	unsigned buffer_time_min, buffer_time_max;
	snd_pcm_hw_params_get_buffer_time_min(hwparams, &buffer_time_min, 0);
	snd_pcm_hw_params_get_buffer_time_max(hwparams, &buffer_time_max, 0);
531 532 533
	FormatDebug(alsa_output_domain, "buffer: size=%u..%u time=%u..%u",
		    (unsigned)buffer_size_min, (unsigned)buffer_size_max,
		    buffer_time_min, buffer_time_max);
534 535 536 537 538 539 540

	snd_pcm_uframes_t period_size_min, period_size_max;
	snd_pcm_hw_params_get_period_size_min(hwparams, &period_size_min, 0);
	snd_pcm_hw_params_get_period_size_max(hwparams, &period_size_max, 0);
	unsigned period_time_min, period_time_max;
	snd_pcm_hw_params_get_period_time_min(hwparams, &period_time_min, 0);
	snd_pcm_hw_params_get_period_time_max(hwparams, &period_time_max, 0);
541 542 543
	FormatDebug(alsa_output_domain, "period: size=%u..%u time=%u..%u",
		    (unsigned)period_size_min, (unsigned)period_size_max,
		    period_time_min, period_time_max);
544

545 546 547
	if (ad->buffer_time > 0) {
		buffer_time = ad->buffer_time;
		cmd = "snd_pcm_hw_params_set_buffer_time_near";
Max Kellermann's avatar
Max Kellermann committed
548
		err = snd_pcm_hw_params_set_buffer_time_near(ad->pcm, hwparams,
549
							     &buffer_time, nullptr);
550 551
		if (err < 0)
			goto error;
552 553
	} else {
		err = snd_pcm_hw_params_get_buffer_time(hwparams, &buffer_time,
554
							nullptr);
555 556
		if (err < 0)
			buffer_time = 0;
557
	}
558

559 560 561
	if (period_time_ro == 0 && buffer_time >= 10000) {
		period_time_ro = period_time = buffer_time / 4;

562 563 564
		FormatDebug(alsa_output_domain,
			    "default period_time = buffer_time/4 = %u/4 = %u",
			    buffer_time, period_time);
565 566
	}

567 568 569
	if (period_time_ro > 0) {
		period_time = period_time_ro;
		cmd = "snd_pcm_hw_params_set_period_time_near";
Max Kellermann's avatar
Max Kellermann committed
570
		err = snd_pcm_hw_params_set_period_time_near(ad->pcm, hwparams,
571
							     &period_time, nullptr);
572 573 574
		if (err < 0)
			goto error;
	}
575

576
	cmd = "snd_pcm_hw_params";
Max Kellermann's avatar
Max Kellermann committed
577
	err = snd_pcm_hw_params(ad->pcm, hwparams);
578
	if (err == -EPIPE && --retry > 0 && period_time_ro > 0) {
579
		period_time_ro = period_time_ro >> 1;
580 581
		goto configure_hw;
	} else if (err < 0)
Avuton Olrich's avatar
Avuton Olrich committed
582
		goto error;
583
	if (retry != MPD_ALSA_RETRY_NR)
584 585
		FormatDebug(alsa_output_domain,
			    "ALSA period_time set to %d", period_time);
586

587
	snd_pcm_uframes_t alsa_buffer_size;
588
	cmd = "snd_pcm_hw_params_get_buffer_size";
589
	err = snd_pcm_hw_params_get_buffer_size(hwparams, &alsa_buffer_size);
Avuton Olrich's avatar
Avuton Olrich committed
590 591
	if (err < 0)
		goto error;
592

593
	snd_pcm_uframes_t alsa_period_size;
594
	cmd = "snd_pcm_hw_params_get_period_size";
595
	err = snd_pcm_hw_params_get_period_size(hwparams, &alsa_period_size,
596
						nullptr);
Avuton Olrich's avatar
Avuton Olrich committed
597 598
	if (err < 0)
		goto error;
599

600
	/* configure SW params */
601
	snd_pcm_sw_params_t *swparams;
602 603
	snd_pcm_sw_params_alloca(&swparams);

604
	cmd = "snd_pcm_sw_params_current";
Max Kellermann's avatar
Max Kellermann committed
605
	err = snd_pcm_sw_params_current(ad->pcm, swparams);
Avuton Olrich's avatar
Avuton Olrich committed
606 607
	if (err < 0)
		goto error;
608 609

	cmd = "snd_pcm_sw_params_set_start_threshold";
Max Kellermann's avatar
Max Kellermann committed
610
	err = snd_pcm_sw_params_set_start_threshold(ad->pcm, swparams,
Avuton Olrich's avatar
Avuton Olrich committed
611 612 613 614
						    alsa_buffer_size -
						    alsa_period_size);
	if (err < 0)
		goto error;
615

616
	cmd = "snd_pcm_sw_params_set_avail_min";
Max Kellermann's avatar
Max Kellermann committed
617
	err = snd_pcm_sw_params_set_avail_min(ad->pcm, swparams,
Avuton Olrich's avatar
Avuton Olrich committed
618 619 620
					      alsa_period_size);
	if (err < 0)
		goto error;
621 622

	cmd = "snd_pcm_sw_params";
Max Kellermann's avatar
Max Kellermann committed
623
	err = snd_pcm_sw_params(ad->pcm, swparams);
Avuton Olrich's avatar
Avuton Olrich committed
624 625 626
	if (err < 0)
		goto error;

627 628
	FormatDebug(alsa_output_domain, "buffer_size=%u period_size=%u",
		    (unsigned)alsa_buffer_size, (unsigned)alsa_period_size);
629

630 631 632 633 634 635 636 637
	if (alsa_period_size == 0)
		/* this works around a SIGFPE bug that occurred when
		   an ALSA driver indicated period_size==0; this
		   caused a division by zero in alsa_play().  By using
		   the fallback "1", we make sure that this won't
		   happen again. */
		alsa_period_size = 1;

638 639 640
	ad->period_frames = alsa_period_size;
	ad->period_position = 0;

641 642
	ad->silence = new uint8_t[snd_pcm_frames_to_bytes(ad->pcm,
							  alsa_period_size)];
643 644 645
	snd_pcm_format_set_silence(format, ad->silence,
				   alsa_period_size * channels);

646
	return true;
647

648
error:
649 650
	error.Format(alsa_output_domain, err,
		     "Error opening ALSA device \"%s\" (%s): %s",
651
		     ad->GetDevice(), cmd, snd_strerror(-err));
652 653 654
	return false;
}

655 656 657 658
inline bool
AlsaOutput::SetupDop(const AudioFormat audio_format,
		     bool *shift8_r, bool *packed_r, bool *reverse_endian_r,
		     Error &error)
659
{
660
	assert(dop);
661
	assert(audio_format.format == SampleFormat::DSD);
662 663 664

	/* pass 24 bit to alsa_setup() */

665 666 667
	AudioFormat dop_format = audio_format;
	dop_format.format = SampleFormat::S24_P32;
	dop_format.sample_rate /= 2;
668

669
	const AudioFormat check = dop_format;
670

671
	if (!alsa_setup(this, dop_format, packed_r, reverse_endian_r, error))
672 673
		return false;

674
	/* if the device allows only 32 bit, shift all DoP
675 676 677 678
	   samples left by 8 bit and leave the lower 8 bit cleared;
	   the DSD-over-USB documentation does not specify whether
	   this is legal, but there is anecdotical evidence that this
	   is possible (and the only option for some devices) */
679 680 681
	*shift8_r = dop_format.format == SampleFormat::S32;
	if (dop_format.format == SampleFormat::S32)
		dop_format.format = SampleFormat::S24_P32;
682

683
	if (dop_format != check) {
684 685
		/* no bit-perfect playback, which is required
		   for DSD over USB */
686
		error.Format(alsa_output_domain,
687
			     "Failed to configure DSD-over-PCM on ALSA device \"%s\"",
688 689
			     GetDevice());
		delete[] silence;
690 691 692 693 694 695
		return false;
	}

	return true;
}

696 697
inline bool
AlsaOutput::SetupOrDop(AudioFormat &audio_format, Error &error)
698
{
699
	bool shift8 = false, packed, reverse_endian;
700

701
	const bool dop2 = dop &&
702
		audio_format.format == SampleFormat::DSD;
703 704 705 706 707
	const bool success = dop2
		? SetupDop(audio_format,
			   &shift8, &packed, &reverse_endian,
			   error)
		: alsa_setup(this, audio_format, &packed, &reverse_endian,
708
			     error);
709 710 711
	if (!success)
		return false;

712 713
	pcm_export->Open(audio_format.format,
			 audio_format.channels,
714
			 true, dop2, shift8, packed, reverse_endian);
715
	return true;
716 717
}

718 719
inline bool
AlsaOutput::Open(AudioFormat &audio_format, Error &error)
720
{
721 722
	int err = snd_pcm_open(&pcm, GetDevice(),
			       SND_PCM_STREAM_PLAYBACK, mode);
723
	if (err < 0) {
724
		error.Format(alsa_output_domain, err,
725
			    "Failed to open ALSA device \"%s\": %s",
726
			    GetDevice(), snd_strerror(err));
727
		return false;
728
	}
729

730
	FormatDebug(alsa_output_domain, "opened %s type=%s",
731 732
		    snd_pcm_name(pcm),
		    snd_pcm_type_name(snd_pcm_type(pcm)));
733

734 735
	if (!SetupOrDop(audio_format, error)) {
		snd_pcm_close(pcm);
736 737 738
		return false;
	}

739 740
	in_frame_size = audio_format.GetFrameSize();
	out_frame_size = pcm_export->GetFrameSize(audio_format);
741

742
	must_prepare = false;
743

744
	return true;
745 746
}

747 748
inline int
AlsaOutput::Recover(int err)
Avuton Olrich's avatar
Avuton Olrich committed
749 750
{
	if (err == -EPIPE) {
751
		FormatDebug(alsa_output_domain,
752 753
			    "Underrun on ALSA device \"%s\"",
			    GetDevice());
Avuton Olrich's avatar
Avuton Olrich committed
754
	} else if (err == -ESTRPIPE) {
755 756
		FormatDebug(alsa_output_domain,
			    "ALSA device \"%s\" was suspended",
757
			    GetDevice());
758 759
	}

760
	switch (snd_pcm_state(pcm)) {
Warren Dukes's avatar
Warren Dukes committed
761
	case SND_PCM_STATE_PAUSED:
762
		err = snd_pcm_pause(pcm, /* disable */ 0);
Warren Dukes's avatar
Warren Dukes committed
763 764
		break;
	case SND_PCM_STATE_SUSPENDED:
765
		err = snd_pcm_resume(pcm);
766 767 768
		if (err == -EAGAIN)
			return 0;
		/* fall-through to snd_pcm_prepare: */
769 770
	case SND_PCM_STATE_SETUP:
	case SND_PCM_STATE_XRUN:
771 772
		period_position = 0;
		err = snd_pcm_prepare(pcm);
Warren Dukes's avatar
Warren Dukes committed
773
		break;
774 775
	case SND_PCM_STATE_DISCONNECTED:
		break;
Max Kellermann's avatar
Max Kellermann committed
776 777 778 779
	/* this is no error, so just keep running */
	case SND_PCM_STATE_RUNNING:
		err = 0;
		break;
780 781 782
	default:
		/* unknown state, do nothing */
		break;
783 784 785 786 787
	}

	return err;
}

788 789
inline void
AlsaOutput::Drain()
790
{
791
	if (snd_pcm_state(pcm) != SND_PCM_STATE_RUNNING)
792 793
		return;

794
	if (period_position > 0) {
795 796 797
		/* generate some silence to finish the partial
		   period */
		snd_pcm_uframes_t nframes =
798 799
			period_frames - period_position;
		WriteSilence(nframes);
800 801
	}

802
	snd_pcm_drain(pcm);
803

804
	period_position = 0;
805 806
}

807 808
inline void
AlsaOutput::Cancel()
Avuton Olrich's avatar
Avuton Olrich committed
809
{
810 811
	period_position = 0;
	must_prepare = true;
812

813
	snd_pcm_drop(pcm);
814 815
}

816 817
inline void
AlsaOutput::Close()
Avuton Olrich's avatar
Avuton Olrich committed
818
{
819 820
	snd_pcm_close(pcm);
	delete[] silence;
821 822
}

823 824
inline size_t
AlsaOutput::Play(const void *chunk, size_t size, Error &error)
825
{
826
	assert(size > 0);
827
	assert(size % in_frame_size == 0);
828

829 830
	if (must_prepare) {
		must_prepare = false;
831

832
		int err = snd_pcm_prepare(pcm);
833 834 835 836 837 838
		if (err < 0) {
			error.Set(alsa_output_domain, err, snd_strerror(-err));
			return 0;
		}
	}

839
	const auto e = pcm_export->Export({chunk, size});
Max Kellermann's avatar
Max Kellermann committed
840
	if (e.size == 0)
841 842 843 844 845 846
		/* the DoP (DSD over PCM) filter converts two frames
		   at a time and ignores the last odd frame; if there
		   was only one frame (e.g. the last frame in the
		   file), the result is empty; to avoid an endless
		   loop, bail out here, and pretend the one frame has
		   been played */
Max Kellermann's avatar
Max Kellermann committed
847 848
		return size;

849 850
	chunk = e.data;
	size = e.size;
851

852
	assert(size % out_frame_size == 0);
853

854
	size /= out_frame_size;
855
	assert(size > 0);
856

857
	while (true) {
858
		snd_pcm_sframes_t ret = writei(pcm, chunk, size);
859
		if (ret > 0) {
860 861
			period_position = (period_position + ret)
				% period_frames;
862

863 864
			size_t bytes_written = ret * out_frame_size;
			return pcm_export->CalcSourceSize(bytes_written);
865
		}
866 867

		if (ret < 0 && ret != -EAGAIN && ret != -EINTR &&
868
		    Recover(ret) < 0) {
869
			error.Set(alsa_output_domain, ret, snd_strerror(-ret));
870
			return 0;
871 872 873 874
		}
	}
}

875 876
typedef AudioOutputWrapper<AlsaOutput> Wrapper;

877
const struct AudioOutputPlugin alsa_output_plugin = {
878 879
	"alsa",
	alsa_test_default_device,
880 881 882 883 884 885
	&Wrapper::Init,
	&Wrapper::Finish,
	&Wrapper::Enable,
	&Wrapper::Disable,
	&Wrapper::Open,
	&Wrapper::Close,
886 887
	nullptr,
	nullptr,
888 889 890
	&Wrapper::Play,
	&Wrapper::Drain,
	&Wrapper::Cancel,
891 892 893
	nullptr,

	&alsa_mixer_plugin,
894
};