AlsaOutputPlugin.cxx 22.5 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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 "system/ByteOrder.hxx"
28
#include "util/Manual.hxx"
29 30
#include "util/Error.hxx"
#include "util/Domain.hxx"
31
#include "util/ConstBuffer.hxx"
32
#include "Log.hxx"
33

34
#include <alsa/asoundlib.h>
35

36 37
#include <string>

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

43 44 45 46 47
#if SND_LIB_VERSION >= 0x1001d
/* alsa-lib supports DSD_U32 since version 1.0.29 */
#define HAVE_ALSA_DSD_U32
#endif

48 49
static const char default_device[] = "default";

50
static constexpr unsigned MPD_ALSA_BUFFER_TIME_US = 500000;
51

52
static constexpr unsigned MPD_ALSA_RETRY_NR = 5;
53

54
struct AlsaOutput {
55
	AudioOutput base;
56

57
	Manual<PcmExport> pcm_export;
58

59 60 61 62 63
	/**
	 * The configured name of the ALSA device; empty for the
	 * default device
	 */
	std::string device;
64

65
#ifdef ENABLE_DSD
66
	/**
Max Kellermann's avatar
Max Kellermann committed
67
	 * Enable DSD over PCM according to the DoP standard?
68
	 *
69
	 * @see http://dsd-guide.com/dop-open-standard
70
	 */
71
	bool dop;
72
#endif
73

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

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

80 81 82
	/** the mode flags passed to snd_pcm_open */
	int mode;

Max Kellermann's avatar
Max Kellermann committed
83
	/** the libasound PCM device handle */
Max Kellermann's avatar
Max Kellermann committed
84
	snd_pcm_t *pcm;
Max Kellermann's avatar
Max Kellermann committed
85

86 87 88 89 90 91 92 93 94
	/**
	 * 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;
95 96 97 98 99 100 101 102 103 104

	/**
	 * 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;
105

106
	/**
107 108 109 110 111 112 113 114
	 * 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.
115
	 */
116
	bool must_prepare;
117

118 119 120 121 122
	/**
	 * This buffer gets allocated after opening the ALSA device.
	 * It contains silence samples, enough to fill one period (see
	 * #period_frames).
	 */
123
	uint8_t *silence;
124

125 126
	AlsaOutput()
		:base(alsa_output_plugin),
127
		 mode(0) {
128 129
	}

130 131 132 133 134 135 136 137 138 139
	~AlsaOutput() {
		/* free libasound's config cache */
		snd_config_update_free_global();
	}

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

140 141
	bool Configure(const ConfigBlock &block, Error &error);
	static AlsaOutput *Create(const ConfigBlock &block, Error &error);
142 143 144 145 146 147 148 149 150 151 152 153

	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:
154
#ifdef ENABLE_DSD
155
	bool SetupDop(AudioFormat audio_format,
156
		      PcmExport::Params &params,
157
		      Error &error);
158 159
#endif

160 161
	bool SetupOrDop(AudioFormat &audio_format, PcmExport::Params &params,
			Error &error);
162 163 164 165 166 167 168

	int Recover(int err);

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

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

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

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

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

184
#ifdef ENABLE_DSD
185
	dop = block.GetBlockValue("dop", false) ||
186
		/* legacy name from MPD 0.18 and older: */
187
		block.GetBlockValue("dsd_usb", false);
188
#endif
189

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

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

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

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

	return true;
210 211
}

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

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

222
	return ad;
223 224
}

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

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

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

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

253
	return true;
254 255
}

256 257 258 259 260
/**
 * 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.
 */
261
gcc_const
Max Kellermann's avatar
Max Kellermann committed
262
static snd_pcm_format_t
263
ToAlsaPcmFormat(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
static snd_pcm_format_t
301
ByteSwapAlsaPcmFormat(snd_pcm_format_t fmt)
302
{
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
	case SND_PCM_FORMAT_S32_BE: return SND_PCM_FORMAT_S32_LE;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

#ifdef HAVE_ALSA_DSD_U32
	case SND_PCM_FORMAT_DSD_U16_LE:
		return SND_PCM_FORMAT_DSD_U16_BE;

	case SND_PCM_FORMAT_DSD_U16_BE:
		return SND_PCM_FORMAT_DSD_U16_LE;

	case SND_PCM_FORMAT_DSD_U32_LE:
		return SND_PCM_FORMAT_DSD_U32_BE;

	case SND_PCM_FORMAT_DSD_U32_BE:
		return SND_PCM_FORMAT_DSD_U32_LE;
#endif

332 333 334
	default: return SND_PCM_FORMAT_UNKNOWN;
	}
}
335

