Control.hxx 12.3 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
Warren Dukes's avatar
Warren Dukes committed
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.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20 21
#ifndef MPD_PLAYER_CONTROL_HXX
#define MPD_PLAYER_CONTROL_HXX
Warren Dukes's avatar
Warren Dukes committed
22

23
#include "output/Client.hxx"
24
#include "AudioFormat.hxx"
25 26
#include "thread/Mutex.hxx"
#include "thread/Cond.hxx"
27
#include "thread/Thread.hxx"
28
#include "CrossFade.hxx"
29
#include "Chrono.hxx"
30 31
#include "ReplayGainConfig.hxx"
#include "ReplayGainMode.hxx"
32

33
#include <exception>
34
#include <memory>
35

36
#include <stdint.h>
Warren Dukes's avatar
Warren Dukes committed
37

38
class PlayerListener;
39
class MultipleOutputs;
40
class DetachedSong;
41

42 43 44 45
enum class PlayerState : uint8_t {
	STOP,
	PAUSE,
	PLAY
46
};
Warren Dukes's avatar
Warren Dukes committed
47

48 49 50 51 52
enum class PlayerCommand : uint8_t {
	NONE,
	EXIT,
	STOP,
	PAUSE,
53 54 55 56 57 58

	/**
	 * Seek to a certain position in the specified song.  This
	 * command can also be used to change the current song or
	 * start playback.
	 */
59
	SEEK,
60

61
	CLOSE_AUDIO,
62

63
	/**
64
	 * At least one AudioOutput.enabled flag has been modified;
65 66
	 * commit those changes to the output threads.
	 */
67
	UPDATE_AUDIO,
68

69
	/** PlayerControl.next_song has been updated */
70
	QUEUE,
71 72

	/**
73
	 * cancel pre-decoding PlayerControl.next_song; if the player
74 75 76
	 * has already started playing this song, it will completely
	 * stop
	 */
77
	CANCEL,
78 79

	/**
80
	 * Refresh status information in the #PlayerControl struct,
81 82
	 * e.g. elapsed_time.
	 */
83
	REFRESH,
84 85
};

86 87
enum class PlayerError : uint8_t {
	NONE,
88 89 90 91

	/**
	 * The decoder has failed to decode the song.
	 */
92
	DECODER,
93 94 95 96

	/**
	 * The audio output has failed.
	 */
97
	OUTPUT,
98
};
Warren Dukes's avatar
Warren Dukes committed
99

100
struct player_status {
101
	PlayerState state;
102
	uint16_t bit_rate;
103
	AudioFormat audio_format;
104
	SignedSongTime total_time;
105
	SongTime elapsed_time;
106 107
};

108
struct PlayerControl final : AudioOutputClient {
109 110
	PlayerListener &listener;

111 112
	MultipleOutputs &outputs;

113
	const unsigned buffer_chunks;
114

115
	const unsigned buffered_before_play;
116

117 118 119 120 121
	/**
	 * The "audio_output_format" setting.
	 */
	const AudioFormat configured_audio_format;

122 123 124 125
	/**
	 * The handle of the player thread.
	 */
	Thread thread;
126

127
	/**
128
	 * This lock protects #command, #state, #error, #tagged_song.
129
	 */
130
	mutable Mutex mutex;
131 132 133 134

