OutputThread.cxx 14.2 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 "Internal.hxx"
22
#include "OutputAPI.hxx"
23
#include "Domain.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "pcm/PcmMix.hxx"
25
#include "pcm/Domain.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
#include "PlayerControl.hxx"
31 32
#include "MusicPipe.hxx"
#include "MusicChunk.hxx"
33
#include "thread/Util.hxx"
34
#include "thread/Slack.hxx"
35
#include "thread/Name.hxx"
36
#include "system/FatalError.hxx"
37
#include "util/Error.hxx"
38
#include "util/ConstBuffer.hxx"
39
#include "Log.hxx"
40
#include "Compiler.h"
41

42
#include <assert.h>
Max Kellermann's avatar
Max Kellermann committed
43
#include <string.h>
44

45 46
void
AudioOutput::CommandFinished()
47
{
48 49
	assert(command != Command::NONE);
	command = Command::NONE;
50

51
	mutex.unlock();
Max Kellermann's avatar
Max Kellermann committed
52
	audio_output_client_notify.Signal();
53
	mutex.lock();
54 55
}

56 57
inline bool
AudioOutput::Enable()
58
{
59
	if (really_enabled)
60 61
		return true;

62 63 64 65
	mutex.unlock();
	Error error;
	bool success = ao_plugin_enable(this, error);
	mutex.lock();
66
	if (!success) {
67 68
		FormatError(error,
			    "Failed to enable \"%s\" [%s]",
69
			    name, plugin.name);
70 71 72
		return false;
	}

73
	really_enabled = true;
74 75 76
	return true;
}

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

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

86 87 88
		mutex.unlock();
		ao_plugin_disable(this);
		mutex.lock();
89 90 91
	}
}

92 93
inline AudioFormat
AudioOutput::OpenFilter(AudioFormat &format, Error &error_r)
94
{
95
	assert(format.IsValid());
96

97
	/* the replay_gain filter cannot fail here */
98 99
	if (replay_gain_filter != nullptr &&
	    !replay_gain_filter->Open(format, error_r).IsDefined())
100 101
		return AudioFormat::Undefined();

102 103 104 105
	if (other_replay_gain_filter != nullptr &&
	    !other_replay_gain_filter->Open(format, error_r).IsDefined()) {
		if (replay_gain_filter != nullptr)
			replay_gain_filter->Close();
106 107
		return AudioFormat::Undefined();
	}
108

109
	const AudioFormat af = filter->Open(format, error_r);
110
	if (!af.IsDefined()) {
111 112 113 114
		if (replay_gain_filter != nullptr)
			replay_gain_filter->Close();
		if (other_replay_gain_filter != nullptr)
			other_replay_gain_filter->Close();
115 116 117
	}

	return af;
118 119
}

120 121
void
AudioOutput::CloseFilter()
122
{
123 124 125 126
	if (replay_gain_filter != nullptr)
		replay_gain_filter->Close();
	if (other_replay_gain_filter != nullptr)
		other_replay_gain_filter->Close();
127

128
	filter->Close();
129 130
}

131 132
inline void
AudioOutput::Open()
133 134
{
	bool success;
135
	Error error;
136
	struct audio_format_string af_string;
137

138 139 140 141
	assert(!open);
	assert(pipe != nullptr);
	assert(current_chunk == nullptr);
	assert(in_audio_format.IsValid());
142

143
	fail_timer.Reset();
144

145 146
	/* enable the device (just in case the last enable has failed) */

147
	if (!Enable())
148 149 150
		/* still no luck */
		return;

151 152
	/* open the filter */

153
	const AudioFormat filter_audio_format =
154
		OpenFilter(in_audio_format, error);
155
	if (!filter_audio_format.IsDefined()) {
156
		FormatError(error, "Failed to open filter for \"%s\" [%s]",
157
			    name, plugin.name);
158

159
		fail_timer.Update();
160 161 162
		return;
	}

163
	assert(filter_audio_format.IsValid());
164

165 166
	out_audio_format = filter_audio_format;
	out_audio_format.ApplyMask(config_audio_format);
167

168
	mutex.unlock();
169 170 171 172

	const AudioFormat retry_audio_format = out_audio_format;

 retry_without_dsd:
173 174
	success = ao_plugin_open(this, out_audio_format, error);
	mutex.lock();
175

176
	assert(!open);
177 178

	if (!success) {
179
		FormatError(error, "Failed to open \"%s\" [%s]",
180
			    name, plugin.name);
181

182
		mutex.unlock();
183
		CloseFilter();
184 185
		mutex.lock();

186
		fail_timer.Update();
187 188 189
		return;
	}

190
	if (!convert_filter_set(convert_filter, out_audio_format,
191 192
				error)) {
		FormatError(error, "Failed to convert for \"%s\" [%s]",
193
			    name, plugin.name);
194

195
		mutex.unlock();
196
		ao_plugin_close(this);
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

		if (error.IsDomain(pcm_domain) &&
		    out_audio_format.format == SampleFormat::DSD) {
			/* 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 */

			// TODO: clean up this workaround

			FormatError(output_domain, "Retrying without DSD");

			out_audio_format = retry_audio_format;
			out_audio_format.format = SampleFormat::FLOAT;

			/* clear the Error to allow reusing it */
			error.Clear();

			/* sorry for the "goto" - this is a workaround
			   for the stable branch that should be as
			   unintrusive as possible */
			goto retry_without_dsd;
		}

222
		CloseFilter();
223 224
		mutex.lock();

225
		fail_timer.Update();
226 227
		return;
	}
228

229
	open = true;
230

231 232
	FormatDebug(output_domain,
		    "opened plugin=%s name=\"%s\" audio_format=%s",
233 234
		    plugin.name, name,
		    audio_format_to_string(out_audio_format, &af_string));
235

236
	if (in_audio_format != out_audio_format)
237
		FormatDebug(output_domain, "converting from %s",
238
			    audio_format_to_string(in_audio_format,
239
						   &af_string));
240 241
}

