Skip to content
Open
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
10 changes: 8 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@ endif()

# sendspin-cpp

set(SENDSPIN_GIT_TAG "v0.10.0" CACHE STRING
# The fork commit of Sendspin/sendspin-cpp#287, which always reports the source signal
# (Sendspin/spec#335), until that is in a sendspin-cpp release.
set(SENDSPIN_GIT_REPOSITORY "https://github.com/meiser79/sendspin-cpp.git" CACHE STRING
"sendspin-cpp git repository to build against")
set(SENDSPIN_GIT_TAG "96e002da70810feeb1d6243e80c82b3bf233b2fa" CACHE STRING
"sendspin-cpp git tag or commit to build against")

# player, metadata, controller (group transport verbs) and source; no FORCE, so -D overrides still win.
Expand All @@ -57,7 +61,7 @@ set(IXWEBSOCKET_INSTALL OFF CACHE BOOL "Install IXWebSocket alongside our own ta
include(FetchContent)
FetchContent_Declare(
sendspin
GIT_REPOSITORY https://github.com/Sendspin/sendspin-cpp.git
GIT_REPOSITORY ${SENDSPIN_GIT_REPOSITORY}
# No GIT_SHALLOW: an overriding commit SHA that is not a branch tip will not shallow-fetch.
GIT_TAG ${SENDSPIN_GIT_TAG}
)
Expand Down Expand Up @@ -303,6 +307,7 @@ add_library(sendspin-cli-core STATIC
src/cli.cpp
src/audio_sink.cpp
src/audio_source.cpp
src/signal_detector.cpp
src/control_client.cpp
src/control_common.cpp
src/control_socket.cpp
Expand Down Expand Up @@ -538,6 +543,7 @@ if(SENDSPIN_CLI_BUILD_TESTS)
tests/device_spec_test.cpp
tests/discovery_test.cpp
tests/hooks_test.cpp
tests/signal_detector_test.cpp
tests/null_sink_test.cpp
tests/pairing_endpoint_test.cpp
tests/pairing_listener_test.cpp
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ scaling the stream in software, see `--alsa-mixer` in
```bash
sendspin-cli -n den --input default # a microphone or line-in
sendspin-cli -n den --input loopback # what this host plays
sendspin-cli -n den --input hw:1,0 --signal-threshold -50 # tell the server when a record plays
```

Off unless given. `-l` lists capture devices too. See
Expand Down
19 changes: 19 additions & 0 deletions docs/wiki/Advanced-Usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,25 @@ Nothing is captured until the server starts the source, and the device is releas
when the server stops it. Without `--input` the player does not offer the source role at
all.

### Start and stop on a signal

`--signal-threshold <dBFS>` tells the server whether the input carries a signal, so it can start
playing a turntable when the needle drops and stop again once the record ends:

```bash
sendspin-cli -n den --input hw:1,0 --signal-threshold -50
```

The signal counts as present after half a second above the level, and absent after five
seconds below it. What the server does with that is its own setting; in Music Assistant it
is the device's line-in autostart target. `-90` to `-1`: a less negative level needs a
louder signal, which is what a noisy preamp wants. `sendspin-cli status` shows the state
on the `input:` line. Without it the input is reported as having no signal, so a server
only plays it when asked to.

The device stays open the whole time instead of only while the server streams it, since
the level can only be read from audio the card delivers.

`sendspin-cli -l` lists capture devices in their own section, under the outputs: ALSA
PCMs with the rates, formats and channel counts each takes, then the PulseAudio sources
and PipeWire source nodes, or on macOS the CoreAudio input devices, then PortAudio's input
Expand Down
1 change: 1 addition & 0 deletions docs/wiki/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ already does that.
| `server` | `-s`, `--server` | `<host>[:<port>]`, a `ws://` URL, or `mdns:[<name>]` | none — wait to be discovered |
| `port` | `--port` | the port this player's own WebSocket server listens on | `8928` |
| `input` | `--input` | a capture device to stream to the server: `default`, `hw:1,0`, `alsa:<device>`, `pulse[:<source>]`, `pipewire[:<node>]`, `coreaudio[:<device>]` on macOS, `portaudio[:<device>]`, `loopback[:<sink>]` (on macOS `loopback[:<device>]`), `tone`, `null`; see [Stream a microphone or line-in](Advanced-Usage#stream-a-microphone-or-line-in) and [Stream what this host plays](Advanced-Usage#stream-what-this-host-plays) | none — nothing is captured |
| `signal-threshold` | `--signal-threshold` | report a signal on `input` above this level, `-90` to `-1` dBFS; keeps the input open; see [Start and stop on a signal](Advanced-Usage#start-and-stop-on-a-signal) | none — no signal is reported |
| `buffer-ms` | `--buffer-ms` | audio the output backend keeps queued, 10–2000 | `100` |
| `audio-format` | `--audio-format` | preferred formats, comma-separated in priority order: `codec:rate:depth:channels[,...]`, e.g. `flac:48000:24:2,pcm:48000:24:2`; offered first in that order, with the rest of the advertised list still behind them, so a server that cannot encode them falls back — a preference, not a restriction; refuses to start if the advertised list does not carry every one — it carries a single channel count — and an `opus` entry at anything but 48000/16 and at most 2 channels is refused outright | none — device-derived order |
| `output-delay` | `--output-delay` | latency this endpoint's hardware adds after the audio port, 0–5000. `static-delay` / `--static-delay` is still accepted as the old name | `0` |
Expand Down
4 changes: 4 additions & 0 deletions packaging/sendspin-cli.conf.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
# pulse or pipewire captures the sound server's default source; -l lists the named ones.
#input = hw:1,0

# Report a signal on the input above this level (-90 to -1 dBFS), so the server can start and
# stop it on its own. Keeps the input device open the whole time.
#signal-threshold = -50

# Audio the output backend keeps buffered, 10-2000 ms. Raise it on a device that stutters.
#buffer-ms = 100

Expand Down
104 changes: 97 additions & 7 deletions src/audio_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,20 +109,96 @@ SourceCapture::SourceCapture(AudioSource& source, StreamFormat format, Writer wr
: source_(source), format_(format), writer_(std::move(writer)) {}

SourceCapture::~SourceCapture() {
this->on_streaming_stopped();
this->streaming_ = false;
this->forwarding_ = false;
this->stop_thread_();
}

namespace {

constexpr int SIGNAL_PRESENT = 1;
constexpr int SIGNAL_ABSENT = 2;

std::optional<sendspin::SourceSignal> to_signal(int value) {
switch (value) {
case SIGNAL_PRESENT:
return sendspin::SourceSignal::PRESENT;
case SIGNAL_ABSENT:
return sendspin::SourceSignal::ABSENT;
default:
return std::nullopt;
}
}

} // namespace

void SourceCapture::enable_signal_detection(double threshold_dbfs) {
if (this->sensing_) {
return;
}
// Before the thread starts: from then on the detector is the capture thread's.
this->detector_.emplace(threshold_dbfs);
this->sensing_ = true;
log_line(LogLevel::INFO, LOG_TAG, "Sensing a signal on '%s' above %.0f dBFS",
this->source_.name().c_str(), threshold_dbfs);
this->start_thread_();
}

std::optional<sendspin::SourceSignal> SourceCapture::signal() const {
return to_signal(this->signal_.load());
}

std::optional<sendspin::SourceSignal> SourceCapture::take_signal_change() {
return to_signal(this->signal_change_.exchange(0));
}

void SourceCapture::publish_(std::optional<bool> change) {
if (!change.has_value()) {
return;
}
const int value = *change ? SIGNAL_PRESENT : SIGNAL_ABSENT;
this->signal_ = value;
this->signal_change_ = value;
log_line(LogLevel::INFO, LOG_TAG, "Signal %s on '%s'", *change ? "present" : "absent",
this->source_.name().c_str());
}

void SourceCapture::on_streaming_started() {
if (this->thread_.joinable()) {
if (this->streaming_) {
return;
}
log_line(LogLevel::INFO, LOG_TAG, "Input stream opened: capturing from '%s'",
this->source_.name().c_str());
this->streaming_ = true;
this->forwarding_ = true;
this->start_thread_();
}

void SourceCapture::on_streaming_stopped() {
if (!this->streaming_) {
return;
}
this->streaming_ = false;
this->forwarding_ = false;
if (this->sensing_) {
log_line(LogLevel::INFO, LOG_TAG, "Input stream closed: still sensing '%s'",
this->source_.name().c_str());
return;
}
this->stop_thread_();
log_line(LogLevel::INFO, LOG_TAG, "Input stream closed: released '%s'",
this->source_.name().c_str());
}

void SourceCapture::start_thread_() {
if (this->thread_.joinable()) {
return;
}
this->stopping_ = false;
this->thread_ = std::thread([this] { this->run_(); });
}

void SourceCapture::on_streaming_stopped() {
void SourceCapture::stop_thread_() {
if (!this->thread_.joinable()) {
return;
}
Expand All @@ -132,8 +208,6 @@ void SourceCapture::on_streaming_stopped() {
}
this->stop_cv_.notify_all();
this->thread_.join();
log_line(LogLevel::INFO, LOG_TAG, "Input stream closed: released '%s'",
this->source_.name().c_str());
}

bool SourceCapture::wait_(int64_t delay_ms) {
Expand All @@ -159,6 +233,9 @@ void SourceCapture::run_() {
if (!open) {
open = this->source_.open(this->format_);
if (!open) {
if (this->detector_) {
this->publish_(this->detector_->reset());
}
log_line(LogLevel::WARN, LOG_TAG,
"Input device '%s' is unavailable -- retrying in %lld ms",
this->source_.name().c_str(), static_cast<long long>(retry_ms));
Expand All @@ -179,6 +256,9 @@ void SourceCapture::run_() {
this->source_.name().c_str());
this->source_.close();
open = false;
if (this->detector_) {
this->publish_(this->detector_->reset());
}
// Paced even when the reopen works, so a device that opens but cannot read never spins.
if (!this->wait_(SINK_RESCAN_DELAY_MS)) {
break;
Expand All @@ -188,8 +268,18 @@ void SourceCapture::run_() {
if (bytes == 0) {
continue;
}
// A refused write is the role's drop policy at work, not ours to retry.
this->writer_(buffer.data(), static_cast<size_t>(bytes), capture_time_us);
if (this->detector_) {
const auto frames_read = static_cast<uint64_t>(bytes) / bytes_per_frame;
const auto read_ms =
static_cast<uint32_t>(frames_read * 1000U / this->format_.sample_rate);
this->publish_(this->detector_->feed(
pcm_level_dbfs(buffer.data(), static_cast<size_t>(bytes), this->format_.bit_depth),
read_ms));
}
if (this->forwarding_) {
// A refused write is the role's drop policy at work, not ours to retry.
this->writer_(buffer.data(), static_cast<size_t>(bytes), capture_time_us);
}

// An unclocked PCM such as ALSA's `null` never blocks; hold it near real time.
window_frames += static_cast<size_t>(bytes) / bytes_per_frame;
Expand Down
35 changes: 31 additions & 4 deletions src/audio_source.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
#pragma once

#include "audio_sink.h"
#include "signal_detector.h"

#include <sendspin/source_role.h>

#include <array>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
Expand Down Expand Up @@ -81,8 +83,9 @@ class AudioSource {
AudioSource() = default;
};

/// Runs an AudioSource on one capture thread while the source role's input stream is open.
/// Main loop only. Must be destroyed before the client its writer reaches.
/// Runs an AudioSource on one capture thread while the source role's input stream is open, or
/// all the time once line sensing is on. Main loop only. Must be destroyed before the client its
/// writer reaches.
class SourceCapture final : public sendspin::SourceRoleListener {
public:
/// SourceRole::write_audio(), or a stand-in; called from the capture thread only.
Expand All @@ -92,14 +95,27 @@ class SourceCapture final : public sendspin::SourceRoleListener {
SourceCapture(AudioSource& source, StreamFormat format, Writer writer);
~SourceCapture() override;

/// Keeps the device open from now on and judges its level against `threshold_dbfs`.
void enable_signal_detection(double threshold_dbfs);

void on_streaming_started() override;
/// Returns once the capture thread has joined.
/// Returns once the capture thread has joined, unless line sensing keeps it running.
void on_streaming_stopped() override;

bool streaming() const {
return this->thread_.joinable();
return this->streaming_;
}

bool sensing() const {
return this->sensing_;
}

/// The signal state the capture thread last settled on, if it has settled on one.
std::optional<sendspin::SourceSignal> signal() const;

/// A signal change not yet taken, for SourceRole::set_signal(); the latest wins.
std::optional<sendspin::SourceSignal> take_signal_change();

const StreamFormat& format() const {
return this->format_;
}
Expand All @@ -113,11 +129,22 @@ class SourceCapture final : public sendspin::SourceRoleListener {
/// Sleeps up to `delay_ms`, waking early on a stop.
/// @return false if the thread should exit.
bool wait_(int64_t delay_ms);
void start_thread_();
void stop_thread_();
/// Capture thread: publishes a change the detector reported.
void publish_(std::optional<bool> change);

AudioSource& source_;
StreamFormat format_;
Writer writer_;

bool streaming_{false};
bool sensing_{false};
std::optional<SignalDetector> detector_; ///< capture thread only once the thread runs
std::atomic<bool> forwarding_{false}; ///< whether reads go to the writer
std::atomic<int> signal_{0}; ///< 0 unknown, 1 present, 2 absent
std::atomic<int> signal_change_{0}; ///< as signal_, 0 when nothing is pending

std::thread thread_;
std::mutex stop_mutex_;
std::condition_variable stop_cv_;
Expand Down
Loading