	/**
	 * Trigger this object after you have modified #command.
	 */
135
	Cond cond;
136

137 138 139 140 141 142 143
	/**
	 * This object gets signalled when the player thread has
	 * finished the #command.  It wakes up the client that waits
	 * (i.e. the main thread).
	 */
	Cond client_cond;

144 145
	/**
	 * The error that occurred in the player thread.  This
146
	 * attribute is only valid if #error_type is not
147 148
	 * #PlayerError::NONE.  The object must be freed when this
	 * object transitions back to #PlayerError::NONE.
149
	 */
150
	std::exception_ptr error;
151

152 153 154 155 156 157 158 159
	/**
	 * The next queued song.
	 *
	 * This is a duplicate, and must be freed when this attribute
	 * is cleared.
	 */
	std::unique_ptr<DetachedSong> next_song;

160
	/**
161 162 163
	 * A copy of the current #DetachedSong after its tags have
	 * been updated by the decoder (for example, a radio stream
	 * that has sent a new tag after switching to the next song).
164 165
	 * This shall be used by PlayerListener::OnPlayerTagModified()
	 * to update the current #DetachedSong in the queue.
166 167 168 169
	 *
	 * Protected by #mutex.  Set by the PlayerThread and consumed
	 * by the main thread.
	 */
170
	std::unique_ptr<DetachedSong> tagged_song;
171

172 173
	PlayerCommand command = PlayerCommand::NONE;
	PlayerState state = PlayerState::STOP;
174

175
	PlayerError error_type = PlayerError::NONE;
176

177 178
	ReplayGainMode replay_gain_mode = ReplayGainMode::OFF;

179 180 181 182 183 184 185
	/**
	 * If this flag is set, then the player will be auto-paused at
	 * the end of the song, before the next song starts to play.
	 *
	 * This is a copy of the queue's "single" flag most of the
	 * time.
	 */
186
	bool border_pause = false;
Warren Dukes's avatar
Warren Dukes committed
187

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	/**
	 * If this flag is set, then the player thread is currently
	 * occupied and will not be able to respond quickly to
	 * commands (e.g. waiting for the decoder thread to finish
	 * seeking).  This is used to skip #PlayerCommand::REFRESH to
	 * avoid blocking the main thread.
	 */
	bool occupied = false;

	struct ScopeOccupied {
		PlayerControl &pc;

		explicit ScopeOccupied(PlayerControl &_pc) noexcept:pc(_pc) {
			assert(!pc.occupied);
			pc.occupied = true;
		}

		~ScopeOccupied() noexcept {
			assert(pc.occupied);
			pc.occupied = false;
		}
	};

211 212 213 214 215 216 217 218 219 220 221 222 223 224
	AudioFormat audio_format;
	uint16_t bit_rate;

	SignedSongTime total_time;
	SongTime elapsed_time;

	SongTime seek_time;

	CrossFadeSettings cross_fade;

	const ReplayGainConfig replay_gain_config;

	double total_play_time = 0;

225 226
	PlayerControl(PlayerListener &_listener,
		      MultipleOutputs &_outputs,
227
		      unsigned buffer_chunks,
228
		      unsigned buffered_before_play,
229
		      AudioFormat _configured_audio_format,
230 231
		      const ReplayGainConfig &_replay_gain_config) noexcept;
	~PlayerControl() noexcept;
232

233 234 235
	/**
	 * Locks the object.
	 */
236
	void Lock() const noexcept {
237 238
		mutex.lock();
	}
239

240 241 242
	/**
	 * Unlocks the object.
	 */
243
	void Unlock() const noexcept {
244 245
		mutex.unlock();
	}
Warren Dukes's avatar
Warren Dukes committed
246

247 248 249 250
	/**
	 * Signals the object.  The object should be locked prior to
	 * calling this function.
	 */
251
	void Signal() noexcept {
252 253
		cond.signal();
	}
254

255 256 257 258
	/**
	 * Signals the object.  The object is temporarily locked by
	 * this function.
	 */
259
	void LockSignal() noexcept {
260
		const std::lock_guard<Mutex> protect(mutex);
261 262
		Signal();
	}
263

264 265 266 267 268
	/**
	 * Waits for a signal on the object.  This function is only
	 * valid in the player thread.  The object must be locked
	 * prior to calling this function.
	 */
269
	void Wait() noexcept {
270
		assert(thread.IsInside());
271

272 273
		cond.wait(mutex);
	}
Warren Dukes's avatar
Warren Dukes committed
274

275 276 277 278 279
	/**
	 * Wake up the client waiting for command completion.
	 *
	 * Caller must lock the object.
	 */
280
	void ClientSignal() noexcept {
281
		assert(thread.IsInside());
282 283 284 285 286 287 288 289 290 291

		client_cond.signal();
	}

