Merge Wave 6A: studio outputs, cameras, viewer counts and layers
RTMP output for the Stream Studio through libavformat (any stream codec, pushed as H.264 + AAC; tested against `ffmpeg -listen 1`, ffprobe checks), MJPEG cameras (decoded off the capture thread), TeamSpeak 6's own viewer counts (`viewer` of `notifystreaminfo`, refreshed round robin), a viewer quality picker for Voelin streams (`a=x-voelin-layers` in the offer, an `x-voelin-layer` signal only Voelin streamers get), viewer-side stats over the player, Windows cameras through Media Foundation (compile-checked only), and the docs for all of them. Merged cleanly with server-wide stream discovery and renegotiation; the viewer-count refresh now covers every channel's streams. fmt, clippy and the tests of stream, media, core, ui and voelinctl pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
3bd230767c
41 files changed
+3878
-233
No files matched your search
@@ -243,6 +243,14 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
},
|
||||
/// Watch simulcast layer `layer` of a stream (`None`: as the bandwidth
|
||||
/// allows). Only for a stream whose [`Event::WatchLayers`] listed
|
||||
/// layers; otherwise an [`Event::Error`].
|
||||
SetWatchLayer {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
layer: Option<LayerId>,
|
||||
},
|
||||
/// Playback volume of a watched stream's audio, linear (1 = unchanged,
|
||||
/// up to 4).
|
||||
SetStreamVolume {
|
||||
@@ -552,6 +560,15 @@ pub enum Event {
|
||||
stream_id: String,
|
||||
state: WatchState,
|
||||
},
|
||||
/// The simulcast layers a watched stream offers (a Voelin streamer with
|
||||
/// several lists them; empty: none to choose from), and the one we asked
|
||||
/// for with [`Command::SetWatchLayer`] (`None`: as the bandwidth allows).
|
||||
WatchLayers {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
layers: Vec<LayerSpec>,
|
||||
layer: Option<LayerId>,
|
||||
},
|
||||
/// A setting was set or reset (by anyone: a command, the UI through
|
||||
/// [`Engine::settings`], …). Read the new value from the settings.
|
||||
SettingChanged {
|
||||
@@ -944,6 +961,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::WatchStream { session, .. }
|
||||
| Command::LeaveStream { session, .. }
|
||||
| Command::RequestStreamKeyframe { session, .. }
|
||||
| Command::SetWatchLayer { session, .. }
|
||||
| Command::SetStreamVolume { session, .. }
|
||||
| Command::SetClientVolume { session, .. }
|
||||
| Command::SetClientMuted { session, .. }
|
||||
|
||||
@@ -79,6 +79,8 @@ const OPUS_BITRATE: i32 = 128_000;
|
||||
pub const MAX_QUEUED: usize = 30;
|
||||
/// Keyframe requests while waiting for one are at least this far apart.
|
||||
const KEYFRAME_RETRY: Duration = Duration::from_millis(500);
|
||||
/// The decoding rates of [`DecodeStats`] cover at least this long.
|
||||
const RATE_WINDOW: Duration = Duration::from_millis(500);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MediaError {
|
||||
@@ -1852,6 +1854,17 @@ fn gpu_alignment<'a>(encoders: impl IntoIterator<Item = &'a dyn VideoEncoder>) -
|
||||
u64::from(alignment.0) << 32 | u64::from(alignment.1)
|
||||
}
|
||||
|
||||
/// Which of a studio's outputs get an encoder's packets.
|
||||
#[derive(Clone, Copy)]
|
||||
enum ToStudio<'a> {
|
||||
None,
|
||||
/// The stream codec's: all of them, recordings and replay buffer too.
|
||||
All(&'a Studio),
|
||||
/// Another codec's: the outputs that asked for it
|
||||
/// ([`Studio::output_codecs`]).
|
||||
Asked(&'a Studio),
|
||||
}
|
||||
|
||||
/// One encoder of a layer: its keyframe and bitrate state.
|
||||
struct LayerEncoder {
|
||||
codec: Codec,
|
||||
@@ -1878,7 +1891,7 @@ impl LayerEncoder {
|
||||
shared: &Shared,
|
||||
layer: &Layer,
|
||||
sink: &dyn MediaSink,
|
||||
studio: Option<&Studio>,
|
||||
studio: ToStudio<'_>,
|
||||
picture: &Picture,
|
||||
requested: bool,
|
||||
target: u64,
|
||||
@@ -1907,15 +1920,18 @@ impl LayerEncoder {
|
||||
let mut produced_keyframe = false;
|
||||
let mut out = |chunk: EncodedChunk<'_>| {
|
||||
produced_keyframe |= chunk.keyframe;
|
||||
if let Some(studio) = studio {
|
||||
studio.write_packet(&Packet {
|
||||
track: Track::Video { codec, layer: u32::from(layer.id) },
|
||||
pts_90khz: chunk.pts_90khz,
|
||||
keyframe: chunk.keyframe,
|
||||
width,
|
||||
height,
|
||||
data: chunk.data,
|
||||
});
|
||||
let packet = Packet {
|
||||
track: Track::Video { codec, layer: u32::from(layer.id) },
|
||||
pts_90khz: chunk.pts_90khz,
|
||||
keyframe: chunk.keyframe,
|
||||
width,
|
||||
height,
|
||||
data: chunk.data,
|
||||
};
|
||||
match studio {
|
||||
ToStudio::All(studio) => studio.write_packet(&packet),
|
||||
ToStudio::Asked(studio) => studio.write_output_packet(&packet),
|
||||
ToStudio::None => {}
|
||||
}
|
||||
let encoded = EncodedFrame {
|
||||
kind: MediaKind::Video,
|
||||
@@ -2007,6 +2023,14 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
// The codecs viewers chose; none known: the stream codec.
|
||||
wanted.clear();
|
||||
sink.video_codecs(&mut wanted);
|
||||
// With a studio, the stream codec for its recordings and replay
|
||||
// buffer, and the codecs its outputs of this layer need (RTMP: H.264).
|
||||
if let Some(studio) = &shared.studio {
|
||||
if !wanted.contains(&primary.codec) {
|
||||
wanted.insert(0, primary.codec);
|
||||
}
|
||||
studio.output_codecs(u32::from(layer.id), &mut wanted);
|
||||
}
|
||||
let now = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
if now != generation {
|
||||
generation = now;
|
||||
@@ -2068,12 +2092,13 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap);
|
||||
let started = Instant::now();
|
||||
if primary_on {
|
||||
let studio = shared.studio.as_deref();
|
||||
let studio = shared.studio.as_deref().map_or(ToStudio::None, ToStudio::All);
|
||||
primary.encode(shared, layer, &*sink, studio, &picture, requested, target);
|
||||
layer.target.store(primary.bitrate, Ordering::Relaxed);
|
||||
}
|
||||
for encoder in &mut extra {
|
||||
encoder.encode(shared, layer, &*sink, None, &picture, requested, target);
|
||||
let studio = shared.studio.as_deref().map_or(ToStudio::None, ToStudio::Asked);
|
||||
encoder.encode(shared, layer, &*sink, studio, &picture, requested, target);
|
||||
}
|
||||
layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||
layer.encoded.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -2401,6 +2426,23 @@ pub struct DecodeStats {
|
||||
pub height: u32,
|
||||
/// The last error (no decoder for the codec, decoding failed).
|
||||
pub error: Option<String>,
|
||||
/// Bytes of video received.
|
||||
pub bytes: u64,
|
||||
/// Pictures decoded per second and video received in bit/s, over the
|
||||
/// time since the previous [`VideoPipeline::stats`] (at least
|
||||
/// [`RATE_WINDOW`]; the watch screen asks once a second).
|
||||
pub fps: u32,
|
||||
pub bitrate: u64,
|
||||
}
|
||||
|
||||
/// Where the rates of [`DecodeStats`] were last measured from.
|
||||
#[derive(Default)]
|
||||
struct DecodeRates {
|
||||
since: Option<Instant>,
|
||||
decoded: u64,
|
||||
bytes: u64,
|
||||
fps: u32,
|
||||
bitrate: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -2416,6 +2458,7 @@ struct DecodeQueue {
|
||||
state: Mutex<QueueState>,
|
||||
cond: Condvar,
|
||||
stats: Mutex<DecodeStats>,
|
||||
rates: Mutex<DecodeRates>,
|
||||
}
|
||||
|
||||
/// Feeds frames into a [`VideoPipeline`]; cheap to clone.
|
||||
@@ -2432,6 +2475,7 @@ impl FrameInput {
|
||||
if frame.kind != MediaKind::Video {
|
||||
return;
|
||||
}
|
||||
lock(&self.queue.stats).bytes += frame.data.len() as u64;
|
||||
let mut state = lock(&self.queue.state);
|
||||
if state.frames.len() >= MAX_QUEUED {
|
||||
state.frames.clear();
|
||||
@@ -2486,7 +2530,19 @@ impl VideoPipeline {
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> DecodeStats {
|
||||
lock(&self.input.queue.stats).clone()
|
||||
let mut stats = lock(&self.input.queue.stats).clone();
|
||||
let mut rates = lock(&self.input.queue.rates);
|
||||
let now = Instant::now();
|
||||
let elapsed = rates.since.map(|since| now.saturating_duration_since(since));
|
||||
if elapsed.is_none_or(|e| e >= RATE_WINDOW) {
|
||||
if let Some(seconds) = elapsed.map(|e| e.as_secs_f64()) {
|
||||
rates.fps = ((stats.decoded - rates.decoded) as f64 / seconds).round() as u32;
|
||||
rates.bitrate = ((stats.bytes - rates.bytes) as f64 * 8.0 / seconds) as u64;
|
||||
}
|
||||
(rates.since, rates.decoded, rates.bytes) = (Some(now), stats.decoded, stats.bytes);
|
||||
}
|
||||
(stats.fps, stats.bitrate) = (rates.fps, rates.bitrate);
|
||||
stats
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2981,6 +3037,11 @@ mod tests {
|
||||
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
|
||||
assert_eq!(stats.codec, Some(Codec::Vp8));
|
||||
assert_eq!(preview.streamer().backend(), "synthetic");
|
||||
// Rates over the second since: the pattern's rate, its bitrate.
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let stats = preview.stats();
|
||||
assert!((20..=40).contains(&stats.fps), "{stats:?}");
|
||||
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
|
||||
}
|
||||
|
||||
fn layer(id: LayerId, scale: f32, max_fps: Option<u32>, bitrate: u64) -> LayerSpec {
|
||||
|
||||
@@ -463,6 +463,9 @@ impl Session {
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
}
|
||||
// Kept for streams started later, also without a connection.
|
||||
Command::SetStreamLayers { layers, .. } => {
|
||||
self.stream_layers = layers.clone();
|
||||
@@ -1091,6 +1094,8 @@ impl Session {
|
||||
bitrate: 0,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
// The UI takes the directory's count, which stays current.
|
||||
viewers: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -38,6 +38,10 @@ use crate::settings::{STREAM_PERMISSIONS, SharedSettings, StreamPermissions};
|
||||
use crate::voice::VoiceCmd;
|
||||
use crate::{Event, SessionId};
|
||||
|
||||
/// How often the viewer count of one stream in our channel is asked for
|
||||
/// (round robin, see [`Streams::refresh_viewer_counts`]).
|
||||
const VIEWER_COUNTS: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Our own stream.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum StreamState {
|
||||
@@ -159,6 +163,10 @@ pub(crate) enum StreamInput {
|
||||
RequestKeyframe {
|
||||
stream_id: String,
|
||||
},
|
||||
WatchLayer {
|
||||
stream_id: String,
|
||||
layer: Option<LayerId>,
|
||||
},
|
||||
/// Simulcast layers of our stream (now and for streams started later).
|
||||
Layers(Vec<LayerSpec>),
|
||||
/// SRTP profile order of new connections.
|
||||
@@ -320,6 +328,8 @@ struct StreamTask {
|
||||
|
||||
impl StreamTask {
|
||||
async fn run(mut self, mut rx: mpsc::UnboundedReceiver<StreamInput>) {
|
||||
let mut counts = tokio::time::interval(VIEWER_COUNTS);
|
||||
counts.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
loop {
|
||||
tokio::select! {
|
||||
input = rx.recv() => match input {
|
||||
@@ -331,6 +341,7 @@ impl StreamTask {
|
||||
Some(input) => self.input(input).await,
|
||||
},
|
||||
() = self.streams.wait_peers() => {}
|
||||
_ = counts.tick() => self.streams.refresh_viewer_counts(),
|
||||
}
|
||||
self.flush();
|
||||
}
|
||||
@@ -365,6 +376,10 @@ impl StreamTask {
|
||||
self.streams.request_keyframe(&stream_id);
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::WatchLayer { stream_id, layer } => self
|
||||
.streams
|
||||
.set_watch_layer(&stream_id, layer)
|
||||
.map(|()| self.watch_layers(&stream_id)),
|
||||
StreamInput::Layers(layers) => {
|
||||
self.layers = layers.clone();
|
||||
// Without a stream they are used for the next one.
|
||||
@@ -533,6 +548,7 @@ impl StreamTask {
|
||||
}
|
||||
WatchState::Ended(reason)
|
||||
}
|
||||
WatchEvent::Layers(_) => return self.watch_layers(&id),
|
||||
WatchEvent::Frame(frame) => {
|
||||
if let (MediaKind::Audio, Some(audio)) = (frame.kind, &self.audio) {
|
||||
audio.send(AudioIn::StreamAudio {
|
||||
@@ -550,6 +566,17 @@ impl StreamTask {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the layers of watched stream `id` and the one we asked for.
|
||||
fn watch_layers(&self, id: &str) {
|
||||
let Some(watched) = self.streams.watching().find(|v| v.id() == id) else { return };
|
||||
self.emit(Event::WatchLayers {
|
||||
session: self.session,
|
||||
stream_id: id.to_owned(),
|
||||
layers: watched.layers().to_vec(),
|
||||
layer: watched.layer(),
|
||||
});
|
||||
}
|
||||
|
||||
/// The answer `stream.permissions` gives to a join request; `None`: ask.
|
||||
fn join_decision(&self, viewer: ClientId) -> Option<bool> {
|
||||
match *self.settings.current().get_arc(&STREAM_PERMISSIONS) {
|
||||
@@ -618,6 +645,7 @@ mod tests {
|
||||
bitrate: setup.bitrate,
|
||||
viewer_limit: setup.viewer_limit,
|
||||
audio: setup.audio,
|
||||
viewers: Some(0),
|
||||
};
|
||||
let return_code = (c == from).then(|| "1".to_owned());
|
||||
(c, StreamNotification::Started { info, return_code })
|
||||
@@ -977,6 +1005,7 @@ mod tests {
|
||||
bitrate: 0,
|
||||
viewer_limit: 0,
|
||||
audio: true,
|
||||
viewers: None,
|
||||
};
|
||||
handles[1].send(StreamInput::Directory(vec![entry]));
|
||||
wait(&mut rx, |e| match e {
|
||||
|
||||
Reference in new issue
Block a user