Skip to content

Commit df59ccd

Browse files
meiser79claude
andcommitted
Let a source report metadata for its input audio
SourceRole::set_metadata() reports what the captured audio is, for a source that learns it from the device feeding it, and clear_metadata() withdraws it. Opt in with SourceRoleConfig::metadata, which reserves the text block when the role is added. The protocol task copies the block into each client/state source object it sends, converting the local timestamp through the connection's time filter, so the trivially copyable state snapshot stays free of the text. Follows the source metadata object proposed for roles/source/v1.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a10289a commit df59ccd

8 files changed

Lines changed: 358 additions & 7 deletions

File tree

‎docs/integration-guide.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,19 @@ source.set_signal(SourceSignal::PRESENT); // or ABSENT
199199

200200
Detecting the signal is up to the application (a jack-detect pin, a link state, or a level meter on the input); call `set_signal()` on each change. The server decides what to do with it (roles/source/v1.md "Default streaming behavior").
201201

202+
A role configured with `metadata` also reports what the input audio is, for a source that learns it from the device feeding it (a Bluetooth sender's track information, a cast receiver's media status). Main loop only; the text is copied before the call returns:
203+
204+
```cpp
205+
SourceMetadata now_playing;
206+
now_playing.title = "Blue in Green";
207+
now_playing.artist = "Miles Davis";
208+
now_playing.progress = SourceMetadataProgress{.track_progress_ms = 1000, .track_duration_ms = 337000};
209+
source.set_metadata(now_playing); // timestamp_us 0: measured now
210+
source.clear_metadata(); // nothing known any more
211+
```
212+
213+
Call it when the track or the playback state changes, not to move the position on: the server extrapolates that from `progress` (roles/source/v1.md "Source metadata"). A text field over the spec's cap is cut at a UTF-8 boundary; a field that is not valid UTF-8, or a `track` of 0, refuses the whole report. The text block (about 3 KB) is reserved when the role is added, from `buffer_location`.
214+
202215
`examples/source_client/` is a working reference: it captures the default PortAudio input device and feeds `write_audio()` from the capture callback with each buffer's capture time on the client's clock. With `-s` it also reports line sense from the input's level.
203216
204217
### Application-Specific Roles
@@ -1279,7 +1292,7 @@ Never call `loop()`, `start()` or `stop()` from a listener, role or provider cal
12791292

12801293
`ControllerRole::send_command()` is callable from any thread.
12811294

1282-
`SourceRole::write_audio()` is for exactly one capture thread; the library does not serialize concurrent writers. `SourceRole::set_signal()` and `is_streaming()` are main loop only.
1295+
`SourceRole::write_audio()` is for exactly one capture thread; the library does not serialize concurrent writers. `SourceRole::set_signal()`, `set_metadata()`, `clear_metadata()` and `is_streaming()` are main loop only.
12831296

12841297
`ArtworkRole::frame_done()` must be called from the main loop thread (typically from inside `on_image_display()`/`on_image_clear()` or when a cross-fade animation completes).
12851298

@@ -1593,6 +1606,7 @@ Configuration passed to `client.add_source()`. A value that breaks any rule belo
15931606
| `opus_bitrate` | `uint32_t` | `128000` | Opus bitrate in bit/s, 500 to 512000; ignored for `PCM` and `FLAC` |
15941607
| `opus_complexity` | `uint8_t` | `2` | Opus encoder complexity, at most 10; ignored for `PCM` and `FLAC` |
15951608
| `line_sense` | `bool` | `false` | Advertise signal sensing; see `SourceRole::set_signal()` |
1609+
| `metadata` | `bool` | `false` | Allow `SourceRole::set_metadata()`; reserves its text block when the role is added |
15961610
| `buffer_location` | `MemoryLocation` | `PREFER_EXTERNAL` | Placement of the capture buffer, the chunk buffer and a `FLAC` or `OPUS` encoder's chunk scratch (ESP-IDF only) |
15971611
| `priority` | `unsigned` | `3` | FreeRTOS priority for the source task, below the protocol and httpd tasks (ESP-IDF only) |
15981612
| `psram_stack` | `bool` | `false` | Allocate the source task stack in PSRAM (ESP-IDF only) |

