From 62f6179abe24339c2e5b7350528afbcad4c52067 Mon Sep 17 00:00:00 2001 From: ailurux Date: Thu, 15 Feb 2024 16:12:07 +1100 Subject: Added offset for track seeking, wav impl. only rn --- src/audio/audio_decoder.cpp | 11 +++++++---- src/audio/audio_fsm.cpp | 12 ++++++++++-- src/audio/audio_source.cpp | 9 +++++++-- src/audio/fatfs_audio_input.cpp | 8 ++++---- src/audio/include/audio_decoder.hpp | 2 +- src/audio/include/audio_events.hpp | 5 +++++ src/audio/include/audio_fsm.hpp | 3 +++ src/audio/include/audio_source.hpp | 6 +++++- src/audio/include/fatfs_audio_input.hpp | 4 ++-- 9 files changed, 44 insertions(+), 16 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index b0a973d9..02cf27e3 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -51,9 +51,10 @@ static constexpr std::size_t kCodecBufferLength = drivers::kI2SBufferLengthFrames * sizeof(sample::Sample); Timer::Timer(std::shared_ptr t, - const codecs::ICodec::OutputFormat& format) + const codecs::ICodec::OutputFormat& format, + uint32_t current_seconds) : track_(t), - current_seconds_(0), + current_seconds_(current_seconds), current_sample_in_second_(0), samples_per_second_(format.sample_rate_hz * format.num_channels), total_duration_seconds_(format.total_samples.value_or(0) / @@ -131,7 +132,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { return false; } - auto open_res = codec_->OpenStream(stream); + auto open_res = codec_->OpenStream(stream, stream->Offset()); if (open_res.has_error()) { ESP_LOGE(kTag, "codec failed to start: %s", codecs::ICodec::ErrorString(open_res.error()).c_str()); @@ -147,6 +148,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { ESP_LOGI(kTag, "stream started ok"); events::Audio().Dispatch(internal::InputFileOpened{}); + // TODO: How does this need to change? auto tags = std::make_shared(Track{ .tags = stream->tags(), .db_info = {}, @@ -155,7 +157,8 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { }); timer_.reset(new Timer(tags, open_res.value())); - PlaybackUpdate ev{.seconds_elapsed = 0, .track = tags}; + // TODO: How does *this?* need to change? + PlaybackUpdate ev{.seconds_elapsed = stream->Offset(), .track = tags}; events::Audio().Dispatch(ev); events::Ui().Dispatch(ev); diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index ba6e5ffe..c67cfc7a 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -244,11 +244,19 @@ void Uninitialised::react(const system_fsm::BootComplete& ev) { } void Standby::react(const PlayFile& ev) { - sFileSource->SetPath(ev.filename); + sFileSource->SetPath(ev.filename, 10); } void Playback::react(const PlayFile& ev) { - sFileSource->SetPath(ev.filename); + sFileSource->SetPath(ev.filename, 15); +} + +void Standby::react(const SeekFile& ev) { + sFileSource->SetPath(ev.filename, ev.offset); +} + +void Playback::react(const SeekFile& ev) { + sFileSource->SetPath(ev.filename, ev.offset); } void Standby::react(const internal::InputFileOpened& ev) { diff --git a/src/audio/audio_source.cpp b/src/audio/audio_source.cpp index 44de1d1b..2543db44 100644 --- a/src/audio/audio_source.cpp +++ b/src/audio/audio_source.cpp @@ -11,8 +11,9 @@ namespace audio { TaggedStream::TaggedStream(std::shared_ptr t, - std::unique_ptr w) - : codecs::IStream(w->type()), tags_(t), wrapped_(std::move(w)) {} + std::unique_ptr w, + uint32_t offset) + : codecs::IStream(w->type()), tags_(t), wrapped_(std::move(w)), offset_(offset) {} auto TaggedStream::tags() -> std::shared_ptr { return tags_; @@ -38,6 +39,10 @@ auto TaggedStream::Size() -> std::optional { return wrapped_->Size(); } +auto TaggedStream::Offset() -> uint32_t { + return offset_; +} + auto TaggedStream::SetPreambleFinished() -> void { wrapped_->SetPreambleFinished(); } diff --git a/src/audio/fatfs_audio_input.cpp b/src/audio/fatfs_audio_input.cpp index 7726a94a..665e8c1d 100644 --- a/src/audio/fatfs_audio_input.cpp +++ b/src/audio/fatfs_audio_input.cpp @@ -62,9 +62,9 @@ auto FatfsAudioInput::SetPath(std::optional path) -> void { } } -auto FatfsAudioInput::SetPath(const std::string& path) -> void { +auto FatfsAudioInput::SetPath(const std::string& path,uint32_t offset) -> void { std::lock_guard guard{new_stream_mutex_}; - if (OpenFile(path)) { + if (OpenFile(path, offset)) { has_new_stream_ = true; has_new_stream_.notify_one(); } @@ -103,7 +103,7 @@ auto FatfsAudioInput::NextStream() -> std::shared_ptr { } } -auto FatfsAudioInput::OpenFile(const std::string& path) -> bool { +auto FatfsAudioInput::OpenFile(const std::string& path,uint32_t offset) -> bool { ESP_LOGI(kTag, "opening file %s", path.c_str()); auto tags = tag_parser_.ReadAndParseTags(path); @@ -136,7 +136,7 @@ auto FatfsAudioInput::OpenFile(const std::string& path) -> bool { auto source = std::make_unique(stream_type.value(), std::move(file)); - new_stream_.reset(new TaggedStream(tags, std::move(source))); + new_stream_.reset(new TaggedStream(tags, std::move(source), offset)); return true; } diff --git a/src/audio/include/audio_decoder.hpp b/src/audio/include/audio_decoder.hpp index 318e6fd4..b8aac710 100644 --- a/src/audio/include/audio_decoder.hpp +++ b/src/audio/include/audio_decoder.hpp @@ -24,7 +24,7 @@ namespace audio { */ class Timer { public: - Timer(std::shared_ptr, const codecs::ICodec::OutputFormat& format); + Timer(std::shared_ptr, const codecs::ICodec::OutputFormat& format, uint32_t current_seconds = 0); auto AddSamples(std::size_t) -> void; diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index 03584062..8459333f 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -45,6 +45,11 @@ struct PlayFile : tinyfsm::Event { std::string filename; }; +struct SeekFile : tinyfsm::Event { + std::string filename; + uint32_t offset; +}; + struct StepUpVolume : tinyfsm::Event {}; struct StepDownVolume : tinyfsm::Event {}; struct SetVolume : tinyfsm::Event { diff --git a/src/audio/include/audio_fsm.hpp b/src/audio/include/audio_fsm.hpp index 29ec489a..71cd2701 100644 --- a/src/audio/include/audio_fsm.hpp +++ b/src/audio/include/audio_fsm.hpp @@ -57,6 +57,7 @@ class AudioState : public tinyfsm::Fsm { virtual void react(const system_fsm::BluetoothEvent&); virtual void react(const PlayFile&) {} + virtual void react(const SeekFile&) {} virtual void react(const QueueUpdate&) {} virtual void react(const PlaybackUpdate&) {} void react(const TogglePlayPause&); @@ -99,6 +100,7 @@ class Uninitialised : public AudioState { class Standby : public AudioState { public: void react(const PlayFile&) override; + void react(const SeekFile&) override; void react(const internal::InputFileOpened&) override; void react(const QueueUpdate&) override; void react(const system_fsm::KeyLockChanged&) override; @@ -115,6 +117,7 @@ class Playback : public AudioState { void react(const system_fsm::HasPhonesChanged&) override; void react(const PlayFile&) override; + void react(const SeekFile&) override; void react(const QueueUpdate&) override; void react(const PlaybackUpdate&) override; diff --git a/src/audio/include/audio_source.hpp b/src/audio/include/audio_source.hpp index 68145f5b..b2fd173d 100644 --- a/src/audio/include/audio_source.hpp +++ b/src/audio/include/audio_source.hpp @@ -16,7 +16,8 @@ namespace audio { class TaggedStream : public codecs::IStream { public: TaggedStream(std::shared_ptr, - std::unique_ptr wrapped); + std::unique_ptr wrapped, + uint32_t offset = 0); auto tags() -> std::shared_ptr; @@ -30,11 +31,14 @@ class TaggedStream : public codecs::IStream { auto Size() -> std::optional override; + auto Offset() -> uint32_t; + auto SetPreambleFinished() -> void override; private: std::shared_ptr tags_; std::unique_ptr wrapped_; + int32_t offset_; }; class IAudioSource { diff --git a/src/audio/include/fatfs_audio_input.hpp b/src/audio/include/fatfs_audio_input.hpp index 4cccbb46..10b7433e 100644 --- a/src/audio/include/fatfs_audio_input.hpp +++ b/src/audio/include/fatfs_audio_input.hpp @@ -39,7 +39,7 @@ class FatfsAudioInput : public IAudioSource { * given file path. */ auto SetPath(std::optional) -> void; - auto SetPath(const std::string&) -> void; + auto SetPath(const std::string&,uint32_t offset = 0) -> void; auto SetPath() -> void; auto HasNewStream() -> bool override; @@ -49,7 +49,7 @@ class FatfsAudioInput : public IAudioSource { FatfsAudioInput& operator=(const FatfsAudioInput&) = delete; private: - auto OpenFile(const std::string& path) -> bool; + auto OpenFile(const std::string& path,uint32_t offset) -> bool; auto ContainerToStreamType(database::Container) -> std::optional; -- cgit v1.2.3 From a49d754da6c293445be16ac643d10849c01ea96b Mon Sep 17 00:00:00 2001 From: ailurux Date: Fri, 16 Feb 2024 10:57:47 +1100 Subject: Seeking working with hardcoded event, wav only --- src/audio/audio_decoder.cpp | 2 +- src/audio/audio_fsm.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index 02cf27e3..eaa9ff9c 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -155,7 +155,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { .bitrate_kbps = open_res->sample_rate_hz, .encoding = stream->type(), }); - timer_.reset(new Timer(tags, open_res.value())); + timer_.reset(new Timer(tags, open_res.value(), stream->Offset())); // TODO: How does *this?* need to change? PlaybackUpdate ev{.seconds_elapsed = stream->Offset(), .track = tags}; diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index c67cfc7a..75e3c24a 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -244,11 +244,13 @@ void Uninitialised::react(const system_fsm::BootComplete& ev) { } void Standby::react(const PlayFile& ev) { + sCurrentTrack = 0; + sIsPlaybackAllowed = true; sFileSource->SetPath(ev.filename, 10); } void Playback::react(const PlayFile& ev) { - sFileSource->SetPath(ev.filename, 15); + sFileSource->SetPath(ev.filename, 10); } void Standby::react(const SeekFile& ev) { -- cgit v1.2.3 From 665679b8854d34c13d8eb92167aa8a4691619d8b Mon Sep 17 00:00:00 2001 From: ailurux Date: Fri, 16 Feb 2024 12:55:11 +1100 Subject: WIP: seeking in lua example --- src/audio/audio_decoder.cpp | 3 +-- src/audio/audio_fsm.cpp | 6 ++++-- src/audio/audio_source.cpp | 7 ++++++- src/audio/fatfs_audio_input.cpp | 2 +- src/audio/include/audio_events.hpp | 3 ++- src/audio/include/audio_source.hpp | 7 ++++++- 6 files changed, 20 insertions(+), 8 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index eaa9ff9c..68a8a86b 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -148,16 +148,15 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { ESP_LOGI(kTag, "stream started ok"); events::Audio().Dispatch(internal::InputFileOpened{}); - // TODO: How does this need to change? auto tags = std::make_shared(Track{ .tags = stream->tags(), .db_info = {}, .bitrate_kbps = open_res->sample_rate_hz, .encoding = stream->type(), + .filepath = stream->Filepath(), }); timer_.reset(new Timer(tags, open_res.value(), stream->Offset())); - // TODO: How does *this?* need to change? PlaybackUpdate ev{.seconds_elapsed = stream->Offset(), .track = tags}; events::Audio().Dispatch(ev); events::Ui().Dispatch(ev); diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 75e3c24a..0e213b6e 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -246,14 +246,16 @@ void Uninitialised::react(const system_fsm::BootComplete& ev) { void Standby::react(const PlayFile& ev) { sCurrentTrack = 0; sIsPlaybackAllowed = true; - sFileSource->SetPath(ev.filename, 10); + sFileSource->SetPath(ev.filename); } void Playback::react(const PlayFile& ev) { - sFileSource->SetPath(ev.filename, 10); + sFileSource->SetPath(ev.filename); } void Standby::react(const SeekFile& ev) { + sCurrentTrack = 0; + sIsPlaybackAllowed = true; sFileSource->SetPath(ev.filename, ev.offset); } diff --git a/src/audio/audio_source.cpp b/src/audio/audio_source.cpp index 2543db44..d9e8e04a 100644 --- a/src/audio/audio_source.cpp +++ b/src/audio/audio_source.cpp @@ -12,8 +12,9 @@ namespace audio { TaggedStream::TaggedStream(std::shared_ptr t, std::unique_ptr w, + std::string filepath, uint32_t offset) - : codecs::IStream(w->type()), tags_(t), wrapped_(std::move(w)), offset_(offset) {} + : codecs::IStream(w->type()), tags_(t), wrapped_(std::move(w)), filepath_(filepath), offset_(offset) {} auto TaggedStream::tags() -> std::shared_ptr { return tags_; @@ -43,6 +44,10 @@ auto TaggedStream::Offset() -> uint32_t { return offset_; } +auto TaggedStream::Filepath() -> std::string { + return filepath_; +} + auto TaggedStream::SetPreambleFinished() -> void { wrapped_->SetPreambleFinished(); } diff --git a/src/audio/fatfs_audio_input.cpp b/src/audio/fatfs_audio_input.cpp index 665e8c1d..74c1154b 100644 --- a/src/audio/fatfs_audio_input.cpp +++ b/src/audio/fatfs_audio_input.cpp @@ -136,7 +136,7 @@ auto FatfsAudioInput::OpenFile(const std::string& path,uint32_t offset) -> bool auto source = std::make_unique(stream_type.value(), std::move(file)); - new_stream_.reset(new TaggedStream(tags, std::move(source), offset)); + new_stream_.reset(new TaggedStream(tags, std::move(source), path, offset)); return true; } diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index 8459333f..96e77987 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -26,6 +26,7 @@ struct Track { uint32_t duration; uint32_t bitrate_kbps; codecs::StreamType encoding; + std::string filepath; }; struct PlaybackStarted : tinyfsm::Event {}; @@ -46,8 +47,8 @@ struct PlayFile : tinyfsm::Event { }; struct SeekFile : tinyfsm::Event { + uint32_t offset; std::string filename; - uint32_t offset; }; struct StepUpVolume : tinyfsm::Event {}; diff --git a/src/audio/include/audio_source.hpp b/src/audio/include/audio_source.hpp index b2fd173d..b38acd7a 100644 --- a/src/audio/include/audio_source.hpp +++ b/src/audio/include/audio_source.hpp @@ -17,7 +17,9 @@ class TaggedStream : public codecs::IStream { public: TaggedStream(std::shared_ptr, std::unique_ptr wrapped, - uint32_t offset = 0); + std::string path, + uint32_t offset = 0 + ); auto tags() -> std::shared_ptr; @@ -33,11 +35,14 @@ class TaggedStream : public codecs::IStream { auto Offset() -> uint32_t; + auto Filepath() -> std::string; + auto SetPreambleFinished() -> void override; private: std::shared_ptr tags_; std::unique_ptr wrapped_; + std::string filepath_; int32_t offset_; }; -- cgit v1.2.3 From c60bb9ee42eea2c88ef90228274bd28350a87ae4 Mon Sep 17 00:00:00 2001 From: ailurux Date: Fri, 16 Feb 2024 16:19:12 +1100 Subject: Fix issue with seeking whilst paused --- src/audio/audio_fsm.cpp | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 0e213b6e..bb7d33dc 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -254,8 +254,6 @@ void Playback::react(const PlayFile& ev) { } void Standby::react(const SeekFile& ev) { - sCurrentTrack = 0; - sIsPlaybackAllowed = true; sFileSource->SetPath(ev.filename, ev.offset); } -- cgit v1.2.3 From f54347794f45261e0c0fde1104a70d1063c77305 Mon Sep 17 00:00:00 2001 From: ailurux Date: Thu, 22 Feb 2024 14:37:14 +1100 Subject: WIP: Flac not working-- coming back to this later --- src/audio/audio_decoder.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src/audio') diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index 68a8a86b..6c26dec8 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -167,6 +167,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { auto Decoder::ContinueDecoding() -> bool { auto res = codec_->DecodeTo(codec_buffer_); if (res.has_error()) { + ESP_LOGI(kTag, "RAN INTO DECODING ERROR"); return true; } -- cgit v1.2.3 From 77145e56f4062cd060ee7fa0af9ad1a2e46df5b1 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Wed, 28 Feb 2024 21:21:23 +1100 Subject: basic working flac and mp3 seeking flac impl is fairly slow as it doesn't use the seek tables; for some reason miniflac seems to get *really* upset if you seek the stream. --- src/audio/audio_decoder.cpp | 1 - 1 file changed, 1 deletion(-) (limited to 'src/audio') diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index 6c26dec8..68a8a86b 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -167,7 +167,6 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { auto Decoder::ContinueDecoding() -> bool { auto res = codec_->DecodeTo(codec_buffer_); if (res.has_error()) { - ESP_LOGI(kTag, "RAN INTO DECODING ERROR"); return true; } -- cgit v1.2.3 From d41f9f703375171d5766840c9edec32ff47bb25d Mon Sep 17 00:00:00 2001 From: jacqueline Date: Thu, 29 Feb 2024 12:08:12 +1100 Subject: Use drflac instead of miniflac This one is fast as hell! Does seeking really good too. Thank u Doctor Flac. --- src/audio/audio_converter.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_converter.cpp b/src/audio/audio_converter.cpp index dc2fef95..946a0b63 100644 --- a/src/audio/audio_converter.cpp +++ b/src/audio/audio_converter.cpp @@ -77,9 +77,9 @@ auto SampleConverter::ConvertSamples(cpp::span input, reinterpret_cast(input.data()), input.size_bytes()}; size_t bytes_sent = 0; while (bytes_sent < input_as_bytes.size()) { - bytes_sent += - xStreamBufferSend(source_, input_as_bytes.subspan(bytes_sent).data(), - input_as_bytes.size() - bytes_sent, portMAX_DELAY); + bytes_sent += xStreamBufferSend( + source_, input_as_bytes.subspan(bytes_sent).data(), + input_as_bytes.size() - bytes_sent, pdMS_TO_TICKS(100)); } } -- cgit v1.2.3 From 173b09b0151ae765b1a8e69dfb60d14d502801f6 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Thu, 29 Feb 2024 15:47:21 +1100 Subject: Clear the drain buffer when skipping between tracks --- src/audio/audio_fsm.cpp | 53 +++++++++++++++++++++++++++------- src/audio/bt_audio_output.cpp | 2 +- src/audio/i2s_audio_output.cpp | 2 +- src/audio/include/audio_events.hpp | 8 ++++- src/audio/include/audio_fsm.hpp | 7 +++-- src/audio/include/audio_sink.hpp | 17 +++++++++-- src/audio/include/bt_audio_output.hpp | 5 ++-- src/audio/include/i2s_audio_output.hpp | 5 ++-- src/audio/include/track_queue.hpp | 3 ++ src/audio/track_queue.cpp | 43 ++++++++++++++++----------- 10 files changed, 106 insertions(+), 39 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index ea0315eb..08a0941a 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -51,6 +51,10 @@ std::shared_ptr AudioState::sI2SOutput; std::shared_ptr AudioState::sBtOutput; std::shared_ptr AudioState::sOutput; +// Two seconds of samples for two channels, at a representative sample rate. +constexpr size_t kDrainBufferSize = sizeof(sample::Sample) * 48000 * 4; +StreamBufferHandle_t AudioState::sDrainBuffer; + std::optional AudioState::sCurrentTrack; bool AudioState::sIsPlaybackAllowed; @@ -129,7 +133,7 @@ void AudioState::react(const SetVolumeBalance& ev) { void AudioState::react(const OutputModeChanged& ev) { ESP_LOGI(kTag, "output mode changed"); auto new_mode = sServices->nvs().OutputMode(); - sOutput->SetMode(IAudioOutput::Modes::kOff); + sOutput->mode(IAudioOutput::Modes::kOff); switch (new_mode) { case drivers::NvsStorage::Output::kBluetooth: sOutput = sBtOutput; @@ -138,7 +142,7 @@ void AudioState::react(const OutputModeChanged& ev) { sOutput = sI2SOutput; break; } - sOutput->SetMode(IAudioOutput::Modes::kOnPaused); + sOutput->mode(IAudioOutput::Modes::kOnPaused); sSampleConverter->SetOutput(sOutput); // Bluetooth volume isn't 'changed' until we've connected to a device. @@ -150,6 +154,32 @@ void AudioState::react(const OutputModeChanged& ev) { } } +auto AudioState::clearDrainBuffer() -> void { + // Tell the decoder to stop adding new samples. This might not take effect + // immediately, since the decoder might currently be stuck waiting for space + // to become available in the drain buffer. + sFileSource->SetPath(); + + auto mode = sOutput->mode(); + if (mode == IAudioOutput::Modes::kOnPlaying) { + // If we're currently playing, then the drain buffer will be actively + // draining on its own. Just keep trying to reset until it works. + while (xStreamBufferReset(sDrainBuffer) != pdPASS) { + } + } else { + // If we're not currently playing, then we need to actively pull samples + // out of the drain buffer to unblock the decoder. + while (!xStreamBufferIsEmpty(sDrainBuffer)) { + // Read a little to unblock the decoder. + uint8_t drain[2048]; + xStreamBufferReceive(sDrainBuffer, drain, sizeof(drain), 0); + + // Try to quickly discard the rest. + xStreamBufferReset(sDrainBuffer); + } + } +} + auto AudioState::playTrack(database::TrackId id) -> void { sCurrentTrack = id; sServices->bg_worker().Dispatch([=]() { @@ -194,10 +224,6 @@ void AudioState::react(const TogglePlayPause& ev) { namespace states { -// Two seconds of samples for two channels, at a representative sample rate. -constexpr size_t kDrainBufferSize = sizeof(sample::Sample) * 48000 * 4; -static StreamBufferHandle_t sDrainBuffer; - void Uninitialised::react(const system_fsm::BootComplete& ev) { sServices = ev.services; @@ -229,7 +255,7 @@ void Uninitialised::react(const system_fsm::BootComplete& ev) { } else { sOutput = sBtOutput; } - sOutput->SetMode(IAudioOutput::Modes::kOnPaused); + sOutput->mode(IAudioOutput::Modes::kOnPaused); events::Ui().Dispatch(VolumeLimitChanged{ .new_limit_db = @@ -272,6 +298,7 @@ void Standby::react(const QueueUpdate& ev) { if (!current_track || (sCurrentTrack && (*sCurrentTrack == *current_track))) { return; } + clearDrainBuffer(); playTrack(*current_track); } @@ -315,7 +342,7 @@ void Standby::react(const system_fsm::StorageMounted& ev) { void Playback::entry() { ESP_LOGI(kTag, "beginning playback"); - sOutput->SetMode(IAudioOutput::Modes::kOnPlaying); + sOutput->mode(IAudioOutput::Modes::kOnPlaying); events::System().Dispatch(PlaybackStarted{}); events::Ui().Dispatch(PlaybackStarted{}); @@ -323,10 +350,10 @@ void Playback::entry() { void Playback::exit() { ESP_LOGI(kTag, "finishing playback"); - sOutput->SetMode(IAudioOutput::Modes::kOnPaused); + sOutput->mode(IAudioOutput::Modes::kOnPaused); - // Stash the current volume now, in case it changed during playback, since we - // might be powering off soon. + // Stash the current volume now, in case it changed during playback, since + // we might be powering off soon. commitVolume(); events::System().Dispatch(PlaybackStopped{}); @@ -343,6 +370,10 @@ void Playback::react(const QueueUpdate& ev) { if (!ev.current_changed) { return; } + // Cut the current track immediately. + if (ev.reason == QueueUpdate::Reason::kExplicitUpdate) { + clearDrainBuffer(); + } auto current_track = sServices->track_queue().current(); if (!current_track) { sFileSource->SetPath(); diff --git a/src/audio/bt_audio_output.cpp b/src/audio/bt_audio_output.cpp index 41c89069..dff98e36 100644 --- a/src/audio/bt_audio_output.cpp +++ b/src/audio/bt_audio_output.cpp @@ -35,7 +35,7 @@ BluetoothAudioOutput::BluetoothAudioOutput(StreamBufferHandle_t s, BluetoothAudioOutput::~BluetoothAudioOutput() {} -auto BluetoothAudioOutput::SetMode(Modes mode) -> void { +auto BluetoothAudioOutput::changeMode(Modes mode) -> void { if (mode == Modes::kOnPlaying) { bluetooth_.SetSource(stream()); } else { diff --git a/src/audio/i2s_audio_output.cpp b/src/audio/i2s_audio_output.cpp index 4043574e..cd61d97f 100644 --- a/src/audio/i2s_audio_output.cpp +++ b/src/audio/i2s_audio_output.cpp @@ -58,7 +58,7 @@ I2SAudioOutput::~I2SAudioOutput() { dac_->SetSource(nullptr); } -auto I2SAudioOutput::SetMode(Modes mode) -> void { +auto I2SAudioOutput::changeMode(Modes mode) -> void { if (mode == current_mode_) { return; } diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index 03584062..a79ca4ec 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -14,7 +14,6 @@ #include "tinyfsm.hpp" #include "track.hpp" -#include "track_queue.hpp" #include "types.hpp" namespace audio { @@ -39,6 +38,13 @@ struct PlaybackStopped : tinyfsm::Event {}; struct QueueUpdate : tinyfsm::Event { bool current_changed; + + enum Reason { + kExplicitUpdate, + kRepeatingLastTrack, + kTrackFinished, + }; + Reason reason; }; struct PlayFile : tinyfsm::Event { diff --git a/src/audio/include/audio_fsm.hpp b/src/audio/include/audio_fsm.hpp index 29ec489a..2d335e74 100644 --- a/src/audio/include/audio_fsm.hpp +++ b/src/audio/include/audio_fsm.hpp @@ -52,7 +52,7 @@ class AudioState : public tinyfsm::Fsm { void react(const OutputModeChanged&); virtual void react(const system_fsm::BootComplete&) {} - virtual void react(const system_fsm::KeyLockChanged&) {}; + virtual void react(const system_fsm::KeyLockChanged&){}; virtual void react(const system_fsm::StorageMounted&) {} virtual void react(const system_fsm::BluetoothEvent&); @@ -67,6 +67,7 @@ class AudioState : public tinyfsm::Fsm { virtual void react(const internal::AudioPipelineIdle&) {} protected: + auto clearDrainBuffer() -> void; auto playTrack(database::TrackId id) -> void; auto commitVolume() -> void; @@ -79,6 +80,8 @@ class AudioState : public tinyfsm::Fsm { static std::shared_ptr sBtOutput; static std::shared_ptr sOutput; + static StreamBufferHandle_t sDrainBuffer; + static std::optional sCurrentTrack; auto readyToPlay() -> bool; @@ -91,7 +94,7 @@ class Uninitialised : public AudioState { public: void react(const system_fsm::BootComplete&) override; - void react(const system_fsm::BluetoothEvent&) override {}; + void react(const system_fsm::BluetoothEvent&) override{}; using AudioState::react; }; diff --git a/src/audio/include/audio_sink.hpp b/src/audio/include/audio_sink.hpp index eba55eb5..85c23f5c 100644 --- a/src/audio/include/audio_sink.hpp +++ b/src/audio/include/audio_sink.hpp @@ -27,7 +27,8 @@ class IAudioOutput { StreamBufferHandle_t stream_; public: - IAudioOutput(StreamBufferHandle_t stream) : stream_(stream) {} + IAudioOutput(StreamBufferHandle_t stream) + : stream_(stream), mode_(Modes::kOff) {} virtual ~IAudioOutput() {} @@ -41,7 +42,14 @@ class IAudioOutput { * Indicates whether this output is currently being sent samples. If this is * false, the output should place itself into a low power state. */ - virtual auto SetMode(Modes) -> void = 0; + auto mode(Modes m) -> void { + if (mode_ == m) { + return; + } + changeMode(m); + mode_ = m; + } + auto mode() -> Modes { return mode_; } virtual auto SetVolumeImbalance(int_fast8_t balance) -> void = 0; @@ -67,6 +75,11 @@ class IAudioOutput { virtual auto Configure(const Format& format) -> void = 0; auto stream() -> StreamBufferHandle_t { return stream_; } + + protected: + Modes mode_; + + virtual auto changeMode(Modes new_mode) -> void = 0; }; } // namespace audio diff --git a/src/audio/include/bt_audio_output.hpp b/src/audio/include/bt_audio_output.hpp index f6d2200c..a61e718a 100644 --- a/src/audio/include/bt_audio_output.hpp +++ b/src/audio/include/bt_audio_output.hpp @@ -28,8 +28,6 @@ class BluetoothAudioOutput : public IAudioOutput { tasks::WorkerPool&); ~BluetoothAudioOutput(); - auto SetMode(Modes) -> void override; - auto SetVolumeImbalance(int_fast8_t balance) -> void override; auto SetVolume(uint16_t) -> void override; @@ -48,6 +46,9 @@ class BluetoothAudioOutput : public IAudioOutput { BluetoothAudioOutput(const BluetoothAudioOutput&) = delete; BluetoothAudioOutput& operator=(const BluetoothAudioOutput&) = delete; + protected: + auto changeMode(Modes) -> void override; + private: drivers::Bluetooth& bluetooth_; tasks::WorkerPool& bg_worker_; diff --git a/src/audio/include/i2s_audio_output.hpp b/src/audio/include/i2s_audio_output.hpp index 7c297106..5f3fc3ff 100644 --- a/src/audio/include/i2s_audio_output.hpp +++ b/src/audio/include/i2s_audio_output.hpp @@ -23,8 +23,6 @@ class I2SAudioOutput : public IAudioOutput { I2SAudioOutput(StreamBufferHandle_t, drivers::IGpios& expander); ~I2SAudioOutput(); - auto SetMode(Modes) -> void override; - auto SetMaxVolume(uint16_t) -> void; auto SetVolumeDb(uint16_t) -> void; @@ -46,6 +44,9 @@ class I2SAudioOutput : public IAudioOutput { I2SAudioOutput(const I2SAudioOutput&) = delete; I2SAudioOutput& operator=(const I2SAudioOutput&) = delete; + protected: + auto changeMode(Modes) -> void override; + private: drivers::IGpios& expander_; std::unique_ptr dac_; diff --git a/src/audio/include/track_queue.hpp b/src/audio/include/track_queue.hpp index e4fd7881..5b7c9448 100644 --- a/src/audio/include/track_queue.hpp +++ b/src/audio/include/track_queue.hpp @@ -12,6 +12,7 @@ #include #include +#include "audio_events.hpp" #include "cppbor_parse.h" #include "database.hpp" #include "tasks.hpp" @@ -120,6 +121,8 @@ class TrackQueue { TrackQueue& operator=(const TrackQueue&) = delete; private: + auto next(QueueUpdate::Reason r) -> void; + mutable std::shared_mutex mutex_; tasks::WorkerPool& bg_worker_; diff --git a/src/audio/track_queue.cpp b/src/audio/track_queue.cpp index b75230fc..ccadd3a6 100644 --- a/src/audio/track_queue.cpp +++ b/src/audio/track_queue.cpp @@ -33,6 +33,8 @@ namespace audio { [[maybe_unused]] static constexpr char kTag[] = "tracks"; +using Reason = QueueUpdate::Reason; + RandomIterator::RandomIterator() : seed_(0), pos_(0), size_(0), replay_(false) {} @@ -72,8 +74,11 @@ auto RandomIterator::replay(bool r) -> void { replay_ = r; } -auto notifyChanged(bool current_changed) -> void { - QueueUpdate ev{.current_changed = current_changed}; +auto notifyChanged(bool current_changed, Reason reason) -> void { + QueueUpdate ev{ + .current_changed = current_changed, + .reason = reason, + }; events::Ui().Dispatch(ev); events::Audio().Dispatch(ev); } @@ -157,7 +162,7 @@ auto TrackQueue::insert(Item i, size_t index) -> void { update_shuffler(); } } - notifyChanged(current_changed); + notifyChanged(current_changed, Reason::kExplicitUpdate); } else if (std::holds_alternative(i)) { // Iterators can be very large, and retrieving items from them often // requires disk i/o. Handle them asynchronously so that inserting them @@ -185,7 +190,7 @@ auto TrackQueue::insert(Item i, size_t index) -> void { const std::unique_lock lock(mutex_); update_shuffler(); } - notifyChanged(current_changed); + notifyChanged(current_changed, Reason::kExplicitUpdate); }); } } @@ -200,6 +205,10 @@ auto TrackQueue::append(Item i) -> void { } auto TrackQueue::next() -> void { + next(Reason::kExplicitUpdate); +} + +auto TrackQueue::next(Reason r) -> void { bool changed = true; { @@ -221,7 +230,7 @@ auto TrackQueue::next() -> void { } } - notifyChanged(changed); + notifyChanged(changed, r); } auto TrackQueue::previous() -> void { @@ -245,22 +254,22 @@ auto TrackQueue::previous() -> void { } } - notifyChanged(changed); + notifyChanged(changed, Reason::kExplicitUpdate); } auto TrackQueue::finish() -> void { if (repeat_) { - notifyChanged(true); + notifyChanged(true, Reason::kRepeatingLastTrack); } else { - next(); + next(Reason::kTrackFinished); } } auto TrackQueue::skipTo(database::TrackId id) -> void { // Defer this work to the background not because it's particularly - // long-running (although it could be), but because we want to ensure we only - // search for the given id after any previously pending iterator insertions - // have finished. + // long-running (although it could be), but because we want to ensure we + // only search for the given id after any previously pending iterator + // insertions have finished. bg_worker_.Dispatch([=, this]() { bool found = false; { @@ -274,7 +283,7 @@ auto TrackQueue::skipTo(database::TrackId id) -> void { } } if (found) { - notifyChanged(true); + notifyChanged(true, Reason::kExplicitUpdate); } }); } @@ -294,7 +303,7 @@ auto TrackQueue::clear() -> void { } } - notifyChanged(true); + notifyChanged(true, Reason::kExplicitUpdate); } auto TrackQueue::random(bool en) -> void { @@ -311,7 +320,7 @@ auto TrackQueue::random(bool en) -> void { } // Current track doesn't get randomised until next(). - notifyChanged(false); + notifyChanged(false, Reason::kExplicitUpdate); } auto TrackQueue::random() const -> bool { @@ -325,7 +334,7 @@ auto TrackQueue::repeat(bool en) -> void { repeat_ = en; } - notifyChanged(false); + notifyChanged(false, Reason::kExplicitUpdate); } auto TrackQueue::repeat() const -> bool { @@ -341,7 +350,7 @@ auto TrackQueue::replay(bool en) -> void { shuffle_->replay(en); } } - notifyChanged(false); + notifyChanged(false, Reason::kExplicitUpdate); } auto TrackQueue::replay() const -> bool { @@ -477,7 +486,7 @@ auto TrackQueue::deserialise(const std::string& s) -> void { QueueParseClient client{*this}; const uint8_t* data = reinterpret_cast(s.data()); cppbor::parse(data, data + s.size(), &client); - notifyChanged(true); + notifyChanged(true, Reason::kExplicitUpdate); } } // namespace audio -- cgit v1.2.3 From b2f0e6d3a45083b04e85feccb3f7742a35d6e41f Mon Sep 17 00:00:00 2001 From: jacqueline Date: Thu, 29 Feb 2024 16:30:17 +1100 Subject: Clear the drain buffer also when seeking --- src/audio/audio_fsm.cpp | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/audio') diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 50f18452..d4272c3d 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -290,10 +290,12 @@ void Playback::react(const PlayFile& ev) { } void Standby::react(const SeekFile& ev) { + clearDrainBuffer(); sFileSource->SetPath(ev.filename, ev.offset); } void Playback::react(const SeekFile& ev) { + clearDrainBuffer(); sFileSource->SetPath(ev.filename, ev.offset); } -- cgit v1.2.3 From 14552881900bb3ed0e9ed2d4a732e4104b32ccfa Mon Sep 17 00:00:00 2001 From: jacqueline Date: Wed, 6 Mar 2024 13:59:33 +1100 Subject: Restore the previous track position when booting --- src/audio/audio_fsm.cpp | 43 +++++++++++++++++++++++++++++++++++--- src/audio/include/audio_events.hpp | 1 + src/audio/track_queue.cpp | 2 +- 3 files changed, 42 insertions(+), 4 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index d4272c3d..05c7c216 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -13,6 +13,8 @@ #include "audio_sink.hpp" #include "bluetooth_types.hpp" +#include "cppbor.h" +#include "cppbor_parse.h" #include "esp_heap_caps.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" @@ -58,6 +60,8 @@ StreamBufferHandle_t AudioState::sDrainBuffer; std::optional AudioState::sCurrentTrack; bool AudioState::sIsPlaybackAllowed; +static std::optional> sLastTrackUpdate; + void AudioState::react(const system_fsm::BluetoothEvent& ev) { if (ev.event != drivers::bluetooth::Event::kConnectionStateChanged) { return; @@ -310,11 +314,15 @@ void Standby::react(const QueueUpdate& ev) { if (!current_track || (sCurrentTrack && (*sCurrentTrack == *current_track))) { return; } + if (ev.reason == QueueUpdate::Reason::kDeserialised && sLastTrackUpdate) { + return; + } clearDrainBuffer(); playTrack(*current_track); } static const char kQueueKey[] = "audio:queue"; +static const char kCurrentFileKey[] = "audio:current"; void Standby::react(const system_fsm::KeyLockChanged& ev) { if (!ev.locking) { @@ -332,6 +340,14 @@ void Standby::react(const system_fsm::KeyLockChanged& ev) { return; } db->put(kQueueKey, queue.serialise()); + + if (sLastTrackUpdate) { + cppbor::Array current_track{ + cppbor::Tstr{sLastTrackUpdate->first}, + cppbor::Uint{sLastTrackUpdate->second}, + }; + db->put(kCurrentFileKey, current_track.toString()); + } }); } @@ -341,13 +357,32 @@ void Standby::react(const system_fsm::StorageMounted& ev) { if (!db) { return; } - auto res = db->get(kQueueKey); - if (res) { + + // Restore the currently playing file before restoring the queue. This way, + // we can fall back to restarting the queue's current track if there's any + // issue restoring the current file. + auto current = db->get(kCurrentFileKey); + if (current) { + // Again, ensure we don't boot-loop by trying to play a track that causes + // a crash over and over again. + db->put(kCurrentFileKey, ""); + auto [parsed, unused, err] = cppbor::parse( + reinterpret_cast(current->data()), current->size()); + if (parsed->type() == cppbor::ARRAY) { + std::string filename = parsed->asArray()->get(0)->asTstr()->value(); + uint32_t pos = parsed->asArray()->get(1)->asUint()->value(); + sLastTrackUpdate = std::make_pair(filename, pos); + sFileSource->SetPath(filename, pos); + } + } + + auto queue = db->get(kQueueKey); + if (queue) { // Don't restore the same queue again. This ideally should do nothing, // but guards against bad edge cases where restoring the queue ends up // causing a crash. db->put(kQueueKey, ""); - sServices->track_queue().deserialise(*res); + sServices->track_queue().deserialise(*queue); } }); } @@ -399,6 +434,7 @@ void Playback::react(const QueueUpdate& ev) { void Playback::react(const PlaybackUpdate& ev) { ESP_LOGI(kTag, "elapsed: %lu, total: %lu", ev.seconds_elapsed, ev.track->duration); + sLastTrackUpdate = std::make_pair(ev.track->filepath, ev.seconds_elapsed); } void Playback::react(const internal::InputFileOpened& ev) {} @@ -407,6 +443,7 @@ void Playback::react(const internal::InputFileClosed& ev) {} void Playback::react(const internal::InputFileFinished& ev) { ESP_LOGI(kTag, "finished playing file"); + sLastTrackUpdate.reset(); sServices->track_queue().finish(); if (!sServices->track_queue().current()) { for (int i = 0; i < 20; i++) { diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index d55e4e0d..a8533646 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -44,6 +44,7 @@ struct QueueUpdate : tinyfsm::Event { kExplicitUpdate, kRepeatingLastTrack, kTrackFinished, + kDeserialised, }; Reason reason; }; diff --git a/src/audio/track_queue.cpp b/src/audio/track_queue.cpp index ccadd3a6..a3f4c815 100644 --- a/src/audio/track_queue.cpp +++ b/src/audio/track_queue.cpp @@ -486,7 +486,7 @@ auto TrackQueue::deserialise(const std::string& s) -> void { QueueParseClient client{*this}; const uint8_t* data = reinterpret_cast(s.data()); cppbor::parse(data, data + s.size(), &client); - notifyChanged(true, Reason::kExplicitUpdate); + notifyChanged(true, Reason::kDeserialised); } } // namespace audio -- cgit v1.2.3 From 175bfc4e3e9f7aa39e084d3f1625347f1d5711ec Mon Sep 17 00:00:00 2001 From: jacqueline Date: Mon, 25 Mar 2024 17:34:41 +1100 Subject: WIP rewrie audio pipeline+fsm guts for more reliability --- src/audio/audio_converter.cpp | 51 ++++-- src/audio/audio_decoder.cpp | 78 +++------ src/audio/audio_fsm.cpp | 315 +++++++++++++++++++--------------- src/audio/include/audio_converter.hpp | 5 + src/audio/include/audio_decoder.hpp | 20 --- src/audio/include/audio_events.hpp | 108 +++++++++--- src/audio/include/audio_fsm.hpp | 53 +++--- src/audio/track_queue.cpp | 2 +- 8 files changed, 349 insertions(+), 283 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_converter.cpp b/src/audio/audio_converter.cpp index 946a0b63..1b233731 100644 --- a/src/audio/audio_converter.cpp +++ b/src/audio/audio_converter.cpp @@ -5,14 +5,17 @@ */ #include "audio_converter.hpp" +#include #include #include #include +#include "audio_events.hpp" #include "audio_sink.hpp" #include "esp_heap_caps.h" #include "esp_log.h" +#include "event_queue.hpp" #include "freertos/portmacro.h" #include "freertos/projdefs.h" #include "i2s_dac.hpp" @@ -35,7 +38,9 @@ SampleConverter::SampleConverter() resampler_(nullptr), source_(xStreamBufferCreateWithCaps(kSourceBufferLength, sizeof(sample::Sample) * 2, - MALLOC_CAP_DMA)) { + MALLOC_CAP_DMA)), + leftover_bytes_(0), + samples_sunk_(0) { input_buffer_ = { reinterpret_cast(heap_caps_calloc( kSampleBufferLength, sizeof(sample::Sample), MALLOC_CAP_DMA)), @@ -107,6 +112,19 @@ auto SampleConverter::Main() -> void { sink_->Configure(new_target); } target_format_ = new_target; + + // Send a final sample count for the previous sample rate. + if (samples_sunk_ > 0) { + events::Audio().Dispatch(internal::ConverterProgress{ + .samples_sunk = samples_sunk_, + }); + } + + samples_sunk_ = 0; + events::Audio().Dispatch(internal::ConverterConfigurationChanged{ + .src_format = source_format_, + .dst_format = target_format_, + }); } // Loop until we finish reading all the bytes indicated. There might be @@ -154,9 +172,8 @@ auto SampleConverter::HandleSamples(cpp::span input, if (source_format_ == target_format_) { // The happiest possible case: the input format matches the output // format already. - std::size_t bytes_sent = xStreamBufferSend( - sink_->stream(), input.data(), input.size_bytes(), portMAX_DELAY); - return bytes_sent / sizeof(sample::Sample); + SendToSink(input); + return input.size(); } size_t samples_used = 0; @@ -186,16 +203,26 @@ auto SampleConverter::HandleSamples(cpp::span input, samples_used = input.size(); } - size_t bytes_sent = 0; - size_t bytes_to_send = output_source.size_bytes(); - while (bytes_sent < bytes_to_send) { - bytes_sent += xStreamBufferSend( - sink_->stream(), - reinterpret_cast(output_source.data()) + bytes_sent, - bytes_to_send - bytes_sent, portMAX_DELAY); - } + SendToSink(output_source); } return samples_used; } +auto SampleConverter::SendToSink(cpp::span samples) -> void { + // Update the number of samples sunk so far *before* actually sinking them, + // since writing to the stream buffer will block when the buffer gets full. + samples_sunk_ += samples.size(); + if (samples_sunk_ >= + target_format_.sample_rate * target_format_.num_channels) { + events::Audio().Dispatch(internal::ConverterProgress{ + .samples_sunk = samples_sunk_, + }); + samples_sunk_ = 0; + } + + xStreamBufferSend(sink_->stream(), + reinterpret_cast(samples.data()), + samples.size_bytes(), portMAX_DELAY); +} + } // namespace audio diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index 68a8a86b..55ebc0ec 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -5,6 +5,7 @@ */ #include "audio_decoder.hpp" +#include #include #include @@ -50,39 +51,6 @@ namespace audio { static constexpr std::size_t kCodecBufferLength = drivers::kI2SBufferLengthFrames * sizeof(sample::Sample); -Timer::Timer(std::shared_ptr t, - const codecs::ICodec::OutputFormat& format, - uint32_t current_seconds) - : track_(t), - current_seconds_(current_seconds), - current_sample_in_second_(0), - samples_per_second_(format.sample_rate_hz * format.num_channels), - total_duration_seconds_(format.total_samples.value_or(0) / - format.num_channels / format.sample_rate_hz) { - track_->duration = total_duration_seconds_; -} - -auto Timer::AddSamples(std::size_t samples) -> void { - bool incremented = false; - current_sample_in_second_ += samples; - while (current_sample_in_second_ >= samples_per_second_) { - current_seconds_++; - current_sample_in_second_ -= samples_per_second_; - incremented = true; - } - - if (incremented) { - if (total_duration_seconds_ < current_seconds_) { - total_duration_seconds_ = current_seconds_; - track_->duration = total_duration_seconds_; - } - - PlaybackUpdate ev{.seconds_elapsed = current_seconds_, .track = track_}; - events::Audio().Dispatch(ev); - events::Ui().Dispatch(ev); - } -} - auto Decoder::Start(std::shared_ptr source, std::shared_ptr sink) -> Decoder* { Decoder* task = new Decoder(source, sink); @@ -92,11 +60,7 @@ auto Decoder::Start(std::shared_ptr source, Decoder::Decoder(std::shared_ptr source, std::shared_ptr mixer) - : source_(source), - converter_(mixer), - codec_(), - timer_(), - current_format_() { + : source_(source), converter_(mixer), codec_(), current_format_() { ESP_LOGI(kTag, "allocating codec buffer, %u KiB", kCodecBufferLength / 1024); codec_buffer_ = { reinterpret_cast(heap_caps_calloc( @@ -117,7 +81,6 @@ void Decoder::Main() { } if (ContinueDecoding()) { - events::Audio().Dispatch(internal::InputFileFinished{}); stream_.reset(); } } @@ -129,6 +92,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { codec_.reset(codecs::CreateCodecForType(stream->type()).value_or(nullptr)); if (!codec_) { ESP_LOGE(kTag, "no codec found"); + events::Audio().Dispatch(internal::DecoderError{}); return false; } @@ -136,6 +100,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { if (open_res.has_error()) { ESP_LOGE(kTag, "codec failed to start: %s", codecs::ICodec::ErrorString(open_res.error()).c_str()); + events::Audio().Dispatch(internal::DecoderError{}); return false; } stream->SetPreambleFinished(); @@ -146,20 +111,23 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { }; ESP_LOGI(kTag, "stream started ok"); - events::Audio().Dispatch(internal::InputFileOpened{}); - - auto tags = std::make_shared(Track{ - .tags = stream->tags(), - .db_info = {}, - .bitrate_kbps = open_res->sample_rate_hz, - .encoding = stream->type(), - .filepath = stream->Filepath(), - }); - timer_.reset(new Timer(tags, open_res.value(), stream->Offset())); - PlaybackUpdate ev{.seconds_elapsed = stream->Offset(), .track = tags}; - events::Audio().Dispatch(ev); - events::Ui().Dispatch(ev); + std::optional duration; + if (open_res->total_samples) { + duration = open_res->total_samples.value() / open_res->num_channels / + open_res->sample_rate_hz; + } + + events::Audio().Dispatch(internal::DecoderOpened{ + .track = std::make_shared(TrackInfo{ + .tags = stream->tags(), + .uri = stream->Filepath(), + .duration = duration, + .start_offset = stream->Offset(), + .bitrate_kbps = open_res->sample_rate_hz, + .encoding = stream->type(), + }), + }); return true; } @@ -167,6 +135,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { auto Decoder::ContinueDecoding() -> bool { auto res = codec_->DecodeTo(codec_buffer_); if (res.has_error()) { + events::Audio().Dispatch(internal::DecoderError{}); return true; } @@ -176,11 +145,8 @@ auto Decoder::ContinueDecoding() -> bool { res->is_stream_finished); } - if (timer_) { - timer_->AddSamples(res->samples_written); - } - if (res->is_stream_finished) { + events::Audio().Dispatch(internal::DecoderClosed{}); codec_.reset(); } diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 05c7c216..7a138cba 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -36,6 +36,7 @@ #include "sample.hpp" #include "service_locator.hpp" #include "system_events.hpp" +#include "tinyfsm.hpp" #include "track.hpp" #include "track_queue.hpp" #include "wm8523.hpp" @@ -54,13 +55,158 @@ std::shared_ptr AudioState::sBtOutput; std::shared_ptr AudioState::sOutput; // Two seconds of samples for two channels, at a representative sample rate. -constexpr size_t kDrainBufferSize = sizeof(sample::Sample) * 48000 * 4; +constexpr size_t kDrainLatencySamples = 48000; +constexpr size_t kDrainBufferSize = + sizeof(sample::Sample) * kDrainLatencySamples * 4; + StreamBufferHandle_t AudioState::sDrainBuffer; -std::optional AudioState::sCurrentTrack; -bool AudioState::sIsPlaybackAllowed; +std::shared_ptr AudioState::sCurrentTrack; +uint64_t AudioState::sCurrentSamples; +std::optional AudioState::sCurrentFormat; + +std::shared_ptr AudioState::sNextTrack; +uint64_t AudioState::sNextTrackCueSamples; + +bool AudioState::sIsResampling; +bool AudioState::sIsPaused = true; + +auto AudioState::currentPositionSeconds() -> std::optional { + if (!sCurrentTrack || !sCurrentFormat) { + return {}; + } + return sCurrentSamples / + (sCurrentFormat->num_channels * sCurrentFormat->sample_rate); +} + +void AudioState::react(const QueueUpdate& ev) { + if (!ev.current_changed && ev.reason != QueueUpdate::kRepeatingLastTrack) { + return; + } + + SetTrack::Transition transition; + switch (ev.reason) { + case QueueUpdate::kExplicitUpdate: + transition = SetTrack::Transition::kHardCut; + break; + case QueueUpdate::kRepeatingLastTrack: + case QueueUpdate::kTrackFinished: + transition = SetTrack::Transition::kGapless; + break; + case QueueUpdate::kDeserialised: + default: + // The current track is deserialised separately in order to retain seek + // position. + return; + } + + SetTrack cmd{ + .new_track = {}, + .seek_to_second = 0, + .transition = transition, + }; -static std::optional> sLastTrackUpdate; + auto current = sServices->track_queue().current(); + if (current) { + cmd.new_track = *current; + } + + tinyfsm::FsmList::dispatch(cmd); +} + +void AudioState::react(const SetTrack& ev) { + if (ev.transition == SetTrack::Transition::kHardCut) { + clearDrainBuffer(); + } + + // Move the rest of the work to a background worker, since it may require db + // lookups to resolve a track id into a path. + auto new_track = ev.new_track; + uint32_t seek_to = ev.seek_to_second.value_or(0); + sServices->bg_worker().Dispatch([=]() { + std::optional path; + if (std::holds_alternative(new_track)) { + auto db = sServices->database().lock(); + if (db) { + path = db->getTrackPath(std::get(new_track)); + } + } else if (std::holds_alternative(new_track)) { + path = std::get(new_track); + } + + if (path) { + sFileSource->SetPath(*path, seek_to); + } else { + sFileSource->SetPath(); + } + }); +} + +void AudioState::react(const TogglePlayPause& ev) { + sIsPaused = !ev.set_to.value_or(sIsPaused); + if (!sIsPaused && is_in_state() && sCurrentTrack) { + transit(); + } else if (sIsPaused && is_in_state()) { + transit(); + } +} + +void AudioState::react(const internal::DecoderOpened& ev) { + ESP_LOGI(kTag, "decoder opened %s", ev.track->uri.c_str()); + sNextTrack = ev.track; + sNextTrackCueSamples = sCurrentSamples + kDrainLatencySamples; +} + +void AudioState::react(const internal::DecoderClosed&) { + ESP_LOGI(kTag, "decoder closed"); + // FIXME: only when we were playing the current track + sServices->track_queue().finish(); +} + +void AudioState::react(const internal::DecoderError&) { + ESP_LOGW(kTag, "decoder errored"); + // FIXME: only when we were playing the current track + sServices->track_queue().finish(); +} + +void AudioState::react(const internal::ConverterConfigurationChanged& ev) { + sCurrentFormat = ev.dst_format; + sIsResampling = ev.src_format != ev.dst_format; + ESP_LOGI(kTag, "output format now %u ch @ %lu hz (resample=%i)", + sCurrentFormat->num_channels, sCurrentFormat->sample_rate, + sIsResampling); +} + +void AudioState::react(const internal::ConverterProgress& ev) { + ESP_LOGI(kTag, "sample converter sunk %lu samples", ev.samples_sunk); + sCurrentSamples += ev.samples_sunk; + + if (sNextTrack && sCurrentSamples >= sNextTrackCueSamples) { + ESP_LOGI(kTag, "next track is now sinking"); + sCurrentTrack = sNextTrack; + sCurrentSamples -= sNextTrackCueSamples; + sCurrentSamples += + sNextTrack->start_offset.value_or(0) * + (sCurrentFormat->num_channels * sCurrentFormat->sample_rate); + + sNextTrack.reset(); + sNextTrackCueSamples = 0; + } + + PlaybackUpdate event{ + .current_track = sCurrentTrack, + .track_position = currentPositionSeconds(), + .paused = !is_in_state(), + }; + + events::System().Dispatch(event); + events::Ui().Dispatch(event); + + if (sCurrentTrack && !sIsPaused && !is_in_state()) { + ESP_LOGI(kTag, "ready to play!"); + transit(); + } +} void AudioState::react(const system_fsm::BluetoothEvent& ev) { if (ev.event != drivers::bluetooth::Event::kConnectionStateChanged) { @@ -184,17 +330,6 @@ auto AudioState::clearDrainBuffer() -> void { } } -auto AudioState::playTrack(database::TrackId id) -> void { - sCurrentTrack = id; - sServices->bg_worker().Dispatch([=]() { - auto db = sServices->database().lock(); - if (!db) { - return; - } - sFileSource->SetPath(db->getTrackPath(id)); - }); -} - auto AudioState::commitVolume() -> void { auto mode = sServices->nvs().OutputMode(); auto vol = sOutput->GetVolume(); @@ -209,23 +344,6 @@ auto AudioState::commitVolume() -> void { } } -auto AudioState::readyToPlay() -> bool { - return sCurrentTrack.has_value() && sIsPlaybackAllowed; -} - -void AudioState::react(const TogglePlayPause& ev) { - sIsPlaybackAllowed = !sIsPlaybackAllowed; - if (readyToPlay()) { - if (!is_in_state()) { - transit(); - } - } else { - if (!is_in_state()) { - transit(); - } - } -} - namespace states { void Uninitialised::react(const system_fsm::BootComplete& ev) { @@ -283,44 +401,6 @@ void Uninitialised::react(const system_fsm::BootComplete& ev) { transit(); } -void Standby::react(const PlayFile& ev) { - sCurrentTrack = 0; - sIsPlaybackAllowed = true; - sFileSource->SetPath(ev.filename); -} - -void Playback::react(const PlayFile& ev) { - sFileSource->SetPath(ev.filename); -} - -void Standby::react(const SeekFile& ev) { - clearDrainBuffer(); - sFileSource->SetPath(ev.filename, ev.offset); -} - -void Playback::react(const SeekFile& ev) { - clearDrainBuffer(); - sFileSource->SetPath(ev.filename, ev.offset); -} - -void Standby::react(const internal::InputFileOpened& ev) { - if (readyToPlay()) { - transit(); - } -} - -void Standby::react(const QueueUpdate& ev) { - auto current_track = sServices->track_queue().current(); - if (!current_track || (sCurrentTrack && (*sCurrentTrack == *current_track))) { - return; - } - if (ev.reason == QueueUpdate::Reason::kDeserialised && sLastTrackUpdate) { - return; - } - clearDrainBuffer(); - playTrack(*current_track); -} - static const char kQueueKey[] = "audio:queue"; static const char kCurrentFileKey[] = "audio:current"; @@ -328,7 +408,7 @@ void Standby::react(const system_fsm::KeyLockChanged& ev) { if (!ev.locking) { return; } - sServices->bg_worker().Dispatch([]() { + sServices->bg_worker().Dispatch([this]() { auto db = sServices->database().lock(); if (!db) { return; @@ -341,10 +421,10 @@ void Standby::react(const system_fsm::KeyLockChanged& ev) { } db->put(kQueueKey, queue.serialise()); - if (sLastTrackUpdate) { + if (sCurrentTrack) { cppbor::Array current_track{ - cppbor::Tstr{sLastTrackUpdate->first}, - cppbor::Uint{sLastTrackUpdate->second}, + cppbor::Tstr{sCurrentTrack->uri}, + cppbor::Uint{currentPositionSeconds().value_or(0)}, }; db->put(kCurrentFileKey, current_track.toString()); } @@ -371,8 +451,12 @@ void Standby::react(const system_fsm::StorageMounted& ev) { if (parsed->type() == cppbor::ARRAY) { std::string filename = parsed->asArray()->get(0)->asTstr()->value(); uint32_t pos = parsed->asArray()->get(1)->asUint()->value(); - sLastTrackUpdate = std::make_pair(filename, pos); - sFileSource->SetPath(filename, pos); + + events::Audio().Dispatch(SetTrack{ + .new_track = filename, + .seek_to_second = pos, + .transition = SetTrack::Transition::kHardCut, + }); } } @@ -388,76 +472,31 @@ void Standby::react(const system_fsm::StorageMounted& ev) { } void Playback::entry() { - ESP_LOGI(kTag, "beginning playback"); + ESP_LOGI(kTag, "audio output resumed"); sOutput->mode(IAudioOutput::Modes::kOnPlaying); - events::System().Dispatch(PlaybackStarted{}); - events::Ui().Dispatch(PlaybackStarted{}); + PlaybackUpdate event{ + .current_track = sCurrentTrack, + .track_position = currentPositionSeconds(), + .paused = false, + }; + + events::System().Dispatch(event); + events::Ui().Dispatch(event); } void Playback::exit() { - ESP_LOGI(kTag, "finishing playback"); + ESP_LOGI(kTag, "audio output paused"); sOutput->mode(IAudioOutput::Modes::kOnPaused); - // Stash the current volume now, in case it changed during playback, since - // we might be powering off soon. - commitVolume(); - - events::System().Dispatch(PlaybackStopped{}); - events::Ui().Dispatch(PlaybackStopped{}); -} - -void Playback::react(const system_fsm::HasPhonesChanged& ev) { - if (!ev.has_headphones) { - transit(); - } -} - -void Playback::react(const QueueUpdate& ev) { - if (!ev.current_changed) { - return; - } - // Cut the current track immediately. - if (ev.reason == QueueUpdate::Reason::kExplicitUpdate) { - clearDrainBuffer(); - } - auto current_track = sServices->track_queue().current(); - if (!current_track) { - sFileSource->SetPath(); - sCurrentTrack.reset(); - transit(); - return; - } - playTrack(*current_track); -} - -void Playback::react(const PlaybackUpdate& ev) { - ESP_LOGI(kTag, "elapsed: %lu, total: %lu", ev.seconds_elapsed, - ev.track->duration); - sLastTrackUpdate = std::make_pair(ev.track->filepath, ev.seconds_elapsed); -} - -void Playback::react(const internal::InputFileOpened& ev) {} - -void Playback::react(const internal::InputFileClosed& ev) {} + PlaybackUpdate event{ + .current_track = sCurrentTrack, + .track_position = currentPositionSeconds(), + .paused = true, + }; -void Playback::react(const internal::InputFileFinished& ev) { - ESP_LOGI(kTag, "finished playing file"); - sLastTrackUpdate.reset(); - sServices->track_queue().finish(); - if (!sServices->track_queue().current()) { - for (int i = 0; i < 20; i++) { - if (xStreamBufferIsEmpty(sDrainBuffer)) { - break; - } - vTaskDelay(pdMS_TO_TICKS(200)); - } - transit(); - } -} - -void Playback::react(const internal::AudioPipelineIdle& ev) { - transit(); + events::System().Dispatch(event); + events::Ui().Dispatch(event); } } // namespace states diff --git a/src/audio/include/audio_converter.hpp b/src/audio/include/audio_converter.hpp index c2ebde60..dcd068b5 100644 --- a/src/audio/include/audio_converter.hpp +++ b/src/audio/include/audio_converter.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include @@ -40,6 +41,8 @@ class SampleConverter { auto SetTargetFormat(const IAudioOutput::Format& format) -> void; auto HandleSamples(cpp::span, bool) -> size_t; + auto SendToSink(cpp::span) -> void; + struct Args { IAudioOutput::Format format; size_t samples_available; @@ -59,6 +62,8 @@ class SampleConverter { IAudioOutput::Format source_format_; IAudioOutput::Format target_format_; size_t leftover_bytes_; + + uint32_t samples_sunk_; }; } // namespace audio diff --git a/src/audio/include/audio_decoder.hpp b/src/audio/include/audio_decoder.hpp index b8aac710..89f0f43c 100644 --- a/src/audio/include/audio_decoder.hpp +++ b/src/audio/include/audio_decoder.hpp @@ -19,25 +19,6 @@ namespace audio { -/* - * Sample-based timer for the current elapsed playback time. - */ -class Timer { - public: - Timer(std::shared_ptr, const codecs::ICodec::OutputFormat& format, uint32_t current_seconds = 0); - - auto AddSamples(std::size_t) -> void; - - private: - std::shared_ptr track_; - - uint32_t current_seconds_; - uint32_t current_sample_in_second_; - uint32_t samples_per_second_; - - uint32_t total_duration_seconds_; -}; - /* * Handle to a persistent task that takes bytes from the given source, decodes * them into sample::Sample (normalised to 16 bit signed PCM), and then @@ -65,7 +46,6 @@ class Decoder { std::shared_ptr stream_; std::unique_ptr codec_; - std::unique_ptr timer_; std::optional current_format_; std::optional current_sink_format_; diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index a8533646..9af30467 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -9,8 +9,10 @@ #include #include #include +#include #include +#include "audio_sink.hpp" #include "tinyfsm.hpp" #include "track.hpp" @@ -18,24 +20,80 @@ namespace audio { -struct Track { +/* + * Struct encapsulating information about the decoder's current track. + */ +struct TrackInfo { + /* + * Audio tags extracted from the file. May be absent for files without any + * parseable tags. + */ std::shared_ptr tags; - std::shared_ptr db_info; - uint32_t duration; - uint32_t bitrate_kbps; + /* + * URI that the current track was retrieved from. This is currently always a + * file path on the SD card. + */ + std::string uri; + + /* + * The length of this track in seconds. This is either retrieved from the + * track's tags, or sometimes computed. It may therefore sometimes be + * inaccurate or missing. + */ + std::optional duration; + + /* The offset in seconds that this file's decoding started from. */ + std::optional start_offset; + + /* The approximate bitrate of this track in its original encoded form. */ + std::optional bitrate_kbps; + + /* The encoded format of the this track. */ codecs::StreamType encoding; - std::string filepath; }; -struct PlaybackStarted : tinyfsm::Event {}; - +/* + * Event emitted by the audio FSM when the state of the audio pipeline has + * changed. This is usually once per second while a track is playing, plus one + * event each when a track starts or finishes. + */ struct PlaybackUpdate : tinyfsm::Event { - uint32_t seconds_elapsed; - std::shared_ptr track; + /* + * The track that is currently being decoded by the audio pipeline. May be + * absent if there is no current track. + */ + std::shared_ptr current_track; + + /* + * How long the current track has been playing for, in seconds. Will always + * be present if current_track is present. + */ + std::optional track_position; + + /* Whether or not the current track is currently being output to a sink. */ + bool paused; +}; + +/* + * Sets a new track to be decoded by the audio pipeline, replacing any + * currently playing track. + */ +struct SetTrack : tinyfsm::Event { + std::variant new_track; + std::optional seek_to_second; + + enum Transition { + kHardCut, + kGapless, + // TODO: kCrossFade + }; + Transition transition; }; -struct PlaybackStopped : tinyfsm::Event {}; +struct TogglePlayPause : tinyfsm::Event { + std::optional set_to; +}; struct QueueUpdate : tinyfsm::Event { bool current_changed; @@ -49,15 +107,6 @@ struct QueueUpdate : tinyfsm::Event { Reason reason; }; -struct PlayFile : tinyfsm::Event { - std::string filename; -}; - -struct SeekFile : tinyfsm::Event { - uint32_t offset; - std::string filename; -}; - struct StepUpVolume : tinyfsm::Event {}; struct StepDownVolume : tinyfsm::Event {}; struct SetVolume : tinyfsm::Event { @@ -83,17 +132,26 @@ struct SetVolumeLimit : tinyfsm::Event { int limit_db; }; -struct TogglePlayPause : tinyfsm::Event {}; - struct OutputModeChanged : tinyfsm::Event {}; namespace internal { -struct InputFileOpened : tinyfsm::Event {}; -struct InputFileClosed : tinyfsm::Event {}; -struct InputFileFinished : tinyfsm::Event {}; +struct DecoderOpened : tinyfsm::Event { + std::shared_ptr track; +}; + +struct DecoderClosed : tinyfsm::Event {}; + +struct DecoderError : tinyfsm::Event {}; -struct AudioPipelineIdle : tinyfsm::Event {}; +struct ConverterConfigurationChanged : tinyfsm::Event { + IAudioOutput::Format src_format; + IAudioOutput::Format dst_format; +}; + +struct ConverterProgress : tinyfsm::Event { + uint32_t samples_sunk; +}; } // namespace internal diff --git a/src/audio/include/audio_fsm.hpp b/src/audio/include/audio_fsm.hpp index 13e241be..62bb4786 100644 --- a/src/audio/include/audio_fsm.hpp +++ b/src/audio/include/audio_fsm.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include #include @@ -41,6 +42,17 @@ class AudioState : public tinyfsm::Fsm { /* Fallback event handler. Does nothing. */ void react(const tinyfsm::Event& ev) {} + void react(const QueueUpdate&); + void react(const SetTrack&); + void react(const TogglePlayPause&); + + void react(const internal::DecoderOpened&); + void react(const internal::DecoderClosed&); + void react(const internal::DecoderError&); + + void react(const internal::ConverterConfigurationChanged&); + void react(const internal::ConverterProgress&); + void react(const StepUpVolume&); void react(const StepDownVolume&); virtual void react(const system_fsm::HasPhonesChanged&); @@ -56,17 +68,6 @@ class AudioState : public tinyfsm::Fsm { virtual void react(const system_fsm::StorageMounted&) {} virtual void react(const system_fsm::BluetoothEvent&); - virtual void react(const PlayFile&) {} - virtual void react(const SeekFile&) {} - virtual void react(const QueueUpdate&) {} - virtual void react(const PlaybackUpdate&) {} - void react(const TogglePlayPause&); - - virtual void react(const internal::InputFileOpened&) {} - virtual void react(const internal::InputFileClosed&) {} - virtual void react(const internal::InputFileFinished&) {} - virtual void react(const internal::AudioPipelineIdle&) {} - protected: auto clearDrainBuffer() -> void; auto playTrack(database::TrackId id) -> void; @@ -83,10 +84,17 @@ class AudioState : public tinyfsm::Fsm { static StreamBufferHandle_t sDrainBuffer; - static std::optional sCurrentTrack; + static std::shared_ptr sCurrentTrack; + static uint64_t sCurrentSamples; + static std::optional sCurrentFormat; - auto readyToPlay() -> bool; - static bool sIsPlaybackAllowed; + static std::shared_ptr sNextTrack; + static uint64_t sNextTrackCueSamples; + + static bool sIsResampling; + static bool sIsPaused; + + auto currentPositionSeconds() -> std::optional; }; namespace states { @@ -94,7 +102,6 @@ namespace states { class Uninitialised : public AudioState { public: void react(const system_fsm::BootComplete&) override; - void react(const system_fsm::BluetoothEvent&) override{}; using AudioState::react; @@ -102,10 +109,6 @@ class Uninitialised : public AudioState { class Standby : public AudioState { public: - void react(const PlayFile&) override; - void react(const SeekFile&) override; - void react(const internal::InputFileOpened&) override; - void react(const QueueUpdate&) override; void react(const system_fsm::KeyLockChanged&) override; void react(const system_fsm::StorageMounted&) override; @@ -117,18 +120,6 @@ class Playback : public AudioState { void entry() override; void exit() override; - void react(const system_fsm::HasPhonesChanged&) override; - - void react(const PlayFile&) override; - void react(const SeekFile&) override; - void react(const QueueUpdate&) override; - void react(const PlaybackUpdate&) override; - - void react(const internal::InputFileOpened&) override; - void react(const internal::InputFileClosed&) override; - void react(const internal::InputFileFinished&) override; - void react(const internal::AudioPipelineIdle&) override; - using AudioState::react; }; diff --git a/src/audio/track_queue.cpp b/src/audio/track_queue.cpp index a3f4c815..dbe283c4 100644 --- a/src/audio/track_queue.cpp +++ b/src/audio/track_queue.cpp @@ -136,7 +136,7 @@ auto TrackQueue::insert(Item i, size_t index) -> void { { const std::shared_lock lock(mutex_); was_queue_empty = pos_ == tracks_.size(); - current_changed = pos_ == was_queue_empty || index == pos_; + current_changed = was_queue_empty || index == pos_; } auto update_shuffler = [=, this]() { -- cgit v1.2.3 From 078b77d0f796be3c787f62b9b830512e38d3b076 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Tue, 26 Mar 2024 12:12:42 +1100 Subject: pass stream start/update/end events through the whole pipeline --- src/audio/audio_converter.cpp | 209 ++++++++++++++++++++-------------- src/audio/audio_decoder.cpp | 34 +++--- src/audio/audio_fsm.cpp | 31 ++--- src/audio/include/audio_converter.hpp | 18 +-- src/audio/include/audio_events.hpp | 15 +-- src/audio/include/audio_fsm.hpp | 9 +- 6 files changed, 167 insertions(+), 149 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_converter.cpp b/src/audio/audio_converter.cpp index 1b233731..ebbd405f 100644 --- a/src/audio/audio_converter.cpp +++ b/src/audio/audio_converter.cpp @@ -28,7 +28,7 @@ [[maybe_unused]] static constexpr char kTag[] = "mixer"; static constexpr std::size_t kSampleBufferLength = - drivers::kI2SBufferLengthFrames * sizeof(sample::Sample); + drivers::kI2SBufferLengthFrames * sizeof(sample::Sample) * 2; static constexpr std::size_t kSourceBufferLength = kSampleBufferLength * 2; namespace audio { @@ -68,24 +68,32 @@ auto SampleConverter::SetOutput(std::shared_ptr output) -> void { sink_ = output; } -auto SampleConverter::ConvertSamples(cpp::span input, - const IAudioOutput::Format& format, - bool is_eos) -> void { +auto SampleConverter::beginStream(std::shared_ptr track) -> void { Args args{ - .format = format, + .track = new std::shared_ptr(track), + .samples_available = 0, + .is_end_of_stream = false, + }; + xQueueSend(commands_, &args, portMAX_DELAY); +} + +auto SampleConverter::continueStream(cpp::span input) -> void { + Args args{ + .track = nullptr, .samples_available = input.size(), - .is_end_of_stream = is_eos, + .is_end_of_stream = false, }; xQueueSend(commands_, &args, portMAX_DELAY); + xStreamBufferSend(source_, input.data(), input.size_bytes(), portMAX_DELAY); +} - cpp::span input_as_bytes = { - reinterpret_cast(input.data()), input.size_bytes()}; - size_t bytes_sent = 0; - while (bytes_sent < input_as_bytes.size()) { - bytes_sent += xStreamBufferSend( - source_, input_as_bytes.subspan(bytes_sent).data(), - input_as_bytes.size() - bytes_sent, pdMS_TO_TICKS(100)); - } +auto SampleConverter::endStream() -> void { + Args args{ + .track = nullptr, + .samples_available = 0, + .is_end_of_stream = true, + }; + xQueueSend(commands_, &args, portMAX_DELAY); } auto SampleConverter::Main() -> void { @@ -93,86 +101,93 @@ auto SampleConverter::Main() -> void { Args args; while (!xQueueReceive(commands_, &args, portMAX_DELAY)) { } - if (args.format != source_format_) { - resampler_.reset(); - source_format_ = args.format; - leftover_bytes_ = 0; - - auto new_target = sink_->PrepareFormat(args.format); - if (new_target != target_format_) { - // The new format is different to the old one. Wait for the sink to - // drain before continuing. - while (!xStreamBufferIsEmpty(sink_->stream())) { - ESP_LOGI(kTag, "waiting for sink stream to drain..."); - // TODO(jacqueline): Get the sink drain ISR to notify us of this - // via semaphore instead of busy-ish waiting. - vTaskDelay(pdMS_TO_TICKS(10)); - } - - sink_->Configure(new_target); - } - target_format_ = new_target; - // Send a final sample count for the previous sample rate. - if (samples_sunk_ > 0) { - events::Audio().Dispatch(internal::ConverterProgress{ - .samples_sunk = samples_sunk_, - }); + if (args.track) { + handleBeginStream(*args.track); + delete args.track; + } + if (args.samples_available) { + handleContinueStream(args.samples_available); + } + if (args.is_end_of_stream) { + handleEndStream(); + } + } +} + +auto SampleConverter::handleBeginStream(std::shared_ptr track) + -> void { + if (track->format != source_format_) { + resampler_.reset(); + source_format_ = track->format; + leftover_bytes_ = 0; + + auto new_target = sink_->PrepareFormat(track->format); + if (new_target != target_format_) { + // The new format is different to the old one. Wait for the sink to + // drain before continuing. + while (!xStreamBufferIsEmpty(sink_->stream())) { + ESP_LOGI(kTag, "waiting for sink stream to drain..."); + // TODO(jacqueline): Get the sink drain ISR to notify us of this + // via semaphore instead of busy-ish waiting. + vTaskDelay(pdMS_TO_TICKS(10)); } - samples_sunk_ = 0; - events::Audio().Dispatch(internal::ConverterConfigurationChanged{ - .src_format = source_format_, - .dst_format = target_format_, - }); + sink_->Configure(new_target); } + target_format_ = new_target; + } - // Loop until we finish reading all the bytes indicated. There might be - // leftovers from each iteration, and from this process as a whole, - // depending on the resampling stage. - size_t bytes_read = 0; - size_t bytes_to_read = args.samples_available * sizeof(sample::Sample); - while (bytes_read < bytes_to_read) { - // First top up the input buffer, taking care not to overwrite anything - // remaining from a previous iteration. - size_t bytes_read_this_it = xStreamBufferReceive( - source_, input_buffer_as_bytes_.subspan(leftover_bytes_).data(), - std::min(input_buffer_as_bytes_.size() - leftover_bytes_, - bytes_to_read - bytes_read), - portMAX_DELAY); - bytes_read += bytes_read_this_it; - - // Calculate the number of whole samples that are now in the input buffer. - size_t bytes_in_buffer = bytes_read_this_it + leftover_bytes_; - size_t samples_in_buffer = bytes_in_buffer / sizeof(sample::Sample); - - size_t samples_used = - HandleSamples(input_buffer_.first(samples_in_buffer), - args.is_end_of_stream && bytes_read == bytes_to_read); - - // Maybe the resampler didn't consume everything. Maybe the last few - // bytes we read were half a frame. Either way, we need to calculate the - // size of the remainder in bytes, then move it to the front of our - // buffer. - size_t bytes_used = samples_used * sizeof(sample::Sample); - assert(bytes_used <= bytes_in_buffer); - - leftover_bytes_ = bytes_in_buffer - bytes_used; - if (leftover_bytes_ > 0) { - std::memmove(input_buffer_as_bytes_.data(), - input_buffer_as_bytes_.data() + bytes_used, - leftover_bytes_); - } + samples_sunk_ = 0; + events::Audio().Dispatch(internal::StreamStarted{ + .track = track, + .src_format = source_format_, + .dst_format = target_format_, + }); +} + +auto SampleConverter::handleContinueStream(size_t samples_available) -> void { + // Loop until we finish reading all the bytes indicated. There might be + // leftovers from each iteration, and from this process as a whole, + // depending on the resampling stage. + size_t bytes_read = 0; + size_t bytes_to_read = samples_available * sizeof(sample::Sample); + while (bytes_read < bytes_to_read) { + // First top up the input buffer, taking care not to overwrite anything + // remaining from a previous iteration. + size_t bytes_read_this_it = xStreamBufferReceive( + source_, input_buffer_as_bytes_.subspan(leftover_bytes_).data(), + std::min(input_buffer_as_bytes_.size() - leftover_bytes_, + bytes_to_read - bytes_read), + portMAX_DELAY); + bytes_read += bytes_read_this_it; + + // Calculate the number of whole samples that are now in the input buffer. + size_t bytes_in_buffer = bytes_read_this_it + leftover_bytes_; + size_t samples_in_buffer = bytes_in_buffer / sizeof(sample::Sample); + + size_t samples_used = handleSamples(input_buffer_.first(samples_in_buffer)); + + // Maybe the resampler didn't consume everything. Maybe the last few + // bytes we read were half a frame. Either way, we need to calculate the + // size of the remainder in bytes, then move it to the front of our + // buffer. + size_t bytes_used = samples_used * sizeof(sample::Sample); + assert(bytes_used <= bytes_in_buffer); + + leftover_bytes_ = bytes_in_buffer - bytes_used; + if (leftover_bytes_ > 0) { + std::memmove(input_buffer_as_bytes_.data(), + input_buffer_as_bytes_.data() + bytes_used, leftover_bytes_); } } } -auto SampleConverter::HandleSamples(cpp::span input, - bool is_eos) -> size_t { +auto SampleConverter::handleSamples(cpp::span input) -> size_t { if (source_format_ == target_format_) { // The happiest possible case: the input format matches the output // format already. - SendToSink(input); + sendToSink(input); return input.size(); } @@ -190,7 +205,7 @@ auto SampleConverter::HandleSamples(cpp::span input, size_t read, written; std::tie(read, written) = resampler_->Process(input.subspan(samples_used), - resampled_buffer_, is_eos); + resampled_buffer_, false); samples_used += read; if (read == 0 && written == 0) { @@ -203,18 +218,40 @@ auto SampleConverter::HandleSamples(cpp::span input, samples_used = input.size(); } - SendToSink(output_source); + sendToSink(output_source); } + return samples_used; } -auto SampleConverter::SendToSink(cpp::span samples) -> void { +auto SampleConverter::handleEndStream() -> void { + if (resampler_) { + size_t read, written; + std::tie(read, written) = resampler_->Process({}, resampled_buffer_, true); + + if (written > 0) { + sendToSink(resampled_buffer_.first(written)); + } + } + + // Send a final update to finish off this stream's samples. + if (samples_sunk_ > 0) { + events::Audio().Dispatch(internal::StreamUpdate{ + .samples_sunk = samples_sunk_, + }); + samples_sunk_ = 0; + } + + events::Audio().Dispatch(internal::StreamEnded{}); +} + +auto SampleConverter::sendToSink(cpp::span samples) -> void { // Update the number of samples sunk so far *before* actually sinking them, // since writing to the stream buffer will block when the buffer gets full. samples_sunk_ += samples.size(); if (samples_sunk_ >= target_format_.sample_rate * target_format_.num_channels) { - events::Audio().Dispatch(internal::ConverterProgress{ + events::Audio().Dispatch(internal::StreamUpdate{ .samples_sunk = samples_sunk_, }); samples_sunk_ = 0; diff --git a/src/audio/audio_decoder.cpp b/src/audio/audio_decoder.cpp index 55ebc0ec..90c69c16 100644 --- a/src/audio/audio_decoder.cpp +++ b/src/audio/audio_decoder.cpp @@ -72,7 +72,6 @@ void Decoder::Main() { for (;;) { if (source_->HasNewStream() || !stream_) { std::shared_ptr new_stream = source_->NextStream(); - ESP_LOGI(kTag, "decoder has new stream"); if (new_stream && BeginDecoding(new_stream)) { stream_ = new_stream; } else { @@ -91,8 +90,7 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { codec_.reset(); codec_.reset(codecs::CreateCodecForType(stream->type()).value_or(nullptr)); if (!codec_) { - ESP_LOGE(kTag, "no codec found"); - events::Audio().Dispatch(internal::DecoderError{}); + ESP_LOGE(kTag, "no codec found for stream"); return false; } @@ -100,7 +98,6 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { if (open_res.has_error()) { ESP_LOGE(kTag, "codec failed to start: %s", codecs::ICodec::ErrorString(open_res.error()).c_str()); - events::Audio().Dispatch(internal::DecoderError{}); return false; } stream->SetPreambleFinished(); @@ -110,24 +107,21 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { .bits_per_sample = 16, }; - ESP_LOGI(kTag, "stream started ok"); - std::optional duration; if (open_res->total_samples) { duration = open_res->total_samples.value() / open_res->num_channels / open_res->sample_rate_hz; } - events::Audio().Dispatch(internal::DecoderOpened{ - .track = std::make_shared(TrackInfo{ - .tags = stream->tags(), - .uri = stream->Filepath(), - .duration = duration, - .start_offset = stream->Offset(), - .bitrate_kbps = open_res->sample_rate_hz, - .encoding = stream->type(), - }), - }); + converter_->beginStream(std::make_shared(TrackInfo{ + .tags = stream->tags(), + .uri = stream->Filepath(), + .duration = duration, + .start_offset = stream->Offset(), + .bitrate_kbps = open_res->sample_rate_hz, + .encoding = stream->type(), + .format = *current_sink_format_, + })); return true; } @@ -135,18 +129,16 @@ auto Decoder::BeginDecoding(std::shared_ptr stream) -> bool { auto Decoder::ContinueDecoding() -> bool { auto res = codec_->DecodeTo(codec_buffer_); if (res.has_error()) { - events::Audio().Dispatch(internal::DecoderError{}); + converter_->endStream(); return true; } if (res->samples_written > 0) { - converter_->ConvertSamples(codec_buffer_.first(res->samples_written), - current_sink_format_.value(), - res->is_stream_finished); + converter_->continueStream(codec_buffer_.first(res->samples_written)); } if (res->is_stream_finished) { - events::Audio().Dispatch(internal::DecoderClosed{}); + converter_->endStream(); codec_.reset(); } diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 7a138cba..a6f4f4d1 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -55,9 +55,9 @@ std::shared_ptr AudioState::sBtOutput; std::shared_ptr AudioState::sOutput; // Two seconds of samples for two channels, at a representative sample rate. -constexpr size_t kDrainLatencySamples = 48000; +constexpr size_t kDrainLatencySamples = 48000 * 2 * 2; constexpr size_t kDrainBufferSize = - sizeof(sample::Sample) * kDrainLatencySamples * 4; + sizeof(sample::Sample) * kDrainLatencySamples; StreamBufferHandle_t AudioState::sDrainBuffer; @@ -151,33 +151,24 @@ void AudioState::react(const TogglePlayPause& ev) { } } -void AudioState::react(const internal::DecoderOpened& ev) { - ESP_LOGI(kTag, "decoder opened %s", ev.track->uri.c_str()); +void AudioState::react(const internal::StreamStarted& ev) { + sCurrentFormat = ev.dst_format; + sIsResampling = ev.src_format != ev.dst_format; sNextTrack = ev.track; sNextTrackCueSamples = sCurrentSamples + kDrainLatencySamples; -} -void AudioState::react(const internal::DecoderClosed&) { - ESP_LOGI(kTag, "decoder closed"); - // FIXME: only when we were playing the current track - sServices->track_queue().finish(); + ESP_LOGI(kTag, "new stream %s %u ch @ %lu hz (resample=%i)", + ev.track->uri.c_str(), sCurrentFormat->num_channels, + sCurrentFormat->sample_rate, sIsResampling); } -void AudioState::react(const internal::DecoderError&) { - ESP_LOGW(kTag, "decoder errored"); +void AudioState::react(const internal::StreamEnded&) { + ESP_LOGI(kTag, "stream ended"); // FIXME: only when we were playing the current track sServices->track_queue().finish(); } -void AudioState::react(const internal::ConverterConfigurationChanged& ev) { - sCurrentFormat = ev.dst_format; - sIsResampling = ev.src_format != ev.dst_format; - ESP_LOGI(kTag, "output format now %u ch @ %lu hz (resample=%i)", - sCurrentFormat->num_channels, sCurrentFormat->sample_rate, - sIsResampling); -} - -void AudioState::react(const internal::ConverterProgress& ev) { +void AudioState::react(const internal::StreamUpdate& ev) { ESP_LOGI(kTag, "sample converter sunk %lu samples", ev.samples_sunk); sCurrentSamples += ev.samples_sunk; diff --git a/src/audio/include/audio_converter.hpp b/src/audio/include/audio_converter.hpp index dcd068b5..232b5d8e 100644 --- a/src/audio/include/audio_converter.hpp +++ b/src/audio/include/audio_converter.hpp @@ -10,6 +10,7 @@ #include #include +#include "audio_events.hpp" #include "audio_sink.hpp" #include "audio_source.hpp" #include "codec.hpp" @@ -31,20 +32,23 @@ class SampleConverter { auto SetOutput(std::shared_ptr) -> void; - auto ConvertSamples(cpp::span, - const IAudioOutput::Format& format, - bool is_eos) -> void; + auto beginStream(std::shared_ptr) -> void; + auto continueStream(cpp::span) -> void; + auto endStream() -> void; private: auto Main() -> void; - auto SetTargetFormat(const IAudioOutput::Format& format) -> void; - auto HandleSamples(cpp::span, bool) -> size_t; + auto handleBeginStream(std::shared_ptr) -> void; + auto handleContinueStream(size_t samples_available) -> void; + auto handleEndStream() -> void; - auto SendToSink(cpp::span) -> void; + auto handleSamples(cpp::span) -> size_t; + + auto sendToSink(cpp::span) -> void; struct Args { - IAudioOutput::Format format; + std::shared_ptr* track; size_t samples_available; bool is_end_of_stream; }; diff --git a/src/audio/include/audio_events.hpp b/src/audio/include/audio_events.hpp index 9af30467..b8a0dba6 100644 --- a/src/audio/include/audio_events.hpp +++ b/src/audio/include/audio_events.hpp @@ -51,6 +51,8 @@ struct TrackInfo { /* The encoded format of the this track. */ codecs::StreamType encoding; + + IAudioOutput::Format format; }; /* @@ -136,23 +138,18 @@ struct OutputModeChanged : tinyfsm::Event {}; namespace internal { -struct DecoderOpened : tinyfsm::Event { +struct StreamStarted : tinyfsm::Event { std::shared_ptr track; -}; - -struct DecoderClosed : tinyfsm::Event {}; - -struct DecoderError : tinyfsm::Event {}; - -struct ConverterConfigurationChanged : tinyfsm::Event { IAudioOutput::Format src_format; IAudioOutput::Format dst_format; }; -struct ConverterProgress : tinyfsm::Event { +struct StreamUpdate : tinyfsm::Event { uint32_t samples_sunk; }; +struct StreamEnded : tinyfsm::Event {}; + } // namespace internal } // namespace audio diff --git a/src/audio/include/audio_fsm.hpp b/src/audio/include/audio_fsm.hpp index 62bb4786..c00813ac 100644 --- a/src/audio/include/audio_fsm.hpp +++ b/src/audio/include/audio_fsm.hpp @@ -46,12 +46,9 @@ class AudioState : public tinyfsm::Fsm { void react(const SetTrack&); void react(const TogglePlayPause&); - void react(const internal::DecoderOpened&); - void react(const internal::DecoderClosed&); - void react(const internal::DecoderError&); - - void react(const internal::ConverterConfigurationChanged&); - void react(const internal::ConverterProgress&); + void react(const internal::StreamStarted&); + void react(const internal::StreamUpdate&); + void react(const internal::StreamEnded&); void react(const StepUpVolume&); void react(const StepDownVolume&); -- cgit v1.2.3 From 4cec85af2d779ea8f6e3b46dfbea61ef5b0419f8 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Tue, 26 Mar 2024 16:45:20 +1100 Subject: implement handling of stream/playback ending --- src/audio/audio_converter.cpp | 1 + src/audio/audio_fsm.cpp | 119 +++++++++++++++++++++++++++------------- src/audio/i2s_audio_output.cpp | 3 - src/audio/include/audio_fsm.hpp | 6 +- 4 files changed, 88 insertions(+), 41 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_converter.cpp b/src/audio/audio_converter.cpp index ebbd405f..015be6a3 100644 --- a/src/audio/audio_converter.cpp +++ b/src/audio/audio_converter.cpp @@ -241,6 +241,7 @@ auto SampleConverter::handleEndStream() -> void { }); samples_sunk_ = 0; } + leftover_bytes_ = 0; events::Audio().Dispatch(internal::StreamEnded{}); } diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index a6f4f4d1..07737872 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -60,38 +60,58 @@ constexpr size_t kDrainBufferSize = sizeof(sample::Sample) * kDrainLatencySamples; StreamBufferHandle_t AudioState::sDrainBuffer; +std::optional AudioState::sDrainFormat; std::shared_ptr AudioState::sCurrentTrack; uint64_t AudioState::sCurrentSamples; -std::optional AudioState::sCurrentFormat; +bool AudioState::sCurrentTrackIsFromQueue; std::shared_ptr AudioState::sNextTrack; uint64_t AudioState::sNextTrackCueSamples; +bool AudioState::sNextTrackIsFromQueue; bool AudioState::sIsResampling; bool AudioState::sIsPaused = true; auto AudioState::currentPositionSeconds() -> std::optional { - if (!sCurrentTrack || !sCurrentFormat) { + if (!sCurrentTrack || !sDrainFormat) { return {}; } return sCurrentSamples / - (sCurrentFormat->num_channels * sCurrentFormat->sample_rate); + (sDrainFormat->num_channels * sDrainFormat->sample_rate); } void AudioState::react(const QueueUpdate& ev) { - if (!ev.current_changed && ev.reason != QueueUpdate::kRepeatingLastTrack) { - return; + SetTrack cmd{ + .new_track = std::monostate{}, + .seek_to_second = {}, + .transition = SetTrack::Transition::kHardCut, + }; + + auto current = sServices->track_queue().current(); + if (current) { + cmd.new_track = *current; } - SetTrack::Transition transition; switch (ev.reason) { case QueueUpdate::kExplicitUpdate: - transition = SetTrack::Transition::kHardCut; + if (!ev.current_changed) { + return; + } + sNextTrackIsFromQueue = true; + cmd.transition = SetTrack::Transition::kHardCut; break; case QueueUpdate::kRepeatingLastTrack: + sNextTrackIsFromQueue = true; + cmd.transition = SetTrack::Transition::kGapless; + break; case QueueUpdate::kTrackFinished: - transition = SetTrack::Transition::kGapless; + if (!ev.current_changed) { + cmd.new_track = std::monostate{}; + } else { + sNextTrackIsFromQueue = true; + } + cmd.transition = SetTrack::Transition::kGapless; break; case QueueUpdate::kDeserialised: default: @@ -100,25 +120,29 @@ void AudioState::react(const QueueUpdate& ev) { return; } - SetTrack cmd{ - .new_track = {}, - .seek_to_second = 0, - .transition = transition, - }; - - auto current = sServices->track_queue().current(); - if (current) { - cmd.new_track = *current; - } - tinyfsm::FsmList::dispatch(cmd); } void AudioState::react(const SetTrack& ev) { if (ev.transition == SetTrack::Transition::kHardCut) { + sCurrentTrack.reset(); + sCurrentSamples = 0; + sCurrentTrackIsFromQueue = false; clearDrainBuffer(); } + if (std::holds_alternative(ev.new_track)) { + ESP_LOGI(kTag, "playback finished, awaiting drain"); + sFileSource->SetPath(); + awaitEmptyDrainBuffer(); + sCurrentTrack.reset(); + sDrainFormat.reset(); + sCurrentSamples = 0; + sCurrentTrackIsFromQueue = false; + transit(); + return; + } + // Move the rest of the work to a background worker, since it may require db // lookups to resolve a track id into a path. auto new_track = ev.new_track; @@ -152,46 +176,56 @@ void AudioState::react(const TogglePlayPause& ev) { } void AudioState::react(const internal::StreamStarted& ev) { - sCurrentFormat = ev.dst_format; + sDrainFormat = ev.dst_format; sIsResampling = ev.src_format != ev.dst_format; + sNextTrack = ev.track; - sNextTrackCueSamples = sCurrentSamples + kDrainLatencySamples; + sNextTrackCueSamples = sCurrentSamples + (kDrainLatencySamples / 2); ESP_LOGI(kTag, "new stream %s %u ch @ %lu hz (resample=%i)", - ev.track->uri.c_str(), sCurrentFormat->num_channels, - sCurrentFormat->sample_rate, sIsResampling); + ev.track->uri.c_str(), sDrainFormat->num_channels, + sDrainFormat->sample_rate, sIsResampling); } void AudioState::react(const internal::StreamEnded&) { ESP_LOGI(kTag, "stream ended"); - // FIXME: only when we were playing the current track - sServices->track_queue().finish(); + + if (sCurrentTrackIsFromQueue) { + sServices->track_queue().finish(); + } else { + tinyfsm::FsmList::dispatch(SetTrack{ + .new_track = std::monostate{}, + .seek_to_second = {}, + .transition = SetTrack::Transition::kGapless, + }); + } } void AudioState::react(const internal::StreamUpdate& ev) { - ESP_LOGI(kTag, "sample converter sunk %lu samples", ev.samples_sunk); sCurrentSamples += ev.samples_sunk; if (sNextTrack && sCurrentSamples >= sNextTrackCueSamples) { ESP_LOGI(kTag, "next track is now sinking"); sCurrentTrack = sNextTrack; sCurrentSamples -= sNextTrackCueSamples; - sCurrentSamples += - sNextTrack->start_offset.value_or(0) * - (sCurrentFormat->num_channels * sCurrentFormat->sample_rate); + sCurrentSamples += sNextTrack->start_offset.value_or(0) * + (sDrainFormat->num_channels * sDrainFormat->sample_rate); + sCurrentTrackIsFromQueue = sNextTrackIsFromQueue; sNextTrack.reset(); sNextTrackCueSamples = 0; + sNextTrackIsFromQueue = false; } - PlaybackUpdate event{ - .current_track = sCurrentTrack, - .track_position = currentPositionSeconds(), - .paused = !is_in_state(), - }; - - events::System().Dispatch(event); - events::Ui().Dispatch(event); + if (sCurrentTrack) { + PlaybackUpdate event{ + .current_track = sCurrentTrack, + .track_position = currentPositionSeconds(), + .paused = !is_in_state(), + }; + events::System().Dispatch(event); + events::Ui().Dispatch(event); + } if (sCurrentTrack && !sIsPaused && !is_in_state()) { ESP_LOGI(kTag, "ready to play!"); @@ -321,6 +355,17 @@ auto AudioState::clearDrainBuffer() -> void { } } +auto AudioState::awaitEmptyDrainBuffer() -> void { + if (is_in_state()) { + for (int i = 0; i < 10 && !xStreamBufferIsEmpty(sDrainBuffer); i++) { + vTaskDelay(pdMS_TO_TICKS(250)); + } + } + if (!xStreamBufferIsEmpty(sDrainBuffer)) { + clearDrainBuffer(); + } +} + auto AudioState::commitVolume() -> void { auto mode = sServices->nvs().OutputMode(); auto vol = sOutput->GetVolume(); diff --git a/src/audio/i2s_audio_output.cpp b/src/audio/i2s_audio_output.cpp index cd61d97f..3fb99159 100644 --- a/src/audio/i2s_audio_output.cpp +++ b/src/audio/i2s_audio_output.cpp @@ -152,9 +152,6 @@ auto I2SAudioOutput::Configure(const Format& fmt) -> void { return; } - ESP_LOGI(kTag, "incoming audio stream: %u ch %u bpp @ %lu Hz", - fmt.num_channels, fmt.bits_per_sample, fmt.sample_rate); - drivers::I2SDac::Channels ch; switch (fmt.num_channels) { case 1: diff --git a/src/audio/include/audio_fsm.hpp b/src/audio/include/audio_fsm.hpp index c00813ac..60afb321 100644 --- a/src/audio/include/audio_fsm.hpp +++ b/src/audio/include/audio_fsm.hpp @@ -67,6 +67,8 @@ class AudioState : public tinyfsm::Fsm { protected: auto clearDrainBuffer() -> void; + auto awaitEmptyDrainBuffer() -> void; + auto playTrack(database::TrackId id) -> void; auto commitVolume() -> void; @@ -83,10 +85,12 @@ class AudioState : public tinyfsm::Fsm { static std::shared_ptr sCurrentTrack; static uint64_t sCurrentSamples; - static std::optional sCurrentFormat; + static std::optional sDrainFormat; + static bool sCurrentTrackIsFromQueue; static std::shared_ptr sNextTrack; static uint64_t sNextTrackCueSamples; + static bool sNextTrackIsFromQueue; static bool sIsResampling; static bool sIsPaused; -- cgit v1.2.3 From 239e6d89507a24c849385f4bfa93ac4ad58e5de5 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Thu, 28 Mar 2024 13:30:24 +1100 Subject: bump esp-idf to 5.2.1 --- src/audio/audio_converter.cpp | 1 - src/audio/audio_fsm.cpp | 1 - src/audio/fatfs_audio_input.cpp | 1 - src/audio/include/audio_sink.hpp | 1 - src/audio/readahead_source.cpp | 1 - 5 files changed, 5 deletions(-) (limited to 'src/audio') diff --git a/src/audio/audio_converter.cpp b/src/audio/audio_converter.cpp index 015be6a3..eb1cde80 100644 --- a/src/audio/audio_converter.cpp +++ b/src/audio/audio_converter.cpp @@ -19,7 +19,6 @@ #include "freertos/portmacro.h" #include "freertos/projdefs.h" #include "i2s_dac.hpp" -#include "idf_additions.h" #include "resample.hpp" #include "sample.hpp" diff --git a/src/audio/audio_fsm.cpp b/src/audio/audio_fsm.cpp index 07737872..424b0eff 100644 --- a/src/audio/audio_fsm.cpp +++ b/src/audio/audio_fsm.cpp @@ -31,7 +31,6 @@ #include "future_fetcher.hpp" #include "i2s_audio_output.hpp" #include "i2s_dac.hpp" -#include "idf_additions.h" #include "nvs.hpp" #include "sample.hpp" #include "service_locator.hpp" diff --git a/src/audio/fatfs_audio_input.cpp b/src/audio/fatfs_audio_input.cpp index 74c1154b..29d32390 100644 --- a/src/audio/fatfs_audio_input.cpp +++ b/src/audio/fatfs_audio_input.cpp @@ -22,7 +22,6 @@ #include "ff.h" #include "freertos/portmacro.h" #include "freertos/projdefs.h" -#include "idf_additions.h" #include "readahead_source.hpp" #include "span.hpp" diff --git a/src/audio/include/audio_sink.hpp b/src/audio/include/audio_sink.hpp index 85c23f5c..e11f3ce0 100644 --- a/src/audio/include/audio_sink.hpp +++ b/src/audio/include/audio_sink.hpp @@ -11,7 +11,6 @@ #include "esp_heap_caps.h" #include "freertos/FreeRTOS.h" -#include "idf_additions.h" namespace audio { diff --git a/src/audio/readahead_source.cpp b/src/audio/readahead_source.cpp index c7b960d2..fe7ac3bd 100644 --- a/src/audio/readahead_source.cpp +++ b/src/audio/readahead_source.cpp @@ -17,7 +17,6 @@ #include "audio_source.hpp" #include "codec.hpp" #include "freertos/portmacro.h" -#include "idf_additions.h" #include "spi.hpp" #include "tasks.hpp" #include "types.hpp" -- cgit v1.2.3 From 35a822fe602cdc9e3a3482df3913ea33af6fc8c2 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Thu, 28 Mar 2024 14:46:09 +1100 Subject: Use 48kHz SBC instead of 44.1 --- src/audio/bt_audio_output.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/audio') diff --git a/src/audio/bt_audio_output.cpp b/src/audio/bt_audio_output.cpp index dff98e36..04daf71f 100644 --- a/src/audio/bt_audio_output.cpp +++ b/src/audio/bt_audio_output.cpp @@ -83,7 +83,7 @@ auto BluetoothAudioOutput::PrepareFormat(const Format& orig) -> Format { // ESP-IDF's current Bluetooth implementation currently handles SBC encoding, // but requires a fixed input format. return Format{ - .sample_rate = 44100, + .sample_rate = 48000, .num_channels = 2, .bits_per_sample = 16, }; -- cgit v1.2.3