	/**
	 * The client calls this method to wait for command
	 * completion.
	 *
	 * Caller must lock the object.
	 */
292
	void ClientWait() noexcept {
293
		assert(!thread.IsInside());
294 295 296 297

		client_cond.wait(mutex);
	}

298 299 300 301 302 303 304
	/**
	 * A command has been finished.  This method clears the
	 * command and signals the client.
	 *
	 * To be called from the player thread.  Caller must lock the
	 * object.
	 */
305
	void CommandFinished() noexcept {
306
		assert(command != PlayerCommand::NONE);
307

308
		command = PlayerCommand::NONE;
309 310 311
		ClientSignal();
	}

312
	void LockCommandFinished() noexcept {
313
		const std::lock_guard<Mutex> protect(mutex);
314 315 316
		CommandFinished();
	}

317 318 319 320 321 322 323 324 325 326
	/**
	 * Checks if the size of the #MusicPipe is below the #threshold.  If
	 * not, it attempts to synchronize with all output threads, and waits
	 * until another #MusicChunk is finished.
	 *
	 * Caller must lock the mutex.
	 *
	 * @param threshold the maximum number of chunks in the pipe
	 * @return true if there are less than #threshold chunks in the pipe
	 */
327
	bool WaitOutputConsumed(unsigned threshold) noexcept;
328

329
	bool LockWaitOutputConsumed(unsigned threshold) noexcept {
330
		const std::lock_guard<Mutex> protect(mutex);
331 332 333
		return WaitOutputConsumed(threshold);
	}

334 335 336 337 338 339 340
private:
	/**
	 * Wait for the command to be finished by the player thread.
	 *
	 * To be called from the main thread.  Caller must lock the
	 * object.
	 */
341
	void WaitCommandLocked() noexcept {
342
		while (command != PlayerCommand::NONE)
343 344 345 346 347 348 349 350 351 352
			ClientWait();
	}

	/**
	 * Send a command to the player thread and synchronously wait
	 * for it to finish.
	 *
	 * To be called from the main thread.  Caller must lock the
	 * object.
	 */
353
	void SynchronousCommand(PlayerCommand cmd) noexcept {
354
		assert(command == PlayerCommand::NONE);
355 356 357 358 359 360 361 362 363 364 365 366 367

		command = cmd;
		Signal();
		WaitCommandLocked();
	}

	/**
	 * Send a command to the player thread and synchronously wait
	 * for it to finish.
	 *
	 * To be called from the main thread.  This method locks the
	 * object.
	 */
368
	void LockSynchronousCommand(PlayerCommand cmd) noexcept {
369
		const std::lock_guard<Mutex> protect(mutex);
370 371 372 373
		SynchronousCommand(cmd);
	}

public:
374
	/**
375
	 * Throws on error.
376
	 *
377
	 * @param song the song to be queued
378
	 */
379
	void Play(std::unique_ptr<DetachedSong> song);
380

381
	/**
382
	 * see PlayerCommand::CANCEL
383
	 */
384
	void LockCancel() noexcept;
Warren Dukes's avatar
Warren Dukes committed
385

386
	void LockSetPause(bool pause_flag) noexcept;
Warren Dukes's avatar
Warren Dukes committed
387

388
private:
389
	void PauseLocked() noexcept;
390

391
	void ClearError() noexcept {
392
		error_type = PlayerError::NONE;
393
		error = std::exception_ptr();
394 395
	}

396
public:
397
	void LockPause() noexcept;
Warren Dukes's avatar
Warren Dukes committed
398

399 400 401
	/**
	 * Set the player's #border_pause flag.
	 */
402
	void LockSetBorderPause(bool border_pause) noexcept;
403

404
	bool ApplyBorderPause() noexcept {
405 406 407 408 409
		if (border_pause)
			state = PlayerState::PAUSE;
		return border_pause;
	}

410
	bool LockApplyBorderPause() noexcept {
411
		const std::lock_guard<Mutex> lock(mutex);
412 413 414
		return ApplyBorderPause();
	}

415
	void Kill() noexcept;
Warren Dukes's avatar
Warren Dukes committed
416

417
	gcc_pure
418
	player_status LockGetStatus() noexcept;
Warren Dukes's avatar
Warren Dukes committed
419

420
	PlayerState GetState() const noexcept {
421 422
		return state;
	}
Warren Dukes's avatar
Warren Dukes committed
423

424 425 426 427 428
	/**
	 * Set the error.  Discards any previous error condition.
	 *
	 * Caller must lock the object.
	 *
429
	 * @param type the error type; must not be #PlayerError::NONE
430
	 */
431
	void SetError(PlayerError type, std::exception_ptr &&_error) noexcept;
432

433 434 435
	/**
	 * Set the error and set state to PlayerState::PAUSE.
	 */
436
	void SetOutputError(std::exception_ptr &&_error) noexcept {
437 438 439 440 441 442 443
		SetError(PlayerError::OUTPUT, std::move(_error));

		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		state = PlayerState::PAUSE;
	}

444
	void LockSetOutputError(std::exception_ptr &&_error) noexcept {
445
		const std::lock_guard<Mutex> lock(mutex);
446 447 448
		SetOutputError(std::move(_error));
	}

449
	/**
450 451
	 * Checks whether an error has occurred, and if so, rethrows
	 * it.
452 453 454
	 *
	 * Caller must lock the object.
	 */
455
	void CheckRethrowError() const {
456
		if (error_type != PlayerError::NONE)
457
			std::rethrow_exception(error);
458
	}
459

460
	/**
461
	 * Like CheckRethrowError(), but locks and unlocks the object.
462
	 */
463
	void LockCheckRethrowError() const {
464
		const std::lock_guard<Mutex> protect(mutex);
465
		CheckRethrowError();
466 467
	}

468
	void LockClearError() noexcept;
Warren Dukes's avatar
Warren Dukes committed
469

470
	PlayerError GetErrorType() const noexcept {
471 472 473
		return error_type;
	}

474 475
	/**
	 * Set the #tagged_song attribute to a newly allocated copy of
476
	 * the given #DetachedSong.  Locks and unlocks the object.
477
	 */
478
	void LockSetTaggedSong(const DetachedSong &song) noexcept;
479

480
	void ClearTaggedSong() noexcept;
481 482 483 484 485 486