336 337 338 339
/**
 * Check if there is a "packed" version of the give PCM format.
 * Returns SND_PCM_FORMAT_UNKNOWN if not.
 */
340
static snd_pcm_format_t
341
PackAlsaPcmFormat(snd_pcm_format_t fmt)
342 343 344 345 346 347 348 349 350 351 352 353 354
{
	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;
	}
}

355 356 357 358
/**
 * Attempts to configure the specified sample format.  On failure,
 * fall back to the packed version.
 */
359
static int
360 361
AlsaTryFormatOrPacked(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
		      snd_pcm_format_t fmt, PcmExport::Params &params)
362 363 364
{
	int err = snd_pcm_hw_params_set_format(pcm, hwparams, fmt);
	if (err == 0)
365
		params.pack24 = false;
366 367 368 369

	if (err != -EINVAL)
		return err;

370
	fmt = PackAlsaPcmFormat(fmt);
371 372 373 374 375
	if (fmt == SND_PCM_FORMAT_UNKNOWN)
		return -EINVAL;

	err = snd_pcm_hw_params_set_format(pcm, hwparams, fmt);
	if (err == 0)
376
		params.pack24 = true;
377 378 379 380

	return err;
}

381
/**
382 383
 * Attempts to configure the specified sample format, and tries the
 * reversed host byte order if was not supported.
384 385
 */
static int
386 387 388
AlsaTryFormatOrByteSwap(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
			snd_pcm_format_t fmt,
			PcmExport::Params &params)
