OutputThread.cxx 10.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 "Internal.hxx"
22
#include "Client.hxx"
23
#include "OutputAPI.hxx"
24
#include "Domain.hxx"
Max Kellermann's avatar
Max Kellermann committed
25
#include "pcm/PcmMix.hxx"
Max Kellermann's avatar
Max Kellermann committed
26
#include "notify.hxx"
27 28 29
#include "filter/FilterInternal.hxx"
#include "filter/plugins/ConvertFilterPlugin.hxx"
#include "filter/plugins/ReplayGainFilterPlugin.hxx"
30 31
#include "mixer/MixerInternal.hxx"
#include "mixer/plugins/SoftwareMixerPlugin.hxx"
32 33
#include "MusicPipe.hxx"
#include "MusicChunk.hxx"
34
#include "thread/Util.hxx"
35
#include "thread/Slack.hxx"
36
#include "thread/Name.hxx"
37
#include "util/ConstBuffer.hxx"
38
#include "util/StringBuffer.hxx"
39
#include "util/ScopeExit.hxx"
40
#include "util/RuntimeError.hxx"
41
#include "Log.hxx"
42
#include "Compiler.h"
43

44 45
#include <stdexcept>

46
#include <assert.h>
Max Kellermann's avatar
Max Kellermann committed
47
#include <string.h>
48

49 50
void
AudioOutput::CommandFinished()
51
{
52 53
	assert(command != Command::NONE);
	command = Command::NONE;
54

55
	const ScopeUnlock unlock(mutex);
Max Kellermann's avatar
Max Kellermann committed
56
	audio_output_client_notify.Signal();
57 58
}

59
inline void
60
AudioOutput::Enable()
61
{
62
	if (really_enabled)
63
		return;
64

65
	try {
66
		const ScopeUnlock unlock(mutex);
67
		ao_plugin_enable(*this);
68
	} catch (const std::runtime_error &e) {
69 70
		std::throw_with_nested(FormatRuntimeError("Failed to enable output \"%s\" [%s]",
							  name, plugin.name));
71 72
	}

73
	really_enabled = true;
74 75
}

76 77
inline void
AudioOutput::Disable()
78
{
79 80
	if (open)
		Close(false);
81

82 83
	if (really_enabled) {
		really_enabled = false;
84

85
		const ScopeUnlock unlock(mutex);
86
		ao_plugin_disable(*this);
87 88 89
	}
}

90 91
void
AudioOutput::CloseFilter()
92
{
93 94
	if (mixer != nullptr && mixer->IsPlugin(software_mixer_plugin))
		software_mixer_set_filter(*mixer, nullptr);
95

96
	source.Close();
97 98
}

99 100
inline void
AudioOutput::Open()
101
{
102
	assert(request.audio_format.IsValid());
103

104
	fail_timer.Reset();
105

106
	/* enable the device (just in case the last enable has failed) */
107
	Enable();
108

109
	AudioFormat f;
110

111 112 113 114
	try {
		f = source.Open(request.audio_format, *request.pipe,
				prepared_replay_gain_filter,
				prepared_other_replay_gain_filter,
115
				prepared_filter);
116 117 118

		if (mixer != nullptr && mixer->IsPlugin(software_mixer_plugin))
			software_mixer_set_filter(*mixer, volume_filter.Get());
119
	} catch (const std::runtime_error &e) {
120 121
		std::throw_with_nested(FormatRuntimeError("Failed to open filter for \"%s\" [%s]",
							  name, plugin.name));
122
	}
123

124 125 126
	const auto cf = f.WithMask(config_audio_format);

	if (open && cf != filter_audio_format) {
127 128 129 130
		/* if the filter's output format changes, the output
		   must be reopened as well */
		CloseOutput(true);
		open = false;
131
	}
132

133
	filter_audio_format = cf;
134

135
	if (!open) {
136 137 138
		try {
			OpenOutputAndConvert(filter_audio_format);
		} catch (...) {
139
			CloseFilter();
140
			throw;
141
		}
142 143

		open = true;
144 145 146 147 148 149 150 151 152 153 154 155
	} else if (f != out_audio_format) {
		/* reconfigure the final ConvertFilter for its new
		   input AudioFormat */

		try {
			convert_filter_set(convert_filter.Get(),
					   out_audio_format);
		} catch (const std::runtime_error &e) {
			Close(false);
			std::throw_with_nested(FormatRuntimeError("Failed to convert for \"%s\" [%s]",
								  name, plugin.name));
		}
156
	}
157

158
	if (f != source.GetInputAudioFormat() || f != out_audio_format)
159
		FormatDebug(output_domain, "converting in=%s -> f=%s -> out=%s",
160 161 162
			    ToString(source.GetInputAudioFormat()).c_str(),
			    ToString(f).c_str(),
			    ToString(out_audio_format).c_str());
163 164
}