‎docs/internals.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ The primitives other than the Inbox and the inbound and outbound rings live in `
4545
| `InboundGate`, one per connection | The connection's transport: the fallback message in flight, the count of ring items not yet taken, the out-of-band close | The protocol task, which takes and consumes them and detaches the gate; the connection manager detaches it when the connection leaves it, from any thread |
4646
| `ProtocolTask` command queue (`ProtocolCommand`) | Transport threads (accepts of upgraded inbound connections, in slots reserved per socket); any thread (controller commands, in `CONSUMER_COMMAND_BURST` slots, the push past them refused, each stamped with the controller's teardown generation it was validated under and dropped by the task if a teardown has moved it on since) | The protocol task; at `stop()`, the joining thread for what the final tick left |
4747
| `ProtocolTask` state slot (`publish_state()`) | Main loop (`SendspinClient::publish_state()` and `start()`), latest-wins `client/state` | The protocol task |
48+
| The source's metadata block (`SourceRole::Impl::metadata`, under its `mutex`) | Main loop (`set_metadata()`, `clear_metadata()`, each followed by `publish_state()`) | The protocol task, which copies it into each `client/state` source object it builds (`append_state_metadata()`), so the trivially copyable state snapshot carries none of its text |
4849
| `ProtocolTask` request slot (`post_requests()`, `LifecycleRequests`) | Any thread, latest-wins and never refused: `connect_to()` (the latest URL), `disconnect()` (the latest reason, and it drops a waiting `connect_to()`), `leave()`, the pairing-window gestures (the later of a confirm and a cancel), unpaired-access changes | The protocol task; at `stop()`, the joining thread for what the final tick left |
4950
| Role command bits (the sync task's `EventFlags`; the visualizer's and artwork's on their item list's flags, through `InboundItemList::signal()`) | The protocol task, or the main loop in `stop()` (`COMMAND_STOP`, `COMMAND_STREAM_END`, ...); the main loop (the player's `COMMAND_START`, the visualizer's `COMMAND_ACK`, which the protocol task also signals for a stream event the full inbox ring dropped) | The role's thread |
5051
| Sync-task stream ordinals (`SyncTask::started_ordinal_`, `ended_ordinal_`) | The main loop's start acknowledgement; the protocol task's stream end | Sync task (see [Stream End and Start](#stream-end-and-start)) |
@@ -60,7 +61,7 @@ Plain atomics carry the rest: the `connected_` and `paired_` flags on `Connectio
6061

6162
### Locks
6263

63-
Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `clock()` reads behind `server_information()` copies); `RecordStore::mutex_`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration.
64+
Every library lock is a leaf: it is held only to copy or update its own state, never across a call that takes another library lock, a send, a listener or the persistence provider, so no two library locks are ever held at once and there is no lock order. The locks are the Inbox's `mutex_`; the inbound ring's own and each outbound ring's, the source's capture ring included (`SharedRingBuffer::mtx_` on host, the FreeRTOS ring's internal lock on ESP); each `InboundItemList::mutex_`; `ProtocolTask::command_mutex_` (the command queue, the state slot and the request slot); `ConnectionManager::published_mutex_` (which also serialises the role threads' `clock()` reads behind `server_information()` copies); `RecordStore::mutex_`; the source's `SourceMetadataBlock::mutex`; the artwork role's `DrainTask::slot_mutex` (its ack gates, between the decode thread and the main loop); each `ShadowSlot::mutex_`; the ESP server's `SendspinWsServer::pending_mutex_`; and, on host, the mutex inside `EventFlags`. Connection state has no lock at all: only the protocol task touches it, except the transport's own atomics, which state their writer and reader at their declaration.
6465