389
{
390
	int err = AlsaTryFormatOrPacked(pcm, hwparams, fmt, params);
391
	if (err == 0)
392
		params.reverse_endian = false;
393

394 395
	if (err != -EINVAL)
		return err;
396

397 398
	fmt = ByteSwapAlsaPcmFormat(fmt);
	if (fmt == SND_PCM_FORMAT_UNKNOWN)
399 400
		return -EINVAL;

401
	err = AlsaTryFormatOrPacked(pcm, hwparams, fmt, params);
402
	if (err == 0)
403
		params.reverse_endian = true;
404 405 406 407

	return err;
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
/**
 * Attempts to configure the specified sample format.  On DSD_U8
 * failure, attempt to switch to DSD_U32.
 */
static int
AlsaTryFormatDsd(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
		 snd_pcm_format_t fmt, PcmExport::Params &params)
{
	int err = AlsaTryFormatOrByteSwap(pcm, hwparams, fmt, params);

#if defined(ENABLE_DSD) && defined(HAVE_ALSA_DSD_U32)
	if (err == 0)
		params.dsd_u32 = false;

	if (err == -EINVAL && fmt == SND_PCM_FORMAT_DSD_U8) {
		/* attempt to switch to DSD_U32 */
		fmt = IsLittleEndian()
			? SND_PCM_FORMAT_DSD_U32_LE
			: SND_PCM_FORMAT_DSD_U32_BE;
		err = AlsaTryFormatOrByteSwap(pcm, hwparams, fmt, params);
		if (err == 0)
			params.dsd_u32 = true;
	}
#endif

	return err;
}

436 437 438 439 440 441 442 443 444
static int
AlsaTryFormat(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
	      SampleFormat sample_format,
	      PcmExport::Params &params)
{
	snd_pcm_format_t alsa_format = ToAlsaPcmFormat(sample_format);
	if (alsa_format == SND_PCM_FORMAT_UNKNOWN)
		return -EINVAL;

445
	return AlsaTryFormatDsd(pcm, hwparams, alsa_format, params);
446 447
}

448
/**
449
 * Configure a sample format, and probe other formats if that fails.
450
 */
451
static int
452 453 454
AlsaSetupFormat(snd_pcm_t *pcm, snd_pcm_hw_params_t *hwparams,
		AudioFormat &audio_format,
		PcmExport::Params &params)
455
{
456
	/* try the input format first */
457

458
	int err = AlsaTryFormat(pcm, hwparams, audio_format.format, params);
459

460
	/* if unsupported by the hardware, try other formats */
461

462
	static constexpr SampleFormat probe_formats[] = {
463 464 465 466 467
		SampleFormat::S24_P32,
		SampleFormat::S32,
		SampleFormat::S16,
		SampleFormat::S8,
		SampleFormat::UNDEFINED,
468
	};
469

470
	for (unsigned i = 0;
471
	     err == -EINVAL && probe_formats[i] != SampleFormat::UNDEFINED;
472
	     ++i) {
473 474
		const SampleFormat mpd_format = probe_formats[i];
		if (mpd_format == audio_format.format)
475
			continue;
476

477
		err = AlsaTryFormat(pcm, hwparams, mpd_format, params);
478
		if (err == 0)
479
			audio_format.format = mpd_format;
480
	}
481

482
	return err;
483 484 485 486 487 488 489
}

/**
 * Set up the snd_pcm_t object which was opened by the caller.  Set up
 * the configured settings and the audio format.
 */
static bool
490 491
AlsaSetup(AlsaOutput *ad, AudioFormat &audio_format,
	  PcmExport::Params &params, Error &error)
492
{
493 494
	unsigned int sample_rate = audio_format.sample_rate;
	unsigned int channels = audio_format.channels;
495
	int err;
496
	const char *cmd = nullptr;
497
	unsigned retry = MPD_ALSA_RETRY_NR;
498 499 500 501 502 503
	unsigned int period_time, period_time_ro;
	unsigned int buffer_time;

	period_time_ro = period_time = ad->period_time;
configure_hw:
	/* configure HW params */
504
	snd_pcm_hw_params_t *hwparams;
505 506 507 508 509 510
	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;

511 512 513 514 515
	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;
516

517
	err = AlsaSetupFormat(ad->pcm, hwparams, audio_format, params);
Avuton Olrich's avatar
Avuton Olrich committed
518
	if (err < 0) {
519 520
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support format %s: %s",
521
			     ad->GetDevice(),
522 523
			     sample_format_to_string(audio_format.format),
			     snd_strerror(-err));
524
		return false;
525 526
	}

527 528
	snd_pcm_format_t format;
	if (snd_pcm_hw_params_get_format(hwparams, &format) == 0)
529 530 531
		FormatDebug(alsa_output_domain,
			    "format=%s (%s)", snd_pcm_format_name(format),
			    snd_pcm_format_description(format));
532

Max Kellermann's avatar
Max Kellermann committed
533
	err = snd_pcm_hw_params_set_channels_near(ad->pcm, hwparams,
Avuton Olrich's avatar
Avuton Olrich committed
534 535
						  &channels);
	if (err < 0) {
536 537
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support %i channels: %s",
538
			     ad->GetDevice(), (int)audio_format.channels,
539
			     snd_strerror(-err));
540
		return false;
541
	}
542
	audio_format.channels = (int8_t)channels;
543

Max Kellermann's avatar
Max Kellermann committed
544
	err = snd_pcm_hw_params_set_rate_near(ad->pcm, hwparams,
545
					      &sample_rate, nullptr);
546
	if (err < 0 || sample_rate == 0) {
547 548
		error.Format(alsa_output_domain, err,
			     "ALSA device \"%s\" does not support %u Hz audio",
549
			     ad->GetDevice(), audio_format.sample_rate);
550
		return false;
551
	}
552
	audio_format.sample_rate = sample_rate;
553

554 555 556 557 558 559
	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);
560 561 562
	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);
563 564 565 566 567 568 569

	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);
570 571 572
	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);
573

574 575 576
	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
577
		err = snd_pcm_hw_params_set_buffer_time_near(ad->pcm, hwparams,
578
							     &buffer_time, nullptr);
579 580
		if (err < 0)
			goto error;
581 582
	} else {
		err = snd_pcm_hw_params_get_buffer_time(hwparams, &buffer_time,
583
							nullptr);
584 585
		if (err < 0)
			buffer_time = 0;
586
	}