242 243
void
AudioOutput::Close(bool drain)
244
{
245
	assert(open);
246

247
	pipe = nullptr;
248

249 250
	current_chunk = nullptr;
	open = false;
251

252
	mutex.unlock();
253

254
	if (drain)
255
		ao_plugin_drain(this);
256
	else
257
		ao_plugin_cancel(this);
258

259 260
	ao_plugin_close(this);
	CloseFilter();
261

262
	mutex.lock();
263

264
	FormatDebug(output_domain, "closed plugin=%s name=\"%s\"",
265
		    plugin.name, name);
266 267
}

268 269
void
AudioOutput::ReopenFilter()
270
{
271
	Error error;
272

273
	mutex.unlock();
274
	CloseFilter();
275 276
	mutex.lock();

277
	const AudioFormat filter_audio_format =
278
		OpenFilter(in_audio_format, error);
279
	if (!filter_audio_format.IsDefined() ||
280
	    !convert_filter_set(convert_filter, out_audio_format,
281
				error)) {
282 283
		FormatError(error,
			    "Failed to open filter for \"%s\" [%s]",
284
			    name, plugin.name);
285

286
		/* this is a little code duplication from Close(),
287
		   but we cannot call this function because we must
288
		   not call filter_close(filter) again */
289

290
		pipe = nullptr;
291

292 293 294
		current_chunk = nullptr;
		open = false;
		fail_timer.Update();
295

296 297 298
		mutex.unlock();
		ao_plugin_close(this);
		mutex.lock();
299 300 301 302 303

		return;
	}
}

304 305
void
AudioOutput::Reopen()
306
{
307 308 309 310 311
	if (!config_audio_format.IsFullyDefined()) {
		if (open) {
			const MusicPipe *mp = pipe;
			Close(true);
			pipe = mp;
312 313 314 315 316
		}

		/* no audio format is configured: copy in->out, let
		   the output's open() method determine the effective
		   out_audio_format */
317 318
		out_audio_format = in_audio_format;
		out_audio_format.ApplyMask(config_audio_format);
319 320
	}

321
	if (open)
322 323
		/* the audio format has changed, and all filters have
		   to be reconfigured */
324
		ReopenFilter();
325
	else
326
		Open();
327 328
}

329 330 331 332 333 334
/**
 * Wait until the output's delay reaches zero.
 *
 * @return true if playback should be continued, false if a command
 * was issued
 */
335 336
inline bool
AudioOutput::WaitForDelay()
337 338
{
	while (true) {
339
		unsigned delay = ao_plugin_delay(this);
340 341 342
		if (delay == 0)
			return true;

343
		(void)cond.timed_wait(mutex, delay);
344

345
		if (command != Command::NONE)
346 347 348 349
			return false;
	}
}

350
static ConstBuffer<void>
351
ao_chunk_data(AudioOutput *ao, const MusicChunk *chunk,
352
	      Filter *replay_gain_filter,
353
	      unsigned *replay_gain_serial_p)