	/**
	 * Read and clear the #tagged_song attribute.
	 *
	 * Caller must lock the object.
	 */
487
	std::unique_ptr<DetachedSong> ReadTaggedSong() noexcept;
488 489 490 491

	/**
	 * Like ReadTaggedSong(), but locks and unlocks the object.
	 */
492
	std::unique_ptr<DetachedSong> LockReadTaggedSong() noexcept;
493

494
	void LockStop() noexcept;
495

496
	void LockUpdateAudio() noexcept;
497

498
private:
499
	void EnqueueSongLocked(std::unique_ptr<DetachedSong> song) noexcept;
500

501
	/**
502
	 * Throws on error.
503
	 */
504
	void SeekLocked(std::unique_ptr<DetachedSong> song, SongTime t);
505

506
public:
507 508 509 510
	/**
	 * @param song the song to be queued; the given instance will be owned
	 * and freed by the player
	 */
511
	void LockEnqueueSong(std::unique_ptr<DetachedSong> song) noexcept;
512 513 514 515

	/**
	 * Makes the player thread seek the specified song to a position.
	 *
516
	 * Throws on error.
517
	 *
518 519 520
	 * @param song the song to be queued; the given instance will be owned
	 * and freed by the player
	 */
521
	void LockSeek(std::unique_ptr<DetachedSong> song, SongTime t);
522

523
	void SetCrossFade(float cross_fade_seconds) noexcept;
524

525
	float GetCrossFade() const noexcept {
526
		return cross_fade.duration;
527 528
	}

529
	void SetMixRampDb(float mixramp_db) noexcept;
530

531
	float GetMixRampDb() const noexcept {
532
		return cross_fade.mixramp_db;
533 534
	}

535
	void SetMixRampDelay(float mixramp_delay_seconds) noexcept;
536

537
	float GetMixRampDelay() const noexcept {
538
		return cross_fade.mixramp_delay;
539 540
	}

541
	void LockSetReplayGainMode(ReplayGainMode _mode) noexcept {
542
		const std::lock_guard<Mutex> protect(mutex);
543 544 545
		replay_gain_mode = _mode;
	}

546
	double GetTotalPlayTime() const noexcept {
547 548
		return total_play_time;
	}
549 550 551 552 553 554 555 556 557

	/* virtual methods from AudioOutputClient */
	void ChunksConsumed() override {
		LockSignal();
	}

	void ApplyEnabled() override {
		LockUpdateAudio();
	}
558 559

private:
560
	void RunThread() noexcept;
561
};
562

Warren Dukes's avatar
Warren Dukes committed
563
#endif