Merge the development branch: Wave 5B's phone screens and quick-share sound

Both sides kept. From the development branch: the phone's voice channel
screen, the pages over it (pins, topics, members), the voice button in
the phone's top bar, the quick share's mixer and picker, invite links,
viewer counts, the studio's cameras and RTMP output, and the Android
pieces.

The phone's top bar keeps this wave's search button next to the voice
button and the bell (the bell opens the notifications panel); its tabs
mark Home also on the friends, messages and Library pages and Servers on
a server's events page. The phone shell shows both sides' pages: this
wave's friends, messages, events and Library pages with their back
button, and the development branch's voice channel screen, which hides
the bottom navigation as before.

Home keeps this wave's page, which maps the design onto TeamSpeak as
decided for it (friends' presence across servers, the latest chats of
every server, live streams of all servers); the development branch's
interim home (people on the current server, its chats, its streams)
gives way to it. Its server cards still switch the phone to the Servers
tab through Nav.show. A server item keeps this wave's detail and flavor
with the development branch's wording of `live` (streams on the server).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-04 03:20:20 +03:00
commit cd5ac614ef
104 files changed
+8174 -574

No files matched your search

+18
View File
@@ -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, .. }
+120 -16
View File
@@ -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 {
@@ -1582,7 +1584,8 @@ impl Ingest {
}
/// Whether frames go to the GPU: every layer's encoders take GPU frames
/// and the GPU stage has not failed.
/// and the GPU stage has not failed. On Android: the screen can render
/// straight into the encoder (`mediacodec`'s surface path).
fn gpu_path(&self) -> bool {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
{
@@ -1593,7 +1596,18 @@ impl Ingest {
.iter()
.all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0)
}
#[cfg(not(all(target_os = "linux", feature = "media-desktop")))]
#[cfg(target_os = "android")]
{
!self.layers.is_empty()
&& self
.layers
.iter()
.all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0)
}
#[cfg(not(any(
all(target_os = "linux", feature = "media-desktop"),
target_os = "android"
)))]
false
}
@@ -1717,7 +1731,38 @@ impl FrameSink for Ingest {
}
fn accepts_dmabuf(&self) -> bool {
self.gpu_path()
cfg!(all(target_os = "linux", feature = "media-desktop")) && self.gpu_path()
}
fn accepts_gpu(&self) -> bool {
cfg!(target_os = "android") && self.gpu_path()
}
/// Android: the screen goes straight into each due layer's encoder,
/// which draws it at the layer's size; only its size and time come here.
#[cfg(target_os = "android")]
fn gpu(&mut self, frame: GpuFrame) -> bool {
if self.shared.stopped() {
return false;
}
self.pacer.keep(frame.timestamp);
self.refresh();
let shared = &self.shared;
shared.captured.fetch_add(1, Ordering::Relaxed);
shared
.size
.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
if shared.sink().is_none() {
return true;
}
for l in &mut self.layers {
if !l.layer.stopped() && l.pacer.take(frame.timestamp) {
let (width, height) = l.spec.output_size(frame.width, frame.height);
l.layer.gpu_inbox.put(Arc::new(frame.sized(width, height)));
}
}
shared.gpu_converted.fetch_add(1, Ordering::Relaxed);
true
}
/// The tiled layout the GPU's own RGB surfaces have, once the GPU stage
@@ -1852,6 +1897,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 +1934,7 @@ impl LayerEncoder {
shared: &Shared,
layer: &Layer,
sink: &dyn MediaSink,
studio: Option<&Studio>,
studio: ToStudio<'_>,
picture: &Picture,
requested: bool,
target: u64,
@@ -1907,15 +1963,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 +2066,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 +2135,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 +2469,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 +2501,7 @@ struct DecodeQueue {
state: Mutex<QueueState>,
cond: Condvar,
stats: Mutex<DecodeStats>,
rates: Mutex<DecodeRates>,
}
/// Feeds frames into a [`VideoPipeline`]; cheap to clone.
@@ -2432,6 +2518,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 +2573,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 +3080,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 {
+5
View File
@@ -484,6 +484,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();
@@ -1118,6 +1121,8 @@ impl Session {
bitrate: 0,
viewer_limit: 0,
audio: true,
// The UI takes the directory's count, which stays current.
viewers: None,
})
})
.collect();
+29
View File
@@ -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 {
+244
View File
@@ -180,6 +180,250 @@ async fn a_studio_stream_records_and_replays_while_the_scene_switches() {
std::fs::remove_dir_all(&dir).ok();
}
/// FFmpeg's own RTMP server (`ffmpeg -listen 1`) on `port`, keeping what
/// it receives in `out`; its log goes to `out` with `.log`.
fn rtmp_server(port: u16, out: &Path) -> std::process::Child {
let log = std::fs::File::create(out.with_extension("log")).unwrap();
Process::new("ffmpeg")
.args(["-hide_banner", "-nostdin", "-loglevel", "warning", "-listen", "1", "-i"])
.arg(format!("rtmp://127.0.0.1:{port}/live/test-key"))
.args(["-c", "copy", "-y"])
.arg(out)
.stderr(log)
.spawn()
.unwrap()
}
/// Add the RTMP output `spec`, trying again while the server starts.
async fn add_rtmp(studio: &studio::Studio, spec: &voelin_core::studio::OutputSpec) {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
match studio.apply(Command::AddOutput(spec.clone())).await {
Ok(()) => return,
Err(e) if Instant::now() < deadline => {
eprintln!("not yet: {e}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
Err(e) => panic!("the RTMP output did not connect: {e}"),
}
}
}
/// Wait up to `limit` for `child` to exit by itself.
fn wait_exit(child: &mut std::process::Child, limit: Duration) -> Option<std::process::ExitStatus> {
let deadline = Instant::now() + limit;
while Instant::now() < deadline {
if let Some(status) = child.try_wait().unwrap() {
return Some(status);
}
std::thread::sleep(Duration::from_millis(50));
}
None
}
/// ffprobe's view of the streams of `path`: codec, width, height, sample
/// rate and channels per stream.
fn probe_streams(path: &Path) -> Vec<String> {
let out = Process::new("ffprobe")
.args(["-v", "error", "-show_entries"])
.args(["stream=codec_name,width,height,sample_rate,channels", "-of", "csv=p=0"])
.arg(path)
.output()
.unwrap();
assert!(out.status.success(), "ffprobe: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout)
.lines()
.map(|l| l.trim_end_matches(',').to_owned())
.collect()
}
/// The audio of `path`, mono, decoded by ffmpeg: its length in seconds and
/// its frequency (from the zero crossings), ignoring the first 100 ms.
fn tone(path: &Path) -> (f64, f64) {
let out = Process::new("ffmpeg")
.args(["-v", "error", "-i"])
.arg(path)
.args(["-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"])
.output()
.unwrap();
assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
let samples: Vec<f32> =
out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect();
let tail = &samples[samples.len().min(4800)..];
let crossings = tail.windows(2).filter(|w| (w[0] < 0.0) != (w[1] < 0.0)).count();
let seconds = tail.len() as f64 / 48_000.0;
(samples.len() as f64 / 48_000.0, crossings as f64 / 2.0 / seconds.max(1e-9))
}
/// Whether the first video frame of `path` is a keyframe.
fn starts_with_keyframe(path: &Path) -> bool {
let out = Process::new("ffprobe")
.args(["-v", "error", "-select_streams", "v", "-read_intervals", "%+#1"])
.args(["-show_entries", "frame=key_frame", "-of", "csv=p=0"])
.arg(path)
.output()
.unwrap();
// Side data (an encoder's SEI) adds fields after the flag.
String::from_utf8_lossy(&out.stdout).lines().next().and_then(|l| l.split(',').next())
== Some("1")
}
/// The studio pushed over RTMP to FFmpeg's own RTMP server: H.264 as
/// encoded and the tone as AAC arrive, with the stream key; the server goes
/// away mid-stream and a new one takes its place, which the output finds
/// again (starting at a keyframe); End Stream unpublishes cleanly, so the
/// server finishes its file and exits by itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did() {
use voelin_core::media::voelin_media::ffmpeg::avio::Connection;
use voelin_core::studio::OutputSpec;
if !has("ffmpeg") || !has("ffprobe") {
eprintln!("skipped: ffmpeg and ffprobe are the RTMP server and the check");
return;
}
if let Err(e) = Connection::available() {
eprintln!("skipped: no FFmpeg libraries with RTMP: {e}");
return;
}
let codecs = Codecs::new();
if !codecs.encoder_codecs().contains(&Codec::H264) {
eprintln!("skipped: no H.264 encoder");
return;
}
let settings = Settings::in_memory();
let mut scenes =
Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() };
scenes.scenes.push(colour_scene(1, "Red", RED));
settings.set(&STUDIO_SCENES, scenes).unwrap();
let studio = studio::start(&settings).await.unwrap();
let config = StreamerConfig {
fps: 30,
bitrate_kbps: 800,
codec: Codec::H264,
audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })],
..StreamerConfig::default()
};
let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let dir = std::env::temp_dir().join(format!("voelin-studio-rtmp-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (first, second) = (dir.join("first.flv"), dir.join("second.flv"));
let mut server = rtmp_server(port, &first);
// The key apart from the URL, as a service gives them.
let spec = OutputSpec::Url {
url: format!("rtmp://127.0.0.1:{port}/live"),
token: Some("test-key".into()),
};
add_rtmp(&studio, &spec).await;
studio.apply(Command::GoLive).await.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
// The server goes away (as a service restarting would); another one
// takes the address.
Process::new("kill").args(["-TERM", &server.id().to_string()]).status().unwrap();
assert!(wait_exit(&mut server, Duration::from_secs(10)).is_some(), "the first server hangs");
let mut server = rtmp_server(port, &second);
let deadline = Instant::now() + Duration::from_secs(20);
while std::fs::metadata(&second).map_or(0, |m| m.len()) < 20_000 {
assert!(Instant::now() < deadline, "the output did not come back");
tokio::time::sleep(Duration::from_millis(100)).await;
}
tokio::time::sleep(Duration::from_secs(2)).await;
studio.apply(Command::EndStream).await.unwrap();
let status = wait_exit(&mut server, Duration::from_secs(10));
if status.is_none() {
let _ = server.kill();
}
streamer.stop();
assert!(status.is_some_and(|s| s.success()), "the server did not finish: {status:?}");
for (file, seconds) in [(&first, 2.0), (&second, 1.5)] {
let log = std::fs::read_to_string(file.with_extension("log")).unwrap_or_default();
// The key arrived as the stream's name.
assert!(!log.contains("Unexpected stream"), "{log}");
let streams = probe_streams(file);
assert_eq!(streams, [format!("h264,{WIDTH},{HEIGHT}"), "aac,48000,2".to_owned()], "{log}");
assert!(starts_with_keyframe(file), "{}", file.display());
let pictures = decode(file);
assert!(pictures.len() as f64 >= seconds * 25.0, "{} pictures", pictures.len());
assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0]));
let (length, hz) = tone(file);
assert!(length >= seconds, "{length} s of audio in {}", file.display());
assert!((430.0..450.0).contains(&hz), "{hz} Hz in {}", file.display());
}
std::fs::remove_dir_all(&dir).ok();
}
/// A VP8 stream goes out over RTMP all the same: the streamer encodes H.264
/// of the output's layer beside the VP8 (the key in the URL this time),
/// while the recording keeps the stream's VP8.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_vp8_stream_goes_out_over_rtmp_as_h264() {
use voelin_core::media::voelin_media::ffmpeg::avio::Connection;
use voelin_core::studio::OutputSpec;
if !has("ffmpeg") || !has("ffprobe") || Connection::available().is_err() {
eprintln!("skipped: needs ffmpeg, ffprobe and the FFmpeg libraries with RTMP");
return;
}
let codecs = Codecs::new();
if ![Codec::Vp8, Codec::H264].iter().all(|c| codecs.encoder_codecs().contains(c)) {
eprintln!("skipped: needs VP8 and H.264 encoders");
return;
}
let settings = Settings::in_memory();
let mut scenes =
Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() };
scenes.scenes.push(colour_scene(1, "Red", RED));
settings.set(&STUDIO_SCENES, scenes).unwrap();
let studio = studio::start(&settings).await.unwrap();
let config = StreamerConfig {
fps: 30,
bitrate_kbps: 800,
codec: Codec::Vp8,
audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })],
..StreamerConfig::default()
};
let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let dir = std::env::temp_dir().join(format!("voelin-studio-rtmp-vp8-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (pushed, recording) = (dir.join("pushed.flv"), dir.join("recording.webm"));
let mut server = rtmp_server(port, &pushed);
let spec =
OutputSpec::Url { url: format!("rtmp://127.0.0.1:{port}/live/test-key"), token: None };
add_rtmp(&studio, &spec).await;
studio.apply(Command::StartRecording { path: recording.clone() }).await.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let encoded = streamer.stats().layers[0].codecs.clone();
studio.apply(Command::StopRecording).await.unwrap();
studio.apply(Command::EndStream).await.unwrap();
let status = wait_exit(&mut server, Duration::from_secs(10));
if status.is_none() {
let _ = server.kill();
}
streamer.stop();
assert!(status.is_some_and(|s| s.success()), "the server did not finish: {status:?}");
assert_eq!(encoded, [Codec::Vp8, Codec::H264]);
let log = std::fs::read_to_string(pushed.with_extension("log")).unwrap_or_default();
assert!(!log.contains("Unexpected stream"), "{log}");
let streams = probe_streams(&pushed);
assert_eq!(streams, [format!("h264,{WIDTH},{HEIGHT}"), "aac,48000,2".to_owned()], "{log}");
assert!(starts_with_keyframe(&pushed));
let pictures = decode(&pushed);
assert!(pictures.len() >= 60, "{} pictures", pictures.len());
assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0]));
let (length, hz) = tone(&pushed);
assert!(length >= 2.0 && (430.0..450.0).contains(&hz), "{length} s at {hz} Hz");
let (streams, _) = probe(&recording);
check_streams(&streams);
std::fs::remove_dir_all(&dir).ok();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_studio_source_needs_a_studio() {
let codecs = Codecs::new();