587

588 589 590
	if (period_time_ro == 0 && buffer_time >= 10000) {
		period_time_ro = period_time = buffer_time / 4;

591 592 593
		FormatDebug(alsa_output_domain,
			    "default period_time = buffer_time/4 = %u/4 = %u",
			    buffer_time, period_time);
594 595
	}

596 597 598
	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
599
		err = snd_pcm_hw_params_set_period_time_near(ad->pcm, hwparams,
600
							     &period_time, nullptr);
601 602 603
		if (err < 0)
			goto error;
	}
604

605
	cmd = "snd_pcm_hw_params";
Max Kellermann's avatar
Max Kellermann committed
606
	err = snd_pcm_hw_params(ad->pcm, hwparams);
607
	if (err == -EPIPE && --retry > 0 && period_time_ro > 0) {
608
		period_time_ro = period_time_ro >> 1;
609 610
		goto configure_hw;
	} else if (err < 0)
Avuton Olrich's avatar
Avuton Olrich committed
611
		goto error;
612
	if (retry != MPD_ALSA_RETRY_NR)
613 614
		FormatDebug(alsa_output_domain,
			    "ALSA period_time set to %d", period_time);
615

616
	snd_pcm_uframes_t alsa_buffer_size;
617
	cmd = "snd_pcm_hw_params_get_buffer_size";
618
	err = snd_pcm_hw_params_get_buffer_size(hwparams, &alsa_buffer_size);
Avuton Olrich's avatar
Avuton Olrich committed
619 620
	if (err < 0)
		goto error;
621

622
	snd_pcm_uframes_t alsa_period_size;
623
	cmd = "snd_pcm_hw_params_get_period_size";
624
	err = snd_pcm_hw_params_get_period_size(hwparams, &alsa_period_size,
625
						nullptr);
Avuton Olrich's avatar
Avuton Olrich committed
626 627
	if (err < 0)
		goto error;
628

629
	/* configure SW params */
630
	snd_pcm_sw_params_t *swparams;
631 632
	snd_pcm_sw_params_alloca(&swparams);

633
	cmd = "snd_pcm_sw_params_current";
Max Kellermann's avatar
Max Kellermann committed
634
	err = snd_pcm_sw_params_current(ad->pcm, swparams);
Avuton Olrich's avatar
Avuton Olrich committed
635 636
	if (err < 0)
		goto error;
637 638

	cmd = "snd_pcm_sw_params_set_start_threshold";
Max Kellermann's avatar
Max Kellermann committed
639
	err = snd_pcm_sw_params_set_start_threshold(ad->pcm, swparams,
Avuton Olrich's avatar
Avuton Olrich committed
640 641 642 643
						    alsa_buffer_size -
						    alsa_period_size);
	if (err < 0)
		goto error;
644

645
	cmd = "snd_pcm_sw_params_set_avail_min";
Max Kellermann's avatar
Max Kellermann committed
646
	err = snd_pcm_sw_params_set_avail_min(ad->pcm, swparams,
Avuton Olrich's avatar
Avuton Olrich committed
647 648 649
					      alsa_period_size);
	if (err < 0)
		goto error;
650 651

	cmd = "snd_pcm_sw_params";
Max Kellermann's avatar
Max Kellermann committed
652
	err = snd_pcm_sw_params(ad->pcm, swparams);
Avuton Olrich's avatar
Avuton Olrich committed
653 654 655
	if (err < 0)
		goto error;

656 657
	FormatDebug(alsa_output_domain, "buffer_size=%u period_size=%u",
		    (unsigned)alsa_buffer_size, (unsigned)alsa_period_size);
658

659 660 661 662 663 664 665 666
	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;

667 668 669
	ad->period_frames = alsa_period_size;
	ad->period_position = 0;

670 671
	ad->silence = new uint8_t[snd_pcm_frames_to_bytes(ad->pcm,
							  alsa_period_size)];
672 673 674
	snd_pcm_format_set_silence(format, ad->silence,
				   alsa_period_size * channels);

675
	return true;
676

677
error:
678 679
	error.Format(alsa_output_domain, err,
		     "Error opening ALSA device \"%s\" (%s): %s",
680
		     ad->GetDevice(), cmd, snd_strerror(-err));
