aboutsummaryrefslogtreecommitdiffstats
path: root/src/output/OutputThread.cxx
blob: 52dfc63ef5bb2cd278077dd93210e5100fcd6c36 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
/*
 * Copyright (C) 2003-2014 The Music Player Daemon Project
 * http://www.musicpd.org
 *
 * 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.
 *
 * 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.
 */

#include "config.h"
#include "OutputThread.hxx"
#include "OutputInternal.hxx"
#include "OutputAPI.hxx"
#include "OutputError.hxx"
#include "pcm/PcmMix.hxx"
#include "notify.hxx"
#include "filter/FilterInternal.hxx"
#include "filter/plugins/ConvertFilterPlugin.hxx"
#include "filter/plugins/ReplayGainFilterPlugin.hxx"
#include "PlayerControl.hxx"
#include "MusicPipe.hxx"
#include "MusicChunk.hxx"
#include "thread/Util.hxx"
#include "thread/Name.hxx"
#include "system/FatalError.hxx"
#include "util/Error.hxx"
#include "Log.hxx"
#include "Compiler.h"

#include <assert.h>
#include <string.h>

static void ao_command_finished(struct audio_output *ao)
{
	assert(ao->command != AO_COMMAND_NONE);
	ao->command = AO_COMMAND_NONE;

	ao->mutex.unlock();
	audio_output_client_notify.Signal();
	ao->mutex.lock();
}

static bool
ao_enable(struct audio_output *ao)
{
	Error error;
	bool success;

	if (ao->really_enabled)
		return true;

	ao->mutex.unlock();
	success = ao_plugin_enable(ao, error);
	ao->mutex.lock();
	if (!success) {
		FormatError(error,
			    "Failed to enable \"%s\" [%s]",
			    ao->name, ao->plugin->name);
		return false;
	}

	ao->really_enabled = true;
	return true;
}

static void
ao_close(struct audio_output *ao, bool drain);

static void
ao_disable(struct audio_output *ao)
{
	if (ao->open)
		ao_close(ao, false);

	if (ao->really_enabled) {
		ao->really_enabled = false;

		ao->mutex.unlock();
		ao_plugin_disable(ao);
		ao->mutex.lock();
	}
}

static AudioFormat
ao_filter_open(struct audio_output *ao, AudioFormat &format,
	       Error &error_r)
{
	assert(format.IsValid());

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

	if (ao->other_replay_gain_filter != nullptr &&
	    !ao->other_replay_gain_filter->Open(format, error_r).IsDefined()) {
		if (ao->replay_gain_filter != nullptr)
			ao->replay_gain_filter->Close();
		return AudioFormat::Undefined();
	}

	const AudioFormat af = ao->filter->Open(format, error_r);
	if (!af.IsDefined()) {
		if (ao->replay_gain_filter != nullptr)
			ao->replay_gain_filter->Close();
		if (ao->other_replay_gain_filter != nullptr)
			ao->other_replay_gain_filter->Close();
	}

	return af;
}

static void
ao_filter_close(struct audio_output *ao)
{
	if (ao->replay_gain_filter != nullptr)
		ao->replay_gain_filter->Close();
	if (ao->other_replay_gain_filter != nullptr)
		ao->other_replay_gain_filter->Close();

	ao->filter->Close();
}