6566
### The Inbound Ring
6667

‎include/sendspin/config.h‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -818,10 +818,13 @@ struct SourceRoleConfig {
818818
/// @brief Opus encoder complexity, at most MAX_OPUS_COMPLEXITY. Ignored (and not validated)
819819
/// for PCM and FLAC.
820820
uint8_t opus_complexity{DEFAULT_OPUS_COMPLEXITY};
821-
uint8_t channels{2}; ///< Capture channel count; must be > 0 (at most 8 for FLAC, 1 or 2
822-
///< for OPUS)
823-
uint8_t bit_depth{16}; ///< Bits per sample: 16, 24 (3 packed bytes), or 32 (16 for OPUS)
824-
bool line_sense{false}; ///< Advertise signal sensing (see SourceRole::set_signal())
821+
uint8_t channels{2}; ///< Capture channel count; must be > 0 (at most 8 for FLAC, 1 or 2
822+
///< for OPUS)
823+
uint8_t bit_depth{16}; ///< Bits per sample: 16, 24 (3 packed bytes), or 32 (16 for OPUS)
824+
bool line_sense{false}; ///< Advertise signal sensing (see SourceRole::set_signal())
825+
/// @brief Allow SourceRole::set_metadata(): reserves its text block (about 3 KB, placed by
826+
/// buffer_location) when the role is added
827+
bool metadata{false};
825828
bool psram_stack{false}; ///< Allocate the source task stack in PSRAM (ESP-IDF only)
826829
};
827830

‎include/sendspin/source_role.h‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
#include <cstddef>
2323
#include <cstdint>
2424
#include <memory>
25+
#include <optional>
26+
#include <string_view>
2527

