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 PlayerOutputs;
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

	/**
	 * Seek to a certain position in the specified song.  This
	 * command can also be used to change the current song or
57 58 59
	 * start playback.  It "finishes" immediately, but
	 * PlayerControl::seeking will be set until seeking really
	 * completes (or fails).
60
	 */
61
	SEEK,
62

63
	CLOSE_AUDIO,
64

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

71
	/** PlayerControl.next_song has been updated */
72
	QUEUE,
73 74

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

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

88 89
enum class PlayerError : uint8_t {
	NONE,
90 91 92 93

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

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

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

110
struct PlayerControl final : AudioOutputClient {
111 112
	PlayerListener &listener;

113
	PlayerOutputs &outputs;
114

115
	const unsigned buffer_chunks;
116

117
	const unsigned buffered_before_play;
118

119 120 121 122 123
	/**
	 * The "audio_output_format" setting.
	 */
	const AudioFormat configured_audio_format;

124 125 126 127
	/**
	 * The handle of the player thread.
	 */
	Thread thread;
128

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

	/**
	 * Trigger this object after you have modified #command.
	 */
137
	Cond cond;
138

139 140 141 142 143 144 145
	/**
	 * 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;

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

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

162
	/**
163 164 165
	 * 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).
166 167
	 * This shall be used by PlayerListener::OnPlayerTagModified()
	 * to update the current #DetachedSong in the queue.
168 169 170 171
	 *
	 * Protected by #mutex.  Set by the PlayerThread and consumed
	 * by the main thread.
	 */
172
	std::unique_ptr<DetachedSong> tagged_song;
173

174 175
	PlayerCommand command = PlayerCommand::NONE;
	PlayerState state = PlayerState::STOP;
176

177
	PlayerError error_type = PlayerError::NONE;
178

179 180
	ReplayGainMode replay_gain_mode = ReplayGainMode::OFF;

181 182 183 184 185
	/**
	 * Is the player currently busy with the SEEK command?
	 */
	bool seeking = false;

186 187 188 189 190 191 192
	/**
	 * 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.
	 */
193
	bool border_pause = false;
Warren Dukes's avatar
Warren Dukes committed
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	/**
	 * 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;
		}
	};

218 219 220 221 222 223 224 225 226 227 228 229 230 231
	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;

232
	PlayerControl(PlayerListener &_listener,
233
		      PlayerOutputs &_outputs,
234
		      unsigned buffer_chunks,
235
		      unsigned buffered_before_play,
236
		      AudioFormat _configured_audio_format,
237 238
		      const ReplayGainConfig &_replay_gain_config) noexcept;
	~PlayerControl() noexcept;
239

240 241 242
	/**
	 * Locks the object.
	 */
243
	void Lock() const noexcept {
244 245
		mutex.lock();
	}
246

247 248 249
	/**
	 * Unlocks the object.
	 */
250
	void Unlock() const noexcept {
251 252
		mutex.unlock();
	}
Warren Dukes's avatar
Warren Dukes committed
253

254 255 256 257
	/**
	 * Signals the object.  The object should be locked prior to
	 * calling this function.
	 */
258
	void Signal() noexcept {
259 260
		cond.signal();
	}
261

262 263 264 265
	/**
	 * Signals the object.  The object is temporarily locked by
	 * this function.
	 */
266
	void LockSignal() noexcept {
267
		const std::lock_guard<Mutex> protect(mutex);
268 269
		Signal();
	}
270

271 272 273 274 275
	/**
	 * 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.
	 */
276
	void Wait() noexcept {
277
		assert(thread.IsInside());
278

279 280
		cond.wait(mutex);
	}
Warren Dukes's avatar
Warren Dukes committed
281

282 283 284 285 286
	/**
	 * Wake up the client waiting for command completion.
	 *
	 * Caller must lock the object.
	 */
287
	void ClientSignal() noexcept {
288
		assert(thread.IsInside());
289 290 291 292 293 294 295 296 297 298

		client_cond.signal();
	}