static void
ao_open(struct audio_output *ao)
{
	bool success;
	Error error;
	struct audio_format_string af_string;

	assert(!ao->open);
	assert(ao->pipe != nullptr);
	assert(ao->chunk == nullptr);
	assert(ao->in_audio_format.IsValid());

	ao->fail_timer.Reset();

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

	if (!ao_enable(ao))
		/* still no luck */
		return;

	/* open the filter */

	const AudioFormat filter_audio_format =
		ao_filter_open(ao, ao->in_audio_format, error);
	if (!filter_audio_format.IsDefined()) {
		FormatError(error, "Failed to open filter for \"%s\" [%s]",
			    ao->name, ao->plugin->name);

		ao->fail_timer.Update();
		return;
	}

	assert(filter_audio_format.IsValid());

	ao->out_audio_format = filter_audio_format;
	ao->out_audio_format.ApplyMask(ao->config_audio_format);

	ao->mutex.unlock();
	success = ao_plugin_open(ao, ao->out_audio_format, error);
	ao->mutex.lock();

	assert(!ao->open);

	if (!success) {
		FormatError(error, "Failed to open \"%s\" [%s]",
			    ao->name, ao->plugin->name);

		ao_filter_close(ao);
		ao->fail_timer.Update();
		return;
	}

	if (!convert_filter_set(ao->convert_filter, ao->out_audio_format,
				error)) {
		FormatError(error, "Failed to convert for \"%s\" [%s]",
			    ao->name, ao->plugin->name);

		ao_filter_close(ao);
		ao->fail_timer.Update();
		return;
	}

	ao->open = true;

	FormatDebug(output_domain,
		    "opened plugin=%s name=\"%s\" audio_format=%s",
		    ao->plugin->name, ao->name,
		    audio_format_to_string(ao->out_audio_format, &af_string));

	if (ao->in_audio_format != ao->out_audio_format)
		FormatDebug(output_domain, "converting from %s",
			    audio_format_to_string(ao->in_audio_format,
						   &af_string));
}

static void
ao_close(struct audio_output *ao, bool drain)
{
	assert(ao->open);

	ao->pipe = nullptr;

	ao->chunk = nullptr;
	ao->open = false;

	ao->mutex.unlock();

	if (drain)
		ao_plugin_drain(ao);
	else
		ao_plugin_cancel(ao);

	ao_plugin_close(ao);
	ao_filter_close(ao);

	ao->mutex.lock();

	FormatDebug(output_domain, "closed plugin=%s name=\"%s\"",
		    ao->plugin->name, ao->name);
}

static void
ao_reopen_filter(struct audio_output *ao)
{
	Error error;

	ao_filter_close(ao);
	const AudioFormat filter_audio_format =
		ao_filter_open(ao, ao->in_audio_format, error);
	if (!filter_audio_format.IsDefined() ||
	    !convert_filter_set(ao->convert_filter, ao->out_audio_format,
				error)) {
		FormatError(error,
			    "Failed to open filter for \"%s\" [%s]",
			    ao->name, ao->plugin->name);

		/* this is a little code duplication fro ao_close(),
		   but we cannot call this function because we must
		   not call filter_close(ao->filter) again */

		ao->pipe = nullptr;

		ao->chunk = nullptr;
		ao->open = false;
		ao->fail_timer.Update();

		ao->mutex.unlock();
		ao_plugin_close(ao);
		ao->mutex.lock();

		return;
	}
}

static void
ao_reopen(struct audio_output *ao)
{
	if (!ao->config_audio_format.IsFullyDefined()) {
		if (ao->open) {
			const MusicPipe *mp = ao->pipe;
			ao_close(ao, true);
			ao->pipe = mp;
		}

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

	if (ao->open)
		/* the audio format has changed, and all filters have
		   to be reconfigured */
		ao_reopen_filter(ao);
	else
		ao_open(ao);
}

/**
 * Wait until the output's delay reaches zero.
 *
 * @return true if playback should be continued, false if a command
 * was issued
 */
static bool
ao_wait(struct audio_output *ao)
{
	while (true) {
		unsigned delay = ao_plugin_delay(ao);
		if (delay == 0)
			return true;

		(void)ao->cond.timed_wait(ao->mutex, delay);

		if (ao->command != AO_COMMAND_NONE)
			return false;
	}
}

static const void *
ao_chunk_data(struct audio_output *ao, const struct music_chunk *chunk,
	      Filter *replay_gain_filter,
	      unsigned *replay_gain_serial_p,
	      size_t *length_r)
{
	assert(chunk != nullptr);
	assert(!chunk->IsEmpty());
	assert(chunk->CheckFormat(ao->in_audio_format));

	const void *data = chunk->data;
	size_t length = chunk->length;

	(void)ao;

	assert(length % ao->in_audio_format.GetFrameSize() == 0);

	if (length > 0 && replay_gain_filter != nullptr) {
		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
						    : nullptr);
			*replay_gain_serial_p = chunk->replay_gain_serial;
		}

		Error error;
		data = replay_gain_filter->FilterPCM(data, length,
						     &length, error);
		if (data == nullptr) {
			FormatError(error, "\"%s\" [%s] failed to filter",
				    ao->name, ao->plugin->name);
			return nullptr;
		}
	}

	*length_r = length;
	return data;
}