681 682 683
	return false;
}

684 685
#ifdef ENABLE_DSD

686 687
inline bool
AlsaOutput::SetupDop(const AudioFormat audio_format,
688
		     PcmExport::Params &params,
689
		     Error &error)
690
{
691
	assert(dop);
692
	assert(audio_format.format == SampleFormat::DSD);
693

694
	/* pass 24 bit to AlsaSetup() */
695

696 697 698
	AudioFormat dop_format = audio_format;
	dop_format.format = SampleFormat::S24_P32;
	dop_format.sample_rate /= 2;
699

700
	const AudioFormat check = dop_format;
701

702
	if (!AlsaSetup(this, dop_format, params, error))
703 704
		return false;

705
	/* if the device allows only 32 bit, shift all DoP
706 707 708 709
	   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) */
710
	params.shift8 = dop_format.format == SampleFormat::S32;
711 712
	if (dop_format.format == SampleFormat::S32)
		dop_format.format = SampleFormat::S24_P32;
713

714
	if (dop_format != check) {
715 716
		/* no bit-perfect playback, which is required
		   for DSD over USB */
717
		error.Format(alsa_output_domain,
718
			     "Failed to configure DSD-over-PCM on ALSA device \"%s\"",
719 720
			     GetDevice());
		delete[] silence;
721 722 723 724 725 726
		return false;
	}

	return true;
}

727 728
#endif

729
inline bool
730 731
AlsaOutput::SetupOrDop(AudioFormat &audio_format, PcmExport::Params &params,
		       Error &error)
732
{
733
#ifdef ENABLE_DSD
734 735 736
	Error dop_error;
	if (dop && audio_format.format == SampleFormat::DSD &&
	    SetupDop(audio_format, params, dop_error)) {
737
		params.dop = true;
738
		return true;
739
	}
740
#endif
741

742 743 744 745 746 747 748 749 750 751 752
	if (AlsaSetup(this, audio_format, params, error))
		return true;

#ifdef ENABLE_DSD
	if (dop_error.IsDefined())
		/* if DoP was attempted, prefer returning the original
		   DoP error instead of the fallback error */
		error = std::move(dop_error);
#endif

	return false;
753 754
}

755 756
inline bool
AlsaOutput::Open(AudioFormat &audio_format, Error &error)
757
{
758 759
	int err = snd_pcm_open(&pcm, GetDevice(),
			       SND_PCM_STREAM_PLAYBACK, mode);
760
	if (err < 0) {
761
		error.Format(alsa_output_domain, err,
762
			    "Failed to open ALSA device \"%s\": %s",
763
			    GetDevice(), snd_strerror(err));
764
		return false;
765
	}
766

767
	FormatDebug(alsa_output_domain, "opened %s type=%s",
768 769
		    snd_pcm_name(pcm),
		    snd_pcm_type_name(snd_pcm_type(pcm)));
770

771 772 773 774
	PcmExport::Params params;
	params.alsa_channel_order = true;

	if (!SetupOrDop(audio_format, params, error)) {
775
		snd_pcm_close(pcm);
776 777 778
		return false;
	}

779 780 781 782
	pcm_export->Open(audio_format.format,
			 audio_format.channels,
			 params);

783 784
	in_frame_size = audio_format.GetFrameSize();
	out_frame_size = pcm_export->GetFrameSize(audio_format);
785

786
	must_prepare = false;
787

788
	return true;
789 790
}