165
void
166 167 168
AudioOutput::OpenOutputAndConvert(AudioFormat desired_audio_format)
{
	out_audio_format = desired_audio_format;
169

170
	try {
171
		ao_plugin_open(*this, out_audio_format);
172
	} catch (const std::runtime_error &e) {
173 174
		std::throw_with_nested(FormatRuntimeError("Failed to open \"%s\" [%s]",
							  name, plugin.name));
175 176
	}

177 178 179
	FormatDebug(output_domain,
		    "opened plugin=%s name=\"%s\" audio_format=%s",
		    plugin.name, name,
180
		    ToString(out_audio_format).c_str());
181

182 183 184
	try {
		convert_filter_set(convert_filter.Get(), out_audio_format);
	} catch (const std::runtime_error &e) {
185
		ao_plugin_close(*this);
186

187
		if (out_audio_format.format == SampleFormat::DSD) {
188 189 190 191 192 193
			/* if the audio output supports DSD, but not
			   the given sample rate, it asks MPD to
			   resample; resampling DSD however is not
			   implemented; our last resort is to give up
			   DSD and fall back to PCM */

194
			LogError(e);
195 196
			FormatError(output_domain, "Retrying without DSD");

197
			desired_audio_format.format = SampleFormat::FLOAT;
198 199
			OpenOutputAndConvert(desired_audio_format);
			return;
200 201
		}

202 203
		std::throw_with_nested(FormatRuntimeError("Failed to convert for \"%s\" [%s]",
							  name, plugin.name));
204
	}
205 206
}

207 208
void
AudioOutput::Close(bool drain)
209
{
210
	assert(open);
211

212
	open = false;
213

214
	const ScopeUnlock unlock(mutex);
215

216
	CloseOutput(drain);
217
	CloseFilter();
218

219
	FormatDebug(output_domain, "closed plugin=%s name=\"%s\"",
220
		    plugin.name, name);
221 222
}

223 224 225 226
inline void
AudioOutput::CloseOutput(bool drain)
{
	if (drain)
227
		ao_plugin_drain(*this);
228
	else
229
		ao_plugin_cancel(*this);
230

231
	ao_plugin_close(*this);
232 233
}

234 235 236 237 238 239
/**
 * Wait until the output's delay reaches zero.
 *
 * @return true if playback should be continued, false if a command
 * was issued
 */
240 241
inline bool
AudioOutput::WaitForDelay()
242 243
{
	while (true) {
244
		const auto delay = ao_plugin_delay(*this);
245
		if (delay <= std::chrono::steady_clock::duration::zero())
246 247
			return true;

248
		(void)cond.timed_wait(mutex, delay);
249

250
		if (command != Command::NONE)
251 252 253 254
			return false;
	}
}

255 256 257
bool
AudioOutput::FillSourceOrClose()
try {
258
	return source.Fill(mutex);
259 260 261 262 263 264 265 266 267 268 269 270
} catch (const std::runtime_error &e) {
	FormatError(e, "Failed to filter for output \"%s\" [%s]",
		    name, plugin.name);

	Close(false);

	/* don't automatically reopen this device for 10
	   seconds */
	fail_timer.Update();
	return false;
}

271
inline bool
272
AudioOutput::PlayChunk()
273
{
274 275 276 277 278
	if (tags) {
		const auto *tag = source.ReadTag();
		if (tag != nullptr) {
			const ScopeUnlock unlock(mutex);
			try {
279
				ao_plugin_send_tag(*this, *tag);
280 281 282 283
			} catch (const std::runtime_error &e) {
				FormatError(e, "Failed to send tag to \"%s\" [%s]",
					    name, plugin.name);
			}
284
		}
285 286
	}

287 288 289 290
	while (command == Command::NONE) {
		const auto data = source.PeekData();
		if (data.IsEmpty())
			break;
291

292
		if (!WaitForDelay())
293 294
			break;

295 296
		size_t nbytes;

297
		try {
298
			const ScopeUnlock unlock(mutex);
299
			nbytes = ao_plugin_play(*this, data.data, data.size);
300
			assert(nbytes <= data.size);
301 302
		} catch (const std::runtime_error &e) {
			FormatError(e, "\"%s\" [%s] failed to play",
303
				    name, plugin.name);
304

305 306 307 308
			nbytes = 0;
		}

		if (nbytes == 0) {
309
			Close(false);
310 311 312

			/* don't automatically reopen this device for
			   10 seconds */
313 314
			assert(!fail_timer.IsDefined());
			fail_timer.Update();
315

316
			return false;
317 318
		}

319
		assert(nbytes % out_audio_format.GetFrameSize() == 0);
320

321
		source.ConsumeData(nbytes);
322 323
	}

324 325 326
	return true;
}

