Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ src/
decoder_source.cpp - thread lifecycle and orchestration
audio_decoder.{h,cpp} - FLAC/MP3/Opus/Vorbis/WAV decode loop
audio_reader.{h,cpp} - HTTP → RingBuffer
c_string_view.h - CStringView: non-owning view of NUL-terminated text
ring_buffer.{h,cpp} - SPSC byte ring buffer; owns storage, zero-copy on both sides, no lock to move data
md_transfer_buffer.{h,cpp} - flat staging buffer with start-pointer + length cursors (decoder output)
types.cpp - AudioStreamInfo, detect_audio_file_type{,_from_content}, audio_file_type_to_string
Expand Down
7 changes: 3 additions & 4 deletions src/audio_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
#include <algorithm>
#include <chrono>
#include <thread>
#include <utility>

namespace micro_decoder {

Expand Down Expand Up @@ -50,11 +49,11 @@ static uint64_t now_ms() {

AudioReader::AudioReader(uint32_t http_timeout_ms, uint32_t http_read_timeout_ms,
uint32_t write_timeout_ms, size_t http_rx_buffer_size,
std::string user_agent, std::string ca_certificate)
CStringView user_agent, CStringView ca_certificate)
: max_read_size_(http_rx_buffer_size == 0 ? DEFAULT_RX_BUFFER_SIZE : http_rx_buffer_size),
write_timeout_ms_(write_timeout_ms) {
this->request_.user_agent = std::move(user_agent);
this->request_.ca_certificate = std::move(ca_certificate);
this->request_.user_agent = user_agent;
this->request_.ca_certificate = ca_certificate;
this->request_.rx_buffer_size = http_rx_buffer_size;
this->request_.connect_timeout_ms = http_timeout_ms;
this->request_.read_timeout_ms = http_read_timeout_ms;
Expand Down
6 changes: 4 additions & 2 deletions src/audio_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#pragma once

#include "c_string_view.h"
#include "micro_decoder/types.h"
#include "platform/http_client.h"
#include "ring_buffer.h"
Expand All @@ -40,7 +41,8 @@ enum class AudioReaderState : uint8_t {
* @brief Reads raw audio data from an HTTP URL into a RingBuffer.
*
* Runs on the reader thread. Typical usage:
* 1. Construct with the HTTP timeouts and receive buffer size.
* 1. Construct with the HTTP timeouts, receive buffer size, user agent, and CA certificate.
* The last two are viewed rather than copied, so their text must outlive the reader.
* 2. Call set_sink() to set the destination RingBuffer.
* 3. Call start_url() to connect and detect the file type.
* 4. Call run() in a loop until it returns FINISHED or FAILED.
Expand All @@ -60,7 +62,7 @@ class AudioReader {
public:
explicit AudioReader(uint32_t http_timeout_ms, uint32_t http_read_timeout_ms,
uint32_t write_timeout_ms, size_t http_rx_buffer_size,
std::string user_agent, std::string ca_certificate);
CStringView user_agent, CStringView ca_certificate);
~AudioReader();

AudioReader(const AudioReader&) = delete;
Expand Down
105 changes: 105 additions & 0 deletions src/c_string_view.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright 2026 Kevin Ahrendt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// @file c_string_view.h
/// @brief CStringView: a non-owning view of NUL-terminated text

#pragma once

#include <cstddef>
#include <cstdlib>
#include <string>

namespace micro_decoder {

/**
* @brief Non-owning view of text that is guaranteed to be NUL-terminated
*
* Lets text be handed to C APIs that take a `const char*` without copying it first. A plain
* std::string_view cannot do that: it may end anywhere inside a larger buffer. This view can
* only be built from a std::string or a const character array whose last element is a NUL,
* such as a string literal, so c_str() is always safe to pass on.
*
* @note The view holds a pointer, not a copy. The text it was built from must outlive every
* use of the view and must not be modified or reallocated meanwhile. Building one from a
* temporary std::string does not compile, which catches the most common way to break that.
*/
class CStringView {
public:
/// @brief Constructs an empty view
constexpr CStringView() = default;

/// @brief Views the characters of a std::string the caller keeps alive
/// @note Implicit, like std::string_view's conversions, so a std::string can be passed
/// wherever a view is taken.
/// @param str Text to view; must outlive the view and stay unchanged while it is used
// cppcheck-suppress noExplicitConstructor // converting is the point of a view type
CStringView(const std::string& str) : data_(str.c_str()), size_(str.size()) {}

/// @brief Views a string literal, or any const character array ending in a NUL
/// @note The length is measured up to the first NUL rather than taken from N, so an
/// array holding shorter text is viewed correctly too. An array whose last element is
/// not a NUL fails to compile in a constant expression and aborts otherwise, rather than
/// letting the length scan run off its end.
/// @param literal Character array whose last element is a NUL
template <size_t N>
// cppcheck-suppress noExplicitConstructor // lets a literal stand in for a view
constexpr CStringView(const char (&literal)[N])
: data_(literal), size_(terminated_length(literal)) {}

/// @brief Refuses a writable array, whose text could change while the view points at it
template <size_t N>
CStringView(char (&)[N]) = delete;

/// @brief Refuses a temporary, which would be destroyed while the view still points at it
CStringView(const std::string&&) = delete;

/// @brief Returns the text as a NUL-terminated C string
/// @return Pointer to the first character; never nullptr
constexpr const char* c_str() const {
return this->data_;
}

/// @brief Returns the length of the text, excluding the terminating NUL
/// @return Number of characters
constexpr size_t size() const {
return this->size_;
}

/// @brief Returns true when the text is empty
/// @return true if size() is 0
constexpr bool empty() const {
return this->size_ == 0;
}

private:
/// @brief Returns the length of the text in a NUL-terminated array
/// @param text Character array whose last element must be a NUL
/// @return Characters before the first NUL
template <size_t N>
static constexpr size_t terminated_length(const char (&text)[N]) {
// std::abort() is not constexpr, so reaching it in a constant expression is a
// compile error
return text[N - 1] == '\0' ? std::char_traits<char>::length(text)
: (std::abort(), static_cast<size_t>(0));
}

// Pointer fields
const char* data_{""};

// size_t fields
size_t size_{0};
};

} // namespace micro_decoder
9 changes: 8 additions & 1 deletion src/decoder_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ static constexpr uint32_t MAX_HTTP_IDLE_BACKOFF_MS = 100;
/// @brief Internal implementation state for DecoderSource (pImpl)
struct DecoderSource::Impl {
// Struct fields
/// @brief The caller's settings, fixed for the object's lifetime
/// @note Declared first so it is destroyed last, after both worker threads are joined:
/// the reader's HTTP client views http_user_agent and http_ca_certificate here rather
/// than copying them. Nothing changes this after the constructor, so those views never
/// see the strings reallocate.
DecoderConfig config;
EventFlags event_flags;
RingBuffer ring_buffer;
Expand Down Expand Up @@ -385,7 +390,9 @@ struct DecoderSource::Impl {
void reader_thread_main() {
// One AudioReader for the thread's whole life, so a persistent reader keeps its HTTP
// client (and, on ESP-IDF, the esp_http_client handle with its receive buffer and TLS
// transport) between playbacks instead of rebuilding it for each one
// transport) between playbacks instead of rebuilding it for each one. It views the
// user agent and CA certificate in this->config instead of copying them, which is
// safe because config outlives this thread and never changes (see its declaration).
AudioReader reader(this->config.http_timeout_ms, this->config.http_read_timeout_ms,
this->config.reader_write_timeout_ms, this->config.http_rx_buffer_size,
this->config.http_user_agent, this->config.http_ca_certificate);
Expand Down
5 changes: 3 additions & 2 deletions src/host/http_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,10 @@ class CurlHttpClient final : public HttpClient {
}
if (!request.ca_certificate.empty()) {
#ifdef CURLOPT_CAINFO_BLOB
// CURL_BLOB_COPY: libcurl copies the data immediately, so .data() lifetime is fine.
// CURL_BLOB_COPY: libcurl copies the data immediately, so the view only has to
// outlive this call.
curl_blob blob{
static_cast<void*>(const_cast<char*>(request.ca_certificate.data())),
static_cast<void*>(const_cast<char*>(request.ca_certificate.c_str())),
request.ca_certificate.size(),
CURL_BLOB_COPY,
};
Expand Down
15 changes: 10 additions & 5 deletions src/platform/http_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

#pragma once

#include "c_string_view.h"

#include <cstddef>
#include <cstdint>
#include <memory>
Expand Down Expand Up @@ -52,12 +54,14 @@ struct HttpRequest {
std::string url;

/// @brief User-Agent header value; empty uses the platform client's default
std::string user_agent;
/// @note Not copied: the text must outlive the HttpClient this request is opened on.
CStringView user_agent;

/// @brief PEM-encoded CA certificate(s) used to verify HTTPS servers
/// Empty falls back to the platform default trust store (certificate bundle on ESP-IDF,
/// system trust store on host). Ignored for plain HTTP.
std::string ca_certificate;
/// @note Not copied: the text must outlive the HttpClient this request is opened on.
CStringView ca_certificate;

/// @brief Polled while open() blocks; nullptr disables cancellation
HttpCancelCheck cancel_check{nullptr};
Expand Down Expand Up @@ -88,9 +92,10 @@ struct HttpRequest {
*
* A client may be opened again after close(). Implementations are free to keep their
* connection handle and buffers across that cycle instead of rebuilding them, so every
* HttpRequest passed to one instance must differ only in url and the cancel hook. The
* ca_certificate string must also stay alive and unchanged for as long as the instance:
* the ESP-IDF client keeps a pointer to its characters rather than a copy.
* HttpRequest passed to one instance must differ only in url and the cancel hook. The text
* behind user_agent and ca_certificate is only viewed, never copied into the request, so it
* must stay alive and unchanged for as long as the instance: the ESP-IDF client goes on
* pointing at the certificate's characters after open() returns.
*
* @code
* HttpRequest request;
Expand Down
2 changes: 2 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ set(DECODER_TESTS
prepare_during_url_playback
prepare_then_destroy
prepare_then_stop
reader_views_request_text
play_url_user_agent
)

foreach(test_name IN LISTS DECODER_TESTS)
Expand Down
Loading
Loading