static const void *
ao_filter_chunk(struct audio_output *ao, const struct music_chunk *chunk,
		size_t *length_r)
{
	size_t length;
	const void *data = ao_chunk_data(ao, chunk, ao->replay_gain_filter,
					 &ao->replay_gain_serial, &length);
	if (data == nullptr)
		return nullptr;

	if (length == 0) {
		/* empty chunk, nothing to do */
		*length_r = 0;
		return data;
	}

	/* cross-fade */

	if (chunk->other != nullptr) {
		size_t other_length;
		const void *other_data =
			ao_chunk_data(ao, chunk->other,
				      ao->other_replay_gain_filter,
				      &ao->other_replay_gain_serial,
				      &other_length);
		if (other_data == nullptr)
			return nullptr;

		if (other_length == 0) {
			*length_r = 0;
			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 */

		if (length > other_length)
			length = other_length;

		void *dest = ao->cross_fade_buffer.Get(other_length);
		memcpy(dest, other_data, other_length);
		if (!pcm_mix(ao->cross_fade_dither, dest, data, length,
			     ao->in_audio_format.format,
			     1.0 - chunk->mix_ratio)) {
			FormatError(output_domain,
				    "Cannot cross-fade format %s",
				    sample_format_to_string(ao->in_audio_format.format));
			return nullptr;
		}

		data = dest;
		length = other_length;
	}

	/* apply filter chain */

	Error error;
	data = ao->filter->FilterPCM(data, length, &length, error);
	if (data == nullptr) {
		FormatError(error, "\"%s\" [%s] failed to filter",
			    ao->name, ao->plugin->name);
		return nullptr;
	}

	*length_r = length;
	return data;
}

static bool
ao_play_chunk(struct audio_output *ao, const struct music_chunk *chunk)
{
	assert(ao != nullptr);
	assert(ao->filter != nullptr);

	if (ao->tags && gcc_unlikely(chunk->tag != nullptr)) {
		ao->mutex.unlock();
		ao_plugin_send_tag(ao, chunk->tag);
		ao->mutex.lock();
	}

	size_t size;
#if GCC_CHECK_VERSION(4,7)
	/* workaround -Wmaybe-uninitialized false positive */
	size = 0;
#endif
	const char *data = (const char *)ao_filter_chunk(ao, chunk, &size);
	if (data == nullptr) {
		ao_close(ao, false);

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

	Error error;

	while (size > 0 && ao->command == AO_COMMAND_NONE) {
		size_t nbytes;

		if (!ao_wait(ao))
			break;

		ao->mutex.unlock();
		nbytes = ao_plugin_play(ao, data, size, error);
		ao->mutex.lock();
		if (nbytes == 0) {
			/* play()==0 means failure */
			FormatError(error, "\"%s\" [%s] failed to play",
				    ao->name, ao->plugin->name);

			ao_close(ao, false);

			/* don't automatically reopen this device for
			   10 seconds */
			assert(!ao->fail_timer.IsDefined());
			ao->fail_timer.Update();

			return false;
		}

		assert(nbytes <= size);
		assert(nbytes % ao->out_audio_format.GetFrameSize() == 0);

		data += nbytes;
		size -= nbytes;
	}

	return true;
}

static const struct music_chunk *
ao_next_chunk(struct audio_output *ao)
{
	return ao->chunk != nullptr
		/* continue the previous play() call */
		? ao->chunk->next
		/* get the first chunk from the pipe */
		: ao->pipe->Peek();
}

/**
 * Plays all remaining chunks, until the tail of the pipe has been
 * reached (and no more chunks are queued), or until a command is
 * received.
 *
 * @return true if at least one chunk has been available, false if the
 * tail of the pipe was already reached
 */
static bool
ao_play(struct audio_output *ao)
{
	bool success;
	const struct music_chunk *chunk;

	assert(ao->pipe != nullptr);

	chunk = ao_next_chunk(ao);
	if (chunk == nullptr)
		/* no chunk available */
		return false;

	ao->chunk_finished = false;

	assert(!ao->in_playback_loop);
	ao->in_playback_loop = true;

	while (chunk != nullptr && ao->command == AO_COMMAND_NONE) {
		assert(!ao->chunk_finished);

		ao->chunk = chunk;

		success = ao_play_chunk(ao, chunk);
		if (!success) {
			assert(ao->chunk == nullptr);
			break;
		}

		assert(ao->chunk == chunk);
		chunk = chunk->next;
	}

	assert(ao->in_playback_loop);
	ao->in_playback_loop = false;

	ao->chunk_finished = true;

	ao->mutex.unlock();
	ao->player_control->LockSignal();
	ao->mutex.lock();

	return true;
}

static void ao_pause(struct audio_output *ao)
{
	bool ret;

	ao->mutex.unlock();
	ao_plugin_cancel(ao);
	ao->mutex.lock();

	ao->pause = true;
	ao_command_finished(ao);

	do {
		if (!ao_wait(ao))
			break;

		ao->mutex.unlock();
		ret = ao_plugin_pause(ao);
		ao->mutex.lock();

		if (!ret) {
			ao_close(ao, false);
			break;
		}
	} while (ao->command == AO_COMMAND_NONE);

	ao->pause = false;
}

static void
audio_output_task(void *arg)
{
	struct audio_output *ao = (struct audio_output *)arg;

	FormatThreadName("output:%s", ao->name);

	SetThreadRealtime();

	ao->mutex.lock();

	while (1) {
		switch (ao->command) {
		case AO_COMMAND_NONE:
			break;

		case AO_COMMAND_ENABLE:
			ao_enable(ao);
			ao_command_finished(ao);
			break;

		case AO_COMMAND_DISABLE:
			ao_disable(ao);
			ao_command_finished(ao);
			break;

		case AO_COMMAND_OPEN:
			ao_open(ao);
			ao_command_finished(ao);
			break;

		case AO_COMMAND_REOPEN:
			ao_reopen(ao);
			ao_command_finished(ao);
			break;

		case AO_COMMAND_CLOSE:
			assert(ao->open);
			assert(ao->pipe != nullptr);

			ao_close(ao, false);
			ao_command_finished(ao);
			break;

		case AO_COMMAND_PAUSE:
			if (!ao->open) {
				/* the output has failed after
				   audio_output_all_pause() has
				   submitted the PAUSE command; bail
				   out */
				ao_command_finished(ao);
				break;
			}

			ao_pause(ao);
			/* don't "break" here: this might cause
			   ao_play() to be called when command==CLOSE
			   ends the paused state - "continue" checks
			   the new command first */
			continue;

		case AO_COMMAND_DRAIN:
			if (ao->open) {
				assert(ao->chunk == nullptr);
				assert(ao->pipe->Peek() == nullptr);

				ao->mutex.unlock();
				ao_plugin_drain(ao);
				ao->mutex.lock();
			}

			ao_command_finished(ao);
			continue;

		case AO_COMMAND_CANCEL:
			ao->chunk = nullptr;

			if (ao->open) {
				ao->mutex.unlock();
				ao_plugin_cancel(ao);
				ao->mutex.lock();
			}

			ao_command_finished(ao);
			continue;

		case AO_COMMAND_KILL:
			ao->chunk = nullptr;
			ao_command_finished(ao);
			ao->mutex.unlock();
			return;
		}

		if (ao->open && ao->allow_play && ao_play(ao))
			/* don't wait for an event if there are more
			   chunks in the pipe */
			continue;

		if (ao->command == AO_COMMAND_NONE) {
			ao->woken_for_play = false;
			ao->cond.wait(ao->mutex);
		}
	}
}

void audio_output_thread_start(struct audio_output *ao)
{
	assert(ao->command == AO_COMMAND_NONE);

	Error error;
	if (!ao->thread.Start(audio_output_task, ao, error))
		FatalError(error);
}