1 /*
2 * Copyright 2003-2021 The Music Player Daemon Project
3 * http://www.musicpd.org
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /* \file
21 *
22 * The player thread controls the playback. It acts as a bridge
23 * between the decoder thread and the output thread(s): it receives
24 * #MusicChunk objects from the decoder, optionally mixes them
25 * (cross-fading), applies software volume, and sends them to the
26 * audio outputs via PlayerOutputs::Play()
27 * (i.e. MultipleOutputs::Play()).
28 *
29 * It is controlled by the main thread (the playlist code), see
30 * Control.hxx. The playlist enqueues new songs into the player
31 * thread and sends it commands.
32 *
33 * The player thread itself does not do any I/O. It synchronizes with
34 * other threads via #GMutex and #GCond objects, and passes
35 * #MusicChunk instances around in #MusicPipe objects.
36 */
37
38 #include "Control.hxx"
39 #include "Outputs.hxx"
40 #include "Listener.hxx"
41 #include "decoder/Control.hxx"
42 #include "MusicPipe.hxx"
43 #include "MusicBuffer.hxx"
44 #include "MusicChunk.hxx"
45 #include "song/DetachedSong.hxx"
46 #include "CrossFade.hxx"
47 #include "tag/Tag.hxx"
48 #include "Idle.hxx"
49 #include "util/Compiler.h"
50 #include "util/Domain.hxx"
51 #include "thread/Name.hxx"
52 #include "Log.hxx"
53
54 #include <exception>
55 #include <memory>
56
57 #include <string.h>
58
59 static constexpr Domain player_domain("player");
60
61 /**
62 * Start playback as soon as enough data for this duration has been
63 * pushed to the decoder pipe.
64 */
65 static constexpr auto buffer_before_play_duration = std::chrono::seconds(1);
66
67 class Player {
68 PlayerControl &pc;
69
70 DecoderControl &dc;
71
72 MusicBuffer &buffer;
73
74 std::shared_ptr<MusicPipe> pipe;
75
76 /**
77 * the song currently being played
78 */
79 std::unique_ptr<DetachedSong> song;
80
81 /**
82 * The tag of the "next" song during cross-fade. It is
83 * postponed, and sent to the output thread when the new song
84 * really begins.
85 */
86 std::unique_ptr<Tag> cross_fade_tag;
87
88 /**
89 * Start playback as soon as this number of chunks has been
90 * pushed to the decoder pipe. This is calculated based on
91 * #buffer_before_play_duration.
92 */
93 unsigned buffer_before_play;
94
95 /**
96 * If the decoder pipe gets consumed below this threshold,
97 * it's time to wake up the decoder.
98 *
99 * It is calculated in a way which should prevent a wakeup
100 * after each single consumed chunk; it is more efficient to
101 * make the decoder decode a larger block at a time.
102 */
103 const unsigned decoder_wakeup_threshold;
104
105 /**
106 * Are we waiting for #buffer_before_play?
107 */
108 bool buffering = true;
109
110 /**
111 * true if the decoder is starting and did not provide data
112 * yet
113 */
114 bool decoder_starting = false;
115
116 /**
117 * Did we wake up the DecoderThread recently? This avoids
118 * duplicate wakeup calls.
119 */
120 bool decoder_woken = false;
121
122 /**
123 * is the player paused?
124 */
125 bool paused = false;
126
127 /**
128 * is there a new song in pc.next_song?
129 */
130 bool queued = true;
131
132 /**
133 * Was any audio output opened successfully? It might have
134 * failed meanwhile, but was not explicitly closed by the
135 * player thread. When this flag is unset, some output
136 * methods must not be called.
137 */
138 bool output_open = false;
139
140 /**
141 * Is cross-fading to the next song enabled?
142 */
143 enum class CrossFadeState : uint8_t {
144 /**
145 * The initial state: we don't know yet if we will
146 * cross-fade; it will be determined soon.
147 */
148 UNKNOWN,
149
150 /**
151 * Cross-fading is disabled for the transition to the
152 * next song.
153 */
154 DISABLED,
155
156 /**
157 * Cross-fading is enabled (but may not yet be in
158 * progress), will start near the end of the current
159 * song.
160 */
161 ENABLED,
162
163 /**
164 * Currently cross-fading to the next song.
165 */
166 ACTIVE,
167 } xfade_state = CrossFadeState::UNKNOWN;
168
169 /**
170 * The number of chunks used for crossfading.
171 */
172 unsigned cross_fade_chunks = 0;
173
174 /**
175 * The current audio format for the audio outputs.
176 */
177 AudioFormat play_audio_format = AudioFormat::Undefined();
178
179 /**
180 * The time stamp of the chunk most recently sent to the
181 * output thread. This attribute is only used if
182 * MultipleOutputs::GetElapsedTime() didn't return a usable
183 * value; the output thread can estimate the elapsed time more
184 * precisely.
185 */
186 SongTime elapsed_time = SongTime::zero();
187
188 /**
189 * If this is positive, then we need to ask the decoder to
190 * seek after it has completed startup. This is needed if the
191 * decoder is in the middle of startup while the player
192 * receives another seek command.
193 *
194 * This is only valid while #decoder_starting is true.
195 */
196 SongTime pending_seek;
197
198 public:
Player(PlayerControl & _pc,DecoderControl & _dc,MusicBuffer & _buffer)199 Player(PlayerControl &_pc, DecoderControl &_dc,
200 MusicBuffer &_buffer) noexcept
201 :pc(_pc), dc(_dc), buffer(_buffer),
202 decoder_wakeup_threshold(buffer.GetSize() * 3 / 4)
203 {
204 }
205
206 private:
207 /**
208 * Reset cross-fading to the initial state. A check to
209 * re-enable it at an appropriate time will be scheduled.
210 */
ResetCrossFade()211 void ResetCrossFade() noexcept {
212 xfade_state = CrossFadeState::UNKNOWN;
213 }
214
215 template<typename P>
ReplacePipe(P && _pipe)216 void ReplacePipe(P &&_pipe) noexcept {
217 ResetCrossFade();
218 pipe = std::forward<P>(_pipe);
219 }
220
221 /**
222 * Start the decoder.
223 *
224 * Caller must lock the mutex.
225 */
226 void StartDecoder(std::unique_lock<Mutex> &lock,
227 std::shared_ptr<MusicPipe> pipe,
228 bool initial_seek_essential) noexcept;
229
230 /**
231 * The decoder has acknowledged the "START" command (see
232 * ActivateDecoder()). This function checks if the decoder
233 * initialization has completed yet. If not, it will wait
234 * some more.
235 *
236 * Caller must lock the mutex.
237 *
238 * @return false if the decoder has failed, true on success
239 * (though the decoder startup may or may not yet be finished)
240 */
241 bool CheckDecoderStartup(std::unique_lock<Mutex> &lock) noexcept;
242
243 /**
244 * Stop the decoder and clears (and frees) its music pipe.
245 *
246 * Caller must lock the mutex.
247 */
248 void StopDecoder(std::unique_lock<Mutex> &lock) noexcept;
249
250 /**
251 * Is the decoder still busy on the same song as the player?
252 *
253 * Note: this function does not check if the decoder is already
254 * finished.
255 */
256 [[nodiscard]] gcc_pure
IsDecoderAtCurrentSong() const257 bool IsDecoderAtCurrentSong() const noexcept {
258 assert(pipe != nullptr);
259
260 return dc.pipe == pipe;
261 }
262
263 /**
264 * Returns true if the decoder is decoding the next song (or has begun
265 * decoding it, or has finished doing it), and the player hasn't
266 * switched to that song yet.
267 */
268 [[nodiscard]] gcc_pure
IsDecoderAtNextSong() const269 bool IsDecoderAtNextSong() const noexcept {
270 return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
271 }
272
273 /**
274 * Invoke DecoderControl::Seek() and update our state or
275 * handle errors.
276 *
277 * Caller must lock the mutex.
278 *
279 * @return false if the decoder has failed
280 */
281 bool SeekDecoder(std::unique_lock<Mutex> &lock,
282 SongTime seek_time) noexcept;
283
284 /**
285 * This is the handler for the #PlayerCommand::SEEK command.
286 *
287 * Caller must lock the mutex.
288 *
289 * @return false if the decoder has failed
290 */
291 bool SeekDecoder(std::unique_lock<Mutex> &lock) noexcept;
292
CancelPendingSeek()293 void CancelPendingSeek() noexcept {
294 pending_seek = SongTime::zero();
295 pc.CancelPendingSeek();
296 }
297
298 /**
299 * Check if the decoder has reported an error, and forward it
300 * to PlayerControl::SetError().
301 *
302 * @return false if an error has occurred
303 */
304 bool ForwardDecoderError() noexcept;
305
306 /**
307 * After the decoder has been started asynchronously, activate
308 * it for playback. That is, make the currently decoded song
309 * active (assign it to #song), clear PlayerControl::next_song
310 * and #queued, initialize #elapsed_time, and set
311 * #decoder_starting.
312 *
313 * When returning, the decoder may not have completed startup
314 * yet, therefore we don't know the audio format yet. To
315 * finish decoder startup, call CheckDecoderStartup().
316 *
317 * Caller must lock the mutex.
318 */
319 void ActivateDecoder() noexcept;
320
321 /**
322 * Wrapper for MultipleOutputs::Open(). Upon failure, it
323 * pauses the player.
324 *
325 * Caller must lock the mutex.
326 *
327 * @return true on success
328 */
329 bool OpenOutput() noexcept;
330
331 /**
332 * Obtains the next chunk from the music pipe, optionally applies
333 * cross-fading, and sends it to all audio outputs.
334 *
335 * @return true on success, false on error (playback will be stopped)
336 */
337 bool PlayNextChunk() noexcept;
338
UnlockCheckOutputs()339 unsigned UnlockCheckOutputs() noexcept {
340 const ScopeUnlock unlock(pc.mutex);
341 return pc.outputs.CheckPipe();
342 }
343
344 /**
345 * Player lock must be held before calling.
346 *
347 * @return false to stop playback
348 */
349 bool ProcessCommand(std::unique_lock<Mutex> &lock) noexcept;
350
351 /**
352 * This is called at the border between two songs: the audio output
353 * has consumed all chunks of the current song, and we should start
354 * sending chunks from the next one.
355 *
356 * Caller must lock the mutex.
357 */
358 void SongBorder() noexcept;
359
360 public:
361 /*
362 * The main loop of the player thread, during playback. This
363 * is basically a state machine, which multiplexes data
364 * between the decoder thread and the output threads.
365 */
366 void Run() noexcept;
367 };
368
369 void
StartDecoder(std::unique_lock<Mutex> & lock,std::shared_ptr<MusicPipe> _pipe,bool initial_seek_essential)370 Player::StartDecoder(std::unique_lock<Mutex> &lock,
371 std::shared_ptr<MusicPipe> _pipe,
372 bool initial_seek_essential) noexcept
373 {
374 assert(queued || pc.command == PlayerCommand::SEEK);
375 assert(pc.next_song != nullptr);
376
377 /* copy ReplayGain parameters to the decoder */
378 dc.replay_gain_mode = pc.replay_gain_mode;
379
380 SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
381
382 dc.Start(lock, std::make_unique<DetachedSong>(*pc.next_song),
383 start_time, pc.next_song->GetEndTime(),
384 initial_seek_essential,
385 buffer, std::move(_pipe));
386 }
387
388 void
StopDecoder(std::unique_lock<Mutex> & lock)389 Player::StopDecoder(std::unique_lock<Mutex> &lock) noexcept
390 {
391 const PlayerControl::ScopeOccupied occupied(pc);
392
393 dc.Stop(lock);
394
395 if (dc.pipe != nullptr) {
396 /* clear and free the decoder pipe */
397
398 dc.pipe->Clear();
399 dc.pipe.reset();
400
401 /* just in case we've been cross-fading: cancel it
402 now, because we just deleted the new song's decoder
403 pipe */
404 ResetCrossFade();
405 }
406 }
407
408 bool
ForwardDecoderError()409 Player::ForwardDecoderError() noexcept
410 {
411 try {
412 dc.CheckRethrowError();
413 } catch (...) {
414 pc.SetError(PlayerError::DECODER, std::current_exception());
415 return false;
416 }
417
418 return true;
419 }
420
421 void
ActivateDecoder()422 Player::ActivateDecoder() noexcept
423 {
424 assert(queued || pc.command == PlayerCommand::SEEK);
425 assert(pc.next_song != nullptr);
426
427 queued = false;
428
429 pc.ClearTaggedSong();
430
431 song = std::exchange(pc.next_song, nullptr);
432
433 elapsed_time = pc.seek_time;
434
435 /* set the "starting" flag, which will be cleared by
436 CheckDecoderStartup() */
437 decoder_starting = true;
438 pending_seek = SongTime::zero();
439
440 /* update PlayerControl's song information */
441 pc.total_time = song->GetDuration();
442 pc.bit_rate = 0;
443 pc.audio_format.Clear();
444
445 {
446 /* call playlist::SyncWithPlayer() in the main thread */
447 const ScopeUnlock unlock(pc.mutex);
448 pc.listener.OnPlayerSync();
449 }
450 }
451
452 /**
453 * Returns the real duration of the song, comprising the duration
454 * indicated by the decoder plugin.
455 */
456 static SignedSongTime
real_song_duration(const DetachedSong & song,SignedSongTime decoder_duration)457 real_song_duration(const DetachedSong &song,
458 SignedSongTime decoder_duration) noexcept
459 {
460 if (decoder_duration.IsNegative())
461 /* the decoder plugin didn't provide information; fall
462 back to Song::GetDuration() */
463 return song.GetDuration();
464
465 const SongTime start_time = song.GetStartTime();
466 const SongTime end_time = song.GetEndTime();
467
468 if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
469 return {end_time - start_time};
470
471 return {SongTime(decoder_duration) - start_time};
472 }
473
474 bool
OpenOutput()475 Player::OpenOutput() noexcept
476 {
477 assert(play_audio_format.IsDefined());
478 assert(pc.state == PlayerState::PLAY ||
479 pc.state == PlayerState::PAUSE);
480
481 try {
482 const ScopeUnlock unlock(pc.mutex);
483 pc.outputs.Open(play_audio_format);
484 } catch (...) {
485 LogError(std::current_exception());
486
487 output_open = false;
488
489 /* pause: the user may resume playback as soon as an
490 audio output becomes available */
491 paused = true;
492
493 pc.SetOutputError(std::current_exception());
494
495 idle_add(IDLE_PLAYER);
496
497 return false;
498 }
499
500 output_open = true;
501 paused = false;
502
503 pc.state = PlayerState::PLAY;
504
505 idle_add(IDLE_PLAYER);
506
507 return true;
508 }
509
510 inline bool
CheckDecoderStartup(std::unique_lock<Mutex> & lock)511 Player::CheckDecoderStartup(std::unique_lock<Mutex> &lock) noexcept
512 {
513 assert(decoder_starting);
514
515 if (!ForwardDecoderError()) {
516 /* the decoder failed */
517 return false;
518 } else if (!dc.IsStarting()) {
519 /* the decoder is ready and ok */
520
521 if (output_open &&
522 !pc.WaitOutputConsumed(lock, 1))
523 /* the output devices havn't finished playing
524 all chunks yet - wait for that */
525 return true;
526
527 pc.total_time = real_song_duration(*dc.song,
528 dc.total_time);
529 pc.audio_format = dc.in_audio_format;
530 play_audio_format = dc.out_audio_format;
531 decoder_starting = false;
532
533 const size_t buffer_before_play_size =
534 play_audio_format.TimeToSize(buffer_before_play_duration);
535 buffer_before_play =
536 (buffer_before_play_size + sizeof(MusicChunk::data) - 1)
537 / sizeof(MusicChunk::data);
538
539 idle_add(IDLE_PLAYER);
540
541 if (pending_seek > SongTime::zero()) {
542 assert(pc.seeking);
543
544 bool success = SeekDecoder(lock, pending_seek);
545 pc.seeking = false;
546 pc.ClientSignal();
547 if (!success)
548 return false;
549
550 /* re-fill the buffer after seeking */
551 buffering = true;
552 } else if (pc.seeking) {
553 pc.seeking = false;
554 pc.ClientSignal();
555
556 /* re-fill the buffer after seeking */
557 buffering = true;
558 }
559
560 if (!paused && !OpenOutput()) {
561 FmtError(player_domain,
562 "problems opening audio device "
563 "while playing \"{}\"",
564 dc.song->GetURI());
565 return true;
566 }
567
568 return true;
569 } else {
570 /* the decoder is not yet ready; wait
571 some more */
572 dc.WaitForDecoder(lock);
573
574 return true;
575 }
576 }
577
578 bool
SeekDecoder(std::unique_lock<Mutex> & lock,SongTime seek_time)579 Player::SeekDecoder(std::unique_lock<Mutex> &lock, SongTime seek_time) noexcept
580 {
581 assert(song);
582 assert(!decoder_starting);
583
584 if (!pc.total_time.IsNegative()) {
585 const SongTime total_time(pc.total_time);
586 if (seek_time > total_time)
587 seek_time = total_time;
588 }
589
590 try {
591 const PlayerControl::ScopeOccupied occupied(pc);
592
593 dc.Seek(lock, song->GetStartTime() + seek_time);
594 } catch (...) {
595 /* decoder failure */
596 pc.SetError(PlayerError::DECODER, std::current_exception());
597 return false;
598 }
599
600 elapsed_time = seek_time;
601 return true;
602 }
603
604 inline bool
SeekDecoder(std::unique_lock<Mutex> & lock)605 Player::SeekDecoder(std::unique_lock<Mutex> &lock) noexcept
606 {
607 assert(pc.next_song != nullptr);
608
609 if (pc.seek_time > SongTime::zero() && // TODO: allow this only if the song duration is known
610 dc.IsUnseekableCurrentSong(*pc.next_song)) {
611 /* seeking into the current song; but we already know
612 it's not seekable, so let's fail early */
613 /* note the seek_time>0 check: if seeking to the
614 beginning, we can simply restart the decoder */
615 pc.next_song.reset();
616 pc.SetError(PlayerError::DECODER,
617 std::make_exception_ptr(std::runtime_error("Not seekable")));
618 pc.CommandFinished();
619 return true;
620 }
621
622 CancelPendingSeek();
623
624 {
625 const ScopeUnlock unlock(pc.mutex);
626 pc.outputs.Cancel();
627 }
628
629 idle_add(IDLE_PLAYER);
630
631 if (!dc.IsSeekableCurrentSong(*pc.next_song)) {
632 /* the decoder is already decoding the "next" song -
633 stop it and start the previous song again */
634
635 StopDecoder(lock);
636
637 /* clear music chunks which might still reside in the
638 pipe */
639 pipe->Clear();
640
641 /* re-start the decoder */
642 StartDecoder(lock, pipe, true);
643 ActivateDecoder();
644
645 pc.seeking = true;
646 pc.CommandFinished();
647
648 assert(xfade_state == CrossFadeState::UNKNOWN);
649
650 return true;
651 } else {
652 if (!IsDecoderAtCurrentSong()) {
653 /* the decoder is already decoding the "next" song,
654 but it is the same song file; exchange the pipe */
655 ReplacePipe(dc.pipe);
656 }
657
658 pc.next_song.reset();
659 queued = false;
660
661 if (decoder_starting) {
662 /* wait for the decoder to complete
663 initialization; postpone the SEEK
664 command */
665
666 pending_seek = pc.seek_time;
667 pc.seeking = true;
668 pc.CommandFinished();
669 return true;
670 } else {
671 /* send the SEEK command */
672
673 if (!SeekDecoder(lock, pc.seek_time)) {
674 pc.CommandFinished();
675 return false;
676 }
677 }
678 }
679
680 pc.CommandFinished();
681
682 assert(xfade_state == CrossFadeState::UNKNOWN);
683
684 /* re-fill the buffer after seeking */
685 buffering = true;
686
687 {
688 /* call syncPlaylistWithQueue() in the main thread */
689 const ScopeUnlock unlock(pc.mutex);
690 pc.listener.OnPlayerSync();
691 }
692
693 return true;
694 }
695
696 inline bool
ProcessCommand(std::unique_lock<Mutex> & lock)697 Player::ProcessCommand(std::unique_lock<Mutex> &lock) noexcept
698 {
699 switch (pc.command) {
700 case PlayerCommand::NONE:
701 break;
702
703 case PlayerCommand::STOP:
704 case PlayerCommand::EXIT:
705 case PlayerCommand::CLOSE_AUDIO:
706 return false;
707
708 case PlayerCommand::UPDATE_AUDIO:
709 {
710 const ScopeUnlock unlock(pc.mutex);
711 pc.outputs.EnableDisable();
712 }
713
714 pc.CommandFinished();
715 break;
716
717 case PlayerCommand::QUEUE:
718 assert(pc.next_song != nullptr);
719 assert(!queued);
720 assert(!IsDecoderAtNextSong());
721
722 queued = true;
723 pc.CommandFinished();
724
725 if (dc.IsIdle())
726 StartDecoder(lock, std::make_shared<MusicPipe>(),
727 false);
728
729 break;
730
731 case PlayerCommand::PAUSE:
732 paused = !paused;
733 if (paused) {
734 pc.state = PlayerState::PAUSE;
735
736 const ScopeUnlock unlock(pc.mutex);
737 pc.outputs.Pause();
738 } else if (!play_audio_format.IsDefined()) {
739 /* the decoder hasn't provided an audio format
740 yet - don't open the audio device yet */
741 pc.state = PlayerState::PLAY;
742 } else {
743 OpenOutput();
744 }
745
746 pc.CommandFinished();
747 break;
748
749 case PlayerCommand::SEEK:
750 return SeekDecoder(lock);
751
752 case PlayerCommand::CANCEL:
753 if (pc.next_song == nullptr)
754 /* the cancel request arrived too late, we're
755 already playing the queued song... stop
756 everything now */
757 return false;
758
759 if (IsDecoderAtNextSong())
760 /* the decoder is already decoding the song -
761 stop it and reset the position */
762 StopDecoder(lock);
763
764 pc.next_song.reset();
765 queued = false;
766 pc.CommandFinished();
767 break;
768
769 case PlayerCommand::REFRESH:
770 if (output_open && !paused) {
771 const ScopeUnlock unlock(pc.mutex);
772 pc.outputs.CheckPipe();
773 }
774
775 pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
776 ? SongTime(pc.outputs.GetElapsedTime())
777 : elapsed_time;
778
779 pc.CommandFinished();
780 break;
781 }
782
783 return true;
784 }
785
786 inline void
LockUpdateSongTag(DetachedSong & song,const Tag & new_tag)787 PlayerControl::LockUpdateSongTag(DetachedSong &song,
788 const Tag &new_tag) noexcept
789 {
790 if (song.IsFile())
791 /* don't update tags of local files, only remote
792 streams may change tags dynamically */
793 return;
794
795 song.SetTag(new_tag);
796
797 LockSetTaggedSong(song);
798
799 /* the main thread will update the playlist version when he
800 receives this event */
801 listener.OnPlayerTagModified();
802
803 /* notify all clients that the tag of the current song has
804 changed */
805 idle_add(IDLE_PLAYER);
806 }
807
808 inline void
PlayChunk(DetachedSong & song,MusicChunkPtr chunk,const AudioFormat & format)809 PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk,
810 const AudioFormat &format)
811 {
812 assert(chunk->CheckFormat(format));
813
814 if (chunk->tag != nullptr)
815 LockUpdateSongTag(song, *chunk->tag);
816
817 if (chunk->IsEmpty())
818 return;
819
820 {
821 const std::scoped_lock<Mutex> lock(mutex);
822 bit_rate = chunk->bit_rate;
823 }
824
825 /* send the chunk to the audio outputs */
826
827 const double chunk_length(chunk->length);
828
829 outputs.Play(std::move(chunk));
830 total_play_time += format.SizeToTime<decltype(total_play_time)>(chunk_length);
831 }
832
833 inline bool
PlayNextChunk()834 Player::PlayNextChunk() noexcept
835 {
836 if (!pc.LockWaitOutputConsumed(64))
837 /* the output pipe is still large enough, don't send
838 another chunk */
839 return true;
840
841 /* activate cross-fading? */
842 if (xfade_state == CrossFadeState::ENABLED &&
843 IsDecoderAtNextSong() &&
844 pipe->GetSize() <= cross_fade_chunks) {
845 /* beginning of the cross fade - adjust
846 cross_fade_chunks which might be bigger than the
847 remaining number of chunks in the old song */
848 cross_fade_chunks = pipe->GetSize();
849 xfade_state = CrossFadeState::ACTIVE;
850 }
851
852 MusicChunkPtr chunk;
853 if (xfade_state == CrossFadeState::ACTIVE) {
854 /* perform cross fade */
855
856 assert(IsDecoderAtNextSong());
857
858 unsigned cross_fade_position = pipe->GetSize();
859 assert(cross_fade_position <= cross_fade_chunks);
860
861 auto other_chunk = dc.pipe->Shift();
862 if (other_chunk != nullptr) {
863 chunk = pipe->Shift();
864 assert(chunk != nullptr);
865 assert(chunk->other == nullptr);
866
867 /* don't send the tags of the new song (which
868 is being faded in) yet; postpone it until
869 the current song is faded out */
870 cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
871 std::move(other_chunk->tag));
872
873 if (pc.cross_fade.mixramp_delay <= FloatDuration::zero()) {
874 chunk->mix_ratio = ((float)cross_fade_position)
875 / cross_fade_chunks;
876 } else {
877 chunk->mix_ratio = -1;
878 }
879
880 if (other_chunk->IsEmpty()) {
881 /* the "other" chunk was a MusicChunk
882 which had only a tag, but no music
883 data - we cannot cross-fade that;
884 but since this happens only at the
885 beginning of the new song, we can
886 easily recover by throwing it away
887 now */
888 other_chunk.reset();
889 }
890
891 chunk->other = std::move(other_chunk);
892 } else {
893 /* there are not enough decoded chunks yet */
894
895 std::unique_lock<Mutex> lock(pc.mutex);
896
897 if (dc.IsIdle()) {
898 /* the decoder isn't running, abort
899 cross fading */
900 xfade_state = CrossFadeState::DISABLED;
901 } else {
902 /* wait for the decoder */
903 dc.Signal();
904 dc.WaitForDecoder(lock);
905
906 return true;
907 }
908 }
909 }
910
911 if (chunk == nullptr)
912 chunk = pipe->Shift();
913
914 assert(chunk != nullptr);
915
916 /* insert the postponed tag if cross-fading is finished */
917
918 if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
919 chunk->tag = Tag::Merge(std::move(chunk->tag),
920 std::move(cross_fade_tag));
921 cross_fade_tag = nullptr;
922 }
923
924 /* play the current chunk */
925
926 try {
927 pc.PlayChunk(*song, std::move(chunk),
928 play_audio_format);
929 } catch (...) {
930 LogError(std::current_exception());
931
932 chunk.reset();
933
934 /* pause: the user may resume playback as soon as an
935 audio output becomes available */
936 paused = true;
937
938 pc.LockSetOutputError(std::current_exception());
939
940 idle_add(IDLE_PLAYER);
941
942 return false;
943 }
944
945 const std::scoped_lock<Mutex> lock(pc.mutex);
946
947 /* this formula should prevent that the decoder gets woken up
948 with each chunk; it is more efficient to make it decode a
949 larger block at a time */
950 if (!dc.IsIdle() && dc.pipe->GetSize() <= decoder_wakeup_threshold) {
951 if (!decoder_woken) {
952 decoder_woken = true;
953 dc.Signal();
954 }
955 } else
956 decoder_woken = false;
957
958 return true;
959 }
960
961 inline void
SongBorder()962 Player::SongBorder() noexcept
963 {
964 {
965 const ScopeUnlock unlock(pc.mutex);
966
967 FmtNotice(player_domain, "played \"{}\"", song->GetURI());
968
969 ReplacePipe(dc.pipe);
970
971 pc.outputs.SongBorder();
972 }
973
974 ActivateDecoder();
975
976 const bool border_pause = pc.ApplyBorderPause();
977 if (border_pause) {
978 paused = true;
979 pc.listener.OnBorderPause();
980
981 /* drain all outputs to guarantee the current song is
982 really being played to the end; without this, the
983 Pause() call would drop all ring buffers */
984 pc.outputs.Drain();
985
986 pc.outputs.Pause();
987 idle_add(IDLE_PLAYER);
988 }
989 }
990
991 inline void
Run()992 Player::Run() noexcept
993 {
994 pipe = std::make_shared<MusicPipe>();
995
996 std::unique_lock<Mutex> lock(pc.mutex);
997
998 StartDecoder(lock, pipe, true);
999 ActivateDecoder();
1000
1001 pc.state = PlayerState::PLAY;
1002
1003 pc.CommandFinished();
1004
1005 while (ProcessCommand(lock)) {
1006 if (decoder_starting) {
1007 /* wait until the decoder is initialized completely */
1008
1009 if (!CheckDecoderStartup(lock))
1010 break;
1011
1012 continue;
1013 }
1014
1015 if (buffering) {
1016 /* buffering at the start of the song - wait
1017 until the buffer is large enough, to
1018 prevent stuttering on slow machines */
1019
1020 if (pipe->GetSize() < buffer_before_play &&
1021 !dc.IsIdle() && !buffer.IsFull()) {
1022 /* not enough decoded buffer space yet */
1023
1024 dc.WaitForDecoder(lock);
1025 continue;
1026 } else {
1027 /* buffering is complete */
1028 buffering = false;
1029 }
1030 }
1031
1032 if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) {
1033 /* the decoder has finished the current song;
1034 make it decode the next song */
1035
1036 assert(dc.pipe == nullptr || dc.pipe == pipe);
1037
1038 StartDecoder(lock, std::make_shared<MusicPipe>(),
1039 false);
1040 }
1041
1042 if (/* no cross-fading if MPD is going to pause at the
1043 end of the current song */
1044 !pc.border_pause &&
1045 IsDecoderAtNextSong() &&
1046 xfade_state == CrossFadeState::UNKNOWN &&
1047 !dc.IsStarting()) {
1048 /* enable cross fading in this song? if yes,
1049 calculate how many chunks will be required
1050 for it */
1051 cross_fade_chunks =
1052 pc.cross_fade.Calculate(pc.total_time,
1053 dc.total_time,
1054 dc.replay_gain_db,
1055 dc.replay_gain_prev_db,
1056 dc.GetMixRampStart(),
1057 dc.GetMixRampPreviousEnd(),
1058 dc.out_audio_format,
1059 play_audio_format,
1060 buffer.GetSize() -
1061 buffer_before_play);
1062 if (cross_fade_chunks > 0)
1063 xfade_state = CrossFadeState::ENABLED;
1064 else
1065 /* cross fading is disabled or the
1066 next song is too short */
1067 xfade_state = CrossFadeState::DISABLED;
1068 }
1069
1070 if (paused) {
1071 if (pc.command == PlayerCommand::NONE)
1072 pc.Wait(lock);
1073 } else if (!pipe->IsEmpty()) {
1074 /* at least one music chunk is ready - send it
1075 to the audio output */
1076
1077 const ScopeUnlock unlock(pc.mutex);
1078 PlayNextChunk();
1079 } else if (UnlockCheckOutputs() > 0) {
1080 /* not enough data from decoder, but the
1081 output thread is still busy, so it's
1082 okay */
1083
1084 /* wake up the decoder (just in case it's
1085 waiting for space in the MusicBuffer) and
1086 wait for it */
1087 // TODO: eliminate this kludge
1088 dc.Signal();
1089
1090 dc.WaitForDecoder(lock);
1091 } else if (IsDecoderAtNextSong()) {
1092 /* at the beginning of a new song */
1093
1094 SongBorder();
1095 } else if (dc.IsIdle()) {
1096 if (queued)
1097 /* the decoder has just stopped,
1098 between the two IsIdle() checks,
1099 probably while UnlockCheckOutputs()
1100 left the mutex unlocked; to restart
1101 the decoder instead of stopping
1102 playback completely, let's re-enter
1103 this loop */
1104 continue;
1105
1106 /* check the size of the pipe again, because
1107 the decoder thread may have added something
1108 since we last checked */
1109 if (pipe->IsEmpty()) {
1110 /* wait for the hardware to finish
1111 playback */
1112 const ScopeUnlock unlock(pc.mutex);
1113 pc.outputs.Drain();
1114 break;
1115 }
1116 } else if (output_open) {
1117 /* the decoder is too busy and hasn't provided
1118 new PCM data in time: wait for the
1119 decoder */
1120
1121 /* wake up the decoder (just in case it's
1122 waiting for space in the MusicBuffer) and
1123 wait for it */
1124 // TODO: eliminate this kludge
1125 dc.Signal();
1126
1127 dc.WaitForDecoder(lock);
1128 }
1129 }
1130
1131 CancelPendingSeek();
1132 StopDecoder(lock);
1133
1134 pipe.reset();
1135
1136 cross_fade_tag.reset();
1137
1138 if (song != nullptr) {
1139 FmtNotice(player_domain, "played \"{}\"", song->GetURI());
1140 song.reset();
1141 }
1142
1143 pc.ClearTaggedSong();
1144
1145 if (queued) {
1146 assert(pc.next_song != nullptr);
1147 pc.next_song.reset();
1148 }
1149
1150 pc.state = PlayerState::STOP;
1151 }
1152
1153 static void
do_play(PlayerControl & pc,DecoderControl & dc,MusicBuffer & buffer)1154 do_play(PlayerControl &pc, DecoderControl &dc,
1155 MusicBuffer &buffer) noexcept
1156 {
1157 Player player(pc, dc, buffer);
1158 player.Run();
1159 }
1160
1161 void
RunThread()1162 PlayerControl::RunThread() noexcept
1163 try {
1164 SetThreadName("player");
1165
1166 DecoderControl dc(mutex, cond,
1167 input_cache,
1168 configured_audio_format,
1169 replay_gain_config);
1170 dc.StartThread();
1171
1172 MusicBuffer buffer(buffer_chunks);
1173
1174 std::unique_lock<Mutex> lock(mutex);
1175
1176 while (true) {
1177 switch (command) {
1178 case PlayerCommand::SEEK:
1179 case PlayerCommand::QUEUE:
1180 assert(next_song != nullptr);
1181
1182 {
1183 const ScopeUnlock unlock(mutex);
1184 do_play(*this, dc, buffer);
1185
1186 /* give the main thread a chance to
1187 queue another song, just in case
1188 we've stopped playback
1189 spuriously */
1190 listener.OnPlayerSync();
1191 }
1192
1193 break;
1194
1195 case PlayerCommand::STOP:
1196 {
1197 const ScopeUnlock unlock(mutex);
1198 outputs.Cancel();
1199 }
1200
1201 /* fall through */
1202 #if CLANG_OR_GCC_VERSION(7,0)
1203 [[fallthrough]];
1204 #endif
1205
1206 case PlayerCommand::PAUSE:
1207 next_song.reset();
1208
1209 CommandFinished();
1210 break;
1211
1212 case PlayerCommand::CLOSE_AUDIO:
1213 {
1214 const ScopeUnlock unlock(mutex);
1215 outputs.Release();
1216 }
1217
1218 CommandFinished();
1219
1220 assert(buffer.IsEmptyUnsafe());
1221
1222 break;
1223
1224 case PlayerCommand::UPDATE_AUDIO:
1225 {
1226 const ScopeUnlock unlock(mutex);
1227 outputs.EnableDisable();
1228 }
1229
1230 CommandFinished();
1231 break;
1232
1233 case PlayerCommand::EXIT:
1234 {
1235 const ScopeUnlock unlock(mutex);
1236 dc.Quit();
1237 outputs.Close();
1238 }
1239
1240 CommandFinished();
1241 return;
1242
1243 case PlayerCommand::CANCEL:
1244 next_song.reset();
1245
1246 CommandFinished();
1247 break;
1248
1249 case PlayerCommand::REFRESH:
1250 /* no-op when not playing */
1251 CommandFinished();
1252 break;
1253
1254 case PlayerCommand::NONE:
1255 Wait(lock);
1256 break;
1257 }
1258 }
1259 } catch (...) {
1260 /* exceptions caught here are thrown during initialization;
1261 the main loop doesn't throw */
1262
1263 LogError(std::current_exception());
1264
1265 /* TODO: what now? How will the main thread learn about this
1266 failure? */
1267 }
1268