354
{
355
	assert(chunk != nullptr);
356 357
	assert(!chunk->IsEmpty());
	assert(chunk->CheckFormat(ao->in_audio_format));
358

359
	ConstBuffer<void> data(chunk->data, chunk->length);
360 361 362

	(void)ao;

363
	assert(data.size % ao->in_audio_format.GetFrameSize() == 0);
364

365
	if (!data.IsEmpty() && replay_gain_filter != nullptr) {
366 367 368 369
		if (chunk->replay_gain_serial != *replay_gain_serial_p) {
			replay_gain_filter_set_info(replay_gain_filter,
						    chunk->replay_gain_serial != 0
						    ? &chunk->replay_gain_info
370
						    : nullptr);
371 372 373
			*replay_gain_serial_p = chunk->replay_gain_serial;
		}

374
		Error error;
375 376
		data = replay_gain_filter->FilterPCM(data, error);
		if (data.IsNull())
377
			FormatError(error, "\"%s\" [%s] failed to filter",
378
				    ao->name, ao->plugin.name);
379 380
	}

381 382 383
	return data;
}

384 385
static ConstBuffer<void>
ao_filter_chunk(AudioOutput *ao, const MusicChunk *chunk)
386
{
387 388 389 390
	ConstBuffer<void> data =
		ao_chunk_data(ao, chunk, ao->replay_gain_filter,
			      &ao->replay_gain_serial);
	if (data.IsEmpty())
391
		return data;
392

393 394
	/* cross-fade */

395
	if (chunk->other != nullptr) {
396
		ConstBuffer<void> other_data =
397 398
			ao_chunk_data(ao, chunk->other,
				      ao->other_replay_gain_filter,
399 400
				      &ao->other_replay_gain_serial);
		if (other_data.IsNull())
401
			return nullptr;
402

403
		if (other_data.IsEmpty())
404 405 406 407 408 409 410
			return data;

		/* if the "other" chunk is longer, then that trailer
		   is used as-is, without mixing; it is part of the
		   "next" song being faded in, and if there's a rest,
		   it means cross-fading ends here */

411 412
		if (data.size > other_data.size)
			data.size = other_data.size;
413

Max Kellermann's avatar
Max Kellermann committed
414 415 416 417 418 419 420 421 422
		float mix_ratio = chunk->mix_ratio;
		if (mix_ratio >= 0)
			/* reverse the mix ratio (because the
			   arguments to pcm_mix() are reversed), but
			   only if the mix ratio is non-negative; a
			   negative mix ratio is a MixRamp special
			   case */
			mix_ratio = 1.0 - mix_ratio;

423 424 425
		void *dest = ao->cross_fade_buffer.Get(other_data.size);
		memcpy(dest, other_data.data, other_data.size);
		if (!pcm_mix(ao->cross_fade_dither, dest, data.data, data.size,
426
			     ao->in_audio_format.format,
Max Kellermann's avatar
Max Kellermann committed
427
			     mix_ratio)) {
428 429 430
			FormatError(output_domain,
				    "Cannot cross-fade format %s",
				    sample_format_to_string(ao->in_audio_format.format));
431
			return nullptr;
432
		}
433

434 435
		data.data = dest;
		data.size = other_data.size;
436 437
	}

438
	/* apply filter chain */
439

440
	Error error;
441 442
	data = ao->filter->FilterPCM(data, error);
	if (data.IsNull()) {
443
		FormatError(error, "\"%s\" [%s] failed to filter",
444
			    ao->name, ao->plugin.name);
445
		return nullptr;
446 447 448 449 450
	}

	return data;
}