791 792
inline int
AlsaOutput::Recover(int err)
Avuton Olrich's avatar
Avuton Olrich committed
793 794
{
	if (err == -EPIPE) {
795
		FormatDebug(alsa_output_domain,
796 797
			    "Underrun on ALSA device \"%s\"",
			    GetDevice());
Avuton Olrich's avatar
Avuton Olrich committed
798
	} else if (err == -ESTRPIPE) {
799 800
		FormatDebug(alsa_output_domain,
			    "ALSA device \"%s\" was suspended",
801
			    GetDevice());
802 803
	}

804
	switch (snd_pcm_state(pcm)) {
Warren Dukes's avatar
Warren Dukes committed
805
	case SND_PCM_STATE_PAUSED:
806
		err = snd_pcm_pause(pcm, /* disable */ 0);
Warren Dukes's avatar
Warren Dukes committed
807 808
		break;
	case SND_PCM_STATE_SUSPENDED:
809
		err = snd_pcm_resume(pcm);
810 811 812
		if (err == -EAGAIN)
			return 0;
		/* fall-through to snd_pcm_prepare: */
813 814
	case SND_PCM_STATE_SETUP:
	case SND_PCM_STATE_XRUN:
815 816
		period_position = 0;
		err = snd_pcm_prepare(pcm);
Warren Dukes's avatar
Warren Dukes committed
817
		break;
818 819
	case SND_PCM_STATE_DISCONNECTED:
		break;
Max Kellermann's avatar
Max Kellermann committed
820 821 822 823
	/* this is no error, so just keep running */
	case SND_PCM_STATE_RUNNING:
		err = 0;
		break;
824 825 826
	default:
		/* unknown state, do nothing */
		break;
827 828 829 830 831
	}

	return err;
}

832 833
inline void
AlsaOutput::Drain()
834
{
835
	if (snd_pcm_state(pcm) != SND_PCM_STATE_RUNNING)
836 837
		return;

838
	if (period_position > 0) {
839 840 841
		/* generate some silence to finish the partial
		   period */
		snd_pcm_uframes_t nframes =
842 843
			period_frames - period_position;
		WriteSilence(nframes);
844 845
	}

846
	snd_pcm_drain(pcm);
847

848
	period_position = 0;
849 850
}

851 852
inline void
AlsaOutput::Cancel()
Avuton Olrich's avatar
Avuton Olrich committed
853
{
854 855
	period_position = 0;
	must_prepare = true;
856

857
	snd_pcm_drop(pcm);
858 859
}

860 861
inline void
AlsaOutput::Close()
Avuton Olrich's avatar
Avuton Olrich committed
862
{
863 864
	snd_pcm_close(pcm);
	delete[] silence;
865 866
}

867 868
inline size_t
AlsaOutput::Play(const void *chunk, size_t size, Error &error)
869
{
870
	assert(size > 0);
871
	assert(size % in_frame_size == 0);
872

873 874
	if (must_prepare) {
		must_prepare = false;
875

876
		int err = snd_pcm_prepare(pcm);
877 878 879 880 881 882
		if (err < 0) {
			error.Set(alsa_output_domain, err, snd_strerror(-err));
			return 0;
		}
	}

883
	const auto e = pcm_export->Export({chunk, size});
Max Kellermann's avatar
Max Kellermann committed
884
	if (e.size == 0)
885 886 887 888 889 890
		/* 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
891 892
		return size;

893 894
	chunk = e.data;
	size = e.size;
895

896
	assert(size % out_frame_size == 0);
897

898
	size /= out_frame_size;
899
	assert(size > 0);
900

901
	while (true) {
902
		snd_pcm_sframes_t ret = snd_pcm_writei(pcm, chunk, size);
903
		if (ret > 0) {
904 905
			period_position = (period_position + ret)
				% period_frames;
906

907 908
			size_t bytes_written = ret * out_frame_size;
			return pcm_export->CalcSourceSize(bytes_written);
909
		}
910 911

		if (ret < 0 && ret != -EAGAIN && ret != -EINTR &&
912
		    Recover(ret) < 0) {
913
			error.Set(alsa_output_domain, ret, snd_strerror(-ret));
914
			return 0;
915 916 917 918
		}
	}
}

919 920
typedef AudioOutputWrapper<AlsaOutput> Wrapper;

921
const struct AudioOutputPlugin alsa_output_plugin = {
922 923
	"alsa",
	alsa_test_default_device,
924 925 926 927 928 929
	&Wrapper::Init,
	&Wrapper::Finish,
	&Wrapper::Enable,
	&Wrapper::Disable,
	&Wrapper::Open,
	&Wrapper::Close,
930 931
	nullptr,
	nullptr,
932 933 934
	&Wrapper::Play,
	&Wrapper::Drain,
	&Wrapper::Cancel,
935 936 937
	nullptr,

	&alsa_mixer_plugin,
938
};