2628
namespace sendspin {
2729

@@ -37,6 +39,30 @@ enum class SourceSignal : uint8_t {
3739
ABSENT, // No audio signal on the capture input
3840
};
3941

42+
/// @brief Playback position of the input audio (roles/source/v1.md "client/state source object")
43+
struct SourceMetadataProgress {
44+
uint32_t track_progress_ms{0};
45+
uint32_t track_duration_ms{0}; ///< 0 for unknown or unlimited
46+
uint32_t playback_speed{1000}; ///< Speed multiplier * 1000; 0 is paused
47+
};
48+
49+
/// @brief What the input audio is, for SourceRole::set_metadata(). The text is copied before the
50+
/// call returns; each field longer than the spec's cap (255 bytes, 2048 for artwork_url) is cut
51+
/// at a UTF-8 boundary.
52+
struct SourceMetadata {
53+
/// @brief Local-clock time (SendspinClient::now_us()) at which `progress` was measured, or 0
54+
/// for the time of the call. Converted to the server clock when each client/state is sent.
55+
int64_t timestamp_us{0};
56+
std::optional<std::string_view> title{};
57+
std::optional<std::string_view> artist{};
58+
std::optional<std::string_view> album_artist{};
59+
std::optional<std::string_view> album{};
60+
std::optional<std::string_view> artwork_url{};
61+
std::optional<uint16_t> year{};
62+
std::optional<uint16_t> track{}; ///< At least 1
63+
std::optional<SourceMetadataProgress> progress{};
64+
};
65+
4066
/// @brief Listener for source role events. All methods fire on the main loop thread.
4167
class SourceRoleListener {
4268
public:
@@ -119,6 +145,18 @@ class SourceRole {
119145
/// warning) otherwise.
120146
void set_signal(SourceSignal signal);
121147

148+
/// @brief Reports what the input audio is, published to the server in client/state
149+
///
150+
/// Main loop only. Needs SourceRoleConfig::metadata. Send it when the metadata or the playback
151+
/// state changes, not to advance the position: the server extrapolates that from `progress`
152+
/// (roles/source/v1.md "Source metadata").
153+
/// @return false, changing nothing, without SourceRoleConfig::metadata, when its block could
154+
/// not be reserved, or when a text field is not valid UTF-8 or `track` is 0.
155+
bool set_metadata(const SourceMetadata& metadata);
156+
157+
/// @brief Withdraws the metadata set_metadata() reported. Main loop only.
158+
void clear_metadata();
159+
122160
/// @brief Whether the input stream is open, as the started/stopped callbacks last reported.
123161
/// Main loop only.
124162
bool is_streaming() const;

‎src/client.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1784,6 +1784,13 @@ void SendspinClient::publish_client_state(SendspinConnection* conn) {
17841784
client_state_for_roles(snapshot, entry->owned_roles & conn->get_active_role_mask());
17851785
JsonDocument json = make_json_document(*this->json_arena_);
17861786
build_client_state_message(&state_msg, json);
1787+
#ifdef SENDSPIN_ENABLE_SOURCE
1788+
// The metadata text lives in the role's block, not in the trivially copyable snapshot.
1789+
if (state_msg.source.has_value() && this->source_) {
1790+
this->source_->impl_->append_state_metadata(json["payload"]["source"].as<JsonObject>(),
1791+
conn->time_filter());
1792+
}
1793+
#endif
17871794
conn->send_json(json);
17881795
}
17891796

‎src/source_role.cpp‎

Lines changed: 115 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
#include "connection.h"
16+
#include "inline_text.h"
1617
#include "platform/json_arena.h"
1718
#include "platform/logging.h"
1819
#include "protocol_messages.h"
@@ -22,7 +23,9 @@
2223
#include "time_filter.h"
2324

2425
#include <algorithm>
26+
#include <array>
2527
#include <cinttypes>
28+
#include <cstring>
2629
#include <iterator>
2730

2831
static const char* const TAG = "sendspin.source";
@@ -125,7 +128,17 @@ SourceRole::Impl::Impl(SourceRoleConfig config, SendspinClient* client)
125128
: config(config),
126129
client(client),
127130
task(std::make_unique<SourceTask>(this)),
128-
config_valid(validate_config(config)) {}
131+
config_valid(validate_config(config)) {
132+
if (!config.metadata) {
133+
return;
134+
}
135+
auto block = std::make_unique<SourceMetadataBlock>();
136+
if (!block->text.allocate(SourceMetadataBlock::OFFSETS.back(), config.buffer_location)) {
137+
SS_LOGE(TAG, "Failed to reserve the source metadata block; set_metadata() is refused");
138+
return;
139+
}
140+
this->metadata = std::move(block);
141+
}
129142

130143
SourceRole::Impl::~Impl() {
131144
// Joined first, while the role it reads its config and gate through is still whole
@@ -206,6 +219,14 @@ void SourceRole::set_signal(SourceSignal signal) {
206219
this->impl_->set_signal(signal);
207220
}
208221

222+
bool SourceRole::set_metadata(const SourceMetadata& metadata) {
223+
return this->impl_->set_metadata(metadata);
224+
}
225+
226+
void SourceRole::clear_metadata() {
227+
this->impl_->clear_metadata();
228+
}
229+
209230
bool SourceRole::is_streaming() const {
210231
return this->impl_->streaming_active;
211232
}
@@ -400,6 +421,99 @@ bool SourceRole::Impl::write_audio(const uint8_t* data, size_t len, int64_t capt
400421
return this->task->write_audio(data, len, capture_time_us);
401422
}
402423

424+
bool SourceRole::Impl::set_metadata(const SourceMetadata& report) {
425+
if (!this->config.metadata) {
426+
SS_LOGW(TAG, "set_metadata() ignored: metadata not configured");
427+
return false;
428+
}
429+
if (!this->metadata) {
430+
return false;
431+
}
432+
const std::array<const std::optional<std::string_view>*, SOURCE_METADATA_TEXT_FIELDS> fields{
433+
&report.title, &report.artist, &report.album_artist, &report.album, &report.artwork_url};
434+
for (const std::optional<std::string_view>* field : fields) {
435+
if (field->has_value() && !is_valid_utf8(field->value())) {
436+
SS_LOGW(TAG, "set_metadata() refused: a text field is not valid UTF-8");
437+
return false;
438+
}
439+
}
440+
if (report.track == 0) {
441+
SS_LOGW(TAG, "set_metadata() refused: track must be at least 1");
442+
return false;
443+
}
444+
{
445+
SourceMetadataBlock& block = *this->metadata;
446+
const std::lock_guard<std::mutex> lock(block.mutex);
447+
for (size_t i = 0; i < SOURCE_METADATA_TEXT_FIELDS; ++i) {
448+
const auto field = static_cast<SourceMetadataText>(i);
449+
block.present[i] = fields[i]->has_value();
450+
const std::string_view kept =
451+
block.present[i]
452+
? utf8_truncate(fields[i]->value(), SourceMetadataBlock::capacity(field))
453+
: std::string_view{};
454+
std::memcpy(block.text.data() + SourceMetadataBlock::OFFSETS[i], kept.data(),
455+
kept.size());
456+
block.sizes[i] = static_cast<uint16_t>(kept.size());
457+
}
458+
block.timestamp_us =
459+
report.timestamp_us != 0 ? report.timestamp_us : SendspinClient::now_us();
460+
block.progress = report.progress;
461+
block.year = report.year;
462+
block.track = report.track;
463+
block.set = true;
464+
}
465+
this->client->publish_state();
466+
return true;
467+
}
468+
469+
void SourceRole::Impl::clear_metadata() {
470+
if (!this->metadata) {
471+
return;
472+
}
473+
{
474+
const std::lock_guard<std::mutex> lock(this->metadata->mutex);
475+
if (!this->metadata->set) {
476+
return;
477+
}
478+
this->metadata->set = false;
479+
}
480+
this->client->publish_state();
481+
}
482+
483+
void SourceRole::Impl::append_state_metadata(JsonObject source,
484+
const SendspinTimeFilter& filter) const {
485+
if (!this->metadata) {
486+
return;
487+
}
488+
static constexpr std::array<const char*, SOURCE_METADATA_TEXT_FIELDS> KEYS{
489+
"title", "artist", "album_artist", "album", "artwork_url"};
490+
const SourceMetadataBlock& block = *this->metadata;
491+
// ArduinoJson copies each string_view into the document, so nothing outlives the lock.
492+
const std::lock_guard<std::mutex> lock(block.mutex);
493+
if (!block.set) {
494+
return;
495+
}
496+
JsonObject out = source["metadata"].to<JsonObject>();
497+
out["timestamp"] = filter.compute_server_time(block.timestamp_us);
498+
for (size_t i = 0; i < SOURCE_METADATA_TEXT_FIELDS; ++i) {
499+
if (block.present[i]) {
500+
out[KEYS[i]] = block.view(static_cast<SourceMetadataText>(i));
501+
}
502+
}
503+
if (block.year.has_value()) {
504+
out["year"] = block.year.value();
505+
}
506+
if (block.track.has_value()) {
507+
out["track"] = block.track.value();
508+
}
509+
if (block.progress.has_value()) {
510+
JsonObject progress = out["progress"].to<JsonObject>();
511+
progress["track_progress"] = block.progress->track_progress_ms;
512+
progress["track_duration"] = block.progress->track_duration_ms;
513+
progress["playback_speed"] = block.progress->playback_speed;
514+
}
515+
}
516+
403517
void SourceRole::Impl::set_signal(SourceSignal new_signal) {
404518
if (!this->config.line_sense) {
405519
SS_LOGW(TAG, "set_signal() ignored: line_sense not configured");

0 commit comments

Comments
 (0)