451
inline bool
452
AudioOutput::PlayChunk(const MusicChunk *chunk)
453
{
454
	assert(filter != nullptr);
455

456 457
	if (tags && gcc_unlikely(chunk->tag != nullptr)) {
		mutex.unlock();
458
		ao_plugin_send_tag(this, *chunk->tag);
459
		mutex.lock();
460 461
	}

462 463
	auto data = ConstBuffer<char>::FromVoid(ao_filter_chunk(this, chunk));
	if (data.IsNull()) {
464
		Close(false);
465 466 467

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

472 473
	Error error;

474
	while (!data.IsEmpty() && command == Command::NONE) {
475
		if (!WaitForDelay())
476 477
			break;

478
		mutex.unlock();
479 480
		size_t nbytes = ao_plugin_play(this, data.data, data.size,
					       error);
481
		mutex.lock();
482 483
		if (nbytes == 0) {
			/* play()==0 means failure */
484
			FormatError(error, "\"%s\" [%s] failed to play",
485
				    name, plugin.name);
486

487
			Close(false);
488 489 490

			/* don't automatically reopen this device for
			   10 seconds */
491 492
			assert(!fail_timer.IsDefined());
			fail_timer.Update();
493

494
			return false;
495 496
		}

497
		assert(nbytes <= data.size);
498
		assert(nbytes % out_audio_format.GetFrameSize() == 0);
499

500 501
		data.data += nbytes;
		data.size -= nbytes;
502 503
	}

504 505 506
	return true;
}

507
inline const MusicChunk *
508
AudioOutput::GetNextChunk() const
509
{
510
	return current_chunk != nullptr
511
		/* continue the previous play() call */
512
		? current_chunk->next
513
		/* get the first chunk from the pipe */
514
		: pipe->Peek();
515 516
}

517 518
inline bool
AudioOutput::Play()
519
{
520
	assert(pipe != nullptr);
521

522
	const MusicChunk *chunk = GetNextChunk();
523
	if (chunk == nullptr)
524 525
		/* no chunk available */
		return false;
526

527
	current_chunk_finished = false;
528

529 530
	assert(!in_playback_loop);
	in_playback_loop = true;
531

532
	while (chunk != nullptr && command == Command::NONE) {
533
		assert(!current_chunk_finished);
534

535
		current_chunk = chunk;
536

537 538
		if (!PlayChunk(chunk)) {
			assert(current_chunk == nullptr);
539 540 541
			break;
		}

542
		assert(current_chunk == chunk);
543 544 545
		chunk = chunk->next;
	}

546 547
	assert(in_playback_loop);
	in_playback_loop = false;
548

549
	current_chunk_finished = true;
550

551 552 553
	mutex.unlock();
	player_control->LockSignal();
	mutex.lock();
554 555

	return true;
556 557
}

558 559
inline void
AudioOutput::Pause()
560
{
561 562 563
	mutex.unlock();
	ao_plugin_cancel(this);
	mutex.lock();
564

565 566
	pause = true;
	CommandFinished();
567 568

	do {
569
		if (!WaitForDelay())
570 571
			break;

572 573 574
		mutex.unlock();
		bool success = ao_plugin_pause(this);
		mutex.lock();
575

576 577
		if (!success) {
			Close(false);
578 579
			break;
		}
580
	} while (command == Command::NONE);
581

582
	pause = false;
583 584
}

585 586
inline void
AudioOutput::Task()
587
{
588
	FormatThreadName("output:%s", name);
589

590
	SetThreadRealtime();
591
	SetThreadTimerSlackUS(100);
592

593
	mutex.lock();
594

595
	while (1) {
596
		switch (command) {
597
		case Command::NONE:
598 599
			break;

600
		case Command::ENABLE:
601 602
			Enable();
			CommandFinished();
603 604
			break;

605
		case Command::DISABLE:
606 607
			Disable();
			CommandFinished();
608 609
			break;

610
		case Command::OPEN:
611 612
			Open();
			CommandFinished();
613 614
			break;

615
		case Command::REOPEN:
616 617
			Reopen();
			CommandFinished();
618 619
			break;

620
		case Command::CLOSE:
621 622
			assert(open);
			assert(pipe != nullptr);
623

624 625
			Close(false);
			CommandFinished();
626 627
			break;

628
		case Command::PAUSE:
629
			if (!open) {
630 631 632 633
				/* the output has failed after
				   audio_output_all_pause() has
				   submitted the PAUSE command; bail
				   out */
634
				CommandFinished();
635 636 637
				break;
			}

638
			Pause();
639
			/* don't "break" here: this might cause
640
			   Play() to be called when command==CLOSE
641 642 643
			   ends the paused state - "continue" checks
			   the new command first */
			continue;
644

645
		case Command::DRAIN:
646 647 648
			if (open) {
				assert(current_chunk == nullptr);
				assert(pipe->Peek() == nullptr);
649

650 651 652
				mutex.unlock();
				ao_plugin_drain(this);
				mutex.lock();
653 654
			}

655
			CommandFinished();
656 657
			continue;

658
		case Command::CANCEL:
659
			current_chunk = nullptr;
660

661 662 663 664
			if (open) {
				mutex.unlock();
				ao_plugin_cancel(this);
				mutex.lock();
665 666
			}

667
			CommandFinished();
668
			continue;
669

670
		case Command::KILL:
671 672 673
			current_chunk = nullptr;
			CommandFinished();
			mutex.unlock();
674
			return;
675 676
		}

677
		if (open && allow_play && Play())
678 679 680
			/* don't wait for an event if there are more
			   chunks in the pipe */
			continue;
681

682
		if (command == Command::NONE) {
683 684
			woken_for_play = false;
			cond.wait(mutex);
685
		}
686 687 688
	}
}

689 690 691 692 693 694 695
void
AudioOutput::Task(void *arg)
{
	AudioOutput *ao = (AudioOutput *)arg;
	ao->Task();
}

696 697
void
AudioOutput::StartThread()
698
{
699
	assert(command == Command::NONE);
700

701
	Error error;
702
	if (!thread.Start(Task, this, error))
703
		FatalError(error);
704
}