327 328
inline bool
AudioOutput::Play()
329
{
330
	if (!FillSourceOrClose())
331 332
		/* no chunk available */
		return false;
333

334 335
	assert(!in_playback_loop);
	in_playback_loop = true;
336

337 338 339 340 341
	AtScopeExit(this) {
		assert(in_playback_loop);
		in_playback_loop = false;
	};

342 343
	unsigned n = 0;

344
	do {
345 346 347
		if (command != Command::NONE)
			return true;

348 349 350 351 352
		if (++n >= 64) {
			/* wake up the player every now and then to
			   give it a chance to refill the pipe before
			   it runs empty */
			const ScopeUnlock unlock(mutex);
353
			client->ChunksConsumed();
354 355 356
			n = 0;
		}

357
		if (!PlayChunk())
358
			break;
359
	} while (FillSourceOrClose());
360

361
	const ScopeUnlock unlock(mutex);
362
	client->ChunksConsumed();
363 364

	return true;
365 366
}

367 368
inline void
AudioOutput::Pause()
369
{
370 371
	{
		const ScopeUnlock unlock(mutex);
372
		ao_plugin_cancel(*this);
373
	}
374

375 376
	pause = true;
	CommandFinished();
377 378

	do {
379
		if (!WaitForDelay())
380 381
			break;

382
		bool success;
383
		try {
384
			const ScopeUnlock unlock(mutex);
385
			success = ao_plugin_pause(*this);
386 387 388 389
		} catch (const std::runtime_error &e) {
			FormatError(e, "\"%s\" [%s] failed to pause",
				    name, plugin.name);
			success = false;
390
		}
391

392 393
		if (!success) {
			Close(false);
394 395
			break;
		}
396
	} while (command == Command::NONE);
397

398
	pause = false;
399 400
}

401
void
402
AudioOutput::Task()
403
{
404
	FormatThreadName("output:%s", name);
405

406 407 408 409 410
	try {
		SetThreadRealtime();
	} catch (const std::runtime_error &e) {
		LogError(e,
			 "OutputThread could not get realtime scheduling, continuing anyway");
411
	}
412

413
	SetThreadTimerSlackUS(100);
414

415
	const std::lock_guard<Mutex> lock(mutex);
416

417
	while (true) {
418
		switch (command) {
419
		case Command::NONE:
420 421
			break;

422
		case Command::ENABLE:
423 424
			last_error = nullptr;

425 426 427 428 429
			try {
				Enable();
			} catch (const std::runtime_error &e) {
				LogError(e);
				fail_timer.Update();
430
				last_error = std::current_exception();
431 432
			}

433
			CommandFinished();
434 435
			break;

436
		case Command::DISABLE:
437 438
			Disable();
			CommandFinished();
439 440
			break;

441
		case Command::OPEN:
442 443
			last_error = nullptr;

444 445 446 447 448
			try {
				Open();
			} catch (const std::runtime_error &e) {
				LogError(e);
				fail_timer.Update();
449
				last_error = std::current_exception();
450 451
			}

452
			CommandFinished();
453 454
			break;

455
		case Command::CLOSE:
456 457
			if (open)
				Close(false);
458
			CommandFinished();
459 460
			break;

461
		case Command::PAUSE:
462
			if (!open) {
463 464 465 466
				/* the output has failed after
				   audio_output_all_pause() has
				   submitted the PAUSE command; bail
				   out */
467
				CommandFinished();
468 469 470
				break;
			}

471
			Pause();
472
			/* don't "break" here: this might cause
473
			   Play() to be called when command==CLOSE
474 475 476
			   ends the paused state - "continue" checks
			   the new command first */
			continue;
477

478
		case Command::DRAIN:
479
			if (open) {
480
				const ScopeUnlock unlock(mutex);
481
				ao_plugin_drain(*this);
482 483
			}

484
			CommandFinished();
485 486
			continue;

487
		case Command::CANCEL:
488
			source.Cancel();
489

490
			if (open) {
491
				const ScopeUnlock unlock(mutex);
492
				ao_plugin_cancel(*this);
493 494
			}

495
			CommandFinished();
496
			continue;
497

498
		case Command::KILL:
499
			Disable();
500
			source.Cancel();
501
			CommandFinished();
502
			return;
503 504
		}

505
		if (open && allow_play && Play())
506 507 508
			/* don't wait for an event if there are more
			   chunks in the pipe */
			continue;
509

510
		if (command == Command::NONE) {
511 512
			woken_for_play = false;
			cond.wait(mutex);
513
		}
514 515 516
	}
}

517 518
void
AudioOutput::StartThread()
519
{
520
	assert(command == Command::NONE);
521

522
	thread.Start();
523
}