	/**
	 * The client calls this method to wait for command
	 * completion.
	 *
	 * Caller must lock the object.
	 */
299
	void ClientWait() noexcept {
300
		assert(!thread.IsInside());
301 302 303 304

		client_cond.wait(mutex);
	}

305 306 307 308 309 310 311
	/**
	 * 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.
	 */
312
	void CommandFinished() noexcept {
313
		assert(command != PlayerCommand::NONE);
314

315
		command = PlayerCommand::NONE;
316 317 318
		ClientSignal();
	}

319
	void LockCommandFinished() noexcept {
320
		const std::lock_guard<Mutex> protect(mutex);
321 322 323
		CommandFinished();
	}

324 325 326 327 328 329 330 331 332 333
	/**
	 * 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
	 */
334
	bool WaitOutputConsumed(unsigned threshold) noexcept;
335

336
	bool LockWaitOutputConsumed(unsigned threshold) noexcept {
337
		const std::lock_guard<Mutex> protect(mutex);
338 339 340
		return WaitOutputConsumed(threshold);
	}

341 342 343 344 345 346 347
private:
	/**
	 * Wait for the command to be finished by the player thread.
	 *
	 * To be called from the main thread.  Caller must lock the
	 * object.
	 */
348
	void WaitCommandLocked() noexcept {
349
		while (command != PlayerCommand::NONE)
350 351 352 353 354 355 356 357 358 359
			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.
	 */
360
	void SynchronousCommand(PlayerCommand cmd) noexcept {
361
		assert(command == PlayerCommand::NONE);
362 363 364 365 366 367 368 369 370 371 372 373 374

		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.
	 */
375
	void LockSynchronousCommand(PlayerCommand cmd) noexcept {
376
		const std::lock_guard<Mutex> protect(mutex);
377 378 379 380
		SynchronousCommand(cmd);
	}

public:
381
	/**
382
	 * Throws on error.
383
	 *
384
	 * @param song the song to be queued
385
	 */
386
	void Play(std::unique_ptr<DetachedSong> song);
387

388
	/**
389
	 * see PlayerCommand::CANCEL
390
	 */
391
	void LockCancel() noexcept;
Warren Dukes's avatar
Warren Dukes committed
392

393
	void LockSetPause(bool pause_flag) noexcept;
Warren Dukes's avatar
Warren Dukes committed
394

395
private:
396
	void PauseLocked() noexcept;
397

398
	void ClearError() noexcept {
399
		error_type = PlayerError::NONE;
400
		error = std::exception_ptr();
401 402
	}

403
public:
404
	void LockPause() noexcept;
Warren Dukes's avatar
Warren Dukes committed
405

406 407 408
	/**
	 * Set the player's #border_pause flag.
	 */
409
	void LockSetBorderPause(bool border_pause) noexcept;
410

411
	bool ApplyBorderPause() noexcept {
412 413 414 415 416
		if (border_pause)
			state = PlayerState::PAUSE;
		return border_pause;
	}

417
	void Kill() noexcept;
Warren Dukes's avatar
Warren Dukes committed
418

419
	gcc_pure
420
	player_status LockGetStatus() noexcept;
Warren Dukes's avatar
Warren Dukes committed
421

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

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

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

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

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

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

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

470
	void LockClearError() noexcept;
Warren Dukes's avatar
Warren Dukes committed
471

472
	PlayerError GetErrorType() const noexcept {
473 474 475
		return error_type;
	}

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

482
	void ClearTaggedSong() noexcept;
483 484 485 486 487 488

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

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

496
	void LockStop() noexcept;
497

498
	void LockUpdateAudio() noexcept;
499

500
private:
501
	void EnqueueSongLocked(std::unique_ptr<DetachedSong> song) noexcept;
502

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

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

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

525
	void SetCrossFade(float cross_fade_seconds) noexcept;
526

527
	float GetCrossFade() const noexcept {
528
		return cross_fade.duration;
529 530
	}

531
	void SetMixRampDb(float mixramp_db) noexcept;
532

533
	float GetMixRampDb() const noexcept {
534
		return cross_fade.mixramp_db;
535 536
	}

537
	void SetMixRampDelay(float mixramp_delay_seconds) noexcept;
538

539
	float GetMixRampDelay() const noexcept {
540
		return cross_fade.mixramp_delay;
541 542
	}

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

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

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

	void ApplyEnabled() override {
		LockUpdateAudio();
	}
560 561

private:
562
	void RunThread() noexcept;
563
};
564

Warren Dukes's avatar
Warren Dukes committed
565
#endif