OutputThread.cxx 10.6 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 301
		} catch (const std::runtime_error &e) {
			FormatError(e, "\"%s\" [%s] failed to play",
302
				    name, plugin.name);
303

304 305 306 307
			nbytes = 0;
		}

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

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

315
			return false;
316 317
		}

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

320
		source.ConsumeData(nbytes);
321 322
	}

323 324 325
	return true;
}

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

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

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

341 342
	unsigned n = 0;

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

347 348 349 350 351
		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);
352
			client->ChunksConsumed();
353 354 355
			n = 0;
		}

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

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

	return true;
364 365
}

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

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

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

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

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

397
	pause = false;
398 399
}

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

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

412
	SetThreadTimerSlackUS(100);
413

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

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

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

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

432
			CommandFinished();
433 434
			break;

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

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

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

451
			CommandFinished();
452 453
			break;

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

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

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

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

483
			CommandFinished();
484 485
			continue;

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

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

494
			CommandFinished();
495
			continue;
496

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

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

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

516 517 518 519 520 521 522
void
AudioOutput::Task(void *arg)
{
	AudioOutput *ao = (AudioOutput *)arg;
	ao->Task();
}

523 524
void
AudioOutput::StartThread()
525
{
526
	assert(command == Command::NONE);
527

528
	thread.Start(Task, this);
529
}